Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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