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

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