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

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