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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997
  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 whether or not a pack has been received.
  965. *
  966. * This can be called before calling {@link #getPackSize()} to avoid causing
  967. * {@code IllegalStateException} when the pack size was not set because no
  968. * pack was received.
  969. *
  970. * @return true if a pack has been received.
  971. * @since 5.6
  972. */
  973. public boolean hasReceivedPack() {
  974. return packSize != null;
  975. }
  976. /**
  977. * Get the size of the received pack file including the index size.
  978. *
  979. * This can only be called if the pack is already received.
  980. *
  981. * @return the size of the received pack including index size
  982. * @throws java.lang.IllegalStateException
  983. * if called before the pack has been received
  984. * @since 3.3
  985. */
  986. public long getPackSize() {
  987. if (packSize != null)
  988. return packSize.longValue();
  989. throw new IllegalStateException(JGitText.get().packSizeNotSetYet);
  990. }
  991. /**
  992. * Get the commits from the client's shallow file.
  993. *
  994. * @return if the client is a shallow repository, the list of edge commits
  995. * that define the client's shallow boundary. Empty set if the client
  996. * is earlier than Git 1.9, or is a full clone.
  997. * @since 3.5
  998. */
  999. protected Set<ObjectId> getClientShallowCommits() {
  1000. return clientShallowCommits;
  1001. }
  1002. /**
  1003. * Whether any commands to be executed have been read.
  1004. *
  1005. * @return {@code true} if any commands to be executed have been read.
  1006. */
  1007. protected boolean hasCommands() {
  1008. return !commands.isEmpty();
  1009. }
  1010. /**
  1011. * Whether an error occurred that should be advertised.
  1012. *
  1013. * @return true if an error occurred that should be advertised.
  1014. */
  1015. protected boolean hasError() {
  1016. return advertiseError != null;
  1017. }
  1018. /**
  1019. * Initialize the instance with the given streams.
  1020. *
  1021. * @param input
  1022. * raw input to read client commands and pack data from. Caller
  1023. * must ensure the input is buffered, otherwise read performance
  1024. * may suffer.
  1025. * @param output
  1026. * response back to the Git network client. Caller must ensure
  1027. * the output is buffered, otherwise write performance may
  1028. * suffer.
  1029. * @param messages
  1030. * secondary "notice" channel to send additional messages out
  1031. * through. When run over SSH this should be tied back to the
  1032. * standard error channel of the command execution. For most
  1033. * other network connections this should be null.
  1034. */
  1035. protected void init(final InputStream input, final OutputStream output,
  1036. final OutputStream messages) {
  1037. origOut = output;
  1038. rawIn = input;
  1039. rawOut = output;
  1040. msgOut = messages;
  1041. if (timeout > 0) {
  1042. final Thread caller = Thread.currentThread();
  1043. timer = new InterruptTimer(caller.getName() + "-Timer"); //$NON-NLS-1$
  1044. timeoutIn = new TimeoutInputStream(rawIn, timer);
  1045. TimeoutOutputStream o = new TimeoutOutputStream(rawOut, timer);
  1046. timeoutIn.setTimeout(timeout * 1000);
  1047. o.setTimeout(timeout * 1000);
  1048. rawIn = timeoutIn;
  1049. rawOut = o;
  1050. }
  1051. pckIn = new PacketLineIn(rawIn);
  1052. pckOut = new PacketLineOut(rawOut);
  1053. pckOut.setFlushOnEnd(false);
  1054. enabledCapabilities = new HashSet<>();
  1055. commands = new ArrayList<>();
  1056. }
  1057. /**
  1058. * Get advertised refs, or the default if not explicitly advertised.
  1059. *
  1060. * @return advertised refs, or the default if not explicitly advertised.
  1061. */
  1062. protected Map<String, Ref> getAdvertisedOrDefaultRefs() {
  1063. if (refs == null)
  1064. setAdvertisedRefs(null, null);
  1065. return refs;
  1066. }
  1067. /**
  1068. * Receive a pack from the stream and check connectivity if necessary.
  1069. *
  1070. * @throws java.io.IOException
  1071. * an error occurred during unpacking or connectivity checking.
  1072. */
  1073. protected void receivePackAndCheckConnectivity() throws IOException {
  1074. receivePack();
  1075. if (needCheckConnectivity()) {
  1076. checkSubmodules();
  1077. checkConnectivity();
  1078. }
  1079. parser = null;
  1080. }
  1081. /**
  1082. * Unlock the pack written by this object.
  1083. *
  1084. * @throws java.io.IOException
  1085. * the pack could not be unlocked.
  1086. */
  1087. protected void unlockPack() throws IOException {
  1088. if (packLock != null) {
  1089. packLock.unlock();
  1090. packLock = null;
  1091. }
  1092. }
  1093. /**
  1094. * Generate an advertisement of available refs and capabilities.
  1095. *
  1096. * @param adv
  1097. * the advertisement formatter.
  1098. * @throws java.io.IOException
  1099. * the formatter failed to write an advertisement.
  1100. * @throws org.eclipse.jgit.transport.ServiceMayNotContinueException
  1101. * the hook denied advertisement.
  1102. */
  1103. public void sendAdvertisedRefs(RefAdvertiser adv)
  1104. throws IOException, ServiceMayNotContinueException {
  1105. if (advertiseError != null) {
  1106. adv.writeOne("ERR " + advertiseError); //$NON-NLS-1$
  1107. return;
  1108. }
  1109. try {
  1110. advertiseRefsHook.advertiseRefs(this);
  1111. } catch (ServiceMayNotContinueException fail) {
  1112. if (fail.getMessage() != null) {
  1113. adv.writeOne("ERR " + fail.getMessage()); //$NON-NLS-1$
  1114. fail.setOutput();
  1115. }
  1116. throw fail;
  1117. }
  1118. adv.init(db);
  1119. adv.advertiseCapability(CAPABILITY_SIDE_BAND_64K);
  1120. adv.advertiseCapability(CAPABILITY_DELETE_REFS);
  1121. adv.advertiseCapability(CAPABILITY_REPORT_STATUS);
  1122. if (allowQuiet)
  1123. adv.advertiseCapability(CAPABILITY_QUIET);
  1124. String nonce = getPushCertificateParser().getAdvertiseNonce();
  1125. if (nonce != null) {
  1126. adv.advertiseCapability(nonce);
  1127. }
  1128. if (db.getRefDatabase().performsAtomicTransactions())
  1129. adv.advertiseCapability(CAPABILITY_ATOMIC);
  1130. if (allowOfsDelta)
  1131. adv.advertiseCapability(CAPABILITY_OFS_DELTA);
  1132. if (allowPushOptions) {
  1133. adv.advertiseCapability(CAPABILITY_PUSH_OPTIONS);
  1134. }
  1135. adv.advertiseCapability(OPTION_AGENT, UserAgent.get());
  1136. adv.send(getAdvertisedOrDefaultRefs().values());
  1137. for (ObjectId obj : advertisedHaves)
  1138. adv.advertiseHave(obj);
  1139. if (adv.isEmpty())
  1140. adv.advertiseId(ObjectId.zeroId(), "capabilities^{}"); //$NON-NLS-1$
  1141. adv.end();
  1142. }
  1143. /**
  1144. * Returns the statistics on the received pack if available. This should be
  1145. * called after {@link #receivePack} is called.
  1146. *
  1147. * @return ReceivedPackStatistics
  1148. * @since 4.6
  1149. */
  1150. @Nullable
  1151. public ReceivedPackStatistics getReceivedPackStatistics() {
  1152. return stats;
  1153. }
  1154. /**
  1155. * Receive a list of commands from the input.
  1156. *
  1157. * @throws java.io.IOException
  1158. */
  1159. protected void recvCommands() throws IOException {
  1160. PacketLineIn pck = maxCommandBytes > 0
  1161. ? new PacketLineIn(rawIn, maxCommandBytes)
  1162. : pckIn;
  1163. PushCertificateParser certParser = getPushCertificateParser();
  1164. boolean firstPkt = true;
  1165. try {
  1166. for (;;) {
  1167. String line;
  1168. try {
  1169. line = pck.readString();
  1170. } catch (EOFException eof) {
  1171. if (commands.isEmpty())
  1172. return;
  1173. throw eof;
  1174. }
  1175. if (PacketLineIn.isEnd(line)) {
  1176. break;
  1177. }
  1178. if (line.length() >= 48 && line.startsWith("shallow ")) { //$NON-NLS-1$
  1179. parseShallow(line.substring(8, 48));
  1180. continue;
  1181. }
  1182. if (firstPkt) {
  1183. firstPkt = false;
  1184. FirstCommand firstLine = FirstCommand.fromLine(line);
  1185. enabledCapabilities = firstLine.getCapabilities();
  1186. line = firstLine.getLine();
  1187. enableCapabilities();
  1188. if (line.equals(GitProtocolConstants.OPTION_PUSH_CERT)) {
  1189. certParser.receiveHeader(pck, !isBiDirectionalPipe());
  1190. continue;
  1191. }
  1192. }
  1193. if (line.equals(PushCertificateParser.BEGIN_SIGNATURE)) {
  1194. certParser.receiveSignature(pck);
  1195. continue;
  1196. }
  1197. ReceiveCommand cmd = parseCommand(line);
  1198. if (cmd.getRefName().equals(Constants.HEAD)) {
  1199. cmd.setResult(Result.REJECTED_CURRENT_BRANCH);
  1200. } else {
  1201. cmd.setRef(refs.get(cmd.getRefName()));
  1202. }
  1203. commands.add(cmd);
  1204. if (certParser.enabled()) {
  1205. certParser.addCommand(cmd);
  1206. }
  1207. }
  1208. pushCert = certParser.build();
  1209. if (hasCommands()) {
  1210. readPostCommands(pck);
  1211. }
  1212. } catch (PackProtocolException e) {
  1213. discardCommands();
  1214. fatalError(e.getMessage());
  1215. throw e;
  1216. } catch (InputOverLimitIOException e) {
  1217. String msg = JGitText.get().tooManyCommands;
  1218. discardCommands();
  1219. fatalError(msg);
  1220. throw new PackProtocolException(msg);
  1221. }
  1222. }
  1223. private void discardCommands() {
  1224. if (sideBand) {
  1225. long max = maxDiscardBytes;
  1226. if (max < 0) {
  1227. max = Math.max(3 * maxCommandBytes, 3L << 20);
  1228. }
  1229. try {
  1230. new PacketLineIn(rawIn, max).discardUntilEnd();
  1231. } catch (IOException e) {
  1232. // Ignore read failures attempting to discard.
  1233. }
  1234. }
  1235. }
  1236. private void parseShallow(String idStr) throws PackProtocolException {
  1237. ObjectId id;
  1238. try {
  1239. id = ObjectId.fromString(idStr);
  1240. } catch (InvalidObjectIdException e) {
  1241. throw new PackProtocolException(e.getMessage(), e);
  1242. }
  1243. clientShallowCommits.add(id);
  1244. }
  1245. static ReceiveCommand parseCommand(String line) throws PackProtocolException {
  1246. if (line == null || line.length() < 83) {
  1247. throw new PackProtocolException(
  1248. JGitText.get().errorInvalidProtocolWantedOldNewRef);
  1249. }
  1250. String oldStr = line.substring(0, 40);
  1251. String newStr = line.substring(41, 81);
  1252. ObjectId oldId, newId;
  1253. try {
  1254. oldId = ObjectId.fromString(oldStr);
  1255. newId = ObjectId.fromString(newStr);
  1256. } catch (InvalidObjectIdException e) {
  1257. throw new PackProtocolException(
  1258. JGitText.get().errorInvalidProtocolWantedOldNewRef, e);
  1259. }
  1260. String name = line.substring(82);
  1261. if (!Repository.isValidRefName(name)) {
  1262. throw new PackProtocolException(
  1263. JGitText.get().errorInvalidProtocolWantedOldNewRef);
  1264. }
  1265. return new ReceiveCommand(oldId, newId, name);
  1266. }
  1267. /**
  1268. * @param in
  1269. * request stream.
  1270. * @throws IOException
  1271. * request line cannot be read.
  1272. */
  1273. void readPostCommands(PacketLineIn in) throws IOException {
  1274. // Do nothing by default.
  1275. }
  1276. /**
  1277. * Enable capabilities based on a previously read capabilities line.
  1278. */
  1279. protected void enableCapabilities() {
  1280. sideBand = isCapabilityEnabled(CAPABILITY_SIDE_BAND_64K);
  1281. quiet = allowQuiet && isCapabilityEnabled(CAPABILITY_QUIET);
  1282. if (sideBand) {
  1283. OutputStream out = rawOut;
  1284. rawOut = new SideBandOutputStream(CH_DATA, MAX_BUF, out);
  1285. msgOut = new SideBandOutputStream(CH_PROGRESS, MAX_BUF, out);
  1286. errOut = new SideBandOutputStream(CH_ERROR, MAX_BUF, out);
  1287. pckOut = new PacketLineOut(rawOut);
  1288. pckOut.setFlushOnEnd(false);
  1289. }
  1290. }
  1291. /**
  1292. * Check if the peer requested a capability.
  1293. *
  1294. * @param name
  1295. * protocol name identifying the capability.
  1296. * @return true if the peer requested the capability to be enabled.
  1297. */
  1298. protected boolean isCapabilityEnabled(String name) {
  1299. return enabledCapabilities.contains(name);
  1300. }
  1301. void checkRequestWasRead() {
  1302. if (enabledCapabilities == null)
  1303. throw new RequestNotYetReadException();
  1304. }
  1305. /**
  1306. * Whether a pack is expected based on the list of commands.
  1307. *
  1308. * @return {@code true} if a pack is expected based on the list of commands.
  1309. */
  1310. protected boolean needPack() {
  1311. for (ReceiveCommand cmd : commands) {
  1312. if (cmd.getType() != ReceiveCommand.Type.DELETE)
  1313. return true;
  1314. }
  1315. return false;
  1316. }
  1317. /**
  1318. * Receive a pack from the input and store it in the repository.
  1319. *
  1320. * @throws IOException
  1321. * an error occurred reading or indexing the pack.
  1322. */
  1323. private void receivePack() throws IOException {
  1324. // It might take the client a while to pack the objects it needs
  1325. // to send to us. We should increase our timeout so we don't
  1326. // abort while the client is computing.
  1327. //
  1328. if (timeoutIn != null)
  1329. timeoutIn.setTimeout(10 * timeout * 1000);
  1330. ProgressMonitor receiving = NullProgressMonitor.INSTANCE;
  1331. ProgressMonitor resolving = NullProgressMonitor.INSTANCE;
  1332. if (sideBand && !quiet)
  1333. resolving = new SideBandProgressMonitor(msgOut);
  1334. try (ObjectInserter ins = db.newObjectInserter()) {
  1335. String lockMsg = "jgit receive-pack"; //$NON-NLS-1$
  1336. if (getRefLogIdent() != null)
  1337. lockMsg += " from " + getRefLogIdent().toExternalString(); //$NON-NLS-1$
  1338. parser = ins.newPackParser(packInputStream());
  1339. parser.setAllowThin(true);
  1340. parser.setNeedNewObjectIds(checkReferencedIsReachable);
  1341. parser.setNeedBaseObjectIds(checkReferencedIsReachable);
  1342. parser.setCheckEofAfterPackFooter(!biDirectionalPipe
  1343. && !isExpectDataAfterPackFooter());
  1344. parser.setExpectDataAfterPackFooter(isExpectDataAfterPackFooter());
  1345. parser.setObjectChecker(objectChecker);
  1346. parser.setLockMessage(lockMsg);
  1347. parser.setMaxObjectSizeLimit(maxObjectSizeLimit);
  1348. packLock = parser.parse(receiving, resolving);
  1349. packSize = Long.valueOf(parser.getPackSize());
  1350. stats = parser.getReceivedPackStatistics();
  1351. ins.flush();
  1352. }
  1353. if (timeoutIn != null)
  1354. timeoutIn.setTimeout(timeout * 1000);
  1355. }
  1356. private InputStream packInputStream() {
  1357. InputStream packIn = rawIn;
  1358. if (maxPackSizeLimit >= 0) {
  1359. packIn = new LimitedInputStream(packIn, maxPackSizeLimit) {
  1360. @Override
  1361. protected void limitExceeded() throws TooLargePackException {
  1362. throw new TooLargePackException(limit);
  1363. }
  1364. };
  1365. }
  1366. return packIn;
  1367. }
  1368. private boolean needCheckConnectivity() {
  1369. return isCheckReceivedObjects()
  1370. || isCheckReferencedObjectsAreReachable()
  1371. || !getClientShallowCommits().isEmpty();
  1372. }
  1373. private void checkSubmodules()
  1374. throws IOException {
  1375. ObjectDatabase odb = db.getObjectDatabase();
  1376. if (objectChecker == null) {
  1377. return;
  1378. }
  1379. for (GitmoduleEntry entry : objectChecker.getGitsubmodules()) {
  1380. AnyObjectId blobId = entry.getBlobId();
  1381. ObjectLoader blob = odb.open(blobId, Constants.OBJ_BLOB);
  1382. try {
  1383. SubmoduleValidator.assertValidGitModulesFile(
  1384. new String(blob.getBytes(), UTF_8));
  1385. } catch (LargeObjectException | SubmoduleValidationException e) {
  1386. throw new IOException(e);
  1387. }
  1388. }
  1389. }
  1390. private void checkConnectivity() throws IOException {
  1391. ObjectIdSubclassMap<ObjectId> baseObjects = null;
  1392. ObjectIdSubclassMap<ObjectId> providedObjects = null;
  1393. ProgressMonitor checking = NullProgressMonitor.INSTANCE;
  1394. if (sideBand && !quiet) {
  1395. SideBandProgressMonitor m = new SideBandProgressMonitor(msgOut);
  1396. m.setDelayStart(750, TimeUnit.MILLISECONDS);
  1397. checking = m;
  1398. }
  1399. if (checkReferencedIsReachable) {
  1400. baseObjects = parser.getBaseObjectIds();
  1401. providedObjects = parser.getNewObjectIds();
  1402. }
  1403. parser = null;
  1404. try (ObjectWalk ow = new ObjectWalk(db)) {
  1405. if (baseObjects != null) {
  1406. ow.sort(RevSort.TOPO);
  1407. if (!baseObjects.isEmpty())
  1408. ow.sort(RevSort.BOUNDARY, true);
  1409. }
  1410. for (ReceiveCommand cmd : commands) {
  1411. if (cmd.getResult() != Result.NOT_ATTEMPTED)
  1412. continue;
  1413. if (cmd.getType() == ReceiveCommand.Type.DELETE)
  1414. continue;
  1415. ow.markStart(ow.parseAny(cmd.getNewId()));
  1416. }
  1417. for (ObjectId have : advertisedHaves) {
  1418. RevObject o = ow.parseAny(have);
  1419. ow.markUninteresting(o);
  1420. if (baseObjects != null && !baseObjects.isEmpty()) {
  1421. o = ow.peel(o);
  1422. if (o instanceof RevCommit)
  1423. o = ((RevCommit) o).getTree();
  1424. if (o instanceof RevTree)
  1425. ow.markUninteresting(o);
  1426. }
  1427. }
  1428. checking.beginTask(JGitText.get().countingObjects,
  1429. ProgressMonitor.UNKNOWN);
  1430. RevCommit c;
  1431. while ((c = ow.next()) != null) {
  1432. checking.update(1);
  1433. if (providedObjects != null //
  1434. && !c.has(RevFlag.UNINTERESTING) //
  1435. && !providedObjects.contains(c))
  1436. throw new MissingObjectException(c, Constants.TYPE_COMMIT);
  1437. }
  1438. RevObject o;
  1439. while ((o = ow.nextObject()) != null) {
  1440. checking.update(1);
  1441. if (o.has(RevFlag.UNINTERESTING)) {
  1442. continue;
  1443. }
  1444. if (providedObjects != null) {
  1445. if (providedObjects.contains(o)) {
  1446. continue;
  1447. }
  1448. throw new MissingObjectException(o, o.getType());
  1449. }
  1450. if (o instanceof RevBlob && !db.getObjectDatabase().has(o))
  1451. throw new MissingObjectException(o, Constants.TYPE_BLOB);
  1452. }
  1453. checking.endTask();
  1454. if (baseObjects != null) {
  1455. for (ObjectId id : baseObjects) {
  1456. o = ow.parseAny(id);
  1457. if (!o.has(RevFlag.UNINTERESTING)) {
  1458. throw new MissingObjectException(o, o.getType());
  1459. }
  1460. }
  1461. }
  1462. }
  1463. }
  1464. /**
  1465. * Validate the command list.
  1466. */
  1467. protected void validateCommands() {
  1468. for (ReceiveCommand cmd : commands) {
  1469. final Ref ref = cmd.getRef();
  1470. if (cmd.getResult() != Result.NOT_ATTEMPTED)
  1471. continue;
  1472. RevObject newObj = null;
  1473. if (cmd.getType() == ReceiveCommand.Type.CREATE
  1474. || cmd.getType() == ReceiveCommand.Type.UPDATE) {
  1475. try {
  1476. newObj = walk.parseAny(cmd.getNewId());
  1477. } catch (IOException e) {
  1478. cmd.setResult(Result.REJECTED_MISSING_OBJECT,
  1479. cmd.getNewId().name());
  1480. continue;
  1481. }
  1482. if (cmd.getRefName().startsWith(Constants.R_HEADS)
  1483. && !(newObj instanceof RevCommit)) {
  1484. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1485. JGitText.get().nonCommitToHeads);
  1486. continue;
  1487. }
  1488. }
  1489. if (cmd.getType() == ReceiveCommand.Type.DELETE) {
  1490. if (!isAllowDeletes()) {
  1491. // Deletes are not supported on this repository.
  1492. cmd.setResult(Result.REJECTED_NODELETE);
  1493. continue;
  1494. }
  1495. if (!isAllowBranchDeletes()
  1496. && ref.getName().startsWith(Constants.R_HEADS)) {
  1497. // Branches cannot be deleted, but other refs can.
  1498. cmd.setResult(Result.REJECTED_NODELETE);
  1499. continue;
  1500. }
  1501. }
  1502. if (cmd.getType() == ReceiveCommand.Type.CREATE) {
  1503. if (!isAllowCreates()) {
  1504. cmd.setResult(Result.REJECTED_NOCREATE);
  1505. continue;
  1506. }
  1507. if (ref != null && !isAllowNonFastForwards()) {
  1508. // Creation over an existing ref is certainly not going
  1509. // to be a fast-forward update. We can reject it early.
  1510. //
  1511. cmd.setResult(Result.REJECTED_NONFASTFORWARD);
  1512. continue;
  1513. }
  1514. if (ref != null) {
  1515. // A well behaved client shouldn't have sent us a
  1516. // create command for a ref we advertised to it.
  1517. //
  1518. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1519. JGitText.get().refAlreadyExists);
  1520. continue;
  1521. }
  1522. }
  1523. if (cmd.getType() == ReceiveCommand.Type.DELETE && ref != null) {
  1524. ObjectId id = ref.getObjectId();
  1525. if (id == null) {
  1526. id = ObjectId.zeroId();
  1527. }
  1528. if (!ObjectId.zeroId().equals(cmd.getOldId())
  1529. && !id.equals(cmd.getOldId())) {
  1530. // Delete commands can be sent with the old id matching our
  1531. // advertised value, *OR* with the old id being 0{40}. Any
  1532. // other requested old id is invalid.
  1533. //
  1534. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1535. JGitText.get().invalidOldIdSent);
  1536. continue;
  1537. }
  1538. }
  1539. if (cmd.getType() == ReceiveCommand.Type.UPDATE) {
  1540. if (ref == null) {
  1541. // The ref must have been advertised in order to be updated.
  1542. //
  1543. cmd.setResult(Result.REJECTED_OTHER_REASON, JGitText.get().noSuchRef);
  1544. continue;
  1545. }
  1546. ObjectId id = ref.getObjectId();
  1547. if (id == null) {
  1548. // We cannot update unborn branch
  1549. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1550. JGitText.get().cannotUpdateUnbornBranch);
  1551. continue;
  1552. }
  1553. if (!id.equals(cmd.getOldId())) {
  1554. // A properly functioning client will send the same
  1555. // object id we advertised.
  1556. //
  1557. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1558. JGitText.get().invalidOldIdSent);
  1559. continue;
  1560. }
  1561. // Is this possibly a non-fast-forward style update?
  1562. //
  1563. RevObject oldObj;
  1564. try {
  1565. oldObj = walk.parseAny(cmd.getOldId());
  1566. } catch (IOException e) {
  1567. cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd
  1568. .getOldId().name());
  1569. continue;
  1570. }
  1571. if (oldObj instanceof RevCommit && newObj instanceof RevCommit) {
  1572. try {
  1573. if (walk.isMergedInto((RevCommit) oldObj,
  1574. (RevCommit) newObj))
  1575. cmd.setTypeFastForwardUpdate();
  1576. else
  1577. cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
  1578. } catch (MissingObjectException e) {
  1579. cmd.setResult(Result.REJECTED_MISSING_OBJECT, e
  1580. .getMessage());
  1581. } catch (IOException e) {
  1582. cmd.setResult(Result.REJECTED_OTHER_REASON);
  1583. }
  1584. } else {
  1585. cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
  1586. }
  1587. if (cmd.getType() == ReceiveCommand.Type.UPDATE_NONFASTFORWARD
  1588. && !isAllowNonFastForwards()) {
  1589. cmd.setResult(Result.REJECTED_NONFASTFORWARD);
  1590. continue;
  1591. }
  1592. }
  1593. if (!cmd.getRefName().startsWith(Constants.R_REFS)
  1594. || !Repository.isValidRefName(cmd.getRefName())) {
  1595. cmd.setResult(Result.REJECTED_OTHER_REASON, JGitText.get().funnyRefname);
  1596. }
  1597. }
  1598. }
  1599. /**
  1600. * Whether any commands have been rejected so far.
  1601. *
  1602. * @return if any commands have been rejected so far.
  1603. * @since 3.6
  1604. */
  1605. protected boolean anyRejects() {
  1606. for (ReceiveCommand cmd : commands) {
  1607. if (cmd.getResult() != Result.NOT_ATTEMPTED && cmd.getResult() != Result.OK)
  1608. return true;
  1609. }
  1610. return false;
  1611. }
  1612. /**
  1613. * Set the result to fail for any command that was not processed yet.
  1614. *
  1615. * @since 3.6
  1616. */
  1617. protected void failPendingCommands() {
  1618. ReceiveCommand.abort(commands);
  1619. }
  1620. /**
  1621. * Filter the list of commands according to result.
  1622. *
  1623. * @param want
  1624. * desired status to filter by.
  1625. * @return a copy of the command list containing only those commands with the
  1626. * desired status.
  1627. */
  1628. protected List<ReceiveCommand> filterCommands(Result want) {
  1629. return ReceiveCommand.filter(commands, want);
  1630. }
  1631. /**
  1632. * Execute commands to update references.
  1633. */
  1634. protected void executeCommands() {
  1635. List<ReceiveCommand> toApply = filterCommands(Result.NOT_ATTEMPTED);
  1636. if (toApply.isEmpty())
  1637. return;
  1638. ProgressMonitor updating = NullProgressMonitor.INSTANCE;
  1639. if (sideBand) {
  1640. SideBandProgressMonitor pm = new SideBandProgressMonitor(msgOut);
  1641. pm.setDelayStart(250, TimeUnit.MILLISECONDS);
  1642. updating = pm;
  1643. }
  1644. BatchRefUpdate batch = db.getRefDatabase().newBatchUpdate();
  1645. batch.setAllowNonFastForwards(isAllowNonFastForwards());
  1646. batch.setAtomic(isAtomic());
  1647. batch.setRefLogIdent(getRefLogIdent());
  1648. batch.setRefLogMessage("push", true); //$NON-NLS-1$
  1649. batch.addCommand(toApply);
  1650. try {
  1651. batch.setPushCertificate(getPushCertificate());
  1652. batch.execute(walk, updating);
  1653. } catch (IOException err) {
  1654. for (ReceiveCommand cmd : toApply) {
  1655. if (cmd.getResult() == Result.NOT_ATTEMPTED)
  1656. cmd.reject(err);
  1657. }
  1658. }
  1659. }
  1660. /**
  1661. * Send a status report.
  1662. *
  1663. * @param forClient
  1664. * true if this report is for a Git client, false if it is for an
  1665. * end-user.
  1666. * @param unpackError
  1667. * an error that occurred during unpacking, or {@code null}
  1668. * @param out
  1669. * the reporter for sending the status strings.
  1670. * @throws java.io.IOException
  1671. * an error occurred writing the status report.
  1672. */
  1673. protected void sendStatusReport(final boolean forClient,
  1674. final Throwable unpackError, final Reporter out) throws IOException {
  1675. if (unpackError != null) {
  1676. out.sendString("unpack error " + unpackError.getMessage()); //$NON-NLS-1$
  1677. if (forClient) {
  1678. for (ReceiveCommand cmd : commands) {
  1679. out.sendString("ng " + cmd.getRefName() //$NON-NLS-1$
  1680. + " n/a (unpacker error)"); //$NON-NLS-1$
  1681. }
  1682. }
  1683. return;
  1684. }
  1685. if (forClient)
  1686. out.sendString("unpack ok"); //$NON-NLS-1$
  1687. for (ReceiveCommand cmd : commands) {
  1688. if (cmd.getResult() == Result.OK) {
  1689. if (forClient)
  1690. out.sendString("ok " + cmd.getRefName()); //$NON-NLS-1$
  1691. continue;
  1692. }
  1693. final StringBuilder r = new StringBuilder();
  1694. if (forClient)
  1695. r.append("ng ").append(cmd.getRefName()).append(" "); //$NON-NLS-1$ //$NON-NLS-2$
  1696. else
  1697. r.append(" ! [rejected] ").append(cmd.getRefName()).append(" ("); //$NON-NLS-1$ //$NON-NLS-2$
  1698. switch (cmd.getResult()) {
  1699. case NOT_ATTEMPTED:
  1700. r.append("server bug; ref not processed"); //$NON-NLS-1$
  1701. break;
  1702. case REJECTED_NOCREATE:
  1703. r.append("creation prohibited"); //$NON-NLS-1$
  1704. break;
  1705. case REJECTED_NODELETE:
  1706. r.append("deletion prohibited"); //$NON-NLS-1$
  1707. break;
  1708. case REJECTED_NONFASTFORWARD:
  1709. r.append("non-fast forward"); //$NON-NLS-1$
  1710. break;
  1711. case REJECTED_CURRENT_BRANCH:
  1712. r.append("branch is currently checked out"); //$NON-NLS-1$
  1713. break;
  1714. case REJECTED_MISSING_OBJECT:
  1715. if (cmd.getMessage() == null)
  1716. r.append("missing object(s)"); //$NON-NLS-1$
  1717. else if (cmd.getMessage().length() == Constants.OBJECT_ID_STRING_LENGTH) {
  1718. r.append("object "); //$NON-NLS-1$
  1719. r.append(cmd.getMessage());
  1720. r.append(" missing"); //$NON-NLS-1$
  1721. } else
  1722. r.append(cmd.getMessage());
  1723. break;
  1724. case REJECTED_OTHER_REASON:
  1725. if (cmd.getMessage() == null)
  1726. r.append("unspecified reason"); //$NON-NLS-1$
  1727. else
  1728. r.append(cmd.getMessage());
  1729. break;
  1730. case LOCK_FAILURE:
  1731. r.append("failed to lock"); //$NON-NLS-1$
  1732. break;
  1733. case OK:
  1734. // We shouldn't have reached this case (see 'ok' case above).
  1735. continue;
  1736. }
  1737. if (!forClient)
  1738. r.append(")"); //$NON-NLS-1$
  1739. out.sendString(r.toString());
  1740. }
  1741. }
  1742. /**
  1743. * Close and flush (if necessary) the underlying streams.
  1744. *
  1745. * @throws java.io.IOException
  1746. */
  1747. protected void close() throws IOException {
  1748. if (sideBand) {
  1749. // If we are using side band, we need to send a final
  1750. // flush-pkt to tell the remote peer the side band is
  1751. // complete and it should stop decoding. We need to
  1752. // use the original output stream as rawOut is now the
  1753. // side band data channel.
  1754. //
  1755. ((SideBandOutputStream) msgOut).flushBuffer();
  1756. ((SideBandOutputStream) rawOut).flushBuffer();
  1757. PacketLineOut plo = new PacketLineOut(origOut);
  1758. plo.setFlushOnEnd(false);
  1759. plo.end();
  1760. }
  1761. if (biDirectionalPipe) {
  1762. // If this was a native git connection, flush the pipe for
  1763. // the caller. For smart HTTP we don't do this flush and
  1764. // instead let the higher level HTTP servlet code do it.
  1765. //
  1766. if (!sideBand && msgOut != null)
  1767. msgOut.flush();
  1768. rawOut.flush();
  1769. }
  1770. }
  1771. /**
  1772. * Release any resources used by this object.
  1773. *
  1774. * @throws java.io.IOException
  1775. * the pack could not be unlocked.
  1776. */
  1777. protected void release() throws IOException {
  1778. walk.close();
  1779. unlockPack();
  1780. timeoutIn = null;
  1781. rawIn = null;
  1782. rawOut = null;
  1783. msgOut = null;
  1784. pckIn = null;
  1785. pckOut = null;
  1786. refs = null;
  1787. // Keep the capabilities. If responses are sent after this release
  1788. // we need to remember at least whether sideband communication has to be
  1789. // used
  1790. commands = null;
  1791. if (timer != null) {
  1792. try {
  1793. timer.terminate();
  1794. } finally {
  1795. timer = null;
  1796. }
  1797. }
  1798. }
  1799. /** Interface for reporting status messages. */
  1800. static abstract class Reporter {
  1801. abstract void sendString(String s) throws IOException;
  1802. }
  1803. }