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.

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