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

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