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

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