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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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.util.ArrayList;
  49. import java.util.HashSet;
  50. import java.util.Iterator;
  51. import java.util.List;
  52. import java.util.Map;
  53. import java.util.Set;
  54. import org.eclipse.jgit.errors.PackProtocolException;
  55. import org.eclipse.jgit.lib.NullProgressMonitor;
  56. import org.eclipse.jgit.lib.ObjectId;
  57. import org.eclipse.jgit.lib.PackWriter;
  58. import org.eclipse.jgit.lib.ProgressMonitor;
  59. import org.eclipse.jgit.lib.Ref;
  60. import org.eclipse.jgit.lib.Repository;
  61. import org.eclipse.jgit.revwalk.RevCommit;
  62. import org.eclipse.jgit.revwalk.RevFlag;
  63. import org.eclipse.jgit.revwalk.RevFlagSet;
  64. import org.eclipse.jgit.revwalk.RevObject;
  65. import org.eclipse.jgit.revwalk.RevTag;
  66. import org.eclipse.jgit.revwalk.RevWalk;
  67. import org.eclipse.jgit.transport.BasePackFetchConnection.MultiAck;
  68. import org.eclipse.jgit.transport.RefAdvertiser.PacketLineOutRefAdvertiser;
  69. import org.eclipse.jgit.util.io.InterruptTimer;
  70. import org.eclipse.jgit.util.io.TimeoutInputStream;
  71. import org.eclipse.jgit.util.io.TimeoutOutputStream;
  72. /**
  73. * Implements the server side of a fetch connection, transmitting objects.
  74. */
  75. public class UploadPack {
  76. static final String OPTION_INCLUDE_TAG = BasePackFetchConnection.OPTION_INCLUDE_TAG;
  77. static final String OPTION_MULTI_ACK = BasePackFetchConnection.OPTION_MULTI_ACK;
  78. static final String OPTION_MULTI_ACK_DETAILED = BasePackFetchConnection.OPTION_MULTI_ACK_DETAILED;
  79. static final String OPTION_THIN_PACK = BasePackFetchConnection.OPTION_THIN_PACK;
  80. static final String OPTION_SIDE_BAND = BasePackFetchConnection.OPTION_SIDE_BAND;
  81. static final String OPTION_SIDE_BAND_64K = BasePackFetchConnection.OPTION_SIDE_BAND_64K;
  82. static final String OPTION_OFS_DELTA = BasePackFetchConnection.OPTION_OFS_DELTA;
  83. static final String OPTION_NO_PROGRESS = BasePackFetchConnection.OPTION_NO_PROGRESS;
  84. /** Database we read the objects from. */
  85. private final Repository db;
  86. /** Revision traversal support over {@link #db}. */
  87. private final RevWalk walk;
  88. /** Timeout in seconds to wait for client interaction. */
  89. private int timeout;
  90. /**
  91. * Is the client connection a bi-directional socket or pipe?
  92. * <p>
  93. * If true, this class assumes it can perform multiple read and write cycles
  94. * with the client over the input and output streams. This matches the
  95. * functionality available with a standard TCP/IP connection, or a local
  96. * operating system or in-memory pipe.
  97. * <p>
  98. * If false, this class runs in a read everything then output results mode,
  99. * making it suitable for single round-trip systems RPCs such as HTTP.
  100. */
  101. private boolean biDirectionalPipe = true;
  102. /** Timer to manage {@link #timeout}. */
  103. private InterruptTimer timer;
  104. private InputStream rawIn;
  105. private OutputStream rawOut;
  106. private PacketLineIn pckIn;
  107. private PacketLineOut pckOut;
  108. /** The refs we advertised as existing at the start of the connection. */
  109. private Map<String, Ref> refs;
  110. /** Filter used while advertising the refs to the client. */
  111. private RefFilter refFilter;
  112. /** Capabilities requested by the client. */
  113. private final Set<String> options = new HashSet<String>();
  114. /** Objects the client wants to obtain. */
  115. private final List<RevObject> wantAll = new ArrayList<RevObject>();
  116. /** Objects the client wants to obtain. */
  117. private final List<RevCommit> wantCommits = new ArrayList<RevCommit>();
  118. /** Objects on both sides, these don't have to be sent. */
  119. private final List<RevObject> commonBase = new ArrayList<RevObject>();
  120. /** null if {@link #commonBase} should be examined again. */
  121. private Boolean okToGiveUp;
  122. /** Marked on objects we sent in our advertisement list. */
  123. private final RevFlag ADVERTISED;
  124. /** Marked on objects the client has asked us to give them. */
  125. private final RevFlag WANT;
  126. /** Marked on objects both we and the client have. */
  127. private final RevFlag PEER_HAS;
  128. /** Marked on objects in {@link #commonBase}. */
  129. private final RevFlag COMMON;
  130. private final RevFlagSet SAVE;
  131. private MultiAck multiAck = MultiAck.OFF;
  132. /**
  133. * Create a new pack upload for an open repository.
  134. *
  135. * @param copyFrom
  136. * the source repository.
  137. */
  138. public UploadPack(final Repository copyFrom) {
  139. db = copyFrom;
  140. walk = new RevWalk(db);
  141. walk.setRetainBody(false);
  142. ADVERTISED = walk.newFlag("ADVERTISED");
  143. WANT = walk.newFlag("WANT");
  144. PEER_HAS = walk.newFlag("PEER_HAS");
  145. COMMON = walk.newFlag("COMMON");
  146. walk.carry(PEER_HAS);
  147. SAVE = new RevFlagSet();
  148. SAVE.add(ADVERTISED);
  149. SAVE.add(WANT);
  150. SAVE.add(PEER_HAS);
  151. refFilter = RefFilter.DEFAULT;
  152. }
  153. /** @return the repository this upload is reading from. */
  154. public final Repository getRepository() {
  155. return db;
  156. }
  157. /** @return the RevWalk instance used by this connection. */
  158. public final RevWalk getRevWalk() {
  159. return walk;
  160. }
  161. /** @return timeout (in seconds) before aborting an IO operation. */
  162. public int getTimeout() {
  163. return timeout;
  164. }
  165. /**
  166. * Set the timeout before willing to abort an IO call.
  167. *
  168. * @param seconds
  169. * number of seconds to wait (with no data transfer occurring)
  170. * before aborting an IO read or write operation with the
  171. * connected client.
  172. */
  173. public void setTimeout(final int seconds) {
  174. timeout = seconds;
  175. }
  176. /**
  177. * @return true if this class expects a bi-directional pipe opened between
  178. * the client and itself. The default is true.
  179. */
  180. public boolean isBiDirectionalPipe() {
  181. return biDirectionalPipe;
  182. }
  183. /**
  184. * @param twoWay
  185. * if true, this class will assume the socket is a fully
  186. * bidirectional pipe between the two peers and takes advantage
  187. * of that by first transmitting the known refs, then waiting to
  188. * read commands. If false, this class assumes it must read the
  189. * commands before writing output and does not perform the
  190. * initial advertising.
  191. */
  192. public void setBiDirectionalPipe(final boolean twoWay) {
  193. biDirectionalPipe = twoWay;
  194. }
  195. /** @return the filter used while advertising the refs to the client */
  196. public RefFilter getRefFilter() {
  197. return refFilter;
  198. }
  199. /**
  200. * Set the filter used while advertising the refs to the client.
  201. * <p>
  202. * Only refs allowed by this filter will be sent to the client. This can
  203. * be used by a server to restrict the list of references the client can
  204. * obtain through clone or fetch, effectively limiting the access to only
  205. * certain refs.
  206. *
  207. * @param refFilter
  208. * the filter; may be null to show all refs.
  209. */
  210. public void setRefFilter(final RefFilter refFilter) {
  211. this.refFilter = refFilter != null ? refFilter : RefFilter.DEFAULT;
  212. }
  213. /**
  214. * Execute the upload task on the socket.
  215. *
  216. * @param input
  217. * raw input to read client commands from. Caller must ensure the
  218. * input is buffered, otherwise read performance may suffer.
  219. * @param output
  220. * response back to the Git network client, to write the pack
  221. * data onto. Caller must ensure the output is buffered,
  222. * otherwise write performance may suffer.
  223. * @param messages
  224. * secondary "notice" channel to send additional messages out
  225. * through. When run over SSH this should be tied back to the
  226. * standard error channel of the command execution. For most
  227. * other network connections this should be null.
  228. * @throws IOException
  229. */
  230. public void upload(final InputStream input, final OutputStream output,
  231. final OutputStream messages) throws IOException {
  232. try {
  233. rawIn = input;
  234. rawOut = output;
  235. if (timeout > 0) {
  236. final Thread caller = Thread.currentThread();
  237. timer = new InterruptTimer(caller.getName() + "-Timer");
  238. TimeoutInputStream i = new TimeoutInputStream(rawIn, timer);
  239. TimeoutOutputStream o = new TimeoutOutputStream(rawOut, timer);
  240. i.setTimeout(timeout * 1000);
  241. o.setTimeout(timeout * 1000);
  242. rawIn = i;
  243. rawOut = o;
  244. }
  245. pckIn = new PacketLineIn(rawIn);
  246. pckOut = new PacketLineOut(rawOut);
  247. service();
  248. } finally {
  249. if (timer != null) {
  250. try {
  251. timer.terminate();
  252. } finally {
  253. timer = null;
  254. }
  255. }
  256. }
  257. }
  258. private void service() throws IOException {
  259. if (biDirectionalPipe)
  260. sendAdvertisedRefs(new PacketLineOutRefAdvertiser(pckOut));
  261. else {
  262. refs = refFilter.filter(db.getAllRefs());
  263. for (Ref r : refs.values()) {
  264. try {
  265. walk.parseAny(r.getObjectId()).add(ADVERTISED);
  266. } catch (IOException e) {
  267. // Skip missing/corrupt objects
  268. }
  269. }
  270. }
  271. recvWants();
  272. if (wantAll.isEmpty())
  273. return;
  274. if (options.contains(OPTION_MULTI_ACK_DETAILED))
  275. multiAck = MultiAck.DETAILED;
  276. else if (options.contains(OPTION_MULTI_ACK))
  277. multiAck = MultiAck.CONTINUE;
  278. else
  279. multiAck = MultiAck.OFF;
  280. if (negotiate())
  281. sendPack();
  282. }
  283. /**
  284. * Generate an advertisement of available refs and capabilities.
  285. *
  286. * @param adv
  287. * the advertisement formatter.
  288. * @throws IOException
  289. * the formatter failed to write an advertisement.
  290. */
  291. public void sendAdvertisedRefs(final RefAdvertiser adv) throws IOException {
  292. adv.init(walk, ADVERTISED);
  293. adv.advertiseCapability(OPTION_INCLUDE_TAG);
  294. adv.advertiseCapability(OPTION_MULTI_ACK_DETAILED);
  295. adv.advertiseCapability(OPTION_MULTI_ACK);
  296. adv.advertiseCapability(OPTION_OFS_DELTA);
  297. adv.advertiseCapability(OPTION_SIDE_BAND);
  298. adv.advertiseCapability(OPTION_SIDE_BAND_64K);
  299. adv.advertiseCapability(OPTION_THIN_PACK);
  300. adv.advertiseCapability(OPTION_NO_PROGRESS);
  301. adv.setDerefTags(true);
  302. refs = refFilter.filter(db.getAllRefs());
  303. adv.send(refs);
  304. adv.end();
  305. }
  306. private void recvWants() throws IOException {
  307. boolean isFirst = true;
  308. for (;; isFirst = false) {
  309. String line;
  310. try {
  311. line = pckIn.readString();
  312. } catch (EOFException eof) {
  313. if (isFirst)
  314. break;
  315. throw eof;
  316. }
  317. if (line == PacketLineIn.END)
  318. break;
  319. if (!line.startsWith("want ") || line.length() < 45)
  320. throw new PackProtocolException("expected want; got " + line);
  321. if (isFirst && line.length() > 45) {
  322. String opt = line.substring(45);
  323. if (opt.startsWith(" "))
  324. opt = opt.substring(1);
  325. for (String c : opt.split(" "))
  326. options.add(c);
  327. line = line.substring(0, 45);
  328. }
  329. final ObjectId id = ObjectId.fromString(line.substring(5));
  330. final RevObject o;
  331. try {
  332. o = walk.parseAny(id);
  333. } catch (IOException e) {
  334. throw new PackProtocolException(id.name() + " not valid", e);
  335. }
  336. if (!o.has(ADVERTISED))
  337. throw new PackProtocolException(id.name() + " not valid");
  338. want(o);
  339. }
  340. }
  341. private void want(RevObject o) {
  342. if (!o.has(WANT)) {
  343. o.add(WANT);
  344. wantAll.add(o);
  345. if (o instanceof RevCommit)
  346. wantCommits.add((RevCommit) o);
  347. else if (o instanceof RevTag) {
  348. do {
  349. o = ((RevTag) o).getObject();
  350. } while (o instanceof RevTag);
  351. if (o instanceof RevCommit)
  352. want(o);
  353. }
  354. }
  355. }
  356. private boolean negotiate() throws IOException {
  357. ObjectId last = ObjectId.zeroId();
  358. for (;;) {
  359. String line;
  360. try {
  361. line = pckIn.readString();
  362. } catch (EOFException eof) {
  363. throw eof;
  364. }
  365. if (line == PacketLineIn.END) {
  366. if (commonBase.isEmpty() || multiAck != MultiAck.OFF)
  367. pckOut.writeString("NAK\n");
  368. pckOut.flush();
  369. if (!biDirectionalPipe)
  370. return false;
  371. } else if (line.startsWith("have ") && line.length() == 45) {
  372. final ObjectId id = ObjectId.fromString(line.substring(5));
  373. if (matchHave(id)) {
  374. // Both sides have the same object; let the client know.
  375. //
  376. last = id;
  377. switch (multiAck) {
  378. case OFF:
  379. if (commonBase.size() == 1)
  380. pckOut.writeString("ACK " + id.name() + "\n");
  381. break;
  382. case CONTINUE:
  383. pckOut.writeString("ACK " + id.name() + " continue\n");
  384. break;
  385. case DETAILED:
  386. pckOut.writeString("ACK " + id.name() + " common\n");
  387. break;
  388. }
  389. } else if (okToGiveUp()) {
  390. // They have this object; we don't.
  391. //
  392. switch (multiAck) {
  393. case OFF:
  394. break;
  395. case CONTINUE:
  396. pckOut.writeString("ACK " + id.name() + " continue\n");
  397. break;
  398. case DETAILED:
  399. pckOut.writeString("ACK " + id.name() + " ready\n");
  400. break;
  401. }
  402. }
  403. } else if (line.equals("done")) {
  404. if (commonBase.isEmpty())
  405. pckOut.writeString("NAK\n");
  406. else if (multiAck != MultiAck.OFF)
  407. pckOut.writeString("ACK " + last.name() + "\n");
  408. return true;
  409. } else {
  410. throw new PackProtocolException("expected have; got " + line);
  411. }
  412. }
  413. }
  414. private boolean matchHave(final ObjectId id) {
  415. final RevObject o;
  416. try {
  417. o = walk.parseAny(id);
  418. } catch (IOException err) {
  419. return false;
  420. }
  421. if (!o.has(PEER_HAS)) {
  422. o.add(PEER_HAS);
  423. if (o instanceof RevCommit)
  424. ((RevCommit) o).carry(PEER_HAS);
  425. addCommonBase(o);
  426. }
  427. return true;
  428. }
  429. private void addCommonBase(final RevObject o) {
  430. if (!o.has(COMMON)) {
  431. o.add(COMMON);
  432. commonBase.add(o);
  433. okToGiveUp = null;
  434. }
  435. }
  436. private boolean okToGiveUp() throws PackProtocolException {
  437. if (okToGiveUp == null)
  438. okToGiveUp = Boolean.valueOf(okToGiveUpImp());
  439. return okToGiveUp.booleanValue();
  440. }
  441. private boolean okToGiveUpImp() throws PackProtocolException {
  442. if (commonBase.isEmpty())
  443. return false;
  444. try {
  445. for (final Iterator<RevCommit> i = wantCommits.iterator(); i
  446. .hasNext();) {
  447. final RevCommit want = i.next();
  448. if (wantSatisfied(want))
  449. i.remove();
  450. }
  451. } catch (IOException e) {
  452. throw new PackProtocolException("internal revision error", e);
  453. }
  454. return wantCommits.isEmpty();
  455. }
  456. private boolean wantSatisfied(final RevCommit want) throws IOException {
  457. walk.resetRetain(SAVE);
  458. walk.markStart(want);
  459. for (;;) {
  460. final RevCommit c = walk.next();
  461. if (c == null)
  462. break;
  463. if (c.has(PEER_HAS)) {
  464. addCommonBase(c);
  465. return true;
  466. }
  467. }
  468. return false;
  469. }
  470. private void sendPack() throws IOException {
  471. final boolean thin = options.contains(OPTION_THIN_PACK);
  472. final boolean progress = !options.contains(OPTION_NO_PROGRESS);
  473. final boolean sideband = options.contains(OPTION_SIDE_BAND)
  474. || options.contains(OPTION_SIDE_BAND_64K);
  475. ProgressMonitor pm = NullProgressMonitor.INSTANCE;
  476. OutputStream packOut = rawOut;
  477. if (sideband) {
  478. int bufsz = SideBandOutputStream.SMALL_BUF;
  479. if (options.contains(OPTION_SIDE_BAND_64K))
  480. bufsz = SideBandOutputStream.MAX_BUF;
  481. packOut = new SideBandOutputStream(SideBandOutputStream.CH_DATA,
  482. bufsz, rawOut);
  483. if (progress)
  484. pm = new SideBandProgressMonitor(new SideBandOutputStream(
  485. SideBandOutputStream.CH_PROGRESS, bufsz, rawOut));
  486. }
  487. final PackWriter pw;
  488. pw = new PackWriter(db, pm, NullProgressMonitor.INSTANCE);
  489. pw.setDeltaBaseAsOffset(options.contains(OPTION_OFS_DELTA));
  490. pw.setThin(thin);
  491. pw.preparePack(wantAll, commonBase);
  492. if (options.contains(OPTION_INCLUDE_TAG)) {
  493. for (final Ref r : refs.values()) {
  494. final RevObject o;
  495. try {
  496. o = walk.parseAny(r.getObjectId());
  497. } catch (IOException e) {
  498. continue;
  499. }
  500. if (o.has(WANT) || !(o instanceof RevTag))
  501. continue;
  502. final RevTag t = (RevTag) o;
  503. if (!pw.willInclude(t) && pw.willInclude(t.getObject()))
  504. pw.addObject(t);
  505. }
  506. }
  507. pw.writePack(packOut);
  508. packOut.flush();
  509. if (sideband)
  510. pckOut.end();
  511. }
  512. }