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.

BaseReceivePack.java 59KB

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