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

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