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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570
  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 static org.eclipse.jgit.lib.RefDatabase.ALL;
  45. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_AGENT;
  46. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_ALLOW_REACHABLE_SHA1_IN_WANT;
  47. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_ALLOW_TIP_SHA1_IN_WANT;
  48. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_INCLUDE_TAG;
  49. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_MULTI_ACK;
  50. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_MULTI_ACK_DETAILED;
  51. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_NO_DONE;
  52. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_NO_PROGRESS;
  53. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_OFS_DELTA;
  54. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SHALLOW;
  55. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SIDE_BAND;
  56. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SIDE_BAND_64K;
  57. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_THIN_PACK;
  58. import java.io.EOFException;
  59. import java.io.IOException;
  60. import java.io.InputStream;
  61. import java.io.OutputStream;
  62. import java.text.MessageFormat;
  63. import java.util.ArrayList;
  64. import java.util.Collection;
  65. import java.util.Collections;
  66. import java.util.HashSet;
  67. import java.util.List;
  68. import java.util.Map;
  69. import java.util.Set;
  70. import org.eclipse.jgit.errors.CorruptObjectException;
  71. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  72. import org.eclipse.jgit.errors.MissingObjectException;
  73. import org.eclipse.jgit.errors.PackProtocolException;
  74. import org.eclipse.jgit.internal.JGitText;
  75. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  76. import org.eclipse.jgit.lib.Constants;
  77. import org.eclipse.jgit.lib.NullProgressMonitor;
  78. import org.eclipse.jgit.lib.ObjectId;
  79. import org.eclipse.jgit.lib.ProgressMonitor;
  80. import org.eclipse.jgit.lib.Ref;
  81. import org.eclipse.jgit.lib.RefDatabase;
  82. import org.eclipse.jgit.lib.Repository;
  83. import org.eclipse.jgit.revwalk.AsyncRevObjectQueue;
  84. import org.eclipse.jgit.revwalk.DepthWalk;
  85. import org.eclipse.jgit.revwalk.ObjectWalk;
  86. import org.eclipse.jgit.revwalk.RevCommit;
  87. import org.eclipse.jgit.revwalk.RevFlag;
  88. import org.eclipse.jgit.revwalk.RevFlagSet;
  89. import org.eclipse.jgit.revwalk.RevObject;
  90. import org.eclipse.jgit.revwalk.RevTag;
  91. import org.eclipse.jgit.revwalk.RevWalk;
  92. import org.eclipse.jgit.revwalk.filter.CommitTimeRevFilter;
  93. import org.eclipse.jgit.storage.pack.PackConfig;
  94. import org.eclipse.jgit.storage.pack.PackStatistics;
  95. import org.eclipse.jgit.transport.GitProtocolConstants.MultiAck;
  96. import org.eclipse.jgit.transport.RefAdvertiser.PacketLineOutRefAdvertiser;
  97. import org.eclipse.jgit.util.io.InterruptTimer;
  98. import org.eclipse.jgit.util.io.NullOutputStream;
  99. import org.eclipse.jgit.util.io.TimeoutInputStream;
  100. import org.eclipse.jgit.util.io.TimeoutOutputStream;
  101. /**
  102. * Implements the server side of a fetch connection, transmitting objects.
  103. */
  104. public class UploadPack {
  105. /** Policy the server uses to validate client requests */
  106. public static enum RequestPolicy {
  107. /** Client may only ask for objects the server advertised a reference for. */
  108. ADVERTISED,
  109. /**
  110. * Client may ask for any commit reachable from a reference advertised by
  111. * the server.
  112. */
  113. REACHABLE_COMMIT,
  114. /**
  115. * Client may ask for objects that are the tip of any reference, even if not
  116. * advertised.
  117. * <p>
  118. * This may happen, for example, when a custom {@link RefFilter} is set.
  119. *
  120. * @since 3.1
  121. */
  122. TIP,
  123. /**
  124. * Client may ask for any commit reachable from any reference, even if that
  125. * reference wasn't advertised.
  126. *
  127. * @since 3.1
  128. */
  129. REACHABLE_COMMIT_TIP,
  130. /** Client may ask for any SHA-1 in the repository. */
  131. ANY;
  132. }
  133. /**
  134. * Validator for client requests.
  135. *
  136. * @since 3.1
  137. */
  138. public interface RequestValidator {
  139. /**
  140. * Check a list of client wants against the request policy.
  141. *
  142. * @param up
  143. * {@link UploadPack} instance.
  144. * @param wants
  145. * objects the client requested that were not advertised.
  146. *
  147. * @throws PackProtocolException
  148. * if one or more wants is not valid.
  149. * @throws IOException
  150. * if a low-level exception occurred.
  151. * @since 3.1
  152. */
  153. void checkWants(UploadPack up, List<ObjectId> wants)
  154. throws PackProtocolException, IOException;
  155. }
  156. /** Data in the first line of a request, the line itself plus options. */
  157. public static class FirstLine {
  158. private final String line;
  159. private final Set<String> options;
  160. /**
  161. * Parse the first line of a receive-pack request.
  162. *
  163. * @param line
  164. * line from the client.
  165. */
  166. public FirstLine(String line) {
  167. if (line.length() > 45) {
  168. final HashSet<String> opts = new HashSet<String>();
  169. String opt = line.substring(45);
  170. if (opt.startsWith(" ")) //$NON-NLS-1$
  171. opt = opt.substring(1);
  172. for (String c : opt.split(" ")) //$NON-NLS-1$
  173. opts.add(c);
  174. this.line = line.substring(0, 45);
  175. this.options = Collections.unmodifiableSet(opts);
  176. } else {
  177. this.line = line;
  178. this.options = Collections.emptySet();
  179. }
  180. }
  181. /** @return non-capabilities part of the line. */
  182. public String getLine() {
  183. return line;
  184. }
  185. /** @return options parsed from the line. */
  186. public Set<String> getOptions() {
  187. return options;
  188. }
  189. }
  190. /** Database we read the objects from. */
  191. private final Repository db;
  192. /** Revision traversal support over {@link #db}. */
  193. private final RevWalk walk;
  194. /** Configuration to pass into the PackWriter. */
  195. private PackConfig packConfig;
  196. /** Configuration for various transfer options. */
  197. private TransferConfig transferConfig;
  198. /** Timeout in seconds to wait for client interaction. */
  199. private int timeout;
  200. /**
  201. * Is the client connection a bi-directional socket or pipe?
  202. * <p>
  203. * If true, this class assumes it can perform multiple read and write cycles
  204. * with the client over the input and output streams. This matches the
  205. * functionality available with a standard TCP/IP connection, or a local
  206. * operating system or in-memory pipe.
  207. * <p>
  208. * If false, this class runs in a read everything then output results mode,
  209. * making it suitable for single round-trip systems RPCs such as HTTP.
  210. */
  211. private boolean biDirectionalPipe = true;
  212. /** Timer to manage {@link #timeout}. */
  213. private InterruptTimer timer;
  214. private InputStream rawIn;
  215. private OutputStream rawOut;
  216. private PacketLineIn pckIn;
  217. private PacketLineOut pckOut;
  218. private OutputStream msgOut = NullOutputStream.INSTANCE;
  219. /** The refs we advertised as existing at the start of the connection. */
  220. private Map<String, Ref> refs;
  221. /** Hook used while advertising the refs to the client. */
  222. private AdvertiseRefsHook advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  223. /** Filter used while advertising the refs to the client. */
  224. private RefFilter refFilter = RefFilter.DEFAULT;
  225. /** Hook handling the various upload phases. */
  226. private PreUploadHook preUploadHook = PreUploadHook.NULL;
  227. /** Hook for taking post upload actions. */
  228. private PostUploadHook postUploadHook = PostUploadHook.NULL;
  229. /** Capabilities requested by the client. */
  230. private Set<String> options;
  231. String userAgent;
  232. /** Raw ObjectIds the client has asked for, before validating them. */
  233. private final Set<ObjectId> wantIds = new HashSet<ObjectId>();
  234. /** Objects the client wants to obtain. */
  235. private final Set<RevObject> wantAll = new HashSet<RevObject>();
  236. /** Objects on both sides, these don't have to be sent. */
  237. private final Set<RevObject> commonBase = new HashSet<RevObject>();
  238. /** Shallow commits the client already has. */
  239. private final Set<ObjectId> clientShallowCommits = new HashSet<ObjectId>();
  240. /** Shallow commits on the client which are now becoming unshallow */
  241. private final List<ObjectId> unshallowCommits = new ArrayList<ObjectId>();
  242. /** Desired depth from the client on a shallow request. */
  243. private int depth;
  244. /** Commit time of the oldest common commit, in seconds. */
  245. private int oldestTime;
  246. /** null if {@link #commonBase} should be examined again. */
  247. private Boolean okToGiveUp;
  248. private boolean sentReady;
  249. /** Objects we sent in our advertisement list, clients can ask for these. */
  250. private Set<ObjectId> advertised;
  251. /** Marked on objects the client has asked us to give them. */
  252. private final RevFlag WANT;
  253. /** Marked on objects both we and the client have. */
  254. private final RevFlag PEER_HAS;
  255. /** Marked on objects in {@link #commonBase}. */
  256. private final RevFlag COMMON;
  257. /** Objects where we found a path from the want list to a common base. */
  258. private final RevFlag SATISFIED;
  259. private final RevFlagSet SAVE;
  260. private RequestValidator requestValidator = new AdvertisedRequestValidator();
  261. private MultiAck multiAck = MultiAck.OFF;
  262. private boolean noDone;
  263. private PackStatistics statistics;
  264. @SuppressWarnings("deprecation")
  265. private UploadPackLogger logger = UploadPackLogger.NULL;
  266. /**
  267. * Create a new pack upload for an open repository.
  268. *
  269. * @param copyFrom
  270. * the source repository.
  271. */
  272. public UploadPack(final Repository copyFrom) {
  273. db = copyFrom;
  274. walk = new RevWalk(db);
  275. walk.setRetainBody(false);
  276. WANT = walk.newFlag("WANT"); //$NON-NLS-1$
  277. PEER_HAS = walk.newFlag("PEER_HAS"); //$NON-NLS-1$
  278. COMMON = walk.newFlag("COMMON"); //$NON-NLS-1$
  279. SATISFIED = walk.newFlag("SATISFIED"); //$NON-NLS-1$
  280. walk.carry(PEER_HAS);
  281. SAVE = new RevFlagSet();
  282. SAVE.add(WANT);
  283. SAVE.add(PEER_HAS);
  284. SAVE.add(COMMON);
  285. SAVE.add(SATISFIED);
  286. setTransferConfig(null);
  287. }
  288. /** @return the repository this upload is reading from. */
  289. public final Repository getRepository() {
  290. return db;
  291. }
  292. /** @return the RevWalk instance used by this connection. */
  293. public final RevWalk getRevWalk() {
  294. return walk;
  295. }
  296. /**
  297. * Get refs which were advertised to the client.
  298. *
  299. * @return all refs which were advertised to the client, or null if
  300. * {@link #setAdvertisedRefs(Map)} has not been called yet.
  301. */
  302. public final Map<String, Ref> getAdvertisedRefs() {
  303. return refs;
  304. }
  305. /**
  306. * Set the refs advertised by this UploadPack.
  307. * <p>
  308. * Intended to be called from a {@link PreUploadHook}.
  309. *
  310. * @param allRefs
  311. * explicit set of references to claim as advertised by this
  312. * UploadPack instance. This overrides any references that
  313. * may exist in the source repository. The map is passed
  314. * to the configured {@link #getRefFilter()}. If null, assumes
  315. * all refs were advertised.
  316. */
  317. public void setAdvertisedRefs(Map<String, Ref> allRefs) {
  318. if (allRefs != null)
  319. refs = allRefs;
  320. else
  321. refs = db.getAllRefs();
  322. if (refFilter == RefFilter.DEFAULT)
  323. refs = transferConfig.getRefFilter().filter(refs);
  324. else
  325. refs = refFilter.filter(refs);
  326. }
  327. /** @return timeout (in seconds) before aborting an IO operation. */
  328. public int getTimeout() {
  329. return timeout;
  330. }
  331. /**
  332. * Set the timeout before willing to abort an IO call.
  333. *
  334. * @param seconds
  335. * number of seconds to wait (with no data transfer occurring)
  336. * before aborting an IO read or write operation with the
  337. * connected client.
  338. */
  339. public void setTimeout(final int seconds) {
  340. timeout = seconds;
  341. }
  342. /**
  343. * @return true if this class expects a bi-directional pipe opened between
  344. * the client and itself. The default is true.
  345. */
  346. public boolean isBiDirectionalPipe() {
  347. return biDirectionalPipe;
  348. }
  349. /**
  350. * @param twoWay
  351. * if true, this class will assume the socket is a fully
  352. * bidirectional pipe between the two peers and takes advantage
  353. * of that by first transmitting the known refs, then waiting to
  354. * read commands. If false, this class assumes it must read the
  355. * commands before writing output and does not perform the
  356. * initial advertising.
  357. */
  358. public void setBiDirectionalPipe(final boolean twoWay) {
  359. biDirectionalPipe = twoWay;
  360. }
  361. /**
  362. * @return policy used by the service to validate client requests, or null for
  363. * a custom request validator.
  364. */
  365. public RequestPolicy getRequestPolicy() {
  366. if (requestValidator instanceof AdvertisedRequestValidator)
  367. return RequestPolicy.ADVERTISED;
  368. if (requestValidator instanceof ReachableCommitRequestValidator)
  369. return RequestPolicy.REACHABLE_COMMIT;
  370. if (requestValidator instanceof TipRequestValidator)
  371. return RequestPolicy.TIP;
  372. if (requestValidator instanceof ReachableCommitTipRequestValidator)
  373. return RequestPolicy.REACHABLE_COMMIT_TIP;
  374. if (requestValidator instanceof AnyRequestValidator)
  375. return RequestPolicy.ANY;
  376. return null;
  377. }
  378. /**
  379. * @param policy
  380. * the policy used to enforce validation of a client's want list.
  381. * By default the policy is {@link RequestPolicy#ADVERTISED},
  382. * which is the Git default requiring clients to only ask for an
  383. * object that a reference directly points to. This may be relaxed
  384. * to {@link RequestPolicy#REACHABLE_COMMIT} or
  385. * {@link RequestPolicy#REACHABLE_COMMIT_TIP} when callers have
  386. * {@link #setBiDirectionalPipe(boolean)} set to false.
  387. * Overrides any policy specified in a {@link TransferConfig}.
  388. */
  389. public void setRequestPolicy(RequestPolicy policy) {
  390. switch (policy) {
  391. case ADVERTISED:
  392. default:
  393. requestValidator = new AdvertisedRequestValidator();
  394. break;
  395. case REACHABLE_COMMIT:
  396. requestValidator = new ReachableCommitRequestValidator();
  397. break;
  398. case TIP:
  399. requestValidator = new TipRequestValidator();
  400. break;
  401. case REACHABLE_COMMIT_TIP:
  402. requestValidator = new ReachableCommitTipRequestValidator();
  403. break;
  404. case ANY:
  405. requestValidator = new AnyRequestValidator();
  406. break;
  407. }
  408. }
  409. /**
  410. * @param validator
  411. * custom validator for client want list.
  412. * @since 3.1
  413. */
  414. public void setRequestValidator(RequestValidator validator) {
  415. requestValidator = validator != null ? validator
  416. : new AdvertisedRequestValidator();
  417. }
  418. /** @return the hook used while advertising the refs to the client */
  419. public AdvertiseRefsHook getAdvertiseRefsHook() {
  420. return advertiseRefsHook;
  421. }
  422. /** @return the filter used while advertising the refs to the client */
  423. public RefFilter getRefFilter() {
  424. return refFilter;
  425. }
  426. /**
  427. * Set the hook used while advertising the refs to the client.
  428. * <p>
  429. * If the {@link AdvertiseRefsHook} chooses to call
  430. * {@link #setAdvertisedRefs(Map)}, only refs set by this hook <em>and</em>
  431. * selected by the {@link RefFilter} will be shown to the client.
  432. *
  433. * @param advertiseRefsHook
  434. * the hook; may be null to show all refs.
  435. */
  436. public void setAdvertiseRefsHook(final AdvertiseRefsHook advertiseRefsHook) {
  437. if (advertiseRefsHook != null)
  438. this.advertiseRefsHook = advertiseRefsHook;
  439. else
  440. this.advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  441. }
  442. /**
  443. * Set the filter used while advertising the refs to the client.
  444. * <p>
  445. * Only refs allowed by this filter will be sent to the client.
  446. * The filter is run against the refs specified by the
  447. * {@link AdvertiseRefsHook} (if applicable). If null or not set, uses the
  448. * filter implied by the {@link TransferConfig}.
  449. *
  450. * @param refFilter
  451. * the filter; may be null to show all refs.
  452. */
  453. public void setRefFilter(final RefFilter refFilter) {
  454. this.refFilter = refFilter != null ? refFilter : RefFilter.DEFAULT;
  455. }
  456. /** @return the configured pre upload hook. */
  457. public PreUploadHook getPreUploadHook() {
  458. return preUploadHook;
  459. }
  460. /**
  461. * Set the hook that controls how this instance will behave.
  462. *
  463. * @param hook
  464. * the hook; if null no special actions are taken.
  465. */
  466. public void setPreUploadHook(PreUploadHook hook) {
  467. preUploadHook = hook != null ? hook : PreUploadHook.NULL;
  468. }
  469. /**
  470. * @return the configured post upload hook.
  471. * @since 4.1
  472. */
  473. public PostUploadHook getPostUploadHook() {
  474. return postUploadHook;
  475. }
  476. /**
  477. * Set the hook for post upload actions (logging, repacking).
  478. *
  479. * @param hook
  480. * the hook; if null no special actions are taken.
  481. * @since 4.1
  482. */
  483. public void setPostUploadHook(PostUploadHook hook) {
  484. postUploadHook = hook != null ? hook : PostUploadHook.NULL;
  485. }
  486. /**
  487. * Set the configuration used by the pack generator.
  488. *
  489. * @param pc
  490. * configuration controlling packing parameters. If null the
  491. * source repository's settings will be used.
  492. */
  493. public void setPackConfig(PackConfig pc) {
  494. this.packConfig = pc;
  495. }
  496. /**
  497. * @param tc
  498. * configuration controlling transfer options. If null the source
  499. * repository's settings will be used.
  500. * @since 3.1
  501. */
  502. public void setTransferConfig(TransferConfig tc) {
  503. this.transferConfig = tc != null ? tc : new TransferConfig(db);
  504. if (transferConfig.isAllowTipSha1InWant()) {
  505. setRequestPolicy(transferConfig.isAllowReachableSha1InWant()
  506. ? RequestPolicy.REACHABLE_COMMIT_TIP : RequestPolicy.TIP);
  507. } else {
  508. setRequestPolicy(transferConfig.isAllowReachableSha1InWant()
  509. ? RequestPolicy.REACHABLE_COMMIT : RequestPolicy.ADVERTISED);
  510. }
  511. }
  512. /**
  513. * @return the configured logger.
  514. *
  515. * @deprecated Use {@link #getPreUploadHook()}.
  516. */
  517. @Deprecated
  518. public UploadPackLogger getLogger() {
  519. return logger;
  520. }
  521. /**
  522. * Set the logger.
  523. *
  524. * @param logger
  525. * the logger instance. If null, no logging occurs.
  526. * @deprecated Use {@link #setPreUploadHook(PreUploadHook)}.
  527. */
  528. @Deprecated
  529. public void setLogger(UploadPackLogger logger) {
  530. this.logger = logger;
  531. }
  532. /**
  533. * Check whether the client expects a side-band stream.
  534. *
  535. * @return true if the client has advertised a side-band capability, false
  536. * otherwise.
  537. * @throws RequestNotYetReadException
  538. * if the client's request has not yet been read from the wire, so
  539. * we do not know if they expect side-band. Note that the client
  540. * may have already written the request, it just has not been
  541. * read.
  542. */
  543. public boolean isSideBand() throws RequestNotYetReadException {
  544. if (options == null)
  545. throw new RequestNotYetReadException();
  546. return (options.contains(OPTION_SIDE_BAND)
  547. || options.contains(OPTION_SIDE_BAND_64K));
  548. }
  549. /**
  550. * Execute the upload task on the socket.
  551. *
  552. * @param input
  553. * raw input to read client commands from. Caller must ensure the
  554. * input is buffered, otherwise read performance may suffer.
  555. * @param output
  556. * response back to the Git network client, to write the pack
  557. * data onto. Caller must ensure the output is buffered,
  558. * otherwise write performance may suffer.
  559. * @param messages
  560. * secondary "notice" channel to send additional messages out
  561. * through. When run over SSH this should be tied back to the
  562. * standard error channel of the command execution. For most
  563. * other network connections this should be null.
  564. * @throws IOException
  565. */
  566. public void upload(final InputStream input, final OutputStream output,
  567. final OutputStream messages) throws IOException {
  568. try {
  569. rawIn = input;
  570. rawOut = output;
  571. if (messages != null)
  572. msgOut = messages;
  573. if (timeout > 0) {
  574. final Thread caller = Thread.currentThread();
  575. timer = new InterruptTimer(caller.getName() + "-Timer"); //$NON-NLS-1$
  576. TimeoutInputStream i = new TimeoutInputStream(rawIn, timer);
  577. TimeoutOutputStream o = new TimeoutOutputStream(rawOut, timer);
  578. i.setTimeout(timeout * 1000);
  579. o.setTimeout(timeout * 1000);
  580. rawIn = i;
  581. rawOut = o;
  582. }
  583. pckIn = new PacketLineIn(rawIn);
  584. pckOut = new PacketLineOut(rawOut);
  585. service();
  586. } finally {
  587. msgOut = NullOutputStream.INSTANCE;
  588. walk.close();
  589. if (timer != null) {
  590. try {
  591. timer.terminate();
  592. } finally {
  593. timer = null;
  594. }
  595. }
  596. }
  597. }
  598. /**
  599. * Get the PackWriter's statistics if a pack was sent to the client.
  600. *
  601. * @return statistics about pack output, if a pack was sent. Null if no pack
  602. * was sent, such as during the negotiation phase of a smart HTTP
  603. * connection, or if the client was already up-to-date.
  604. * @since 3.0
  605. * @deprecated Use {@link #getStatistics()}.
  606. */
  607. @Deprecated
  608. public PackWriter.Statistics getPackStatistics() {
  609. return statistics == null ? null
  610. : new PackWriter.Statistics(statistics);
  611. }
  612. /**
  613. * Get the PackWriter's statistics if a pack was sent to the client.
  614. *
  615. * @return statistics about pack output, if a pack was sent. Null if no pack
  616. * was sent, such as during the negotiation phase of a smart HTTP
  617. * connection, or if the client was already up-to-date.
  618. * @since 4.1
  619. */
  620. public PackStatistics getStatistics() {
  621. return statistics;
  622. }
  623. private Map<String, Ref> getAdvertisedOrDefaultRefs() throws IOException {
  624. if (refs == null)
  625. setAdvertisedRefs(db.getRefDatabase().getRefs(RefDatabase.ALL));
  626. return refs;
  627. }
  628. private void service() throws IOException {
  629. boolean sendPack;
  630. try {
  631. if (biDirectionalPipe)
  632. sendAdvertisedRefs(new PacketLineOutRefAdvertiser(pckOut));
  633. else if (requestValidator instanceof AnyRequestValidator)
  634. advertised = Collections.emptySet();
  635. else
  636. advertised = refIdSet(getAdvertisedOrDefaultRefs().values());
  637. recvWants();
  638. if (wantIds.isEmpty()) {
  639. preUploadHook.onBeginNegotiateRound(this, wantIds, 0);
  640. preUploadHook.onEndNegotiateRound(this, wantIds, 0, 0, false);
  641. return;
  642. }
  643. if (options.contains(OPTION_MULTI_ACK_DETAILED)) {
  644. multiAck = MultiAck.DETAILED;
  645. noDone = options.contains(OPTION_NO_DONE);
  646. } else if (options.contains(OPTION_MULTI_ACK))
  647. multiAck = MultiAck.CONTINUE;
  648. else
  649. multiAck = MultiAck.OFF;
  650. if (!clientShallowCommits.isEmpty())
  651. verifyClientShallow();
  652. if (depth != 0)
  653. processShallow();
  654. if (!clientShallowCommits.isEmpty())
  655. walk.assumeShallow(clientShallowCommits);
  656. sendPack = negotiate();
  657. } catch (ServiceMayNotContinueException err) {
  658. if (!err.isOutput() && err.getMessage() != null) {
  659. try {
  660. pckOut.writeString("ERR " + err.getMessage() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  661. err.setOutput();
  662. } catch (Throwable err2) {
  663. // Ignore this secondary failure (and not mark output).
  664. }
  665. }
  666. throw err;
  667. } catch (IOException | RuntimeException | Error err) {
  668. boolean output = false;
  669. try {
  670. String msg = err instanceof PackProtocolException
  671. ? err.getMessage()
  672. : JGitText.get().internalServerError;
  673. pckOut.writeString("ERR " + msg + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  674. output = true;
  675. } catch (Throwable err2) {
  676. // Ignore this secondary failure, leave output false.
  677. }
  678. if (output) {
  679. throw new UploadPackInternalServerErrorException(err);
  680. }
  681. throw err;
  682. }
  683. if (sendPack)
  684. sendPack();
  685. }
  686. private static Set<ObjectId> refIdSet(Collection<Ref> refs) {
  687. Set<ObjectId> ids = new HashSet<ObjectId>(refs.size());
  688. for (Ref ref : refs) {
  689. ObjectId id = ref.getObjectId();
  690. if (id != null) {
  691. ids.add(id);
  692. }
  693. id = ref.getPeeledObjectId();
  694. if (id != null) {
  695. ids.add(id);
  696. }
  697. }
  698. return ids;
  699. }
  700. private void processShallow() throws IOException {
  701. int walkDepth = depth - 1;
  702. try (DepthWalk.RevWalk depthWalk = new DepthWalk.RevWalk(
  703. walk.getObjectReader(), walkDepth)) {
  704. // Find all the commits which will be shallow
  705. for (ObjectId o : wantIds) {
  706. try {
  707. depthWalk.markRoot(depthWalk.parseCommit(o));
  708. } catch (IncorrectObjectTypeException notCommit) {
  709. // Ignore non-commits in this loop.
  710. }
  711. }
  712. RevCommit o;
  713. while ((o = depthWalk.next()) != null) {
  714. DepthWalk.Commit c = (DepthWalk.Commit) o;
  715. // Commits at the boundary which aren't already shallow in
  716. // the client need to be marked as such
  717. if (c.getDepth() == walkDepth
  718. && !clientShallowCommits.contains(c))
  719. pckOut.writeString("shallow " + o.name()); //$NON-NLS-1$
  720. // Commits not on the boundary which are shallow in the client
  721. // need to become unshallowed
  722. if (c.getDepth() < walkDepth
  723. && clientShallowCommits.remove(c)) {
  724. unshallowCommits.add(c.copy());
  725. pckOut.writeString("unshallow " + c.name()); //$NON-NLS-1$
  726. }
  727. }
  728. }
  729. pckOut.end();
  730. }
  731. private void verifyClientShallow()
  732. throws IOException, PackProtocolException {
  733. AsyncRevObjectQueue q = walk.parseAny(clientShallowCommits, true);
  734. try {
  735. for (;;) {
  736. try {
  737. // Shallow objects named by the client must be commits.
  738. RevObject o = q.next();
  739. if (o == null) {
  740. break;
  741. }
  742. if (!(o instanceof RevCommit)) {
  743. throw new PackProtocolException(
  744. MessageFormat.format(
  745. JGitText.get().invalidShallowObject,
  746. o.name()));
  747. }
  748. } catch (MissingObjectException notCommit) {
  749. // shallow objects not known at the server are ignored
  750. // by git-core upload-pack, match that behavior.
  751. clientShallowCommits.remove(notCommit.getObjectId());
  752. continue;
  753. }
  754. }
  755. } finally {
  756. q.release();
  757. }
  758. }
  759. /**
  760. * Generate an advertisement of available refs and capabilities.
  761. *
  762. * @param adv
  763. * the advertisement formatter.
  764. * @throws IOException
  765. * the formatter failed to write an advertisement.
  766. * @throws ServiceMayNotContinueException
  767. * the hook denied advertisement.
  768. */
  769. public void sendAdvertisedRefs(final RefAdvertiser adv) throws IOException,
  770. ServiceMayNotContinueException {
  771. try {
  772. advertiseRefsHook.advertiseRefs(this);
  773. } catch (ServiceMayNotContinueException fail) {
  774. if (fail.getMessage() != null) {
  775. adv.writeOne("ERR " + fail.getMessage()); //$NON-NLS-1$
  776. fail.setOutput();
  777. }
  778. throw fail;
  779. }
  780. adv.init(db);
  781. adv.advertiseCapability(OPTION_INCLUDE_TAG);
  782. adv.advertiseCapability(OPTION_MULTI_ACK_DETAILED);
  783. adv.advertiseCapability(OPTION_MULTI_ACK);
  784. adv.advertiseCapability(OPTION_OFS_DELTA);
  785. adv.advertiseCapability(OPTION_SIDE_BAND);
  786. adv.advertiseCapability(OPTION_SIDE_BAND_64K);
  787. adv.advertiseCapability(OPTION_THIN_PACK);
  788. adv.advertiseCapability(OPTION_NO_PROGRESS);
  789. adv.advertiseCapability(OPTION_SHALLOW);
  790. if (!biDirectionalPipe)
  791. adv.advertiseCapability(OPTION_NO_DONE);
  792. RequestPolicy policy = getRequestPolicy();
  793. if (policy == RequestPolicy.TIP
  794. || policy == RequestPolicy.REACHABLE_COMMIT_TIP
  795. || policy == null)
  796. adv.advertiseCapability(OPTION_ALLOW_TIP_SHA1_IN_WANT);
  797. if (policy == RequestPolicy.REACHABLE_COMMIT
  798. || policy == RequestPolicy.REACHABLE_COMMIT_TIP
  799. || policy == null)
  800. adv.advertiseCapability(OPTION_ALLOW_REACHABLE_SHA1_IN_WANT);
  801. adv.advertiseCapability(OPTION_AGENT, UserAgent.get());
  802. adv.setDerefTags(true);
  803. Map<String, Ref> advertisedOrDefaultRefs = getAdvertisedOrDefaultRefs();
  804. findSymrefs(adv, advertisedOrDefaultRefs);
  805. advertised = adv.send(advertisedOrDefaultRefs);
  806. if (adv.isEmpty())
  807. adv.advertiseId(ObjectId.zeroId(), "capabilities^{}"); //$NON-NLS-1$
  808. adv.end();
  809. }
  810. /**
  811. * Send a message to the client, if it supports receiving them.
  812. * <p>
  813. * If the client doesn't support receiving messages, the message will be
  814. * discarded, with no other indication to the caller or to the client.
  815. *
  816. * @param what
  817. * string describing the problem identified by the hook. The
  818. * string must not end with an LF, and must not contain an LF.
  819. * @since 3.1
  820. */
  821. public void sendMessage(String what) {
  822. try {
  823. msgOut.write(Constants.encode(what + "\n")); //$NON-NLS-1$
  824. } catch (IOException e) {
  825. // Ignore write failures.
  826. }
  827. }
  828. /**
  829. * @return an underlying stream for sending messages to the client, or null.
  830. * @since 3.1
  831. */
  832. public OutputStream getMessageOutputStream() {
  833. return msgOut;
  834. }
  835. private void recvWants() throws IOException {
  836. boolean isFirst = true;
  837. for (;;) {
  838. String line;
  839. try {
  840. line = pckIn.readString();
  841. } catch (EOFException eof) {
  842. if (isFirst)
  843. break;
  844. throw eof;
  845. }
  846. if (line == PacketLineIn.END)
  847. break;
  848. if (line.startsWith("deepen ")) { //$NON-NLS-1$
  849. depth = Integer.parseInt(line.substring(7));
  850. if (depth <= 0) {
  851. throw new PackProtocolException(
  852. MessageFormat.format(JGitText.get().invalidDepth,
  853. Integer.valueOf(depth)));
  854. }
  855. continue;
  856. }
  857. if (line.startsWith("shallow ")) { //$NON-NLS-1$
  858. clientShallowCommits.add(ObjectId.fromString(line.substring(8)));
  859. continue;
  860. }
  861. if (!line.startsWith("want ") || line.length() < 45) //$NON-NLS-1$
  862. throw new PackProtocolException(MessageFormat.format(JGitText.get().expectedGot, "want", line)); //$NON-NLS-1$
  863. if (isFirst) {
  864. if (line.length() > 45) {
  865. FirstLine firstLine = new FirstLine(line);
  866. options = firstLine.getOptions();
  867. line = firstLine.getLine();
  868. } else
  869. options = Collections.emptySet();
  870. }
  871. wantIds.add(ObjectId.fromString(line.substring(5)));
  872. isFirst = false;
  873. }
  874. }
  875. /**
  876. * Returns the clone/fetch depth. Valid only after calling recvWants(). A
  877. * depth of 1 means return only the wants.
  878. *
  879. * @return the depth requested by the client, or 0 if unbounded.
  880. * @since 4.0
  881. */
  882. public int getDepth() {
  883. if (options == null)
  884. throw new RequestNotYetReadException();
  885. return depth;
  886. }
  887. /**
  888. * Get the user agent of the client.
  889. * <p>
  890. * If the client is new enough to use {@code agent=} capability that value
  891. * will be returned. Older HTTP clients may also supply their version using
  892. * the HTTP {@code User-Agent} header. The capability overrides the HTTP
  893. * header if both are available.
  894. * <p>
  895. * When an HTTP request has been received this method returns the HTTP
  896. * {@code User-Agent} header value until capabilities have been parsed.
  897. *
  898. * @return user agent supplied by the client. Available only if the client
  899. * is new enough to advertise its user agent.
  900. * @since 4.0
  901. */
  902. public String getPeerUserAgent() {
  903. return UserAgent.getAgent(options, userAgent);
  904. }
  905. private boolean negotiate() throws IOException {
  906. okToGiveUp = Boolean.FALSE;
  907. ObjectId last = ObjectId.zeroId();
  908. List<ObjectId> peerHas = new ArrayList<ObjectId>(64);
  909. for (;;) {
  910. String line;
  911. try {
  912. line = pckIn.readString();
  913. } catch (EOFException eof) {
  914. // EOF on stateless RPC (aka smart HTTP) and non-shallow request
  915. // means the client asked for the updated shallow/unshallow data,
  916. // disconnected, and will try another request with actual want/have.
  917. // Don't report the EOF here, its a bug in the protocol that the client
  918. // just disconnects without sending an END.
  919. if (!biDirectionalPipe && depth > 0)
  920. return false;
  921. throw eof;
  922. }
  923. if (line == PacketLineIn.END) {
  924. last = processHaveLines(peerHas, last);
  925. if (commonBase.isEmpty() || multiAck != MultiAck.OFF)
  926. pckOut.writeString("NAK\n"); //$NON-NLS-1$
  927. if (noDone && sentReady) {
  928. pckOut.writeString("ACK " + last.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  929. return true;
  930. }
  931. if (!biDirectionalPipe)
  932. return false;
  933. pckOut.flush();
  934. } else if (line.startsWith("have ") && line.length() == 45) { //$NON-NLS-1$
  935. peerHas.add(ObjectId.fromString(line.substring(5)));
  936. } else if (line.equals("done")) { //$NON-NLS-1$
  937. last = processHaveLines(peerHas, last);
  938. if (commonBase.isEmpty())
  939. pckOut.writeString("NAK\n"); //$NON-NLS-1$
  940. else if (multiAck != MultiAck.OFF)
  941. pckOut.writeString("ACK " + last.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  942. return true;
  943. } else {
  944. throw new PackProtocolException(MessageFormat.format(JGitText.get().expectedGot, "have", line)); //$NON-NLS-1$
  945. }
  946. }
  947. }
  948. private ObjectId processHaveLines(List<ObjectId> peerHas, ObjectId last)
  949. throws IOException {
  950. preUploadHook.onBeginNegotiateRound(this, wantIds, peerHas.size());
  951. if (wantAll.isEmpty() && !wantIds.isEmpty())
  952. parseWants();
  953. if (peerHas.isEmpty())
  954. return last;
  955. sentReady = false;
  956. int haveCnt = 0;
  957. walk.getObjectReader().setAvoidUnreachableObjects(true);
  958. AsyncRevObjectQueue q = walk.parseAny(peerHas, false);
  959. try {
  960. for (;;) {
  961. RevObject obj;
  962. try {
  963. obj = q.next();
  964. } catch (MissingObjectException notFound) {
  965. continue;
  966. }
  967. if (obj == null)
  968. break;
  969. last = obj;
  970. haveCnt++;
  971. if (obj instanceof RevCommit) {
  972. RevCommit c = (RevCommit) obj;
  973. if (oldestTime == 0 || c.getCommitTime() < oldestTime)
  974. oldestTime = c.getCommitTime();
  975. }
  976. if (obj.has(PEER_HAS))
  977. continue;
  978. obj.add(PEER_HAS);
  979. if (obj instanceof RevCommit)
  980. ((RevCommit) obj).carry(PEER_HAS);
  981. addCommonBase(obj);
  982. // If both sides have the same object; let the client know.
  983. //
  984. switch (multiAck) {
  985. case OFF:
  986. if (commonBase.size() == 1)
  987. pckOut.writeString("ACK " + obj.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  988. break;
  989. case CONTINUE:
  990. pckOut.writeString("ACK " + obj.name() + " continue\n"); //$NON-NLS-1$ //$NON-NLS-2$
  991. break;
  992. case DETAILED:
  993. pckOut.writeString("ACK " + obj.name() + " common\n"); //$NON-NLS-1$ //$NON-NLS-2$
  994. break;
  995. }
  996. }
  997. } finally {
  998. q.release();
  999. walk.getObjectReader().setAvoidUnreachableObjects(false);
  1000. }
  1001. int missCnt = peerHas.size() - haveCnt;
  1002. // If we don't have one of the objects but we're also willing to
  1003. // create a pack at this point, let the client know so it stops
  1004. // telling us about its history.
  1005. //
  1006. boolean didOkToGiveUp = false;
  1007. if (0 < missCnt) {
  1008. for (int i = peerHas.size() - 1; i >= 0; i--) {
  1009. ObjectId id = peerHas.get(i);
  1010. if (walk.lookupOrNull(id) == null) {
  1011. didOkToGiveUp = true;
  1012. if (okToGiveUp()) {
  1013. switch (multiAck) {
  1014. case OFF:
  1015. break;
  1016. case CONTINUE:
  1017. pckOut.writeString("ACK " + id.name() + " continue\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1018. break;
  1019. case DETAILED:
  1020. pckOut.writeString("ACK " + id.name() + " ready\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1021. sentReady = true;
  1022. break;
  1023. }
  1024. }
  1025. break;
  1026. }
  1027. }
  1028. }
  1029. if (multiAck == MultiAck.DETAILED && !didOkToGiveUp && okToGiveUp()) {
  1030. ObjectId id = peerHas.get(peerHas.size() - 1);
  1031. pckOut.writeString("ACK " + id.name() + " ready\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1032. sentReady = true;
  1033. }
  1034. preUploadHook.onEndNegotiateRound(this, wantAll, haveCnt, missCnt, sentReady);
  1035. peerHas.clear();
  1036. return last;
  1037. }
  1038. private void parseWants() throws IOException {
  1039. List<ObjectId> notAdvertisedWants = null;
  1040. for (ObjectId obj : wantIds) {
  1041. if (!advertised.contains(obj)) {
  1042. if (notAdvertisedWants == null)
  1043. notAdvertisedWants = new ArrayList<ObjectId>();
  1044. notAdvertisedWants.add(obj);
  1045. }
  1046. }
  1047. if (notAdvertisedWants != null)
  1048. requestValidator.checkWants(this, notAdvertisedWants);
  1049. AsyncRevObjectQueue q = walk.parseAny(wantIds, true);
  1050. try {
  1051. RevObject obj;
  1052. while ((obj = q.next()) != null) {
  1053. want(obj);
  1054. if (!(obj instanceof RevCommit))
  1055. obj.add(SATISFIED);
  1056. if (obj instanceof RevTag) {
  1057. obj = walk.peel(obj);
  1058. if (obj instanceof RevCommit)
  1059. want(obj);
  1060. }
  1061. }
  1062. wantIds.clear();
  1063. } catch (MissingObjectException notFound) {
  1064. throw new WantNotValidException(notFound.getObjectId(), notFound);
  1065. } finally {
  1066. q.release();
  1067. }
  1068. }
  1069. private void want(RevObject obj) {
  1070. if (!obj.has(WANT)) {
  1071. obj.add(WANT);
  1072. wantAll.add(obj);
  1073. }
  1074. }
  1075. /**
  1076. * Validator corresponding to {@link RequestPolicy#ADVERTISED}.
  1077. *
  1078. * @since 3.1
  1079. */
  1080. public static final class AdvertisedRequestValidator
  1081. implements RequestValidator {
  1082. public void checkWants(UploadPack up, List<ObjectId> wants)
  1083. throws PackProtocolException, IOException {
  1084. if (!up.isBiDirectionalPipe())
  1085. new ReachableCommitRequestValidator().checkWants(up, wants);
  1086. else if (!wants.isEmpty())
  1087. throw new WantNotValidException(wants.iterator().next());
  1088. }
  1089. }
  1090. /**
  1091. * Validator corresponding to {@link RequestPolicy#REACHABLE_COMMIT}.
  1092. *
  1093. * @since 3.1
  1094. */
  1095. public static final class ReachableCommitRequestValidator
  1096. implements RequestValidator {
  1097. public void checkWants(UploadPack up, List<ObjectId> wants)
  1098. throws PackProtocolException, IOException {
  1099. checkNotAdvertisedWants(up.getRevWalk(), wants,
  1100. refIdSet(up.getAdvertisedRefs().values()));
  1101. }
  1102. }
  1103. /**
  1104. * Validator corresponding to {@link RequestPolicy#TIP}.
  1105. *
  1106. * @since 3.1
  1107. */
  1108. public static final class TipRequestValidator implements RequestValidator {
  1109. public void checkWants(UploadPack up, List<ObjectId> wants)
  1110. throws PackProtocolException, IOException {
  1111. if (!up.isBiDirectionalPipe())
  1112. new ReachableCommitTipRequestValidator().checkWants(up, wants);
  1113. else if (!wants.isEmpty()) {
  1114. Set<ObjectId> refIds =
  1115. refIdSet(up.getRepository().getRefDatabase().getRefs(ALL).values());
  1116. for (ObjectId obj : wants) {
  1117. if (!refIds.contains(obj))
  1118. throw new WantNotValidException(obj);
  1119. }
  1120. }
  1121. }
  1122. }
  1123. /**
  1124. * Validator corresponding to {@link RequestPolicy#REACHABLE_COMMIT_TIP}.
  1125. *
  1126. * @since 3.1
  1127. */
  1128. public static final class ReachableCommitTipRequestValidator
  1129. implements RequestValidator {
  1130. public void checkWants(UploadPack up, List<ObjectId> wants)
  1131. throws PackProtocolException, IOException {
  1132. checkNotAdvertisedWants(up.getRevWalk(), wants,
  1133. refIdSet(up.getRepository().getRefDatabase().getRefs(ALL).values()));
  1134. }
  1135. }
  1136. /**
  1137. * Validator corresponding to {@link RequestPolicy#ANY}.
  1138. *
  1139. * @since 3.1
  1140. */
  1141. public static final class AnyRequestValidator implements RequestValidator {
  1142. public void checkWants(UploadPack up, List<ObjectId> wants)
  1143. throws PackProtocolException, IOException {
  1144. // All requests are valid.
  1145. }
  1146. }
  1147. private static void checkNotAdvertisedWants(RevWalk walk,
  1148. List<ObjectId> notAdvertisedWants, Set<ObjectId> reachableFrom)
  1149. throws MissingObjectException, IncorrectObjectTypeException, IOException {
  1150. // Walk the requested commits back to the provided set of commits. If any
  1151. // commit exists, a branch was deleted or rewound and the repository owner
  1152. // no longer exports that requested item. If the requested commit is merged
  1153. // into an advertised branch it will be marked UNINTERESTING and no commits
  1154. // return.
  1155. AsyncRevObjectQueue q = walk.parseAny(notAdvertisedWants, true);
  1156. try {
  1157. RevObject obj;
  1158. while ((obj = q.next()) != null) {
  1159. if (!(obj instanceof RevCommit))
  1160. throw new WantNotValidException(obj);
  1161. walk.markStart((RevCommit) obj);
  1162. }
  1163. } catch (MissingObjectException notFound) {
  1164. throw new WantNotValidException(notFound.getObjectId(), notFound);
  1165. } finally {
  1166. q.release();
  1167. }
  1168. for (ObjectId id : reachableFrom) {
  1169. try {
  1170. walk.markUninteresting(walk.parseCommit(id));
  1171. } catch (IncorrectObjectTypeException notCommit) {
  1172. continue;
  1173. }
  1174. }
  1175. RevCommit bad = walk.next();
  1176. if (bad != null) {
  1177. throw new WantNotValidException(bad);
  1178. }
  1179. walk.reset();
  1180. }
  1181. private void addCommonBase(final RevObject o) {
  1182. if (!o.has(COMMON)) {
  1183. o.add(COMMON);
  1184. commonBase.add(o);
  1185. okToGiveUp = null;
  1186. }
  1187. }
  1188. private boolean okToGiveUp() throws PackProtocolException {
  1189. if (okToGiveUp == null)
  1190. okToGiveUp = Boolean.valueOf(okToGiveUpImp());
  1191. return okToGiveUp.booleanValue();
  1192. }
  1193. private boolean okToGiveUpImp() throws PackProtocolException {
  1194. if (commonBase.isEmpty())
  1195. return false;
  1196. try {
  1197. for (RevObject obj : wantAll) {
  1198. if (!wantSatisfied(obj))
  1199. return false;
  1200. }
  1201. return true;
  1202. } catch (IOException e) {
  1203. throw new PackProtocolException(JGitText.get().internalRevisionError, e);
  1204. }
  1205. }
  1206. private boolean wantSatisfied(final RevObject want) throws IOException {
  1207. if (want.has(SATISFIED))
  1208. return true;
  1209. walk.resetRetain(SAVE);
  1210. walk.markStart((RevCommit) want);
  1211. if (oldestTime != 0)
  1212. walk.setRevFilter(CommitTimeRevFilter.after(oldestTime * 1000L));
  1213. for (;;) {
  1214. final RevCommit c = walk.next();
  1215. if (c == null)
  1216. break;
  1217. if (c.has(PEER_HAS)) {
  1218. addCommonBase(c);
  1219. want.add(SATISFIED);
  1220. return true;
  1221. }
  1222. }
  1223. return false;
  1224. }
  1225. private void sendPack() throws IOException {
  1226. final boolean sideband = options.contains(OPTION_SIDE_BAND)
  1227. || options.contains(OPTION_SIDE_BAND_64K);
  1228. if (!biDirectionalPipe) {
  1229. // Ensure the request was fully consumed. Any remaining input must
  1230. // be a protocol error. If we aren't at EOF the implementation is broken.
  1231. int eof = rawIn.read();
  1232. if (0 <= eof)
  1233. throw new CorruptObjectException(MessageFormat.format(
  1234. JGitText.get().expectedEOFReceived,
  1235. "\\x" + Integer.toHexString(eof))); //$NON-NLS-1$
  1236. }
  1237. if (sideband) {
  1238. try {
  1239. sendPack(true);
  1240. } catch (ServiceMayNotContinueException noPack) {
  1241. // This was already reported on (below).
  1242. throw noPack;
  1243. } catch (IOException err) {
  1244. if (reportInternalServerErrorOverSideband())
  1245. throw new UploadPackInternalServerErrorException(err);
  1246. else
  1247. throw err;
  1248. } catch (RuntimeException err) {
  1249. if (reportInternalServerErrorOverSideband())
  1250. throw new UploadPackInternalServerErrorException(err);
  1251. else
  1252. throw err;
  1253. } catch (Error err) {
  1254. if (reportInternalServerErrorOverSideband())
  1255. throw new UploadPackInternalServerErrorException(err);
  1256. else
  1257. throw err;
  1258. }
  1259. } else {
  1260. sendPack(false);
  1261. }
  1262. }
  1263. private boolean reportInternalServerErrorOverSideband() {
  1264. try {
  1265. @SuppressWarnings("resource" /* java 7 */)
  1266. SideBandOutputStream err = new SideBandOutputStream(
  1267. SideBandOutputStream.CH_ERROR,
  1268. SideBandOutputStream.SMALL_BUF,
  1269. rawOut);
  1270. err.write(Constants.encode(JGitText.get().internalServerError));
  1271. err.flush();
  1272. return true;
  1273. } catch (Throwable cannotReport) {
  1274. // Ignore the reason. This is a secondary failure.
  1275. return false;
  1276. }
  1277. }
  1278. @SuppressWarnings("deprecation")
  1279. private void sendPack(final boolean sideband) throws IOException {
  1280. ProgressMonitor pm = NullProgressMonitor.INSTANCE;
  1281. OutputStream packOut = rawOut;
  1282. if (sideband) {
  1283. int bufsz = SideBandOutputStream.SMALL_BUF;
  1284. if (options.contains(OPTION_SIDE_BAND_64K))
  1285. bufsz = SideBandOutputStream.MAX_BUF;
  1286. packOut = new SideBandOutputStream(SideBandOutputStream.CH_DATA,
  1287. bufsz, rawOut);
  1288. if (!options.contains(OPTION_NO_PROGRESS)) {
  1289. msgOut = new SideBandOutputStream(
  1290. SideBandOutputStream.CH_PROGRESS, bufsz, rawOut);
  1291. pm = new SideBandProgressMonitor(msgOut);
  1292. }
  1293. }
  1294. try {
  1295. if (wantAll.isEmpty()) {
  1296. preUploadHook.onSendPack(this, wantIds, commonBase);
  1297. } else {
  1298. preUploadHook.onSendPack(this, wantAll, commonBase);
  1299. }
  1300. msgOut.flush();
  1301. } catch (ServiceMayNotContinueException noPack) {
  1302. if (sideband && noPack.getMessage() != null) {
  1303. noPack.setOutput();
  1304. @SuppressWarnings("resource" /* java 7 */)
  1305. SideBandOutputStream err = new SideBandOutputStream(
  1306. SideBandOutputStream.CH_ERROR,
  1307. SideBandOutputStream.SMALL_BUF, rawOut);
  1308. err.write(Constants.encode(noPack.getMessage()));
  1309. err.flush();
  1310. }
  1311. throw noPack;
  1312. }
  1313. PackConfig cfg = packConfig;
  1314. if (cfg == null)
  1315. cfg = new PackConfig(db);
  1316. final PackWriter pw = new PackWriter(cfg, walk.getObjectReader());
  1317. try {
  1318. pw.setIndexDisabled(true);
  1319. pw.setUseCachedPacks(true);
  1320. pw.setUseBitmaps(depth == 0 && clientShallowCommits.isEmpty());
  1321. pw.setClientShallowCommits(clientShallowCommits);
  1322. pw.setReuseDeltaCommits(true);
  1323. pw.setDeltaBaseAsOffset(options.contains(OPTION_OFS_DELTA));
  1324. pw.setThin(options.contains(OPTION_THIN_PACK));
  1325. pw.setReuseValidatingObjects(false);
  1326. if (commonBase.isEmpty() && refs != null) {
  1327. Set<ObjectId> tagTargets = new HashSet<ObjectId>();
  1328. for (Ref ref : refs.values()) {
  1329. if (ref.getPeeledObjectId() != null)
  1330. tagTargets.add(ref.getPeeledObjectId());
  1331. else if (ref.getObjectId() == null)
  1332. continue;
  1333. else if (ref.getName().startsWith(Constants.R_HEADS))
  1334. tagTargets.add(ref.getObjectId());
  1335. }
  1336. pw.setTagTargets(tagTargets);
  1337. }
  1338. RevWalk rw = walk;
  1339. if (depth > 0) {
  1340. pw.setShallowPack(depth, unshallowCommits);
  1341. rw = new DepthWalk.RevWalk(walk.getObjectReader(), depth - 1);
  1342. rw.assumeShallow(clientShallowCommits);
  1343. }
  1344. if (wantAll.isEmpty()) {
  1345. pw.preparePack(pm, wantIds, commonBase, clientShallowCommits);
  1346. } else {
  1347. walk.reset();
  1348. ObjectWalk ow = rw.toObjectWalkWithSameObjects();
  1349. pw.preparePack(pm, ow, wantAll, commonBase);
  1350. rw = ow;
  1351. }
  1352. if (options.contains(OPTION_INCLUDE_TAG) && refs != null) {
  1353. for (Ref ref : refs.values()) {
  1354. ObjectId objectId = ref.getObjectId();
  1355. // If the object was already requested, skip it.
  1356. if (wantAll.isEmpty()) {
  1357. if (wantIds.contains(objectId))
  1358. continue;
  1359. } else {
  1360. RevObject obj = rw.lookupOrNull(objectId);
  1361. if (obj != null && obj.has(WANT))
  1362. continue;
  1363. }
  1364. if (!ref.isPeeled())
  1365. ref = db.peel(ref);
  1366. ObjectId peeledId = ref.getPeeledObjectId();
  1367. if (peeledId == null)
  1368. continue;
  1369. objectId = ref.getObjectId();
  1370. if (pw.willInclude(peeledId) && !pw.willInclude(objectId))
  1371. pw.addObject(rw.parseAny(objectId));
  1372. }
  1373. }
  1374. pw.writePack(pm, NullProgressMonitor.INSTANCE, packOut);
  1375. if (msgOut != NullOutputStream.INSTANCE) {
  1376. String msg = pw.getStatistics().getMessage() + '\n';
  1377. msgOut.write(Constants.encode(msg));
  1378. msgOut.flush();
  1379. }
  1380. } finally {
  1381. statistics = pw.getStatistics();
  1382. if (statistics != null) {
  1383. postUploadHook.onPostUpload(statistics);
  1384. logger.onPackStatistics(new PackWriter.Statistics(statistics));
  1385. }
  1386. pw.close();
  1387. }
  1388. if (sideband)
  1389. pckOut.end();
  1390. }
  1391. private static void findSymrefs(
  1392. final RefAdvertiser adv, final Map<String, Ref> refs) {
  1393. Ref head = refs.get(Constants.HEAD);
  1394. if (head != null && head.isSymbolic()) {
  1395. adv.addSymref(Constants.HEAD, head.getLeaf().getName());
  1396. }
  1397. }
  1398. }