View Javadoc
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  
46  package org.eclipse.jgit.transport;
47  
48  import static org.eclipse.jgit.lib.RefDatabase.ALL;
49  
50  import java.io.IOException;
51  import java.io.InputStream;
52  import java.io.OutputStream;
53  import java.text.MessageFormat;
54  import java.util.Collection;
55  import java.util.Collections;
56  import java.util.Date;
57  import java.util.Map;
58  import java.util.Set;
59  
60  import org.eclipse.jgit.errors.PackProtocolException;
61  import org.eclipse.jgit.errors.TransportException;
62  import org.eclipse.jgit.internal.JGitText;
63  import org.eclipse.jgit.internal.storage.file.PackLock;
64  import org.eclipse.jgit.lib.AnyObjectId;
65  import org.eclipse.jgit.lib.Config;
66  import org.eclipse.jgit.lib.Constants;
67  import org.eclipse.jgit.lib.MutableObjectId;
68  import org.eclipse.jgit.lib.NullProgressMonitor;
69  import org.eclipse.jgit.lib.ObjectId;
70  import org.eclipse.jgit.lib.ObjectInserter;
71  import org.eclipse.jgit.lib.ProgressMonitor;
72  import org.eclipse.jgit.lib.Ref;
73  import org.eclipse.jgit.revwalk.RevCommit;
74  import org.eclipse.jgit.revwalk.RevCommitList;
75  import org.eclipse.jgit.revwalk.RevFlag;
76  import org.eclipse.jgit.revwalk.RevObject;
77  import org.eclipse.jgit.revwalk.RevSort;
78  import org.eclipse.jgit.revwalk.RevWalk;
79  import org.eclipse.jgit.revwalk.filter.CommitTimeRevFilter;
80  import org.eclipse.jgit.revwalk.filter.RevFilter;
81  import org.eclipse.jgit.transport.GitProtocolConstants.MultiAck;
82  import org.eclipse.jgit.transport.PacketLineIn.AckNackResult;
83  import org.eclipse.jgit.util.TemporaryBuffer;
84  
85  /**
86   * Fetch implementation using the native Git pack transfer service.
87   * <p>
88   * This is the canonical implementation for transferring objects from the remote
89   * repository to the local repository by talking to the 'git-upload-pack'
90   * service. Objects are packed on the remote side into a pack file and then sent
91   * down the pipe to us.
92   * <p>
93   * This connection requires only a bi-directional pipe or socket, and thus is
94   * easily wrapped up into a local process pipe, anonymous TCP socket, or a
95   * command executed through an SSH tunnel.
96   * <p>
97   * If {@link BasePackConnection#statelessRPC} is {@code true}, this connection
98   * can be tunneled over a request-response style RPC system like HTTP.  The RPC
99   * call boundary is determined by this class switching from writing to the
100  * OutputStream to reading from the InputStream.
101  * <p>
102  * Concrete implementations should just call
103  * {@link #init(java.io.InputStream, java.io.OutputStream)} and
104  * {@link #readAdvertisedRefs()} methods in constructor or before any use. They
105  * should also handle resources releasing in {@link #close()} method if needed.
106  */
107 public abstract class BasePackFetchConnection extends BasePackConnection
108 		implements FetchConnection {
109 	/**
110 	 * Maximum number of 'have' lines to send before giving up.
111 	 * <p>
112 	 * During {@link #negotiate(ProgressMonitor)} we send at most this many
113 	 * commits to the remote peer as 'have' lines without an ACK response before
114 	 * we give up.
115 	 */
116 	private static final int MAX_HAVES = 256;
117 
118 	/**
119 	 * Amount of data the client sends before starting to read.
120 	 * <p>
121 	 * Any output stream given to the client must be able to buffer this many
122 	 * bytes before the client will stop writing and start reading from the
123 	 * input stream. If the output stream blocks before this many bytes are in
124 	 * the send queue, the system will deadlock.
125 	 */
126 	protected static final int MIN_CLIENT_BUFFER = 2 * 32 * 46 + 8;
127 
128 	/**
129 	 * Include tags if we are also including the referenced objects.
130 	 * @since 2.0
131 	 */
132 	public static final String OPTION_INCLUDE_TAG = GitProtocolConstants.OPTION_INCLUDE_TAG;
133 
134 	/**
135 	 * Mutli-ACK support for improved negotiation.
136 	 * @since 2.0
137 	 */
138 	public static final String OPTION_MULTI_ACK = GitProtocolConstants.OPTION_MULTI_ACK;
139 
140 	/**
141 	 * Mutli-ACK detailed support for improved negotiation.
142 	 * @since 2.0
143 	 */
144 	public static final String OPTION_MULTI_ACK_DETAILED = GitProtocolConstants.OPTION_MULTI_ACK_DETAILED;
145 
146 	/**
147 	 * The client supports packs with deltas but not their bases.
148 	 * @since 2.0
149 	 */
150 	public static final String OPTION_THIN_PACK = GitProtocolConstants.OPTION_THIN_PACK;
151 
152 	/**
153 	 * The client supports using the side-band for progress messages.
154 	 * @since 2.0
155 	 */
156 	public static final String OPTION_SIDE_BAND = GitProtocolConstants.OPTION_SIDE_BAND;
157 
158 	/**
159 	 * The client supports using the 64K side-band for progress messages.
160 	 * @since 2.0
161 	 */
162 	public static final String OPTION_SIDE_BAND_64K = GitProtocolConstants.OPTION_SIDE_BAND_64K;
163 
164 	/**
165 	 * The client supports packs with OFS deltas.
166 	 * @since 2.0
167 	 */
168 	public static final String OPTION_OFS_DELTA = GitProtocolConstants.OPTION_OFS_DELTA;
169 
170 	/**
171 	 * The client supports shallow fetches.
172 	 * @since 2.0
173 	 */
174 	public static final String OPTION_SHALLOW = GitProtocolConstants.OPTION_SHALLOW;
175 
176 	/**
177 	 * The client does not want progress messages and will ignore them.
178 	 * @since 2.0
179 	 */
180 	public static final String OPTION_NO_PROGRESS = GitProtocolConstants.OPTION_NO_PROGRESS;
181 
182 	/**
183 	 * The client supports receiving a pack before it has sent "done".
184 	 * @since 2.0
185 	 */
186 	public static final String OPTION_NO_DONE = GitProtocolConstants.OPTION_NO_DONE;
187 
188 	/**
189 	 * The client supports fetching objects at the tip of any ref, even if not
190 	 * advertised.
191 	 * @since 3.1
192 	 */
193 	public static final String OPTION_ALLOW_TIP_SHA1_IN_WANT = GitProtocolConstants.OPTION_ALLOW_TIP_SHA1_IN_WANT;
194 
195 	/**
196 	 * The client supports fetching objects that are reachable from a tip of a
197 	 * ref that is allowed to fetch.
198 	 * @since 4.1
199 	 */
200 	public static final String OPTION_ALLOW_REACHABLE_SHA1_IN_WANT = GitProtocolConstants.OPTION_ALLOW_REACHABLE_SHA1_IN_WANT;
201 
202 	private final RevWalk walk;
203 
204 	/** All commits that are immediately reachable by a local ref. */
205 	private RevCommitList<RevCommit> reachableCommits;
206 
207 	/** Marks an object as having all its dependencies. */
208 	final RevFlag REACHABLE;
209 
210 	/** Marks a commit known to both sides of the connection. */
211 	final RevFlag COMMON;
212 
213 	/** Like {@link #COMMON} but means its also in {@link #pckState}. */
214 	private final RevFlag STATE;
215 
216 	/** Marks a commit listed in the advertised refs. */
217 	final RevFlag ADVERTISED;
218 
219 	private MultiAck multiAck = MultiAck.OFF;
220 
221 	private boolean thinPack;
222 
223 	private boolean sideband;
224 
225 	private boolean includeTags;
226 
227 	private boolean allowOfsDelta;
228 
229 	private boolean noDone;
230 
231 	private boolean noProgress;
232 
233 	private String lockMessage;
234 
235 	private PackLock packLock;
236 
237 	/** RPC state, if {@link BasePackConnection#statelessRPC} is true. */
238 	private TemporaryBuffer.Heap state;
239 
240 	private PacketLineOut pckState;
241 
242 	/**
243 	 * Create a new connection to fetch using the native git transport.
244 	 *
245 	 * @param packTransport
246 	 *            the transport.
247 	 */
248 	public BasePackFetchConnection(final PackTransport packTransport) {
249 		super(packTransport);
250 
251 		if (local != null) {
252 			final FetchConfig cfg = local.getConfig().get(FetchConfig::new);
253 			allowOfsDelta = cfg.allowOfsDelta;
254 		} else {
255 			allowOfsDelta = true;
256 		}
257 		includeTags = transport.getTagOpt() != TagOpt.NO_TAGS;
258 		thinPack = transport.isFetchThin();
259 
260 		if (local != null) {
261 			walk = new RevWalk(local);
262 			reachableCommits = new RevCommitList<>();
263 			REACHABLE = walk.newFlag("REACHABLE"); //$NON-NLS-1$
264 			COMMON = walk.newFlag("COMMON"); //$NON-NLS-1$
265 			STATE = walk.newFlag("STATE"); //$NON-NLS-1$
266 			ADVERTISED = walk.newFlag("ADVERTISED"); //$NON-NLS-1$
267 
268 			walk.carry(COMMON);
269 			walk.carry(REACHABLE);
270 			walk.carry(ADVERTISED);
271 		} else {
272 			walk = null;
273 			REACHABLE = null;
274 			COMMON = null;
275 			STATE = null;
276 			ADVERTISED = null;
277 		}
278 	}
279 
280 	private static class FetchConfig {
281 		final boolean allowOfsDelta;
282 
283 		FetchConfig(final Config c) {
284 			allowOfsDelta = c.getBoolean("repack", "usedeltabaseoffset", true); //$NON-NLS-1$ //$NON-NLS-2$
285 		}
286 	}
287 
288 	@Override
289 	public final void fetch(final ProgressMonitor monitor,
290 			final Collection<Ref> want, final Set<ObjectId> have)
291 			throws TransportException {
292 		fetch(monitor, want, have, null);
293 	}
294 
295 	/**
296 	 * @since 3.0
297 	 */
298 	@Override
299 	public final void fetch(final ProgressMonitor monitor,
300 			final Collection<Ref> want, final Set<ObjectId> have,
301 			OutputStream outputStream) throws TransportException {
302 		markStartedOperation();
303 		doFetch(monitor, want, have, outputStream);
304 	}
305 
306 	@Override
307 	public boolean didFetchIncludeTags() {
308 		return false;
309 	}
310 
311 	@Override
312 	public boolean didFetchTestConnectivity() {
313 		return false;
314 	}
315 
316 	@Override
317 	public void setPackLockMessage(final String message) {
318 		lockMessage = message;
319 	}
320 
321 	@Override
322 	public Collection<PackLock> getPackLocks() {
323 		if (packLock != null)
324 			return Collections.singleton(packLock);
325 		return Collections.<PackLock> emptyList();
326 	}
327 
328 	/**
329 	 * Execute common ancestor negotiation and fetch the objects.
330 	 *
331 	 * @param monitor
332 	 *            progress monitor to receive status updates. If the monitor is
333 	 *            the {@link NullProgressMonitor#INSTANCE}, then the no-progress
334 	 *            option enabled.
335 	 * @param want
336 	 *            the advertised remote references the caller wants to fetch.
337 	 * @param have
338 	 *            additional objects to assume that already exist locally. This
339 	 *            will be added to the set of objects reachable from the
340 	 *            destination repository's references.
341 	 * @param outputStream
342 	 *            ouputStream to write sideband messages to
343 	 * @throws TransportException
344 	 *             if any exception occurs.
345 	 * @since 3.0
346 	 */
347 	protected void doFetch(final ProgressMonitor monitor,
348 			final Collection<Ref> want, final Set<ObjectId> have,
349 			OutputStream outputStream) throws TransportException {
350 		try {
351 			noProgress = monitor == NullProgressMonitor.INSTANCE;
352 
353 			markRefsAdvertised();
354 			markReachable(have, maxTimeWanted(want));
355 
356 			if (statelessRPC) {
357 				state = new TemporaryBuffer.Heap(Integer.MAX_VALUE);
358 				pckState = new PacketLineOut(state);
359 			}
360 
361 			if (sendWants(want)) {
362 				negotiate(monitor);
363 
364 				walk.dispose();
365 				reachableCommits = null;
366 				state = null;
367 				pckState = null;
368 
369 				receivePack(monitor, outputStream);
370 			}
371 		} catch (CancelledException ce) {
372 			close();
373 			return; // Caller should test (or just know) this themselves.
374 		} catch (IOException err) {
375 			close();
376 			throw new TransportException(err.getMessage(), err);
377 		} catch (RuntimeException err) {
378 			close();
379 			throw new TransportException(err.getMessage(), err);
380 		}
381 	}
382 
383 	@Override
384 	public void close() {
385 		if (walk != null)
386 			walk.close();
387 		super.close();
388 	}
389 
390 	private int maxTimeWanted(final Collection<Ref> wants) {
391 		int maxTime = 0;
392 		for (final Ref r : wants) {
393 			try {
394 				final RevObject obj = walk.parseAny(r.getObjectId());
395 				if (obj instanceof RevCommit) {
396 					final int cTime = ((RevCommit) obj).getCommitTime();
397 					if (maxTime < cTime)
398 						maxTime = cTime;
399 				}
400 			} catch (IOException error) {
401 				// We don't have it, but we want to fetch (thus fixing error).
402 			}
403 		}
404 		return maxTime;
405 	}
406 
407 	private void markReachable(final Set<ObjectId> have, final int maxTime)
408 			throws IOException {
409 		Map<String, Ref> refs = local.getRefDatabase().getRefs(ALL);
410 		for (final Ref r : refs.values()) {
411 			ObjectId id = r.getPeeledObjectId();
412 			if (id == null)
413 				id = r.getObjectId();
414 			if (id == null)
415 				continue;
416 			parseReachable(id);
417 		}
418 
419 		for (ObjectId id : local.getAdditionalHaves())
420 			parseReachable(id);
421 
422 		for (ObjectId id : have)
423 			parseReachable(id);
424 
425 		if (maxTime > 0) {
426 			// Mark reachable commits until we reach maxTime. These may
427 			// wind up later matching up against things we want and we
428 			// can avoid asking for something we already happen to have.
429 			//
430 			final Date maxWhen = new Date(maxTime * 1000L);
431 			walk.sort(RevSort.COMMIT_TIME_DESC);
432 			walk.markStart(reachableCommits);
433 			walk.setRevFilter(CommitTimeRevFilter.after(maxWhen));
434 			for (;;) {
435 				final RevCommit c = walk.next();
436 				if (c == null)
437 					break;
438 				if (c.has(ADVERTISED) && !c.has(COMMON)) {
439 					// This is actually going to be a common commit, but
440 					// our peer doesn't know that fact yet.
441 					//
442 					c.add(COMMON);
443 					c.carry(COMMON);
444 					reachableCommits.add(c);
445 				}
446 			}
447 		}
448 	}
449 
450 	private void parseReachable(ObjectId id) {
451 		try {
452 			RevCommit o = walk.parseCommit(id);
453 			if (!o.has(REACHABLE)) {
454 				o.add(REACHABLE);
455 				reachableCommits.add(o);
456 			}
457 		} catch (IOException readError) {
458 			// If we cannot read the value of the ref skip it.
459 		}
460 	}
461 
462 	private boolean sendWants(final Collection<Ref> want) throws IOException {
463 		final PacketLineOut p = statelessRPC ? pckState : pckOut;
464 		boolean first = true;
465 		for (final Ref r : want) {
466 			ObjectId objectId = r.getObjectId();
467 			if (objectId == null) {
468 				continue;
469 			}
470 			try {
471 				if (walk.parseAny(objectId).has(REACHABLE)) {
472 					// We already have this object. Asking for it is
473 					// not a very good idea.
474 					//
475 					continue;
476 				}
477 			} catch (IOException err) {
478 				// Its OK, we don't have it, but we want to fix that
479 				// by fetching the object from the other side.
480 			}
481 
482 			final StringBuilder line = new StringBuilder(46);
483 			line.append("want "); //$NON-NLS-1$
484 			line.append(objectId.name());
485 			if (first) {
486 				line.append(enableCapabilities());
487 				first = false;
488 			}
489 			line.append('\n');
490 			p.writeString(line.toString());
491 		}
492 		if (first)
493 			return false;
494 		p.end();
495 		outNeedsEnd = false;
496 		return true;
497 	}
498 
499 	private String enableCapabilities() throws TransportException {
500 		final StringBuilder line = new StringBuilder();
501 		if (noProgress)
502 			wantCapability(line, OPTION_NO_PROGRESS);
503 		if (includeTags)
504 			includeTags = wantCapability(line, OPTION_INCLUDE_TAG);
505 		if (allowOfsDelta)
506 			wantCapability(line, OPTION_OFS_DELTA);
507 
508 		if (wantCapability(line, OPTION_MULTI_ACK_DETAILED)) {
509 			multiAck = MultiAck.DETAILED;
510 			if (statelessRPC)
511 				noDone = wantCapability(line, OPTION_NO_DONE);
512 		} else if (wantCapability(line, OPTION_MULTI_ACK))
513 			multiAck = MultiAck.CONTINUE;
514 		else
515 			multiAck = MultiAck.OFF;
516 
517 		if (thinPack)
518 			thinPack = wantCapability(line, OPTION_THIN_PACK);
519 		if (wantCapability(line, OPTION_SIDE_BAND_64K))
520 			sideband = true;
521 		else if (wantCapability(line, OPTION_SIDE_BAND))
522 			sideband = true;
523 
524 		if (statelessRPC && multiAck != MultiAck.DETAILED) {
525 			// Our stateless RPC implementation relies upon the detailed
526 			// ACK status to tell us common objects for reuse in future
527 			// requests.  If its not enabled, we can't talk to the peer.
528 			//
529 			throw new PackProtocolException(uri, MessageFormat.format(
530 					JGitText.get().statelessRPCRequiresOptionToBeEnabled,
531 					OPTION_MULTI_ACK_DETAILED));
532 		}
533 
534 		addUserAgentCapability(line);
535 		return line.toString();
536 	}
537 
538 	private void negotiate(final ProgressMonitor monitor) throws IOException,
539 			CancelledException {
540 		final MutableObjectId ackId = new MutableObjectId();
541 		int resultsPending = 0;
542 		int havesSent = 0;
543 		int havesSinceLastContinue = 0;
544 		boolean receivedContinue = false;
545 		boolean receivedAck = false;
546 		boolean receivedReady = false;
547 
548 		if (statelessRPC)
549 			state.writeTo(out, null);
550 
551 		negotiateBegin();
552 		SEND_HAVES: for (;;) {
553 			final RevCommit c = walk.next();
554 			if (c == null)
555 				break SEND_HAVES;
556 
557 			pckOut.writeString("have " + c.getId().name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
558 			havesSent++;
559 			havesSinceLastContinue++;
560 
561 			if ((31 & havesSent) != 0) {
562 				// We group the have lines into blocks of 32, each marked
563 				// with a flush (aka end). This one is within a block so
564 				// continue with another have line.
565 				//
566 				continue;
567 			}
568 
569 			if (monitor.isCancelled())
570 				throw new CancelledException();
571 
572 			pckOut.end();
573 			resultsPending++; // Each end will cause a result to come back.
574 
575 			if (havesSent == 32 && !statelessRPC) {
576 				// On the first block we race ahead and try to send
577 				// more of the second block while waiting for the
578 				// remote to respond to our first block request.
579 				// This keeps us one block ahead of the peer.
580 				//
581 				continue;
582 			}
583 
584 			READ_RESULT: for (;;) {
585 				final AckNackResult anr = pckIn.readACK(ackId);
586 				switch (anr) {
587 				case NAK:
588 					// More have lines are necessary to compute the
589 					// pack on the remote side. Keep doing that.
590 					//
591 					resultsPending--;
592 					break READ_RESULT;
593 
594 				case ACK:
595 					// The remote side is happy and knows exactly what
596 					// to send us. There is no further negotiation and
597 					// we can break out immediately.
598 					//
599 					multiAck = MultiAck.OFF;
600 					resultsPending = 0;
601 					receivedAck = true;
602 					if (statelessRPC)
603 						state.writeTo(out, null);
604 					break SEND_HAVES;
605 
606 				case ACK_CONTINUE:
607 				case ACK_COMMON:
608 				case ACK_READY:
609 					// The server knows this commit (ackId). We don't
610 					// need to send any further along its ancestry, but
611 					// we need to continue to talk about other parts of
612 					// our local history.
613 					//
614 					markCommon(walk.parseAny(ackId), anr);
615 					receivedAck = true;
616 					receivedContinue = true;
617 					havesSinceLastContinue = 0;
618 					if (anr == AckNackResult.ACK_READY)
619 						receivedReady = true;
620 					break;
621 				}
622 
623 				if (monitor.isCancelled())
624 					throw new CancelledException();
625 			}
626 
627 			if (noDone & receivedReady)
628 				break SEND_HAVES;
629 			if (statelessRPC)
630 				state.writeTo(out, null);
631 
632 			if (receivedContinue && havesSinceLastContinue > MAX_HAVES) {
633 				// Our history must be really different from the remote's.
634 				// We just sent a whole slew of have lines, and it did not
635 				// recognize any of them. Avoid sending our entire history
636 				// to them by giving up early.
637 				//
638 				break SEND_HAVES;
639 			}
640 		}
641 
642 		// Tell the remote side we have run out of things to talk about.
643 		//
644 		if (monitor.isCancelled())
645 			throw new CancelledException();
646 
647 		if (!receivedReady || !noDone) {
648 			// When statelessRPC is true we should always leave SEND_HAVES
649 			// loop above while in the middle of a request. This allows us
650 			// to just write done immediately.
651 			//
652 			pckOut.writeString("done\n"); //$NON-NLS-1$
653 			pckOut.flush();
654 		}
655 
656 		if (!receivedAck) {
657 			// Apparently if we have never received an ACK earlier
658 			// there is one more result expected from the done we
659 			// just sent to the remote.
660 			//
661 			multiAck = MultiAck.OFF;
662 			resultsPending++;
663 		}
664 
665 		READ_RESULT: while (resultsPending > 0 || multiAck != MultiAck.OFF) {
666 			final AckNackResult anr = pckIn.readACK(ackId);
667 			resultsPending--;
668 			switch (anr) {
669 			case NAK:
670 				// A NAK is a response to an end we queued earlier
671 				// we eat it and look for another ACK/NAK message.
672 				//
673 				break;
674 
675 			case ACK:
676 				// A solitary ACK at this point means the remote won't
677 				// speak anymore, but is going to send us a pack now.
678 				//
679 				break READ_RESULT;
680 
681 			case ACK_CONTINUE:
682 			case ACK_COMMON:
683 			case ACK_READY:
684 				// We will expect a normal ACK to break out of the loop.
685 				//
686 				multiAck = MultiAck.CONTINUE;
687 				break;
688 			}
689 
690 			if (monitor.isCancelled())
691 				throw new CancelledException();
692 		}
693 	}
694 
695 	private void negotiateBegin() throws IOException {
696 		walk.resetRetain(REACHABLE, ADVERTISED);
697 		walk.markStart(reachableCommits);
698 		walk.sort(RevSort.COMMIT_TIME_DESC);
699 		walk.setRevFilter(new RevFilter() {
700 			@Override
701 			public RevFilter clone() {
702 				return this;
703 			}
704 
705 			@Override
706 			public boolean include(final RevWalk walker, final RevCommit c) {
707 				final boolean remoteKnowsIsCommon = c.has(COMMON);
708 				if (c.has(ADVERTISED)) {
709 					// Remote advertised this, and we have it, hence common.
710 					// Whether or not the remote knows that fact is tested
711 					// before we added the flag. If the remote doesn't know
712 					// we have to still send them this object.
713 					//
714 					c.add(COMMON);
715 				}
716 				return !remoteKnowsIsCommon;
717 			}
718 
719 			@Override
720 			public boolean requiresCommitBody() {
721 				return false;
722 			}
723 		});
724 	}
725 
726 	private void markRefsAdvertised() {
727 		for (final Ref r : getRefs()) {
728 			markAdvertised(r.getObjectId());
729 			if (r.getPeeledObjectId() != null)
730 				markAdvertised(r.getPeeledObjectId());
731 		}
732 	}
733 
734 	private void markAdvertised(final AnyObjectId id) {
735 		try {
736 			walk.parseAny(id).add(ADVERTISED);
737 		} catch (IOException readError) {
738 			// We probably just do not have this object locally.
739 		}
740 	}
741 
742 	private void markCommon(final RevObject obj, final AckNackResult anr)
743 			throws IOException {
744 		if (statelessRPC && anr == AckNackResult.ACK_COMMON && !obj.has(STATE)) {
745 			StringBuilder s;
746 
747 			s = new StringBuilder(6 + Constants.OBJECT_ID_STRING_LENGTH);
748 			s.append("have "); //$NON-NLS-1$
749 			s.append(obj.name());
750 			s.append('\n');
751 			pckState.writeString(s.toString());
752 			obj.add(STATE);
753 		}
754 		obj.add(COMMON);
755 		if (obj instanceof RevCommit)
756 			((RevCommit) obj).carry(COMMON);
757 	}
758 
759 	private void receivePack(final ProgressMonitor monitor,
760 			OutputStream outputStream) throws IOException {
761 		onReceivePack();
762 		InputStream input = in;
763 		if (sideband)
764 			input = new SideBandInputStream(input, monitor, getMessageWriter(),
765 					outputStream);
766 
767 		try (ObjectInserter ins = local.newObjectInserter()) {
768 			PackParser parser = ins.newPackParser(input);
769 			parser.setAllowThin(thinPack);
770 			parser.setObjectChecker(transport.getObjectChecker());
771 			parser.setLockMessage(lockMessage);
772 			packLock = parser.parse(monitor);
773 			ins.flush();
774 		}
775 	}
776 
777 	/**
778 	 * Notification event delivered just before the pack is received from the
779 	 * network. This event can be used by RPC such as {@link TransportHttp} to
780 	 * disable its request magic and ensure the pack stream is read correctly.
781 	 *
782 	 * @since 2.0
783 	 */
784 	protected void onReceivePack() {
785 		// By default do nothing for TCP based protocols.
786 	}
787 
788 	private static class CancelledException extends Exception {
789 		private static final long serialVersionUID = 1L;
790 	}
791 }