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

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