You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UploadPack.java 69KB

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