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

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