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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665
  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.RefDatabase.ALL;
  45. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_AGENT;
  46. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_ALLOW_REACHABLE_SHA1_IN_WANT;
  47. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_ALLOW_TIP_SHA1_IN_WANT;
  48. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_INCLUDE_TAG;
  49. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_MULTI_ACK;
  50. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_MULTI_ACK_DETAILED;
  51. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_NO_DONE;
  52. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_NO_PROGRESS;
  53. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_OFS_DELTA;
  54. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SHALLOW;
  55. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SIDE_BAND;
  56. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SIDE_BAND_64K;
  57. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_THIN_PACK;
  58. import java.io.ByteArrayOutputStream;
  59. import java.io.EOFException;
  60. import java.io.IOException;
  61. import java.io.InputStream;
  62. import java.io.OutputStream;
  63. import java.text.MessageFormat;
  64. import java.util.ArrayList;
  65. import java.util.Collection;
  66. import java.util.Collections;
  67. import java.util.HashSet;
  68. import java.util.List;
  69. import java.util.Map;
  70. import java.util.Set;
  71. import org.eclipse.jgit.errors.CorruptObjectException;
  72. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  73. import org.eclipse.jgit.errors.MissingObjectException;
  74. import org.eclipse.jgit.errors.PackProtocolException;
  75. import org.eclipse.jgit.internal.JGitText;
  76. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  77. import org.eclipse.jgit.lib.BitmapIndex;
  78. import org.eclipse.jgit.lib.BitmapIndex.BitmapBuilder;
  79. import org.eclipse.jgit.lib.Constants;
  80. import org.eclipse.jgit.lib.NullProgressMonitor;
  81. import org.eclipse.jgit.lib.ObjectId;
  82. import org.eclipse.jgit.lib.ObjectReader;
  83. import org.eclipse.jgit.lib.ProgressMonitor;
  84. import org.eclipse.jgit.lib.Ref;
  85. import org.eclipse.jgit.lib.RefDatabase;
  86. import org.eclipse.jgit.lib.Repository;
  87. import org.eclipse.jgit.revwalk.AsyncRevObjectQueue;
  88. import org.eclipse.jgit.revwalk.BitmapWalker;
  89. import org.eclipse.jgit.revwalk.DepthWalk;
  90. import org.eclipse.jgit.revwalk.ObjectWalk;
  91. import org.eclipse.jgit.revwalk.RevCommit;
  92. import org.eclipse.jgit.revwalk.RevFlag;
  93. import org.eclipse.jgit.revwalk.RevFlagSet;
  94. import org.eclipse.jgit.revwalk.RevObject;
  95. import org.eclipse.jgit.revwalk.RevTag;
  96. import org.eclipse.jgit.revwalk.RevWalk;
  97. import org.eclipse.jgit.revwalk.filter.CommitTimeRevFilter;
  98. import org.eclipse.jgit.storage.pack.PackConfig;
  99. import org.eclipse.jgit.storage.pack.PackStatistics;
  100. import org.eclipse.jgit.transport.GitProtocolConstants.MultiAck;
  101. import org.eclipse.jgit.transport.RefAdvertiser.PacketLineOutRefAdvertiser;
  102. import org.eclipse.jgit.util.io.InterruptTimer;
  103. import org.eclipse.jgit.util.io.NullOutputStream;
  104. import org.eclipse.jgit.util.io.TimeoutInputStream;
  105. import org.eclipse.jgit.util.io.TimeoutOutputStream;
  106. /**
  107. * Implements the server side of a fetch connection, transmitting objects.
  108. */
  109. public class UploadPack {
  110. /** Policy the server uses to validate client requests */
  111. public static enum RequestPolicy {
  112. /** Client may only ask for objects the server advertised a reference for. */
  113. ADVERTISED,
  114. /**
  115. * Client may ask for any commit reachable from a reference advertised by
  116. * the server.
  117. */
  118. REACHABLE_COMMIT,
  119. /**
  120. * Client may ask for objects that are the tip of any reference, even if not
  121. * advertised.
  122. * <p>
  123. * This may happen, for example, when a custom {@link RefFilter} is set.
  124. *
  125. * @since 3.1
  126. */
  127. TIP,
  128. /**
  129. * Client may ask for any commit reachable from any reference, even if that
  130. * reference wasn't advertised.
  131. *
  132. * @since 3.1
  133. */
  134. REACHABLE_COMMIT_TIP,
  135. /** Client may ask for any SHA-1 in the repository. */
  136. ANY;
  137. }
  138. /**
  139. * Validator for client requests.
  140. *
  141. * @since 3.1
  142. */
  143. public interface RequestValidator {
  144. /**
  145. * Check a list of client wants against the request policy.
  146. *
  147. * @param up
  148. * {@link UploadPack} instance.
  149. * @param wants
  150. * objects the client requested that were not advertised.
  151. *
  152. * @throws PackProtocolException
  153. * if one or more wants is not valid.
  154. * @throws IOException
  155. * if a low-level exception occurred.
  156. * @since 3.1
  157. */
  158. void checkWants(UploadPack up, List<ObjectId> wants)
  159. throws PackProtocolException, IOException;
  160. }
  161. /** Data in the first line of a request, the line itself plus options. */
  162. public static class FirstLine {
  163. private final String line;
  164. private final Set<String> options;
  165. /**
  166. * Parse the first line of a receive-pack request.
  167. *
  168. * @param line
  169. * line from the client.
  170. */
  171. public FirstLine(String line) {
  172. if (line.length() > 45) {
  173. final HashSet<String> opts = new HashSet<>();
  174. String opt = line.substring(45);
  175. if (opt.startsWith(" ")) //$NON-NLS-1$
  176. opt = opt.substring(1);
  177. for (String c : opt.split(" ")) //$NON-NLS-1$
  178. opts.add(c);
  179. this.line = line.substring(0, 45);
  180. this.options = Collections.unmodifiableSet(opts);
  181. } else {
  182. this.line = line;
  183. this.options = Collections.emptySet();
  184. }
  185. }
  186. /** @return non-capabilities part of the line. */
  187. public String getLine() {
  188. return line;
  189. }
  190. /** @return options parsed from the line. */
  191. public Set<String> getOptions() {
  192. return options;
  193. }
  194. }
  195. /** Database we read the objects from. */
  196. private final Repository db;
  197. /** Revision traversal support over {@link #db}. */
  198. private final RevWalk walk;
  199. /** Configuration to pass into the PackWriter. */
  200. private PackConfig packConfig;
  201. /** Configuration for various transfer options. */
  202. private TransferConfig transferConfig;
  203. /** Timeout in seconds to wait for client interaction. */
  204. private int timeout;
  205. /**
  206. * Is the client connection a bi-directional socket or pipe?
  207. * <p>
  208. * If true, this class assumes it can perform multiple read and write cycles
  209. * with the client over the input and output streams. This matches the
  210. * functionality available with a standard TCP/IP connection, or a local
  211. * operating system or in-memory pipe.
  212. * <p>
  213. * If false, this class runs in a read everything then output results mode,
  214. * making it suitable for single round-trip systems RPCs such as HTTP.
  215. */
  216. private boolean biDirectionalPipe = true;
  217. /** Timer to manage {@link #timeout}. */
  218. private InterruptTimer timer;
  219. private InputStream rawIn;
  220. private ResponseBufferedOutputStream rawOut;
  221. private PacketLineIn pckIn;
  222. private PacketLineOut pckOut;
  223. private OutputStream msgOut = NullOutputStream.INSTANCE;
  224. /** The refs we advertised as existing at the start of the connection. */
  225. private Map<String, Ref> refs;
  226. /** Hook used while advertising the refs to the client. */
  227. private AdvertiseRefsHook advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  228. /** Filter used while advertising the refs to the client. */
  229. private RefFilter refFilter = RefFilter.DEFAULT;
  230. /** Hook handling the various upload phases. */
  231. private PreUploadHook preUploadHook = PreUploadHook.NULL;
  232. /** Hook for taking post upload actions. */
  233. private PostUploadHook postUploadHook = PostUploadHook.NULL;
  234. /** Capabilities requested by the client. */
  235. private Set<String> options;
  236. String userAgent;
  237. /** Raw ObjectIds the client has asked for, before validating them. */
  238. private final Set<ObjectId> wantIds = new HashSet<>();
  239. /** Objects the client wants to obtain. */
  240. private final Set<RevObject> wantAll = new HashSet<>();
  241. /** Objects on both sides, these don't have to be sent. */
  242. private final Set<RevObject> commonBase = new HashSet<>();
  243. /** Shallow commits the client already has. */
  244. private final Set<ObjectId> clientShallowCommits = new HashSet<>();
  245. /** Shallow commits on the client which are now becoming unshallow */
  246. private final List<ObjectId> unshallowCommits = new ArrayList<>();
  247. /** Desired depth from the client on a shallow request. */
  248. private int depth;
  249. /** Commit time of the oldest common commit, in seconds. */
  250. private int oldestTime;
  251. /** null if {@link #commonBase} should be examined again. */
  252. private Boolean okToGiveUp;
  253. private boolean sentReady;
  254. /** Objects we sent in our advertisement list, clients can ask for these. */
  255. private Set<ObjectId> advertised;
  256. /** Marked on objects the client has asked us to give them. */
  257. private final RevFlag WANT;
  258. /** Marked on objects both we and the client have. */
  259. private final RevFlag PEER_HAS;
  260. /** Marked on objects in {@link #commonBase}. */
  261. private final RevFlag COMMON;
  262. /** Objects where we found a path from the want list to a common base. */
  263. private final RevFlag SATISFIED;
  264. private final RevFlagSet SAVE;
  265. private RequestValidator requestValidator = new AdvertisedRequestValidator();
  266. private MultiAck multiAck = MultiAck.OFF;
  267. private boolean noDone;
  268. private PackStatistics statistics;
  269. @SuppressWarnings("deprecation")
  270. private UploadPackLogger logger = UploadPackLogger.NULL;
  271. /**
  272. * Create a new pack upload for an open repository.
  273. *
  274. * @param copyFrom
  275. * the source repository.
  276. */
  277. public UploadPack(final Repository copyFrom) {
  278. db = copyFrom;
  279. walk = new RevWalk(db);
  280. walk.setRetainBody(false);
  281. WANT = walk.newFlag("WANT"); //$NON-NLS-1$
  282. PEER_HAS = walk.newFlag("PEER_HAS"); //$NON-NLS-1$
  283. COMMON = walk.newFlag("COMMON"); //$NON-NLS-1$
  284. SATISFIED = walk.newFlag("SATISFIED"); //$NON-NLS-1$
  285. walk.carry(PEER_HAS);
  286. SAVE = new RevFlagSet();
  287. SAVE.add(WANT);
  288. SAVE.add(PEER_HAS);
  289. SAVE.add(COMMON);
  290. SAVE.add(SATISFIED);
  291. setTransferConfig(null);
  292. }
  293. /** @return the repository this upload is reading from. */
  294. public final Repository getRepository() {
  295. return db;
  296. }
  297. /** @return the RevWalk instance used by this connection. */
  298. public final RevWalk getRevWalk() {
  299. return walk;
  300. }
  301. /**
  302. * Get refs which were advertised to the client.
  303. *
  304. * @return all refs which were advertised to the client, or null if
  305. * {@link #setAdvertisedRefs(Map)} has not been called yet.
  306. */
  307. public final Map<String, Ref> getAdvertisedRefs() {
  308. return refs;
  309. }
  310. /**
  311. * Set the refs advertised by this UploadPack.
  312. * <p>
  313. * Intended to be called from a {@link PreUploadHook}.
  314. *
  315. * @param allRefs
  316. * explicit set of references to claim as advertised by this
  317. * UploadPack instance. This overrides any references that
  318. * may exist in the source repository. The map is passed
  319. * to the configured {@link #getRefFilter()}. If null, assumes
  320. * all refs were advertised.
  321. */
  322. public void setAdvertisedRefs(Map<String, Ref> allRefs) {
  323. if (allRefs != null)
  324. refs = allRefs;
  325. else
  326. refs = db.getAllRefs();
  327. if (refFilter == RefFilter.DEFAULT)
  328. refs = transferConfig.getRefFilter().filter(refs);
  329. else
  330. refs = refFilter.filter(refs);
  331. }
  332. /** @return timeout (in seconds) before aborting an IO operation. */
  333. public int getTimeout() {
  334. return timeout;
  335. }
  336. /**
  337. * Set the timeout before willing to abort an IO call.
  338. *
  339. * @param seconds
  340. * number of seconds to wait (with no data transfer occurring)
  341. * before aborting an IO read or write operation with the
  342. * connected client.
  343. */
  344. public void setTimeout(final int seconds) {
  345. timeout = seconds;
  346. }
  347. /**
  348. * @return true if this class expects a bi-directional pipe opened between
  349. * the client and itself. The default is true.
  350. */
  351. public boolean isBiDirectionalPipe() {
  352. return biDirectionalPipe;
  353. }
  354. /**
  355. * @param twoWay
  356. * if true, this class will assume the socket is a fully
  357. * bidirectional pipe between the two peers and takes advantage
  358. * of that by first transmitting the known refs, then waiting to
  359. * read commands. If false, this class assumes it must read the
  360. * commands before writing output and does not perform the
  361. * initial advertising.
  362. */
  363. public void setBiDirectionalPipe(final boolean twoWay) {
  364. biDirectionalPipe = twoWay;
  365. }
  366. /**
  367. * @return policy used by the service to validate client requests, or null for
  368. * a custom request validator.
  369. */
  370. public RequestPolicy getRequestPolicy() {
  371. if (requestValidator instanceof AdvertisedRequestValidator)
  372. return RequestPolicy.ADVERTISED;
  373. if (requestValidator instanceof ReachableCommitRequestValidator)
  374. return RequestPolicy.REACHABLE_COMMIT;
  375. if (requestValidator instanceof TipRequestValidator)
  376. return RequestPolicy.TIP;
  377. if (requestValidator instanceof ReachableCommitTipRequestValidator)
  378. return RequestPolicy.REACHABLE_COMMIT_TIP;
  379. if (requestValidator instanceof AnyRequestValidator)
  380. return RequestPolicy.ANY;
  381. return null;
  382. }
  383. /**
  384. * @param policy
  385. * the policy used to enforce validation of a client's want list.
  386. * By default the policy is {@link RequestPolicy#ADVERTISED},
  387. * which is the Git default requiring clients to only ask for an
  388. * object that a reference directly points to. This may be relaxed
  389. * to {@link RequestPolicy#REACHABLE_COMMIT} or
  390. * {@link RequestPolicy#REACHABLE_COMMIT_TIP} when callers have
  391. * {@link #setBiDirectionalPipe(boolean)} set to false.
  392. * Overrides any policy specified in a {@link TransferConfig}.
  393. */
  394. public void setRequestPolicy(RequestPolicy policy) {
  395. switch (policy) {
  396. case ADVERTISED:
  397. default:
  398. requestValidator = new AdvertisedRequestValidator();
  399. break;
  400. case REACHABLE_COMMIT:
  401. requestValidator = new ReachableCommitRequestValidator();
  402. break;
  403. case TIP:
  404. requestValidator = new TipRequestValidator();
  405. break;
  406. case REACHABLE_COMMIT_TIP:
  407. requestValidator = new ReachableCommitTipRequestValidator();
  408. break;
  409. case ANY:
  410. requestValidator = new AnyRequestValidator();
  411. break;
  412. }
  413. }
  414. /**
  415. * @param validator
  416. * custom validator for client want list.
  417. * @since 3.1
  418. */
  419. public void setRequestValidator(RequestValidator validator) {
  420. requestValidator = validator != null ? validator
  421. : new AdvertisedRequestValidator();
  422. }
  423. /** @return the hook used while advertising the refs to the client */
  424. public AdvertiseRefsHook getAdvertiseRefsHook() {
  425. return advertiseRefsHook;
  426. }
  427. /** @return the filter used while advertising the refs to the client */
  428. public RefFilter getRefFilter() {
  429. return refFilter;
  430. }
  431. /**
  432. * Set the hook used while advertising the refs to the client.
  433. * <p>
  434. * If the {@link AdvertiseRefsHook} chooses to call
  435. * {@link #setAdvertisedRefs(Map)}, only refs set by this hook <em>and</em>
  436. * selected by the {@link RefFilter} will be shown to the client.
  437. *
  438. * @param advertiseRefsHook
  439. * the hook; may be null to show all refs.
  440. */
  441. public void setAdvertiseRefsHook(final AdvertiseRefsHook advertiseRefsHook) {
  442. if (advertiseRefsHook != null)
  443. this.advertiseRefsHook = advertiseRefsHook;
  444. else
  445. this.advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  446. }
  447. /**
  448. * Set the filter used while advertising the refs to the client.
  449. * <p>
  450. * Only refs allowed by this filter will be sent to the client.
  451. * The filter is run against the refs specified by the
  452. * {@link AdvertiseRefsHook} (if applicable). If null or not set, uses the
  453. * filter implied by the {@link TransferConfig}.
  454. *
  455. * @param refFilter
  456. * the filter; may be null to show all refs.
  457. */
  458. public void setRefFilter(final RefFilter refFilter) {
  459. this.refFilter = refFilter != null ? refFilter : RefFilter.DEFAULT;
  460. }
  461. /** @return the configured pre upload hook. */
  462. public PreUploadHook getPreUploadHook() {
  463. return preUploadHook;
  464. }
  465. /**
  466. * Set the hook that controls how this instance will behave.
  467. *
  468. * @param hook
  469. * the hook; if null no special actions are taken.
  470. */
  471. public void setPreUploadHook(PreUploadHook hook) {
  472. preUploadHook = hook != null ? hook : PreUploadHook.NULL;
  473. }
  474. /**
  475. * @return the configured post upload hook.
  476. * @since 4.1
  477. */
  478. public PostUploadHook getPostUploadHook() {
  479. return postUploadHook;
  480. }
  481. /**
  482. * Set the hook for post upload actions (logging, repacking).
  483. *
  484. * @param hook
  485. * the hook; if null no special actions are taken.
  486. * @since 4.1
  487. */
  488. public void setPostUploadHook(PostUploadHook hook) {
  489. postUploadHook = hook != null ? hook : PostUploadHook.NULL;
  490. }
  491. /**
  492. * Set the configuration used by the pack generator.
  493. *
  494. * @param pc
  495. * configuration controlling packing parameters. If null the
  496. * source repository's settings will be used.
  497. */
  498. public void setPackConfig(PackConfig pc) {
  499. this.packConfig = pc;
  500. }
  501. /**
  502. * @param tc
  503. * configuration controlling transfer options. If null the source
  504. * repository's settings will be used.
  505. * @since 3.1
  506. */
  507. public void setTransferConfig(TransferConfig tc) {
  508. this.transferConfig = tc != null ? tc : new TransferConfig(db);
  509. if (transferConfig.isAllowTipSha1InWant()) {
  510. setRequestPolicy(transferConfig.isAllowReachableSha1InWant()
  511. ? RequestPolicy.REACHABLE_COMMIT_TIP : RequestPolicy.TIP);
  512. } else {
  513. setRequestPolicy(transferConfig.isAllowReachableSha1InWant()
  514. ? RequestPolicy.REACHABLE_COMMIT : RequestPolicy.ADVERTISED);
  515. }
  516. }
  517. /**
  518. * @return the configured logger.
  519. *
  520. * @deprecated Use {@link #getPreUploadHook()}.
  521. */
  522. @Deprecated
  523. public UploadPackLogger getLogger() {
  524. return logger;
  525. }
  526. /**
  527. * Set the logger.
  528. *
  529. * @param logger
  530. * the logger instance. If null, no logging occurs.
  531. * @deprecated Use {@link #setPreUploadHook(PreUploadHook)}.
  532. */
  533. @Deprecated
  534. public void setLogger(UploadPackLogger logger) {
  535. this.logger = logger;
  536. }
  537. /**
  538. * Check whether the client expects a side-band stream.
  539. *
  540. * @return true if the client has advertised a side-band capability, false
  541. * otherwise.
  542. * @throws RequestNotYetReadException
  543. * if the client's request has not yet been read from the wire, so
  544. * we do not know if they expect side-band. Note that the client
  545. * may have already written the request, it just has not been
  546. * read.
  547. */
  548. public boolean isSideBand() throws RequestNotYetReadException {
  549. if (options == null)
  550. throw new RequestNotYetReadException();
  551. return (options.contains(OPTION_SIDE_BAND)
  552. || options.contains(OPTION_SIDE_BAND_64K));
  553. }
  554. /**
  555. * Execute the upload task on the socket.
  556. *
  557. * @param input
  558. * raw input to read client commands from. Caller must ensure the
  559. * input is buffered, otherwise read performance may suffer.
  560. * @param output
  561. * response back to the Git network client, to write the pack
  562. * data onto. Caller must ensure the output is buffered,
  563. * otherwise write performance may suffer.
  564. * @param messages
  565. * secondary "notice" channel to send additional messages out
  566. * through. When run over SSH this should be tied back to the
  567. * standard error channel of the command execution. For most
  568. * other network connections this should be null.
  569. * @throws IOException
  570. */
  571. public void upload(final InputStream input, OutputStream output,
  572. final OutputStream messages) throws IOException {
  573. try {
  574. rawIn = input;
  575. if (messages != null)
  576. msgOut = messages;
  577. if (timeout > 0) {
  578. final Thread caller = Thread.currentThread();
  579. timer = new InterruptTimer(caller.getName() + "-Timer"); //$NON-NLS-1$
  580. TimeoutInputStream i = new TimeoutInputStream(rawIn, timer);
  581. @SuppressWarnings("resource")
  582. TimeoutOutputStream o = new TimeoutOutputStream(output, timer);
  583. i.setTimeout(timeout * 1000);
  584. o.setTimeout(timeout * 1000);
  585. rawIn = i;
  586. output = o;
  587. }
  588. rawOut = new ResponseBufferedOutputStream(output);
  589. if (biDirectionalPipe) {
  590. rawOut.stopBuffering();
  591. }
  592. pckIn = new PacketLineIn(rawIn);
  593. pckOut = new PacketLineOut(rawOut);
  594. service();
  595. } finally {
  596. msgOut = NullOutputStream.INSTANCE;
  597. walk.close();
  598. if (timer != null) {
  599. try {
  600. timer.terminate();
  601. } finally {
  602. timer = null;
  603. }
  604. }
  605. }
  606. }
  607. /**
  608. * Get the PackWriter's statistics if a pack was sent to the client.
  609. *
  610. * @return statistics about pack output, if a pack was sent. Null if no pack
  611. * was sent, such as during the negotiation phase of a smart HTTP
  612. * connection, or if the client was already up-to-date.
  613. * @since 3.0
  614. * @deprecated Use {@link #getStatistics()}.
  615. */
  616. @Deprecated
  617. public PackWriter.Statistics getPackStatistics() {
  618. return statistics == null ? null
  619. : new PackWriter.Statistics(statistics);
  620. }
  621. /**
  622. * Get the PackWriter's statistics if a pack was sent to the client.
  623. *
  624. * @return statistics about pack output, if a pack was sent. Null if no pack
  625. * was sent, such as during the negotiation phase of a smart HTTP
  626. * connection, or if the client was already up-to-date.
  627. * @since 4.1
  628. */
  629. public PackStatistics getStatistics() {
  630. return statistics;
  631. }
  632. private Map<String, Ref> getAdvertisedOrDefaultRefs() throws IOException {
  633. if (refs == null)
  634. setAdvertisedRefs(db.getRefDatabase().getRefs(RefDatabase.ALL));
  635. return refs;
  636. }
  637. private void service() throws IOException {
  638. boolean sendPack = false;
  639. // If it's a non-bidi request, we need to read the entire request before
  640. // writing a response. Buffer the response until then.
  641. try {
  642. if (biDirectionalPipe)
  643. sendAdvertisedRefs(new PacketLineOutRefAdvertiser(pckOut));
  644. else if (requestValidator instanceof AnyRequestValidator)
  645. advertised = Collections.emptySet();
  646. else
  647. advertised = refIdSet(getAdvertisedOrDefaultRefs().values());
  648. recvWants();
  649. if (wantIds.isEmpty()) {
  650. preUploadHook.onBeginNegotiateRound(this, wantIds, 0);
  651. preUploadHook.onEndNegotiateRound(this, wantIds, 0, 0, false);
  652. return;
  653. }
  654. if (options.contains(OPTION_MULTI_ACK_DETAILED)) {
  655. multiAck = MultiAck.DETAILED;
  656. noDone = options.contains(OPTION_NO_DONE);
  657. } else if (options.contains(OPTION_MULTI_ACK))
  658. multiAck = MultiAck.CONTINUE;
  659. else
  660. multiAck = MultiAck.OFF;
  661. if (!clientShallowCommits.isEmpty())
  662. verifyClientShallow();
  663. if (depth != 0)
  664. processShallow();
  665. if (!clientShallowCommits.isEmpty())
  666. walk.assumeShallow(clientShallowCommits);
  667. sendPack = negotiate();
  668. if (sendPack && !biDirectionalPipe) {
  669. // Ensure the request was fully consumed. Any remaining input must
  670. // be a protocol error. If we aren't at EOF the implementation is broken.
  671. int eof = rawIn.read();
  672. if (0 <= eof) {
  673. sendPack = false;
  674. throw new CorruptObjectException(MessageFormat.format(
  675. JGitText.get().expectedEOFReceived,
  676. "\\x" + Integer.toHexString(eof))); //$NON-NLS-1$
  677. }
  678. }
  679. } catch (ServiceMayNotContinueException err) {
  680. if (!err.isOutput() && err.getMessage() != null) {
  681. try {
  682. pckOut.writeString("ERR " + err.getMessage() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  683. err.setOutput();
  684. } catch (Throwable err2) {
  685. // Ignore this secondary failure (and not mark output).
  686. }
  687. }
  688. throw err;
  689. } catch (IOException | RuntimeException | Error err) {
  690. boolean output = false;
  691. try {
  692. String msg = err instanceof PackProtocolException
  693. ? err.getMessage()
  694. : JGitText.get().internalServerError;
  695. pckOut.writeString("ERR " + msg + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  696. output = true;
  697. } catch (Throwable err2) {
  698. // Ignore this secondary failure, leave output false.
  699. }
  700. if (output) {
  701. throw new UploadPackInternalServerErrorException(err);
  702. }
  703. throw err;
  704. } finally {
  705. if (!sendPack && !biDirectionalPipe) {
  706. while (0 < rawIn.skip(2048) || 0 <= rawIn.read()) {
  707. // Discard until EOF.
  708. }
  709. }
  710. rawOut.stopBuffering();
  711. }
  712. if (sendPack)
  713. sendPack();
  714. }
  715. private static Set<ObjectId> refIdSet(Collection<Ref> refs) {
  716. Set<ObjectId> ids = new HashSet<>(refs.size());
  717. for (Ref ref : refs) {
  718. ObjectId id = ref.getObjectId();
  719. if (id != null) {
  720. ids.add(id);
  721. }
  722. id = ref.getPeeledObjectId();
  723. if (id != null) {
  724. ids.add(id);
  725. }
  726. }
  727. return ids;
  728. }
  729. private void processShallow() throws IOException {
  730. int walkDepth = depth - 1;
  731. try (DepthWalk.RevWalk depthWalk = new DepthWalk.RevWalk(
  732. walk.getObjectReader(), walkDepth)) {
  733. // Find all the commits which will be shallow
  734. for (ObjectId o : wantIds) {
  735. try {
  736. depthWalk.markRoot(depthWalk.parseCommit(o));
  737. } catch (IncorrectObjectTypeException notCommit) {
  738. // Ignore non-commits in this loop.
  739. }
  740. }
  741. RevCommit o;
  742. while ((o = depthWalk.next()) != null) {
  743. DepthWalk.Commit c = (DepthWalk.Commit) o;
  744. // Commits at the boundary which aren't already shallow in
  745. // the client need to be marked as such
  746. if (c.getDepth() == walkDepth
  747. && !clientShallowCommits.contains(c))
  748. pckOut.writeString("shallow " + o.name()); //$NON-NLS-1$
  749. // Commits not on the boundary which are shallow in the client
  750. // need to become unshallowed
  751. if (c.getDepth() < walkDepth
  752. && clientShallowCommits.remove(c)) {
  753. unshallowCommits.add(c.copy());
  754. pckOut.writeString("unshallow " + c.name()); //$NON-NLS-1$
  755. }
  756. }
  757. }
  758. pckOut.end();
  759. }
  760. private void verifyClientShallow()
  761. throws IOException, PackProtocolException {
  762. AsyncRevObjectQueue q = walk.parseAny(clientShallowCommits, true);
  763. try {
  764. for (;;) {
  765. try {
  766. // Shallow objects named by the client must be commits.
  767. RevObject o = q.next();
  768. if (o == null) {
  769. break;
  770. }
  771. if (!(o instanceof RevCommit)) {
  772. throw new PackProtocolException(
  773. MessageFormat.format(
  774. JGitText.get().invalidShallowObject,
  775. o.name()));
  776. }
  777. } catch (MissingObjectException notCommit) {
  778. // shallow objects not known at the server are ignored
  779. // by git-core upload-pack, match that behavior.
  780. clientShallowCommits.remove(notCommit.getObjectId());
  781. continue;
  782. }
  783. }
  784. } finally {
  785. q.release();
  786. }
  787. }
  788. /**
  789. * Generate an advertisement of available refs and capabilities.
  790. *
  791. * @param adv
  792. * the advertisement formatter.
  793. * @throws IOException
  794. * the formatter failed to write an advertisement.
  795. * @throws ServiceMayNotContinueException
  796. * the hook denied advertisement.
  797. */
  798. public void sendAdvertisedRefs(final RefAdvertiser adv) throws IOException,
  799. ServiceMayNotContinueException {
  800. try {
  801. advertiseRefsHook.advertiseRefs(this);
  802. } catch (ServiceMayNotContinueException fail) {
  803. if (fail.getMessage() != null) {
  804. adv.writeOne("ERR " + fail.getMessage()); //$NON-NLS-1$
  805. fail.setOutput();
  806. }
  807. throw fail;
  808. }
  809. adv.init(db);
  810. adv.advertiseCapability(OPTION_INCLUDE_TAG);
  811. adv.advertiseCapability(OPTION_MULTI_ACK_DETAILED);
  812. adv.advertiseCapability(OPTION_MULTI_ACK);
  813. adv.advertiseCapability(OPTION_OFS_DELTA);
  814. adv.advertiseCapability(OPTION_SIDE_BAND);
  815. adv.advertiseCapability(OPTION_SIDE_BAND_64K);
  816. adv.advertiseCapability(OPTION_THIN_PACK);
  817. adv.advertiseCapability(OPTION_NO_PROGRESS);
  818. adv.advertiseCapability(OPTION_SHALLOW);
  819. if (!biDirectionalPipe)
  820. adv.advertiseCapability(OPTION_NO_DONE);
  821. RequestPolicy policy = getRequestPolicy();
  822. if (policy == RequestPolicy.TIP
  823. || policy == RequestPolicy.REACHABLE_COMMIT_TIP
  824. || policy == null)
  825. adv.advertiseCapability(OPTION_ALLOW_TIP_SHA1_IN_WANT);
  826. if (policy == RequestPolicy.REACHABLE_COMMIT
  827. || policy == RequestPolicy.REACHABLE_COMMIT_TIP
  828. || policy == null)
  829. adv.advertiseCapability(OPTION_ALLOW_REACHABLE_SHA1_IN_WANT);
  830. adv.advertiseCapability(OPTION_AGENT, UserAgent.get());
  831. adv.setDerefTags(true);
  832. Map<String, Ref> advertisedOrDefaultRefs = getAdvertisedOrDefaultRefs();
  833. findSymrefs(adv, advertisedOrDefaultRefs);
  834. advertised = adv.send(advertisedOrDefaultRefs);
  835. if (adv.isEmpty())
  836. adv.advertiseId(ObjectId.zeroId(), "capabilities^{}"); //$NON-NLS-1$
  837. adv.end();
  838. }
  839. /**
  840. * Send a message to the client, if it supports receiving them.
  841. * <p>
  842. * If the client doesn't support receiving messages, the message will be
  843. * discarded, with no other indication to the caller or to the client.
  844. *
  845. * @param what
  846. * string describing the problem identified by the hook. The
  847. * string must not end with an LF, and must not contain an LF.
  848. * @since 3.1
  849. */
  850. public void sendMessage(String what) {
  851. try {
  852. msgOut.write(Constants.encode(what + "\n")); //$NON-NLS-1$
  853. } catch (IOException e) {
  854. // Ignore write failures.
  855. }
  856. }
  857. /**
  858. * @return an underlying stream for sending messages to the client, or null.
  859. * @since 3.1
  860. */
  861. public OutputStream getMessageOutputStream() {
  862. return msgOut;
  863. }
  864. private void recvWants() throws IOException {
  865. boolean isFirst = true;
  866. for (;;) {
  867. String line;
  868. try {
  869. line = pckIn.readString();
  870. } catch (EOFException eof) {
  871. if (isFirst)
  872. break;
  873. throw eof;
  874. }
  875. if (line == PacketLineIn.END)
  876. break;
  877. if (line.startsWith("deepen ")) { //$NON-NLS-1$
  878. depth = Integer.parseInt(line.substring(7));
  879. if (depth <= 0) {
  880. throw new PackProtocolException(
  881. MessageFormat.format(JGitText.get().invalidDepth,
  882. Integer.valueOf(depth)));
  883. }
  884. continue;
  885. }
  886. if (line.startsWith("shallow ")) { //$NON-NLS-1$
  887. clientShallowCommits.add(ObjectId.fromString(line.substring(8)));
  888. continue;
  889. }
  890. if (!line.startsWith("want ") || line.length() < 45) //$NON-NLS-1$
  891. throw new PackProtocolException(MessageFormat.format(JGitText.get().expectedGot, "want", line)); //$NON-NLS-1$
  892. if (isFirst) {
  893. if (line.length() > 45) {
  894. FirstLine firstLine = new FirstLine(line);
  895. options = firstLine.getOptions();
  896. line = firstLine.getLine();
  897. } else
  898. options = Collections.emptySet();
  899. }
  900. wantIds.add(ObjectId.fromString(line.substring(5)));
  901. isFirst = false;
  902. }
  903. }
  904. /**
  905. * Returns the clone/fetch depth. Valid only after calling recvWants(). A
  906. * depth of 1 means return only the wants.
  907. *
  908. * @return the depth requested by the client, or 0 if unbounded.
  909. * @since 4.0
  910. */
  911. public int getDepth() {
  912. if (options == null)
  913. throw new RequestNotYetReadException();
  914. return depth;
  915. }
  916. /**
  917. * Get the user agent of the client.
  918. * <p>
  919. * If the client is new enough to use {@code agent=} capability that value
  920. * will be returned. Older HTTP clients may also supply their version using
  921. * the HTTP {@code User-Agent} header. The capability overrides the HTTP
  922. * header if both are available.
  923. * <p>
  924. * When an HTTP request has been received this method returns the HTTP
  925. * {@code User-Agent} header value until capabilities have been parsed.
  926. *
  927. * @return user agent supplied by the client. Available only if the client
  928. * is new enough to advertise its user agent.
  929. * @since 4.0
  930. */
  931. public String getPeerUserAgent() {
  932. return UserAgent.getAgent(options, userAgent);
  933. }
  934. private boolean negotiate() throws IOException {
  935. okToGiveUp = Boolean.FALSE;
  936. ObjectId last = ObjectId.zeroId();
  937. List<ObjectId> peerHas = new ArrayList<>(64);
  938. for (;;) {
  939. String line;
  940. try {
  941. line = pckIn.readString();
  942. } catch (EOFException eof) {
  943. // EOF on stateless RPC (aka smart HTTP) and non-shallow request
  944. // means the client asked for the updated shallow/unshallow data,
  945. // disconnected, and will try another request with actual want/have.
  946. // Don't report the EOF here, its a bug in the protocol that the client
  947. // just disconnects without sending an END.
  948. if (!biDirectionalPipe && depth > 0)
  949. return false;
  950. throw eof;
  951. }
  952. if (line == PacketLineIn.END) {
  953. last = processHaveLines(peerHas, last);
  954. if (commonBase.isEmpty() || multiAck != MultiAck.OFF)
  955. pckOut.writeString("NAK\n"); //$NON-NLS-1$
  956. if (noDone && sentReady) {
  957. pckOut.writeString("ACK " + last.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  958. return true;
  959. }
  960. if (!biDirectionalPipe)
  961. return false;
  962. pckOut.flush();
  963. } else if (line.startsWith("have ") && line.length() == 45) { //$NON-NLS-1$
  964. peerHas.add(ObjectId.fromString(line.substring(5)));
  965. } else if (line.equals("done")) { //$NON-NLS-1$
  966. last = processHaveLines(peerHas, last);
  967. if (commonBase.isEmpty())
  968. pckOut.writeString("NAK\n"); //$NON-NLS-1$
  969. else if (multiAck != MultiAck.OFF)
  970. pckOut.writeString("ACK " + last.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  971. return true;
  972. } else {
  973. throw new PackProtocolException(MessageFormat.format(JGitText.get().expectedGot, "have", line)); //$NON-NLS-1$
  974. }
  975. }
  976. }
  977. private ObjectId processHaveLines(List<ObjectId> peerHas, ObjectId last)
  978. throws IOException {
  979. preUploadHook.onBeginNegotiateRound(this, wantIds, peerHas.size());
  980. if (wantAll.isEmpty() && !wantIds.isEmpty())
  981. parseWants();
  982. if (peerHas.isEmpty())
  983. return last;
  984. sentReady = false;
  985. int haveCnt = 0;
  986. walk.getObjectReader().setAvoidUnreachableObjects(true);
  987. AsyncRevObjectQueue q = walk.parseAny(peerHas, false);
  988. try {
  989. for (;;) {
  990. RevObject obj;
  991. try {
  992. obj = q.next();
  993. } catch (MissingObjectException notFound) {
  994. continue;
  995. }
  996. if (obj == null)
  997. break;
  998. last = obj;
  999. haveCnt++;
  1000. if (obj instanceof RevCommit) {
  1001. RevCommit c = (RevCommit) obj;
  1002. if (oldestTime == 0 || c.getCommitTime() < oldestTime)
  1003. oldestTime = c.getCommitTime();
  1004. }
  1005. if (obj.has(PEER_HAS))
  1006. continue;
  1007. obj.add(PEER_HAS);
  1008. if (obj instanceof RevCommit)
  1009. ((RevCommit) obj).carry(PEER_HAS);
  1010. addCommonBase(obj);
  1011. // If both sides have the same object; let the client know.
  1012. //
  1013. switch (multiAck) {
  1014. case OFF:
  1015. if (commonBase.size() == 1)
  1016. pckOut.writeString("ACK " + obj.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1017. break;
  1018. case CONTINUE:
  1019. pckOut.writeString("ACK " + obj.name() + " continue\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1020. break;
  1021. case DETAILED:
  1022. pckOut.writeString("ACK " + obj.name() + " common\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1023. break;
  1024. }
  1025. }
  1026. } finally {
  1027. q.release();
  1028. walk.getObjectReader().setAvoidUnreachableObjects(false);
  1029. }
  1030. int missCnt = peerHas.size() - haveCnt;
  1031. // If we don't have one of the objects but we're also willing to
  1032. // create a pack at this point, let the client know so it stops
  1033. // telling us about its history.
  1034. //
  1035. boolean didOkToGiveUp = false;
  1036. if (0 < missCnt) {
  1037. for (int i = peerHas.size() - 1; i >= 0; i--) {
  1038. ObjectId id = peerHas.get(i);
  1039. if (walk.lookupOrNull(id) == null) {
  1040. didOkToGiveUp = true;
  1041. if (okToGiveUp()) {
  1042. switch (multiAck) {
  1043. case OFF:
  1044. break;
  1045. case CONTINUE:
  1046. pckOut.writeString("ACK " + id.name() + " continue\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1047. break;
  1048. case DETAILED:
  1049. pckOut.writeString("ACK " + id.name() + " ready\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1050. sentReady = true;
  1051. break;
  1052. }
  1053. }
  1054. break;
  1055. }
  1056. }
  1057. }
  1058. if (multiAck == MultiAck.DETAILED && !didOkToGiveUp && okToGiveUp()) {
  1059. ObjectId id = peerHas.get(peerHas.size() - 1);
  1060. pckOut.writeString("ACK " + id.name() + " ready\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1061. sentReady = true;
  1062. }
  1063. preUploadHook.onEndNegotiateRound(this, wantAll, haveCnt, missCnt, sentReady);
  1064. peerHas.clear();
  1065. return last;
  1066. }
  1067. private void parseWants() throws IOException {
  1068. List<ObjectId> notAdvertisedWants = null;
  1069. for (ObjectId obj : wantIds) {
  1070. if (!advertised.contains(obj)) {
  1071. if (notAdvertisedWants == null)
  1072. notAdvertisedWants = new ArrayList<>();
  1073. notAdvertisedWants.add(obj);
  1074. }
  1075. }
  1076. if (notAdvertisedWants != null)
  1077. requestValidator.checkWants(this, notAdvertisedWants);
  1078. AsyncRevObjectQueue q = walk.parseAny(wantIds, true);
  1079. try {
  1080. RevObject obj;
  1081. while ((obj = q.next()) != null) {
  1082. want(obj);
  1083. if (!(obj instanceof RevCommit))
  1084. obj.add(SATISFIED);
  1085. if (obj instanceof RevTag) {
  1086. obj = walk.peel(obj);
  1087. if (obj instanceof RevCommit)
  1088. want(obj);
  1089. }
  1090. }
  1091. wantIds.clear();
  1092. } catch (MissingObjectException notFound) {
  1093. throw new WantNotValidException(notFound.getObjectId(), notFound);
  1094. } finally {
  1095. q.release();
  1096. }
  1097. }
  1098. private void want(RevObject obj) {
  1099. if (!obj.has(WANT)) {
  1100. obj.add(WANT);
  1101. wantAll.add(obj);
  1102. }
  1103. }
  1104. /**
  1105. * Validator corresponding to {@link RequestPolicy#ADVERTISED}.
  1106. *
  1107. * @since 3.1
  1108. */
  1109. public static final class AdvertisedRequestValidator
  1110. implements RequestValidator {
  1111. @Override
  1112. public void checkWants(UploadPack up, List<ObjectId> wants)
  1113. throws PackProtocolException, IOException {
  1114. if (!up.isBiDirectionalPipe())
  1115. new ReachableCommitRequestValidator().checkWants(up, wants);
  1116. else if (!wants.isEmpty())
  1117. throw new WantNotValidException(wants.iterator().next());
  1118. }
  1119. }
  1120. /**
  1121. * Validator corresponding to {@link RequestPolicy#REACHABLE_COMMIT}.
  1122. *
  1123. * @since 3.1
  1124. */
  1125. public static final class ReachableCommitRequestValidator
  1126. implements RequestValidator {
  1127. @Override
  1128. public void checkWants(UploadPack up, List<ObjectId> wants)
  1129. throws PackProtocolException, IOException {
  1130. checkNotAdvertisedWants(up, wants,
  1131. refIdSet(up.getAdvertisedRefs().values()));
  1132. }
  1133. }
  1134. /**
  1135. * Validator corresponding to {@link RequestPolicy#TIP}.
  1136. *
  1137. * @since 3.1
  1138. */
  1139. public static final class TipRequestValidator implements RequestValidator {
  1140. @Override
  1141. public void checkWants(UploadPack up, List<ObjectId> wants)
  1142. throws PackProtocolException, IOException {
  1143. if (!up.isBiDirectionalPipe())
  1144. new ReachableCommitTipRequestValidator().checkWants(up, wants);
  1145. else if (!wants.isEmpty()) {
  1146. Set<ObjectId> refIds =
  1147. refIdSet(up.getRepository().getRefDatabase().getRefs(ALL).values());
  1148. for (ObjectId obj : wants) {
  1149. if (!refIds.contains(obj))
  1150. throw new WantNotValidException(obj);
  1151. }
  1152. }
  1153. }
  1154. }
  1155. /**
  1156. * Validator corresponding to {@link RequestPolicy#REACHABLE_COMMIT_TIP}.
  1157. *
  1158. * @since 3.1
  1159. */
  1160. public static final class ReachableCommitTipRequestValidator
  1161. implements RequestValidator {
  1162. @Override
  1163. public void checkWants(UploadPack up, List<ObjectId> wants)
  1164. throws PackProtocolException, IOException {
  1165. checkNotAdvertisedWants(up, wants,
  1166. refIdSet(up.getRepository().getRefDatabase().getRefs(ALL).values()));
  1167. }
  1168. }
  1169. /**
  1170. * Validator corresponding to {@link RequestPolicy#ANY}.
  1171. *
  1172. * @since 3.1
  1173. */
  1174. public static final class AnyRequestValidator implements RequestValidator {
  1175. @Override
  1176. public void checkWants(UploadPack up, List<ObjectId> wants)
  1177. throws PackProtocolException, IOException {
  1178. // All requests are valid.
  1179. }
  1180. }
  1181. private static void checkNotAdvertisedWantsUsingBitmap(ObjectReader reader,
  1182. BitmapIndex bitmapIndex, List<ObjectId> notAdvertisedWants,
  1183. Set<ObjectId> reachableFrom) throws IOException {
  1184. BitmapWalker bitmapWalker = new BitmapWalker(new ObjectWalk(reader), bitmapIndex, null);
  1185. BitmapBuilder reachables = bitmapWalker.findObjects(reachableFrom, null, false);
  1186. for (ObjectId oid : notAdvertisedWants) {
  1187. if (!reachables.contains(oid)) {
  1188. throw new WantNotValidException(oid);
  1189. }
  1190. }
  1191. }
  1192. private static void checkNotAdvertisedWants(UploadPack up,
  1193. List<ObjectId> notAdvertisedWants, Set<ObjectId> reachableFrom)
  1194. throws MissingObjectException, IncorrectObjectTypeException, IOException {
  1195. // Walk the requested commits back to the provided set of commits. If any
  1196. // commit exists, a branch was deleted or rewound and the repository owner
  1197. // no longer exports that requested item. If the requested commit is merged
  1198. // into an advertised branch it will be marked UNINTERESTING and no commits
  1199. // return.
  1200. ObjectReader reader = up.getRevWalk().getObjectReader();
  1201. try (RevWalk walk = new RevWalk(reader)) {
  1202. AsyncRevObjectQueue q = walk.parseAny(notAdvertisedWants, true);
  1203. try {
  1204. RevObject obj;
  1205. while ((obj = q.next()) != null) {
  1206. if (!(obj instanceof RevCommit)) {
  1207. // If unadvertized non-commits are requested, use
  1208. // bitmaps. If there are no bitmaps, instead of
  1209. // incurring the expense of a manual walk, reject
  1210. // the request.
  1211. BitmapIndex bitmapIndex = reader.getBitmapIndex();
  1212. if (bitmapIndex != null) {
  1213. checkNotAdvertisedWantsUsingBitmap(
  1214. reader,
  1215. bitmapIndex,
  1216. notAdvertisedWants,
  1217. reachableFrom);
  1218. return;
  1219. }
  1220. throw new WantNotValidException(obj);
  1221. }
  1222. walk.markStart((RevCommit) obj);
  1223. }
  1224. } catch (MissingObjectException notFound) {
  1225. throw new WantNotValidException(notFound.getObjectId(),
  1226. notFound);
  1227. } finally {
  1228. q.release();
  1229. }
  1230. for (ObjectId id : reachableFrom) {
  1231. try {
  1232. walk.markUninteresting(walk.parseCommit(id));
  1233. } catch (IncorrectObjectTypeException notCommit) {
  1234. continue;
  1235. }
  1236. }
  1237. RevCommit bad = walk.next();
  1238. if (bad != null) {
  1239. throw new WantNotValidException(bad);
  1240. }
  1241. }
  1242. }
  1243. private void addCommonBase(final RevObject o) {
  1244. if (!o.has(COMMON)) {
  1245. o.add(COMMON);
  1246. commonBase.add(o);
  1247. okToGiveUp = null;
  1248. }
  1249. }
  1250. private boolean okToGiveUp() throws PackProtocolException {
  1251. if (okToGiveUp == null)
  1252. okToGiveUp = Boolean.valueOf(okToGiveUpImp());
  1253. return okToGiveUp.booleanValue();
  1254. }
  1255. private boolean okToGiveUpImp() throws PackProtocolException {
  1256. if (commonBase.isEmpty())
  1257. return false;
  1258. try {
  1259. for (RevObject obj : wantAll) {
  1260. if (!wantSatisfied(obj))
  1261. return false;
  1262. }
  1263. return true;
  1264. } catch (IOException e) {
  1265. throw new PackProtocolException(JGitText.get().internalRevisionError, e);
  1266. }
  1267. }
  1268. private boolean wantSatisfied(final RevObject want) throws IOException {
  1269. if (want.has(SATISFIED))
  1270. return true;
  1271. walk.resetRetain(SAVE);
  1272. walk.markStart((RevCommit) want);
  1273. if (oldestTime != 0)
  1274. walk.setRevFilter(CommitTimeRevFilter.after(oldestTime * 1000L));
  1275. for (;;) {
  1276. final RevCommit c = walk.next();
  1277. if (c == null)
  1278. break;
  1279. if (c.has(PEER_HAS)) {
  1280. addCommonBase(c);
  1281. want.add(SATISFIED);
  1282. return true;
  1283. }
  1284. }
  1285. return false;
  1286. }
  1287. private void sendPack() throws IOException {
  1288. final boolean sideband = options.contains(OPTION_SIDE_BAND)
  1289. || options.contains(OPTION_SIDE_BAND_64K);
  1290. if (sideband) {
  1291. try {
  1292. sendPack(true);
  1293. } catch (ServiceMayNotContinueException noPack) {
  1294. // This was already reported on (below).
  1295. throw noPack;
  1296. } catch (IOException err) {
  1297. if (reportInternalServerErrorOverSideband())
  1298. throw new UploadPackInternalServerErrorException(err);
  1299. else
  1300. throw err;
  1301. } catch (RuntimeException err) {
  1302. if (reportInternalServerErrorOverSideband())
  1303. throw new UploadPackInternalServerErrorException(err);
  1304. else
  1305. throw err;
  1306. } catch (Error err) {
  1307. if (reportInternalServerErrorOverSideband())
  1308. throw new UploadPackInternalServerErrorException(err);
  1309. else
  1310. throw err;
  1311. }
  1312. } else {
  1313. sendPack(false);
  1314. }
  1315. }
  1316. private boolean reportInternalServerErrorOverSideband() {
  1317. try {
  1318. @SuppressWarnings("resource" /* java 7 */)
  1319. SideBandOutputStream err = new SideBandOutputStream(
  1320. SideBandOutputStream.CH_ERROR,
  1321. SideBandOutputStream.SMALL_BUF,
  1322. rawOut);
  1323. err.write(Constants.encode(JGitText.get().internalServerError));
  1324. err.flush();
  1325. return true;
  1326. } catch (Throwable cannotReport) {
  1327. // Ignore the reason. This is a secondary failure.
  1328. return false;
  1329. }
  1330. }
  1331. @SuppressWarnings("deprecation")
  1332. private void sendPack(final boolean sideband) throws IOException {
  1333. ProgressMonitor pm = NullProgressMonitor.INSTANCE;
  1334. OutputStream packOut = rawOut;
  1335. if (sideband) {
  1336. int bufsz = SideBandOutputStream.SMALL_BUF;
  1337. if (options.contains(OPTION_SIDE_BAND_64K))
  1338. bufsz = SideBandOutputStream.MAX_BUF;
  1339. packOut = new SideBandOutputStream(SideBandOutputStream.CH_DATA,
  1340. bufsz, rawOut);
  1341. if (!options.contains(OPTION_NO_PROGRESS)) {
  1342. msgOut = new SideBandOutputStream(
  1343. SideBandOutputStream.CH_PROGRESS, bufsz, rawOut);
  1344. pm = new SideBandProgressMonitor(msgOut);
  1345. }
  1346. }
  1347. try {
  1348. if (wantAll.isEmpty()) {
  1349. preUploadHook.onSendPack(this, wantIds, commonBase);
  1350. } else {
  1351. preUploadHook.onSendPack(this, wantAll, commonBase);
  1352. }
  1353. msgOut.flush();
  1354. } catch (ServiceMayNotContinueException noPack) {
  1355. if (sideband && noPack.getMessage() != null) {
  1356. noPack.setOutput();
  1357. @SuppressWarnings("resource" /* java 7 */)
  1358. SideBandOutputStream err = new SideBandOutputStream(
  1359. SideBandOutputStream.CH_ERROR,
  1360. SideBandOutputStream.SMALL_BUF, rawOut);
  1361. err.write(Constants.encode(noPack.getMessage()));
  1362. err.flush();
  1363. }
  1364. throw noPack;
  1365. }
  1366. PackConfig cfg = packConfig;
  1367. if (cfg == null)
  1368. cfg = new PackConfig(db);
  1369. final PackWriter pw = new PackWriter(cfg, walk.getObjectReader());
  1370. try {
  1371. pw.setIndexDisabled(true);
  1372. pw.setUseCachedPacks(true);
  1373. pw.setUseBitmaps(depth == 0 && clientShallowCommits.isEmpty());
  1374. pw.setClientShallowCommits(clientShallowCommits);
  1375. pw.setReuseDeltaCommits(true);
  1376. pw.setDeltaBaseAsOffset(options.contains(OPTION_OFS_DELTA));
  1377. pw.setThin(options.contains(OPTION_THIN_PACK));
  1378. pw.setReuseValidatingObjects(false);
  1379. if (commonBase.isEmpty() && refs != null) {
  1380. Set<ObjectId> tagTargets = new HashSet<>();
  1381. for (Ref ref : refs.values()) {
  1382. if (ref.getPeeledObjectId() != null)
  1383. tagTargets.add(ref.getPeeledObjectId());
  1384. else if (ref.getObjectId() == null)
  1385. continue;
  1386. else if (ref.getName().startsWith(Constants.R_HEADS))
  1387. tagTargets.add(ref.getObjectId());
  1388. }
  1389. pw.setTagTargets(tagTargets);
  1390. }
  1391. RevWalk rw = walk;
  1392. if (depth > 0) {
  1393. pw.setShallowPack(depth, unshallowCommits);
  1394. rw = new DepthWalk.RevWalk(walk.getObjectReader(), depth - 1);
  1395. rw.assumeShallow(clientShallowCommits);
  1396. }
  1397. if (wantAll.isEmpty()) {
  1398. pw.preparePack(pm, wantIds, commonBase, clientShallowCommits);
  1399. } else {
  1400. walk.reset();
  1401. ObjectWalk ow = rw.toObjectWalkWithSameObjects();
  1402. pw.preparePack(pm, ow, wantAll, commonBase, PackWriter.NONE);
  1403. rw = ow;
  1404. }
  1405. if (options.contains(OPTION_INCLUDE_TAG) && refs != null) {
  1406. for (Ref ref : refs.values()) {
  1407. ObjectId objectId = ref.getObjectId();
  1408. // If the object was already requested, skip it.
  1409. if (wantAll.isEmpty()) {
  1410. if (wantIds.contains(objectId))
  1411. continue;
  1412. } else {
  1413. RevObject obj = rw.lookupOrNull(objectId);
  1414. if (obj != null && obj.has(WANT))
  1415. continue;
  1416. }
  1417. if (!ref.isPeeled())
  1418. ref = db.peel(ref);
  1419. ObjectId peeledId = ref.getPeeledObjectId();
  1420. if (peeledId == null)
  1421. continue;
  1422. objectId = ref.getObjectId();
  1423. if (pw.willInclude(peeledId) && !pw.willInclude(objectId))
  1424. pw.addObject(rw.parseAny(objectId));
  1425. }
  1426. }
  1427. pw.writePack(pm, NullProgressMonitor.INSTANCE, packOut);
  1428. if (msgOut != NullOutputStream.INSTANCE) {
  1429. String msg = pw.getStatistics().getMessage() + '\n';
  1430. msgOut.write(Constants.encode(msg));
  1431. msgOut.flush();
  1432. }
  1433. } finally {
  1434. statistics = pw.getStatistics();
  1435. if (statistics != null) {
  1436. postUploadHook.onPostUpload(statistics);
  1437. logger.onPackStatistics(new PackWriter.Statistics(statistics));
  1438. }
  1439. pw.close();
  1440. }
  1441. if (sideband)
  1442. pckOut.end();
  1443. }
  1444. private static void findSymrefs(
  1445. final RefAdvertiser adv, final Map<String, Ref> refs) {
  1446. Ref head = refs.get(Constants.HEAD);
  1447. if (head != null && head.isSymbolic()) {
  1448. adv.addSymref(Constants.HEAD, head.getLeaf().getName());
  1449. }
  1450. }
  1451. private static class ResponseBufferedOutputStream extends OutputStream {
  1452. private final OutputStream rawOut;
  1453. private OutputStream out;
  1454. ResponseBufferedOutputStream(OutputStream rawOut) {
  1455. this.rawOut = rawOut;
  1456. this.out = new ByteArrayOutputStream();
  1457. }
  1458. @Override
  1459. public void write(int b) throws IOException {
  1460. out.write(b);
  1461. }
  1462. @Override
  1463. public void write(byte b[]) throws IOException {
  1464. out.write(b);
  1465. }
  1466. @Override
  1467. public void write(byte b[], int off, int len) throws IOException {
  1468. out.write(b, off, len);
  1469. }
  1470. @Override
  1471. public void flush() throws IOException {
  1472. out.flush();
  1473. }
  1474. @Override
  1475. public void close() throws IOException {
  1476. out.close();
  1477. }
  1478. void stopBuffering() throws IOException {
  1479. if (out != rawOut) {
  1480. ((ByteArrayOutputStream) out).writeTo(rawOut);
  1481. out = rawOut;
  1482. }
  1483. }
  1484. }
  1485. }