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.

ReceivePack.java 67KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292
  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.nio.charset.StandardCharsets.UTF_8;
  45. import static org.eclipse.jgit.lib.Constants.HEAD;
  46. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_ATOMIC;
  47. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_DELETE_REFS;
  48. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_OFS_DELTA;
  49. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_PUSH_OPTIONS;
  50. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_QUIET;
  51. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_REPORT_STATUS;
  52. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_SIDE_BAND_64K;
  53. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_AGENT;
  54. import static org.eclipse.jgit.transport.SideBandOutputStream.CH_DATA;
  55. import static org.eclipse.jgit.transport.SideBandOutputStream.CH_ERROR;
  56. import static org.eclipse.jgit.transport.SideBandOutputStream.CH_PROGRESS;
  57. import static org.eclipse.jgit.transport.SideBandOutputStream.MAX_BUF;
  58. import java.io.EOFException;
  59. import java.io.IOException;
  60. import java.io.InputStream;
  61. import java.io.OutputStream;
  62. import java.text.MessageFormat;
  63. import java.util.ArrayList;
  64. import java.util.Collections;
  65. import java.util.HashSet;
  66. import java.util.List;
  67. import java.util.Map;
  68. import java.util.Set;
  69. import java.util.concurrent.TimeUnit;
  70. import org.eclipse.jgit.annotations.Nullable;
  71. import org.eclipse.jgit.errors.InvalidObjectIdException;
  72. import org.eclipse.jgit.errors.LargeObjectException;
  73. import org.eclipse.jgit.errors.MissingObjectException;
  74. import org.eclipse.jgit.errors.PackProtocolException;
  75. import org.eclipse.jgit.errors.TooLargePackException;
  76. import org.eclipse.jgit.errors.UnpackException;
  77. import org.eclipse.jgit.internal.JGitText;
  78. import org.eclipse.jgit.internal.storage.file.PackLock;
  79. import org.eclipse.jgit.internal.submodule.SubmoduleValidator;
  80. import org.eclipse.jgit.internal.submodule.SubmoduleValidator.SubmoduleValidationException;
  81. import org.eclipse.jgit.internal.transport.parser.FirstCommand;
  82. import org.eclipse.jgit.lib.AnyObjectId;
  83. import org.eclipse.jgit.lib.BatchRefUpdate;
  84. import org.eclipse.jgit.lib.Config;
  85. import org.eclipse.jgit.lib.ConfigConstants;
  86. import org.eclipse.jgit.lib.Constants;
  87. import org.eclipse.jgit.lib.GitmoduleEntry;
  88. import org.eclipse.jgit.lib.NullProgressMonitor;
  89. import org.eclipse.jgit.lib.ObjectChecker;
  90. import org.eclipse.jgit.lib.ObjectDatabase;
  91. import org.eclipse.jgit.lib.ObjectId;
  92. import org.eclipse.jgit.lib.ObjectIdSubclassMap;
  93. import org.eclipse.jgit.lib.ObjectInserter;
  94. import org.eclipse.jgit.lib.ObjectLoader;
  95. import org.eclipse.jgit.lib.PersonIdent;
  96. import org.eclipse.jgit.lib.ProgressMonitor;
  97. import org.eclipse.jgit.lib.Ref;
  98. import org.eclipse.jgit.lib.Repository;
  99. import org.eclipse.jgit.revwalk.ObjectWalk;
  100. import org.eclipse.jgit.revwalk.RevBlob;
  101. import org.eclipse.jgit.revwalk.RevCommit;
  102. import org.eclipse.jgit.revwalk.RevFlag;
  103. import org.eclipse.jgit.revwalk.RevObject;
  104. import org.eclipse.jgit.revwalk.RevSort;
  105. import org.eclipse.jgit.revwalk.RevTree;
  106. import org.eclipse.jgit.revwalk.RevWalk;
  107. import org.eclipse.jgit.transport.PacketLineIn.InputOverLimitIOException;
  108. import org.eclipse.jgit.transport.ReceiveCommand.Result;
  109. import org.eclipse.jgit.transport.RefAdvertiser.PacketLineOutRefAdvertiser;
  110. import org.eclipse.jgit.util.io.InterruptTimer;
  111. import org.eclipse.jgit.util.io.LimitedInputStream;
  112. import org.eclipse.jgit.util.io.TimeoutInputStream;
  113. import org.eclipse.jgit.util.io.TimeoutOutputStream;
  114. /**
  115. * Implements the server side of a push connection, receiving objects.
  116. */
  117. public class ReceivePack {
  118. /**
  119. * Data in the first line of a request, the line itself plus capabilities.
  120. *
  121. * @deprecated Use {@link FirstCommand} instead.
  122. * @since 5.6
  123. */
  124. @Deprecated
  125. public static class FirstLine {
  126. private final FirstCommand command;
  127. /**
  128. * Parse the first line of a receive-pack request.
  129. *
  130. * @param line
  131. * line from the client.
  132. */
  133. public FirstLine(String line) {
  134. command = FirstCommand.fromLine(line);
  135. }
  136. /** @return non-capabilities part of the line. */
  137. public String getLine() {
  138. return command.getLine();
  139. }
  140. /** @return capabilities parsed from the line. */
  141. public Set<String> getCapabilities() {
  142. return command.getCapabilities();
  143. }
  144. }
  145. /** Database we write the stored objects into. */
  146. private final Repository db;
  147. /** Revision traversal support over {@link #db}. */
  148. private final RevWalk walk;
  149. /**
  150. * Is the client connection a bi-directional socket or pipe?
  151. * <p>
  152. * If true, this class assumes it can perform multiple read and write cycles
  153. * with the client over the input and output streams. This matches the
  154. * functionality available with a standard TCP/IP connection, or a local
  155. * operating system or in-memory pipe.
  156. * <p>
  157. * If false, this class runs in a read everything then output results mode,
  158. * making it suitable for single round-trip systems RPCs such as HTTP.
  159. */
  160. private boolean biDirectionalPipe = true;
  161. /** Expecting data after the pack footer */
  162. private boolean expectDataAfterPackFooter;
  163. /** Should an incoming transfer validate objects? */
  164. private ObjectChecker objectChecker;
  165. /** Should an incoming transfer permit create requests? */
  166. private boolean allowCreates;
  167. /** Should an incoming transfer permit delete requests? */
  168. private boolean allowAnyDeletes;
  169. private boolean allowBranchDeletes;
  170. /** Should an incoming transfer permit non-fast-forward requests? */
  171. private boolean allowNonFastForwards;
  172. /** Should an incoming transfer permit push options? **/
  173. private boolean allowPushOptions;
  174. /**
  175. * Should the requested ref updates be performed as a single atomic
  176. * transaction?
  177. */
  178. private boolean atomic;
  179. private boolean allowOfsDelta;
  180. private boolean allowQuiet = true;
  181. /** Identity to record action as within the reflog. */
  182. private PersonIdent refLogIdent;
  183. /** Hook used while advertising the refs to the client. */
  184. private AdvertiseRefsHook advertiseRefsHook;
  185. /** Filter used while advertising the refs to the client. */
  186. private RefFilter refFilter;
  187. /** Timeout in seconds to wait for client interaction. */
  188. private int timeout;
  189. /** Timer to manage {@link #timeout}. */
  190. private InterruptTimer timer;
  191. private TimeoutInputStream timeoutIn;
  192. // Original stream passed to init(), since rawOut may be wrapped in a
  193. // sideband.
  194. private OutputStream origOut;
  195. /** Raw input stream. */
  196. private InputStream rawIn;
  197. /** Raw output stream. */
  198. private OutputStream rawOut;
  199. /** Optional message output stream. */
  200. private OutputStream msgOut;
  201. private SideBandOutputStream errOut;
  202. /** Packet line input stream around {@link #rawIn}. */
  203. private PacketLineIn pckIn;
  204. /** Packet line output stream around {@link #rawOut}. */
  205. private PacketLineOut pckOut;
  206. private final MessageOutputWrapper msgOutWrapper = new MessageOutputWrapper();
  207. private PackParser parser;
  208. /** The refs we advertised as existing at the start of the connection. */
  209. private Map<String, Ref> refs;
  210. /** All SHA-1s shown to the client, which can be possible edges. */
  211. private Set<ObjectId> advertisedHaves;
  212. /** Capabilities requested by the client. */
  213. private Set<String> enabledCapabilities;
  214. String userAgent;
  215. private Set<ObjectId> clientShallowCommits;
  216. private List<ReceiveCommand> commands;
  217. private long maxCommandBytes;
  218. private long maxDiscardBytes;
  219. private StringBuilder advertiseError;
  220. /**
  221. * If {@link BasePackPushConnection#CAPABILITY_SIDE_BAND_64K} is enabled.
  222. */
  223. private boolean sideBand;
  224. private boolean quiet;
  225. /** Lock around the received pack file, while updating refs. */
  226. private PackLock packLock;
  227. private boolean checkReferencedIsReachable;
  228. /** Git object size limit */
  229. private long maxObjectSizeLimit;
  230. /** Total pack size limit */
  231. private long maxPackSizeLimit = -1;
  232. /** The size of the received pack, including index size */
  233. private Long packSize;
  234. private PushCertificateParser pushCertificateParser;
  235. private SignedPushConfig signedPushConfig;
  236. private PushCertificate pushCert;
  237. private ReceivedPackStatistics stats;
  238. /** Hook to validate the update commands before execution. */
  239. private PreReceiveHook preReceive;
  240. private ReceiveCommandErrorHandler receiveCommandErrorHandler = new ReceiveCommandErrorHandler() {
  241. // Use the default implementation.
  242. };
  243. /** Hook to report on the commands after execution. */
  244. private PostReceiveHook postReceive;
  245. /** If {@link BasePackPushConnection#CAPABILITY_REPORT_STATUS} is enabled. */
  246. private boolean reportStatus;
  247. /** Whether the client intends to use push options. */
  248. private boolean usePushOptions;
  249. private List<String> pushOptions;
  250. /**
  251. * Create a new pack receive for an open repository.
  252. *
  253. * @param into
  254. * the destination repository.
  255. */
  256. public ReceivePack(Repository into) {
  257. db = into;
  258. walk = new RevWalk(db);
  259. walk.setRetainBody(false);
  260. TransferConfig tc = db.getConfig().get(TransferConfig.KEY);
  261. objectChecker = tc.newReceiveObjectChecker();
  262. ReceiveConfig rc = db.getConfig().get(ReceiveConfig::new);
  263. allowCreates = rc.allowCreates;
  264. allowAnyDeletes = true;
  265. allowBranchDeletes = rc.allowDeletes;
  266. allowNonFastForwards = rc.allowNonFastForwards;
  267. allowOfsDelta = rc.allowOfsDelta;
  268. allowPushOptions = rc.allowPushOptions;
  269. maxCommandBytes = rc.maxCommandBytes;
  270. maxDiscardBytes = rc.maxDiscardBytes;
  271. advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  272. refFilter = RefFilter.DEFAULT;
  273. advertisedHaves = new HashSet<>();
  274. clientShallowCommits = new HashSet<>();
  275. signedPushConfig = rc.signedPush;
  276. preReceive = PreReceiveHook.NULL;
  277. postReceive = PostReceiveHook.NULL;
  278. }
  279. /** Configuration for receive operations. */
  280. private static class ReceiveConfig {
  281. final boolean allowCreates;
  282. final boolean allowDeletes;
  283. final boolean allowNonFastForwards;
  284. final boolean allowOfsDelta;
  285. final boolean allowPushOptions;
  286. final long maxCommandBytes;
  287. final long maxDiscardBytes;
  288. final SignedPushConfig signedPush;
  289. ReceiveConfig(Config config) {
  290. allowCreates = true;
  291. allowDeletes = !config.getBoolean("receive", "denydeletes", false); //$NON-NLS-1$ //$NON-NLS-2$
  292. allowNonFastForwards = !config.getBoolean("receive", //$NON-NLS-1$
  293. "denynonfastforwards", false); //$NON-NLS-1$
  294. allowOfsDelta = config.getBoolean("repack", "usedeltabaseoffset", //$NON-NLS-1$ //$NON-NLS-2$
  295. true);
  296. allowPushOptions = config.getBoolean("receive", "pushoptions", //$NON-NLS-1$ //$NON-NLS-2$
  297. false);
  298. maxCommandBytes = config.getLong("receive", //$NON-NLS-1$
  299. "maxCommandBytes", //$NON-NLS-1$
  300. 3 << 20);
  301. maxDiscardBytes = config.getLong("receive", //$NON-NLS-1$
  302. "maxCommandDiscardBytes", //$NON-NLS-1$
  303. -1);
  304. signedPush = SignedPushConfig.KEY.parse(config);
  305. }
  306. }
  307. /**
  308. * Output stream that wraps the current {@link #msgOut}.
  309. * <p>
  310. * We don't want to expose {@link #msgOut} directly because it can change
  311. * several times over the course of a session.
  312. */
  313. class MessageOutputWrapper extends OutputStream {
  314. @Override
  315. public void write(int ch) {
  316. if (msgOut != null) {
  317. try {
  318. msgOut.write(ch);
  319. } catch (IOException e) {
  320. // Ignore write failures.
  321. }
  322. }
  323. }
  324. @Override
  325. public void write(byte[] b, int off, int len) {
  326. if (msgOut != null) {
  327. try {
  328. msgOut.write(b, off, len);
  329. } catch (IOException e) {
  330. // Ignore write failures.
  331. }
  332. }
  333. }
  334. @Override
  335. public void write(byte[] b) {
  336. write(b, 0, b.length);
  337. }
  338. @Override
  339. public void flush() {
  340. if (msgOut != null) {
  341. try {
  342. msgOut.flush();
  343. } catch (IOException e) {
  344. // Ignore write failures.
  345. }
  346. }
  347. }
  348. }
  349. /**
  350. * Get the repository this receive completes into.
  351. *
  352. * @return the repository this receive completes into.
  353. */
  354. public Repository getRepository() {
  355. return db;
  356. }
  357. /**
  358. * Get the RevWalk instance used by this connection.
  359. *
  360. * @return the RevWalk instance used by this connection.
  361. */
  362. public RevWalk getRevWalk() {
  363. return walk;
  364. }
  365. /**
  366. * Get refs which were advertised to the client.
  367. *
  368. * @return all refs which were advertised to the client, or null if
  369. * {@link #setAdvertisedRefs(Map, Set)} has not been called yet.
  370. */
  371. public Map<String, Ref> getAdvertisedRefs() {
  372. return refs;
  373. }
  374. /**
  375. * Set the refs advertised by this ReceivePack.
  376. * <p>
  377. * Intended to be called from a
  378. * {@link org.eclipse.jgit.transport.PreReceiveHook}.
  379. *
  380. * @param allRefs
  381. * explicit set of references to claim as advertised by this
  382. * ReceivePack instance. This overrides any references that may
  383. * exist in the source repository. The map is passed to the
  384. * configured {@link #getRefFilter()}. If null, assumes all refs
  385. * were advertised.
  386. * @param additionalHaves
  387. * explicit set of additional haves to claim as advertised. If
  388. * null, assumes the default set of additional haves from the
  389. * repository.
  390. */
  391. public void setAdvertisedRefs(Map<String, Ref> allRefs,
  392. Set<ObjectId> additionalHaves) {
  393. refs = allRefs != null ? allRefs : db.getAllRefs();
  394. refs = refFilter.filter(refs);
  395. advertisedHaves.clear();
  396. Ref head = refs.get(HEAD);
  397. if (head != null && head.isSymbolic()) {
  398. refs.remove(HEAD);
  399. }
  400. for (Ref ref : refs.values()) {
  401. if (ref.getObjectId() != null) {
  402. advertisedHaves.add(ref.getObjectId());
  403. }
  404. }
  405. if (additionalHaves != null) {
  406. advertisedHaves.addAll(additionalHaves);
  407. } else {
  408. advertisedHaves.addAll(db.getAdditionalHaves());
  409. }
  410. }
  411. /**
  412. * Get objects advertised to the client.
  413. *
  414. * @return the set of objects advertised to the as present in this
  415. * repository, or null if {@link #setAdvertisedRefs(Map, Set)} has
  416. * not been called yet.
  417. */
  418. public final Set<ObjectId> getAdvertisedObjects() {
  419. return advertisedHaves;
  420. }
  421. /**
  422. * Whether this instance will validate all referenced, but not supplied by
  423. * the client, objects are reachable from another reference.
  424. *
  425. * @return true if this instance will validate all referenced, but not
  426. * supplied by the client, objects are reachable from another
  427. * reference.
  428. */
  429. public boolean isCheckReferencedObjectsAreReachable() {
  430. return checkReferencedIsReachable;
  431. }
  432. /**
  433. * Validate all referenced but not supplied objects are reachable.
  434. * <p>
  435. * If enabled, this instance will verify that references to objects not
  436. * contained within the received pack are already reachable through at least
  437. * one other reference displayed as part of {@link #getAdvertisedRefs()}.
  438. * <p>
  439. * This feature is useful when the application doesn't trust the client to
  440. * not provide a forged SHA-1 reference to an object, in an attempt to
  441. * access parts of the DAG that they aren't allowed to see and which have
  442. * been hidden from them via the configured
  443. * {@link org.eclipse.jgit.transport.AdvertiseRefsHook} or
  444. * {@link org.eclipse.jgit.transport.RefFilter}.
  445. * <p>
  446. * Enabling this feature may imply at least some, if not all, of the same
  447. * functionality performed by {@link #setCheckReceivedObjects(boolean)}.
  448. * Applications are encouraged to enable both features, if desired.
  449. *
  450. * @param b
  451. * {@code true} to enable the additional check.
  452. */
  453. public void setCheckReferencedObjectsAreReachable(boolean b) {
  454. this.checkReferencedIsReachable = b;
  455. }
  456. /**
  457. * Whether this class expects a bi-directional pipe opened between the
  458. * client and itself.
  459. *
  460. * @return true if this class expects a bi-directional pipe opened between
  461. * the client and itself. The default is true.
  462. */
  463. public boolean isBiDirectionalPipe() {
  464. return biDirectionalPipe;
  465. }
  466. /**
  467. * Whether this class will assume the socket is a fully bidirectional pipe
  468. * between the two peers and takes advantage of that by first transmitting
  469. * the known refs, then waiting to read commands.
  470. *
  471. * @param twoWay
  472. * if true, this class will assume the socket is a fully
  473. * bidirectional pipe between the two peers and takes advantage
  474. * of that by first transmitting the known refs, then waiting to
  475. * read commands. If false, this class assumes it must read the
  476. * commands before writing output and does not perform the
  477. * initial advertising.
  478. */
  479. public void setBiDirectionalPipe(boolean twoWay) {
  480. biDirectionalPipe = twoWay;
  481. }
  482. /**
  483. * Whether there is data expected after the pack footer.
  484. *
  485. * @return {@code true} if there is data expected after the pack footer.
  486. */
  487. public boolean isExpectDataAfterPackFooter() {
  488. return expectDataAfterPackFooter;
  489. }
  490. /**
  491. * Whether there is additional data in InputStream after pack.
  492. *
  493. * @param e
  494. * {@code true} if there is additional data in InputStream after
  495. * pack.
  496. */
  497. public void setExpectDataAfterPackFooter(boolean e) {
  498. expectDataAfterPackFooter = e;
  499. }
  500. /**
  501. * Whether this instance will verify received objects are formatted
  502. * correctly.
  503. *
  504. * @return {@code true} if this instance will verify received objects are
  505. * formatted correctly. Validating objects requires more CPU time on
  506. * this side of the connection.
  507. */
  508. public boolean isCheckReceivedObjects() {
  509. return objectChecker != null;
  510. }
  511. /**
  512. * Whether to enable checking received objects
  513. *
  514. * @param check
  515. * {@code true} to enable checking received objects; false to
  516. * assume all received objects are valid.
  517. * @see #setObjectChecker(ObjectChecker)
  518. */
  519. public void setCheckReceivedObjects(boolean check) {
  520. if (check && objectChecker == null)
  521. setObjectChecker(new ObjectChecker());
  522. else if (!check && objectChecker != null)
  523. setObjectChecker(null);
  524. }
  525. /**
  526. * Set the object checking instance to verify each received object with
  527. *
  528. * @param impl
  529. * if non-null the object checking instance to verify each
  530. * received object with; null to disable object checking.
  531. * @since 3.4
  532. */
  533. public void setObjectChecker(ObjectChecker impl) {
  534. objectChecker = impl;
  535. }
  536. /**
  537. * Whether the client can request refs to be created.
  538. *
  539. * @return {@code true} if the client can request refs to be created.
  540. */
  541. public boolean isAllowCreates() {
  542. return allowCreates;
  543. }
  544. /**
  545. * Whether to permit create ref commands to be processed.
  546. *
  547. * @param canCreate
  548. * {@code true} to permit create ref commands to be processed.
  549. */
  550. public void setAllowCreates(boolean canCreate) {
  551. allowCreates = canCreate;
  552. }
  553. /**
  554. * Whether the client can request refs to be deleted.
  555. *
  556. * @return {@code true} if the client can request refs to be deleted.
  557. */
  558. public boolean isAllowDeletes() {
  559. return allowAnyDeletes;
  560. }
  561. /**
  562. * Whether to permit delete ref commands to be processed.
  563. *
  564. * @param canDelete
  565. * {@code true} to permit delete ref commands to be processed.
  566. */
  567. public void setAllowDeletes(boolean canDelete) {
  568. allowAnyDeletes = canDelete;
  569. }
  570. /**
  571. * Whether the client can delete from {@code refs/heads/}.
  572. *
  573. * @return {@code true} if the client can delete from {@code refs/heads/}.
  574. * @since 3.6
  575. */
  576. public boolean isAllowBranchDeletes() {
  577. return allowBranchDeletes;
  578. }
  579. /**
  580. * Configure whether to permit deletion of branches from the
  581. * {@code refs/heads/} namespace.
  582. *
  583. * @param canDelete
  584. * {@code true} to permit deletion of branches from the
  585. * {@code refs/heads/} namespace.
  586. * @since 3.6
  587. */
  588. public void setAllowBranchDeletes(boolean canDelete) {
  589. allowBranchDeletes = canDelete;
  590. }
  591. /**
  592. * Whether the client can request non-fast-forward updates of a ref,
  593. * possibly making objects unreachable.
  594. *
  595. * @return {@code true} if the client can request non-fast-forward updates
  596. * of a ref, possibly making objects unreachable.
  597. */
  598. public boolean isAllowNonFastForwards() {
  599. return allowNonFastForwards;
  600. }
  601. /**
  602. * Configure whether to permit the client to ask for non-fast-forward
  603. * updates of an existing ref.
  604. *
  605. * @param canRewind
  606. * {@code true} to permit the client to ask for non-fast-forward
  607. * updates of an existing ref.
  608. */
  609. public void setAllowNonFastForwards(boolean canRewind) {
  610. allowNonFastForwards = canRewind;
  611. }
  612. /**
  613. * Whether the client's commands should be performed as a single atomic
  614. * transaction.
  615. *
  616. * @return {@code true} if the client's commands should be performed as a
  617. * single atomic transaction.
  618. * @since 4.4
  619. */
  620. public boolean isAtomic() {
  621. return atomic;
  622. }
  623. /**
  624. * Configure whether to perform the client's commands as a single atomic
  625. * transaction.
  626. *
  627. * @param atomic
  628. * {@code true} to perform the client's commands as a single
  629. * atomic transaction.
  630. * @since 4.4
  631. */
  632. public void setAtomic(boolean atomic) {
  633. this.atomic = atomic;
  634. }
  635. /**
  636. * Get identity of the user making the changes in the reflog.
  637. *
  638. * @return identity of the user making the changes in the reflog.
  639. */
  640. public PersonIdent getRefLogIdent() {
  641. return refLogIdent;
  642. }
  643. /**
  644. * Set the identity of the user appearing in the affected reflogs.
  645. * <p>
  646. * The timestamp portion of the identity is ignored. A new identity with the
  647. * current timestamp will be created automatically when the updates occur
  648. * and the log records are written.
  649. *
  650. * @param pi
  651. * identity of the user. If null the identity will be
  652. * automatically determined based on the repository
  653. * configuration.
  654. */
  655. public void setRefLogIdent(PersonIdent pi) {
  656. refLogIdent = pi;
  657. }
  658. /**
  659. * Get the hook used while advertising the refs to the client
  660. *
  661. * @return the hook used while advertising the refs to the client
  662. */
  663. public AdvertiseRefsHook getAdvertiseRefsHook() {
  664. return advertiseRefsHook;
  665. }
  666. /**
  667. * Get the filter used while advertising the refs to the client
  668. *
  669. * @return the filter used while advertising the refs to the client
  670. */
  671. public RefFilter getRefFilter() {
  672. return refFilter;
  673. }
  674. /**
  675. * Set the hook used while advertising the refs to the client.
  676. * <p>
  677. * If the {@link org.eclipse.jgit.transport.AdvertiseRefsHook} chooses to
  678. * call {@link #setAdvertisedRefs(Map,Set)}, only refs set by this hook
  679. * <em>and</em> selected by the {@link org.eclipse.jgit.transport.RefFilter}
  680. * will be shown to the client. Clients may still attempt to create or
  681. * update a reference not advertised by the configured
  682. * {@link org.eclipse.jgit.transport.AdvertiseRefsHook}. These attempts
  683. * should be rejected by a matching
  684. * {@link org.eclipse.jgit.transport.PreReceiveHook}.
  685. *
  686. * @param advertiseRefsHook
  687. * the hook; may be null to show all refs.
  688. */
  689. public void setAdvertiseRefsHook(AdvertiseRefsHook advertiseRefsHook) {
  690. if (advertiseRefsHook != null)
  691. this.advertiseRefsHook = advertiseRefsHook;
  692. else
  693. this.advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  694. }
  695. /**
  696. * Set the filter used while advertising the refs to the client.
  697. * <p>
  698. * Only refs allowed by this filter will be shown to the client. The filter
  699. * is run against the refs specified by the
  700. * {@link org.eclipse.jgit.transport.AdvertiseRefsHook} (if applicable).
  701. *
  702. * @param refFilter
  703. * the filter; may be null to show all refs.
  704. */
  705. public void setRefFilter(RefFilter refFilter) {
  706. this.refFilter = refFilter != null ? refFilter : RefFilter.DEFAULT;
  707. }
  708. /**
  709. * Get timeout (in seconds) before aborting an IO operation.
  710. *
  711. * @return timeout (in seconds) before aborting an IO operation.
  712. */
  713. public int getTimeout() {
  714. return timeout;
  715. }
  716. /**
  717. * Set the timeout before willing to abort an IO call.
  718. *
  719. * @param seconds
  720. * number of seconds to wait (with no data transfer occurring)
  721. * before aborting an IO read or write operation with the
  722. * connected client.
  723. */
  724. public void setTimeout(int seconds) {
  725. timeout = seconds;
  726. }
  727. /**
  728. * Set the maximum number of command bytes to read from the client.
  729. *
  730. * @param limit
  731. * command limit in bytes; if 0 there is no limit.
  732. * @since 4.7
  733. */
  734. public void setMaxCommandBytes(long limit) {
  735. maxCommandBytes = limit;
  736. }
  737. /**
  738. * Set the maximum number of command bytes to discard from the client.
  739. * <p>
  740. * Discarding remaining bytes allows this instance to consume the rest of
  741. * the command block and send a human readable over-limit error via the
  742. * side-band channel. If the client sends an excessive number of bytes this
  743. * limit kicks in and the instance disconnects, resulting in a non-specific
  744. * 'pipe closed', 'end of stream', or similar generic error at the client.
  745. * <p>
  746. * When the limit is set to {@code -1} the implementation will default to
  747. * the larger of {@code 3 * maxCommandBytes} or {@code 3 MiB}.
  748. *
  749. * @param limit
  750. * discard limit in bytes; if 0 there is no limit; if -1 the
  751. * implementation tries to set a reasonable default.
  752. * @since 4.7
  753. */
  754. public void setMaxCommandDiscardBytes(long limit) {
  755. maxDiscardBytes = limit;
  756. }
  757. /**
  758. * Set the maximum allowed Git object size.
  759. * <p>
  760. * If an object is larger than the given size the pack-parsing will throw an
  761. * exception aborting the receive-pack operation.
  762. *
  763. * @param limit
  764. * the Git object size limit. If zero then there is not limit.
  765. */
  766. public void setMaxObjectSizeLimit(long limit) {
  767. maxObjectSizeLimit = limit;
  768. }
  769. /**
  770. * Set the maximum allowed pack size.
  771. * <p>
  772. * A pack exceeding this size will be rejected.
  773. *
  774. * @param limit
  775. * the pack size limit, in bytes
  776. * @since 3.3
  777. */
  778. public void setMaxPackSizeLimit(long limit) {
  779. if (limit < 0)
  780. throw new IllegalArgumentException(
  781. MessageFormat.format(JGitText.get().receivePackInvalidLimit,
  782. Long.valueOf(limit)));
  783. maxPackSizeLimit = limit;
  784. }
  785. /**
  786. * Check whether the client expects a side-band stream.
  787. *
  788. * @return true if the client has advertised a side-band capability, false
  789. * otherwise.
  790. * @throws org.eclipse.jgit.transport.RequestNotYetReadException
  791. * if the client's request has not yet been read from the wire,
  792. * so we do not know if they expect side-band. Note that the
  793. * client may have already written the request, it just has not
  794. * been read.
  795. */
  796. public boolean isSideBand() throws RequestNotYetReadException {
  797. checkRequestWasRead();
  798. return enabledCapabilities.contains(CAPABILITY_SIDE_BAND_64K);
  799. }
  800. /**
  801. * Whether clients may request avoiding noisy progress messages.
  802. *
  803. * @return true if clients may request avoiding noisy progress messages.
  804. * @since 4.0
  805. */
  806. public boolean isAllowQuiet() {
  807. return allowQuiet;
  808. }
  809. /**
  810. * Configure if clients may request the server skip noisy messages.
  811. *
  812. * @param allow
  813. * true to allow clients to request quiet behavior; false to
  814. * refuse quiet behavior and send messages anyway. This may be
  815. * necessary if processing is slow and the client-server network
  816. * connection can timeout.
  817. * @since 4.0
  818. */
  819. public void setAllowQuiet(boolean allow) {
  820. allowQuiet = allow;
  821. }
  822. /**
  823. * Whether the server supports receiving push options.
  824. *
  825. * @return true if the server supports receiving push options.
  826. * @since 4.5
  827. */
  828. public boolean isAllowPushOptions() {
  829. return allowPushOptions;
  830. }
  831. /**
  832. * Configure if the server supports receiving push options.
  833. *
  834. * @param allow
  835. * true to optionally accept option strings from the client.
  836. * @since 4.5
  837. */
  838. public void setAllowPushOptions(boolean allow) {
  839. allowPushOptions = allow;
  840. }
  841. /**
  842. * True if the client wants less verbose output.
  843. *
  844. * @return true if the client has requested the server to be less verbose.
  845. * @throws org.eclipse.jgit.transport.RequestNotYetReadException
  846. * if the client's request has not yet been read from the wire,
  847. * so we do not know if they expect side-band. Note that the
  848. * client may have already written the request, it just has not
  849. * been read.
  850. * @since 4.0
  851. */
  852. public boolean isQuiet() throws RequestNotYetReadException {
  853. checkRequestWasRead();
  854. return quiet;
  855. }
  856. /**
  857. * Set the configuration for push certificate verification.
  858. *
  859. * @param cfg
  860. * new configuration; if this object is null or its
  861. * {@link SignedPushConfig#getCertNonceSeed()} is null, push
  862. * certificate verification will be disabled.
  863. * @since 4.1
  864. */
  865. public void setSignedPushConfig(SignedPushConfig cfg) {
  866. signedPushConfig = cfg;
  867. }
  868. private PushCertificateParser getPushCertificateParser() {
  869. if (pushCertificateParser == null) {
  870. pushCertificateParser = new PushCertificateParser(db,
  871. signedPushConfig);
  872. }
  873. return pushCertificateParser;
  874. }
  875. /**
  876. * Get the user agent of the client.
  877. * <p>
  878. * If the client is new enough to use {@code agent=} capability that value
  879. * will be returned. Older HTTP clients may also supply their version using
  880. * the HTTP {@code User-Agent} header. The capability overrides the HTTP
  881. * header if both are available.
  882. * <p>
  883. * When an HTTP request has been received this method returns the HTTP
  884. * {@code User-Agent} header value until capabilities have been parsed.
  885. *
  886. * @return user agent supplied by the client. Available only if the client
  887. * is new enough to advertise its user agent.
  888. * @since 4.0
  889. */
  890. public String getPeerUserAgent() {
  891. return UserAgent.getAgent(enabledCapabilities, userAgent);
  892. }
  893. /**
  894. * Get all of the command received by the current request.
  895. *
  896. * @return all of the command received by the current request.
  897. */
  898. public List<ReceiveCommand> getAllCommands() {
  899. return Collections.unmodifiableList(commands);
  900. }
  901. /**
  902. * Set an error handler for {@link ReceiveCommand}.
  903. *
  904. * @param receiveCommandErrorHandler
  905. * @since 5.7
  906. */
  907. public void setReceiveCommandErrorHandler(
  908. ReceiveCommandErrorHandler receiveCommandErrorHandler) {
  909. this.receiveCommandErrorHandler = receiveCommandErrorHandler;
  910. }
  911. /**
  912. * Send an error message to the client.
  913. * <p>
  914. * If any error messages are sent before the references are advertised to
  915. * the client, the errors will be sent instead of the advertisement and the
  916. * receive operation will be aborted. All clients should receive and display
  917. * such early stage errors.
  918. * <p>
  919. * If the reference advertisements have already been sent, messages are sent
  920. * in a side channel. If the client doesn't support receiving messages, the
  921. * message will be discarded, with no other indication to the caller or to
  922. * the client.
  923. * <p>
  924. * {@link org.eclipse.jgit.transport.PreReceiveHook}s should always try to
  925. * use
  926. * {@link org.eclipse.jgit.transport.ReceiveCommand#setResult(Result, String)}
  927. * with a result status of
  928. * {@link org.eclipse.jgit.transport.ReceiveCommand.Result#REJECTED_OTHER_REASON}
  929. * to indicate any reasons for rejecting an update. Messages attached to a
  930. * command are much more likely to be returned to the client.
  931. *
  932. * @param what
  933. * string describing the problem identified by the hook. The
  934. * string must not end with an LF, and must not contain an LF.
  935. */
  936. public void sendError(String what) {
  937. if (refs == null) {
  938. if (advertiseError == null)
  939. advertiseError = new StringBuilder();
  940. advertiseError.append(what).append('\n');
  941. } else {
  942. msgOutWrapper.write(Constants.encode("error: " + what + "\n")); //$NON-NLS-1$ //$NON-NLS-2$
  943. }
  944. }
  945. private void fatalError(String msg) {
  946. if (errOut != null) {
  947. try {
  948. errOut.write(Constants.encode(msg));
  949. errOut.flush();
  950. } catch (IOException e) {
  951. // Ignore write failures
  952. }
  953. } else {
  954. sendError(msg);
  955. }
  956. }
  957. /**
  958. * Send a message to the client, if it supports receiving them.
  959. * <p>
  960. * If the client doesn't support receiving messages, the message will be
  961. * discarded, with no other indication to the caller or to the client.
  962. *
  963. * @param what
  964. * string describing the problem identified by the hook. The
  965. * string must not end with an LF, and must not contain an LF.
  966. */
  967. public void sendMessage(String what) {
  968. msgOutWrapper.write(Constants.encode(what + "\n")); //$NON-NLS-1$
  969. }
  970. /**
  971. * Get an underlying stream for sending messages to the client.
  972. *
  973. * @return an underlying stream for sending messages to the client.
  974. */
  975. public OutputStream getMessageOutputStream() {
  976. return msgOutWrapper;
  977. }
  978. /**
  979. * Get whether or not a pack has been received.
  980. *
  981. * This can be called before calling {@link #getPackSize()} to avoid causing
  982. * {@code IllegalStateException} when the pack size was not set because no
  983. * pack was received.
  984. *
  985. * @return true if a pack has been received.
  986. * @since 5.6
  987. */
  988. public boolean hasReceivedPack() {
  989. return packSize != null;
  990. }
  991. /**
  992. * Get the size of the received pack file including the index size.
  993. *
  994. * This can only be called if the pack is already received.
  995. *
  996. * @return the size of the received pack including index size
  997. * @throws java.lang.IllegalStateException
  998. * if called before the pack has been received
  999. * @since 3.3
  1000. */
  1001. public long getPackSize() {
  1002. if (packSize != null)
  1003. return packSize.longValue();
  1004. throw new IllegalStateException(JGitText.get().packSizeNotSetYet);
  1005. }
  1006. /**
  1007. * Get the commits from the client's shallow file.
  1008. *
  1009. * @return if the client is a shallow repository, the list of edge commits
  1010. * that define the client's shallow boundary. Empty set if the
  1011. * client is earlier than Git 1.9, or is a full clone.
  1012. */
  1013. private Set<ObjectId> getClientShallowCommits() {
  1014. return clientShallowCommits;
  1015. }
  1016. /**
  1017. * Whether any commands to be executed have been read.
  1018. *
  1019. * @return {@code true} if any commands to be executed have been read.
  1020. */
  1021. private boolean hasCommands() {
  1022. return !commands.isEmpty();
  1023. }
  1024. /**
  1025. * Whether an error occurred that should be advertised.
  1026. *
  1027. * @return true if an error occurred that should be advertised.
  1028. */
  1029. private boolean hasError() {
  1030. return advertiseError != null;
  1031. }
  1032. /**
  1033. * Initialize the instance with the given streams.
  1034. *
  1035. * Visible for out-of-tree subclasses (e.g. tests that need to set the
  1036. * streams without going through the {@link #service()} method).
  1037. *
  1038. * @param input
  1039. * raw input to read client commands and pack data from. Caller
  1040. * must ensure the input is buffered, otherwise read performance
  1041. * may suffer.
  1042. * @param output
  1043. * response back to the Git network client. Caller must ensure
  1044. * the output is buffered, otherwise write performance may
  1045. * suffer.
  1046. * @param messages
  1047. * secondary "notice" channel to send additional messages out
  1048. * through. When run over SSH this should be tied back to the
  1049. * standard error channel of the command execution. For most
  1050. * other network connections this should be null.
  1051. */
  1052. protected void init(final InputStream input, final OutputStream output,
  1053. final OutputStream messages) {
  1054. origOut = output;
  1055. rawIn = input;
  1056. rawOut = output;
  1057. msgOut = messages;
  1058. if (timeout > 0) {
  1059. final Thread caller = Thread.currentThread();
  1060. timer = new InterruptTimer(caller.getName() + "-Timer"); //$NON-NLS-1$
  1061. timeoutIn = new TimeoutInputStream(rawIn, timer);
  1062. TimeoutOutputStream o = new TimeoutOutputStream(rawOut, timer);
  1063. timeoutIn.setTimeout(timeout * 1000);
  1064. o.setTimeout(timeout * 1000);
  1065. rawIn = timeoutIn;
  1066. rawOut = o;
  1067. }
  1068. pckIn = new PacketLineIn(rawIn);
  1069. pckOut = new PacketLineOut(rawOut);
  1070. pckOut.setFlushOnEnd(false);
  1071. enabledCapabilities = new HashSet<>();
  1072. commands = new ArrayList<>();
  1073. }
  1074. /**
  1075. * Get advertised refs, or the default if not explicitly advertised.
  1076. *
  1077. * @return advertised refs, or the default if not explicitly advertised.
  1078. */
  1079. private Map<String, Ref> getAdvertisedOrDefaultRefs() {
  1080. if (refs == null)
  1081. setAdvertisedRefs(null, null);
  1082. return refs;
  1083. }
  1084. /**
  1085. * Receive a pack from the stream and check connectivity if necessary.
  1086. *
  1087. * Visible for out-of-tree subclasses. Subclasses overriding this method
  1088. * should invoke this implementation, as it alters the instance state (e.g.
  1089. * it reads the pack from the input and parses it before running the
  1090. * connectivity checks).
  1091. *
  1092. * @throws java.io.IOException
  1093. * an error occurred during unpacking or connectivity checking.
  1094. * @throws LargeObjectException
  1095. * an large object needs to be opened for the check.
  1096. * @throws SubmoduleValidationException
  1097. * fails to validate the submodule.
  1098. */
  1099. protected void receivePackAndCheckConnectivity() throws IOException,
  1100. LargeObjectException, SubmoduleValidationException {
  1101. receivePack();
  1102. if (needCheckConnectivity()) {
  1103. checkSubmodules();
  1104. checkConnectivity();
  1105. }
  1106. parser = null;
  1107. }
  1108. /**
  1109. * Unlock the pack written by this object.
  1110. *
  1111. * @throws java.io.IOException
  1112. * the pack could not be unlocked.
  1113. */
  1114. private void unlockPack() throws IOException {
  1115. if (packLock != null) {
  1116. packLock.unlock();
  1117. packLock = null;
  1118. }
  1119. }
  1120. /**
  1121. * Generate an advertisement of available refs and capabilities.
  1122. *
  1123. * @param adv
  1124. * the advertisement formatter.
  1125. * @throws java.io.IOException
  1126. * the formatter failed to write an advertisement.
  1127. * @throws org.eclipse.jgit.transport.ServiceMayNotContinueException
  1128. * the hook denied advertisement.
  1129. */
  1130. public void sendAdvertisedRefs(RefAdvertiser adv)
  1131. throws IOException, ServiceMayNotContinueException {
  1132. if (advertiseError != null) {
  1133. adv.writeOne("ERR " + advertiseError); //$NON-NLS-1$
  1134. return;
  1135. }
  1136. try {
  1137. advertiseRefsHook.advertiseRefs(this);
  1138. } catch (ServiceMayNotContinueException fail) {
  1139. if (fail.getMessage() != null) {
  1140. adv.writeOne("ERR " + fail.getMessage()); //$NON-NLS-1$
  1141. fail.setOutput();
  1142. }
  1143. throw fail;
  1144. }
  1145. adv.init(db);
  1146. adv.advertiseCapability(CAPABILITY_SIDE_BAND_64K);
  1147. adv.advertiseCapability(CAPABILITY_DELETE_REFS);
  1148. adv.advertiseCapability(CAPABILITY_REPORT_STATUS);
  1149. if (allowQuiet)
  1150. adv.advertiseCapability(CAPABILITY_QUIET);
  1151. String nonce = getPushCertificateParser().getAdvertiseNonce();
  1152. if (nonce != null) {
  1153. adv.advertiseCapability(nonce);
  1154. }
  1155. if (db.getRefDatabase().performsAtomicTransactions())
  1156. adv.advertiseCapability(CAPABILITY_ATOMIC);
  1157. if (allowOfsDelta)
  1158. adv.advertiseCapability(CAPABILITY_OFS_DELTA);
  1159. if (allowPushOptions) {
  1160. adv.advertiseCapability(CAPABILITY_PUSH_OPTIONS);
  1161. }
  1162. adv.advertiseCapability(OPTION_AGENT, UserAgent.get());
  1163. adv.send(getAdvertisedOrDefaultRefs().values());
  1164. for (ObjectId obj : advertisedHaves)
  1165. adv.advertiseHave(obj);
  1166. if (adv.isEmpty())
  1167. adv.advertiseId(ObjectId.zeroId(), "capabilities^{}"); //$NON-NLS-1$
  1168. adv.end();
  1169. }
  1170. /**
  1171. * Returns the statistics on the received pack if available. This should be
  1172. * called after {@link #receivePack} is called.
  1173. *
  1174. * @return ReceivedPackStatistics
  1175. * @since 4.6
  1176. */
  1177. @Nullable
  1178. public ReceivedPackStatistics getReceivedPackStatistics() {
  1179. return stats;
  1180. }
  1181. /**
  1182. * Receive a list of commands from the input.
  1183. *
  1184. * @throws java.io.IOException
  1185. */
  1186. private void recvCommands() throws IOException {
  1187. PacketLineIn pck = maxCommandBytes > 0
  1188. ? new PacketLineIn(rawIn, maxCommandBytes)
  1189. : pckIn;
  1190. PushCertificateParser certParser = getPushCertificateParser();
  1191. boolean firstPkt = true;
  1192. try {
  1193. for (;;) {
  1194. String line;
  1195. try {
  1196. line = pck.readString();
  1197. } catch (EOFException eof) {
  1198. if (commands.isEmpty())
  1199. return;
  1200. throw eof;
  1201. }
  1202. if (PacketLineIn.isEnd(line)) {
  1203. break;
  1204. }
  1205. if (line.length() >= 48 && line.startsWith("shallow ")) { //$NON-NLS-1$
  1206. parseShallow(line.substring(8, 48));
  1207. continue;
  1208. }
  1209. if (firstPkt) {
  1210. firstPkt = false;
  1211. FirstCommand firstLine = FirstCommand.fromLine(line);
  1212. enabledCapabilities = firstLine.getCapabilities();
  1213. line = firstLine.getLine();
  1214. enableCapabilities();
  1215. if (line.equals(GitProtocolConstants.OPTION_PUSH_CERT)) {
  1216. certParser.receiveHeader(pck, !isBiDirectionalPipe());
  1217. continue;
  1218. }
  1219. }
  1220. if (line.equals(PushCertificateParser.BEGIN_SIGNATURE)) {
  1221. certParser.receiveSignature(pck);
  1222. continue;
  1223. }
  1224. ReceiveCommand cmd = parseCommand(line);
  1225. if (cmd.getRefName().equals(Constants.HEAD)) {
  1226. cmd.setResult(Result.REJECTED_CURRENT_BRANCH);
  1227. } else {
  1228. cmd.setRef(refs.get(cmd.getRefName()));
  1229. }
  1230. commands.add(cmd);
  1231. if (certParser.enabled()) {
  1232. certParser.addCommand(cmd);
  1233. }
  1234. }
  1235. pushCert = certParser.build();
  1236. if (hasCommands()) {
  1237. readPostCommands(pck);
  1238. }
  1239. } catch (Throwable t) {
  1240. discardCommands();
  1241. throw t;
  1242. }
  1243. }
  1244. private void discardCommands() {
  1245. if (sideBand) {
  1246. long max = maxDiscardBytes;
  1247. if (max < 0) {
  1248. max = Math.max(3 * maxCommandBytes, 3L << 20);
  1249. }
  1250. try {
  1251. new PacketLineIn(rawIn, max).discardUntilEnd();
  1252. } catch (IOException e) {
  1253. // Ignore read failures attempting to discard.
  1254. }
  1255. }
  1256. }
  1257. private void parseShallow(String idStr) throws PackProtocolException {
  1258. ObjectId id;
  1259. try {
  1260. id = ObjectId.fromString(idStr);
  1261. } catch (InvalidObjectIdException e) {
  1262. throw new PackProtocolException(e.getMessage(), e);
  1263. }
  1264. clientShallowCommits.add(id);
  1265. }
  1266. /**
  1267. * @param in
  1268. * request stream.
  1269. * @throws IOException
  1270. * request line cannot be read.
  1271. */
  1272. void readPostCommands(PacketLineIn in) throws IOException {
  1273. if (usePushOptions) {
  1274. pushOptions = new ArrayList<>(4);
  1275. for (;;) {
  1276. String option = in.readString();
  1277. if (PacketLineIn.isEnd(option)) {
  1278. break;
  1279. }
  1280. pushOptions.add(option);
  1281. }
  1282. }
  1283. }
  1284. /**
  1285. * Enable capabilities based on a previously read capabilities line.
  1286. */
  1287. private void enableCapabilities() {
  1288. reportStatus = isCapabilityEnabled(CAPABILITY_REPORT_STATUS);
  1289. usePushOptions = isCapabilityEnabled(CAPABILITY_PUSH_OPTIONS);
  1290. sideBand = isCapabilityEnabled(CAPABILITY_SIDE_BAND_64K);
  1291. quiet = allowQuiet && isCapabilityEnabled(CAPABILITY_QUIET);
  1292. if (sideBand) {
  1293. OutputStream out = rawOut;
  1294. rawOut = new SideBandOutputStream(CH_DATA, MAX_BUF, out);
  1295. msgOut = new SideBandOutputStream(CH_PROGRESS, MAX_BUF, out);
  1296. errOut = new SideBandOutputStream(CH_ERROR, MAX_BUF, out);
  1297. pckOut = new PacketLineOut(rawOut);
  1298. pckOut.setFlushOnEnd(false);
  1299. }
  1300. }
  1301. /**
  1302. * Check if the peer requested a capability.
  1303. *
  1304. * @param name
  1305. * protocol name identifying the capability.
  1306. * @return true if the peer requested the capability to be enabled.
  1307. */
  1308. private boolean isCapabilityEnabled(String name) {
  1309. return enabledCapabilities.contains(name);
  1310. }
  1311. private void checkRequestWasRead() {
  1312. if (enabledCapabilities == null)
  1313. throw new RequestNotYetReadException();
  1314. }
  1315. /**
  1316. * Whether a pack is expected based on the list of commands.
  1317. *
  1318. * @return {@code true} if a pack is expected based on the list of commands.
  1319. */
  1320. private boolean needPack() {
  1321. for (ReceiveCommand cmd : commands) {
  1322. if (cmd.getType() != ReceiveCommand.Type.DELETE)
  1323. return true;
  1324. }
  1325. return false;
  1326. }
  1327. /**
  1328. * Receive a pack from the input and store it in the repository.
  1329. *
  1330. * @throws IOException
  1331. * an error occurred reading or indexing the pack.
  1332. */
  1333. private void receivePack() throws IOException {
  1334. // It might take the client a while to pack the objects it needs
  1335. // to send to us. We should increase our timeout so we don't
  1336. // abort while the client is computing.
  1337. //
  1338. if (timeoutIn != null)
  1339. timeoutIn.setTimeout(10 * timeout * 1000);
  1340. ProgressMonitor receiving = NullProgressMonitor.INSTANCE;
  1341. ProgressMonitor resolving = NullProgressMonitor.INSTANCE;
  1342. if (sideBand && !quiet)
  1343. resolving = new SideBandProgressMonitor(msgOut);
  1344. try (ObjectInserter ins = db.newObjectInserter()) {
  1345. String lockMsg = "jgit receive-pack"; //$NON-NLS-1$
  1346. if (getRefLogIdent() != null)
  1347. lockMsg += " from " + getRefLogIdent().toExternalString(); //$NON-NLS-1$
  1348. parser = ins.newPackParser(packInputStream());
  1349. parser.setAllowThin(true);
  1350. parser.setNeedNewObjectIds(checkReferencedIsReachable);
  1351. parser.setNeedBaseObjectIds(checkReferencedIsReachable);
  1352. parser.setCheckEofAfterPackFooter(
  1353. !biDirectionalPipe && !isExpectDataAfterPackFooter());
  1354. parser.setExpectDataAfterPackFooter(isExpectDataAfterPackFooter());
  1355. parser.setObjectChecker(objectChecker);
  1356. parser.setLockMessage(lockMsg);
  1357. parser.setMaxObjectSizeLimit(maxObjectSizeLimit);
  1358. packLock = parser.parse(receiving, resolving);
  1359. packSize = Long.valueOf(parser.getPackSize());
  1360. stats = parser.getReceivedPackStatistics();
  1361. ins.flush();
  1362. }
  1363. if (timeoutIn != null)
  1364. timeoutIn.setTimeout(timeout * 1000);
  1365. }
  1366. private InputStream packInputStream() {
  1367. InputStream packIn = rawIn;
  1368. if (maxPackSizeLimit >= 0) {
  1369. packIn = new LimitedInputStream(packIn, maxPackSizeLimit) {
  1370. @Override
  1371. protected void limitExceeded() throws TooLargePackException {
  1372. throw new TooLargePackException(limit);
  1373. }
  1374. };
  1375. }
  1376. return packIn;
  1377. }
  1378. private boolean needCheckConnectivity() {
  1379. return isCheckReceivedObjects()
  1380. || isCheckReferencedObjectsAreReachable()
  1381. || !getClientShallowCommits().isEmpty();
  1382. }
  1383. private void checkSubmodules() throws IOException, LargeObjectException,
  1384. SubmoduleValidationException {
  1385. ObjectDatabase odb = db.getObjectDatabase();
  1386. if (objectChecker == null) {
  1387. return;
  1388. }
  1389. for (GitmoduleEntry entry : objectChecker.getGitsubmodules()) {
  1390. AnyObjectId blobId = entry.getBlobId();
  1391. ObjectLoader blob = odb.open(blobId, Constants.OBJ_BLOB);
  1392. SubmoduleValidator.assertValidGitModulesFile(
  1393. new String(blob.getBytes(), UTF_8));
  1394. }
  1395. }
  1396. private void checkConnectivity() throws IOException {
  1397. ObjectIdSubclassMap<ObjectId> baseObjects = null;
  1398. ObjectIdSubclassMap<ObjectId> providedObjects = null;
  1399. ProgressMonitor checking = NullProgressMonitor.INSTANCE;
  1400. if (sideBand && !quiet) {
  1401. SideBandProgressMonitor m = new SideBandProgressMonitor(msgOut);
  1402. m.setDelayStart(750, TimeUnit.MILLISECONDS);
  1403. checking = m;
  1404. }
  1405. if (checkReferencedIsReachable) {
  1406. baseObjects = parser.getBaseObjectIds();
  1407. providedObjects = parser.getNewObjectIds();
  1408. }
  1409. parser = null;
  1410. try (ObjectWalk ow = new ObjectWalk(db)) {
  1411. if (baseObjects != null) {
  1412. ow.sort(RevSort.TOPO);
  1413. if (!baseObjects.isEmpty())
  1414. ow.sort(RevSort.BOUNDARY, true);
  1415. }
  1416. for (ReceiveCommand cmd : commands) {
  1417. if (cmd.getResult() != Result.NOT_ATTEMPTED)
  1418. continue;
  1419. if (cmd.getType() == ReceiveCommand.Type.DELETE)
  1420. continue;
  1421. ow.markStart(ow.parseAny(cmd.getNewId()));
  1422. }
  1423. for (ObjectId have : advertisedHaves) {
  1424. RevObject o = ow.parseAny(have);
  1425. ow.markUninteresting(o);
  1426. if (baseObjects != null && !baseObjects.isEmpty()) {
  1427. o = ow.peel(o);
  1428. if (o instanceof RevCommit)
  1429. o = ((RevCommit) o).getTree();
  1430. if (o instanceof RevTree)
  1431. ow.markUninteresting(o);
  1432. }
  1433. }
  1434. checking.beginTask(JGitText.get().countingObjects,
  1435. ProgressMonitor.UNKNOWN);
  1436. RevCommit c;
  1437. while ((c = ow.next()) != null) {
  1438. checking.update(1);
  1439. if (providedObjects != null //
  1440. && !c.has(RevFlag.UNINTERESTING) //
  1441. && !providedObjects.contains(c))
  1442. throw new MissingObjectException(c, Constants.TYPE_COMMIT);
  1443. }
  1444. RevObject o;
  1445. while ((o = ow.nextObject()) != null) {
  1446. checking.update(1);
  1447. if (o.has(RevFlag.UNINTERESTING))
  1448. continue;
  1449. if (providedObjects != null) {
  1450. if (providedObjects.contains(o)) {
  1451. continue;
  1452. }
  1453. throw new MissingObjectException(o, o.getType());
  1454. }
  1455. if (o instanceof RevBlob && !db.getObjectDatabase().has(o))
  1456. throw new MissingObjectException(o, Constants.TYPE_BLOB);
  1457. }
  1458. checking.endTask();
  1459. if (baseObjects != null) {
  1460. for (ObjectId id : baseObjects) {
  1461. o = ow.parseAny(id);
  1462. if (!o.has(RevFlag.UNINTERESTING))
  1463. throw new MissingObjectException(o, o.getType());
  1464. }
  1465. }
  1466. }
  1467. }
  1468. /**
  1469. * Validate the command list.
  1470. */
  1471. private void validateCommands() {
  1472. for (ReceiveCommand cmd : commands) {
  1473. final Ref ref = cmd.getRef();
  1474. if (cmd.getResult() != Result.NOT_ATTEMPTED)
  1475. continue;
  1476. if (cmd.getType() == ReceiveCommand.Type.DELETE) {
  1477. if (!isAllowDeletes()) {
  1478. // Deletes are not supported on this repository.
  1479. cmd.setResult(Result.REJECTED_NODELETE);
  1480. continue;
  1481. }
  1482. if (!isAllowBranchDeletes()
  1483. && ref.getName().startsWith(Constants.R_HEADS)) {
  1484. // Branches cannot be deleted, but other refs can.
  1485. cmd.setResult(Result.REJECTED_NODELETE);
  1486. continue;
  1487. }
  1488. }
  1489. if (cmd.getType() == ReceiveCommand.Type.CREATE) {
  1490. if (!isAllowCreates()) {
  1491. cmd.setResult(Result.REJECTED_NOCREATE);
  1492. continue;
  1493. }
  1494. if (ref != null && !isAllowNonFastForwards()) {
  1495. // Creation over an existing ref is certainly not going
  1496. // to be a fast-forward update. We can reject it early.
  1497. //
  1498. cmd.setResult(Result.REJECTED_NONFASTFORWARD);
  1499. continue;
  1500. }
  1501. if (ref != null) {
  1502. // A well behaved client shouldn't have sent us a
  1503. // create command for a ref we advertised to it.
  1504. //
  1505. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1506. JGitText.get().refAlreadyExists);
  1507. continue;
  1508. }
  1509. }
  1510. if (cmd.getType() == ReceiveCommand.Type.DELETE && ref != null) {
  1511. ObjectId id = ref.getObjectId();
  1512. if (id == null) {
  1513. id = ObjectId.zeroId();
  1514. }
  1515. if (!ObjectId.zeroId().equals(cmd.getOldId())
  1516. && !id.equals(cmd.getOldId())) {
  1517. // Delete commands can be sent with the old id matching our
  1518. // advertised value, *OR* with the old id being 0{40}. Any
  1519. // other requested old id is invalid.
  1520. //
  1521. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1522. JGitText.get().invalidOldIdSent);
  1523. continue;
  1524. }
  1525. }
  1526. if (cmd.getType() == ReceiveCommand.Type.UPDATE) {
  1527. if (ref == null) {
  1528. // The ref must have been advertised in order to be updated.
  1529. //
  1530. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1531. JGitText.get().noSuchRef);
  1532. continue;
  1533. }
  1534. ObjectId id = ref.getObjectId();
  1535. if (id == null) {
  1536. // We cannot update unborn branch
  1537. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1538. JGitText.get().cannotUpdateUnbornBranch);
  1539. continue;
  1540. }
  1541. if (!id.equals(cmd.getOldId())) {
  1542. // A properly functioning client will send the same
  1543. // object id we advertised.
  1544. //
  1545. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1546. JGitText.get().invalidOldIdSent);
  1547. continue;
  1548. }
  1549. // Is this possibly a non-fast-forward style update?
  1550. //
  1551. RevObject oldObj, newObj;
  1552. try {
  1553. oldObj = walk.parseAny(cmd.getOldId());
  1554. } catch (IOException e) {
  1555. receiveCommandErrorHandler
  1556. .handleOldIdValidationException(cmd, e);
  1557. continue;
  1558. }
  1559. try {
  1560. newObj = walk.parseAny(cmd.getNewId());
  1561. } catch (IOException e) {
  1562. receiveCommandErrorHandler
  1563. .handleNewIdValidationException(cmd, e);
  1564. continue;
  1565. }
  1566. if (oldObj instanceof RevCommit
  1567. && newObj instanceof RevCommit) {
  1568. try {
  1569. if (walk.isMergedInto((RevCommit) oldObj,
  1570. (RevCommit) newObj)) {
  1571. cmd.setTypeFastForwardUpdate();
  1572. } else {
  1573. cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
  1574. }
  1575. } catch (IOException e) {
  1576. receiveCommandErrorHandler
  1577. .handleFastForwardCheckException(cmd, e);
  1578. }
  1579. } else {
  1580. cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
  1581. }
  1582. if (cmd.getType() == ReceiveCommand.Type.UPDATE_NONFASTFORWARD
  1583. && !isAllowNonFastForwards()) {
  1584. cmd.setResult(Result.REJECTED_NONFASTFORWARD);
  1585. continue;
  1586. }
  1587. }
  1588. if (!cmd.getRefName().startsWith(Constants.R_REFS)
  1589. || !Repository.isValidRefName(cmd.getRefName())) {
  1590. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1591. JGitText.get().funnyRefname);
  1592. }
  1593. }
  1594. }
  1595. /**
  1596. * Whether any commands have been rejected so far.
  1597. *
  1598. * @return if any commands have been rejected so far.
  1599. */
  1600. private boolean anyRejects() {
  1601. for (ReceiveCommand cmd : commands) {
  1602. if (cmd.getResult() != Result.NOT_ATTEMPTED
  1603. && cmd.getResult() != Result.OK)
  1604. return true;
  1605. }
  1606. return false;
  1607. }
  1608. /**
  1609. * Set the result to fail for any command that was not processed yet.
  1610. *
  1611. */
  1612. private void failPendingCommands() {
  1613. ReceiveCommand.abort(commands);
  1614. }
  1615. /**
  1616. * Filter the list of commands according to result.
  1617. *
  1618. * @param want
  1619. * desired status to filter by.
  1620. * @return a copy of the command list containing only those commands with
  1621. * the desired status.
  1622. */
  1623. private List<ReceiveCommand> filterCommands(Result want) {
  1624. return ReceiveCommand.filter(commands, want);
  1625. }
  1626. /**
  1627. * Execute commands to update references.
  1628. */
  1629. private void executeCommands() {
  1630. List<ReceiveCommand> toApply = filterCommands(Result.NOT_ATTEMPTED);
  1631. if (toApply.isEmpty())
  1632. return;
  1633. ProgressMonitor updating = NullProgressMonitor.INSTANCE;
  1634. if (sideBand) {
  1635. SideBandProgressMonitor pm = new SideBandProgressMonitor(msgOut);
  1636. pm.setDelayStart(250, TimeUnit.MILLISECONDS);
  1637. updating = pm;
  1638. }
  1639. BatchRefUpdate batch = db.getRefDatabase().newBatchUpdate();
  1640. batch.setAllowNonFastForwards(isAllowNonFastForwards());
  1641. batch.setAtomic(isAtomic());
  1642. batch.setRefLogIdent(getRefLogIdent());
  1643. batch.setRefLogMessage("push", true); //$NON-NLS-1$
  1644. batch.addCommand(toApply);
  1645. try {
  1646. batch.setPushCertificate(getPushCertificate());
  1647. batch.execute(walk, updating);
  1648. } catch (IOException e) {
  1649. receiveCommandErrorHandler.handleBatchRefUpdateException(toApply,
  1650. e);
  1651. }
  1652. }
  1653. /**
  1654. * Send a status report.
  1655. *
  1656. * @param unpackError
  1657. * an error that occurred during unpacking, or {@code null}
  1658. * @throws java.io.IOException
  1659. * an error occurred writing the status report.
  1660. * @since 5.6
  1661. */
  1662. private void sendStatusReport(Throwable unpackError) throws IOException {
  1663. Reporter out = new Reporter() {
  1664. @Override
  1665. void sendString(String s) throws IOException {
  1666. if (reportStatus) {
  1667. pckOut.writeString(s + "\n"); //$NON-NLS-1$
  1668. } else if (msgOut != null) {
  1669. msgOut.write(Constants.encode(s + "\n")); //$NON-NLS-1$
  1670. }
  1671. }
  1672. };
  1673. try {
  1674. if (unpackError != null) {
  1675. out.sendString("unpack error " + unpackError.getMessage()); //$NON-NLS-1$
  1676. if (reportStatus) {
  1677. for (ReceiveCommand cmd : commands) {
  1678. out.sendString("ng " + cmd.getRefName() //$NON-NLS-1$
  1679. + " n/a (unpacker error)"); //$NON-NLS-1$
  1680. }
  1681. }
  1682. return;
  1683. }
  1684. if (reportStatus) {
  1685. out.sendString("unpack ok"); //$NON-NLS-1$
  1686. }
  1687. for (ReceiveCommand cmd : commands) {
  1688. if (cmd.getResult() == Result.OK) {
  1689. if (reportStatus) {
  1690. out.sendString("ok " + cmd.getRefName()); //$NON-NLS-1$
  1691. }
  1692. continue;
  1693. }
  1694. final StringBuilder r = new StringBuilder();
  1695. if (reportStatus) {
  1696. r.append("ng ").append(cmd.getRefName()).append(" "); //$NON-NLS-1$ //$NON-NLS-2$
  1697. } else {
  1698. r.append(" ! [rejected] ").append(cmd.getRefName()) //$NON-NLS-1$
  1699. .append(" ("); //$NON-NLS-1$
  1700. }
  1701. switch (cmd.getResult()) {
  1702. case NOT_ATTEMPTED:
  1703. r.append("server bug; ref not processed"); //$NON-NLS-1$
  1704. break;
  1705. case REJECTED_NOCREATE:
  1706. r.append("creation prohibited"); //$NON-NLS-1$
  1707. break;
  1708. case REJECTED_NODELETE:
  1709. r.append("deletion prohibited"); //$NON-NLS-1$
  1710. break;
  1711. case REJECTED_NONFASTFORWARD:
  1712. r.append("non-fast forward"); //$NON-NLS-1$
  1713. break;
  1714. case REJECTED_CURRENT_BRANCH:
  1715. r.append("branch is currently checked out"); //$NON-NLS-1$
  1716. break;
  1717. case REJECTED_MISSING_OBJECT:
  1718. if (cmd.getMessage() == null)
  1719. r.append("missing object(s)"); //$NON-NLS-1$
  1720. else if (cmd.getMessage()
  1721. .length() == Constants.OBJECT_ID_STRING_LENGTH) {
  1722. r.append("object "); //$NON-NLS-1$
  1723. r.append(cmd.getMessage());
  1724. r.append(" missing"); //$NON-NLS-1$
  1725. } else
  1726. r.append(cmd.getMessage());
  1727. break;
  1728. case REJECTED_OTHER_REASON:
  1729. if (cmd.getMessage() == null)
  1730. r.append("unspecified reason"); //$NON-NLS-1$
  1731. else
  1732. r.append(cmd.getMessage());
  1733. break;
  1734. case LOCK_FAILURE:
  1735. r.append("failed to lock"); //$NON-NLS-1$
  1736. break;
  1737. case OK:
  1738. // We shouldn't have reached this case (see 'ok' case
  1739. // above).
  1740. continue;
  1741. }
  1742. if (!reportStatus) {
  1743. r.append(")"); //$NON-NLS-1$
  1744. }
  1745. out.sendString(r.toString());
  1746. }
  1747. } finally {
  1748. if (reportStatus) {
  1749. pckOut.end();
  1750. }
  1751. }
  1752. }
  1753. /**
  1754. * Close and flush (if necessary) the underlying streams.
  1755. *
  1756. * @throws java.io.IOException
  1757. */
  1758. private void close() throws IOException {
  1759. if (sideBand) {
  1760. // If we are using side band, we need to send a final
  1761. // flush-pkt to tell the remote peer the side band is
  1762. // complete and it should stop decoding. We need to
  1763. // use the original output stream as rawOut is now the
  1764. // side band data channel.
  1765. //
  1766. ((SideBandOutputStream) msgOut).flushBuffer();
  1767. ((SideBandOutputStream) rawOut).flushBuffer();
  1768. PacketLineOut plo = new PacketLineOut(origOut);
  1769. plo.setFlushOnEnd(false);
  1770. plo.end();
  1771. }
  1772. if (biDirectionalPipe) {
  1773. // If this was a native git connection, flush the pipe for
  1774. // the caller. For smart HTTP we don't do this flush and
  1775. // instead let the higher level HTTP servlet code do it.
  1776. //
  1777. if (!sideBand && msgOut != null)
  1778. msgOut.flush();
  1779. rawOut.flush();
  1780. }
  1781. }
  1782. /**
  1783. * Release any resources used by this object.
  1784. *
  1785. * @throws java.io.IOException
  1786. * the pack could not be unlocked.
  1787. */
  1788. private void release() throws IOException {
  1789. walk.close();
  1790. unlockPack();
  1791. timeoutIn = null;
  1792. rawIn = null;
  1793. rawOut = null;
  1794. msgOut = null;
  1795. pckIn = null;
  1796. pckOut = null;
  1797. refs = null;
  1798. // Keep the capabilities. If responses are sent after this release
  1799. // we need to remember at least whether sideband communication has to be
  1800. // used
  1801. commands = null;
  1802. if (timer != null) {
  1803. try {
  1804. timer.terminate();
  1805. } finally {
  1806. timer = null;
  1807. }
  1808. }
  1809. }
  1810. /** Interface for reporting status messages. */
  1811. static abstract class Reporter {
  1812. abstract void sendString(String s) throws IOException;
  1813. }
  1814. /**
  1815. * Get the push certificate used to verify the pusher's identity.
  1816. * <p>
  1817. * Only valid after commands are read from the wire.
  1818. *
  1819. * @return the parsed certificate, or null if push certificates are disabled
  1820. * or no cert was presented by the client.
  1821. * @since 4.1
  1822. */
  1823. public PushCertificate getPushCertificate() {
  1824. return pushCert;
  1825. }
  1826. /**
  1827. * Set the push certificate used to verify the pusher's identity.
  1828. * <p>
  1829. * Should only be called if reconstructing an instance without going through
  1830. * the normal {@link #recvCommands()} flow.
  1831. *
  1832. * @param cert
  1833. * the push certificate to set.
  1834. * @since 4.1
  1835. */
  1836. public void setPushCertificate(PushCertificate cert) {
  1837. pushCert = cert;
  1838. }
  1839. /**
  1840. * Gets an unmodifiable view of the option strings associated with the push.
  1841. *
  1842. * @return an unmodifiable view of pushOptions, or null (if pushOptions is).
  1843. * @since 4.5
  1844. */
  1845. @Nullable
  1846. public List<String> getPushOptions() {
  1847. if (isAllowPushOptions() && usePushOptions) {
  1848. return Collections.unmodifiableList(pushOptions);
  1849. }
  1850. // The client doesn't support push options. Return null to
  1851. // distinguish this from the case where the client declared support
  1852. // for push options and sent an empty list of them.
  1853. return null;
  1854. }
  1855. /**
  1856. * Set the push options supplied by the client.
  1857. * <p>
  1858. * Should only be called if reconstructing an instance without going through
  1859. * the normal {@link #recvCommands()} flow.
  1860. *
  1861. * @param options
  1862. * the list of options supplied by the client. The
  1863. * {@code ReceivePack} instance takes ownership of this list.
  1864. * Callers are encouraged to first create a copy if the list may
  1865. * be modified later.
  1866. * @since 4.5
  1867. */
  1868. public void setPushOptions(@Nullable List<String> options) {
  1869. usePushOptions = options != null;
  1870. pushOptions = options;
  1871. }
  1872. /**
  1873. * Get the hook invoked before updates occur.
  1874. *
  1875. * @return the hook invoked before updates occur.
  1876. */
  1877. public PreReceiveHook getPreReceiveHook() {
  1878. return preReceive;
  1879. }
  1880. /**
  1881. * Set the hook which is invoked prior to commands being executed.
  1882. * <p>
  1883. * Only valid commands (those which have no obvious errors according to the
  1884. * received input and this instance's configuration) are passed into the
  1885. * hook. The hook may mark a command with a result of any value other than
  1886. * {@link org.eclipse.jgit.transport.ReceiveCommand.Result#NOT_ATTEMPTED} to
  1887. * block its execution.
  1888. * <p>
  1889. * The hook may be called with an empty command collection if the current
  1890. * set is completely invalid.
  1891. *
  1892. * @param h
  1893. * the hook instance; may be null to disable the hook.
  1894. */
  1895. public void setPreReceiveHook(PreReceiveHook h) {
  1896. preReceive = h != null ? h : PreReceiveHook.NULL;
  1897. }
  1898. /**
  1899. * Get the hook invoked after updates occur.
  1900. *
  1901. * @return the hook invoked after updates occur.
  1902. */
  1903. public PostReceiveHook getPostReceiveHook() {
  1904. return postReceive;
  1905. }
  1906. /**
  1907. * Set the hook which is invoked after commands are executed.
  1908. * <p>
  1909. * Only successful commands (type is
  1910. * {@link org.eclipse.jgit.transport.ReceiveCommand.Result#OK}) are passed
  1911. * into the hook. The hook may be called with an empty command collection if
  1912. * the current set all resulted in an error.
  1913. *
  1914. * @param h
  1915. * the hook instance; may be null to disable the hook.
  1916. */
  1917. public void setPostReceiveHook(PostReceiveHook h) {
  1918. postReceive = h != null ? h : PostReceiveHook.NULL;
  1919. }
  1920. /**
  1921. * Set whether this class will report command failures as warning messages
  1922. * before sending the command results.
  1923. *
  1924. * @param echo
  1925. * if true this class will report command failures as warning
  1926. * messages before sending the command results. This is usually
  1927. * not necessary, but may help buggy Git clients that discard the
  1928. * errors when all branches fail.
  1929. * @deprecated no widely used Git versions need this any more
  1930. */
  1931. @Deprecated
  1932. public void setEchoCommandFailures(boolean echo) {
  1933. // No-op.
  1934. }
  1935. /**
  1936. * Execute the receive task on the socket.
  1937. *
  1938. * @param input
  1939. * raw input to read client commands and pack data from. Caller
  1940. * must ensure the input is buffered, otherwise read performance
  1941. * may suffer.
  1942. * @param output
  1943. * response back to the Git network client. Caller must ensure
  1944. * the output is buffered, otherwise write performance may
  1945. * suffer.
  1946. * @param messages
  1947. * secondary "notice" channel to send additional messages out
  1948. * through. When run over SSH this should be tied back to the
  1949. * standard error channel of the command execution. For most
  1950. * other network connections this should be null.
  1951. * @throws java.io.IOException
  1952. */
  1953. public void receive(final InputStream input, final OutputStream output,
  1954. final OutputStream messages) throws IOException {
  1955. init(input, output, messages);
  1956. try {
  1957. service();
  1958. } finally {
  1959. try {
  1960. close();
  1961. } finally {
  1962. release();
  1963. }
  1964. }
  1965. }
  1966. private void service() throws IOException {
  1967. if (isBiDirectionalPipe()) {
  1968. sendAdvertisedRefs(new PacketLineOutRefAdvertiser(pckOut));
  1969. pckOut.flush();
  1970. } else
  1971. getAdvertisedOrDefaultRefs();
  1972. if (hasError())
  1973. return;
  1974. try {
  1975. recvCommands();
  1976. } catch (PackProtocolException e) {
  1977. fatalError(e.getMessage());
  1978. throw e;
  1979. } catch (InputOverLimitIOException e) {
  1980. String msg = JGitText.get().tooManyCommands;
  1981. fatalError(msg);
  1982. throw new PackProtocolException(msg);
  1983. }
  1984. if (hasCommands()) {
  1985. try (PostReceiveExecutor e = new PostReceiveExecutor()) {
  1986. if (needPack()) {
  1987. try {
  1988. receivePackAndCheckConnectivity();
  1989. } catch (IOException | RuntimeException
  1990. | SubmoduleValidationException | Error err) {
  1991. unlockPack();
  1992. sendStatusReport(err);
  1993. throw new UnpackException(err);
  1994. }
  1995. }
  1996. try {
  1997. setAtomic(isCapabilityEnabled(CAPABILITY_ATOMIC));
  1998. validateCommands();
  1999. if (atomic && anyRejects()) {
  2000. failPendingCommands();
  2001. }
  2002. preReceive.onPreReceive(
  2003. this, filterCommands(Result.NOT_ATTEMPTED));
  2004. if (atomic && anyRejects()) {
  2005. failPendingCommands();
  2006. }
  2007. executeCommands();
  2008. } finally {
  2009. unlockPack();
  2010. }
  2011. sendStatusReport(null);
  2012. }
  2013. autoGc();
  2014. }
  2015. }
  2016. private void autoGc() {
  2017. Repository repo = getRepository();
  2018. if (!repo.getConfig().getBoolean(ConfigConstants.CONFIG_RECEIVE_SECTION,
  2019. ConfigConstants.CONFIG_KEY_AUTOGC, true)) {
  2020. return;
  2021. }
  2022. repo.autoGC(NullProgressMonitor.INSTANCE);
  2023. }
  2024. static ReceiveCommand parseCommand(String line)
  2025. throws PackProtocolException {
  2026. if (line == null || line.length() < 83) {
  2027. throw new PackProtocolException(
  2028. JGitText.get().errorInvalidProtocolWantedOldNewRef);
  2029. }
  2030. String oldStr = line.substring(0, 40);
  2031. String newStr = line.substring(41, 81);
  2032. ObjectId oldId, newId;
  2033. try {
  2034. oldId = ObjectId.fromString(oldStr);
  2035. newId = ObjectId.fromString(newStr);
  2036. } catch (InvalidObjectIdException e) {
  2037. throw new PackProtocolException(
  2038. JGitText.get().errorInvalidProtocolWantedOldNewRef, e);
  2039. }
  2040. String name = line.substring(82);
  2041. if (!Repository.isValidRefName(name)) {
  2042. throw new PackProtocolException(
  2043. JGitText.get().errorInvalidProtocolWantedOldNewRef);
  2044. }
  2045. return new ReceiveCommand(oldId, newId, name);
  2046. }
  2047. private class PostReceiveExecutor implements AutoCloseable {
  2048. @Override
  2049. public void close() {
  2050. postReceive.onPostReceive(ReceivePack.this,
  2051. filterCommands(Result.OK));
  2052. }
  2053. }
  2054. }