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

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