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

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