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

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