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

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