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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261
  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 java.util.Collections.unmodifiableMap;
  45. import static org.eclipse.jgit.util.RefMap.toRefMap;
  46. import static org.eclipse.jgit.lib.Constants.R_TAGS;
  47. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_REF_IN_WANT;
  48. import static org.eclipse.jgit.transport.GitProtocolConstants.COMMAND_FETCH;
  49. import static org.eclipse.jgit.transport.GitProtocolConstants.COMMAND_LS_REFS;
  50. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_SERVER_OPTION;
  51. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_AGENT;
  52. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_ALLOW_REACHABLE_SHA1_IN_WANT;
  53. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_ALLOW_TIP_SHA1_IN_WANT;
  54. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_DEEPEN_RELATIVE;
  55. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_FILTER;
  56. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_INCLUDE_TAG;
  57. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_MULTI_ACK;
  58. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_MULTI_ACK_DETAILED;
  59. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_NO_DONE;
  60. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_NO_PROGRESS;
  61. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_OFS_DELTA;
  62. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SHALLOW;
  63. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SIDE_BAND;
  64. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_SIDE_BAND_64K;
  65. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_THIN_PACK;
  66. import java.io.ByteArrayOutputStream;
  67. import java.io.EOFException;
  68. import java.io.IOException;
  69. import java.io.InputStream;
  70. import java.io.OutputStream;
  71. import java.io.UncheckedIOException;
  72. import java.text.MessageFormat;
  73. import java.util.ArrayList;
  74. import java.util.Collection;
  75. import java.util.Collections;
  76. import java.util.HashSet;
  77. import java.util.List;
  78. import java.util.Map;
  79. import java.util.Objects;
  80. import java.util.Set;
  81. import java.util.TreeMap;
  82. import org.eclipse.jgit.annotations.NonNull;
  83. import org.eclipse.jgit.annotations.Nullable;
  84. import org.eclipse.jgit.errors.CorruptObjectException;
  85. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  86. import org.eclipse.jgit.errors.MissingObjectException;
  87. import org.eclipse.jgit.errors.PackProtocolException;
  88. import org.eclipse.jgit.internal.JGitText;
  89. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  90. import org.eclipse.jgit.internal.transport.parser.FirstWant;
  91. import org.eclipse.jgit.lib.BitmapIndex;
  92. import org.eclipse.jgit.lib.BitmapIndex.BitmapBuilder;
  93. import org.eclipse.jgit.lib.Constants;
  94. import org.eclipse.jgit.lib.NullProgressMonitor;
  95. import org.eclipse.jgit.lib.ObjectId;
  96. import org.eclipse.jgit.lib.ObjectReader;
  97. import org.eclipse.jgit.lib.ProgressMonitor;
  98. import org.eclipse.jgit.lib.Ref;
  99. import org.eclipse.jgit.lib.RefDatabase;
  100. import org.eclipse.jgit.lib.Repository;
  101. import org.eclipse.jgit.revwalk.AsyncRevObjectQueue;
  102. import org.eclipse.jgit.revwalk.BitmapWalker;
  103. import org.eclipse.jgit.revwalk.DepthWalk;
  104. import org.eclipse.jgit.revwalk.ObjectWalk;
  105. import org.eclipse.jgit.revwalk.RevCommit;
  106. import org.eclipse.jgit.revwalk.RevFlag;
  107. import org.eclipse.jgit.revwalk.RevFlagSet;
  108. import org.eclipse.jgit.revwalk.RevObject;
  109. import org.eclipse.jgit.revwalk.RevTag;
  110. import org.eclipse.jgit.revwalk.RevWalk;
  111. import org.eclipse.jgit.revwalk.filter.CommitTimeRevFilter;
  112. import org.eclipse.jgit.storage.pack.PackConfig;
  113. import org.eclipse.jgit.storage.pack.PackStatistics;
  114. import org.eclipse.jgit.transport.GitProtocolConstants.MultiAck;
  115. import org.eclipse.jgit.transport.RefAdvertiser.PacketLineOutRefAdvertiser;
  116. import org.eclipse.jgit.transport.TransferConfig.ProtocolVersion;
  117. import org.eclipse.jgit.util.io.InterruptTimer;
  118. import org.eclipse.jgit.util.io.NullOutputStream;
  119. import org.eclipse.jgit.util.io.TimeoutInputStream;
  120. import org.eclipse.jgit.util.io.TimeoutOutputStream;
  121. /**
  122. * Implements the server side of a fetch connection, transmitting objects.
  123. */
  124. public class UploadPack {
  125. /** Policy the server uses to validate client requests */
  126. public static enum RequestPolicy {
  127. /** Client may only ask for objects the server advertised a reference for. */
  128. ADVERTISED,
  129. /**
  130. * Client may ask for any commit reachable from a reference advertised by
  131. * the server.
  132. */
  133. REACHABLE_COMMIT,
  134. /**
  135. * Client may ask for objects that are the tip of any reference, even if not
  136. * advertised.
  137. * <p>
  138. * This may happen, for example, when a custom {@link RefFilter} is set.
  139. *
  140. * @since 3.1
  141. */
  142. TIP,
  143. /**
  144. * Client may ask for any commit reachable from any reference, even if that
  145. * reference wasn't advertised.
  146. *
  147. * @since 3.1
  148. */
  149. REACHABLE_COMMIT_TIP,
  150. /** Client may ask for any SHA-1 in the repository. */
  151. ANY;
  152. }
  153. /**
  154. * Validator for client requests.
  155. *
  156. * @since 3.1
  157. */
  158. public interface RequestValidator {
  159. /**
  160. * Check a list of client wants against the request policy.
  161. *
  162. * @param up
  163. * {@link UploadPack} instance.
  164. * @param wants
  165. * objects the client requested that were not advertised.
  166. *
  167. * @throws PackProtocolException
  168. * if one or more wants is not valid.
  169. * @throws IOException
  170. * if a low-level exception occurred.
  171. * @since 3.1
  172. */
  173. void checkWants(UploadPack up, List<ObjectId> wants)
  174. throws PackProtocolException, IOException;
  175. }
  176. /**
  177. * Data in the first line of a want-list, the line itself plus options.
  178. *
  179. * @deprecated Use {@link FirstWant} instead
  180. */
  181. @Deprecated
  182. public static class FirstLine {
  183. private final FirstWant firstWant;
  184. /**
  185. * @param line
  186. * line from the client.
  187. */
  188. public FirstLine(String line) {
  189. try {
  190. firstWant = FirstWant.fromLine(line);
  191. } catch (PackProtocolException e) {
  192. throw new UncheckedIOException(e);
  193. }
  194. }
  195. /** @return non-capabilities part of the line. */
  196. public String getLine() {
  197. return firstWant.getLine();
  198. }
  199. /** @return capabilities parsed from the line. */
  200. public Set<String> getOptions() {
  201. if (firstWant.getAgent() != null) {
  202. Set<String> caps = new HashSet<>(firstWant.getCapabilities());
  203. caps.add(OPTION_AGENT + '=' + firstWant.getAgent());
  204. return caps;
  205. }
  206. return firstWant.getCapabilities();
  207. }
  208. }
  209. /*
  210. * {@link java.util.function.Consumer} doesn't allow throwing checked
  211. * exceptions. Define our own to propagate IOExceptions.
  212. */
  213. @FunctionalInterface
  214. private static interface IOConsumer<R> {
  215. void accept(R t) throws IOException;
  216. }
  217. /** Database we read the objects from. */
  218. private final Repository db;
  219. /** Revision traversal support over {@link #db}. */
  220. private final RevWalk walk;
  221. /** Configuration to pass into the PackWriter. */
  222. private PackConfig packConfig;
  223. /** Configuration for various transfer options. */
  224. private TransferConfig transferConfig;
  225. /** Timeout in seconds to wait for client interaction. */
  226. private int timeout;
  227. /**
  228. * Is the client connection a bi-directional socket or pipe?
  229. * <p>
  230. * If true, this class assumes it can perform multiple read and write cycles
  231. * with the client over the input and output streams. This matches the
  232. * functionality available with a standard TCP/IP connection, or a local
  233. * operating system or in-memory pipe.
  234. * <p>
  235. * If false, this class runs in a read everything then output results mode,
  236. * making it suitable for single round-trip systems RPCs such as HTTP.
  237. */
  238. private boolean biDirectionalPipe = true;
  239. /** Timer to manage {@link #timeout}. */
  240. private InterruptTimer timer;
  241. /**
  242. * Whether the client requested to use protocol V2 through a side
  243. * channel (such as the Git-Protocol HTTP header).
  244. */
  245. private boolean clientRequestedV2;
  246. private InputStream rawIn;
  247. private ResponseBufferedOutputStream rawOut;
  248. private PacketLineIn pckIn;
  249. private PacketLineOut pckOut;
  250. private OutputStream msgOut = NullOutputStream.INSTANCE;
  251. /**
  252. * Refs eligible for advertising to the client, set using
  253. * {@link #setAdvertisedRefs}.
  254. */
  255. private Map<String, Ref> refs;
  256. /** Hook used while processing Git protocol v2 requests. */
  257. private ProtocolV2Hook protocolV2Hook = ProtocolV2Hook.DEFAULT;
  258. /** Hook used while advertising the refs to the client. */
  259. private AdvertiseRefsHook advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  260. /** Whether the {@link #advertiseRefsHook} has been invoked. */
  261. private boolean advertiseRefsHookCalled;
  262. /** Filter used while advertising the refs to the client. */
  263. private RefFilter refFilter = RefFilter.DEFAULT;
  264. /** Hook handling the various upload phases. */
  265. private PreUploadHook preUploadHook = PreUploadHook.NULL;
  266. /** Hook for taking post upload actions. */
  267. private PostUploadHook postUploadHook = PostUploadHook.NULL;
  268. /** Caller user agent */
  269. String userAgent;
  270. /** Raw ObjectIds the client has asked for, before validating them. */
  271. private Set<ObjectId> wantIds = new HashSet<>();
  272. /** Objects the client wants to obtain. */
  273. private final Set<RevObject> wantAll = new HashSet<>();
  274. /** Objects on both sides, these don't have to be sent. */
  275. private final Set<RevObject> commonBase = new HashSet<>();
  276. /** Commit time of the oldest common commit, in seconds. */
  277. private int oldestTime;
  278. /** null if {@link #commonBase} should be examined again. */
  279. private Boolean okToGiveUp;
  280. private boolean sentReady;
  281. /** Objects we sent in our advertisement list, clients can ask for these. */
  282. private Set<ObjectId> advertised;
  283. /** Marked on objects the client has asked us to give them. */
  284. private final RevFlag WANT;
  285. /** Marked on objects both we and the client have. */
  286. private final RevFlag PEER_HAS;
  287. /** Marked on objects in {@link #commonBase}. */
  288. private final RevFlag COMMON;
  289. /** Objects where we found a path from the want list to a common base. */
  290. private final RevFlag SATISFIED;
  291. private final RevFlagSet SAVE;
  292. private RequestValidator requestValidator = new AdvertisedRequestValidator();
  293. private MultiAck multiAck = MultiAck.OFF;
  294. private boolean noDone;
  295. private PackStatistics statistics;
  296. /**
  297. * Request this instance is handling.
  298. *
  299. * We need to keep a reference to it for {@link PreUploadHook pre upload
  300. * hooks}. They receive a reference this instance and invoke methods like
  301. * getDepth() to get information about the request.
  302. */
  303. private FetchRequest currentRequest;
  304. /**
  305. * Create a new pack upload for an open repository.
  306. *
  307. * @param copyFrom
  308. * the source repository.
  309. */
  310. public UploadPack(Repository copyFrom) {
  311. db = copyFrom;
  312. walk = new RevWalk(db);
  313. walk.setRetainBody(false);
  314. WANT = walk.newFlag("WANT"); //$NON-NLS-1$
  315. PEER_HAS = walk.newFlag("PEER_HAS"); //$NON-NLS-1$
  316. COMMON = walk.newFlag("COMMON"); //$NON-NLS-1$
  317. SATISFIED = walk.newFlag("SATISFIED"); //$NON-NLS-1$
  318. walk.carry(PEER_HAS);
  319. SAVE = new RevFlagSet();
  320. SAVE.add(WANT);
  321. SAVE.add(PEER_HAS);
  322. SAVE.add(COMMON);
  323. SAVE.add(SATISFIED);
  324. setTransferConfig(null);
  325. }
  326. /**
  327. * Get the repository this upload is reading from.
  328. *
  329. * @return the repository this upload is reading from.
  330. */
  331. public final Repository getRepository() {
  332. return db;
  333. }
  334. /**
  335. * Get the RevWalk instance used by this connection.
  336. *
  337. * @return the RevWalk instance used by this connection.
  338. */
  339. public final RevWalk getRevWalk() {
  340. return walk;
  341. }
  342. /**
  343. * Get refs which were advertised to the client.
  344. *
  345. * @return all refs which were advertised to the client, or null if
  346. * {@link #setAdvertisedRefs(Map)} has not been called yet.
  347. */
  348. public final Map<String, Ref> getAdvertisedRefs() {
  349. return refs;
  350. }
  351. /**
  352. * Set the refs advertised by this UploadPack.
  353. * <p>
  354. * Intended to be called from a
  355. * {@link org.eclipse.jgit.transport.PreUploadHook}.
  356. *
  357. * @param allRefs
  358. * explicit set of references to claim as advertised by this
  359. * UploadPack instance. This overrides any references that may
  360. * exist in the source repository. The map is passed to the
  361. * configured {@link #getRefFilter()}. If null, assumes all refs
  362. * were advertised.
  363. */
  364. public void setAdvertisedRefs(@Nullable Map<String, Ref> allRefs) {
  365. if (allRefs != null)
  366. refs = allRefs;
  367. else
  368. refs = db.getAllRefs();
  369. if (refFilter == RefFilter.DEFAULT)
  370. refs = transferConfig.getRefFilter().filter(refs);
  371. else
  372. refs = refFilter.filter(refs);
  373. }
  374. /**
  375. * Get timeout (in seconds) before aborting an IO operation.
  376. *
  377. * @return timeout (in seconds) before aborting an IO operation.
  378. */
  379. public int getTimeout() {
  380. return timeout;
  381. }
  382. /**
  383. * Set the timeout before willing to abort an IO call.
  384. *
  385. * @param seconds
  386. * number of seconds to wait (with no data transfer occurring)
  387. * before aborting an IO read or write operation with the
  388. * connected client.
  389. */
  390. public void setTimeout(int seconds) {
  391. timeout = seconds;
  392. }
  393. /**
  394. * Whether this class expects a bi-directional pipe opened between the
  395. * client and itself.
  396. *
  397. * @return true if this class expects a bi-directional pipe opened between
  398. * the client and itself. The default is true.
  399. */
  400. public boolean isBiDirectionalPipe() {
  401. return biDirectionalPipe;
  402. }
  403. /**
  404. * Set whether this class will assume the socket is a fully bidirectional
  405. * pipe between the two peers
  406. *
  407. * @param twoWay
  408. * if true, this class will assume the socket is a fully
  409. * bidirectional pipe between the two peers and takes advantage
  410. * of that by first transmitting the known refs, then waiting to
  411. * read commands. If false, this class assumes it must read the
  412. * commands before writing output and does not perform the
  413. * initial advertising.
  414. */
  415. public void setBiDirectionalPipe(boolean twoWay) {
  416. biDirectionalPipe = twoWay;
  417. }
  418. /**
  419. * Get policy used by the service to validate client requests
  420. *
  421. * @return policy used by the service to validate client requests, or null
  422. * for a custom request validator.
  423. */
  424. public RequestPolicy getRequestPolicy() {
  425. if (requestValidator instanceof AdvertisedRequestValidator)
  426. return RequestPolicy.ADVERTISED;
  427. if (requestValidator instanceof ReachableCommitRequestValidator)
  428. return RequestPolicy.REACHABLE_COMMIT;
  429. if (requestValidator instanceof TipRequestValidator)
  430. return RequestPolicy.TIP;
  431. if (requestValidator instanceof ReachableCommitTipRequestValidator)
  432. return RequestPolicy.REACHABLE_COMMIT_TIP;
  433. if (requestValidator instanceof AnyRequestValidator)
  434. return RequestPolicy.ANY;
  435. return null;
  436. }
  437. /**
  438. * Set the policy used to enforce validation of a client's want list.
  439. *
  440. * @param policy
  441. * the policy used to enforce validation of a client's want list.
  442. * By default the policy is
  443. * {@link org.eclipse.jgit.transport.UploadPack.RequestPolicy#ADVERTISED},
  444. * which is the Git default requiring clients to only ask for an
  445. * object that a reference directly points to. This may be
  446. * relaxed to
  447. * {@link org.eclipse.jgit.transport.UploadPack.RequestPolicy#REACHABLE_COMMIT}
  448. * or
  449. * {@link org.eclipse.jgit.transport.UploadPack.RequestPolicy#REACHABLE_COMMIT_TIP}
  450. * when callers have {@link #setBiDirectionalPipe(boolean)} set
  451. * to false. Overrides any policy specified in a
  452. * {@link org.eclipse.jgit.transport.TransferConfig}.
  453. */
  454. public void setRequestPolicy(RequestPolicy policy) {
  455. switch (policy) {
  456. case ADVERTISED:
  457. default:
  458. requestValidator = new AdvertisedRequestValidator();
  459. break;
  460. case REACHABLE_COMMIT:
  461. requestValidator = new ReachableCommitRequestValidator();
  462. break;
  463. case TIP:
  464. requestValidator = new TipRequestValidator();
  465. break;
  466. case REACHABLE_COMMIT_TIP:
  467. requestValidator = new ReachableCommitTipRequestValidator();
  468. break;
  469. case ANY:
  470. requestValidator = new AnyRequestValidator();
  471. break;
  472. }
  473. }
  474. /**
  475. * Set custom validator for client want list.
  476. *
  477. * @param validator
  478. * custom validator for client want list.
  479. * @since 3.1
  480. */
  481. public void setRequestValidator(@Nullable RequestValidator validator) {
  482. requestValidator = validator != null ? validator
  483. : new AdvertisedRequestValidator();
  484. }
  485. /**
  486. * Get the hook used while advertising the refs to the client.
  487. *
  488. * @return the hook used while advertising the refs to the client.
  489. */
  490. public AdvertiseRefsHook getAdvertiseRefsHook() {
  491. return advertiseRefsHook;
  492. }
  493. /**
  494. * Get the filter used while advertising the refs to the client.
  495. *
  496. * @return the filter used while advertising the refs to the client.
  497. */
  498. public RefFilter getRefFilter() {
  499. return refFilter;
  500. }
  501. /**
  502. * Set the hook used while advertising the refs to the client.
  503. * <p>
  504. * If the {@link org.eclipse.jgit.transport.AdvertiseRefsHook} chooses to
  505. * call {@link #setAdvertisedRefs(Map)}, only refs set by this hook
  506. * <em>and</em> selected by the {@link org.eclipse.jgit.transport.RefFilter}
  507. * will be shown to the client.
  508. *
  509. * @param advertiseRefsHook
  510. * the hook; may be null to show all refs.
  511. */
  512. public void setAdvertiseRefsHook(
  513. @Nullable AdvertiseRefsHook advertiseRefsHook) {
  514. this.advertiseRefsHook = advertiseRefsHook != null ? advertiseRefsHook
  515. : AdvertiseRefsHook.DEFAULT;
  516. }
  517. /**
  518. * Set the protocol V2 hook.
  519. *
  520. * @param hook
  521. * the hook; if null no special actions are taken.
  522. * @since 5.1
  523. */
  524. public void setProtocolV2Hook(@Nullable ProtocolV2Hook hook) {
  525. this.protocolV2Hook = hook != null ? hook : ProtocolV2Hook.DEFAULT;
  526. }
  527. /**
  528. * Set the filter used while advertising the refs to the client.
  529. * <p>
  530. * Only refs allowed by this filter will be sent to the client. The filter
  531. * is run against the refs specified by the
  532. * {@link org.eclipse.jgit.transport.AdvertiseRefsHook} (if applicable). If
  533. * null or not set, uses the filter implied by the
  534. * {@link org.eclipse.jgit.transport.TransferConfig}.
  535. *
  536. * @param refFilter
  537. * the filter; may be null to show all refs.
  538. */
  539. public void setRefFilter(@Nullable RefFilter refFilter) {
  540. this.refFilter = refFilter != null ? refFilter : RefFilter.DEFAULT;
  541. }
  542. /**
  543. * Get the configured pre upload hook.
  544. *
  545. * @return the configured pre upload hook.
  546. */
  547. public PreUploadHook getPreUploadHook() {
  548. return preUploadHook;
  549. }
  550. /**
  551. * Set the hook that controls how this instance will behave.
  552. *
  553. * @param hook
  554. * the hook; if null no special actions are taken.
  555. */
  556. public void setPreUploadHook(@Nullable PreUploadHook hook) {
  557. preUploadHook = hook != null ? hook : PreUploadHook.NULL;
  558. }
  559. /**
  560. * Get the configured post upload hook.
  561. *
  562. * @return the configured post upload hook.
  563. * @since 4.1
  564. */
  565. public PostUploadHook getPostUploadHook() {
  566. return postUploadHook;
  567. }
  568. /**
  569. * Set the hook for post upload actions (logging, repacking).
  570. *
  571. * @param hook
  572. * the hook; if null no special actions are taken.
  573. * @since 4.1
  574. */
  575. public void setPostUploadHook(@Nullable PostUploadHook hook) {
  576. postUploadHook = hook != null ? hook : PostUploadHook.NULL;
  577. }
  578. /**
  579. * Set the configuration used by the pack generator.
  580. *
  581. * @param pc
  582. * configuration controlling packing parameters. If null the
  583. * source repository's settings will be used.
  584. */
  585. public void setPackConfig(@Nullable PackConfig pc) {
  586. this.packConfig = pc;
  587. }
  588. /**
  589. * Set configuration controlling transfer options.
  590. *
  591. * @param tc
  592. * configuration controlling transfer options. If null the source
  593. * repository's settings will be used.
  594. * @since 3.1
  595. */
  596. public void setTransferConfig(@Nullable TransferConfig tc) {
  597. this.transferConfig = tc != null ? tc : new TransferConfig(db);
  598. if (transferConfig.isAllowTipSha1InWant()) {
  599. setRequestPolicy(transferConfig.isAllowReachableSha1InWant()
  600. ? RequestPolicy.REACHABLE_COMMIT_TIP : RequestPolicy.TIP);
  601. } else {
  602. setRequestPolicy(transferConfig.isAllowReachableSha1InWant()
  603. ? RequestPolicy.REACHABLE_COMMIT : RequestPolicy.ADVERTISED);
  604. }
  605. }
  606. /**
  607. * Check whether the client expects a side-band stream.
  608. *
  609. * @return true if the client has advertised a side-band capability, false
  610. * otherwise.
  611. * @throws org.eclipse.jgit.transport.RequestNotYetReadException
  612. * if the client's request has not yet been read from the wire, so
  613. * we do not know if they expect side-band. Note that the client
  614. * may have already written the request, it just has not been
  615. * read.
  616. */
  617. public boolean isSideBand() throws RequestNotYetReadException {
  618. if (currentRequest == null) {
  619. throw new RequestNotYetReadException();
  620. }
  621. Set<String> caps = currentRequest.getClientCapabilities();
  622. return caps.contains(OPTION_SIDE_BAND)
  623. || caps.contains(OPTION_SIDE_BAND_64K);
  624. }
  625. /**
  626. * Set the Extra Parameters provided by the client.
  627. *
  628. * <p>These are parameters passed by the client through a side channel
  629. * such as the Git-Protocol HTTP header, to allow a client to request
  630. * a newer response format while remaining compatible with older servers
  631. * that do not understand different request formats.
  632. *
  633. * @param params
  634. * parameters supplied by the client, split at colons or NUL
  635. * bytes.
  636. * @since 5.0
  637. */
  638. public void setExtraParameters(Collection<String> params) {
  639. this.clientRequestedV2 = params.contains("version=2"); //$NON-NLS-1$
  640. }
  641. private boolean useProtocolV2() {
  642. return ProtocolVersion.V2.equals(transferConfig.protocolVersion)
  643. && clientRequestedV2;
  644. }
  645. /**
  646. * Execute the upload task on the socket.
  647. *
  648. * <p>If the client passed extra parameters (e.g., "version=2") through a
  649. * side channel, the caller must call setExtraParameters first to supply
  650. * them.
  651. *
  652. * @param input
  653. * raw input to read client commands from. Caller must ensure the
  654. * input is buffered, otherwise read performance may suffer.
  655. * @param output
  656. * response back to the Git network client, to write the pack
  657. * data onto. Caller must ensure the output is buffered,
  658. * otherwise write performance may suffer.
  659. * @param messages
  660. * secondary "notice" channel to send additional messages out
  661. * through. When run over SSH this should be tied back to the
  662. * standard error channel of the command execution. For most
  663. * other network connections this should be null.
  664. * @throws java.io.IOException
  665. */
  666. public void upload(final InputStream input, OutputStream output,
  667. final OutputStream messages) throws IOException {
  668. try {
  669. rawIn = input;
  670. if (messages != null)
  671. msgOut = messages;
  672. if (timeout > 0) {
  673. final Thread caller = Thread.currentThread();
  674. timer = new InterruptTimer(caller.getName() + "-Timer"); //$NON-NLS-1$
  675. TimeoutInputStream i = new TimeoutInputStream(rawIn, timer);
  676. @SuppressWarnings("resource")
  677. TimeoutOutputStream o = new TimeoutOutputStream(output, timer);
  678. i.setTimeout(timeout * 1000);
  679. o.setTimeout(timeout * 1000);
  680. rawIn = i;
  681. output = o;
  682. }
  683. rawOut = new ResponseBufferedOutputStream(output);
  684. if (biDirectionalPipe) {
  685. rawOut.stopBuffering();
  686. }
  687. pckIn = new PacketLineIn(rawIn);
  688. pckOut = new PacketLineOut(rawOut);
  689. if (useProtocolV2()) {
  690. serviceV2();
  691. } else {
  692. service();
  693. }
  694. } finally {
  695. msgOut = NullOutputStream.INSTANCE;
  696. walk.close();
  697. if (timer != null) {
  698. try {
  699. timer.terminate();
  700. } finally {
  701. timer = null;
  702. }
  703. }
  704. }
  705. }
  706. /**
  707. * Get the PackWriter's statistics if a pack was sent to the client.
  708. *
  709. * @return statistics about pack output, if a pack was sent. Null if no pack
  710. * was sent, such as during the negotiation phase of a smart HTTP
  711. * connection, or if the client was already up-to-date.
  712. * @since 4.1
  713. */
  714. public PackStatistics getStatistics() {
  715. return statistics;
  716. }
  717. private Map<String, Ref> getAdvertisedOrDefaultRefs() throws IOException {
  718. if (refs != null) {
  719. return refs;
  720. }
  721. if (!advertiseRefsHookCalled) {
  722. advertiseRefsHook.advertiseRefs(this);
  723. advertiseRefsHookCalled = true;
  724. }
  725. if (refs == null) {
  726. // Fall back to all refs.
  727. setAdvertisedRefs(
  728. db.getRefDatabase().getRefs().stream()
  729. .collect(toRefMap((a, b) -> b)));
  730. }
  731. return refs;
  732. }
  733. private Map<String, Ref> getFilteredRefs(Collection<String> refPrefixes)
  734. throws IOException {
  735. if (refPrefixes.isEmpty()) {
  736. return getAdvertisedOrDefaultRefs();
  737. }
  738. if (refs == null && !advertiseRefsHookCalled) {
  739. advertiseRefsHook.advertiseRefs(this);
  740. advertiseRefsHookCalled = true;
  741. }
  742. if (refs == null) {
  743. // Fast path: the advertised refs hook did not set advertised refs.
  744. String[] prefixes = refPrefixes.toArray(new String[0]);
  745. Map<String, Ref> rs =
  746. db.getRefDatabase().getRefsByPrefix(prefixes).stream()
  747. .collect(toRefMap((a, b) -> b));
  748. if (refFilter != RefFilter.DEFAULT) {
  749. return refFilter.filter(rs);
  750. }
  751. return transferConfig.getRefFilter().filter(rs);
  752. }
  753. // Slow path: filter the refs provided by the advertised refs hook.
  754. // refFilter has already been applied to refs.
  755. return refs.values().stream()
  756. .filter(ref -> refPrefixes.stream()
  757. .anyMatch(ref.getName()::startsWith))
  758. .collect(toRefMap((a, b) -> b));
  759. }
  760. /**
  761. * Returns the specified references.
  762. * <p>
  763. * This produces an immutable map containing whatever subset of the
  764. * refs named by the caller are present in the supplied {@code refs}
  765. * map.
  766. *
  767. * @param refs
  768. * Map to search for refs to return.
  769. * @param names
  770. * which refs to search for in {@code refs}.
  771. * @return the requested Refs, omitting any that are null or missing.
  772. */
  773. @NonNull
  774. private static Map<String, Ref> mapRefs(
  775. Map<String, Ref> refs, List<String> names) {
  776. return unmodifiableMap(
  777. names.stream()
  778. .map(refs::get)
  779. .filter(Objects::nonNull)
  780. .collect(toRefMap((a, b) -> b)));
  781. }
  782. /**
  783. * Read refs on behalf of the client.
  784. * <p>
  785. * This checks whether the refs are present in the ref advertisement
  786. * since otherwise the client might not be supposed to be able to
  787. * read them.
  788. *
  789. * @param names
  790. * unabbreviated names of references.
  791. * @return the requested Refs, omitting any that are not visible or
  792. * do not exist.
  793. * @throws java.io.IOException
  794. * on failure to read a ref or check it for visibility.
  795. */
  796. @NonNull
  797. private Map<String, Ref> exactRefs(List<String> names) throws IOException {
  798. if (refs != null) {
  799. return mapRefs(refs, names);
  800. }
  801. if (!advertiseRefsHookCalled) {
  802. advertiseRefsHook.advertiseRefs(this);
  803. advertiseRefsHookCalled = true;
  804. }
  805. if (refs == null &&
  806. refFilter == RefFilter.DEFAULT &&
  807. transferConfig.hasDefaultRefFilter()) {
  808. // Fast path: no ref filtering is needed.
  809. String[] ns = names.toArray(new String[0]);
  810. return unmodifiableMap(db.getRefDatabase().exactRef(ns));
  811. }
  812. return mapRefs(getAdvertisedOrDefaultRefs(), names);
  813. }
  814. /**
  815. * Find a ref in the usual search path on behalf of the client.
  816. * <p>
  817. * This checks that the ref is present in the ref advertisement since
  818. * otherwise the client might not be supposed to be able to read it.
  819. *
  820. * @param name
  821. * short name of the ref to find, e.g. "master" to find
  822. * "refs/heads/master".
  823. * @return the requested Ref, or {@code null} if it is not visible or
  824. * does not exist.
  825. * @throws java.io.IOException
  826. * on failure to read the ref or check it for visibility.
  827. */
  828. @Nullable
  829. private Ref findRef(String name) throws IOException {
  830. if (refs != null) {
  831. return RefDatabase.findRef(refs, name);
  832. }
  833. if (!advertiseRefsHookCalled) {
  834. advertiseRefsHook.advertiseRefs(this);
  835. advertiseRefsHookCalled = true;
  836. }
  837. if (refs == null &&
  838. refFilter == RefFilter.DEFAULT &&
  839. transferConfig.hasDefaultRefFilter()) {
  840. // Fast path: no ref filtering is needed.
  841. return db.getRefDatabase().findRef(name);
  842. }
  843. return RefDatabase.findRef(getAdvertisedOrDefaultRefs(), name);
  844. }
  845. private void service() throws IOException {
  846. boolean sendPack = false;
  847. // If it's a non-bidi request, we need to read the entire request before
  848. // writing a response. Buffer the response until then.
  849. PackStatistics.Accumulator accumulator = new PackStatistics.Accumulator();
  850. List<ObjectId> unshallowCommits = new ArrayList<>();
  851. FetchRequest req;
  852. try {
  853. if (biDirectionalPipe)
  854. sendAdvertisedRefs(new PacketLineOutRefAdvertiser(pckOut));
  855. else if (requestValidator instanceof AnyRequestValidator)
  856. advertised = Collections.emptySet();
  857. else
  858. advertised = refIdSet(getAdvertisedOrDefaultRefs().values());
  859. long negotiateStart = System.currentTimeMillis();
  860. accumulator.advertised = advertised.size();
  861. ProtocolV0Parser parser = new ProtocolV0Parser(transferConfig);
  862. req = parser.recvWants(pckIn);
  863. currentRequest = req;
  864. wantIds = req.getWantIds();
  865. if (req.getWantIds().isEmpty()) {
  866. preUploadHook.onBeginNegotiateRound(this, req.getWantIds(), 0);
  867. preUploadHook.onEndNegotiateRound(this, req.getWantIds(), 0, 0,
  868. false);
  869. return;
  870. }
  871. accumulator.wants = req.getWantIds().size();
  872. if (req.getClientCapabilities().contains(OPTION_MULTI_ACK_DETAILED)) {
  873. multiAck = MultiAck.DETAILED;
  874. noDone = req.getClientCapabilities().contains(OPTION_NO_DONE);
  875. } else if (req.getClientCapabilities().contains(OPTION_MULTI_ACK))
  876. multiAck = MultiAck.CONTINUE;
  877. else
  878. multiAck = MultiAck.OFF;
  879. if (!req.getClientShallowCommits().isEmpty()) {
  880. verifyClientShallow(req.getClientShallowCommits());
  881. }
  882. if (req.getDepth() != 0 || req.getDeepenSince() != 0) {
  883. computeShallowsAndUnshallows(req, shallow -> {
  884. pckOut.writeString("shallow " + shallow.name() + '\n'); //$NON-NLS-1$
  885. }, unshallow -> {
  886. pckOut.writeString("unshallow " + unshallow.name() + '\n'); //$NON-NLS-1$
  887. unshallowCommits.add(unshallow);
  888. }, Collections.emptyList());
  889. pckOut.end();
  890. }
  891. if (!req.getClientShallowCommits().isEmpty())
  892. walk.assumeShallow(req.getClientShallowCommits());
  893. sendPack = negotiate(req, accumulator);
  894. accumulator.timeNegotiating += System.currentTimeMillis()
  895. - negotiateStart;
  896. if (sendPack && !biDirectionalPipe) {
  897. // Ensure the request was fully consumed. Any remaining input must
  898. // be a protocol error. If we aren't at EOF the implementation is broken.
  899. int eof = rawIn.read();
  900. if (0 <= eof) {
  901. sendPack = false;
  902. throw new CorruptObjectException(MessageFormat.format(
  903. JGitText.get().expectedEOFReceived,
  904. "\\x" + Integer.toHexString(eof))); //$NON-NLS-1$
  905. }
  906. }
  907. } catch (ServiceMayNotContinueException err) {
  908. if (!err.isOutput() && err.getMessage() != null) {
  909. try {
  910. pckOut.writeString("ERR " + err.getMessage() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  911. err.setOutput();
  912. } catch (Throwable err2) {
  913. // Ignore this secondary failure (and not mark output).
  914. }
  915. }
  916. throw err;
  917. } catch (IOException | RuntimeException | Error err) {
  918. boolean output = false;
  919. try {
  920. String msg = err instanceof PackProtocolException
  921. ? err.getMessage()
  922. : JGitText.get().internalServerError;
  923. pckOut.writeString("ERR " + msg + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  924. output = true;
  925. } catch (Throwable err2) {
  926. // Ignore this secondary failure, leave output false.
  927. }
  928. if (output) {
  929. throw new UploadPackInternalServerErrorException(err);
  930. }
  931. throw err;
  932. } finally {
  933. if (!sendPack && !biDirectionalPipe) {
  934. while (0 < rawIn.skip(2048) || 0 <= rawIn.read()) {
  935. // Discard until EOF.
  936. }
  937. }
  938. rawOut.stopBuffering();
  939. }
  940. if (sendPack) {
  941. sendPack(accumulator, req, refs == null ? null : refs.values(),
  942. unshallowCommits, Collections.emptyList());
  943. }
  944. }
  945. private void lsRefsV2() throws IOException {
  946. ProtocolV2Parser parser = new ProtocolV2Parser(transferConfig);
  947. LsRefsV2Request req = parser.parseLsRefsRequest(pckIn);
  948. protocolV2Hook.onLsRefs(req);
  949. rawOut.stopBuffering();
  950. PacketLineOutRefAdvertiser adv = new PacketLineOutRefAdvertiser(pckOut);
  951. adv.setUseProtocolV2(true);
  952. if (req.getPeel()) {
  953. adv.setDerefTags(true);
  954. }
  955. Map<String, Ref> refsToSend = getFilteredRefs(req.getRefPrefixes());
  956. if (req.getSymrefs()) {
  957. findSymrefs(adv, refsToSend);
  958. }
  959. adv.send(refsToSend.values());
  960. adv.end();
  961. }
  962. // Resolves ref names from the request's want-ref lines to
  963. // object ids, throwing PackProtocolException if any are missing.
  964. private Map<String, ObjectId> wantedRefs(FetchV2Request req)
  965. throws IOException {
  966. Map<String, ObjectId> result = new TreeMap<>();
  967. List<String> wanted = req.getWantedRefs();
  968. Map<String, Ref> resolved = exactRefs(wanted);
  969. for (String refName : wanted) {
  970. Ref ref = resolved.get(refName);
  971. if (ref == null) {
  972. throw new PackProtocolException(MessageFormat
  973. .format(JGitText.get().invalidRefName, refName));
  974. }
  975. ObjectId oid = ref.getObjectId();
  976. if (oid == null) {
  977. throw new PackProtocolException(MessageFormat
  978. .format(JGitText.get().invalidRefName, refName));
  979. }
  980. result.put(refName, oid);
  981. }
  982. return result;
  983. }
  984. private void fetchV2() throws IOException {
  985. // Depending on the requestValidator, #processHaveLines may
  986. // require that advertised be set. Set it only in the required
  987. // circumstances (to avoid a full ref lookup in the case that
  988. // we don't need it).
  989. if (requestValidator instanceof TipRequestValidator ||
  990. requestValidator instanceof ReachableCommitTipRequestValidator ||
  991. requestValidator instanceof AnyRequestValidator) {
  992. advertised = Collections.emptySet();
  993. } else {
  994. advertised = refIdSet(getAdvertisedOrDefaultRefs().values());
  995. }
  996. ProtocolV2Parser parser = new ProtocolV2Parser(transferConfig);
  997. FetchV2Request req = parser.parseFetchRequest(pckIn);
  998. currentRequest = req;
  999. rawOut.stopBuffering();
  1000. protocolV2Hook.onFetch(req);
  1001. // TODO(ifrade): Refactor to pass around the Request object, instead of
  1002. // copying data back to class fields
  1003. List<ObjectId> deepenNots = new ArrayList<>();
  1004. for (String s : req.getDeepenNotRefs()) {
  1005. Ref ref = findRef(s);
  1006. if (ref == null) {
  1007. throw new PackProtocolException(MessageFormat
  1008. .format(JGitText.get().invalidRefName, s));
  1009. }
  1010. deepenNots.add(ref.getObjectId());
  1011. }
  1012. Map<String, ObjectId> wantedRefs = wantedRefs(req);
  1013. // TODO(ifrade): Avoid mutating the parsed request.
  1014. req.getWantIds().addAll(wantedRefs.values());
  1015. wantIds = req.getWantIds();
  1016. boolean sectionSent = false;
  1017. boolean mayHaveShallow = req.getDepth() != 0
  1018. || req.getDeepenSince() != 0
  1019. || !req.getDeepenNotRefs().isEmpty();
  1020. List<ObjectId> shallowCommits = new ArrayList<>();
  1021. List<ObjectId> unshallowCommits = new ArrayList<>();
  1022. if (!req.getClientShallowCommits().isEmpty()) {
  1023. verifyClientShallow(req.getClientShallowCommits());
  1024. }
  1025. if (mayHaveShallow) {
  1026. computeShallowsAndUnshallows(req,
  1027. shallowCommit -> shallowCommits.add(shallowCommit),
  1028. unshallowCommit -> unshallowCommits.add(unshallowCommit),
  1029. deepenNots);
  1030. }
  1031. if (!req.getClientShallowCommits().isEmpty())
  1032. walk.assumeShallow(req.getClientShallowCommits());
  1033. if (req.wasDoneReceived()) {
  1034. processHaveLines(req.getPeerHas(), ObjectId.zeroId(),
  1035. new PacketLineOut(NullOutputStream.INSTANCE));
  1036. } else {
  1037. pckOut.writeString("acknowledgments\n"); //$NON-NLS-1$
  1038. for (ObjectId id : req.getPeerHas()) {
  1039. if (walk.getObjectReader().has(id)) {
  1040. pckOut.writeString("ACK " + id.getName() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1041. }
  1042. }
  1043. processHaveLines(req.getPeerHas(), ObjectId.zeroId(),
  1044. new PacketLineOut(NullOutputStream.INSTANCE));
  1045. if (okToGiveUp()) {
  1046. pckOut.writeString("ready\n"); //$NON-NLS-1$
  1047. } else if (commonBase.isEmpty()) {
  1048. pckOut.writeString("NAK\n"); //$NON-NLS-1$
  1049. }
  1050. sectionSent = true;
  1051. }
  1052. if (req.wasDoneReceived() || okToGiveUp()) {
  1053. if (mayHaveShallow) {
  1054. if (sectionSent)
  1055. pckOut.writeDelim();
  1056. pckOut.writeString("shallow-info\n"); //$NON-NLS-1$
  1057. for (ObjectId o : shallowCommits) {
  1058. pckOut.writeString("shallow " + o.getName() + '\n'); //$NON-NLS-1$
  1059. }
  1060. for (ObjectId o : unshallowCommits) {
  1061. pckOut.writeString("unshallow " + o.getName() + '\n'); //$NON-NLS-1$
  1062. }
  1063. sectionSent = true;
  1064. }
  1065. if (!wantedRefs.isEmpty()) {
  1066. if (sectionSent) {
  1067. pckOut.writeDelim();
  1068. }
  1069. pckOut.writeString("wanted-refs\n"); //$NON-NLS-1$
  1070. for (Map.Entry<String, ObjectId> entry :
  1071. wantedRefs.entrySet()) {
  1072. pckOut.writeString(entry.getValue().getName() + ' ' +
  1073. entry.getKey() + '\n');
  1074. }
  1075. sectionSent = true;
  1076. }
  1077. if (sectionSent)
  1078. pckOut.writeDelim();
  1079. pckOut.writeString("packfile\n"); //$NON-NLS-1$
  1080. sendPack(new PackStatistics.Accumulator(),
  1081. req,
  1082. req.getClientCapabilities().contains(OPTION_INCLUDE_TAG)
  1083. ? db.getRefDatabase().getRefsByPrefix(R_TAGS)
  1084. : null,
  1085. unshallowCommits, deepenNots);
  1086. // sendPack invokes pckOut.end() for us, so we do not
  1087. // need to invoke it here.
  1088. } else {
  1089. // Invoke pckOut.end() by ourselves.
  1090. pckOut.end();
  1091. }
  1092. }
  1093. /*
  1094. * Returns true if this is the last command and we should tear down the
  1095. * connection.
  1096. */
  1097. private boolean serveOneCommandV2() throws IOException {
  1098. String command;
  1099. try {
  1100. command = pckIn.readString();
  1101. } catch (EOFException eof) {
  1102. /* EOF when awaiting command is fine */
  1103. return true;
  1104. }
  1105. if (command == PacketLineIn.END) {
  1106. // A blank request is valid according
  1107. // to the protocol; do nothing in this
  1108. // case.
  1109. return true;
  1110. }
  1111. if (command.equals("command=" + COMMAND_LS_REFS)) { //$NON-NLS-1$
  1112. lsRefsV2();
  1113. return false;
  1114. }
  1115. if (command.equals("command=" + COMMAND_FETCH)) { //$NON-NLS-1$
  1116. fetchV2();
  1117. return false;
  1118. }
  1119. throw new PackProtocolException(MessageFormat
  1120. .format(JGitText.get().unknownTransportCommand, command));
  1121. }
  1122. private List<String> getV2CapabilityAdvertisement() {
  1123. ArrayList<String> caps = new ArrayList<>();
  1124. caps.add("version 2"); //$NON-NLS-1$
  1125. caps.add(COMMAND_LS_REFS);
  1126. boolean advertiseRefInWant = transferConfig.isAllowRefInWant() &&
  1127. db.getConfig().getBoolean("uploadpack", null, //$NON-NLS-1$
  1128. "advertiserefinwant", true); //$NON-NLS-1$
  1129. caps.add(
  1130. COMMAND_FETCH + '=' +
  1131. (transferConfig.isAllowFilter() ? OPTION_FILTER + ' ' : "") + //$NON-NLS-1$
  1132. (advertiseRefInWant ? CAPABILITY_REF_IN_WANT + ' ' : "") + //$NON-NLS-1$
  1133. OPTION_SHALLOW);
  1134. caps.add(CAPABILITY_SERVER_OPTION);
  1135. return caps;
  1136. }
  1137. private void serviceV2() throws IOException {
  1138. if (biDirectionalPipe) {
  1139. // Just like in service(), the capability advertisement
  1140. // is sent only if this is a bidirectional pipe. (If
  1141. // not, the client is expected to call
  1142. // sendAdvertisedRefs() on its own.)
  1143. protocolV2Hook
  1144. .onCapabilities(CapabilitiesV2Request.builder().build());
  1145. for (String s : getV2CapabilityAdvertisement()) {
  1146. pckOut.writeString(s + "\n"); //$NON-NLS-1$
  1147. }
  1148. pckOut.end();
  1149. while (!serveOneCommandV2()) {
  1150. // Repeat until an empty command or EOF.
  1151. }
  1152. return;
  1153. }
  1154. try {
  1155. serveOneCommandV2();
  1156. } finally {
  1157. while (0 < rawIn.skip(2048) || 0 <= rawIn.read()) {
  1158. // Discard until EOF.
  1159. }
  1160. rawOut.stopBuffering();
  1161. }
  1162. }
  1163. private static Set<ObjectId> refIdSet(Collection<Ref> refs) {
  1164. Set<ObjectId> ids = new HashSet<>(refs.size());
  1165. for (Ref ref : refs) {
  1166. ObjectId id = ref.getObjectId();
  1167. if (id != null) {
  1168. ids.add(id);
  1169. }
  1170. id = ref.getPeeledObjectId();
  1171. if (id != null) {
  1172. ids.add(id);
  1173. }
  1174. }
  1175. return ids;
  1176. }
  1177. /*
  1178. * Determines what object ids must be marked as shallow or unshallow for the
  1179. * client.
  1180. */
  1181. private void computeShallowsAndUnshallows(FetchRequest req,
  1182. IOConsumer<ObjectId> shallowFunc,
  1183. IOConsumer<ObjectId> unshallowFunc,
  1184. List<ObjectId> deepenNots)
  1185. throws IOException {
  1186. if (req.getClientCapabilities().contains(OPTION_DEEPEN_RELATIVE)) {
  1187. // TODO(jonathantanmy): Implement deepen-relative
  1188. throw new UnsupportedOperationException();
  1189. }
  1190. int walkDepth = req.getDepth() == 0 ? Integer.MAX_VALUE
  1191. : req.getDepth() - 1;
  1192. try (DepthWalk.RevWalk depthWalk = new DepthWalk.RevWalk(
  1193. walk.getObjectReader(), walkDepth)) {
  1194. depthWalk.setDeepenSince(req.getDeepenSince());
  1195. // Find all the commits which will be shallow
  1196. for (ObjectId o : req.getWantIds()) {
  1197. try {
  1198. depthWalk.markRoot(depthWalk.parseCommit(o));
  1199. } catch (IncorrectObjectTypeException notCommit) {
  1200. // Ignore non-commits in this loop.
  1201. }
  1202. }
  1203. depthWalk.setDeepenNots(deepenNots);
  1204. RevCommit o;
  1205. boolean atLeastOne = false;
  1206. while ((o = depthWalk.next()) != null) {
  1207. DepthWalk.Commit c = (DepthWalk.Commit) o;
  1208. atLeastOne = true;
  1209. boolean isBoundary = (c.getDepth() == walkDepth) || c.isBoundary();
  1210. // Commits at the boundary which aren't already shallow in
  1211. // the client need to be marked as such
  1212. if (isBoundary && !req.getClientShallowCommits().contains(c)) {
  1213. shallowFunc.accept(c.copy());
  1214. }
  1215. // Commits not on the boundary which are shallow in the client
  1216. // need to become unshallowed
  1217. if (!isBoundary && req.getClientShallowCommits().remove(c)) {
  1218. unshallowFunc.accept(c.copy());
  1219. }
  1220. }
  1221. if (!atLeastOne) {
  1222. throw new PackProtocolException(
  1223. JGitText.get().noCommitsSelectedForShallow);
  1224. }
  1225. }
  1226. }
  1227. /*
  1228. * Verify all shallow lines refer to commits
  1229. *
  1230. * It can mutate the input set (removing missing object ids from it)
  1231. */
  1232. private void verifyClientShallow(Set<ObjectId> shallowCommits)
  1233. throws IOException, PackProtocolException {
  1234. AsyncRevObjectQueue q = walk.parseAny(shallowCommits, true);
  1235. try {
  1236. for (;;) {
  1237. try {
  1238. // Shallow objects named by the client must be commits.
  1239. RevObject o = q.next();
  1240. if (o == null) {
  1241. break;
  1242. }
  1243. if (!(o instanceof RevCommit)) {
  1244. throw new PackProtocolException(
  1245. MessageFormat.format(
  1246. JGitText.get().invalidShallowObject,
  1247. o.name()));
  1248. }
  1249. } catch (MissingObjectException notCommit) {
  1250. // shallow objects not known at the server are ignored
  1251. // by git-core upload-pack, match that behavior.
  1252. shallowCommits.remove(notCommit.getObjectId());
  1253. continue;
  1254. }
  1255. }
  1256. } finally {
  1257. q.release();
  1258. }
  1259. }
  1260. /**
  1261. * Generate an advertisement of available refs and capabilities.
  1262. *
  1263. * @param adv
  1264. * the advertisement formatter.
  1265. * @throws java.io.IOException
  1266. * the formatter failed to write an advertisement.
  1267. * @throws org.eclipse.jgit.transport.ServiceMayNotContinueException
  1268. * the hook denied advertisement.
  1269. */
  1270. public void sendAdvertisedRefs(RefAdvertiser adv) throws IOException,
  1271. ServiceMayNotContinueException {
  1272. sendAdvertisedRefs(adv, null);
  1273. }
  1274. /**
  1275. * Generate an advertisement of available refs and capabilities.
  1276. *
  1277. * @param adv
  1278. * the advertisement formatter.
  1279. * @param serviceName
  1280. * if not null, also output "# service=serviceName" followed by a
  1281. * flush packet before the advertisement. This is required
  1282. * in v0 of the HTTP protocol, described in Git's
  1283. * Documentation/technical/http-protocol.txt.
  1284. * @throws java.io.IOException
  1285. * the formatter failed to write an advertisement.
  1286. * @throws org.eclipse.jgit.transport.ServiceMayNotContinueException
  1287. * the hook denied advertisement.
  1288. * @since 5.0
  1289. */
  1290. public void sendAdvertisedRefs(RefAdvertiser adv,
  1291. @Nullable String serviceName) throws IOException,
  1292. ServiceMayNotContinueException {
  1293. if (useProtocolV2()) {
  1294. // The equivalent in v2 is only the capabilities
  1295. // advertisement.
  1296. protocolV2Hook
  1297. .onCapabilities(CapabilitiesV2Request.builder().build());
  1298. for (String s : getV2CapabilityAdvertisement()) {
  1299. adv.writeOne(s);
  1300. }
  1301. adv.end();
  1302. return;
  1303. }
  1304. Map<String, Ref> advertisedOrDefaultRefs = getAdvertisedOrDefaultRefs();
  1305. if (serviceName != null) {
  1306. adv.writeOne("# service=" + serviceName + '\n'); //$NON-NLS-1$
  1307. adv.end();
  1308. }
  1309. adv.init(db);
  1310. adv.advertiseCapability(OPTION_INCLUDE_TAG);
  1311. adv.advertiseCapability(OPTION_MULTI_ACK_DETAILED);
  1312. adv.advertiseCapability(OPTION_MULTI_ACK);
  1313. adv.advertiseCapability(OPTION_OFS_DELTA);
  1314. adv.advertiseCapability(OPTION_SIDE_BAND);
  1315. adv.advertiseCapability(OPTION_SIDE_BAND_64K);
  1316. adv.advertiseCapability(OPTION_THIN_PACK);
  1317. adv.advertiseCapability(OPTION_NO_PROGRESS);
  1318. adv.advertiseCapability(OPTION_SHALLOW);
  1319. if (!biDirectionalPipe)
  1320. adv.advertiseCapability(OPTION_NO_DONE);
  1321. RequestPolicy policy = getRequestPolicy();
  1322. if (policy == RequestPolicy.TIP
  1323. || policy == RequestPolicy.REACHABLE_COMMIT_TIP
  1324. || policy == null)
  1325. adv.advertiseCapability(OPTION_ALLOW_TIP_SHA1_IN_WANT);
  1326. if (policy == RequestPolicy.REACHABLE_COMMIT
  1327. || policy == RequestPolicy.REACHABLE_COMMIT_TIP
  1328. || policy == null)
  1329. adv.advertiseCapability(OPTION_ALLOW_REACHABLE_SHA1_IN_WANT);
  1330. adv.advertiseCapability(OPTION_AGENT, UserAgent.get());
  1331. if (transferConfig.isAllowFilter()) {
  1332. adv.advertiseCapability(OPTION_FILTER);
  1333. }
  1334. adv.setDerefTags(true);
  1335. findSymrefs(adv, advertisedOrDefaultRefs);
  1336. advertised = adv.send(advertisedOrDefaultRefs.values());
  1337. if (adv.isEmpty())
  1338. adv.advertiseId(ObjectId.zeroId(), "capabilities^{}"); //$NON-NLS-1$
  1339. adv.end();
  1340. }
  1341. /**
  1342. * Send a message to the client, if it supports receiving them.
  1343. * <p>
  1344. * If the client doesn't support receiving messages, the message will be
  1345. * discarded, with no other indication to the caller or to the client.
  1346. *
  1347. * @param what
  1348. * string describing the problem identified by the hook. The
  1349. * string must not end with an LF, and must not contain an LF.
  1350. * @since 3.1
  1351. */
  1352. public void sendMessage(String what) {
  1353. try {
  1354. msgOut.write(Constants.encode(what + "\n")); //$NON-NLS-1$
  1355. } catch (IOException e) {
  1356. // Ignore write failures.
  1357. }
  1358. }
  1359. /**
  1360. * Get an underlying stream for sending messages to the client
  1361. *
  1362. * @return an underlying stream for sending messages to the client, or null.
  1363. * @since 3.1
  1364. */
  1365. public OutputStream getMessageOutputStream() {
  1366. return msgOut;
  1367. }
  1368. /**
  1369. * Returns the clone/fetch depth. Valid only after calling recvWants(). A
  1370. * depth of 1 means return only the wants.
  1371. *
  1372. * @return the depth requested by the client, or 0 if unbounded.
  1373. * @since 4.0
  1374. */
  1375. public int getDepth() {
  1376. if (currentRequest == null)
  1377. throw new RequestNotYetReadException();
  1378. return currentRequest.getDepth();
  1379. }
  1380. /**
  1381. * Returns the filter blob limit for the current request. Valid only after
  1382. * calling recvWants(). A limit -1 means no limit.
  1383. *
  1384. * @return filter blob limit requested by the client, or -1 if no limit
  1385. * @since 5.3
  1386. */
  1387. public long getFilterBlobLimit() {
  1388. if (currentRequest == null) {
  1389. throw new RequestNotYetReadException();
  1390. }
  1391. return currentRequest.getFilterSpec().getBlobLimit();
  1392. }
  1393. /**
  1394. * Get the user agent of the client.
  1395. * <p>
  1396. * If the client is new enough to use {@code agent=} capability that value
  1397. * will be returned. Older HTTP clients may also supply their version using
  1398. * the HTTP {@code User-Agent} header. The capability overrides the HTTP
  1399. * header if both are available.
  1400. * <p>
  1401. * When an HTTP request has been received this method returns the HTTP
  1402. * {@code User-Agent} header value until capabilities have been parsed.
  1403. *
  1404. * @return user agent supplied by the client. Available only if the client
  1405. * is new enough to advertise its user agent.
  1406. * @since 4.0
  1407. */
  1408. public String getPeerUserAgent() {
  1409. if (currentRequest != null && currentRequest.getAgent() != null) {
  1410. return currentRequest.getAgent();
  1411. }
  1412. return userAgent;
  1413. }
  1414. private boolean negotiate(FetchRequest req,
  1415. PackStatistics.Accumulator accumulator)
  1416. throws IOException {
  1417. okToGiveUp = Boolean.FALSE;
  1418. ObjectId last = ObjectId.zeroId();
  1419. List<ObjectId> peerHas = new ArrayList<>(64);
  1420. for (;;) {
  1421. String line;
  1422. try {
  1423. line = pckIn.readString();
  1424. } catch (EOFException eof) {
  1425. // EOF on stateless RPC (aka smart HTTP) and non-shallow request
  1426. // means the client asked for the updated shallow/unshallow data,
  1427. // disconnected, and will try another request with actual want/have.
  1428. // Don't report the EOF here, its a bug in the protocol that the client
  1429. // just disconnects without sending an END.
  1430. if (!biDirectionalPipe && req.getDepth() > 0)
  1431. return false;
  1432. throw eof;
  1433. }
  1434. if (line == PacketLineIn.END) {
  1435. last = processHaveLines(peerHas, last, pckOut);
  1436. if (commonBase.isEmpty() || multiAck != MultiAck.OFF)
  1437. pckOut.writeString("NAK\n"); //$NON-NLS-1$
  1438. if (noDone && sentReady) {
  1439. pckOut.writeString("ACK " + last.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1440. return true;
  1441. }
  1442. if (!biDirectionalPipe)
  1443. return false;
  1444. pckOut.flush();
  1445. } else if (line.startsWith("have ") && line.length() == 45) { //$NON-NLS-1$
  1446. peerHas.add(ObjectId.fromString(line.substring(5)));
  1447. accumulator.haves++;
  1448. } else if (line.equals("done")) { //$NON-NLS-1$
  1449. last = processHaveLines(peerHas, last, pckOut);
  1450. if (commonBase.isEmpty())
  1451. pckOut.writeString("NAK\n"); //$NON-NLS-1$
  1452. else if (multiAck != MultiAck.OFF)
  1453. pckOut.writeString("ACK " + last.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1454. return true;
  1455. } else {
  1456. throw new PackProtocolException(MessageFormat.format(JGitText.get().expectedGot, "have", line)); //$NON-NLS-1$
  1457. }
  1458. }
  1459. }
  1460. private ObjectId processHaveLines(List<ObjectId> peerHas, ObjectId last, PacketLineOut out)
  1461. throws IOException {
  1462. preUploadHook.onBeginNegotiateRound(this, wantIds, peerHas.size());
  1463. if (wantAll.isEmpty() && !wantIds.isEmpty())
  1464. parseWants();
  1465. if (peerHas.isEmpty())
  1466. return last;
  1467. sentReady = false;
  1468. int haveCnt = 0;
  1469. walk.getObjectReader().setAvoidUnreachableObjects(true);
  1470. AsyncRevObjectQueue q = walk.parseAny(peerHas, false);
  1471. try {
  1472. for (;;) {
  1473. RevObject obj;
  1474. try {
  1475. obj = q.next();
  1476. } catch (MissingObjectException notFound) {
  1477. continue;
  1478. }
  1479. if (obj == null)
  1480. break;
  1481. last = obj;
  1482. haveCnt++;
  1483. if (obj instanceof RevCommit) {
  1484. RevCommit c = (RevCommit) obj;
  1485. if (oldestTime == 0 || c.getCommitTime() < oldestTime)
  1486. oldestTime = c.getCommitTime();
  1487. }
  1488. if (obj.has(PEER_HAS))
  1489. continue;
  1490. obj.add(PEER_HAS);
  1491. if (obj instanceof RevCommit)
  1492. ((RevCommit) obj).carry(PEER_HAS);
  1493. addCommonBase(obj);
  1494. // If both sides have the same object; let the client know.
  1495. //
  1496. switch (multiAck) {
  1497. case OFF:
  1498. if (commonBase.size() == 1)
  1499. out.writeString("ACK " + obj.name() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1500. break;
  1501. case CONTINUE:
  1502. out.writeString("ACK " + obj.name() + " continue\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1503. break;
  1504. case DETAILED:
  1505. out.writeString("ACK " + obj.name() + " common\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1506. break;
  1507. }
  1508. }
  1509. } finally {
  1510. q.release();
  1511. walk.getObjectReader().setAvoidUnreachableObjects(false);
  1512. }
  1513. int missCnt = peerHas.size() - haveCnt;
  1514. // If we don't have one of the objects but we're also willing to
  1515. // create a pack at this point, let the client know so it stops
  1516. // telling us about its history.
  1517. //
  1518. boolean didOkToGiveUp = false;
  1519. if (0 < missCnt) {
  1520. for (int i = peerHas.size() - 1; i >= 0; i--) {
  1521. ObjectId id = peerHas.get(i);
  1522. if (walk.lookupOrNull(id) == null) {
  1523. didOkToGiveUp = true;
  1524. if (okToGiveUp()) {
  1525. switch (multiAck) {
  1526. case OFF:
  1527. break;
  1528. case CONTINUE:
  1529. out.writeString("ACK " + id.name() + " continue\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1530. break;
  1531. case DETAILED:
  1532. out.writeString("ACK " + id.name() + " ready\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1533. sentReady = true;
  1534. break;
  1535. }
  1536. }
  1537. break;
  1538. }
  1539. }
  1540. }
  1541. if (multiAck == MultiAck.DETAILED && !didOkToGiveUp && okToGiveUp()) {
  1542. ObjectId id = peerHas.get(peerHas.size() - 1);
  1543. out.writeString("ACK " + id.name() + " ready\n"); //$NON-NLS-1$ //$NON-NLS-2$
  1544. sentReady = true;
  1545. }
  1546. preUploadHook.onEndNegotiateRound(this, wantAll, haveCnt, missCnt, sentReady);
  1547. peerHas.clear();
  1548. return last;
  1549. }
  1550. private void parseWants() throws IOException {
  1551. List<ObjectId> notAdvertisedWants = null;
  1552. for (ObjectId obj : wantIds) {
  1553. if (!advertised.contains(obj)) {
  1554. if (notAdvertisedWants == null)
  1555. notAdvertisedWants = new ArrayList<>();
  1556. notAdvertisedWants.add(obj);
  1557. }
  1558. }
  1559. if (notAdvertisedWants != null)
  1560. requestValidator.checkWants(this, notAdvertisedWants);
  1561. AsyncRevObjectQueue q = walk.parseAny(wantIds, true);
  1562. try {
  1563. RevObject obj;
  1564. while ((obj = q.next()) != null) {
  1565. want(obj);
  1566. if (!(obj instanceof RevCommit))
  1567. obj.add(SATISFIED);
  1568. if (obj instanceof RevTag) {
  1569. obj = walk.peel(obj);
  1570. if (obj instanceof RevCommit)
  1571. want(obj);
  1572. }
  1573. }
  1574. wantIds.clear();
  1575. } catch (MissingObjectException notFound) {
  1576. throw new WantNotValidException(notFound.getObjectId(), notFound);
  1577. } finally {
  1578. q.release();
  1579. }
  1580. }
  1581. private void want(RevObject obj) {
  1582. if (!obj.has(WANT)) {
  1583. obj.add(WANT);
  1584. wantAll.add(obj);
  1585. }
  1586. }
  1587. /**
  1588. * Validator corresponding to {@link RequestPolicy#ADVERTISED}.
  1589. *
  1590. * @since 3.1
  1591. */
  1592. public static final class AdvertisedRequestValidator
  1593. implements RequestValidator {
  1594. @Override
  1595. public void checkWants(UploadPack up, List<ObjectId> wants)
  1596. throws PackProtocolException, IOException {
  1597. if (!up.isBiDirectionalPipe())
  1598. new ReachableCommitRequestValidator().checkWants(up, wants);
  1599. else if (!wants.isEmpty())
  1600. throw new WantNotValidException(wants.iterator().next());
  1601. }
  1602. }
  1603. /**
  1604. * Validator corresponding to {@link RequestPolicy#REACHABLE_COMMIT}.
  1605. *
  1606. * @since 3.1
  1607. */
  1608. public static final class ReachableCommitRequestValidator
  1609. implements RequestValidator {
  1610. @Override
  1611. public void checkWants(UploadPack up, List<ObjectId> wants)
  1612. throws PackProtocolException, IOException {
  1613. checkNotAdvertisedWants(up, wants,
  1614. refIdSet(up.getAdvertisedRefs().values()));
  1615. }
  1616. }
  1617. /**
  1618. * Validator corresponding to {@link RequestPolicy#TIP}.
  1619. *
  1620. * @since 3.1
  1621. */
  1622. public static final class TipRequestValidator implements RequestValidator {
  1623. @Override
  1624. public void checkWants(UploadPack up, List<ObjectId> wants)
  1625. throws PackProtocolException, IOException {
  1626. if (!up.isBiDirectionalPipe())
  1627. new ReachableCommitTipRequestValidator().checkWants(up, wants);
  1628. else if (!wants.isEmpty()) {
  1629. Set<ObjectId> refIds =
  1630. refIdSet(up.getRepository().getRefDatabase().getRefs());
  1631. for (ObjectId obj : wants) {
  1632. if (!refIds.contains(obj))
  1633. throw new WantNotValidException(obj);
  1634. }
  1635. }
  1636. }
  1637. }
  1638. /**
  1639. * Validator corresponding to {@link RequestPolicy#REACHABLE_COMMIT_TIP}.
  1640. *
  1641. * @since 3.1
  1642. */
  1643. public static final class ReachableCommitTipRequestValidator
  1644. implements RequestValidator {
  1645. @Override
  1646. public void checkWants(UploadPack up, List<ObjectId> wants)
  1647. throws PackProtocolException, IOException {
  1648. checkNotAdvertisedWants(up, wants,
  1649. refIdSet(up.getRepository().getRefDatabase().getRefs()));
  1650. }
  1651. }
  1652. /**
  1653. * Validator corresponding to {@link RequestPolicy#ANY}.
  1654. *
  1655. * @since 3.1
  1656. */
  1657. public static final class AnyRequestValidator implements RequestValidator {
  1658. @Override
  1659. public void checkWants(UploadPack up, List<ObjectId> wants)
  1660. throws PackProtocolException, IOException {
  1661. // All requests are valid.
  1662. }
  1663. }
  1664. private static void checkNotAdvertisedWantsUsingBitmap(ObjectReader reader,
  1665. BitmapIndex bitmapIndex, List<ObjectId> notAdvertisedWants,
  1666. Set<ObjectId> reachableFrom) throws IOException {
  1667. BitmapWalker bitmapWalker = new BitmapWalker(new ObjectWalk(reader), bitmapIndex, null);
  1668. BitmapBuilder reachables = bitmapWalker.findObjects(reachableFrom, null, false);
  1669. for (ObjectId oid : notAdvertisedWants) {
  1670. if (!reachables.contains(oid)) {
  1671. throw new WantNotValidException(oid);
  1672. }
  1673. }
  1674. }
  1675. private static void checkNotAdvertisedWants(UploadPack up,
  1676. List<ObjectId> notAdvertisedWants, Set<ObjectId> reachableFrom)
  1677. throws MissingObjectException, IncorrectObjectTypeException, IOException {
  1678. // Walk the requested commits back to the provided set of commits. If any
  1679. // commit exists, a branch was deleted or rewound and the repository owner
  1680. // no longer exports that requested item. If the requested commit is merged
  1681. // into an advertised branch it will be marked UNINTERESTING and no commits
  1682. // return.
  1683. ObjectReader reader = up.getRevWalk().getObjectReader();
  1684. try (RevWalk walk = new RevWalk(reader)) {
  1685. walk.setRetainBody(false);
  1686. AsyncRevObjectQueue q = walk.parseAny(notAdvertisedWants, true);
  1687. try {
  1688. RevObject obj;
  1689. while ((obj = q.next()) != null) {
  1690. if (!(obj instanceof RevCommit)) {
  1691. // If unadvertized non-commits are requested, use
  1692. // bitmaps. If there are no bitmaps, instead of
  1693. // incurring the expense of a manual walk, reject
  1694. // the request.
  1695. BitmapIndex bitmapIndex = reader.getBitmapIndex();
  1696. if (bitmapIndex != null) {
  1697. checkNotAdvertisedWantsUsingBitmap(
  1698. reader,
  1699. bitmapIndex,
  1700. notAdvertisedWants,
  1701. reachableFrom);
  1702. return;
  1703. }
  1704. throw new WantNotValidException(obj);
  1705. }
  1706. walk.markStart((RevCommit) obj);
  1707. }
  1708. } catch (MissingObjectException notFound) {
  1709. throw new WantNotValidException(notFound.getObjectId(),
  1710. notFound);
  1711. } finally {
  1712. q.release();
  1713. }
  1714. for (ObjectId id : reachableFrom) {
  1715. try {
  1716. walk.markUninteresting(walk.parseCommit(id));
  1717. } catch (IncorrectObjectTypeException notCommit) {
  1718. continue;
  1719. }
  1720. }
  1721. RevCommit bad = walk.next();
  1722. if (bad != null) {
  1723. throw new WantNotValidException(bad);
  1724. }
  1725. }
  1726. }
  1727. private void addCommonBase(RevObject o) {
  1728. if (!o.has(COMMON)) {
  1729. o.add(COMMON);
  1730. commonBase.add(o);
  1731. okToGiveUp = null;
  1732. }
  1733. }
  1734. private boolean okToGiveUp() throws PackProtocolException {
  1735. if (okToGiveUp == null)
  1736. okToGiveUp = Boolean.valueOf(okToGiveUpImp());
  1737. return okToGiveUp.booleanValue();
  1738. }
  1739. private boolean okToGiveUpImp() throws PackProtocolException {
  1740. if (commonBase.isEmpty())
  1741. return false;
  1742. try {
  1743. for (RevObject obj : wantAll) {
  1744. if (!wantSatisfied(obj))
  1745. return false;
  1746. }
  1747. return true;
  1748. } catch (IOException e) {
  1749. throw new PackProtocolException(JGitText.get().internalRevisionError, e);
  1750. }
  1751. }
  1752. private boolean wantSatisfied(RevObject want) throws IOException {
  1753. if (want.has(SATISFIED))
  1754. return true;
  1755. walk.resetRetain(SAVE);
  1756. walk.markStart((RevCommit) want);
  1757. if (oldestTime != 0)
  1758. walk.setRevFilter(CommitTimeRevFilter.after(oldestTime * 1000L));
  1759. for (;;) {
  1760. final RevCommit c = walk.next();
  1761. if (c == null)
  1762. break;
  1763. if (c.has(PEER_HAS)) {
  1764. addCommonBase(c);
  1765. want.add(SATISFIED);
  1766. return true;
  1767. }
  1768. }
  1769. return false;
  1770. }
  1771. /**
  1772. * Send the requested objects to the client.
  1773. *
  1774. * @param accumulator
  1775. * where to write statistics about the content of the pack.
  1776. * @param req
  1777. * request in process
  1778. * @param allTags
  1779. * refs to search for annotated tags to include in the pack if
  1780. * the {@link #OPTION_INCLUDE_TAG} capability was requested.
  1781. * @param unshallowCommits
  1782. * shallow commits on the client that are now becoming unshallow
  1783. * @param deepenNots
  1784. * objects that the client specified using --shallow-exclude
  1785. * @throws IOException
  1786. * if an error occurred while generating or writing the pack.
  1787. */
  1788. private void sendPack(PackStatistics.Accumulator accumulator,
  1789. FetchRequest req,
  1790. @Nullable Collection<Ref> allTags,
  1791. List<ObjectId> unshallowCommits,
  1792. List<ObjectId> deepenNots) throws IOException {
  1793. Set<String> caps = req.getClientCapabilities();
  1794. boolean sideband = caps.contains(OPTION_SIDE_BAND)
  1795. || caps.contains(OPTION_SIDE_BAND_64K);
  1796. if (sideband) {
  1797. try {
  1798. sendPack(true, req, accumulator, allTags, unshallowCommits,
  1799. deepenNots);
  1800. } catch (ServiceMayNotContinueException noPack) {
  1801. // This was already reported on (below).
  1802. throw noPack;
  1803. } catch (IOException err) {
  1804. if (reportInternalServerErrorOverSideband())
  1805. throw new UploadPackInternalServerErrorException(err);
  1806. else
  1807. throw err;
  1808. } catch (RuntimeException err) {
  1809. if (reportInternalServerErrorOverSideband())
  1810. throw new UploadPackInternalServerErrorException(err);
  1811. else
  1812. throw err;
  1813. } catch (Error err) {
  1814. if (reportInternalServerErrorOverSideband())
  1815. throw new UploadPackInternalServerErrorException(err);
  1816. else
  1817. throw err;
  1818. }
  1819. } else {
  1820. sendPack(false, req, accumulator, allTags, unshallowCommits, deepenNots);
  1821. }
  1822. }
  1823. private boolean reportInternalServerErrorOverSideband() {
  1824. try {
  1825. @SuppressWarnings("resource" /* java 7 */)
  1826. SideBandOutputStream err = new SideBandOutputStream(
  1827. SideBandOutputStream.CH_ERROR,
  1828. SideBandOutputStream.SMALL_BUF,
  1829. rawOut);
  1830. err.write(Constants.encode(JGitText.get().internalServerError));
  1831. err.flush();
  1832. return true;
  1833. } catch (Throwable cannotReport) {
  1834. // Ignore the reason. This is a secondary failure.
  1835. return false;
  1836. }
  1837. }
  1838. /**
  1839. * Send the requested objects to the client.
  1840. *
  1841. * @param sideband
  1842. * whether to wrap the pack in side-band pkt-lines, interleaved
  1843. * with progress messages and errors.
  1844. * @param req
  1845. * request being processed
  1846. * @param accumulator
  1847. * where to write statistics about the content of the pack.
  1848. * @param allTags
  1849. * refs to search for annotated tags to include in the pack if
  1850. * the {@link #OPTION_INCLUDE_TAG} capability was requested.
  1851. * @param unshallowCommits
  1852. * shallow commits on the client that are now becoming unshallow
  1853. * @param deepenNots
  1854. * objects that the client specified using --shallow-exclude
  1855. * @throws IOException
  1856. * if an error occurred while generating or writing the pack.
  1857. */
  1858. private void sendPack(final boolean sideband,
  1859. FetchRequest req,
  1860. PackStatistics.Accumulator accumulator,
  1861. @Nullable Collection<Ref> allTags,
  1862. List<ObjectId> unshallowCommits,
  1863. List<ObjectId> deepenNots) throws IOException {
  1864. ProgressMonitor pm = NullProgressMonitor.INSTANCE;
  1865. OutputStream packOut = rawOut;
  1866. if (sideband) {
  1867. int bufsz = SideBandOutputStream.SMALL_BUF;
  1868. if (req.getClientCapabilities().contains(OPTION_SIDE_BAND_64K))
  1869. bufsz = SideBandOutputStream.MAX_BUF;
  1870. packOut = new SideBandOutputStream(SideBandOutputStream.CH_DATA,
  1871. bufsz, rawOut);
  1872. if (!req.getClientCapabilities().contains(OPTION_NO_PROGRESS)) {
  1873. msgOut = new SideBandOutputStream(
  1874. SideBandOutputStream.CH_PROGRESS, bufsz, rawOut);
  1875. pm = new SideBandProgressMonitor(msgOut);
  1876. }
  1877. }
  1878. try {
  1879. if (wantAll.isEmpty()) {
  1880. preUploadHook.onSendPack(this, wantIds, commonBase);
  1881. } else {
  1882. preUploadHook.onSendPack(this, wantAll, commonBase);
  1883. }
  1884. msgOut.flush();
  1885. } catch (ServiceMayNotContinueException noPack) {
  1886. if (sideband && noPack.getMessage() != null) {
  1887. noPack.setOutput();
  1888. @SuppressWarnings("resource" /* java 7 */)
  1889. SideBandOutputStream err = new SideBandOutputStream(
  1890. SideBandOutputStream.CH_ERROR,
  1891. SideBandOutputStream.SMALL_BUF, rawOut);
  1892. err.write(Constants.encode(noPack.getMessage()));
  1893. err.flush();
  1894. }
  1895. throw noPack;
  1896. }
  1897. PackConfig cfg = packConfig;
  1898. if (cfg == null)
  1899. cfg = new PackConfig(db);
  1900. @SuppressWarnings("resource") // PackWriter is referenced in the finally
  1901. // block, and is closed there
  1902. final PackWriter pw = new PackWriter(cfg, walk.getObjectReader(),
  1903. accumulator);
  1904. try {
  1905. pw.setIndexDisabled(true);
  1906. if (req.getFilterSpec().isNoOp()) {
  1907. pw.setUseCachedPacks(true);
  1908. } else {
  1909. pw.setFilterBlobLimit(req.getFilterSpec().getBlobLimit());
  1910. pw.setUseCachedPacks(false);
  1911. }
  1912. pw.setUseBitmaps(
  1913. req.getDepth() == 0
  1914. && req.getClientShallowCommits().isEmpty());
  1915. pw.setClientShallowCommits(req.getClientShallowCommits());
  1916. pw.setReuseDeltaCommits(true);
  1917. pw.setDeltaBaseAsOffset(
  1918. req.getClientCapabilities().contains(OPTION_OFS_DELTA));
  1919. pw.setThin(req.getClientCapabilities().contains(OPTION_THIN_PACK));
  1920. pw.setReuseValidatingObjects(false);
  1921. // Objects named directly by references go at the beginning
  1922. // of the pack.
  1923. if (commonBase.isEmpty() && refs != null) {
  1924. Set<ObjectId> tagTargets = new HashSet<>();
  1925. for (Ref ref : refs.values()) {
  1926. if (ref.getPeeledObjectId() != null)
  1927. tagTargets.add(ref.getPeeledObjectId());
  1928. else if (ref.getObjectId() == null)
  1929. continue;
  1930. else if (ref.getName().startsWith(Constants.R_HEADS))
  1931. tagTargets.add(ref.getObjectId());
  1932. }
  1933. pw.setTagTargets(tagTargets);
  1934. }
  1935. RevWalk rw = walk;
  1936. if (req.getDepth() > 0 || req.getDeepenSince() != 0 || !deepenNots.isEmpty()) {
  1937. int walkDepth = req.getDepth() == 0 ? Integer.MAX_VALUE
  1938. : req.getDepth() - 1;
  1939. pw.setShallowPack(req.getDepth(), unshallowCommits);
  1940. @SuppressWarnings("resource") // Ownership is transferred below
  1941. DepthWalk.RevWalk dw = new DepthWalk.RevWalk(
  1942. walk.getObjectReader(), walkDepth);
  1943. dw.setDeepenSince(req.getDeepenSince());
  1944. dw.setDeepenNots(deepenNots);
  1945. dw.assumeShallow(req.getClientShallowCommits());
  1946. rw = dw;
  1947. }
  1948. if (wantAll.isEmpty()) {
  1949. pw.preparePack(pm, wantIds, commonBase,
  1950. req.getClientShallowCommits());
  1951. } else {
  1952. walk.reset();
  1953. ObjectWalk ow = rw.toObjectWalkWithSameObjects();
  1954. pw.preparePack(pm, ow, wantAll, commonBase, PackWriter.NONE);
  1955. rw = ow;
  1956. }
  1957. if (req.getClientCapabilities().contains(OPTION_INCLUDE_TAG)
  1958. && allTags != null) {
  1959. for (Ref ref : allTags) {
  1960. ObjectId objectId = ref.getObjectId();
  1961. if (objectId == null) {
  1962. // skip unborn branch
  1963. continue;
  1964. }
  1965. // If the object was already requested, skip it.
  1966. if (wantAll.isEmpty()) {
  1967. if (wantIds.contains(objectId))
  1968. continue;
  1969. } else {
  1970. RevObject obj = rw.lookupOrNull(objectId);
  1971. if (obj != null && obj.has(WANT))
  1972. continue;
  1973. }
  1974. if (!ref.isPeeled())
  1975. ref = db.getRefDatabase().peel(ref);
  1976. ObjectId peeledId = ref.getPeeledObjectId();
  1977. objectId = ref.getObjectId();
  1978. if (peeledId == null || objectId == null)
  1979. continue;
  1980. if (pw.willInclude(peeledId) && !pw.willInclude(objectId)) {
  1981. pw.addObject(rw.parseAny(objectId));
  1982. }
  1983. }
  1984. }
  1985. pw.writePack(pm, NullProgressMonitor.INSTANCE, packOut);
  1986. if (msgOut != NullOutputStream.INSTANCE) {
  1987. String msg = pw.getStatistics().getMessage() + '\n';
  1988. msgOut.write(Constants.encode(msg));
  1989. msgOut.flush();
  1990. }
  1991. } finally {
  1992. statistics = pw.getStatistics();
  1993. if (statistics != null) {
  1994. postUploadHook.onPostUpload(statistics);
  1995. }
  1996. pw.close();
  1997. }
  1998. if (sideband)
  1999. pckOut.end();
  2000. }
  2001. private static void findSymrefs(
  2002. final RefAdvertiser adv, final Map<String, Ref> refs) {
  2003. Ref head = refs.get(Constants.HEAD);
  2004. if (head != null && head.isSymbolic()) {
  2005. adv.addSymref(Constants.HEAD, head.getLeaf().getName());
  2006. }
  2007. }
  2008. private static class ResponseBufferedOutputStream extends OutputStream {
  2009. private final OutputStream rawOut;
  2010. private OutputStream out;
  2011. ResponseBufferedOutputStream(OutputStream rawOut) {
  2012. this.rawOut = rawOut;
  2013. this.out = new ByteArrayOutputStream();
  2014. }
  2015. @Override
  2016. public void write(int b) throws IOException {
  2017. out.write(b);
  2018. }
  2019. @Override
  2020. public void write(byte b[]) throws IOException {
  2021. out.write(b);
  2022. }
  2023. @Override
  2024. public void write(byte b[], int off, int len) throws IOException {
  2025. out.write(b, off, len);
  2026. }
  2027. @Override
  2028. public void flush() throws IOException {
  2029. out.flush();
  2030. }
  2031. @Override
  2032. public void close() throws IOException {
  2033. out.close();
  2034. }
  2035. void stopBuffering() throws IOException {
  2036. if (out != rawOut) {
  2037. ((ByteArrayOutputStream) out).writeTo(rawOut);
  2038. out = rawOut;
  2039. }
  2040. }
  2041. }
  2042. }