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

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