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

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