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

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