You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UploadPack.java 65KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165
  1. /*
  2. * Copyright (C) 2008-2010, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.transport;
  44. import static org.eclipse.jgit.lib.Constants.R_TAGS;
  45. import static org.eclipse.jgit.lib.RefDatabase.ALL;
  46. import static org.eclipse.jgit.transport.GitProtocolConstants.COMMAND_FETCH;
  47. import static org.eclipse.jgit.transport.GitProtocolConstants.COMMAND_LS_REFS;
  48. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_AGENT;
  49. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_ALLOW_REACHABLE_SHA1_IN_WANT;
  50. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_ALLOW_TIP_SHA1_IN_WANT;
  51. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_DEEPEN_RELATIVE;
  52. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_FILTER;
  53. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_INCLUDE_TAG;
  54. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_MULTI_ACK;
  55. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_MULTI_ACK_DETAILED;
  56. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_NO_DONE;
  57. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_NO_PROGRESS;
  58. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_OFS_DELTA;
  59. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SHALLOW;
  60. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SIDE_BAND;
  61. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SIDE_BAND_64K;
  62. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_THIN_PACK;
  63. import java.io.ByteArrayOutputStream;
  64. import java.io.EOFException;
  65. import java.io.IOException;
  66. import java.io.InputStream;
  67. import java.io.OutputStream;
  68. import java.text.MessageFormat;
  69. import java.util.ArrayList;
  70. import java.util.Collection;
  71. import java.util.Collections;
  72. import java.util.HashMap;
  73. import java.util.HashSet;
  74. import java.util.List;
  75. import java.util.Map;
  76. import java.util.Set;
  77. import org.eclipse.jgit.annotations.Nullable;
  78. import org.eclipse.jgit.errors.CorruptObjectException;
  79. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  80. import org.eclipse.jgit.errors.MissingObjectException;
  81. import org.eclipse.jgit.errors.PackProtocolException;
  82. import org.eclipse.jgit.internal.JGitText;
  83. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  84. import org.eclipse.jgit.lib.BitmapIndex;
  85. import org.eclipse.jgit.lib.BitmapIndex.BitmapBuilder;
  86. import org.eclipse.jgit.lib.Constants;
  87. import org.eclipse.jgit.lib.NullProgressMonitor;
  88. import org.eclipse.jgit.lib.ObjectId;
  89. import org.eclipse.jgit.lib.ObjectReader;
  90. import org.eclipse.jgit.lib.ProgressMonitor;
  91. import org.eclipse.jgit.lib.Ref;
  92. import org.eclipse.jgit.lib.Repository;
  93. import org.eclipse.jgit.revwalk.AsyncRevObjectQueue;
  94. import org.eclipse.jgit.revwalk.BitmapWalker;
  95. import org.eclipse.jgit.revwalk.DepthWalk;
  96. import org.eclipse.jgit.revwalk.ObjectWalk;
  97. import org.eclipse.jgit.revwalk.RevCommit;
  98. import org.eclipse.jgit.revwalk.RevFlag;
  99. import org.eclipse.jgit.revwalk.RevFlagSet;
  100. import org.eclipse.jgit.revwalk.RevObject;
  101. import org.eclipse.jgit.revwalk.RevTag;
  102. import org.eclipse.jgit.revwalk.RevWalk;
  103. import org.eclipse.jgit.revwalk.filter.CommitTimeRevFilter;
  104. import org.eclipse.jgit.storage.pack.PackConfig;
  105. import org.eclipse.jgit.storage.pack.PackStatistics;
  106. import org.eclipse.jgit.transport.GitProtocolConstants.MultiAck;
  107. import org.eclipse.jgit.transport.RefAdvertiser.PacketLineOutRefAdvertiser;
  108. import org.eclipse.jgit.transport.TransferConfig.ProtocolVersion;
  109. import org.eclipse.jgit.util.io.InterruptTimer;
  110. import org.eclipse.jgit.util.io.NullOutputStream;
  111. import org.eclipse.jgit.util.io.TimeoutInputStream;
  112. import org.eclipse.jgit.util.io.TimeoutOutputStream;
  113. /**
  114. * Implements the server side of a fetch connection, transmitting objects.
  115. */
  116. public class UploadPack {
  117. /** Policy the server uses to validate client requests */
  118. public static enum RequestPolicy {
  119. /** Client may only ask for objects the server advertised a reference for. */
  120. ADVERTISED,
  121. /**
  122. * Client may ask for any commit reachable from a reference advertised by
  123. * the server.
  124. */
  125. REACHABLE_COMMIT,
  126. /**
  127. * Client may ask for objects that are the tip of any reference, even if not
  128. * advertised.
  129. * <p>
  130. * This may happen, for example, when a custom {@link RefFilter} is set.
  131. *
  132. * @since 3.1
  133. */
  134. TIP,
  135. /**
  136. * Client may ask for any commit reachable from any reference, even if that
  137. * reference wasn't advertised.
  138. *
  139. * @since 3.1
  140. */
  141. REACHABLE_COMMIT_TIP,
  142. /** Client may ask for any SHA-1 in the repository. */
  143. ANY;
  144. }
  145. /**
  146. * Validator for client requests.
  147. *
  148. * @since 3.1
  149. */
  150. public interface RequestValidator {
  151. /**
  152. * Check a list of client wants against the request policy.
  153. *
  154. * @param up
  155. * {@link UploadPack} instance.
  156. * @param wants
  157. * objects the client requested that were not advertised.
  158. *
  159. * @throws PackProtocolException
  160. * if one or more wants is not valid.
  161. * @throws IOException
  162. * if a low-level exception occurred.
  163. * @since 3.1
  164. */
  165. void checkWants(UploadPack up, List<ObjectId> wants)
  166. throws PackProtocolException, IOException;
  167. }
  168. /** Data in the first line of a request, the line itself plus options. */
  169. public static class FirstLine {
  170. private final String line;
  171. private final Set<String> options;
  172. /**
  173. * Parse the first line of a receive-pack request.
  174. *
  175. * @param line
  176. * line from the client.
  177. */
  178. public FirstLine(String line) {
  179. if (line.length() > 45) {
  180. final HashSet<String> opts = new HashSet<>();
  181. String opt = line.substring(45);
  182. if (opt.startsWith(" ")) //$NON-NLS-1$
  183. opt = opt.substring(1);
  184. for (String c : opt.split(" ")) //$NON-NLS-1$
  185. opts.add(c);
  186. this.line = line.substring(0, 45);
  187. this.options = Collections.unmodifiableSet(opts);
  188. } else {
  189. this.line = line;
  190. this.options = Collections.emptySet();
  191. }
  192. }
  193. /** @return non-capabilities part of the line. */
  194. public String getLine() {
  195. return line;
  196. }
  197. /** @return options parsed from the line. */
  198. public Set<String> getOptions() {
  199. return options;
  200. }
  201. }
  202. /** Database we read the objects from. */
  203. private final Repository db;
  204. /** Revision traversal support over {@link #db}. */
  205. private final RevWalk walk;
  206. /** Configuration to pass into the PackWriter. */
  207. private PackConfig packConfig;
  208. /** Configuration for various transfer options. */
  209. private TransferConfig transferConfig;
  210. /** Timeout in seconds to wait for client interaction. */
  211. private int timeout;
  212. /**
  213. * Is the client connection a bi-directional socket or pipe?
  214. * <p>
  215. * If true, this class assumes it can perform multiple read and write cycles
  216. * with the client over the input and output streams. This matches the
  217. * functionality available with a standard TCP/IP connection, or a local
  218. * operating system or in-memory pipe.
  219. * <p>
  220. * If false, this class runs in a read everything then output results mode,
  221. * making it suitable for single round-trip systems RPCs such as HTTP.
  222. */
  223. private boolean biDirectionalPipe = true;
  224. /** Timer to manage {@link #timeout}. */
  225. private InterruptTimer timer;
  226. /**
  227. * Whether the client requested to use protocol V2 through a side
  228. * channel (such as the Git-Protocol HTTP header).
  229. */
  230. private boolean clientRequestedV2;
  231. private InputStream rawIn;
  232. private ResponseBufferedOutputStream rawOut;
  233. private PacketLineIn pckIn;
  234. private PacketLineOut pckOut;
  235. private OutputStream msgOut = NullOutputStream.INSTANCE;
  236. /** The refs we advertised as existing at the start of the connection. */
  237. private Map<String, Ref> refs;
  238. /** Hook used while advertising the refs to the client. */
  239. private AdvertiseRefsHook advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  240. /** Filter used while advertising the refs to the client. */
  241. private RefFilter refFilter = RefFilter.DEFAULT;
  242. /** Hook handling the various upload phases. */
  243. private PreUploadHook preUploadHook = PreUploadHook.NULL;
  244. /** Hook for taking post upload actions. */
  245. private PostUploadHook postUploadHook = PostUploadHook.NULL;
  246. /** Capabilities requested by the client. */
  247. private Set<String> options;
  248. String userAgent;
  249. /** Raw ObjectIds the client has asked for, before validating them. */
  250. private final Set<ObjectId> wantIds = new HashSet<>();
  251. /** Objects the client wants to obtain. */
  252. private final Set<RevObject> wantAll = new HashSet<>();
  253. /** Objects on both sides, these don't have to be sent. */
  254. private final Set<RevObject> commonBase = new HashSet<>();
  255. /** Shallow commits the client already has. */
  256. private final Set<ObjectId> clientShallowCommits = new HashSet<>();
  257. /** Desired depth from the client on a shallow request. */
  258. private int depth;
  259. /**
  260. * Commit time of the newest objects the client has asked us using
  261. * --shallow-since not to send. Cannot be nonzero if depth is nonzero.
  262. */
  263. private int shallowSince;
  264. /**
  265. * (Possibly short) ref names, ancestors of which the client has asked us
  266. * not to send using --shallow-exclude. Cannot be non-null if depth is
  267. * nonzero.
  268. */
  269. private @Nullable List<String> shallowExcludeRefs;
  270. /** Commit time of the oldest common commit, in seconds. */
  271. private int oldestTime;
  272. /** null if {@link #commonBase} should be examined again. */
  273. private Boolean okToGiveUp;
  274. private boolean sentReady;
  275. /** Objects we sent in our advertisement list, clients can ask for these. */
  276. private Set<ObjectId> advertised;
  277. /** Marked on objects the client has asked us to give them. */
  278. private final RevFlag WANT;
  279. /** Marked on objects both we and the client have. */
  280. private final RevFlag PEER_HAS;
  281. /** Marked on objects in {@link #commonBase}. */
  282. private final RevFlag COMMON;
  283. /** Objects where we found a path from the want list to a common base. */
  284. private final RevFlag SATISFIED;
  285. private final RevFlagSet SAVE;
  286. private RequestValidator requestValidator = new AdvertisedRequestValidator();
  287. private MultiAck multiAck = MultiAck.OFF;
  288. private boolean noDone;
  289. private PackStatistics statistics;
  290. private long filterBlobLimit = -1;
  291. /**
  292. * Create a new pack upload for an open repository.
  293. *
  294. * @param copyFrom
  295. * the source repository.
  296. */
  297. public UploadPack(Repository copyFrom) {
  298. db = copyFrom;
  299. walk = new RevWalk(db);
  300. walk.setRetainBody(false);
  301. WANT = walk.newFlag("WANT"); //$NON-NLS-1$
  302. PEER_HAS = walk.newFlag("PEER_HAS"); //$NON-NLS-1$
  303. COMMON = walk.newFlag("COMMON"); //$NON-NLS-1$
  304. SATISFIED = walk.newFlag("SATISFIED"); //$NON-NLS-1$
  305. walk.carry(PEER_HAS);
  306. SAVE = new RevFlagSet();
  307. SAVE.add(WANT);
  308. SAVE.add(PEER_HAS);
  309. SAVE.add(COMMON);
  310. SAVE.add(SATISFIED);
  311. setTransferConfig(null);
  312. }
  313. /**
  314. * Get the repository this upload is reading from.
  315. *
  316. * @return the repository this upload is reading from.
  317. */
  318. public final Repository getRepository() {
  319. return db;
  320. }
  321. /**
  322. * Get the RevWalk instance used by this connection.
  323. *
  324. * @return the RevWalk instance used by this connection.
  325. */
  326. public final RevWalk getRevWalk() {
  327. return walk;
  328. }
  329. /**
  330. * Get refs which were advertised to the client.
  331. *
  332. * @return all refs which were advertised to the client, or null if
  333. * {@link #setAdvertisedRefs(Map)} has not been called yet.
  334. */
  335. public final Map<String, Ref> getAdvertisedRefs() {
  336. return refs;
  337. }
  338. /**
  339. * Set the refs advertised by this UploadPack.
  340. * <p>
  341. * Intended to be called from a
  342. * {@link org.eclipse.jgit.transport.PreUploadHook}.
  343. *
  344. * @param allRefs
  345. * explicit set of references to claim as advertised by this
  346. * UploadPack instance. This overrides any references that may
  347. * exist in the source repository. The map is passed to the
  348. * configured {@link #getRefFilter()}. If null, assumes all refs
  349. * were advertised.
  350. */
  351. public void setAdvertisedRefs(Map<String, Ref> allRefs) {
  352. if (allRefs != null)
  353. refs = allRefs;
  354. else
  355. refs = db.getAllRefs();
  356. if (refFilter == RefFilter.DEFAULT)
  357. refs = transferConfig.getRefFilter().filter(refs);
  358. else
  359. refs = refFilter.filter(refs);
  360. }
  361. /**
  362. * Get timeout (in seconds) before aborting an IO operation.
  363. *
  364. * @return timeout (in seconds) before aborting an IO operation.
  365. */
  366. public int getTimeout() {
  367. return timeout;
  368. }
  369. /**
  370. * Set the timeout before willing to abort an IO call.
  371. *
  372. * @param seconds
  373. * number of seconds to wait (with no data transfer occurring)
  374. * before aborting an IO read or write operation with the
  375. * connected client.
  376. */
  377. public void setTimeout(int seconds) {
  378. timeout = seconds;
  379. }
  380. /**
  381. * Whether this class expects a bi-directional pipe opened between the
  382. * client and itself.
  383. *
  384. * @return true if this class expects a bi-directional pipe opened between
  385. * the client and itself. The default is true.
  386. */
  387. public boolean isBiDirectionalPipe() {
  388. return biDirectionalPipe;
  389. }
  390. /**
  391. * Set whether this class will assume the socket is a fully bidirectional
  392. * pipe between the two peers
  393. *
  394. * @param twoWay
  395. * if true, this class will assume the socket is a fully
  396. * bidirectional pipe between the two peers and takes advantage
  397. * of that by first transmitting the known refs, then waiting to
  398. * read commands. If false, this class assumes it must read the
  399. * commands before writing output and does not perform the
  400. * initial advertising.
  401. */
  402. public void setBiDirectionalPipe(boolean twoWay) {
  403. biDirectionalPipe = twoWay;
  404. }
  405. /**
  406. * Get policy used by the service to validate client requests
  407. *
  408. * @return policy used by the service to validate client requests, or null
  409. * for a custom request validator.
  410. */
  411. public RequestPolicy getRequestPolicy() {
  412. if (requestValidator instanceof AdvertisedRequestValidator)
  413. return RequestPolicy.ADVERTISED;
  414. if (requestValidator instanceof ReachableCommitRequestValidator)
  415. return RequestPolicy.REACHABLE_COMMIT;
  416. if (requestValidator instanceof TipRequestValidator)
  417. return RequestPolicy.TIP;
  418. if (requestValidator instanceof ReachableCommitTipRequestValidator)
  419. return RequestPolicy.REACHABLE_COMMIT_TIP;
  420. if (requestValidator instanceof AnyRequestValidator)
  421. return RequestPolicy.ANY;
  422. return null;
  423. }
  424. /**
  425. * Set the policy used to enforce validation of a client's want list.
  426. *
  427. * @param policy
  428. * the policy used to enforce validation of a client's want list.
  429. * By default the policy is
  430. * {@link org.eclipse.jgit.transport.UploadPack.RequestPolicy#ADVERTISED},
  431. * which is the Git default requiring clients to only ask for an
  432. * object that a reference directly points to. This may be
  433. * relaxed to
  434. * {@link org.eclipse.jgit.transport.UploadPack.RequestPolicy#REACHABLE_COMMIT}
  435. * or
  436. * {@link org.eclipse.jgit.transport.UploadPack.RequestPolicy#REACHABLE_COMMIT_TIP}
  437. * when callers have {@link #setBiDirectionalPipe(boolean)} set
  438. * to false. Overrides any policy specified in a
  439. * {@link org.eclipse.jgit.transport.TransferConfig}.
  440. */
  441. public void setRequestPolicy(RequestPolicy policy) {
  442. switch (policy) {
  443. case ADVERTISED:
  444. default:
  445. requestValidator = new AdvertisedRequestValidator();
  446. break;
  447. case REACHABLE_COMMIT:
  448. requestValidator = new ReachableCommitRequestValidator();
  449. break;
  450. case TIP:
  451. requestValidator = new TipRequestValidator();
  452. break;
  453. case REACHABLE_COMMIT_TIP:
  454. requestValidator = new ReachableCommitTipRequestValidator();
  455. break;
  456. case ANY:
  457. requestValidator = new AnyRequestValidator();
  458. break;
  459. }
  460. }
  461. /**
  462. * Set custom validator for client want list.
  463. *
  464. * @param validator
  465. * custom validator for client want list.
  466. * @since 3.1
  467. */
  468. public void setRequestValidator(RequestValidator validator) {
  469. requestValidator = validator != null ? validator
  470. : new AdvertisedRequestValidator();
  471. }
  472. /**
  473. * Get the hook used while advertising the refs to the client.
  474. *
  475. * @return the hook used while advertising the refs to the client.
  476. */
  477. public AdvertiseRefsHook getAdvertiseRefsHook() {
  478. return advertiseRefsHook;
  479. }
  480. /**
  481. * Get the filter used while advertising the refs to the client.
  482. *
  483. * @return the filter used while advertising the refs to the client.
  484. */
  485. public RefFilter getRefFilter() {
  486. return refFilter;
  487. }
  488. /**
  489. * Set the hook used while advertising the refs to the client.
  490. * <p>
  491. * If the {@link org.eclipse.jgit.transport.AdvertiseRefsHook} chooses to
  492. * call {@link #setAdvertisedRefs(Map)}, only refs set by this hook
  493. * <em>and</em> selected by the {@link org.eclipse.jgit.transport.RefFilter}
  494. * will be shown to the client.
  495. *
  496. * @param advertiseRefsHook
  497. * the hook; may be null to show all refs.
  498. */
  499. public void setAdvertiseRefsHook(AdvertiseRefsHook advertiseRefsHook) {
  500. if (advertiseRefsHook != null)
  501. this.advertiseRefsHook = advertiseRefsHook;
  502. else
  503. this.advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  504. }
  505. /**
  506. * Set the filter used while advertising the refs to the client.
  507. * <p>
  508. * Only refs allowed by this filter will be sent to the client. The filter
  509. * is run against the refs specified by the
  510. * {@link org.eclipse.jgit.transport.AdvertiseRefsHook} (if applicable). If
  511. * null or not set, uses the filter implied by the
  512. * {@link org.eclipse.jgit.transport.TransferConfig}.
  513. *
  514. * @param refFilter
  515. * the filter; may be null to show all refs.
  516. */
  517. public void setRefFilter(RefFilter refFilter) {
  518. this.refFilter = refFilter != null ? refFilter : RefFilter.DEFAULT;
  519. }
  520. /**
  521. * Get the configured pre upload hook.
  522. *
  523. * @return the configured pre upload hook.
  524. */
  525. public PreUploadHook getPreUploadHook() {
  526. return preUploadHook;
  527. }
  528. /**
  529. * Set the hook that controls how this instance will behave.
  530. *
  531. * @param hook
  532. * the hook; if null no special actions are taken.
  533. */
  534. public void setPreUploadHook(PreUploadHook hook) {
  535. preUploadHook = hook != null ? hook : PreUploadHook.NULL;
  536. }
  537. /**
  538. * Get the configured post upload hook.
  539. *
  540. * @return the configured post upload hook.
  541. * @since 4.1
  542. */
  543. public PostUploadHook getPostUploadHook() {
  544. return postUploadHook;
  545. }
  546. /**
  547. * Set the hook for post upload actions (logging, repacking).
  548. *
  549. * @param hook
  550. * the hook; if null no special actions are taken.
  551. * @since 4.1
  552. */
  553. public void setPostUploadHook(PostUploadHook hook) {
  554. postUploadHook = hook != null ? hook : PostUploadHook.NULL;
  555. }
  556. /**
  557. * Set the configuration used by the pack generator.
  558. *
  559. * @param pc
  560. * configuration controlling packing parameters. If null the
  561. * source repository's settings will be used.
  562. */
  563. public void setPackConfig(PackConfig pc) {
  564. this.packConfig = pc;
  565. }
  566. /**
  567. * Set configuration controlling transfer options.
  568. *
  569. * @param tc
  570. * configuration controlling transfer options. If null the source
  571. * repository's settings will be used.
  572. * @since 3.1
  573. */
  574. public void setTransferConfig(TransferConfig tc) {
  575. this.transferConfig = tc != null ? tc : new TransferConfig(db);
  576. if (transferConfig.isAllowTipSha1InWant()) {
  577. setRequestPolicy(transferConfig.isAllowReachableSha1InWant()
  578. ? RequestPolicy.REACHABLE_COMMIT_TIP : RequestPolicy.TIP);
  579. } else {
  580. setRequestPolicy(transferConfig.isAllowReachableSha1InWant()
  581. ? RequestPolicy.REACHABLE_COMMIT : RequestPolicy.ADVERTISED);
  582. }
  583. }
  584. /**
  585. * Check whether the client expects a side-band stream.
  586. *
  587. * @return true if the client has advertised a side-band capability, false
  588. * otherwise.
  589. * @throws org.eclipse.jgit.transport.RequestNotYetReadException
  590. * if the client's request has not yet been read from the wire, so
  591. * we do not know if they expect side-band. Note that the client
  592. * may have already written the request, it just has not been
  593. * read.
  594. */
  595. public boolean isSideBand() throws RequestNotYetReadException {
  596. if (options == null)
  597. throw new RequestNotYetReadException();
  598. return (options.contains(OPTION_SIDE_BAND)
  599. || options.contains(OPTION_SIDE_BAND_64K));
  600. }
  601. /**
  602. * Set the Extra Parameters provided by the client.
  603. *
  604. * <p>These are parameters passed by the client through a side channel
  605. * such as the Git-Protocol HTTP header, to allow a client to request
  606. * a newer response format while remaining compatible with older servers
  607. * that do not understand different request formats.
  608. *
  609. * @param params
  610. * parameters supplied by the client, split at colons or NUL
  611. * bytes.
  612. * @since 5.0
  613. */
  614. public void setExtraParameters(Collection<String> params) {
  615. this.clientRequestedV2 = params.contains("version=2"); //$NON-NLS-1$
  616. }
  617. private boolean useProtocolV2() {
  618. return ProtocolVersion.V2.equals(transferConfig.protocolVersion)
  619. && clientRequestedV2;
  620. }
  621. /**
  622. * Execute the upload task on the socket.
  623. *
  624. * <p>If the client passed extra parameters (e.g., "version=2") through a
  625. * side channel, the caller must call setExtraParameters first to supply
  626. * them.
  627. *
  628. * @param input
  629. * raw input to read client commands from. Caller must ensure the
  630. * input is buffered, otherwise read performance may suffer.
  631. * @param output
  632. * response back to the Git network client, to write the pack
  633. * data onto. Caller must ensure the output is buffered,
  634. * otherwise write performance may suffer.
  635. * @param messages
  636. * secondary "notice" channel to send additional messages out
  637. * through. When run over SSH this should be tied back to the
  638. * standard error channel of the command execution. For most
  639. * other network connections this should be null.
  640. * @throws java.io.IOException
  641. */
  642. public void upload(final InputStream input, OutputStream output,
  643. final OutputStream messages) throws IOException {
  644. try {
  645. rawIn = input;
  646. if (messages != null)
  647. msgOut = messages;
  648. if (timeout > 0) {
  649. final Thread caller = Thread.currentThread();
  650. timer = new InterruptTimer(caller.getName() + "-Timer"); //$NON-NLS-1$
  651. TimeoutInputStream i = new TimeoutInputStream(rawIn, timer);
  652. @SuppressWarnings("resource")
  653. TimeoutOutputStream o = new TimeoutOutputStream(output, timer);
  654. i.setTimeout(timeout * 1000);
  655. o.setTimeout(timeout * 1000);
  656. rawIn = i;
  657. output = o;
  658. }
  659. rawOut = new ResponseBufferedOutputStream(output);
  660. if (biDirectionalPipe) {
  661. rawOut.stopBuffering();
  662. }
  663. pckIn = new PacketLineIn(rawIn);
  664. pckOut = new PacketLineOut(rawOut);
  665. if (useProtocolV2()) {
  666. serviceV2();
  667. } else {
  668. service();
  669. }
  670. } finally {
  671. msgOut = NullOutputStream.INSTANCE;
  672. walk.close();
  673. if (timer != null) {
  674. try {
  675. timer.terminate();
  676. } finally {
  677. timer = null;
  678. }
  679. }
  680. }
  681. }
  682. /**
  683. * Get the PackWriter's statistics if a pack was sent to the client.
  684. *
  685. * @return statistics about pack output, if a pack was sent. Null if no pack
  686. * was sent, such as during the negotiation phase of a smart HTTP
  687. * connection, or if the client was already up-to-date.
  688. * @since 4.1
  689. */
  690. public PackStatistics getStatistics() {
  691. return statistics;
  692. }
  693. private Map<String, Ref> getAdvertisedOrDefaultRefs() throws IOException {
  694. if (refs == null)
  695. setAdvertisedRefs(db.getRefDatabase().getRefs(ALL));
  696. return refs;
  697. }
  698. private void service() throws IOException {
  699. boolean sendPack = false;
  700. // If it's a non-bidi request, we need to read the entire request before
  701. // writing a response. Buffer the response until then.
  702. PackStatistics.Accumulator accumulator = new PackStatistics.Accumulator();
  703. List<ObjectId> unshallowCommits = new ArrayList<>();
  704. try {
  705. if (biDirectionalPipe)
  706. sendAdvertisedRefs(new PacketLineOutRefAdvertiser(pckOut));
  707. else if (requestValidator instanceof AnyRequestValidator)
  708. advertised = Collections.emptySet();
  709. else
  710. advertised = refIdSet(getAdvertisedOrDefaultRefs().values());
  711. long negotiateStart = System.currentTimeMillis();
  712. accumulator.advertised = advertised.size();
  713. recvWants();
  714. if (wantIds.isEmpty()) {
  715. preUploadHook.onBeginNegotiateRound(this, wantIds, 0);
  716. preUploadHook.onEndNegotiateRound(this, wantIds, 0, 0, false);
  717. return;
  718. }
  719. accumulator.wants = wantIds.size();
  720. if (options.contains(OPTION_MULTI_ACK_DETAILED)) {
  721. multiAck = MultiAck.DETAILED;
  722. noDone = options.contains(OPTION_NO_DONE);
  723. } else if (options.contains(OPTION_MULTI_ACK))
  724. multiAck = MultiAck.CONTINUE;
  725. else
  726. multiAck = MultiAck.OFF;
  727. if (!clientShallowCommits.isEmpty())
  728. verifyClientShallow();
  729. if (depth != 0)
  730. processShallow(null, unshallowCommits, true);
  731. if (!clientShallowCommits.isEmpty())
  732. walk.assumeShallow(clientShallowCommits);
  733. sendPack = negotiate(accumulator);
  734. accumulator.timeNegotiating += System.currentTimeMillis()
  735. - negotiateStart;
  736. if (sendPack && !biDirectionalPipe) {
  737. // Ensure the request was fully consumed. Any remaining input must
  738. // be a protocol error. If we aren't at EOF the implementation is broken.
  739. int eof = rawIn.read();
  740. if (0 <= eof) {
  741. sendPack = false;
  742. throw new CorruptObjectException(MessageFormat.format(
  743. JGitText.get().expectedEOFReceived,
  744. "\\x" + Integer.toHexString(eof))); //$NON-NLS-1$
  745. }
  746. }
  747. } catch (ServiceMayNotContinueException err) {
  748. if (!err.isOutput() && err.getMessage() != null) {
  749. try {
  750. pckOut.writeString("ERR " + err.getMessage() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  751. err.setOutput();
  752. } catch (Throwable err2) {
  753. // Ignore this secondary failure (and not mark output).
  754. }
  755. }
  756. throw err;
  757. } catch (IOException | RuntimeException | Error err) {
  758. boolean output = false;
  759. try {
  760. String msg = err instanceof PackProtocolException
  761. ? err.getMessage()
  762. : JGitText.get().internalServerError;
  763. pckOut.writeString("ERR " + msg + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  764. output = true;
  765. } catch (Throwable err2) {
  766. // Ignore this secondary failure, leave output false.
  767. }
  768. if (output) {
  769. throw new UploadPackInternalServerErrorException(err);
  770. }
  771. throw err;
  772. } finally {
  773. if (!sendPack && !biDirectionalPipe) {
  774. while (0 < rawIn.skip(2048) || 0 <= rawIn.read()) {
  775. // Discard until EOF.
  776. }
  777. }
  778. rawOut.stopBuffering();
  779. }
  780. if (sendPack) {
  781. sendPack(accumulator, refs == null ? null : refs.values(), unshallowCommits);
  782. }
  783. }
  784. private void lsRefsV2() throws IOException {
  785. PacketLineOutRefAdvertiser adv = new PacketLineOutRefAdvertiser(pckOut);
  786. String line;
  787. ArrayList<String> refPrefixes = new ArrayList<>();
  788. boolean needToFindSymrefs = false;
  789. adv.setUseProtocolV2(true);
  790. line = pckIn.readString();
  791. // Currently, we do not support any capabilities, so the next
  792. // line is DELIM if there are arguments or END if not.
  793. if (line == PacketLineIn.DELIM) {
  794. while ((line = pckIn.readString()) != PacketLineIn.END) {
  795. if (line.equals("peel")) { //$NON-NLS-1$
  796. adv.setDerefTags(true);
  797. } else if (line.equals("symrefs")) { //$NON-NLS-1$
  798. needToFindSymrefs = true;
  799. } else if (line.startsWith("ref-prefix ")) { //$NON-NLS-1$
  800. refPrefixes.add(line.substring("ref-prefix ".length())); //$NON-NLS-1$
  801. } else {
  802. throw new PackProtocolException(MessageFormat
  803. .format(JGitText.get().unexpectedPacketLine, line));
  804. }
  805. }
  806. } else if (line != PacketLineIn.END) {
  807. throw new PackProtocolException(MessageFormat
  808. .format(JGitText.get().unexpectedPacketLine, line));
  809. }
  810. rawOut.stopBuffering();
  811. Map<String, Ref> refsToSend;
  812. if (refPrefixes.isEmpty()) {
  813. refsToSend = getAdvertisedOrDefaultRefs();
  814. } else {
  815. refsToSend = new HashMap<>();
  816. for (String refPrefix : refPrefixes) {
  817. for (Ref ref : db.getRefDatabase().getRefsByPrefix(refPrefix)) {
  818. refsToSend.put(ref.getName(), ref);
  819. }
  820. }
  821. }
  822. if (needToFindSymrefs) {
  823. findSymrefs(adv, refsToSend);
  824. }
  825. adv.send(refsToSend);
  826. adv.end();
  827. }
  828. private void fetchV2() throws IOException {
  829. options = new HashSet<>();
  830. // Packs are always sent multiplexed and using full 64K
  831. // lengths.
  832. options.add(OPTION_SIDE_BAND_64K);
  833. // Depending on the requestValidator, #processHaveLines may
  834. // require that advertised be set. Set it only in the required
  835. // circumstances (to avoid a full ref lookup in the case that
  836. // we don't need it).
  837. if (requestValidator instanceof TipRequestValidator ||
  838. requestValidator instanceof ReachableCommitTipRequestValidator ||
  839. requestValidator instanceof AnyRequestValidator) {
  840. advertised = Collections.emptySet();
  841. } else {
  842. advertised = refIdSet(getAdvertisedOrDefaultRefs().values());
  843. }
  844. String line;
  845. List<ObjectId> peerHas = new ArrayList<>();
  846. boolean doneReceived = false;
  847. // Currently, we do not support any capabilities, so the next
  848. // line is DELIM.
  849. if ((line = pckIn.readString()) != PacketLineIn.DELIM) {
  850. throw new PackProtocolException(MessageFormat
  851. .format(JGitText.get().unexpectedPacketLine, line));
  852. }
  853. boolean includeTag = false;
  854. while ((line = pckIn.readString()) != PacketLineIn.END) {
  855. if (line.startsWith("want ")) { //$NON-NLS-1$
  856. wantIds.add(ObjectId.fromString(line.substring(5)));
  857. } else if (line.startsWith("have ")) { //$NON-NLS-1$
  858. peerHas.add(ObjectId.fromString(line.substring(5)));
  859. } else if (line.equals("done")) { //$NON-NLS-1$
  860. doneReceived = true;
  861. } else if (line.equals(OPTION_THIN_PACK)) {
  862. options.add(OPTION_THIN_PACK);
  863. } else if (line.equals(OPTION_NO_PROGRESS)) {
  864. options.add(OPTION_NO_PROGRESS);
  865. } else if (line.equals(OPTION_INCLUDE_TAG)) {
  866. options.add(OPTION_INCLUDE_TAG);
  867. includeTag = true;
  868. } else if (line.equals(OPTION_OFS_DELTA)) {
  869. options.add(OPTION_OFS_DELTA);
  870. } else if (line.startsWith("shallow ")) { //$NON-NLS-1$
  871. clientShallowCommits.add(ObjectId.fromString(line.substring(8)));
  872. } else if (line.startsWith("deepen ")) { //$NON-NLS-1$
  873. depth = Integer.parseInt(line.substring(7));
  874. if (depth <= 0) {
  875. throw new PackProtocolException(
  876. MessageFormat.format(JGitText.get().invalidDepth,
  877. Integer.valueOf(depth)));
  878. }
  879. if (shallowSince != 0) {
  880. throw new PackProtocolException(
  881. JGitText.get().deepenSinceWithDeepen);
  882. }
  883. if (shallowExcludeRefs != null) {
  884. throw new PackProtocolException(
  885. JGitText.get().deepenNotWithDeepen);
  886. }
  887. } else if (line.startsWith("deepen-not ")) { //$NON-NLS-1$
  888. List<String> exclude = shallowExcludeRefs;
  889. if (exclude == null) {
  890. exclude = shallowExcludeRefs = new ArrayList<>();
  891. }
  892. exclude.add(line.substring(11));
  893. if (depth != 0) {
  894. throw new PackProtocolException(
  895. JGitText.get().deepenNotWithDeepen);
  896. }
  897. } else if (line.equals(OPTION_DEEPEN_RELATIVE)) {
  898. options.add(OPTION_DEEPEN_RELATIVE);
  899. } else if (line.startsWith("deepen-since ")) { //$NON-NLS-1$
  900. shallowSince = Integer.parseInt(line.substring(13));
  901. if (shallowSince <= 0) {
  902. throw new PackProtocolException(
  903. MessageFormat.format(
  904. JGitText.get().invalidTimestamp, line));
  905. }
  906. if (depth != 0) {
  907. throw new PackProtocolException(
  908. JGitText.get().deepenSinceWithDeepen);
  909. }
  910. } else {
  911. throw new PackProtocolException(MessageFormat
  912. .format(JGitText.get().unexpectedPacketLine, line));
  913. }
  914. }
  915. rawOut.stopBuffering();
  916. boolean sectionSent = false;
  917. @Nullable List<ObjectId> shallowCommits = null;
  918. List<ObjectId> unshallowCommits = new ArrayList<>();
  919. if (!clientShallowCommits.isEmpty()) {
  920. verifyClientShallow();
  921. }
  922. if (depth != 0 || shallowSince != 0 || shallowExcludeRefs != null) {
  923. shallowCommits = new ArrayList<ObjectId>();
  924. processShallow(shallowCommits, unshallowCommits, false);
  925. }
  926. if (!clientShallowCommits.isEmpty())
  927. walk.assumeShallow(clientShallowCommits);
  928. if (doneReceived) {
  929. processHaveLines(peerHas, ObjectId.zeroId(), new PacketLineOut(NullOutputStream.INSTANCE));
  930. } else {
  931. pckOut.writeString("acknowledgments\n"); //$NON-NLS-1$
  932. for (ObjectId id : peerHas) {
  933. if (walk.getObjectReader().has(id)) {
  934. pckOut.writeString("ACK " + id.getName() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  935. }
  936. }
  937. processHaveLines(peerHas, ObjectId.zeroId(), new PacketLineOut(NullOutputStream.INSTANCE));
  938. if (okToGiveUp()) {
  939. pckOut.writeString("ready\n"); //$NON-NLS-1$
  940. } else if (commonBase.isEmpty()) {
  941. pckOut.writeString("NAK\n"); //$NON-NLS-1$
  942. }
  943. sectionSent = true;
  944. }
  945. if (doneReceived || okToGiveUp()) {
  946. if (shallowCommits != null) {
  947. if (sectionSent)
  948. pckOut.writeDelim();
  949. pckOut.writeString("shallow-info\n"); //$NON-NLS-1$
  950. for (ObjectId o : shallowCommits) {
  951. pckOut.writeString("shallow " + o.getName() + '\n'); //$NON-NLS-1$
  952. }
  953. for (ObjectId o : unshallowCommits) {
  954. pckOut.writeString("unshallow " + o.getName() + '\n'); //$NON-NLS-1$
  955. }
  956. sectionSent = true;
  957. }
  958. if (sectionSent)
  959. pckOut.writeDelim();
  960. pckOut.writeString("packfile\n"); //$NON-NLS-1$
  961. sendPack(new PackStatistics.Accumulator(),
  962. includeTag
  963. ? db.getRefDatabase().getRefsByPrefix(R_TAGS)
  964. : null,
  965. new ArrayList<ObjectId>());
  966. }
  967. pckOut.end();
  968. }
  969. /*
  970. * Returns true if this is the last command and we should tear down the
  971. * connection.
  972. */
  973. private boolean serveOneCommandV2() throws IOException {
  974. String command;
  975. try {
  976. command = pckIn.readString();
  977. } catch (EOFException eof) {
  978. /* EOF when awaiting command is fine */
  979. return true;
  980. }
  981. if (command == PacketLineIn.END) {
  982. // A blank request is valid according
  983. // to the protocol; do nothing in this
  984. // case.
  985. return true;
  986. }
  987. if (command.equals("command=" + COMMAND_LS_REFS)) { //$NON-NLS-1$
  988. lsRefsV2();
  989. return false;
  990. }
  991. if (command.equals("command=" + COMMAND_FETCH)) { //$NON-NLS-1$
  992. fetchV2();
  993. return false;
  994. }
  995. throw new PackProtocolException(MessageFormat
  996. .format(JGitText.get().unknownTransportCommand, command));
  997. }
  998. private List<String> getV2CapabilityAdvertisement() {
  999. ArrayList<String> caps = new ArrayList<>();
  1000. caps.add("version 2"); //$NON-NLS-1$
  1001. caps.add(COMMAND_LS_REFS);
  1002. caps.add(COMMAND_FETCH + '=' + OPTION_SHALLOW);
  1003. return caps;
  1004. }
  1005. private void serviceV2() throws IOException {
  1006. if (biDirectionalPipe) {
  1007. // Just like in service(), the capability advertisement
  1008. // is sent only if this is a bidirectional pipe. (If
  1009. // not, the client is expected to call
  1010. // sendAdvertisedRefs() on its own.)
  1011. for (String s : getV2CapabilityAdvertisement()) {
  1012. pckOut.writeString(s + "\n"); //$NON-NLS-1$
  1013. }
  1014. pckOut.end();
  1015. while (!serveOneCommandV2()) {
  1016. // Repeat until an empty command or EOF.
  1017. }
  1018. return;
  1019. }
  1020. try {
  1021. serveOneCommandV2();
  1022. } finally {
  1023. while (0 < rawIn.skip(2048) || 0 <= rawIn.read()) {
  1024. // Discard until EOF.
  1025. }
  1026. rawOut.stopBuffering();
  1027. }
  1028. }
  1029. private static Set<ObjectId> refIdSet(Collection<Ref> refs) {
  1030. Set<ObjectId> ids = new HashSet<>(refs.size());
  1031. for (Ref ref : refs) {
  1032. ObjectId id = ref.getObjectId();
  1033. if (id != null) {
  1034. ids.add(id);
  1035. }
  1036. id = ref.getPeeledObjectId();
  1037. if (id != null) {
  1038. ids.add(id);
  1039. }
  1040. }
  1041. return ids;
  1042. }
  1043. /*
  1044. * Determines what "shallow" and "unshallow" lines to send to the user.
  1045. * The information is written to shallowCommits (if not null) and
  1046. * unshallowCommits, and also written to #pckOut (if writeToPckOut is
  1047. * true).
  1048. */
  1049. private void processShallow(@Nullable List<ObjectId> shallowCommits,
  1050. List<ObjectId> unshallowCommits,
  1051. boolean writeToPckOut) throws IOException {
  1052. if (options.contains(OPTION_DEEPEN_RELATIVE) ||
  1053. shallowSince != 0 ||
  1054. shallowExcludeRefs != null) {
  1055. // TODO(jonathantanmy): Implement deepen-relative, deepen-since,
  1056. // and deepen-not.
  1057. throw new UnsupportedOperationException();
  1058. }
  1059. int walkDepth = depth - 1;
  1060. try (DepthWalk.RevWalk depthWalk = new DepthWalk.RevWalk(
  1061. walk.getObjectReader(), walkDepth)) {
  1062. // Find all the commits which will be shallow
  1063. for (ObjectId o : wantIds) {
  1064. try {
  1065. depthWalk.markRoot(depthWalk.parseCommit(o));
  1066. } catch (IncorrectObjectTypeException notCommit) {
  1067. // Ignore non-commits in this loop.
  1068. }
  1069. }
  1070. RevCommit o;
  1071. while ((o = depthWalk.next()) != null) {
  1072. DepthWalk.Commit c = (DepthWalk.Commit) o;
  1073. // Commits at the boundary which aren't already shallow in
  1074. // the client need to be marked as such
  1075. if (c.getDepth() == walkDepth
  1076. && !clientShallowCommits.contains(c)) {
  1077. if (shallowCommits != null) {
  1078. shallowCommits.add(c.copy());
  1079. }
  1080. if (writeToPckOut) {
  1081. pckOut.writeString("shallow " + o.name()); //$NON-NLS-1$
  1082. }
  1083. }
  1084. // Commits not on the boundary which are shallow in the client
  1085. // need to become unshallowed
  1086. if (c.getDepth() < walkDepth
  1087. && clientShallowCommits.remove(c)) {
  1088. unshallowCommits.add(c.copy());
  1089. if (writeToPckOut) {
  1090. pckOut.writeString("unshallow " + c.name()); //$NON-NLS-1$
  1091. }
  1092. }
  1093. }
  1094. }
  1095. if (writeToPckOut) {
  1096. pckOut.end();
  1097. }
  1098. }
  1099. private void verifyClientShallow()
  1100. throws IOException, PackProtocolException {
  1101. AsyncRevObjectQueue q = walk.parseAny(clientShallowCommits, true);
  1102. try {
  1103. for (;;) {
  1104. try {
  1105. // Shallow objects named by the client must be commits.
  1106. RevObject o = q.next();
  1107. if (o == null) {
  1108. break;
  1109. }
  1110. if (!(o instanceof RevCommit)) {
  1111. throw new PackProtocolException(
  1112. MessageFormat.format(
  1113. JGitText.get().invalidShallowObject,
  1114. o.name()));
  1115. }
  1116. } catch (MissingObjectException notCommit) {
  1117. // shallow objects not known at the server are ignored
  1118. // by git-core upload-pack, match that behavior.
  1119. clientShallowCommits.remove(notCommit.getObjectId());
  1120. continue;
  1121. }
  1122. }
  1123. } finally {
  1124. q.release();
  1125. }
  1126. }
  1127. /**
  1128. * Generate an advertisement of available refs and capabilities.
  1129. *
  1130. * @param adv
  1131. * the advertisement formatter.
  1132. * @throws java.io.IOException
  1133. * the formatter failed to write an advertisement.
  1134. * @throws org.eclipse.jgit.transport.ServiceMayNotContinueException
  1135. * the hook denied advertisement.
  1136. */
  1137. public void sendAdvertisedRefs(RefAdvertiser adv) throws IOException,
  1138. ServiceMayNotContinueException {
  1139. sendAdvertisedRefs(adv, null);
  1140. }
  1141. /**
  1142. * Generate an advertisement of available refs and capabilities.
  1143. *
  1144. * @param adv
  1145. * the advertisement formatter.
  1146. * @param serviceName
  1147. * if not null, also output "# service=serviceName" followed by a
  1148. * flush packet before the advertisement. This is required
  1149. * in v0 of the HTTP protocol, described in Git's
  1150. * Documentation/technical/http-protocol.txt.
  1151. * @throws java.io.IOException
  1152. * the formatter failed to write an advertisement.
  1153. * @throws org.eclipse.jgit.transport.ServiceMayNotContinueException
  1154. * the hook denied advertisement.
  1155. * @since 5.0
  1156. */
  1157. public void sendAdvertisedRefs(RefAdvertiser adv,
  1158. @Nullable String serviceName) throws IOException,
  1159. ServiceMayNotContinueException {
  1160. if (useProtocolV2()) {
  1161. // The equivalent in v2 is only the capabilities
  1162. // advertisement.
  1163. for (String s : getV2CapabilityAdvertisement()) {
  1164. adv.writeOne(s);
  1165. }
  1166. adv.end();
  1167. return;
  1168. }
  1169. try {
  1170. advertiseRefsHook.advertiseRefs(this);
  1171. } catch (ServiceMayNotContinueException fail) {
  1172. if (fail.getMessage() != null) {
  1173. adv.writeOne("ERR " + fail.getMessage()); //$NON-NLS-1$
  1174. fail.setOutput();
  1175. }
  1176. throw fail;
  1177. }
  1178. if (serviceName != null) {
  1179. adv.writeOne("# service=" + serviceName + '\n'); //$NON-NLS-1$
  1180. adv.end();
  1181. }
  1182. adv.init(db);
  1183. adv.advertiseCapability(OPTION_INCLUDE_TAG);
  1184. adv.advertiseCapability(OPTION_MULTI_ACK_DETAILED);
  1185. adv.advertiseCapability(OPTION_MULTI_ACK);
  1186. adv.advertiseCapability(OPTION_OFS_DELTA);
  1187. adv.advertiseCapability(OPTION_SIDE_BAND);
  1188. adv.advertiseCapability(OPTION_SIDE_BAND_64K);
  1189. adv.advertiseCapability(OPTION_THIN_PACK);
  1190. adv.advertiseCapability(OPTION_NO_PROGRESS);
  1191. adv.advertiseCapability(OPTION_SHALLOW);
  1192. if (!biDirectionalPipe)
  1193. adv.advertiseCapability(OPTION_NO_DONE);
  1194. RequestPolicy policy = getRequestPolicy();
  1195. if (policy == RequestPolicy.TIP
  1196. || policy == RequestPolicy.REACHABLE_COMMIT_TIP
  1197. || policy == null)
  1198. adv.advertiseCapability(OPTION_ALLOW_TIP_SHA1_IN_WANT);
  1199. if (policy == RequestPolicy.REACHABLE_COMMIT
  1200. || policy == RequestPolicy.REACHABLE_COMMIT_TIP
  1201. || policy == null)
  1202. adv.advertiseCapability(OPTION_ALLOW_REACHABLE_SHA1_IN_WANT);
  1203. adv.advertiseCapability(OPTION_AGENT, UserAgent.get());
  1204. if (transferConfig.isAllowFilter()) {
  1205. adv.advertiseCapability(OPTION_FILTER);
  1206. }
  1207. adv.setDerefTags(true);
  1208. Map<String, Ref> advertisedOrDefaultRefs = getAdvertisedOrDefaultRefs();
  1209. findSymrefs(adv, advertisedOrDefaultRefs);
  1210. advertised = adv.send(advertisedOrDefaultRefs);
  1211. if (adv.isEmpty())
  1212. adv.advertiseId(ObjectId.zeroId(), "capabilities^{}"); //$NON-NLS-1$
  1213. adv.end();
  1214. }
  1215. /**
  1216. * Send a message to the client, if it supports receiving them.
  1217. * <p>
  1218. * If the client doesn't support receiving messages, the message will be
  1219. * discarded, with no other indication to the caller or to the client.
  1220. *
  1221. * @param what
  1222. * string describing the problem identified by the hook. The
  1223. * string must not end with an LF, and must not contain an LF.
  1224. * @since 3.1
  1225. */
  1226. public void sendMessage(String what) {
  1227. try {
  1228. msgOut.write(Constants.encode(what + "\n")); //$NON-NLS-1$
  1229. } catch (IOException e) {
  1230. // Ignore write failures.
  1231. }
  1232. }
  1233. /**
  1234. * Get an underlying stream for sending messages to the client
  1235. *
  1236. * @return an underlying stream for sending messages to the client, or null.
  1237. * @since 3.1
  1238. */
  1239. public OutputStream getMessageOutputStream() {
  1240. return msgOut;
  1241. }
  1242. private void parseFilter(String arg) throws PackProtocolException {
  1243. if (arg.equals("blob:none")) { //$NON-NLS-1$
  1244. filterBlobLimit = 0;
  1245. } else if (arg.startsWith("blob:limit=")) { //$NON-NLS-1$
  1246. try {
  1247. filterBlobLimit = Long.parseLong(
  1248. arg.substring("blob:limit=".length())); //$NON-NLS-1$
  1249. } catch (NumberFormatException e) {
  1250. throw new PackProtocolException(
  1251. MessageFormat.format(JGitText.get().invalidFilter,
  1252. arg));
  1253. }
  1254. }
  1255. /*
  1256. * We must have (1) either "blob:none" or
  1257. * "blob:limit=" set (because we only support
  1258. * blob size limits for now), and (2) if the
  1259. * latter, then it must be nonnegative. Throw
  1260. * if (1) or (2) is not met.
  1261. */
  1262. if (filterBlobLimit < 0) {
  1263. throw new PackProtocolException(
  1264. MessageFormat.format(JGitText.get().invalidFilter,
  1265. arg));
  1266. }
  1267. }
  1268. private void recvWants() throws IOException {
  1269. boolean isFirst = true;
  1270. boolean filterReceived = false;
  1271. for (;;) {
  1272. String line;
  1273. try {
  1274. line = pckIn.readString();
  1275. } catch (EOFException eof) {
  1276. if (isFirst)
  1277. break;
  1278. throw eof;
  1279. }
  1280. if (line == PacketLineIn.END)
  1281. break;
  1282. if (line.startsWith("deepen ")) { //$NON-NLS-1$
  1283. depth = Integer.parseInt(line.substring(7));
  1284. if (depth <= 0) {
  1285. throw new PackProtocolException(
  1286. MessageFormat.format(JGitText.get().invalidDepth,
  1287. Integer.valueOf(depth)));
  1288. }
  1289. continue;
  1290. }
  1291. if (line.startsWith("shallow ")) { //$NON-NLS-1$
  1292. clientShallowCommits.add(ObjectId.fromString(line.substring(8)));
  1293. continue;
  1294. }
  1295. if (transferConfig.isAllowFilter()
  1296. && line.startsWith(OPTION_FILTER + " ")) { //$NON-NLS-1$
  1297. String arg = line.substring(OPTION_FILTER.length() + 1);
  1298. if (filterReceived) {
  1299. throw new PackProtocolException(JGitText.get().tooManyFilters);
  1300. }
  1301. filterReceived = true;
  1302. parseFilter(arg);
  1303. continue;
  1304. }
  1305. if (!line.startsWith("want ") || line.length() < 45) //$NON-NLS-1$
  1306. throw new PackProtocolException(MessageFormat.format(JGitText.get().expectedGot, "want", line)); //$NON-NLS-1$
  1307. if (isFirst) {
  1308. if (line.length() > 45) {
  1309. FirstLine firstLine = new FirstLine(line);
  1310. options = firstLine.getOptions();
  1311. line = firstLine.getLine();
  1312. } else
  1313. options = Collections.emptySet();
  1314. }
  1315. wantIds.add(ObjectId.fromString(line.substring(5)));
  1316. isFirst = false;
  1317. }
  1318. }
  1319. /**
  1320. * Returns the clone/fetch depth. Valid only after calling recvWants(). A
  1321. * depth of 1 means return only the wants.
  1322. *
  1323. * @return the depth requested by the client, or 0 if unbounded.
  1324. * @since 4.0
  1325. */
  1326. public int getDepth() {
  1327. if (options == null)
  1328. throw new RequestNotYetReadException();
  1329. return depth;
  1330. }
  1331. /**
  1332. * Get the user agent of the client.
  1333. * <p>
  1334. * If the client is new enough to use {@code agent=} capability that value
  1335. * will be returned. Older HTTP clients may also supply their version using
  1336. * the HTTP {@code User-Agent} header. The capability overrides the HTTP
  1337. * header if both are available.
  1338. * <p>
  1339. * When an HTTP request has been received this method returns the HTTP
  1340. * {@code User-Agent} header value until capabilities have been parsed.
  1341. *
  1342. * @return user agent supplied by the client. Available only if the client
  1343. * is new enough to advertise its user agent.
  1344. * @since 4.0
  1345. */
  1346. public String getPeerUserAgent() {
  1347. return UserAgent.getAgent(options, userAgent);
  1348. }
  1349. private boolean negotiate(PackStatistics.Accumulator accumulator)
  1350. throws IOException {
  1351. okToGiveUp = Boolean.FALSE;
  1352. ObjectId last = ObjectId.zeroId();
  1353. List<ObjectId> peerHas = new ArrayList<>(64);
  1354. for (;;) {
  1355. String line;
  1356. try {
  1357. line = pckIn.readString();
  1358. } catch (EOFException eof) {
  1359. // EOF on stateless RPC (aka smart HTTP) and non-shallow request
  1360. // means the client asked for the updated shallow/unshallow data,
  1361. // disconnected, and will try another request with actual want/have.
  1362. // Don't report the EOF here, its a bug in the protocol that the client
  1363. // just disconnects without sending an END.
  1364. if (!biDirectionalPipe && depth > 0)
  1365. return false;
  1366. throw eof;
  1367. }
  1368. if (line == PacketLineIn.END) {
  1369. last = processHaveLines(peerHas, last, pckOut);
  1370. if (commonBase.isEmpty() || multiAck != MultiAck.OFF)
  1371. pckOut.writeString("NAK\n"); //$NON-NLS-1$
  1372. if (noDone && sentReady) {
  1373. pckOut.writeString("ACK " + last.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1374. return true;
  1375. }
  1376. if (!biDirectionalPipe)
  1377. return false;
  1378. pckOut.flush();
  1379. } else if (line.startsWith("have ") && line.length() == 45) { //$NON-NLS-1$
  1380. peerHas.add(ObjectId.fromString(line.substring(5)));
  1381. accumulator.haves++;
  1382. } else if (line.equals("done")) { //$NON-NLS-1$
  1383. last = processHaveLines(peerHas, last, pckOut);
  1384. if (commonBase.isEmpty())
  1385. pckOut.writeString("NAK\n"); //$NON-NLS-1$
  1386. else if (multiAck != MultiAck.OFF)
  1387. pckOut.writeString("ACK " + last.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1388. return true;
  1389. } else {
  1390. throw new PackProtocolException(MessageFormat.format(JGitText.get().expectedGot, "have", line)); //$NON-NLS-1$
  1391. }
  1392. }
  1393. }
  1394. private ObjectId processHaveLines(List<ObjectId> peerHas, ObjectId last, PacketLineOut out)
  1395. throws IOException {
  1396. preUploadHook.onBeginNegotiateRound(this, wantIds, peerHas.size());
  1397. if (wantAll.isEmpty() && !wantIds.isEmpty())
  1398. parseWants();
  1399. if (peerHas.isEmpty())
  1400. return last;
  1401. sentReady = false;
  1402. int haveCnt = 0;
  1403. walk.getObjectReader().setAvoidUnreachableObjects(true);
  1404. AsyncRevObjectQueue q = walk.parseAny(peerHas, false);
  1405. try {
  1406. for (;;) {
  1407. RevObject obj;
  1408. try {
  1409. obj = q.next();
  1410. } catch (MissingObjectException notFound) {
  1411. continue;
  1412. }
  1413. if (obj == null)
  1414. break;
  1415. last = obj;
  1416. haveCnt++;
  1417. if (obj instanceof RevCommit) {
  1418. RevCommit c = (RevCommit) obj;
  1419. if (oldestTime == 0 || c.getCommitTime() < oldestTime)
  1420. oldestTime = c.getCommitTime();
  1421. }
  1422. if (obj.has(PEER_HAS))
  1423. continue;
  1424. obj.add(PEER_HAS);
  1425. if (obj instanceof RevCommit)
  1426. ((RevCommit) obj).carry(PEER_HAS);
  1427. addCommonBase(obj);
  1428. // If both sides have the same object; let the client know.
  1429. //
  1430. switch (multiAck) {
  1431. case OFF:
  1432. if (commonBase.size() == 1)
  1433. out.writeString("ACK " + obj.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1434. break;
  1435. case CONTINUE:
  1436. out.writeString("ACK " + obj.name() + " continue\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1437. break;
  1438. case DETAILED:
  1439. out.writeString("ACK " + obj.name() + " common\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1440. break;
  1441. }
  1442. }
  1443. } finally {
  1444. q.release();
  1445. walk.getObjectReader().setAvoidUnreachableObjects(false);
  1446. }
  1447. int missCnt = peerHas.size() - haveCnt;
  1448. // If we don't have one of the objects but we're also willing to
  1449. // create a pack at this point, let the client know so it stops
  1450. // telling us about its history.
  1451. //
  1452. boolean didOkToGiveUp = false;
  1453. if (0 < missCnt) {
  1454. for (int i = peerHas.size() - 1; i >= 0; i--) {
  1455. ObjectId id = peerHas.get(i);
  1456. if (walk.lookupOrNull(id) == null) {
  1457. didOkToGiveUp = true;
  1458. if (okToGiveUp()) {
  1459. switch (multiAck) {
  1460. case OFF:
  1461. break;
  1462. case CONTINUE:
  1463. out.writeString("ACK " + id.name() + " continue\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1464. break;
  1465. case DETAILED:
  1466. out.writeString("ACK " + id.name() + " ready\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1467. sentReady = true;
  1468. break;
  1469. }
  1470. }
  1471. break;
  1472. }
  1473. }
  1474. }
  1475. if (multiAck == MultiAck.DETAILED && !didOkToGiveUp && okToGiveUp()) {
  1476. ObjectId id = peerHas.get(peerHas.size() - 1);
  1477. out.writeString("ACK " + id.name() + " ready\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1478. sentReady = true;
  1479. }
  1480. preUploadHook.onEndNegotiateRound(this, wantAll, haveCnt, missCnt, sentReady);
  1481. peerHas.clear();
  1482. return last;
  1483. }
  1484. private void parseWants() throws IOException {
  1485. List<ObjectId> notAdvertisedWants = null;
  1486. for (ObjectId obj : wantIds) {
  1487. if (!advertised.contains(obj)) {
  1488. if (notAdvertisedWants == null)
  1489. notAdvertisedWants = new ArrayList<>();
  1490. notAdvertisedWants.add(obj);
  1491. }
  1492. }
  1493. if (notAdvertisedWants != null)
  1494. requestValidator.checkWants(this, notAdvertisedWants);
  1495. AsyncRevObjectQueue q = walk.parseAny(wantIds, true);
  1496. try {
  1497. RevObject obj;
  1498. while ((obj = q.next()) != null) {
  1499. want(obj);
  1500. if (!(obj instanceof RevCommit))
  1501. obj.add(SATISFIED);
  1502. if (obj instanceof RevTag) {
  1503. obj = walk.peel(obj);
  1504. if (obj instanceof RevCommit)
  1505. want(obj);
  1506. }
  1507. }
  1508. wantIds.clear();
  1509. } catch (MissingObjectException notFound) {
  1510. throw new WantNotValidException(notFound.getObjectId(), notFound);
  1511. } finally {
  1512. q.release();
  1513. }
  1514. }
  1515. private void want(RevObject obj) {
  1516. if (!obj.has(WANT)) {
  1517. obj.add(WANT);
  1518. wantAll.add(obj);
  1519. }
  1520. }
  1521. /**
  1522. * Validator corresponding to {@link RequestPolicy#ADVERTISED}.
  1523. *
  1524. * @since 3.1
  1525. */
  1526. public static final class AdvertisedRequestValidator
  1527. implements RequestValidator {
  1528. @Override
  1529. public void checkWants(UploadPack up, List<ObjectId> wants)
  1530. throws PackProtocolException, IOException {
  1531. if (!up.isBiDirectionalPipe())
  1532. new ReachableCommitRequestValidator().checkWants(up, wants);
  1533. else if (!wants.isEmpty())
  1534. throw new WantNotValidException(wants.iterator().next());
  1535. }
  1536. }
  1537. /**
  1538. * Validator corresponding to {@link RequestPolicy#REACHABLE_COMMIT}.
  1539. *
  1540. * @since 3.1
  1541. */
  1542. public static final class ReachableCommitRequestValidator
  1543. implements RequestValidator {
  1544. @Override
  1545. public void checkWants(UploadPack up, List<ObjectId> wants)
  1546. throws PackProtocolException, IOException {
  1547. checkNotAdvertisedWants(up, wants,
  1548. refIdSet(up.getAdvertisedRefs().values()));
  1549. }
  1550. }
  1551. /**
  1552. * Validator corresponding to {@link RequestPolicy#TIP}.
  1553. *
  1554. * @since 3.1
  1555. */
  1556. public static final class TipRequestValidator implements RequestValidator {
  1557. @Override
  1558. public void checkWants(UploadPack up, List<ObjectId> wants)
  1559. throws PackProtocolException, IOException {
  1560. if (!up.isBiDirectionalPipe())
  1561. new ReachableCommitTipRequestValidator().checkWants(up, wants);
  1562. else if (!wants.isEmpty()) {
  1563. Set<ObjectId> refIds =
  1564. refIdSet(up.getRepository().getRefDatabase().getRefs());
  1565. for (ObjectId obj : wants) {
  1566. if (!refIds.contains(obj))
  1567. throw new WantNotValidException(obj);
  1568. }
  1569. }
  1570. }
  1571. }
  1572. /**
  1573. * Validator corresponding to {@link RequestPolicy#REACHABLE_COMMIT_TIP}.
  1574. *
  1575. * @since 3.1
  1576. */
  1577. public static final class ReachableCommitTipRequestValidator
  1578. implements RequestValidator {
  1579. @Override
  1580. public void checkWants(UploadPack up, List<ObjectId> wants)
  1581. throws PackProtocolException, IOException {
  1582. checkNotAdvertisedWants(up, wants,
  1583. refIdSet(up.getRepository().getRefDatabase().getRefs()));
  1584. }
  1585. }
  1586. /**
  1587. * Validator corresponding to {@link RequestPolicy#ANY}.
  1588. *
  1589. * @since 3.1
  1590. */
  1591. public static final class AnyRequestValidator implements RequestValidator {
  1592. @Override
  1593. public void checkWants(UploadPack up, List<ObjectId> wants)
  1594. throws PackProtocolException, IOException {
  1595. // All requests are valid.
  1596. }
  1597. }
  1598. private static void checkNotAdvertisedWantsUsingBitmap(ObjectReader reader,
  1599. BitmapIndex bitmapIndex, List<ObjectId> notAdvertisedWants,
  1600. Set<ObjectId> reachableFrom) throws IOException {
  1601. BitmapWalker bitmapWalker = new BitmapWalker(new ObjectWalk(reader), bitmapIndex, null);
  1602. BitmapBuilder reachables = bitmapWalker.findObjects(reachableFrom, null, false);
  1603. for (ObjectId oid : notAdvertisedWants) {
  1604. if (!reachables.contains(oid)) {
  1605. throw new WantNotValidException(oid);
  1606. }
  1607. }
  1608. }
  1609. private static void checkNotAdvertisedWants(UploadPack up,
  1610. List<ObjectId> notAdvertisedWants, Set<ObjectId> reachableFrom)
  1611. throws MissingObjectException, IncorrectObjectTypeException, IOException {
  1612. // Walk the requested commits back to the provided set of commits. If any
  1613. // commit exists, a branch was deleted or rewound and the repository owner
  1614. // no longer exports that requested item. If the requested commit is merged
  1615. // into an advertised branch it will be marked UNINTERESTING and no commits
  1616. // return.
  1617. ObjectReader reader = up.getRevWalk().getObjectReader();
  1618. try (RevWalk walk = new RevWalk(reader)) {
  1619. AsyncRevObjectQueue q = walk.parseAny(notAdvertisedWants, true);
  1620. try {
  1621. RevObject obj;
  1622. while ((obj = q.next()) != null) {
  1623. if (!(obj instanceof RevCommit)) {
  1624. // If unadvertized non-commits are requested, use
  1625. // bitmaps. If there are no bitmaps, instead of
  1626. // incurring the expense of a manual walk, reject
  1627. // the request.
  1628. BitmapIndex bitmapIndex = reader.getBitmapIndex();
  1629. if (bitmapIndex != null) {
  1630. checkNotAdvertisedWantsUsingBitmap(
  1631. reader,
  1632. bitmapIndex,
  1633. notAdvertisedWants,
  1634. reachableFrom);
  1635. return;
  1636. }
  1637. throw new WantNotValidException(obj);
  1638. }
  1639. walk.markStart((RevCommit) obj);
  1640. }
  1641. } catch (MissingObjectException notFound) {
  1642. throw new WantNotValidException(notFound.getObjectId(),
  1643. notFound);
  1644. } finally {
  1645. q.release();
  1646. }
  1647. for (ObjectId id : reachableFrom) {
  1648. try {
  1649. walk.markUninteresting(walk.parseCommit(id));
  1650. } catch (IncorrectObjectTypeException notCommit) {
  1651. continue;
  1652. }
  1653. }
  1654. RevCommit bad = walk.next();
  1655. if (bad != null) {
  1656. throw new WantNotValidException(bad);
  1657. }
  1658. }
  1659. }
  1660. private void addCommonBase(RevObject o) {
  1661. if (!o.has(COMMON)) {
  1662. o.add(COMMON);
  1663. commonBase.add(o);
  1664. okToGiveUp = null;
  1665. }
  1666. }
  1667. private boolean okToGiveUp() throws PackProtocolException {
  1668. if (okToGiveUp == null)
  1669. okToGiveUp = Boolean.valueOf(okToGiveUpImp());
  1670. return okToGiveUp.booleanValue();
  1671. }
  1672. private boolean okToGiveUpImp() throws PackProtocolException {
  1673. if (commonBase.isEmpty())
  1674. return false;
  1675. try {
  1676. for (RevObject obj : wantAll) {
  1677. if (!wantSatisfied(obj))
  1678. return false;
  1679. }
  1680. return true;
  1681. } catch (IOException e) {
  1682. throw new PackProtocolException(JGitText.get().internalRevisionError, e);
  1683. }
  1684. }
  1685. private boolean wantSatisfied(RevObject want) throws IOException {
  1686. if (want.has(SATISFIED))
  1687. return true;
  1688. walk.resetRetain(SAVE);
  1689. walk.markStart((RevCommit) want);
  1690. if (oldestTime != 0)
  1691. walk.setRevFilter(CommitTimeRevFilter.after(oldestTime * 1000L));
  1692. for (;;) {
  1693. final RevCommit c = walk.next();
  1694. if (c == null)
  1695. break;
  1696. if (c.has(PEER_HAS)) {
  1697. addCommonBase(c);
  1698. want.add(SATISFIED);
  1699. return true;
  1700. }
  1701. }
  1702. return false;
  1703. }
  1704. /**
  1705. * Send the requested objects to the client.
  1706. *
  1707. * @param accumulator
  1708. * where to write statistics about the content of the pack.
  1709. * @param allTags
  1710. * refs to search for annotated tags to include in the pack
  1711. * if the {@link #OPTION_INCLUDE_TAG} capability was
  1712. * requested.
  1713. * @param unshallowCommits
  1714. * shallow commits on the client that are now becoming
  1715. * unshallow
  1716. * @throws IOException
  1717. * if an error occured while generating or writing the pack.
  1718. */
  1719. private void sendPack(PackStatistics.Accumulator accumulator,
  1720. @Nullable Collection<Ref> allTags,
  1721. List<ObjectId> unshallowCommits) throws IOException {
  1722. final boolean sideband = options.contains(OPTION_SIDE_BAND)
  1723. || options.contains(OPTION_SIDE_BAND_64K);
  1724. if (sideband) {
  1725. try {
  1726. sendPack(true, accumulator, allTags, unshallowCommits);
  1727. } catch (ServiceMayNotContinueException noPack) {
  1728. // This was already reported on (below).
  1729. throw noPack;
  1730. } catch (IOException err) {
  1731. if (reportInternalServerErrorOverSideband())
  1732. throw new UploadPackInternalServerErrorException(err);
  1733. else
  1734. throw err;
  1735. } catch (RuntimeException err) {
  1736. if (reportInternalServerErrorOverSideband())
  1737. throw new UploadPackInternalServerErrorException(err);
  1738. else
  1739. throw err;
  1740. } catch (Error err) {
  1741. if (reportInternalServerErrorOverSideband())
  1742. throw new UploadPackInternalServerErrorException(err);
  1743. else
  1744. throw err;
  1745. }
  1746. } else {
  1747. sendPack(false, accumulator, allTags, unshallowCommits);
  1748. }
  1749. }
  1750. private boolean reportInternalServerErrorOverSideband() {
  1751. try {
  1752. @SuppressWarnings("resource" /* java 7 */)
  1753. SideBandOutputStream err = new SideBandOutputStream(
  1754. SideBandOutputStream.CH_ERROR,
  1755. SideBandOutputStream.SMALL_BUF,
  1756. rawOut);
  1757. err.write(Constants.encode(JGitText.get().internalServerError));
  1758. err.flush();
  1759. return true;
  1760. } catch (Throwable cannotReport) {
  1761. // Ignore the reason. This is a secondary failure.
  1762. return false;
  1763. }
  1764. }
  1765. /**
  1766. * Send the requested objects to the client.
  1767. *
  1768. * @param sideband
  1769. * whether to wrap the pack in side-band pkt-lines,
  1770. * interleaved with progress messages and errors.
  1771. * @param accumulator
  1772. * where to write statistics about the content of the pack.
  1773. * @param allTags
  1774. * refs to search for annotated tags to include in the pack
  1775. * if the {@link #OPTION_INCLUDE_TAG} capability was
  1776. * requested.
  1777. * @param unshallowCommits
  1778. * shallow commits on the client that are now becoming
  1779. * unshallow
  1780. * @throws IOException
  1781. * if an error occured while generating or writing the pack.
  1782. */
  1783. private void sendPack(final boolean sideband,
  1784. PackStatistics.Accumulator accumulator,
  1785. @Nullable Collection<Ref> allTags,
  1786. List<ObjectId> unshallowCommits) throws IOException {
  1787. ProgressMonitor pm = NullProgressMonitor.INSTANCE;
  1788. OutputStream packOut = rawOut;
  1789. if (sideband) {
  1790. int bufsz = SideBandOutputStream.SMALL_BUF;
  1791. if (options.contains(OPTION_SIDE_BAND_64K))
  1792. bufsz = SideBandOutputStream.MAX_BUF;
  1793. packOut = new SideBandOutputStream(SideBandOutputStream.CH_DATA,
  1794. bufsz, rawOut);
  1795. if (!options.contains(OPTION_NO_PROGRESS)) {
  1796. msgOut = new SideBandOutputStream(
  1797. SideBandOutputStream.CH_PROGRESS, bufsz, rawOut);
  1798. pm = new SideBandProgressMonitor(msgOut);
  1799. }
  1800. }
  1801. try {
  1802. if (wantAll.isEmpty()) {
  1803. preUploadHook.onSendPack(this, wantIds, commonBase);
  1804. } else {
  1805. preUploadHook.onSendPack(this, wantAll, commonBase);
  1806. }
  1807. msgOut.flush();
  1808. } catch (ServiceMayNotContinueException noPack) {
  1809. if (sideband && noPack.getMessage() != null) {
  1810. noPack.setOutput();
  1811. @SuppressWarnings("resource" /* java 7 */)
  1812. SideBandOutputStream err = new SideBandOutputStream(
  1813. SideBandOutputStream.CH_ERROR,
  1814. SideBandOutputStream.SMALL_BUF, rawOut);
  1815. err.write(Constants.encode(noPack.getMessage()));
  1816. err.flush();
  1817. }
  1818. throw noPack;
  1819. }
  1820. PackConfig cfg = packConfig;
  1821. if (cfg == null)
  1822. cfg = new PackConfig(db);
  1823. @SuppressWarnings("resource") // PackWriter is referenced in the finally
  1824. // block, and is closed there
  1825. final PackWriter pw = new PackWriter(cfg, walk.getObjectReader(),
  1826. accumulator);
  1827. try {
  1828. pw.setIndexDisabled(true);
  1829. if (filterBlobLimit >= 0) {
  1830. pw.setFilterBlobLimit(filterBlobLimit);
  1831. pw.setUseCachedPacks(false);
  1832. } else {
  1833. pw.setUseCachedPacks(true);
  1834. }
  1835. pw.setUseBitmaps(depth == 0 && clientShallowCommits.isEmpty());
  1836. pw.setClientShallowCommits(clientShallowCommits);
  1837. pw.setReuseDeltaCommits(true);
  1838. pw.setDeltaBaseAsOffset(options.contains(OPTION_OFS_DELTA));
  1839. pw.setThin(options.contains(OPTION_THIN_PACK));
  1840. pw.setReuseValidatingObjects(false);
  1841. // Objects named directly by references go at the beginning
  1842. // of the pack.
  1843. if (commonBase.isEmpty() && refs != null) {
  1844. Set<ObjectId> tagTargets = new HashSet<>();
  1845. for (Ref ref : refs.values()) {
  1846. if (ref.getPeeledObjectId() != null)
  1847. tagTargets.add(ref.getPeeledObjectId());
  1848. else if (ref.getObjectId() == null)
  1849. continue;
  1850. else if (ref.getName().startsWith(Constants.R_HEADS))
  1851. tagTargets.add(ref.getObjectId());
  1852. }
  1853. pw.setTagTargets(tagTargets);
  1854. }
  1855. RevWalk rw = walk;
  1856. if (depth > 0) {
  1857. pw.setShallowPack(depth, unshallowCommits);
  1858. rw = new DepthWalk.RevWalk(walk.getObjectReader(), depth - 1);
  1859. rw.assumeShallow(clientShallowCommits);
  1860. }
  1861. if (wantAll.isEmpty()) {
  1862. pw.preparePack(pm, wantIds, commonBase, clientShallowCommits);
  1863. } else {
  1864. walk.reset();
  1865. ObjectWalk ow = rw.toObjectWalkWithSameObjects();
  1866. pw.preparePack(pm, ow, wantAll, commonBase, PackWriter.NONE);
  1867. rw = ow;
  1868. }
  1869. if (options.contains(OPTION_INCLUDE_TAG) && allTags != null) {
  1870. for (Ref ref : allTags) {
  1871. ObjectId objectId = ref.getObjectId();
  1872. if (objectId == null) {
  1873. // skip unborn branch
  1874. continue;
  1875. }
  1876. // If the object was already requested, skip it.
  1877. if (wantAll.isEmpty()) {
  1878. if (wantIds.contains(objectId))
  1879. continue;
  1880. } else {
  1881. RevObject obj = rw.lookupOrNull(objectId);
  1882. if (obj != null && obj.has(WANT))
  1883. continue;
  1884. }
  1885. if (!ref.isPeeled())
  1886. ref = db.getRefDatabase().peel(ref);
  1887. ObjectId peeledId = ref.getPeeledObjectId();
  1888. objectId = ref.getObjectId();
  1889. if (peeledId == null || objectId == null)
  1890. continue;
  1891. if (pw.willInclude(peeledId) && !pw.willInclude(objectId)) {
  1892. pw.addObject(rw.parseAny(objectId));
  1893. }
  1894. }
  1895. }
  1896. pw.writePack(pm, NullProgressMonitor.INSTANCE, packOut);
  1897. if (msgOut != NullOutputStream.INSTANCE) {
  1898. String msg = pw.getStatistics().getMessage() + '\n';
  1899. msgOut.write(Constants.encode(msg));
  1900. msgOut.flush();
  1901. }
  1902. } finally {
  1903. statistics = pw.getStatistics();
  1904. if (statistics != null) {
  1905. postUploadHook.onPostUpload(statistics);
  1906. }
  1907. pw.close();
  1908. }
  1909. if (sideband)
  1910. pckOut.end();
  1911. }
  1912. private static void findSymrefs(
  1913. final RefAdvertiser adv, final Map<String, Ref> refs) {
  1914. Ref head = refs.get(Constants.HEAD);
  1915. if (head != null && head.isSymbolic()) {
  1916. adv.addSymref(Constants.HEAD, head.getLeaf().getName());
  1917. }
  1918. }
  1919. private static class ResponseBufferedOutputStream extends OutputStream {
  1920. private final OutputStream rawOut;
  1921. private OutputStream out;
  1922. ResponseBufferedOutputStream(OutputStream rawOut) {
  1923. this.rawOut = rawOut;
  1924. this.out = new ByteArrayOutputStream();
  1925. }
  1926. @Override
  1927. public void write(int b) throws IOException {
  1928. out.write(b);
  1929. }
  1930. @Override
  1931. public void write(byte b[]) throws IOException {
  1932. out.write(b);
  1933. }
  1934. @Override
  1935. public void write(byte b[], int off, int len) throws IOException {
  1936. out.write(b, off, len);
  1937. }
  1938. @Override
  1939. public void flush() throws IOException {
  1940. out.flush();
  1941. }
  1942. @Override
  1943. public void close() throws IOException {
  1944. out.close();
  1945. }
  1946. void stopBuffering() throws IOException {
  1947. if (out != rawOut) {
  1948. ((ByteArrayOutputStream) out).writeTo(rawOut);
  1949. out = rawOut;
  1950. }
  1951. }
  1952. }
  1953. }