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

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