Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

UploadPack.java 46KB

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