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

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