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 74KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465
  1. /*
  2. * Copyright (C) 2008, 2020 Google Inc. and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.transport;
  11. import static java.util.Collections.unmodifiableMap;
  12. import static java.util.Objects.requireNonNull;
  13. import static org.eclipse.jgit.lib.Constants.R_TAGS;
  14. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_REF_IN_WANT;
  15. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_SERVER_OPTION;
  16. import static org.eclipse.jgit.transport.GitProtocolConstants.COMMAND_FETCH;
  17. import static org.eclipse.jgit.transport.GitProtocolConstants.COMMAND_LS_REFS;
  18. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_AGENT;
  19. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_ALLOW_REACHABLE_SHA1_IN_WANT;
  20. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_ALLOW_TIP_SHA1_IN_WANT;
  21. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_DEEPEN_RELATIVE;
  22. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_FILTER;
  23. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_INCLUDE_TAG;
  24. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_MULTI_ACK;
  25. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_MULTI_ACK_DETAILED;
  26. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_NO_DONE;
  27. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_NO_PROGRESS;
  28. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_OFS_DELTA;
  29. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SHALLOW;
  30. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SIDEBAND_ALL;
  31. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SIDE_BAND;
  32. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SIDE_BAND_64K;
  33. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_THIN_PACK;
  34. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_WAIT_FOR_DONE;
  35. import static org.eclipse.jgit.transport.GitProtocolConstants.VERSION_2_REQUEST;
  36. import static org.eclipse.jgit.util.RefMap.toRefMap;
  37. import java.io.ByteArrayOutputStream;
  38. import java.io.EOFException;
  39. import java.io.IOException;
  40. import java.io.InputStream;
  41. import java.io.OutputStream;
  42. import java.io.UncheckedIOException;
  43. import java.text.MessageFormat;
  44. import java.time.Duration;
  45. import java.time.Instant;
  46. import java.util.ArrayList;
  47. import java.util.Collection;
  48. import java.util.Collections;
  49. import java.util.HashSet;
  50. import java.util.List;
  51. import java.util.Map;
  52. import java.util.Objects;
  53. import java.util.Optional;
  54. import java.util.Set;
  55. import java.util.TreeMap;
  56. import java.util.function.Predicate;
  57. import java.util.stream.Collectors;
  58. import java.util.stream.Stream;
  59. import org.eclipse.jgit.annotations.NonNull;
  60. import org.eclipse.jgit.annotations.Nullable;
  61. import org.eclipse.jgit.errors.CorruptObjectException;
  62. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  63. import org.eclipse.jgit.errors.MissingObjectException;
  64. import org.eclipse.jgit.errors.PackProtocolException;
  65. import org.eclipse.jgit.internal.JGitText;
  66. import org.eclipse.jgit.internal.storage.pack.CachedPackUriProvider;
  67. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  68. import org.eclipse.jgit.internal.transport.parser.FirstWant;
  69. import org.eclipse.jgit.lib.Constants;
  70. import org.eclipse.jgit.lib.NullProgressMonitor;
  71. import org.eclipse.jgit.lib.ObjectId;
  72. import org.eclipse.jgit.lib.ObjectReader;
  73. import org.eclipse.jgit.lib.ProgressMonitor;
  74. import org.eclipse.jgit.lib.Ref;
  75. import org.eclipse.jgit.lib.RefDatabase;
  76. import org.eclipse.jgit.lib.Repository;
  77. import org.eclipse.jgit.revwalk.AsyncRevObjectQueue;
  78. import org.eclipse.jgit.revwalk.DepthWalk;
  79. import org.eclipse.jgit.revwalk.ObjectReachabilityChecker;
  80. import org.eclipse.jgit.revwalk.ObjectWalk;
  81. import org.eclipse.jgit.revwalk.ReachabilityChecker;
  82. import org.eclipse.jgit.revwalk.RevCommit;
  83. import org.eclipse.jgit.revwalk.RevFlag;
  84. import org.eclipse.jgit.revwalk.RevFlagSet;
  85. import org.eclipse.jgit.revwalk.RevObject;
  86. import org.eclipse.jgit.revwalk.RevTag;
  87. import org.eclipse.jgit.revwalk.RevWalk;
  88. import org.eclipse.jgit.revwalk.filter.CommitTimeRevFilter;
  89. import org.eclipse.jgit.storage.pack.PackConfig;
  90. import org.eclipse.jgit.storage.pack.PackStatistics;
  91. import org.eclipse.jgit.transport.GitProtocolConstants.MultiAck;
  92. import org.eclipse.jgit.transport.RefAdvertiser.PacketLineOutRefAdvertiser;
  93. import org.eclipse.jgit.transport.TransferConfig.ProtocolVersion;
  94. import org.eclipse.jgit.util.io.InterruptTimer;
  95. import org.eclipse.jgit.util.io.NullOutputStream;
  96. import org.eclipse.jgit.util.io.TimeoutInputStream;
  97. import org.eclipse.jgit.util.io.TimeoutOutputStream;
  98. /**
  99. * Implements the server side of a fetch connection, transmitting objects.
  100. */
  101. public class UploadPack {
  102. /** Policy the server uses to validate client requests */
  103. public enum RequestPolicy {
  104. /** Client may only ask for objects the server advertised a reference for. */
  105. ADVERTISED,
  106. /**
  107. * Client may ask for any commit reachable from a reference advertised by
  108. * the server.
  109. */
  110. REACHABLE_COMMIT,
  111. /**
  112. * Client may ask for objects that are the tip of any reference, even if not
  113. * advertised.
  114. * <p>
  115. * This may happen, for example, when a custom {@link RefFilter} is set.
  116. *
  117. * @since 3.1
  118. */
  119. TIP,
  120. /**
  121. * Client may ask for any commit reachable from any reference, even if that
  122. * reference wasn't advertised.
  123. *
  124. * @since 3.1
  125. */
  126. REACHABLE_COMMIT_TIP,
  127. /** Client may ask for any SHA-1 in the repository. */
  128. ANY;
  129. }
  130. /**
  131. * Validator for client requests.
  132. *
  133. * @since 3.1
  134. */
  135. public interface RequestValidator {
  136. /**
  137. * Check a list of client wants against the request policy.
  138. *
  139. * @param up
  140. * {@link UploadPack} instance.
  141. * @param wants
  142. * objects the client requested that were not advertised.
  143. *
  144. * @throws PackProtocolException
  145. * if one or more wants is not valid.
  146. * @throws IOException
  147. * if a low-level exception occurred.
  148. * @since 3.1
  149. */
  150. void checkWants(UploadPack up, List<ObjectId> wants)
  151. throws PackProtocolException, IOException;
  152. }
  153. /**
  154. * Data in the first line of a want-list, the line itself plus options.
  155. *
  156. * @deprecated Use {@link FirstWant} instead
  157. */
  158. @Deprecated
  159. public static class FirstLine {
  160. private final FirstWant firstWant;
  161. /**
  162. * @param line
  163. * line from the client.
  164. */
  165. public FirstLine(String line) {
  166. try {
  167. firstWant = FirstWant.fromLine(line);
  168. } catch (PackProtocolException e) {
  169. throw new UncheckedIOException(e);
  170. }
  171. }
  172. /** @return non-capabilities part of the line. */
  173. public String getLine() {
  174. return firstWant.getLine();
  175. }
  176. /** @return capabilities parsed from the line. */
  177. public Set<String> getOptions() {
  178. if (firstWant.getAgent() != null) {
  179. Set<String> caps = new HashSet<>(firstWant.getCapabilities());
  180. caps.add(OPTION_AGENT + '=' + firstWant.getAgent());
  181. return caps;
  182. }
  183. return firstWant.getCapabilities();
  184. }
  185. }
  186. /*
  187. * {@link java.util.function.Consumer} doesn't allow throwing checked
  188. * exceptions. Define our own to propagate IOExceptions.
  189. */
  190. @FunctionalInterface
  191. private static interface IOConsumer<R> {
  192. void accept(R t) throws IOException;
  193. }
  194. /** Database we read the objects from. */
  195. private final Repository db;
  196. /** Revision traversal support over {@link #db}. */
  197. private final RevWalk walk;
  198. /** Configuration to pass into the PackWriter. */
  199. private PackConfig packConfig;
  200. /** Configuration for various transfer options. */
  201. private TransferConfig transferConfig;
  202. /** Timeout in seconds to wait for client interaction. */
  203. private int timeout;
  204. /**
  205. * Is the client connection a bi-directional socket or pipe?
  206. * <p>
  207. * If true, this class assumes it can perform multiple read and write cycles
  208. * with the client over the input and output streams. This matches the
  209. * functionality available with a standard TCP/IP connection, or a local
  210. * operating system or in-memory pipe.
  211. * <p>
  212. * If false, this class runs in a read everything then output results mode,
  213. * making it suitable for single round-trip systems RPCs such as HTTP.
  214. */
  215. private boolean biDirectionalPipe = true;
  216. /** Timer to manage {@link #timeout}. */
  217. private InterruptTimer timer;
  218. /**
  219. * Whether the client requested to use protocol V2 through a side
  220. * channel (such as the Git-Protocol HTTP header).
  221. */
  222. private boolean clientRequestedV2;
  223. private InputStream rawIn;
  224. private ResponseBufferedOutputStream rawOut;
  225. private PacketLineIn pckIn;
  226. private OutputStream msgOut = NullOutputStream.INSTANCE;
  227. private ErrorWriter errOut = new PackProtocolErrorWriter();
  228. /**
  229. * Refs eligible for advertising to the client, set using
  230. * {@link #setAdvertisedRefs}.
  231. */
  232. private Map<String, Ref> refs;
  233. /** Hook used while processing Git protocol v2 requests. */
  234. private ProtocolV2Hook protocolV2Hook = ProtocolV2Hook.DEFAULT;
  235. /** Hook used while advertising the refs to the client. */
  236. private AdvertiseRefsHook advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  237. /** Whether the {@link #advertiseRefsHook} has been invoked. */
  238. private boolean advertiseRefsHookCalled;
  239. /** Filter used while advertising the refs to the client. */
  240. private RefFilter refFilter = RefFilter.DEFAULT;
  241. /** Hook handling the various upload phases. */
  242. private PreUploadHook preUploadHook = PreUploadHook.NULL;
  243. /** Hook for taking post upload actions. */
  244. private PostUploadHook postUploadHook = PostUploadHook.NULL;
  245. /** Caller user agent */
  246. String userAgent;
  247. /** Raw ObjectIds the client has asked for, before validating them. */
  248. private Set<ObjectId> wantIds = new HashSet<>();
  249. /** Objects the client wants to obtain. */
  250. private final Set<RevObject> wantAll = new HashSet<>();
  251. /** Objects on both sides, these don't have to be sent. */
  252. private final Set<RevObject> commonBase = new HashSet<>();
  253. /** Commit time of the oldest common commit, in seconds. */
  254. private int oldestTime;
  255. /** null if {@link #commonBase} should be examined again. */
  256. private Boolean okToGiveUp;
  257. private boolean sentReady;
  258. /** Objects we sent in our advertisement list. */
  259. private Set<ObjectId> advertised;
  260. /** Marked on objects the client has asked us to give them. */
  261. private final RevFlag WANT;
  262. /** Marked on objects both we and the client have. */
  263. private final RevFlag PEER_HAS;
  264. /** Marked on objects in {@link #commonBase}. */
  265. private final RevFlag COMMON;
  266. /** Objects where we found a path from the want list to a common base. */
  267. private final RevFlag SATISFIED;
  268. private final RevFlagSet SAVE;
  269. private RequestValidator requestValidator = new AdvertisedRequestValidator();
  270. private MultiAck multiAck = MultiAck.OFF;
  271. private boolean noDone;
  272. private PackStatistics statistics;
  273. /**
  274. * Request this instance is handling.
  275. *
  276. * We need to keep a reference to it for {@link PreUploadHook pre upload
  277. * hooks}. They receive a reference this instance and invoke methods like
  278. * getDepth() to get information about the request.
  279. */
  280. private FetchRequest currentRequest;
  281. private CachedPackUriProvider cachedPackUriProvider;
  282. /**
  283. * Create a new pack upload for an open repository.
  284. *
  285. * @param copyFrom
  286. * the source repository.
  287. */
  288. public UploadPack(Repository copyFrom) {
  289. db = copyFrom;
  290. walk = new RevWalk(db);
  291. walk.setRetainBody(false);
  292. WANT = walk.newFlag("WANT"); //$NON-NLS-1$
  293. PEER_HAS = walk.newFlag("PEER_HAS"); //$NON-NLS-1$
  294. COMMON = walk.newFlag("COMMON"); //$NON-NLS-1$
  295. SATISFIED = walk.newFlag("SATISFIED"); //$NON-NLS-1$
  296. walk.carry(PEER_HAS);
  297. SAVE = new RevFlagSet();
  298. SAVE.add(WANT);
  299. SAVE.add(PEER_HAS);
  300. SAVE.add(COMMON);
  301. SAVE.add(SATISFIED);
  302. setTransferConfig(null);
  303. }
  304. /**
  305. * Get the repository this upload is reading from.
  306. *
  307. * @return the repository this upload is reading from.
  308. */
  309. public final Repository getRepository() {
  310. return db;
  311. }
  312. /**
  313. * Get the RevWalk instance used by this connection.
  314. *
  315. * @return the RevWalk instance used by this connection.
  316. */
  317. public final RevWalk getRevWalk() {
  318. return walk;
  319. }
  320. /**
  321. * Get refs which were advertised to the client.
  322. *
  323. * @return all refs which were advertised to the client. Only valid during
  324. * the negotiation phase. Will return {@code null} if
  325. * {@link #setAdvertisedRefs(Map)} has not been called yet or if
  326. * {@code #sendPack()} has been called.
  327. */
  328. public final Map<String, Ref> getAdvertisedRefs() {
  329. return refs;
  330. }
  331. /**
  332. * Set the refs advertised by this UploadPack.
  333. * <p>
  334. * Intended to be called from a
  335. * {@link org.eclipse.jgit.transport.PreUploadHook}.
  336. *
  337. * @param allRefs
  338. * explicit set of references to claim as advertised by this
  339. * UploadPack instance. This overrides any references that may
  340. * exist in the source repository. The map is passed to the
  341. * configured {@link #getRefFilter()}. If null, assumes all refs
  342. * were advertised.
  343. */
  344. public void setAdvertisedRefs(@Nullable Map<String, Ref> allRefs) {
  345. if (allRefs != null)
  346. refs = allRefs;
  347. else
  348. refs = db.getAllRefs();
  349. if (refFilter == RefFilter.DEFAULT)
  350. refs = transferConfig.getRefFilter().filter(refs);
  351. else
  352. refs = refFilter.filter(refs);
  353. }
  354. /**
  355. * Get timeout (in seconds) before aborting an IO operation.
  356. *
  357. * @return timeout (in seconds) before aborting an IO operation.
  358. */
  359. public int getTimeout() {
  360. return timeout;
  361. }
  362. /**
  363. * Set the timeout before willing to abort an IO call.
  364. *
  365. * @param seconds
  366. * number of seconds to wait (with no data transfer occurring)
  367. * before aborting an IO read or write operation with the
  368. * connected client.
  369. */
  370. public void setTimeout(int seconds) {
  371. timeout = seconds;
  372. }
  373. /**
  374. * Whether this class expects a bi-directional pipe opened between the
  375. * client and itself.
  376. *
  377. * @return true if this class expects a bi-directional pipe opened between
  378. * the client and itself. The default is true.
  379. */
  380. public boolean isBiDirectionalPipe() {
  381. return biDirectionalPipe;
  382. }
  383. /**
  384. * Set whether this class will assume the socket is a fully bidirectional
  385. * pipe between the two peers
  386. *
  387. * @param twoWay
  388. * if true, this class will assume the socket is a fully
  389. * bidirectional pipe between the two peers and takes advantage
  390. * of that by first transmitting the known refs, then waiting to
  391. * read commands. If false, this class assumes it must read the
  392. * commands before writing output and does not perform the
  393. * initial advertising.
  394. */
  395. public void setBiDirectionalPipe(boolean twoWay) {
  396. biDirectionalPipe = twoWay;
  397. }
  398. /**
  399. * Get policy used by the service to validate client requests
  400. *
  401. * @return policy used by the service to validate client requests, or null
  402. * for a custom request validator.
  403. */
  404. public RequestPolicy getRequestPolicy() {
  405. if (requestValidator instanceof AdvertisedRequestValidator)
  406. return RequestPolicy.ADVERTISED;
  407. if (requestValidator instanceof ReachableCommitRequestValidator)
  408. return RequestPolicy.REACHABLE_COMMIT;
  409. if (requestValidator instanceof TipRequestValidator)
  410. return RequestPolicy.TIP;
  411. if (requestValidator instanceof ReachableCommitTipRequestValidator)
  412. return RequestPolicy.REACHABLE_COMMIT_TIP;
  413. if (requestValidator instanceof AnyRequestValidator)
  414. return RequestPolicy.ANY;
  415. return null;
  416. }
  417. /**
  418. * Set the policy used to enforce validation of a client's want list.
  419. *
  420. * @param policy
  421. * the policy used to enforce validation of a client's want list.
  422. * By default the policy is
  423. * {@link org.eclipse.jgit.transport.UploadPack.RequestPolicy#ADVERTISED},
  424. * which is the Git default requiring clients to only ask for an
  425. * object that a reference directly points to. This may be
  426. * relaxed to
  427. * {@link org.eclipse.jgit.transport.UploadPack.RequestPolicy#REACHABLE_COMMIT}
  428. * or
  429. * {@link org.eclipse.jgit.transport.UploadPack.RequestPolicy#REACHABLE_COMMIT_TIP}
  430. * when callers have {@link #setBiDirectionalPipe(boolean)} set
  431. * to false. Overrides any policy specified in a
  432. * {@link org.eclipse.jgit.transport.TransferConfig}.
  433. */
  434. public void setRequestPolicy(RequestPolicy policy) {
  435. switch (policy) {
  436. case ADVERTISED:
  437. default:
  438. requestValidator = new AdvertisedRequestValidator();
  439. break;
  440. case REACHABLE_COMMIT:
  441. requestValidator = new ReachableCommitRequestValidator();
  442. break;
  443. case TIP:
  444. requestValidator = new TipRequestValidator();
  445. break;
  446. case REACHABLE_COMMIT_TIP:
  447. requestValidator = new ReachableCommitTipRequestValidator();
  448. break;
  449. case ANY:
  450. requestValidator = new AnyRequestValidator();
  451. break;
  452. }
  453. }
  454. /**
  455. * Set custom validator for client want list.
  456. *
  457. * @param validator
  458. * custom validator for client want list.
  459. * @since 3.1
  460. */
  461. public void setRequestValidator(@Nullable RequestValidator validator) {
  462. requestValidator = validator != null ? validator
  463. : new AdvertisedRequestValidator();
  464. }
  465. /**
  466. * Get the hook used while advertising the refs to the client.
  467. *
  468. * @return the hook used while advertising the refs to the client.
  469. */
  470. public AdvertiseRefsHook getAdvertiseRefsHook() {
  471. return advertiseRefsHook;
  472. }
  473. /**
  474. * Get the filter used while advertising the refs to the client.
  475. *
  476. * @return the filter used while advertising the refs to the client.
  477. */
  478. public RefFilter getRefFilter() {
  479. return refFilter;
  480. }
  481. /**
  482. * Set the hook used while advertising the refs to the client.
  483. * <p>
  484. * If the {@link org.eclipse.jgit.transport.AdvertiseRefsHook} chooses to
  485. * call {@link #setAdvertisedRefs(Map)}, only refs set by this hook
  486. * <em>and</em> selected by the {@link org.eclipse.jgit.transport.RefFilter}
  487. * will be shown to the client.
  488. *
  489. * @param advertiseRefsHook
  490. * the hook; may be null to show all refs.
  491. */
  492. public void setAdvertiseRefsHook(
  493. @Nullable AdvertiseRefsHook advertiseRefsHook) {
  494. this.advertiseRefsHook = advertiseRefsHook != null ? advertiseRefsHook
  495. : AdvertiseRefsHook.DEFAULT;
  496. }
  497. /**
  498. * Set the protocol V2 hook.
  499. *
  500. * @param hook
  501. * the hook; if null no special actions are taken.
  502. * @since 5.1
  503. */
  504. public void setProtocolV2Hook(@Nullable ProtocolV2Hook hook) {
  505. this.protocolV2Hook = hook != null ? hook : ProtocolV2Hook.DEFAULT;
  506. }
  507. /**
  508. * Get the currently installed protocol v2 hook.
  509. *
  510. * @return the hook or a default implementation if none installed.
  511. *
  512. * @since 5.5
  513. */
  514. public ProtocolV2Hook getProtocolV2Hook() {
  515. return this.protocolV2Hook != null ? this.protocolV2Hook
  516. : ProtocolV2Hook.DEFAULT;
  517. }
  518. /**
  519. * Set the filter used while advertising the refs to the client.
  520. * <p>
  521. * Only refs allowed by this filter will be sent to the client. The filter
  522. * is run against the refs specified by the
  523. * {@link org.eclipse.jgit.transport.AdvertiseRefsHook} (if applicable). If
  524. * null or not set, uses the filter implied by the
  525. * {@link org.eclipse.jgit.transport.TransferConfig}.
  526. *
  527. * @param refFilter
  528. * the filter; may be null to show all refs.
  529. */
  530. public void setRefFilter(@Nullable RefFilter refFilter) {
  531. this.refFilter = refFilter != null ? refFilter : RefFilter.DEFAULT;
  532. }
  533. /**
  534. * Get the configured pre upload hook.
  535. *
  536. * @return the configured pre upload hook.
  537. */
  538. public PreUploadHook getPreUploadHook() {
  539. return preUploadHook;
  540. }
  541. /**
  542. * Set the hook that controls how this instance will behave.
  543. *
  544. * @param hook
  545. * the hook; if null no special actions are taken.
  546. */
  547. public void setPreUploadHook(@Nullable PreUploadHook hook) {
  548. preUploadHook = hook != null ? hook : PreUploadHook.NULL;
  549. }
  550. /**
  551. * Get the configured post upload hook.
  552. *
  553. * @return the configured post upload hook.
  554. * @since 4.1
  555. */
  556. public PostUploadHook getPostUploadHook() {
  557. return postUploadHook;
  558. }
  559. /**
  560. * Set the hook for post upload actions (logging, repacking).
  561. *
  562. * @param hook
  563. * the hook; if null no special actions are taken.
  564. * @since 4.1
  565. */
  566. public void setPostUploadHook(@Nullable PostUploadHook hook) {
  567. postUploadHook = hook != null ? hook : PostUploadHook.NULL;
  568. }
  569. /**
  570. * Set the configuration used by the pack generator.
  571. *
  572. * @param pc
  573. * configuration controlling packing parameters. If null the
  574. * source repository's settings will be used.
  575. */
  576. public void setPackConfig(@Nullable PackConfig pc) {
  577. this.packConfig = pc;
  578. }
  579. /**
  580. * Set configuration controlling transfer options.
  581. *
  582. * @param tc
  583. * configuration controlling transfer options. If null the source
  584. * repository's settings will be used.
  585. * @since 3.1
  586. */
  587. public void setTransferConfig(@Nullable TransferConfig tc) {
  588. this.transferConfig = tc != null ? tc : new TransferConfig(db);
  589. if (transferConfig.isAllowTipSha1InWant()) {
  590. setRequestPolicy(transferConfig.isAllowReachableSha1InWant()
  591. ? RequestPolicy.REACHABLE_COMMIT_TIP : RequestPolicy.TIP);
  592. } else {
  593. setRequestPolicy(transferConfig.isAllowReachableSha1InWant()
  594. ? RequestPolicy.REACHABLE_COMMIT : RequestPolicy.ADVERTISED);
  595. }
  596. }
  597. /**
  598. * Check whether the client expects a side-band stream.
  599. *
  600. * @return true if the client has advertised a side-band capability, false
  601. * otherwise.
  602. * @throws org.eclipse.jgit.transport.RequestNotYetReadException
  603. * if the client's request has not yet been read from the wire, so
  604. * we do not know if they expect side-band. Note that the client
  605. * may have already written the request, it just has not been
  606. * read.
  607. */
  608. public boolean isSideBand() throws RequestNotYetReadException {
  609. if (currentRequest == null) {
  610. throw new RequestNotYetReadException();
  611. }
  612. Set<String> caps = currentRequest.getClientCapabilities();
  613. return caps.contains(OPTION_SIDE_BAND)
  614. || caps.contains(OPTION_SIDE_BAND_64K);
  615. }
  616. /**
  617. * Set the Extra Parameters provided by the client.
  618. *
  619. * <p>These are parameters passed by the client through a side channel
  620. * such as the Git-Protocol HTTP header, to allow a client to request
  621. * a newer response format while remaining compatible with older servers
  622. * that do not understand different request formats.
  623. *
  624. * @param params
  625. * parameters supplied by the client, split at colons or NUL
  626. * bytes.
  627. * @since 5.0
  628. */
  629. public void setExtraParameters(Collection<String> params) {
  630. this.clientRequestedV2 = params.contains(VERSION_2_REQUEST);
  631. }
  632. /**
  633. * @param p provider of URIs corresponding to cached packs (to support
  634. * the packfile URIs feature)
  635. * @since 5.5
  636. */
  637. public void setCachedPackUriProvider(@Nullable CachedPackUriProvider p) {
  638. cachedPackUriProvider = p;
  639. }
  640. private boolean useProtocolV2() {
  641. return (transferConfig.protocolVersion == null
  642. || ProtocolVersion.V2.equals(transferConfig.protocolVersion))
  643. && clientRequestedV2;
  644. }
  645. /**
  646. * Execute the upload task on the socket.
  647. *
  648. * <p>
  649. * Same as {@link #uploadWithExceptionPropagation} except that the thrown
  650. * exceptions are handled in the method, and the error messages are sent to
  651. * the clients.
  652. *
  653. * <p>
  654. * Call this method if the caller does not have an error handling mechanism.
  655. * Call {@link #uploadWithExceptionPropagation} if the caller wants to have
  656. * its own error handling mechanism.
  657. *
  658. * @param input
  659. * @param output
  660. * @param messages
  661. * @throws java.io.IOException
  662. */
  663. public void upload(InputStream input, OutputStream output,
  664. @Nullable OutputStream messages) throws IOException {
  665. try {
  666. uploadWithExceptionPropagation(input, output, messages);
  667. } catch (ServiceMayNotContinueException err) {
  668. if (!err.isOutput() && err.getMessage() != null) {
  669. try {
  670. errOut.writeError(err.getMessage());
  671. } catch (IOException e) {
  672. err.addSuppressed(e);
  673. throw err;
  674. }
  675. err.setOutput();
  676. }
  677. throw err;
  678. } catch (IOException | RuntimeException | Error err) {
  679. if (rawOut != null) {
  680. String msg = err instanceof PackProtocolException
  681. ? err.getMessage()
  682. : JGitText.get().internalServerError;
  683. try {
  684. errOut.writeError(msg);
  685. } catch (IOException e) {
  686. err.addSuppressed(e);
  687. throw err;
  688. }
  689. throw new UploadPackInternalServerErrorException(err);
  690. }
  691. throw err;
  692. }
  693. }
  694. /**
  695. * Execute the upload task on the socket.
  696. *
  697. * <p>
  698. * If the client passed extra parameters (e.g., "version=2") through a side
  699. * channel, the caller must call setExtraParameters first to supply them.
  700. *
  701. * @param input
  702. * raw input to read client commands from. Caller must ensure the
  703. * input is buffered, otherwise read performance may suffer.
  704. * @param output
  705. * response back to the Git network client, to write the pack
  706. * data onto. Caller must ensure the output is buffered,
  707. * otherwise write performance may suffer.
  708. * @param messages
  709. * secondary "notice" channel to send additional messages out
  710. * through. When run over SSH this should be tied back to the
  711. * standard error channel of the command execution. For most
  712. * other network connections this should be null.
  713. * @throws ServiceMayNotContinueException
  714. * thrown if one of the hooks throws this.
  715. * @throws IOException
  716. * thrown if the server or the client I/O fails, or there's an
  717. * internal server error.
  718. * @since 5.6
  719. */
  720. public void uploadWithExceptionPropagation(InputStream input,
  721. OutputStream output, @Nullable OutputStream messages)
  722. throws ServiceMayNotContinueException, IOException {
  723. try {
  724. rawIn = input;
  725. if (messages != null) {
  726. msgOut = messages;
  727. }
  728. if (timeout > 0) {
  729. final Thread caller = Thread.currentThread();
  730. timer = new InterruptTimer(caller.getName() + "-Timer"); //$NON-NLS-1$
  731. TimeoutInputStream i = new TimeoutInputStream(rawIn, timer);
  732. @SuppressWarnings("resource")
  733. TimeoutOutputStream o = new TimeoutOutputStream(output, timer);
  734. i.setTimeout(timeout * 1000);
  735. o.setTimeout(timeout * 1000);
  736. rawIn = i;
  737. output = o;
  738. }
  739. rawOut = new ResponseBufferedOutputStream(output);
  740. if (biDirectionalPipe) {
  741. rawOut.stopBuffering();
  742. }
  743. pckIn = new PacketLineIn(rawIn);
  744. PacketLineOut pckOut = new PacketLineOut(rawOut);
  745. if (useProtocolV2()) {
  746. serviceV2(pckOut);
  747. } else {
  748. service(pckOut);
  749. }
  750. } finally {
  751. msgOut = NullOutputStream.INSTANCE;
  752. walk.close();
  753. if (timer != null) {
  754. try {
  755. timer.terminate();
  756. } finally {
  757. timer = null;
  758. }
  759. }
  760. }
  761. }
  762. /**
  763. * Get the PackWriter's statistics if a pack was sent to the client.
  764. *
  765. * @return statistics about pack output, if a pack was sent. Null if no pack
  766. * was sent, such as during the negotiation phase of a smart HTTP
  767. * connection, or if the client was already up-to-date.
  768. * @since 4.1
  769. */
  770. public PackStatistics getStatistics() {
  771. return statistics;
  772. }
  773. private Map<String, Ref> getAdvertisedOrDefaultRefs() throws IOException {
  774. if (refs != null) {
  775. return refs;
  776. }
  777. if (!advertiseRefsHookCalled) {
  778. advertiseRefsHook.advertiseRefs(this);
  779. advertiseRefsHookCalled = true;
  780. }
  781. if (refs == null) {
  782. // Fall back to all refs.
  783. setAdvertisedRefs(
  784. db.getRefDatabase().getRefs().stream()
  785. .collect(toRefMap((a, b) -> b)));
  786. }
  787. return refs;
  788. }
  789. private Map<String, Ref> getFilteredRefs(Collection<String> refPrefixes)
  790. throws IOException {
  791. if (refPrefixes.isEmpty()) {
  792. return getAdvertisedOrDefaultRefs();
  793. }
  794. if (refs == null && !advertiseRefsHookCalled) {
  795. advertiseRefsHook.advertiseRefs(this);
  796. advertiseRefsHookCalled = true;
  797. }
  798. if (refs == null) {
  799. // Fast path: the advertised refs hook did not set advertised refs.
  800. String[] prefixes = refPrefixes.toArray(new String[0]);
  801. Map<String, Ref> rs =
  802. db.getRefDatabase().getRefsByPrefix(prefixes).stream()
  803. .collect(toRefMap((a, b) -> b));
  804. if (refFilter != RefFilter.DEFAULT) {
  805. return refFilter.filter(rs);
  806. }
  807. return transferConfig.getRefFilter().filter(rs);
  808. }
  809. // Slow path: filter the refs provided by the advertised refs hook.
  810. // refFilter has already been applied to refs.
  811. return refs.values().stream()
  812. .filter(ref -> refPrefixes.stream()
  813. .anyMatch(ref.getName()::startsWith))
  814. .collect(toRefMap((a, b) -> b));
  815. }
  816. /**
  817. * Returns the specified references.
  818. * <p>
  819. * This produces an immutable map containing whatever subset of the
  820. * refs named by the caller are present in the supplied {@code refs}
  821. * map.
  822. *
  823. * @param refs
  824. * Map to search for refs to return.
  825. * @param names
  826. * which refs to search for in {@code refs}.
  827. * @return the requested Refs, omitting any that are null or missing.
  828. */
  829. @NonNull
  830. private static Map<String, Ref> mapRefs(
  831. Map<String, Ref> refs, List<String> names) {
  832. return unmodifiableMap(
  833. names.stream()
  834. .map(refs::get)
  835. .filter(Objects::nonNull)
  836. .collect(toRefMap((a, b) -> b)));
  837. }
  838. /**
  839. * Read refs on behalf of the client.
  840. * <p>
  841. * This checks whether the refs are present in the ref advertisement
  842. * since otherwise the client might not be supposed to be able to
  843. * read them.
  844. *
  845. * @param names
  846. * unabbreviated names of references.
  847. * @return the requested Refs, omitting any that are not visible or
  848. * do not exist.
  849. * @throws java.io.IOException
  850. * on failure to read a ref or check it for visibility.
  851. */
  852. @NonNull
  853. private Map<String, Ref> exactRefs(List<String> names) throws IOException {
  854. if (refs != null) {
  855. return mapRefs(refs, names);
  856. }
  857. if (!advertiseRefsHookCalled) {
  858. advertiseRefsHook.advertiseRefs(this);
  859. advertiseRefsHookCalled = true;
  860. }
  861. if (refs == null &&
  862. refFilter == RefFilter.DEFAULT &&
  863. transferConfig.hasDefaultRefFilter()) {
  864. // Fast path: no ref filtering is needed.
  865. String[] ns = names.toArray(new String[0]);
  866. return unmodifiableMap(db.getRefDatabase().exactRef(ns));
  867. }
  868. return mapRefs(getAdvertisedOrDefaultRefs(), names);
  869. }
  870. /**
  871. * Find a ref in the usual search path on behalf of the client.
  872. * <p>
  873. * This checks that the ref is present in the ref advertisement since
  874. * otherwise the client might not be supposed to be able to read it.
  875. *
  876. * @param name
  877. * short name of the ref to find, e.g. "master" to find
  878. * "refs/heads/master".
  879. * @return the requested Ref, or {@code null} if it is not visible or
  880. * does not exist.
  881. * @throws java.io.IOException
  882. * on failure to read the ref or check it for visibility.
  883. */
  884. @Nullable
  885. private Ref findRef(String name) throws IOException {
  886. if (refs != null) {
  887. return RefDatabase.findRef(refs, name);
  888. }
  889. if (!advertiseRefsHookCalled) {
  890. advertiseRefsHook.advertiseRefs(this);
  891. advertiseRefsHookCalled = true;
  892. }
  893. if (refs == null &&
  894. refFilter == RefFilter.DEFAULT &&
  895. transferConfig.hasDefaultRefFilter()) {
  896. // Fast path: no ref filtering is needed.
  897. return db.getRefDatabase().findRef(name);
  898. }
  899. return RefDatabase.findRef(getAdvertisedOrDefaultRefs(), name);
  900. }
  901. private void service(PacketLineOut pckOut) throws IOException {
  902. boolean sendPack = false;
  903. // If it's a non-bidi request, we need to read the entire request before
  904. // writing a response. Buffer the response until then.
  905. PackStatistics.Accumulator accumulator = new PackStatistics.Accumulator();
  906. List<ObjectId> unshallowCommits = new ArrayList<>();
  907. FetchRequest req;
  908. try {
  909. if (biDirectionalPipe)
  910. sendAdvertisedRefs(new PacketLineOutRefAdvertiser(pckOut));
  911. else if (requestValidator instanceof AnyRequestValidator)
  912. advertised = Collections.emptySet();
  913. else
  914. advertised = refIdSet(getAdvertisedOrDefaultRefs().values());
  915. Instant negotiateStart = Instant.now();
  916. accumulator.advertised = advertised.size();
  917. ProtocolV0Parser parser = new ProtocolV0Parser(transferConfig);
  918. req = parser.recvWants(pckIn);
  919. currentRequest = req;
  920. wantIds = req.getWantIds();
  921. if (req.getWantIds().isEmpty()) {
  922. preUploadHook.onBeginNegotiateRound(this, req.getWantIds(), 0);
  923. preUploadHook.onEndNegotiateRound(this, req.getWantIds(), 0, 0,
  924. false);
  925. return;
  926. }
  927. accumulator.wants = req.getWantIds().size();
  928. if (req.getClientCapabilities().contains(OPTION_MULTI_ACK_DETAILED)) {
  929. multiAck = MultiAck.DETAILED;
  930. noDone = req.getClientCapabilities().contains(OPTION_NO_DONE);
  931. } else if (req.getClientCapabilities().contains(OPTION_MULTI_ACK))
  932. multiAck = MultiAck.CONTINUE;
  933. else
  934. multiAck = MultiAck.OFF;
  935. if (!req.getClientShallowCommits().isEmpty()) {
  936. verifyClientShallow(req.getClientShallowCommits());
  937. }
  938. if (req.getDepth() != 0 || req.getDeepenSince() != 0) {
  939. computeShallowsAndUnshallows(req, shallow -> {
  940. pckOut.writeString("shallow " + shallow.name() + '\n'); //$NON-NLS-1$
  941. }, unshallow -> {
  942. pckOut.writeString("unshallow " + unshallow.name() + '\n'); //$NON-NLS-1$
  943. unshallowCommits.add(unshallow);
  944. }, Collections.emptyList());
  945. pckOut.end();
  946. }
  947. if (!req.getClientShallowCommits().isEmpty())
  948. walk.assumeShallow(req.getClientShallowCommits());
  949. sendPack = negotiate(req, accumulator, pckOut);
  950. accumulator.timeNegotiating = Duration
  951. .between(negotiateStart, Instant.now()).toMillis();
  952. if (sendPack && !biDirectionalPipe) {
  953. // Ensure the request was fully consumed. Any remaining input must
  954. // be a protocol error. If we aren't at EOF the implementation is broken.
  955. int eof = rawIn.read();
  956. if (0 <= eof) {
  957. sendPack = false;
  958. throw new CorruptObjectException(MessageFormat.format(
  959. JGitText.get().expectedEOFReceived,
  960. "\\x" + Integer.toHexString(eof))); //$NON-NLS-1$
  961. }
  962. }
  963. } finally {
  964. if (!sendPack && !biDirectionalPipe) {
  965. while (0 < rawIn.skip(2048) || 0 <= rawIn.read()) {
  966. // Discard until EOF.
  967. }
  968. }
  969. rawOut.stopBuffering();
  970. }
  971. if (sendPack) {
  972. sendPack(accumulator, req, refs == null ? null : refs.values(),
  973. unshallowCommits, Collections.emptyList(), pckOut);
  974. }
  975. }
  976. private void lsRefsV2(PacketLineOut pckOut) throws IOException {
  977. ProtocolV2Parser parser = new ProtocolV2Parser(transferConfig);
  978. LsRefsV2Request req = parser.parseLsRefsRequest(pckIn);
  979. protocolV2Hook.onLsRefs(req);
  980. rawOut.stopBuffering();
  981. PacketLineOutRefAdvertiser adv = new PacketLineOutRefAdvertiser(pckOut);
  982. adv.setUseProtocolV2(true);
  983. if (req.getPeel()) {
  984. adv.setDerefTags(true);
  985. }
  986. Map<String, Ref> refsToSend = getFilteredRefs(req.getRefPrefixes());
  987. if (req.getSymrefs()) {
  988. findSymrefs(adv, refsToSend);
  989. }
  990. adv.send(refsToSend.values());
  991. adv.end();
  992. }
  993. // Resolves ref names from the request's want-ref lines to
  994. // object ids, throwing PackProtocolException if any are missing.
  995. private Map<String, ObjectId> wantedRefs(FetchV2Request req)
  996. throws IOException {
  997. Map<String, ObjectId> result = new TreeMap<>();
  998. List<String> wanted = req.getWantedRefs();
  999. Map<String, Ref> resolved = exactRefs(wanted);
  1000. for (String refName : wanted) {
  1001. Ref ref = resolved.get(refName);
  1002. if (ref == null) {
  1003. throw new PackProtocolException(MessageFormat
  1004. .format(JGitText.get().invalidRefName, refName));
  1005. }
  1006. ObjectId oid = ref.getObjectId();
  1007. if (oid == null) {
  1008. throw new PackProtocolException(MessageFormat
  1009. .format(JGitText.get().invalidRefName, refName));
  1010. }
  1011. result.put(refName, oid);
  1012. }
  1013. return result;
  1014. }
  1015. private void fetchV2(PacketLineOut pckOut) throws IOException {
  1016. // Depending on the requestValidator, #processHaveLines may
  1017. // require that advertised be set. Set it only in the required
  1018. // circumstances (to avoid a full ref lookup in the case that
  1019. // we don't need it).
  1020. if (requestValidator instanceof TipRequestValidator ||
  1021. requestValidator instanceof ReachableCommitTipRequestValidator ||
  1022. requestValidator instanceof AnyRequestValidator) {
  1023. advertised = Collections.emptySet();
  1024. } else {
  1025. advertised = refIdSet(getAdvertisedOrDefaultRefs().values());
  1026. }
  1027. PackStatistics.Accumulator accumulator = new PackStatistics.Accumulator();
  1028. Instant negotiateStart = Instant.now();
  1029. ProtocolV2Parser parser = new ProtocolV2Parser(transferConfig);
  1030. FetchV2Request req = parser.parseFetchRequest(pckIn);
  1031. currentRequest = req;
  1032. rawOut.stopBuffering();
  1033. protocolV2Hook.onFetch(req);
  1034. if (req.getSidebandAll()) {
  1035. pckOut.setUsingSideband(true);
  1036. }
  1037. // TODO(ifrade): Refactor to pass around the Request object, instead of
  1038. // copying data back to class fields
  1039. List<ObjectId> deepenNots = new ArrayList<>();
  1040. for (String s : req.getDeepenNotRefs()) {
  1041. Ref ref = findRef(s);
  1042. if (ref == null) {
  1043. throw new PackProtocolException(MessageFormat
  1044. .format(JGitText.get().invalidRefName, s));
  1045. }
  1046. deepenNots.add(ref.getObjectId());
  1047. }
  1048. Map<String, ObjectId> wantedRefs = wantedRefs(req);
  1049. // TODO(ifrade): Avoid mutating the parsed request.
  1050. req.getWantIds().addAll(wantedRefs.values());
  1051. wantIds = req.getWantIds();
  1052. boolean sectionSent = false;
  1053. boolean mayHaveShallow = req.getDepth() != 0
  1054. || req.getDeepenSince() != 0
  1055. || !req.getDeepenNotRefs().isEmpty();
  1056. List<ObjectId> shallowCommits = new ArrayList<>();
  1057. List<ObjectId> unshallowCommits = new ArrayList<>();
  1058. if (!req.getClientShallowCommits().isEmpty()) {
  1059. verifyClientShallow(req.getClientShallowCommits());
  1060. }
  1061. if (mayHaveShallow) {
  1062. computeShallowsAndUnshallows(req,
  1063. shallowCommit -> shallowCommits.add(shallowCommit),
  1064. unshallowCommit -> unshallowCommits.add(unshallowCommit),
  1065. deepenNots);
  1066. }
  1067. if (!req.getClientShallowCommits().isEmpty())
  1068. walk.assumeShallow(req.getClientShallowCommits());
  1069. if (req.wasDoneReceived()) {
  1070. processHaveLines(
  1071. req.getPeerHas(), ObjectId.zeroId(),
  1072. new PacketLineOut(NullOutputStream.INSTANCE, false),
  1073. accumulator, req.wasWaitForDoneReceived() ? Option.WAIT_FOR_DONE : Option.NONE);
  1074. } else {
  1075. pckOut.writeString(
  1076. GitProtocolConstants.SECTION_ACKNOWLEDGMENTS + '\n');
  1077. for (ObjectId id : req.getPeerHas()) {
  1078. if (walk.getObjectReader().has(id)) {
  1079. pckOut.writeString("ACK " + id.getName() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1080. }
  1081. }
  1082. processHaveLines(req.getPeerHas(), ObjectId.zeroId(),
  1083. new PacketLineOut(NullOutputStream.INSTANCE, false),
  1084. accumulator, Option.NONE);
  1085. if (!req.wasWaitForDoneReceived() && okToGiveUp()) {
  1086. pckOut.writeString("ready\n"); //$NON-NLS-1$
  1087. } else if (commonBase.isEmpty()) {
  1088. pckOut.writeString("NAK\n"); //$NON-NLS-1$
  1089. }
  1090. sectionSent = true;
  1091. }
  1092. if (req.wasDoneReceived() || (!req.wasWaitForDoneReceived() && okToGiveUp())) {
  1093. if (mayHaveShallow) {
  1094. if (sectionSent)
  1095. pckOut.writeDelim();
  1096. pckOut.writeString("shallow-info\n"); //$NON-NLS-1$
  1097. for (ObjectId o : shallowCommits) {
  1098. pckOut.writeString("shallow " + o.getName() + '\n'); //$NON-NLS-1$
  1099. }
  1100. for (ObjectId o : unshallowCommits) {
  1101. pckOut.writeString("unshallow " + o.getName() + '\n'); //$NON-NLS-1$
  1102. }
  1103. sectionSent = true;
  1104. }
  1105. if (!wantedRefs.isEmpty()) {
  1106. if (sectionSent) {
  1107. pckOut.writeDelim();
  1108. }
  1109. pckOut.writeString("wanted-refs\n"); //$NON-NLS-1$
  1110. for (Map.Entry<String, ObjectId> entry :
  1111. wantedRefs.entrySet()) {
  1112. pckOut.writeString(entry.getValue().getName() + ' ' +
  1113. entry.getKey() + '\n');
  1114. }
  1115. sectionSent = true;
  1116. }
  1117. if (sectionSent)
  1118. pckOut.writeDelim();
  1119. if (!pckOut.isUsingSideband()) {
  1120. // sendPack will write "packfile\n" for us if sideband-all is used.
  1121. // But sideband-all is not used, so we have to write it ourselves.
  1122. pckOut.writeString(
  1123. GitProtocolConstants.SECTION_PACKFILE + '\n');
  1124. }
  1125. accumulator.timeNegotiating = Duration
  1126. .between(negotiateStart, Instant.now()).toMillis();
  1127. sendPack(accumulator,
  1128. req,
  1129. req.getClientCapabilities().contains(OPTION_INCLUDE_TAG)
  1130. ? db.getRefDatabase().getRefsByPrefix(R_TAGS)
  1131. : null,
  1132. unshallowCommits, deepenNots, pckOut);
  1133. // sendPack invokes pckOut.end() for us, so we do not
  1134. // need to invoke it here.
  1135. } else {
  1136. // Invoke pckOut.end() by ourselves.
  1137. pckOut.end();
  1138. }
  1139. }
  1140. /*
  1141. * Returns true if this is the last command and we should tear down the
  1142. * connection.
  1143. */
  1144. private boolean serveOneCommandV2(PacketLineOut pckOut) throws IOException {
  1145. String command;
  1146. try {
  1147. command = pckIn.readString();
  1148. } catch (EOFException eof) {
  1149. /* EOF when awaiting command is fine */
  1150. return true;
  1151. }
  1152. if (PacketLineIn.isEnd(command)) {
  1153. // A blank request is valid according
  1154. // to the protocol; do nothing in this
  1155. // case.
  1156. return true;
  1157. }
  1158. if (command.equals("command=" + COMMAND_LS_REFS)) { //$NON-NLS-1$
  1159. lsRefsV2(pckOut);
  1160. return false;
  1161. }
  1162. if (command.equals("command=" + COMMAND_FETCH)) { //$NON-NLS-1$
  1163. fetchV2(pckOut);
  1164. return false;
  1165. }
  1166. throw new PackProtocolException(MessageFormat
  1167. .format(JGitText.get().unknownTransportCommand, command));
  1168. }
  1169. @SuppressWarnings("nls")
  1170. private List<String> getV2CapabilityAdvertisement() {
  1171. ArrayList<String> caps = new ArrayList<>();
  1172. caps.add("version 2");
  1173. caps.add(COMMAND_LS_REFS);
  1174. boolean advertiseRefInWant = transferConfig.isAllowRefInWant()
  1175. && db.getConfig().getBoolean("uploadpack", null,
  1176. "advertiserefinwant", true);
  1177. caps.add(COMMAND_FETCH + '='
  1178. + (transferConfig.isAllowFilter() ? OPTION_FILTER + ' ' : "")
  1179. + (advertiseRefInWant ? CAPABILITY_REF_IN_WANT + ' ' : "")
  1180. + (transferConfig.isAdvertiseSidebandAll()
  1181. ? OPTION_SIDEBAND_ALL + ' '
  1182. : "")
  1183. + (cachedPackUriProvider != null ? "packfile-uris " : "")
  1184. + (transferConfig.isAdvertiseWaitForDone()
  1185. ? OPTION_WAIT_FOR_DONE + ' '
  1186. : "")
  1187. + OPTION_SHALLOW);
  1188. caps.add(CAPABILITY_SERVER_OPTION);
  1189. return caps;
  1190. }
  1191. private void serviceV2(PacketLineOut pckOut) throws IOException {
  1192. if (biDirectionalPipe) {
  1193. // Just like in service(), the capability advertisement
  1194. // is sent only if this is a bidirectional pipe. (If
  1195. // not, the client is expected to call
  1196. // sendAdvertisedRefs() on its own.)
  1197. protocolV2Hook
  1198. .onCapabilities(CapabilitiesV2Request.builder().build());
  1199. for (String s : getV2CapabilityAdvertisement()) {
  1200. pckOut.writeString(s + "\n"); //$NON-NLS-1$
  1201. }
  1202. pckOut.end();
  1203. while (!serveOneCommandV2(pckOut)) {
  1204. // Repeat until an empty command or EOF.
  1205. }
  1206. return;
  1207. }
  1208. try {
  1209. serveOneCommandV2(pckOut);
  1210. } finally {
  1211. while (0 < rawIn.skip(2048) || 0 <= rawIn.read()) {
  1212. // Discard until EOF.
  1213. }
  1214. rawOut.stopBuffering();
  1215. }
  1216. }
  1217. private static Set<ObjectId> refIdSet(Collection<Ref> refs) {
  1218. Set<ObjectId> ids = new HashSet<>(refs.size());
  1219. for (Ref ref : refs) {
  1220. ObjectId id = ref.getObjectId();
  1221. if (id != null) {
  1222. ids.add(id);
  1223. }
  1224. id = ref.getPeeledObjectId();
  1225. if (id != null) {
  1226. ids.add(id);
  1227. }
  1228. }
  1229. return ids;
  1230. }
  1231. /*
  1232. * Determines what object ids must be marked as shallow or unshallow for the
  1233. * client.
  1234. */
  1235. private void computeShallowsAndUnshallows(FetchRequest req,
  1236. IOConsumer<ObjectId> shallowFunc,
  1237. IOConsumer<ObjectId> unshallowFunc,
  1238. List<ObjectId> deepenNots)
  1239. throws IOException {
  1240. if (req.getClientCapabilities().contains(OPTION_DEEPEN_RELATIVE)) {
  1241. // TODO(jonathantanmy): Implement deepen-relative
  1242. throw new UnsupportedOperationException();
  1243. }
  1244. int walkDepth = req.getDepth() == 0 ? Integer.MAX_VALUE
  1245. : req.getDepth() - 1;
  1246. try (DepthWalk.RevWalk depthWalk = new DepthWalk.RevWalk(
  1247. walk.getObjectReader(), walkDepth)) {
  1248. depthWalk.setDeepenSince(req.getDeepenSince());
  1249. // Find all the commits which will be shallow
  1250. for (ObjectId o : req.getWantIds()) {
  1251. try {
  1252. depthWalk.markRoot(depthWalk.parseCommit(o));
  1253. } catch (IncorrectObjectTypeException notCommit) {
  1254. // Ignore non-commits in this loop.
  1255. }
  1256. }
  1257. depthWalk.setDeepenNots(deepenNots);
  1258. RevCommit o;
  1259. boolean atLeastOne = false;
  1260. while ((o = depthWalk.next()) != null) {
  1261. DepthWalk.Commit c = (DepthWalk.Commit) o;
  1262. atLeastOne = true;
  1263. boolean isBoundary = (c.getDepth() == walkDepth) || c.isBoundary();
  1264. // Commits at the boundary which aren't already shallow in
  1265. // the client need to be marked as such
  1266. if (isBoundary && !req.getClientShallowCommits().contains(c)) {
  1267. shallowFunc.accept(c.copy());
  1268. }
  1269. // Commits not on the boundary which are shallow in the client
  1270. // need to become unshallowed
  1271. if (!isBoundary && req.getClientShallowCommits().remove(c)) {
  1272. unshallowFunc.accept(c.copy());
  1273. }
  1274. }
  1275. if (!atLeastOne) {
  1276. throw new PackProtocolException(
  1277. JGitText.get().noCommitsSelectedForShallow);
  1278. }
  1279. }
  1280. }
  1281. /*
  1282. * Verify all shallow lines refer to commits
  1283. *
  1284. * It can mutate the input set (removing missing object ids from it)
  1285. */
  1286. private void verifyClientShallow(Set<ObjectId> shallowCommits)
  1287. throws IOException, PackProtocolException {
  1288. AsyncRevObjectQueue q = walk.parseAny(shallowCommits, true);
  1289. try {
  1290. for (;;) {
  1291. try {
  1292. // Shallow objects named by the client must be commits.
  1293. RevObject o = q.next();
  1294. if (o == null) {
  1295. break;
  1296. }
  1297. if (!(o instanceof RevCommit)) {
  1298. throw new PackProtocolException(
  1299. MessageFormat.format(
  1300. JGitText.get().invalidShallowObject,
  1301. o.name()));
  1302. }
  1303. } catch (MissingObjectException notCommit) {
  1304. // shallow objects not known at the server are ignored
  1305. // by git-core upload-pack, match that behavior.
  1306. shallowCommits.remove(notCommit.getObjectId());
  1307. continue;
  1308. }
  1309. }
  1310. } finally {
  1311. q.release();
  1312. }
  1313. }
  1314. /**
  1315. * Generate an advertisement of available refs and capabilities.
  1316. *
  1317. * @param adv
  1318. * the advertisement formatter.
  1319. * @throws java.io.IOException
  1320. * the formatter failed to write an advertisement.
  1321. * @throws org.eclipse.jgit.transport.ServiceMayNotContinueException
  1322. * the hook denied advertisement.
  1323. */
  1324. public void sendAdvertisedRefs(RefAdvertiser adv) throws IOException,
  1325. ServiceMayNotContinueException {
  1326. sendAdvertisedRefs(adv, null);
  1327. }
  1328. /**
  1329. * Generate an advertisement of available refs and capabilities.
  1330. *
  1331. * @param adv
  1332. * the advertisement formatter.
  1333. * @param serviceName
  1334. * if not null, also output "# service=serviceName" followed by a
  1335. * flush packet before the advertisement. This is required
  1336. * in v0 of the HTTP protocol, described in Git's
  1337. * Documentation/technical/http-protocol.txt.
  1338. * @throws java.io.IOException
  1339. * the formatter failed to write an advertisement.
  1340. * @throws org.eclipse.jgit.transport.ServiceMayNotContinueException
  1341. * the hook denied advertisement.
  1342. * @since 5.0
  1343. */
  1344. public void sendAdvertisedRefs(RefAdvertiser adv,
  1345. @Nullable String serviceName) throws IOException,
  1346. ServiceMayNotContinueException {
  1347. if (useProtocolV2()) {
  1348. // The equivalent in v2 is only the capabilities
  1349. // advertisement.
  1350. protocolV2Hook
  1351. .onCapabilities(CapabilitiesV2Request.builder().build());
  1352. for (String s : getV2CapabilityAdvertisement()) {
  1353. adv.writeOne(s);
  1354. }
  1355. adv.end();
  1356. return;
  1357. }
  1358. Map<String, Ref> advertisedOrDefaultRefs = getAdvertisedOrDefaultRefs();
  1359. if (serviceName != null) {
  1360. adv.writeOne("# service=" + serviceName + '\n'); //$NON-NLS-1$
  1361. adv.end();
  1362. }
  1363. adv.init(db);
  1364. adv.advertiseCapability(OPTION_INCLUDE_TAG);
  1365. adv.advertiseCapability(OPTION_MULTI_ACK_DETAILED);
  1366. adv.advertiseCapability(OPTION_MULTI_ACK);
  1367. adv.advertiseCapability(OPTION_OFS_DELTA);
  1368. adv.advertiseCapability(OPTION_SIDE_BAND);
  1369. adv.advertiseCapability(OPTION_SIDE_BAND_64K);
  1370. adv.advertiseCapability(OPTION_THIN_PACK);
  1371. adv.advertiseCapability(OPTION_NO_PROGRESS);
  1372. adv.advertiseCapability(OPTION_SHALLOW);
  1373. if (!biDirectionalPipe)
  1374. adv.advertiseCapability(OPTION_NO_DONE);
  1375. RequestPolicy policy = getRequestPolicy();
  1376. if (policy == RequestPolicy.TIP
  1377. || policy == RequestPolicy.REACHABLE_COMMIT_TIP
  1378. || policy == null)
  1379. adv.advertiseCapability(OPTION_ALLOW_TIP_SHA1_IN_WANT);
  1380. if (policy == RequestPolicy.REACHABLE_COMMIT
  1381. || policy == RequestPolicy.REACHABLE_COMMIT_TIP
  1382. || policy == null)
  1383. adv.advertiseCapability(OPTION_ALLOW_REACHABLE_SHA1_IN_WANT);
  1384. adv.advertiseCapability(OPTION_AGENT, UserAgent.get());
  1385. if (transferConfig.isAllowFilter()) {
  1386. adv.advertiseCapability(OPTION_FILTER);
  1387. }
  1388. adv.setDerefTags(true);
  1389. findSymrefs(adv, advertisedOrDefaultRefs);
  1390. advertised = adv.send(advertisedOrDefaultRefs.values());
  1391. if (adv.isEmpty())
  1392. adv.advertiseId(ObjectId.zeroId(), "capabilities^{}"); //$NON-NLS-1$
  1393. adv.end();
  1394. }
  1395. /**
  1396. * Send a message to the client, if it supports receiving them.
  1397. * <p>
  1398. * If the client doesn't support receiving messages, the message will be
  1399. * discarded, with no other indication to the caller or to the client.
  1400. *
  1401. * @param what
  1402. * string describing the problem identified by the hook. The
  1403. * string must not end with an LF, and must not contain an LF.
  1404. * @since 3.1
  1405. */
  1406. public void sendMessage(String what) {
  1407. try {
  1408. msgOut.write(Constants.encode(what + "\n")); //$NON-NLS-1$
  1409. } catch (IOException e) {
  1410. // Ignore write failures.
  1411. }
  1412. }
  1413. /**
  1414. * Get an underlying stream for sending messages to the client
  1415. *
  1416. * @return an underlying stream for sending messages to the client, or null.
  1417. * @since 3.1
  1418. */
  1419. public OutputStream getMessageOutputStream() {
  1420. return msgOut;
  1421. }
  1422. /**
  1423. * Returns the clone/fetch depth. Valid only after calling recvWants(). A
  1424. * depth of 1 means return only the wants.
  1425. *
  1426. * @return the depth requested by the client, or 0 if unbounded.
  1427. * @since 4.0
  1428. */
  1429. public int getDepth() {
  1430. if (currentRequest == null)
  1431. throw new RequestNotYetReadException();
  1432. return currentRequest.getDepth();
  1433. }
  1434. /**
  1435. * Deprecated synonym for {@code getFilterSpec().getBlobLimit()}.
  1436. *
  1437. * @return filter blob limit requested by the client, or -1 if no limit
  1438. * @since 5.3
  1439. * @deprecated Use {@link #getFilterSpec()} instead
  1440. */
  1441. @Deprecated
  1442. public final long getFilterBlobLimit() {
  1443. return getFilterSpec().getBlobLimit();
  1444. }
  1445. /**
  1446. * Returns the filter spec for the current request. Valid only after
  1447. * calling recvWants(). This may be a no-op filter spec, but it won't be
  1448. * null.
  1449. *
  1450. * @return filter requested by the client
  1451. * @since 5.4
  1452. */
  1453. public final FilterSpec getFilterSpec() {
  1454. if (currentRequest == null) {
  1455. throw new RequestNotYetReadException();
  1456. }
  1457. return currentRequest.getFilterSpec();
  1458. }
  1459. /**
  1460. * Get the user agent of the client.
  1461. * <p>
  1462. * If the client is new enough to use {@code agent=} capability that value
  1463. * will be returned. Older HTTP clients may also supply their version using
  1464. * the HTTP {@code User-Agent} header. The capability overrides the HTTP
  1465. * header if both are available.
  1466. * <p>
  1467. * When an HTTP request has been received this method returns the HTTP
  1468. * {@code User-Agent} header value until capabilities have been parsed.
  1469. *
  1470. * @return user agent supplied by the client. Available only if the client
  1471. * is new enough to advertise its user agent.
  1472. * @since 4.0
  1473. */
  1474. public String getPeerUserAgent() {
  1475. if (currentRequest != null && currentRequest.getAgent() != null) {
  1476. return currentRequest.getAgent();
  1477. }
  1478. return userAgent;
  1479. }
  1480. private boolean negotiate(FetchRequest req,
  1481. PackStatistics.Accumulator accumulator,
  1482. PacketLineOut pckOut)
  1483. throws IOException {
  1484. okToGiveUp = Boolean.FALSE;
  1485. ObjectId last = ObjectId.zeroId();
  1486. List<ObjectId> peerHas = new ArrayList<>(64);
  1487. for (;;) {
  1488. String line;
  1489. try {
  1490. line = pckIn.readString();
  1491. } catch (EOFException eof) {
  1492. // EOF on stateless RPC (aka smart HTTP) and non-shallow request
  1493. // means the client asked for the updated shallow/unshallow data,
  1494. // disconnected, and will try another request with actual want/have.
  1495. // Don't report the EOF here, its a bug in the protocol that the client
  1496. // just disconnects without sending an END.
  1497. if (!biDirectionalPipe && req.getDepth() > 0)
  1498. return false;
  1499. throw eof;
  1500. }
  1501. if (PacketLineIn.isEnd(line)) {
  1502. last = processHaveLines(peerHas, last, pckOut, accumulator, Option.NONE);
  1503. if (commonBase.isEmpty() || multiAck != MultiAck.OFF)
  1504. pckOut.writeString("NAK\n"); //$NON-NLS-1$
  1505. if (noDone && sentReady) {
  1506. pckOut.writeString("ACK " + last.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1507. return true;
  1508. }
  1509. if (!biDirectionalPipe)
  1510. return false;
  1511. pckOut.flush();
  1512. } else if (line.startsWith("have ") && line.length() == 45) { //$NON-NLS-1$
  1513. peerHas.add(ObjectId.fromString(line.substring(5)));
  1514. accumulator.haves++;
  1515. } else if (line.equals("done")) { //$NON-NLS-1$
  1516. last = processHaveLines(peerHas, last, pckOut, accumulator, Option.NONE);
  1517. if (commonBase.isEmpty())
  1518. pckOut.writeString("NAK\n"); //$NON-NLS-1$
  1519. else if (multiAck != MultiAck.OFF)
  1520. pckOut.writeString("ACK " + last.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1521. return true;
  1522. } else {
  1523. throw new PackProtocolException(MessageFormat.format(JGitText.get().expectedGot, "have", line)); //$NON-NLS-1$
  1524. }
  1525. }
  1526. }
  1527. private enum Option {
  1528. WAIT_FOR_DONE,
  1529. NONE;
  1530. }
  1531. private ObjectId processHaveLines(List<ObjectId> peerHas, ObjectId last,
  1532. PacketLineOut out, PackStatistics.Accumulator accumulator,
  1533. Option option)
  1534. throws IOException {
  1535. preUploadHook.onBeginNegotiateRound(this, wantIds, peerHas.size());
  1536. if (wantAll.isEmpty() && !wantIds.isEmpty())
  1537. parseWants(accumulator);
  1538. if (peerHas.isEmpty())
  1539. return last;
  1540. sentReady = false;
  1541. int haveCnt = 0;
  1542. walk.getObjectReader().setAvoidUnreachableObjects(true);
  1543. AsyncRevObjectQueue q = walk.parseAny(peerHas, false);
  1544. try {
  1545. for (;;) {
  1546. RevObject obj;
  1547. try {
  1548. obj = q.next();
  1549. } catch (MissingObjectException notFound) {
  1550. continue;
  1551. }
  1552. if (obj == null)
  1553. break;
  1554. last = obj;
  1555. haveCnt++;
  1556. if (obj instanceof RevCommit) {
  1557. RevCommit c = (RevCommit) obj;
  1558. if (oldestTime == 0 || c.getCommitTime() < oldestTime)
  1559. oldestTime = c.getCommitTime();
  1560. }
  1561. if (obj.has(PEER_HAS))
  1562. continue;
  1563. obj.add(PEER_HAS);
  1564. if (obj instanceof RevCommit)
  1565. ((RevCommit) obj).carry(PEER_HAS);
  1566. addCommonBase(obj);
  1567. // If both sides have the same object; let the client know.
  1568. //
  1569. switch (multiAck) {
  1570. case OFF:
  1571. if (commonBase.size() == 1)
  1572. out.writeString("ACK " + obj.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1573. break;
  1574. case CONTINUE:
  1575. out.writeString("ACK " + obj.name() + " continue\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1576. break;
  1577. case DETAILED:
  1578. out.writeString("ACK " + obj.name() + " common\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1579. break;
  1580. }
  1581. }
  1582. } finally {
  1583. q.release();
  1584. walk.getObjectReader().setAvoidUnreachableObjects(false);
  1585. }
  1586. int missCnt = peerHas.size() - haveCnt;
  1587. // If we don't have one of the objects but we're also willing to
  1588. // create a pack at this point, let the client know so it stops
  1589. // telling us about its history.
  1590. //
  1591. if (option != Option.WAIT_FOR_DONE) {
  1592. sentReady = shouldGiveUp(peerHas, out, missCnt);
  1593. }
  1594. preUploadHook.onEndNegotiateRound(this, wantAll, haveCnt, missCnt, sentReady);
  1595. peerHas.clear();
  1596. return last;
  1597. }
  1598. private boolean shouldGiveUp(List<ObjectId> peerHas, PacketLineOut out, int missCnt)
  1599. throws IOException {
  1600. boolean sentReady = false;
  1601. boolean didOkToGiveUp = false;
  1602. if (0 < missCnt) {
  1603. for (int i = peerHas.size() - 1; i >= 0; i--) {
  1604. ObjectId id = peerHas.get(i);
  1605. if (walk.lookupOrNull(id) == null) {
  1606. didOkToGiveUp = true;
  1607. if (okToGiveUp()) {
  1608. switch (multiAck) {
  1609. case OFF:
  1610. break;
  1611. case CONTINUE:
  1612. out.writeString(
  1613. "ACK " + id.name() + " continue\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1614. break;
  1615. case DETAILED:
  1616. out.writeString(
  1617. "ACK " + id.name() + " ready\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1618. sentReady = true;
  1619. break;
  1620. }
  1621. }
  1622. break;
  1623. }
  1624. }
  1625. }
  1626. if (multiAck == MultiAck.DETAILED && !didOkToGiveUp
  1627. && okToGiveUp()) {
  1628. ObjectId id = peerHas.get(peerHas.size() - 1);
  1629. out.writeString("ACK " + id.name() + " ready\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1630. sentReady = true;
  1631. }
  1632. return sentReady;
  1633. }
  1634. private void parseWants(PackStatistics.Accumulator accumulator) throws IOException {
  1635. List<ObjectId> notAdvertisedWants = null;
  1636. for (ObjectId obj : wantIds) {
  1637. if (!advertised.contains(obj)) {
  1638. if (notAdvertisedWants == null)
  1639. notAdvertisedWants = new ArrayList<>();
  1640. notAdvertisedWants.add(obj);
  1641. }
  1642. }
  1643. if (notAdvertisedWants != null) {
  1644. accumulator.notAdvertisedWants = notAdvertisedWants.size();
  1645. Instant startReachabilityChecking = Instant.now();
  1646. requestValidator.checkWants(this, notAdvertisedWants);
  1647. accumulator.reachabilityCheckDuration = Duration
  1648. .between(startReachabilityChecking, Instant.now())
  1649. .toMillis();
  1650. }
  1651. AsyncRevObjectQueue q = walk.parseAny(wantIds, true);
  1652. try {
  1653. RevObject obj;
  1654. while ((obj = q.next()) != null) {
  1655. want(obj);
  1656. if (!(obj instanceof RevCommit))
  1657. obj.add(SATISFIED);
  1658. if (obj instanceof RevTag) {
  1659. obj = walk.peel(obj);
  1660. if (obj instanceof RevCommit)
  1661. want(obj);
  1662. }
  1663. }
  1664. wantIds.clear();
  1665. } catch (MissingObjectException notFound) {
  1666. throw new WantNotValidException(notFound.getObjectId(), notFound);
  1667. } finally {
  1668. q.release();
  1669. }
  1670. }
  1671. private void want(RevObject obj) {
  1672. if (!obj.has(WANT)) {
  1673. obj.add(WANT);
  1674. wantAll.add(obj);
  1675. }
  1676. }
  1677. /**
  1678. * Validator corresponding to {@link RequestPolicy#ADVERTISED}.
  1679. *
  1680. * @since 3.1
  1681. */
  1682. public static final class AdvertisedRequestValidator
  1683. implements RequestValidator {
  1684. @Override
  1685. public void checkWants(UploadPack up, List<ObjectId> wants)
  1686. throws PackProtocolException, IOException {
  1687. if (!up.isBiDirectionalPipe())
  1688. new ReachableCommitRequestValidator().checkWants(up, wants);
  1689. else if (!wants.isEmpty())
  1690. throw new WantNotValidException(wants.iterator().next());
  1691. }
  1692. }
  1693. /**
  1694. * Validator corresponding to {@link RequestPolicy#REACHABLE_COMMIT}.
  1695. *
  1696. * @since 3.1
  1697. */
  1698. public static final class ReachableCommitRequestValidator
  1699. implements RequestValidator {
  1700. @Override
  1701. public void checkWants(UploadPack up, List<ObjectId> wants)
  1702. throws PackProtocolException, IOException {
  1703. checkNotAdvertisedWants(up, wants, up.getAdvertisedRefs().values());
  1704. }
  1705. }
  1706. /**
  1707. * Validator corresponding to {@link RequestPolicy#TIP}.
  1708. *
  1709. * @since 3.1
  1710. */
  1711. public static final class TipRequestValidator implements RequestValidator {
  1712. @Override
  1713. public void checkWants(UploadPack up, List<ObjectId> wants)
  1714. throws PackProtocolException, IOException {
  1715. if (!up.isBiDirectionalPipe())
  1716. new ReachableCommitTipRequestValidator().checkWants(up, wants);
  1717. else if (!wants.isEmpty()) {
  1718. Set<ObjectId> refIds =
  1719. refIdSet(up.getRepository().getRefDatabase().getRefs());
  1720. for (ObjectId obj : wants) {
  1721. if (!refIds.contains(obj))
  1722. throw new WantNotValidException(obj);
  1723. }
  1724. }
  1725. }
  1726. }
  1727. /**
  1728. * Validator corresponding to {@link RequestPolicy#REACHABLE_COMMIT_TIP}.
  1729. *
  1730. * @since 3.1
  1731. */
  1732. public static final class ReachableCommitTipRequestValidator
  1733. implements RequestValidator {
  1734. @Override
  1735. public void checkWants(UploadPack up, List<ObjectId> wants)
  1736. throws PackProtocolException, IOException {
  1737. checkNotAdvertisedWants(up, wants,
  1738. up.getRepository().getRefDatabase().getRefs());
  1739. }
  1740. }
  1741. /**
  1742. * Validator corresponding to {@link RequestPolicy#ANY}.
  1743. *
  1744. * @since 3.1
  1745. */
  1746. public static final class AnyRequestValidator implements RequestValidator {
  1747. @Override
  1748. public void checkWants(UploadPack up, List<ObjectId> wants)
  1749. throws PackProtocolException, IOException {
  1750. // All requests are valid.
  1751. }
  1752. }
  1753. private static void checkNotAdvertisedWants(UploadPack up,
  1754. List<ObjectId> notAdvertisedWants, Collection<Ref> visibleRefs)
  1755. throws IOException {
  1756. ObjectReader reader = up.getRevWalk().getObjectReader();
  1757. try (RevWalk walk = new RevWalk(reader)) {
  1758. walk.setRetainBody(false);
  1759. // Missing "wants" throw exception here
  1760. List<RevObject> wantsAsObjs = objectIdsToRevObjects(walk,
  1761. notAdvertisedWants);
  1762. List<RevCommit> wantsAsCommits = wantsAsObjs.stream()
  1763. .filter(obj -> obj instanceof RevCommit)
  1764. .map(obj -> (RevCommit) obj)
  1765. .collect(Collectors.toList());
  1766. boolean allWantsAreCommits = wantsAsObjs.size() == wantsAsCommits
  1767. .size();
  1768. boolean repoHasBitmaps = reader.getBitmapIndex() != null;
  1769. if (!allWantsAreCommits) {
  1770. if (!repoHasBitmaps && !up.transferConfig.isAllowFilter()) {
  1771. // Checking unadvertised non-commits without bitmaps
  1772. // requires an expensive manual walk. Use allowFilter as an
  1773. // indication that the server operator is willing to pay
  1774. // this cost. Reject the request otherwise.
  1775. RevObject nonCommit = wantsAsObjs
  1776. .stream()
  1777. .filter(obj -> !(obj instanceof RevCommit))
  1778. .limit(1)
  1779. .collect(Collectors.toList()).get(0);
  1780. throw new WantNotValidException(nonCommit);
  1781. }
  1782. try (ObjectWalk objWalk = walk.toObjectWalkWithSameObjects()) {
  1783. Stream<RevObject> startersAsObjs = importantRefsFirst(visibleRefs)
  1784. .map(UploadPack::refToObjectId)
  1785. .map(objId -> objectIdToRevObject(objWalk, objId))
  1786. .filter(Objects::nonNull); // Ignore missing tips
  1787. ObjectReachabilityChecker reachabilityChecker = reader
  1788. .createObjectReachabilityChecker(objWalk);
  1789. Optional<RevObject> unreachable = reachabilityChecker
  1790. .areAllReachable(wantsAsObjs, startersAsObjs);
  1791. if (unreachable.isPresent()) {
  1792. throw new WantNotValidException(unreachable.get());
  1793. }
  1794. }
  1795. return;
  1796. }
  1797. // All wants are commits, we can use ReachabilityChecker
  1798. ReachabilityChecker reachabilityChecker = reader
  1799. .createReachabilityChecker(walk);
  1800. Stream<RevCommit> reachableCommits = importantRefsFirst(visibleRefs)
  1801. .map(UploadPack::refToObjectId)
  1802. .map(objId -> objectIdToRevCommit(walk, objId))
  1803. .filter(Objects::nonNull); // Ignore missing tips
  1804. Optional<RevCommit> unreachable = reachabilityChecker
  1805. .areAllReachable(wantsAsCommits, reachableCommits);
  1806. if (unreachable.isPresent()) {
  1807. throw new WantNotValidException(unreachable.get());
  1808. }
  1809. } catch (MissingObjectException notFound) {
  1810. throw new WantNotValidException(notFound.getObjectId(), notFound);
  1811. }
  1812. }
  1813. static Stream<Ref> importantRefsFirst(
  1814. Collection<Ref> visibleRefs) {
  1815. Predicate<Ref> startsWithRefsHeads = ref -> ref.getName()
  1816. .startsWith(Constants.R_HEADS);
  1817. Predicate<Ref> startsWithRefsTags = ref -> ref.getName()
  1818. .startsWith(Constants.R_TAGS);
  1819. Predicate<Ref> allOther = ref -> !startsWithRefsHeads.test(ref)
  1820. && !startsWithRefsTags.test(ref);
  1821. return Stream.concat(
  1822. visibleRefs.stream().filter(startsWithRefsHeads),
  1823. Stream.concat(
  1824. visibleRefs.stream().filter(startsWithRefsTags),
  1825. visibleRefs.stream().filter(allOther)));
  1826. }
  1827. private static ObjectId refToObjectId(Ref ref) {
  1828. return ref.getObjectId() != null ? ref.getObjectId()
  1829. : ref.getPeeledObjectId();
  1830. }
  1831. /**
  1832. * Translate an object id to a RevCommit.
  1833. *
  1834. * @param walk
  1835. * walk on the relevant object storae
  1836. * @param objectId
  1837. * Object Id
  1838. * @return RevCommit instance or null if the object is missing
  1839. */
  1840. @Nullable
  1841. private static RevCommit objectIdToRevCommit(RevWalk walk,
  1842. ObjectId objectId) {
  1843. if (objectId == null) {
  1844. return null;
  1845. }
  1846. try {
  1847. return walk.parseCommit(objectId);
  1848. } catch (IOException e) {
  1849. return null;
  1850. }
  1851. }
  1852. /**
  1853. * Translate an object id to a RevObject.
  1854. *
  1855. * @param walk
  1856. * walk on the relevant object storage
  1857. * @param objectId
  1858. * Object Id
  1859. * @return RevObject instance or null if the object is missing
  1860. */
  1861. @Nullable
  1862. private static RevObject objectIdToRevObject(RevWalk walk,
  1863. ObjectId objectId) {
  1864. if (objectId == null) {
  1865. return null;
  1866. }
  1867. try {
  1868. return walk.parseAny(objectId);
  1869. } catch (IOException e) {
  1870. return null;
  1871. }
  1872. }
  1873. // Resolve the ObjectIds into RevObjects. Any missing object raises an
  1874. // exception
  1875. private static List<RevObject> objectIdsToRevObjects(RevWalk walk,
  1876. Iterable<ObjectId> objectIds)
  1877. throws MissingObjectException, IOException {
  1878. List<RevObject> result = new ArrayList<>();
  1879. for (ObjectId objectId : objectIds) {
  1880. result.add(walk.parseAny(objectId));
  1881. }
  1882. return result;
  1883. }
  1884. private void addCommonBase(RevObject o) {
  1885. if (!o.has(COMMON)) {
  1886. o.add(COMMON);
  1887. commonBase.add(o);
  1888. okToGiveUp = null;
  1889. }
  1890. }
  1891. private boolean okToGiveUp() throws PackProtocolException {
  1892. if (okToGiveUp == null)
  1893. okToGiveUp = Boolean.valueOf(okToGiveUpImp());
  1894. return okToGiveUp.booleanValue();
  1895. }
  1896. private boolean okToGiveUpImp() throws PackProtocolException {
  1897. if (commonBase.isEmpty())
  1898. return false;
  1899. try {
  1900. for (RevObject obj : wantAll) {
  1901. if (!wantSatisfied(obj))
  1902. return false;
  1903. }
  1904. return true;
  1905. } catch (IOException e) {
  1906. throw new PackProtocolException(JGitText.get().internalRevisionError, e);
  1907. }
  1908. }
  1909. private boolean wantSatisfied(RevObject want) throws IOException {
  1910. if (want.has(SATISFIED))
  1911. return true;
  1912. walk.resetRetain(SAVE);
  1913. walk.markStart((RevCommit) want);
  1914. if (oldestTime != 0)
  1915. walk.setRevFilter(CommitTimeRevFilter.after(oldestTime * 1000L));
  1916. for (;;) {
  1917. final RevCommit c = walk.next();
  1918. if (c == null)
  1919. break;
  1920. if (c.has(PEER_HAS)) {
  1921. addCommonBase(c);
  1922. want.add(SATISFIED);
  1923. return true;
  1924. }
  1925. }
  1926. return false;
  1927. }
  1928. /**
  1929. * Send the requested objects to the client.
  1930. *
  1931. * @param accumulator
  1932. * where to write statistics about the content of the pack.
  1933. * @param req
  1934. * request in process
  1935. * @param allTags
  1936. * refs to search for annotated tags to include in the pack if
  1937. * the {@link #OPTION_INCLUDE_TAG} capability was requested.
  1938. * @param unshallowCommits
  1939. * shallow commits on the client that are now becoming unshallow
  1940. * @param deepenNots
  1941. * objects that the client specified using --shallow-exclude
  1942. * @param pckOut
  1943. * output writer
  1944. * @throws IOException
  1945. * if an error occurred while generating or writing the pack.
  1946. */
  1947. private void sendPack(PackStatistics.Accumulator accumulator,
  1948. FetchRequest req,
  1949. @Nullable Collection<Ref> allTags,
  1950. List<ObjectId> unshallowCommits,
  1951. List<ObjectId> deepenNots,
  1952. PacketLineOut pckOut) throws IOException {
  1953. Set<String> caps = req.getClientCapabilities();
  1954. boolean sideband = caps.contains(OPTION_SIDE_BAND)
  1955. || caps.contains(OPTION_SIDE_BAND_64K);
  1956. if (sideband) {
  1957. errOut = new SideBandErrorWriter();
  1958. int bufsz = SideBandOutputStream.SMALL_BUF;
  1959. if (req.getClientCapabilities().contains(OPTION_SIDE_BAND_64K)) {
  1960. bufsz = SideBandOutputStream.MAX_BUF;
  1961. }
  1962. OutputStream packOut = new SideBandOutputStream(
  1963. SideBandOutputStream.CH_DATA, bufsz, rawOut);
  1964. ProgressMonitor pm = NullProgressMonitor.INSTANCE;
  1965. if (!req.getClientCapabilities().contains(OPTION_NO_PROGRESS)) {
  1966. msgOut = new SideBandOutputStream(
  1967. SideBandOutputStream.CH_PROGRESS, bufsz, rawOut);
  1968. pm = new SideBandProgressMonitor(msgOut);
  1969. }
  1970. sendPack(pm, pckOut, packOut, req, accumulator, allTags,
  1971. unshallowCommits, deepenNots);
  1972. pckOut.end();
  1973. } else {
  1974. sendPack(NullProgressMonitor.INSTANCE, pckOut, rawOut, req,
  1975. accumulator, allTags, unshallowCommits, deepenNots);
  1976. }
  1977. }
  1978. /**
  1979. * Send the requested objects to the client.
  1980. *
  1981. * @param pm
  1982. * progress monitor
  1983. * @param pckOut
  1984. * PacketLineOut that shares the output with packOut
  1985. * @param packOut
  1986. * packfile output
  1987. * @param req
  1988. * request being processed
  1989. * @param accumulator
  1990. * where to write statistics about the content of the pack.
  1991. * @param allTags
  1992. * refs to search for annotated tags to include in the pack if
  1993. * the {@link #OPTION_INCLUDE_TAG} capability was requested.
  1994. * @param unshallowCommits
  1995. * shallow commits on the client that are now becoming unshallow
  1996. * @param deepenNots
  1997. * objects that the client specified using --shallow-exclude
  1998. * @throws IOException
  1999. * if an error occurred while generating or writing the pack.
  2000. */
  2001. private void sendPack(ProgressMonitor pm, PacketLineOut pckOut,
  2002. OutputStream packOut, FetchRequest req,
  2003. PackStatistics.Accumulator accumulator,
  2004. @Nullable Collection<Ref> allTags, List<ObjectId> unshallowCommits,
  2005. List<ObjectId> deepenNots) throws IOException {
  2006. if (wantAll.isEmpty()) {
  2007. preUploadHook.onSendPack(this, wantIds, commonBase);
  2008. } else {
  2009. preUploadHook.onSendPack(this, wantAll, commonBase);
  2010. }
  2011. msgOut.flush();
  2012. // Advertised objects and refs are not used from here on and can be
  2013. // cleared.
  2014. advertised = null;
  2015. refs = null;
  2016. PackConfig cfg = packConfig;
  2017. if (cfg == null)
  2018. cfg = new PackConfig(db);
  2019. @SuppressWarnings("resource") // PackWriter is referenced in the finally
  2020. // block, and is closed there
  2021. final PackWriter pw = new PackWriter(cfg, walk.getObjectReader(),
  2022. accumulator);
  2023. try {
  2024. pw.setIndexDisabled(true);
  2025. if (req.getFilterSpec().isNoOp()) {
  2026. pw.setUseCachedPacks(true);
  2027. } else {
  2028. pw.setFilterSpec(req.getFilterSpec());
  2029. pw.setUseCachedPacks(false);
  2030. }
  2031. pw.setUseBitmaps(
  2032. req.getDepth() == 0
  2033. && req.getClientShallowCommits().isEmpty()
  2034. && req.getFilterSpec().getTreeDepthLimit() == -1);
  2035. pw.setClientShallowCommits(req.getClientShallowCommits());
  2036. pw.setReuseDeltaCommits(true);
  2037. pw.setDeltaBaseAsOffset(
  2038. req.getClientCapabilities().contains(OPTION_OFS_DELTA));
  2039. pw.setThin(req.getClientCapabilities().contains(OPTION_THIN_PACK));
  2040. pw.setReuseValidatingObjects(false);
  2041. // Objects named directly by references go at the beginning
  2042. // of the pack.
  2043. if (commonBase.isEmpty() && refs != null) {
  2044. Set<ObjectId> tagTargets = new HashSet<>();
  2045. for (Ref ref : refs.values()) {
  2046. if (ref.getPeeledObjectId() != null)
  2047. tagTargets.add(ref.getPeeledObjectId());
  2048. else if (ref.getObjectId() == null)
  2049. continue;
  2050. else if (ref.getName().startsWith(Constants.R_HEADS))
  2051. tagTargets.add(ref.getObjectId());
  2052. }
  2053. pw.setTagTargets(tagTargets);
  2054. }
  2055. RevWalk rw = walk;
  2056. if (req.getDepth() > 0 || req.getDeepenSince() != 0 || !deepenNots.isEmpty()) {
  2057. int walkDepth = req.getDepth() == 0 ? Integer.MAX_VALUE
  2058. : req.getDepth() - 1;
  2059. pw.setShallowPack(req.getDepth(), unshallowCommits);
  2060. @SuppressWarnings("resource") // Ownership is transferred below
  2061. DepthWalk.RevWalk dw = new DepthWalk.RevWalk(
  2062. walk.getObjectReader(), walkDepth);
  2063. dw.setDeepenSince(req.getDeepenSince());
  2064. dw.setDeepenNots(deepenNots);
  2065. dw.assumeShallow(req.getClientShallowCommits());
  2066. rw = dw;
  2067. }
  2068. if (wantAll.isEmpty()) {
  2069. pw.preparePack(pm, wantIds, commonBase,
  2070. req.getClientShallowCommits());
  2071. } else {
  2072. walk.reset();
  2073. ObjectWalk ow = rw.toObjectWalkWithSameObjects();
  2074. pw.preparePack(pm, ow, wantAll, commonBase, PackWriter.NONE);
  2075. rw = ow;
  2076. }
  2077. if (req.getClientCapabilities().contains(OPTION_INCLUDE_TAG)
  2078. && allTags != null) {
  2079. for (Ref ref : allTags) {
  2080. ObjectId objectId = ref.getObjectId();
  2081. if (objectId == null) {
  2082. // skip unborn branch
  2083. continue;
  2084. }
  2085. // If the object was already requested, skip it.
  2086. if (wantAll.isEmpty()) {
  2087. if (wantIds.contains(objectId))
  2088. continue;
  2089. } else {
  2090. RevObject obj = rw.lookupOrNull(objectId);
  2091. if (obj != null && obj.has(WANT))
  2092. continue;
  2093. }
  2094. if (!ref.isPeeled())
  2095. ref = db.getRefDatabase().peel(ref);
  2096. ObjectId peeledId = ref.getPeeledObjectId();
  2097. objectId = ref.getObjectId();
  2098. if (peeledId == null || objectId == null)
  2099. continue;
  2100. objectId = ref.getObjectId();
  2101. if (pw.willInclude(peeledId) && !pw.willInclude(objectId)) {
  2102. RevObject o = rw.parseAny(objectId);
  2103. addTagChain(o, pw);
  2104. pw.addObject(o);
  2105. }
  2106. }
  2107. }
  2108. if (pckOut.isUsingSideband()) {
  2109. if (req instanceof FetchV2Request &&
  2110. cachedPackUriProvider != null &&
  2111. !((FetchV2Request) req).getPackfileUriProtocols().isEmpty()) {
  2112. FetchV2Request reqV2 = (FetchV2Request) req;
  2113. pw.setPackfileUriConfig(new PackWriter.PackfileUriConfig(
  2114. pckOut,
  2115. reqV2.getPackfileUriProtocols(),
  2116. cachedPackUriProvider));
  2117. } else {
  2118. // PackWriter will write "packfile-uris\n" and "packfile\n"
  2119. // for us if provided a PackfileUriConfig. In this case, we
  2120. // are not providing a PackfileUriConfig, so we have to
  2121. // write this line ourselves.
  2122. pckOut.writeString(
  2123. GitProtocolConstants.SECTION_PACKFILE + '\n');
  2124. }
  2125. }
  2126. pw.writePack(pm, NullProgressMonitor.INSTANCE, packOut);
  2127. if (msgOut != NullOutputStream.INSTANCE) {
  2128. String msg = pw.getStatistics().getMessage() + '\n';
  2129. msgOut.write(Constants.encode(msg));
  2130. msgOut.flush();
  2131. }
  2132. } finally {
  2133. statistics = pw.getStatistics();
  2134. if (statistics != null) {
  2135. postUploadHook.onPostUpload(statistics);
  2136. }
  2137. pw.close();
  2138. }
  2139. }
  2140. private static void findSymrefs(
  2141. final RefAdvertiser adv, final Map<String, Ref> refs) {
  2142. Ref head = refs.get(Constants.HEAD);
  2143. if (head != null && head.isSymbolic()) {
  2144. adv.addSymref(Constants.HEAD, head.getLeaf().getName());
  2145. }
  2146. }
  2147. private void addTagChain(
  2148. RevObject o, PackWriter pw) throws IOException {
  2149. while (Constants.OBJ_TAG == o.getType()) {
  2150. RevTag t = (RevTag) o;
  2151. o = t.getObject();
  2152. if (o.getType() == Constants.OBJ_TAG && !pw.willInclude(o.getId())) {
  2153. walk.parseBody(o);
  2154. pw.addObject(o);
  2155. }
  2156. }
  2157. }
  2158. private static class ResponseBufferedOutputStream extends OutputStream {
  2159. private final OutputStream rawOut;
  2160. private OutputStream out;
  2161. ResponseBufferedOutputStream(OutputStream rawOut) {
  2162. this.rawOut = rawOut;
  2163. this.out = new ByteArrayOutputStream();
  2164. }
  2165. @Override
  2166. public void write(int b) throws IOException {
  2167. out.write(b);
  2168. }
  2169. @Override
  2170. public void write(byte[] b) throws IOException {
  2171. out.write(b);
  2172. }
  2173. @Override
  2174. public void write(byte[] b, int off, int len) throws IOException {
  2175. out.write(b, off, len);
  2176. }
  2177. @Override
  2178. public void flush() throws IOException {
  2179. out.flush();
  2180. }
  2181. @Override
  2182. public void close() throws IOException {
  2183. out.close();
  2184. }
  2185. void stopBuffering() throws IOException {
  2186. if (out != rawOut) {
  2187. ((ByteArrayOutputStream) out).writeTo(rawOut);
  2188. out = rawOut;
  2189. }
  2190. }
  2191. }
  2192. private interface ErrorWriter {
  2193. void writeError(String message) throws IOException;
  2194. }
  2195. private class SideBandErrorWriter implements ErrorWriter {
  2196. @Override
  2197. public void writeError(String message) throws IOException {
  2198. @SuppressWarnings("resource" /* java 7 */)
  2199. SideBandOutputStream err = new SideBandOutputStream(
  2200. SideBandOutputStream.CH_ERROR,
  2201. SideBandOutputStream.SMALL_BUF, requireNonNull(rawOut));
  2202. err.write(Constants.encode(message));
  2203. err.flush();
  2204. }
  2205. }
  2206. private class PackProtocolErrorWriter implements ErrorWriter {
  2207. @Override
  2208. public void writeError(String message) throws IOException {
  2209. new PacketLineOut(requireNonNull(rawOut))
  2210. .writeString("ERR " + message + '\n'); //$NON-NLS-1$
  2211. }
  2212. }
  2213. }