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.

BasePackFetchConnection.java 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. /*
  2. * Copyright (C) 2008-2010, Google Inc.
  3. * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  4. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  5. * and other copyright owners as documented in the project's IP log.
  6. *
  7. * This program and the accompanying materials are made available
  8. * under the terms of the Eclipse Distribution License v1.0 which
  9. * accompanies this distribution, is reproduced below, and is
  10. * available at http://www.eclipse.org/org/documents/edl-v10.php
  11. *
  12. * All rights reserved.
  13. *
  14. * Redistribution and use in source and binary forms, with or
  15. * without modification, are permitted provided that the following
  16. * conditions are met:
  17. *
  18. * - Redistributions of source code must retain the above copyright
  19. * notice, this list of conditions and the following disclaimer.
  20. *
  21. * - Redistributions in binary form must reproduce the above
  22. * copyright notice, this list of conditions and the following
  23. * disclaimer in the documentation and/or other materials provided
  24. * with the distribution.
  25. *
  26. * - Neither the name of the Eclipse Foundation, Inc. nor the
  27. * names of its contributors may be used to endorse or promote
  28. * products derived from this software without specific prior
  29. * written permission.
  30. *
  31. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  32. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  33. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  34. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  35. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  36. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  37. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  38. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  39. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  40. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  41. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  42. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  43. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  44. */
  45. package org.eclipse.jgit.transport;
  46. import java.io.IOException;
  47. import java.io.InputStream;
  48. import java.io.OutputStream;
  49. import java.text.MessageFormat;
  50. import java.util.Collection;
  51. import java.util.Collections;
  52. import java.util.Date;
  53. import java.util.Set;
  54. import org.eclipse.jgit.errors.PackProtocolException;
  55. import org.eclipse.jgit.errors.TransportException;
  56. import org.eclipse.jgit.internal.JGitText;
  57. import org.eclipse.jgit.internal.storage.file.PackLock;
  58. import org.eclipse.jgit.lib.AnyObjectId;
  59. import org.eclipse.jgit.lib.Config;
  60. import org.eclipse.jgit.lib.Config.SectionParser;
  61. import org.eclipse.jgit.lib.Constants;
  62. import org.eclipse.jgit.lib.MutableObjectId;
  63. import org.eclipse.jgit.lib.ObjectId;
  64. import org.eclipse.jgit.lib.ObjectInserter;
  65. import org.eclipse.jgit.lib.ProgressMonitor;
  66. import org.eclipse.jgit.lib.Ref;
  67. import org.eclipse.jgit.revwalk.RevCommit;
  68. import org.eclipse.jgit.revwalk.RevCommitList;
  69. import org.eclipse.jgit.revwalk.RevFlag;
  70. import org.eclipse.jgit.revwalk.RevObject;
  71. import org.eclipse.jgit.revwalk.RevSort;
  72. import org.eclipse.jgit.revwalk.RevWalk;
  73. import org.eclipse.jgit.revwalk.filter.CommitTimeRevFilter;
  74. import org.eclipse.jgit.revwalk.filter.RevFilter;
  75. import org.eclipse.jgit.transport.PacketLineIn.AckNackResult;
  76. import org.eclipse.jgit.util.TemporaryBuffer;
  77. /**
  78. * Fetch implementation using the native Git pack transfer service.
  79. * <p>
  80. * This is the canonical implementation for transferring objects from the remote
  81. * repository to the local repository by talking to the 'git-upload-pack'
  82. * service. Objects are packed on the remote side into a pack file and then sent
  83. * down the pipe to us.
  84. * <p>
  85. * This connection requires only a bi-directional pipe or socket, and thus is
  86. * easily wrapped up into a local process pipe, anonymous TCP socket, or a
  87. * command executed through an SSH tunnel.
  88. * <p>
  89. * If {@link BasePackConnection#statelessRPC} is {@code true}, this connection
  90. * can be tunneled over a request-response style RPC system like HTTP. The RPC
  91. * call boundary is determined by this class switching from writing to the
  92. * OutputStream to reading from the InputStream.
  93. * <p>
  94. * Concrete implementations should just call
  95. * {@link #init(java.io.InputStream, java.io.OutputStream)} and
  96. * {@link #readAdvertisedRefs()} methods in constructor or before any use. They
  97. * should also handle resources releasing in {@link #close()} method if needed.
  98. */
  99. public abstract class BasePackFetchConnection extends BasePackConnection
  100. implements FetchConnection {
  101. /**
  102. * Maximum number of 'have' lines to send before giving up.
  103. * <p>
  104. * During {@link #negotiate(ProgressMonitor)} we send at most this many
  105. * commits to the remote peer as 'have' lines without an ACK response before
  106. * we give up.
  107. */
  108. private static final int MAX_HAVES = 256;
  109. /**
  110. * Amount of data the client sends before starting to read.
  111. * <p>
  112. * Any output stream given to the client must be able to buffer this many
  113. * bytes before the client will stop writing and start reading from the
  114. * input stream. If the output stream blocks before this many bytes are in
  115. * the send queue, the system will deadlock.
  116. */
  117. protected static final int MIN_CLIENT_BUFFER = 2 * 32 * 46 + 8;
  118. /**
  119. * Include tags if we are also including the referenced objects.
  120. * @since 2.0
  121. */
  122. public static final String OPTION_INCLUDE_TAG = "include-tag"; //$NON-NLS-1$
  123. /**
  124. * Mutli-ACK support for improved negotiation.
  125. * @since 2.0
  126. */
  127. public static final String OPTION_MULTI_ACK = "multi_ack"; //$NON-NLS-1$
  128. /**
  129. * Mutli-ACK detailed support for improved negotiation.
  130. * @since 2.0
  131. */
  132. public static final String OPTION_MULTI_ACK_DETAILED = "multi_ack_detailed"; //$NON-NLS-1$
  133. /**
  134. * The client supports packs with deltas but not their bases.
  135. * @since 2.0
  136. */
  137. public static final String OPTION_THIN_PACK = "thin-pack"; //$NON-NLS-1$
  138. /**
  139. * The client supports using the side-band for progress messages.
  140. * @since 2.0
  141. */
  142. public static final String OPTION_SIDE_BAND = "side-band"; //$NON-NLS-1$
  143. /**
  144. * The client supports using the 64K side-band for progress messages.
  145. * @since 2.0
  146. */
  147. public static final String OPTION_SIDE_BAND_64K = "side-band-64k"; //$NON-NLS-1$
  148. /**
  149. * The client supports packs with OFS deltas.
  150. * @since 2.0
  151. */
  152. public static final String OPTION_OFS_DELTA = "ofs-delta"; //$NON-NLS-1$
  153. /**
  154. * The client supports shallow fetches.
  155. * @since 2.0
  156. */
  157. public static final String OPTION_SHALLOW = "shallow"; //$NON-NLS-1$
  158. /**
  159. * The client does not want progress messages and will ignore them.
  160. * @since 2.0
  161. */
  162. public static final String OPTION_NO_PROGRESS = "no-progress"; //$NON-NLS-1$
  163. /**
  164. * The client supports receiving a pack before it has sent "done".
  165. * @since 2.0
  166. */
  167. public static final String OPTION_NO_DONE = "no-done"; //$NON-NLS-1$
  168. /**
  169. * The client supports fetching objects at the tip of any ref, even if not
  170. * advertised.
  171. * @since 3.1
  172. */
  173. public static final String OPTION_ALLOW_TIP_SHA1_IN_WANT = "allow-tip-sha1-in-want"; //$NON-NLS-1$
  174. static enum MultiAck {
  175. OFF, CONTINUE, DETAILED;
  176. }
  177. private final RevWalk walk;
  178. /** All commits that are immediately reachable by a local ref. */
  179. private RevCommitList<RevCommit> reachableCommits;
  180. /** Marks an object as having all its dependencies. */
  181. final RevFlag REACHABLE;
  182. /** Marks a commit known to both sides of the connection. */
  183. final RevFlag COMMON;
  184. /** Like {@link #COMMON} but means its also in {@link #pckState}. */
  185. private final RevFlag STATE;
  186. /** Marks a commit listed in the advertised refs. */
  187. final RevFlag ADVERTISED;
  188. private MultiAck multiAck = MultiAck.OFF;
  189. private boolean thinPack;
  190. private boolean sideband;
  191. private boolean includeTags;
  192. private boolean allowOfsDelta;
  193. private boolean noDone;
  194. private String lockMessage;
  195. private PackLock packLock;
  196. /** RPC state, if {@link BasePackConnection#statelessRPC} is true. */
  197. private TemporaryBuffer.Heap state;
  198. private PacketLineOut pckState;
  199. /**
  200. * Create a new connection to fetch using the native git transport.
  201. *
  202. * @param packTransport
  203. * the transport.
  204. */
  205. public BasePackFetchConnection(final PackTransport packTransport) {
  206. super(packTransport);
  207. final FetchConfig cfg = local.getConfig().get(FetchConfig.KEY);
  208. includeTags = transport.getTagOpt() != TagOpt.NO_TAGS;
  209. thinPack = transport.isFetchThin();
  210. allowOfsDelta = cfg.allowOfsDelta;
  211. walk = new RevWalk(local);
  212. reachableCommits = new RevCommitList<RevCommit>();
  213. REACHABLE = walk.newFlag("REACHABLE"); //$NON-NLS-1$
  214. COMMON = walk.newFlag("COMMON"); //$NON-NLS-1$
  215. STATE = walk.newFlag("STATE"); //$NON-NLS-1$
  216. ADVERTISED = walk.newFlag("ADVERTISED"); //$NON-NLS-1$
  217. walk.carry(COMMON);
  218. walk.carry(REACHABLE);
  219. walk.carry(ADVERTISED);
  220. }
  221. private static class FetchConfig {
  222. static final SectionParser<FetchConfig> KEY = new SectionParser<FetchConfig>() {
  223. public FetchConfig parse(final Config cfg) {
  224. return new FetchConfig(cfg);
  225. }
  226. };
  227. final boolean allowOfsDelta;
  228. FetchConfig(final Config c) {
  229. allowOfsDelta = c.getBoolean("repack", "usedeltabaseoffset", true); //$NON-NLS-1$ //$NON-NLS-2$
  230. }
  231. }
  232. public final void fetch(final ProgressMonitor monitor,
  233. final Collection<Ref> want, final Set<ObjectId> have)
  234. throws TransportException {
  235. fetch(monitor, want, have, null);
  236. }
  237. /**
  238. * @since 3.0
  239. */
  240. public final void fetch(final ProgressMonitor monitor,
  241. final Collection<Ref> want, final Set<ObjectId> have,
  242. OutputStream outputStream) throws TransportException {
  243. markStartedOperation();
  244. doFetch(monitor, want, have, outputStream);
  245. }
  246. public boolean didFetchIncludeTags() {
  247. return false;
  248. }
  249. public boolean didFetchTestConnectivity() {
  250. return false;
  251. }
  252. public void setPackLockMessage(final String message) {
  253. lockMessage = message;
  254. }
  255. public Collection<PackLock> getPackLocks() {
  256. if (packLock != null)
  257. return Collections.singleton(packLock);
  258. return Collections.<PackLock> emptyList();
  259. }
  260. /**
  261. * Execute common ancestor negotiation and fetch the objects.
  262. *
  263. * @param monitor
  264. * progress monitor to receive status updates.
  265. * @param want
  266. * the advertised remote references the caller wants to fetch.
  267. * @param have
  268. * additional objects to assume that already exist locally. This
  269. * will be added to the set of objects reachable from the
  270. * destination repository's references.
  271. * @param outputStream
  272. * ouputStream to write sideband messages to
  273. * @throws TransportException
  274. * if any exception occurs.
  275. * @since 3.0
  276. */
  277. protected void doFetch(final ProgressMonitor monitor,
  278. final Collection<Ref> want, final Set<ObjectId> have,
  279. OutputStream outputStream) throws TransportException {
  280. try {
  281. markRefsAdvertised();
  282. markReachable(have, maxTimeWanted(want));
  283. if (statelessRPC) {
  284. state = new TemporaryBuffer.Heap(Integer.MAX_VALUE);
  285. pckState = new PacketLineOut(state);
  286. }
  287. if (sendWants(want)) {
  288. negotiate(monitor);
  289. walk.dispose();
  290. reachableCommits = null;
  291. state = null;
  292. pckState = null;
  293. receivePack(monitor, outputStream);
  294. }
  295. } catch (CancelledException ce) {
  296. close();
  297. return; // Caller should test (or just know) this themselves.
  298. } catch (IOException err) {
  299. close();
  300. throw new TransportException(err.getMessage(), err);
  301. } catch (RuntimeException err) {
  302. close();
  303. throw new TransportException(err.getMessage(), err);
  304. }
  305. }
  306. @Override
  307. public void close() {
  308. walk.release();
  309. super.close();
  310. }
  311. private int maxTimeWanted(final Collection<Ref> wants) {
  312. int maxTime = 0;
  313. for (final Ref r : wants) {
  314. try {
  315. final RevObject obj = walk.parseAny(r.getObjectId());
  316. if (obj instanceof RevCommit) {
  317. final int cTime = ((RevCommit) obj).getCommitTime();
  318. if (maxTime < cTime)
  319. maxTime = cTime;
  320. }
  321. } catch (IOException error) {
  322. // We don't have it, but we want to fetch (thus fixing error).
  323. }
  324. }
  325. return maxTime;
  326. }
  327. private void markReachable(final Set<ObjectId> have, final int maxTime)
  328. throws IOException {
  329. for (final Ref r : local.getAllRefs().values()) {
  330. ObjectId id = r.getPeeledObjectId();
  331. if (id == null)
  332. id = r.getObjectId();
  333. if (id == null)
  334. continue;
  335. parseReachable(id);
  336. }
  337. for (ObjectId id : local.getAdditionalHaves())
  338. parseReachable(id);
  339. for (ObjectId id : have)
  340. parseReachable(id);
  341. if (maxTime > 0) {
  342. // Mark reachable commits until we reach maxTime. These may
  343. // wind up later matching up against things we want and we
  344. // can avoid asking for something we already happen to have.
  345. //
  346. final Date maxWhen = new Date(maxTime * 1000L);
  347. walk.sort(RevSort.COMMIT_TIME_DESC);
  348. walk.markStart(reachableCommits);
  349. walk.setRevFilter(CommitTimeRevFilter.after(maxWhen));
  350. for (;;) {
  351. final RevCommit c = walk.next();
  352. if (c == null)
  353. break;
  354. if (c.has(ADVERTISED) && !c.has(COMMON)) {
  355. // This is actually going to be a common commit, but
  356. // our peer doesn't know that fact yet.
  357. //
  358. c.add(COMMON);
  359. c.carry(COMMON);
  360. reachableCommits.add(c);
  361. }
  362. }
  363. }
  364. }
  365. private void parseReachable(ObjectId id) {
  366. try {
  367. RevCommit o = walk.parseCommit(id);
  368. if (!o.has(REACHABLE)) {
  369. o.add(REACHABLE);
  370. reachableCommits.add(o);
  371. }
  372. } catch (IOException readError) {
  373. // If we cannot read the value of the ref skip it.
  374. }
  375. }
  376. private boolean sendWants(final Collection<Ref> want) throws IOException {
  377. final PacketLineOut p = statelessRPC ? pckState : pckOut;
  378. boolean first = true;
  379. for (final Ref r : want) {
  380. try {
  381. if (walk.parseAny(r.getObjectId()).has(REACHABLE)) {
  382. // We already have this object. Asking for it is
  383. // not a very good idea.
  384. //
  385. continue;
  386. }
  387. } catch (IOException err) {
  388. // Its OK, we don't have it, but we want to fix that
  389. // by fetching the object from the other side.
  390. }
  391. final StringBuilder line = new StringBuilder(46);
  392. line.append("want "); //$NON-NLS-1$
  393. line.append(r.getObjectId().name());
  394. if (first) {
  395. line.append(enableCapabilities());
  396. first = false;
  397. }
  398. line.append('\n');
  399. p.writeString(line.toString());
  400. }
  401. if (first)
  402. return false;
  403. p.end();
  404. outNeedsEnd = false;
  405. return true;
  406. }
  407. private String enableCapabilities() throws TransportException {
  408. final StringBuilder line = new StringBuilder();
  409. if (includeTags)
  410. includeTags = wantCapability(line, OPTION_INCLUDE_TAG);
  411. if (allowOfsDelta)
  412. wantCapability(line, OPTION_OFS_DELTA);
  413. if (wantCapability(line, OPTION_MULTI_ACK_DETAILED)) {
  414. multiAck = MultiAck.DETAILED;
  415. if (statelessRPC)
  416. noDone = wantCapability(line, OPTION_NO_DONE);
  417. } else if (wantCapability(line, OPTION_MULTI_ACK))
  418. multiAck = MultiAck.CONTINUE;
  419. else
  420. multiAck = MultiAck.OFF;
  421. if (thinPack)
  422. thinPack = wantCapability(line, OPTION_THIN_PACK);
  423. if (wantCapability(line, OPTION_SIDE_BAND_64K))
  424. sideband = true;
  425. else if (wantCapability(line, OPTION_SIDE_BAND))
  426. sideband = true;
  427. if (statelessRPC && multiAck != MultiAck.DETAILED) {
  428. // Our stateless RPC implementation relies upon the detailed
  429. // ACK status to tell us common objects for reuse in future
  430. // requests. If its not enabled, we can't talk to the peer.
  431. //
  432. throw new PackProtocolException(uri, MessageFormat.format(
  433. JGitText.get().statelessRPCRequiresOptionToBeEnabled,
  434. OPTION_MULTI_ACK_DETAILED));
  435. }
  436. return line.toString();
  437. }
  438. private void negotiate(final ProgressMonitor monitor) throws IOException,
  439. CancelledException {
  440. final MutableObjectId ackId = new MutableObjectId();
  441. int resultsPending = 0;
  442. int havesSent = 0;
  443. int havesSinceLastContinue = 0;
  444. boolean receivedContinue = false;
  445. boolean receivedAck = false;
  446. boolean receivedReady = false;
  447. if (statelessRPC)
  448. state.writeTo(out, null);
  449. negotiateBegin();
  450. SEND_HAVES: for (;;) {
  451. final RevCommit c = walk.next();
  452. if (c == null)
  453. break SEND_HAVES;
  454. pckOut.writeString("have " + c.getId().name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  455. havesSent++;
  456. havesSinceLastContinue++;
  457. if ((31 & havesSent) != 0) {
  458. // We group the have lines into blocks of 32, each marked
  459. // with a flush (aka end). This one is within a block so
  460. // continue with another have line.
  461. //
  462. continue;
  463. }
  464. if (monitor.isCancelled())
  465. throw new CancelledException();
  466. pckOut.end();
  467. resultsPending++; // Each end will cause a result to come back.
  468. if (havesSent == 32 && !statelessRPC) {
  469. // On the first block we race ahead and try to send
  470. // more of the second block while waiting for the
  471. // remote to respond to our first block request.
  472. // This keeps us one block ahead of the peer.
  473. //
  474. continue;
  475. }
  476. READ_RESULT: for (;;) {
  477. final AckNackResult anr = pckIn.readACK(ackId);
  478. switch (anr) {
  479. case NAK:
  480. // More have lines are necessary to compute the
  481. // pack on the remote side. Keep doing that.
  482. //
  483. resultsPending--;
  484. break READ_RESULT;
  485. case ACK:
  486. // The remote side is happy and knows exactly what
  487. // to send us. There is no further negotiation and
  488. // we can break out immediately.
  489. //
  490. multiAck = MultiAck.OFF;
  491. resultsPending = 0;
  492. receivedAck = true;
  493. if (statelessRPC)
  494. state.writeTo(out, null);
  495. break SEND_HAVES;
  496. case ACK_CONTINUE:
  497. case ACK_COMMON:
  498. case ACK_READY:
  499. // The server knows this commit (ackId). We don't
  500. // need to send any further along its ancestry, but
  501. // we need to continue to talk about other parts of
  502. // our local history.
  503. //
  504. markCommon(walk.parseAny(ackId), anr);
  505. receivedAck = true;
  506. receivedContinue = true;
  507. havesSinceLastContinue = 0;
  508. if (anr == AckNackResult.ACK_READY)
  509. receivedReady = true;
  510. break;
  511. }
  512. if (monitor.isCancelled())
  513. throw new CancelledException();
  514. }
  515. if (noDone & receivedReady)
  516. break SEND_HAVES;
  517. if (statelessRPC)
  518. state.writeTo(out, null);
  519. if (receivedContinue && havesSinceLastContinue > MAX_HAVES) {
  520. // Our history must be really different from the remote's.
  521. // We just sent a whole slew of have lines, and it did not
  522. // recognize any of them. Avoid sending our entire history
  523. // to them by giving up early.
  524. //
  525. break SEND_HAVES;
  526. }
  527. }
  528. // Tell the remote side we have run out of things to talk about.
  529. //
  530. if (monitor.isCancelled())
  531. throw new CancelledException();
  532. if (!receivedReady || !noDone) {
  533. // When statelessRPC is true we should always leave SEND_HAVES
  534. // loop above while in the middle of a request. This allows us
  535. // to just write done immediately.
  536. //
  537. pckOut.writeString("done\n"); //$NON-NLS-1$
  538. pckOut.flush();
  539. }
  540. if (!receivedAck) {
  541. // Apparently if we have never received an ACK earlier
  542. // there is one more result expected from the done we
  543. // just sent to the remote.
  544. //
  545. multiAck = MultiAck.OFF;
  546. resultsPending++;
  547. }
  548. READ_RESULT: while (resultsPending > 0 || multiAck != MultiAck.OFF) {
  549. final AckNackResult anr = pckIn.readACK(ackId);
  550. resultsPending--;
  551. switch (anr) {
  552. case NAK:
  553. // A NAK is a response to an end we queued earlier
  554. // we eat it and look for another ACK/NAK message.
  555. //
  556. break;
  557. case ACK:
  558. // A solitary ACK at this point means the remote won't
  559. // speak anymore, but is going to send us a pack now.
  560. //
  561. break READ_RESULT;
  562. case ACK_CONTINUE:
  563. case ACK_COMMON:
  564. case ACK_READY:
  565. // We will expect a normal ACK to break out of the loop.
  566. //
  567. multiAck = MultiAck.CONTINUE;
  568. break;
  569. }
  570. if (monitor.isCancelled())
  571. throw new CancelledException();
  572. }
  573. }
  574. private void negotiateBegin() throws IOException {
  575. walk.resetRetain(REACHABLE, ADVERTISED);
  576. walk.markStart(reachableCommits);
  577. walk.sort(RevSort.COMMIT_TIME_DESC);
  578. walk.setRevFilter(new RevFilter() {
  579. @Override
  580. public RevFilter clone() {
  581. return this;
  582. }
  583. @Override
  584. public boolean include(final RevWalk walker, final RevCommit c) {
  585. final boolean remoteKnowsIsCommon = c.has(COMMON);
  586. if (c.has(ADVERTISED)) {
  587. // Remote advertised this, and we have it, hence common.
  588. // Whether or not the remote knows that fact is tested
  589. // before we added the flag. If the remote doesn't know
  590. // we have to still send them this object.
  591. //
  592. c.add(COMMON);
  593. }
  594. return !remoteKnowsIsCommon;
  595. }
  596. @Override
  597. public boolean requiresCommitBody() {
  598. return false;
  599. }
  600. });
  601. }
  602. private void markRefsAdvertised() {
  603. for (final Ref r : getRefs()) {
  604. markAdvertised(r.getObjectId());
  605. if (r.getPeeledObjectId() != null)
  606. markAdvertised(r.getPeeledObjectId());
  607. }
  608. }
  609. private void markAdvertised(final AnyObjectId id) {
  610. try {
  611. walk.parseAny(id).add(ADVERTISED);
  612. } catch (IOException readError) {
  613. // We probably just do not have this object locally.
  614. }
  615. }
  616. private void markCommon(final RevObject obj, final AckNackResult anr)
  617. throws IOException {
  618. if (statelessRPC && anr == AckNackResult.ACK_COMMON && !obj.has(STATE)) {
  619. StringBuilder s;
  620. s = new StringBuilder(6 + Constants.OBJECT_ID_STRING_LENGTH);
  621. s.append("have "); //$NON-NLS-1$
  622. s.append(obj.name());
  623. s.append('\n');
  624. pckState.writeString(s.toString());
  625. obj.add(STATE);
  626. }
  627. obj.add(COMMON);
  628. if (obj instanceof RevCommit)
  629. ((RevCommit) obj).carry(COMMON);
  630. }
  631. private void receivePack(final ProgressMonitor monitor,
  632. OutputStream outputStream) throws IOException {
  633. onReceivePack();
  634. InputStream input = in;
  635. if (sideband)
  636. input = new SideBandInputStream(input, monitor, getMessageWriter(),
  637. outputStream);
  638. ObjectInserter ins = local.newObjectInserter();
  639. try {
  640. PackParser parser = ins.newPackParser(input);
  641. parser.setAllowThin(thinPack);
  642. parser.setObjectChecking(transport.isCheckFetchedObjects());
  643. parser.setLockMessage(lockMessage);
  644. packLock = parser.parse(monitor);
  645. ins.flush();
  646. } finally {
  647. ins.release();
  648. }
  649. }
  650. /**
  651. * Notification event delivered just before the pack is received from the
  652. * network. This event can be used by RPC such as {@link TransportHttp} to
  653. * disable its request magic and ensure the pack stream is read correctly.
  654. *
  655. * @since 2.0
  656. */
  657. protected void onReceivePack() {
  658. // By default do nothing for TCP based protocols.
  659. }
  660. private static class CancelledException extends Exception {
  661. private static final long serialVersionUID = 1L;
  662. }
  663. }