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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982
  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.MissingObjectException;
  72. import org.eclipse.jgit.errors.PackProtocolException;
  73. import org.eclipse.jgit.errors.TooLargePackException;
  74. import org.eclipse.jgit.internal.JGitText;
  75. import org.eclipse.jgit.internal.storage.file.PackLock;
  76. import org.eclipse.jgit.internal.submodule.SubmoduleValidator;
  77. import org.eclipse.jgit.lib.AnyObjectId;
  78. import org.eclipse.jgit.lib.BatchRefUpdate;
  79. import org.eclipse.jgit.lib.Config;
  80. import org.eclipse.jgit.lib.Constants;
  81. import org.eclipse.jgit.lib.GitmoduleEntry;
  82. import org.eclipse.jgit.lib.NullProgressMonitor;
  83. import org.eclipse.jgit.lib.ObjectChecker;
  84. import org.eclipse.jgit.lib.ObjectDatabase;
  85. import org.eclipse.jgit.lib.ObjectId;
  86. import org.eclipse.jgit.lib.ObjectIdSubclassMap;
  87. import org.eclipse.jgit.lib.ObjectInserter;
  88. import org.eclipse.jgit.lib.ObjectLoader;
  89. import org.eclipse.jgit.lib.PersonIdent;
  90. import org.eclipse.jgit.lib.ProgressMonitor;
  91. import org.eclipse.jgit.lib.Ref;
  92. import org.eclipse.jgit.lib.Repository;
  93. import org.eclipse.jgit.revwalk.ObjectWalk;
  94. import org.eclipse.jgit.revwalk.RevBlob;
  95. import org.eclipse.jgit.revwalk.RevCommit;
  96. import org.eclipse.jgit.revwalk.RevFlag;
  97. import org.eclipse.jgit.revwalk.RevObject;
  98. import org.eclipse.jgit.revwalk.RevSort;
  99. import org.eclipse.jgit.revwalk.RevTree;
  100. import org.eclipse.jgit.revwalk.RevWalk;
  101. import org.eclipse.jgit.transport.PacketLineIn.InputOverLimitIOException;
  102. import org.eclipse.jgit.transport.ReceiveCommand.Result;
  103. import org.eclipse.jgit.util.io.InterruptTimer;
  104. import org.eclipse.jgit.util.io.LimitedInputStream;
  105. import org.eclipse.jgit.util.io.TimeoutInputStream;
  106. import org.eclipse.jgit.util.io.TimeoutOutputStream;
  107. /**
  108. * Base implementation of the side of a push connection that receives objects.
  109. * <p>
  110. * Contains high-level operations for initializing and closing streams,
  111. * advertising refs, reading commands, and receiving and applying a pack.
  112. * Subclasses compose these operations into full service implementations.
  113. */
  114. public abstract class BaseReceivePack {
  115. /** Data in the first line of a request, the line itself plus capabilities. */
  116. public static class FirstLine {
  117. private final String line;
  118. private final Set<String> capabilities;
  119. /**
  120. * Parse the first line of a receive-pack request.
  121. *
  122. * @param line
  123. * line from the client.
  124. */
  125. public FirstLine(String line) {
  126. final HashSet<String> caps = new HashSet<>();
  127. final int nul = line.indexOf('\0');
  128. if (nul >= 0) {
  129. for (String c : line.substring(nul + 1).split(" ")) //$NON-NLS-1$
  130. caps.add(c);
  131. this.line = line.substring(0, nul);
  132. } else
  133. this.line = line;
  134. this.capabilities = Collections.unmodifiableSet(caps);
  135. }
  136. /** @return non-capabilities part of the line. */
  137. public String getLine() {
  138. return line;
  139. }
  140. /** @return capabilities parsed from the line. */
  141. public Set<String> getCapabilities() {
  142. return capabilities;
  143. }
  144. }
  145. /** Database we write the stored objects into. */
  146. private final Repository db;
  147. /** Revision traversal support over {@link #db}. */
  148. private final RevWalk walk;
  149. /**
  150. * Is the client connection a bi-directional socket or pipe?
  151. * <p>
  152. * If true, this class assumes it can perform multiple read and write cycles
  153. * with the client over the input and output streams. This matches the
  154. * functionality available with a standard TCP/IP connection, or a local
  155. * operating system or in-memory pipe.
  156. * <p>
  157. * If false, this class runs in a read everything then output results mode,
  158. * making it suitable for single round-trip systems RPCs such as HTTP.
  159. */
  160. private boolean biDirectionalPipe = true;
  161. /** Expecting data after the pack footer */
  162. private boolean expectDataAfterPackFooter;
  163. /** Should an incoming transfer validate objects? */
  164. private ObjectChecker objectChecker;
  165. /** Should an incoming transfer permit create requests? */
  166. private boolean allowCreates;
  167. /** Should an incoming transfer permit delete requests? */
  168. private boolean allowAnyDeletes;
  169. private boolean allowBranchDeletes;
  170. /** Should an incoming transfer permit non-fast-forward requests? */
  171. private boolean allowNonFastForwards;
  172. /** Should an incoming transfer permit push options? **/
  173. private boolean allowPushOptions;
  174. /**
  175. * Should the requested ref updates be performed as a single atomic
  176. * transaction?
  177. */
  178. private boolean atomic;
  179. private boolean allowOfsDelta;
  180. private boolean allowQuiet = true;
  181. /** Identity to record action as within the reflog. */
  182. private PersonIdent refLogIdent;
  183. /** Hook used while advertising the refs to the client. */
  184. private AdvertiseRefsHook advertiseRefsHook;
  185. /** Filter used while advertising the refs to the client. */
  186. private RefFilter refFilter;
  187. /** Timeout in seconds to wait for client interaction. */
  188. private int timeout;
  189. /** Timer to manage {@link #timeout}. */
  190. private InterruptTimer timer;
  191. private TimeoutInputStream timeoutIn;
  192. // Original stream passed to init(), since rawOut may be wrapped in a
  193. // sideband.
  194. private OutputStream origOut;
  195. /** Raw input stream. */
  196. protected InputStream rawIn;
  197. /** Raw output stream. */
  198. protected OutputStream rawOut;
  199. /** Optional message output stream. */
  200. protected OutputStream msgOut;
  201. private SideBandOutputStream errOut;
  202. /** Packet line input stream around {@link #rawIn}. */
  203. protected PacketLineIn pckIn;
  204. /** Packet line output stream around {@link #rawOut}. */
  205. protected PacketLineOut pckOut;
  206. private final MessageOutputWrapper msgOutWrapper = new MessageOutputWrapper();
  207. private PackParser parser;
  208. /** The refs we advertised as existing at the start of the connection. */
  209. private Map<String, Ref> refs;
  210. /** All SHA-1s shown to the client, which can be possible edges. */
  211. private Set<ObjectId> advertisedHaves;
  212. /** Capabilities requested by the client. */
  213. private Set<String> enabledCapabilities;
  214. String userAgent;
  215. private Set<ObjectId> clientShallowCommits;
  216. private List<ReceiveCommand> commands;
  217. private long maxCommandBytes;
  218. private long maxDiscardBytes;
  219. private StringBuilder advertiseError;
  220. /** If {@link BasePackPushConnection#CAPABILITY_SIDE_BAND_64K} is enabled. */
  221. private boolean sideBand;
  222. private boolean quiet;
  223. /** Lock around the received pack file, while updating refs. */
  224. private PackLock packLock;
  225. private boolean checkReferencedIsReachable;
  226. /** Git object size limit */
  227. private long maxObjectSizeLimit;
  228. /** Total pack size limit */
  229. private long maxPackSizeLimit = -1;
  230. /** The size of the received pack, including index size */
  231. private Long packSize;
  232. private PushCertificateParser pushCertificateParser;
  233. private SignedPushConfig signedPushConfig;
  234. private PushCertificate pushCert;
  235. private ReceivedPackStatistics stats;
  236. /**
  237. * Get the push certificate used to verify the pusher's identity.
  238. * <p>
  239. * Only valid after commands are read from the wire.
  240. *
  241. * @return the parsed certificate, or null if push certificates are disabled
  242. * or no cert was presented by the client.
  243. * @since 4.1
  244. */
  245. public PushCertificate getPushCertificate() {
  246. return pushCert;
  247. }
  248. /**
  249. * Set the push certificate used to verify the pusher's identity.
  250. * <p>
  251. * Should only be called if reconstructing an instance without going through
  252. * the normal {@link #recvCommands()} flow.
  253. *
  254. * @param cert
  255. * the push certificate to set.
  256. * @since 4.1
  257. */
  258. public void setPushCertificate(PushCertificate cert) {
  259. pushCert = cert;
  260. }
  261. /**
  262. * Create a new pack receive for an open repository.
  263. *
  264. * @param into
  265. * the destination repository.
  266. */
  267. protected BaseReceivePack(Repository into) {
  268. db = into;
  269. walk = new RevWalk(db);
  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. */
  368. public final Repository getRepository() {
  369. return db;
  370. }
  371. /**
  372. * Get the RevWalk instance used by this connection.
  373. *
  374. * @return the RevWalk instance used by this connection.
  375. */
  376. public final RevWalk getRevWalk() {
  377. return walk;
  378. }
  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. */
  385. public final Map<String, Ref> getAdvertisedRefs() {
  386. return refs;
  387. }
  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. */
  405. public void setAdvertisedRefs(Map<String, Ref> allRefs, Set<ObjectId> additionalHaves) {
  406. refs = allRefs != null ? allRefs : db.getAllRefs();
  407. refs = refFilter.filter(refs);
  408. advertisedHaves.clear();
  409. Ref head = refs.get(Constants.HEAD);
  410. if (head != null && head.isSymbolic())
  411. refs.remove(Constants.HEAD);
  412. for (Ref ref : refs.values()) {
  413. if (ref.getObjectId() != null)
  414. advertisedHaves.add(ref.getObjectId());
  415. }
  416. if (additionalHaves != null)
  417. advertisedHaves.addAll(additionalHaves);
  418. else
  419. advertisedHaves.addAll(db.getAdditionalHaves());
  420. }
  421. /**
  422. * Get objects advertised to the client.
  423. *
  424. * @return the set of objects advertised to the as present in this repository,
  425. * or null if {@link #setAdvertisedRefs(Map, Set)} has not been called
  426. * yet.
  427. */
  428. public final Set<ObjectId> getAdvertisedObjects() {
  429. return advertisedHaves;
  430. }
  431. /**
  432. * Whether this instance will validate all referenced, but not supplied by
  433. * the client, objects are reachable from another reference.
  434. *
  435. * @return true if this instance will validate all referenced, but not
  436. * supplied by the client, objects are reachable from another
  437. * reference.
  438. */
  439. public boolean isCheckReferencedObjectsAreReachable() {
  440. return checkReferencedIsReachable;
  441. }
  442. /**
  443. * Validate all referenced but not supplied objects are reachable.
  444. * <p>
  445. * If enabled, this instance will verify that references to objects not
  446. * contained within the received pack are already reachable through at least
  447. * one other reference displayed as part of {@link #getAdvertisedRefs()}.
  448. * <p>
  449. * This feature is useful when the application doesn't trust the client to
  450. * not provide a forged SHA-1 reference to an object, in an attempt to
  451. * access parts of the DAG that they aren't allowed to see and which have
  452. * been hidden from them via the configured
  453. * {@link org.eclipse.jgit.transport.AdvertiseRefsHook} or
  454. * {@link org.eclipse.jgit.transport.RefFilter}.
  455. * <p>
  456. * Enabling this feature may imply at least some, if not all, of the same
  457. * functionality performed by {@link #setCheckReceivedObjects(boolean)}.
  458. * Applications are encouraged to enable both features, if desired.
  459. *
  460. * @param b
  461. * {@code true} to enable the additional check.
  462. */
  463. public void setCheckReferencedObjectsAreReachable(boolean b) {
  464. this.checkReferencedIsReachable = b;
  465. }
  466. /**
  467. * Whether this class expects a bi-directional pipe opened between the
  468. * client and itself.
  469. *
  470. * @return true if this class expects a bi-directional pipe opened between
  471. * the client and itself. The default is true.
  472. */
  473. public boolean isBiDirectionalPipe() {
  474. return biDirectionalPipe;
  475. }
  476. /**
  477. * Whether this class will assume the socket is a fully bidirectional pipe
  478. * between the two peers and takes advantage of that by first transmitting
  479. * the known refs, then waiting to read commands.
  480. *
  481. * @param twoWay
  482. * if true, this class will assume the socket is a fully
  483. * bidirectional pipe between the two peers and takes advantage
  484. * of that by first transmitting the known refs, then waiting to
  485. * read commands. If false, this class assumes it must read the
  486. * commands before writing output and does not perform the
  487. * initial advertising.
  488. */
  489. public void setBiDirectionalPipe(boolean twoWay) {
  490. biDirectionalPipe = twoWay;
  491. }
  492. /**
  493. * Whether there is data expected after the pack footer.
  494. *
  495. * @return {@code true} if there is data expected after the pack footer.
  496. */
  497. public boolean isExpectDataAfterPackFooter() {
  498. return expectDataAfterPackFooter;
  499. }
  500. /**
  501. * Whether there is additional data in InputStream after pack.
  502. *
  503. * @param e
  504. * {@code true} if there is additional data in InputStream after
  505. * pack.
  506. */
  507. public void setExpectDataAfterPackFooter(boolean e) {
  508. expectDataAfterPackFooter = e;
  509. }
  510. /**
  511. * Whether this instance will verify received objects are formatted
  512. * correctly.
  513. *
  514. * @return {@code true} if this instance will verify received objects are
  515. * formatted correctly. Validating objects requires more CPU time on
  516. * this side of the connection.
  517. */
  518. public boolean isCheckReceivedObjects() {
  519. return objectChecker != null;
  520. }
  521. /**
  522. * Whether to enable checking received objects
  523. *
  524. * @param check
  525. * {@code true} to enable checking received objects; false to
  526. * assume all received objects are valid.
  527. * @see #setObjectChecker(ObjectChecker)
  528. */
  529. public void setCheckReceivedObjects(boolean check) {
  530. if (check && objectChecker == null)
  531. setObjectChecker(new ObjectChecker());
  532. else if (!check && objectChecker != null)
  533. setObjectChecker(null);
  534. }
  535. /**
  536. * Set the object checking instance to verify each received object with
  537. *
  538. * @param impl
  539. * if non-null the object checking instance to verify each
  540. * received object with; null to disable object checking.
  541. * @since 3.4
  542. */
  543. public void setObjectChecker(ObjectChecker impl) {
  544. objectChecker = impl;
  545. }
  546. /**
  547. * Whether the client can request refs to be created.
  548. *
  549. * @return {@code true} if the client can request refs to be created.
  550. */
  551. public boolean isAllowCreates() {
  552. return allowCreates;
  553. }
  554. /**
  555. * Whether to permit create ref commands to be processed.
  556. *
  557. * @param canCreate
  558. * {@code true} to permit create ref commands to be processed.
  559. */
  560. public void setAllowCreates(boolean canCreate) {
  561. allowCreates = canCreate;
  562. }
  563. /**
  564. * Whether the client can request refs to be deleted.
  565. *
  566. * @return {@code true} if the client can request refs to be deleted.
  567. */
  568. public boolean isAllowDeletes() {
  569. return allowAnyDeletes;
  570. }
  571. /**
  572. * Whether to permit delete ref commands to be processed.
  573. *
  574. * @param canDelete
  575. * {@code true} to permit delete ref commands to be processed.
  576. */
  577. public void setAllowDeletes(boolean canDelete) {
  578. allowAnyDeletes = canDelete;
  579. }
  580. /**
  581. * Whether the client can delete from {@code refs/heads/}.
  582. *
  583. * @return {@code true} if the client can delete from {@code refs/heads/}.
  584. * @since 3.6
  585. */
  586. public boolean isAllowBranchDeletes() {
  587. return allowBranchDeletes;
  588. }
  589. /**
  590. * Configure whether to permit deletion of branches from the
  591. * {@code refs/heads/} namespace.
  592. *
  593. * @param canDelete
  594. * {@code true} to permit deletion of branches from the
  595. * {@code refs/heads/} namespace.
  596. * @since 3.6
  597. */
  598. public void setAllowBranchDeletes(boolean canDelete) {
  599. allowBranchDeletes = canDelete;
  600. }
  601. /**
  602. * Whether the client can request non-fast-forward updates of a ref,
  603. * possibly making objects unreachable.
  604. *
  605. * @return {@code true} if the client can request non-fast-forward updates
  606. * of a ref, possibly making objects unreachable.
  607. */
  608. public boolean isAllowNonFastForwards() {
  609. return allowNonFastForwards;
  610. }
  611. /**
  612. * Configure whether to permit the client to ask for non-fast-forward
  613. * updates of an existing ref.
  614. *
  615. * @param canRewind
  616. * {@code true} to permit the client to ask for non-fast-forward
  617. * updates of an existing ref.
  618. */
  619. public void setAllowNonFastForwards(boolean canRewind) {
  620. allowNonFastForwards = canRewind;
  621. }
  622. /**
  623. * Whether the client's commands should be performed as a single atomic
  624. * transaction.
  625. *
  626. * @return {@code true} if the client's commands should be performed as a
  627. * single atomic transaction.
  628. * @since 4.4
  629. */
  630. public boolean isAtomic() {
  631. return atomic;
  632. }
  633. /**
  634. * Configure whether to perform the client's commands as a single atomic
  635. * transaction.
  636. *
  637. * @param atomic
  638. * {@code true} to perform the client's commands as a single
  639. * atomic transaction.
  640. * @since 4.4
  641. */
  642. public void setAtomic(boolean atomic) {
  643. this.atomic = atomic;
  644. }
  645. /**
  646. * Get identity of the user making the changes in the reflog.
  647. *
  648. * @return identity of the user making the changes in the reflog.
  649. */
  650. public PersonIdent getRefLogIdent() {
  651. return refLogIdent;
  652. }
  653. /**
  654. * Set the identity of the user appearing in the affected reflogs.
  655. * <p>
  656. * The timestamp portion of the identity is ignored. A new identity with the
  657. * current timestamp will be created automatically when the updates occur
  658. * and the log records are written.
  659. *
  660. * @param pi
  661. * identity of the user. If null the identity will be
  662. * automatically determined based on the repository
  663. * configuration.
  664. */
  665. public void setRefLogIdent(PersonIdent pi) {
  666. refLogIdent = pi;
  667. }
  668. /**
  669. * Get the hook used while advertising the refs to the client
  670. *
  671. * @return the hook used while advertising the refs to the client
  672. */
  673. public AdvertiseRefsHook getAdvertiseRefsHook() {
  674. return advertiseRefsHook;
  675. }
  676. /**
  677. * Get the filter used while advertising the refs to the client
  678. *
  679. * @return the filter used while advertising the refs to the client
  680. */
  681. public RefFilter getRefFilter() {
  682. return refFilter;
  683. }
  684. /**
  685. * Set the hook used while advertising the refs to the client.
  686. * <p>
  687. * If the {@link org.eclipse.jgit.transport.AdvertiseRefsHook} chooses to
  688. * call {@link #setAdvertisedRefs(Map,Set)}, only refs set by this hook
  689. * <em>and</em> selected by the {@link org.eclipse.jgit.transport.RefFilter}
  690. * will be shown to the client. Clients may still attempt to create or
  691. * update a reference not advertised by the configured
  692. * {@link org.eclipse.jgit.transport.AdvertiseRefsHook}. These attempts
  693. * should be rejected by a matching
  694. * {@link org.eclipse.jgit.transport.PreReceiveHook}.
  695. *
  696. * @param advertiseRefsHook
  697. * the hook; may be null to show all refs.
  698. */
  699. public void setAdvertiseRefsHook(AdvertiseRefsHook advertiseRefsHook) {
  700. if (advertiseRefsHook != null)
  701. this.advertiseRefsHook = advertiseRefsHook;
  702. else
  703. this.advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  704. }
  705. /**
  706. * Set the filter used while advertising the refs to the client.
  707. * <p>
  708. * Only refs allowed by this filter will be shown to the client. The filter
  709. * is run against the refs specified by the
  710. * {@link org.eclipse.jgit.transport.AdvertiseRefsHook} (if applicable).
  711. *
  712. * @param refFilter
  713. * the filter; may be null to show all refs.
  714. */
  715. public void setRefFilter(RefFilter refFilter) {
  716. this.refFilter = refFilter != null ? refFilter : RefFilter.DEFAULT;
  717. }
  718. /**
  719. * Get timeout (in seconds) before aborting an IO operation.
  720. *
  721. * @return timeout (in seconds) before aborting an IO operation.
  722. */
  723. public int getTimeout() {
  724. return timeout;
  725. }
  726. /**
  727. * Set the timeout before willing to abort an IO call.
  728. *
  729. * @param seconds
  730. * number of seconds to wait (with no data transfer occurring)
  731. * before aborting an IO read or write operation with the
  732. * connected client.
  733. */
  734. public void setTimeout(int seconds) {
  735. timeout = seconds;
  736. }
  737. /**
  738. * Set the maximum number of command bytes to read from the client.
  739. *
  740. * @param limit
  741. * command limit in bytes; if 0 there is no limit.
  742. * @since 4.7
  743. */
  744. public void setMaxCommandBytes(long limit) {
  745. maxCommandBytes = limit;
  746. }
  747. /**
  748. * Set the maximum number of command bytes to discard from the client.
  749. * <p>
  750. * Discarding remaining bytes allows this instance to consume the rest of
  751. * the command block and send a human readable over-limit error via the
  752. * side-band channel. If the client sends an excessive number of bytes this
  753. * limit kicks in and the instance disconnects, resulting in a non-specific
  754. * 'pipe closed', 'end of stream', or similar generic error at the client.
  755. * <p>
  756. * When the limit is set to {@code -1} the implementation will default to
  757. * the larger of {@code 3 * maxCommandBytes} or {@code 3 MiB}.
  758. *
  759. * @param limit
  760. * discard limit in bytes; if 0 there is no limit; if -1 the
  761. * implementation tries to set a reasonable default.
  762. * @since 4.7
  763. */
  764. public void setMaxCommandDiscardBytes(long limit) {
  765. maxDiscardBytes = limit;
  766. }
  767. /**
  768. * Set the maximum allowed Git object size.
  769. * <p>
  770. * If an object is larger than the given size the pack-parsing will throw an
  771. * exception aborting the receive-pack operation.
  772. *
  773. * @param limit
  774. * the Git object size limit. If zero then there is not limit.
  775. */
  776. public void setMaxObjectSizeLimit(long limit) {
  777. maxObjectSizeLimit = limit;
  778. }
  779. /**
  780. * Set the maximum allowed pack size.
  781. * <p>
  782. * A pack exceeding this size will be rejected.
  783. *
  784. * @param limit
  785. * the pack size limit, in bytes
  786. * @since 3.3
  787. */
  788. public void setMaxPackSizeLimit(long limit) {
  789. if (limit < 0)
  790. throw new IllegalArgumentException(MessageFormat.format(
  791. JGitText.get().receivePackInvalidLimit, Long.valueOf(limit)));
  792. maxPackSizeLimit = limit;
  793. }
  794. /**
  795. * Check whether the client expects a side-band stream.
  796. *
  797. * @return true if the client has advertised a side-band capability, false
  798. * otherwise.
  799. * @throws org.eclipse.jgit.transport.RequestNotYetReadException
  800. * if the client's request has not yet been read from the wire, so
  801. * we do not know if they expect side-band. Note that the client
  802. * may have already written the request, it just has not been
  803. * read.
  804. */
  805. public boolean isSideBand() throws RequestNotYetReadException {
  806. checkRequestWasRead();
  807. return enabledCapabilities.contains(CAPABILITY_SIDE_BAND_64K);
  808. }
  809. /**
  810. * Whether clients may request avoiding noisy progress messages.
  811. *
  812. * @return true if clients may request avoiding noisy progress messages.
  813. * @since 4.0
  814. */
  815. public boolean isAllowQuiet() {
  816. return allowQuiet;
  817. }
  818. /**
  819. * Configure if clients may request the server skip noisy messages.
  820. *
  821. * @param allow
  822. * true to allow clients to request quiet behavior; false to
  823. * refuse quiet behavior and send messages anyway. This may be
  824. * necessary if processing is slow and the client-server network
  825. * connection can timeout.
  826. * @since 4.0
  827. */
  828. public void setAllowQuiet(boolean allow) {
  829. allowQuiet = allow;
  830. }
  831. /**
  832. * Whether the server supports receiving push options.
  833. *
  834. * @return true if the server supports receiving push options.
  835. * @since 4.5
  836. */
  837. public boolean isAllowPushOptions() {
  838. return allowPushOptions;
  839. }
  840. /**
  841. * Configure if the server supports receiving push options.
  842. *
  843. * @param allow
  844. * true to optionally accept option strings from the client.
  845. * @since 4.5
  846. */
  847. public void setAllowPushOptions(boolean allow) {
  848. allowPushOptions = allow;
  849. }
  850. /**
  851. * True if the client wants less verbose output.
  852. *
  853. * @return true if the client has requested the server to be less verbose.
  854. * @throws org.eclipse.jgit.transport.RequestNotYetReadException
  855. * if the client's request has not yet been read from the wire,
  856. * so we do not know if they expect side-band. Note that the
  857. * client may have already written the request, it just has not
  858. * been read.
  859. * @since 4.0
  860. */
  861. public boolean isQuiet() throws RequestNotYetReadException {
  862. checkRequestWasRead();
  863. return quiet;
  864. }
  865. /**
  866. * Set the configuration for push certificate verification.
  867. *
  868. * @param cfg
  869. * new configuration; if this object is null or its {@link
  870. * SignedPushConfig#getCertNonceSeed()} is null, push certificate
  871. * verification will be disabled.
  872. * @since 4.1
  873. */
  874. public void setSignedPushConfig(SignedPushConfig cfg) {
  875. signedPushConfig = cfg;
  876. }
  877. private PushCertificateParser getPushCertificateParser() {
  878. if (pushCertificateParser == null) {
  879. pushCertificateParser = new PushCertificateParser(db, signedPushConfig);
  880. }
  881. return pushCertificateParser;
  882. }
  883. /**
  884. * Get the user agent of the client.
  885. * <p>
  886. * If the client is new enough to use {@code agent=} capability that value
  887. * will be returned. Older HTTP clients may also supply their version using
  888. * the HTTP {@code User-Agent} header. The capability overrides the HTTP
  889. * header if both are available.
  890. * <p>
  891. * When an HTTP request has been received this method returns the HTTP
  892. * {@code User-Agent} header value until capabilities have been parsed.
  893. *
  894. * @return user agent supplied by the client. Available only if the client
  895. * is new enough to advertise its user agent.
  896. * @since 4.0
  897. */
  898. public String getPeerUserAgent() {
  899. return UserAgent.getAgent(enabledCapabilities, userAgent);
  900. }
  901. /**
  902. * Get all of the command received by the current request.
  903. *
  904. * @return all of the command received by the current request.
  905. */
  906. public List<ReceiveCommand> getAllCommands() {
  907. return Collections.unmodifiableList(commands);
  908. }
  909. /**
  910. * Send an error message to the client.
  911. * <p>
  912. * If any error messages are sent before the references are advertised to
  913. * the client, the errors will be sent instead of the advertisement and the
  914. * receive operation will be aborted. All clients should receive and display
  915. * such early stage errors.
  916. * <p>
  917. * If the reference advertisements have already been sent, messages are sent
  918. * in a side channel. If the client doesn't support receiving messages, the
  919. * message will be discarded, with no other indication to the caller or to
  920. * the client.
  921. * <p>
  922. * {@link org.eclipse.jgit.transport.PreReceiveHook}s should always try to
  923. * use
  924. * {@link org.eclipse.jgit.transport.ReceiveCommand#setResult(Result, String)}
  925. * with a result status of
  926. * {@link org.eclipse.jgit.transport.ReceiveCommand.Result#REJECTED_OTHER_REASON}
  927. * to indicate any reasons for rejecting an update. Messages attached to a
  928. * command are much more likely to be returned to the client.
  929. *
  930. * @param what
  931. * string describing the problem identified by the hook. The
  932. * string must not end with an LF, and must not contain an LF.
  933. */
  934. public void sendError(String what) {
  935. if (refs == null) {
  936. if (advertiseError == null)
  937. advertiseError = new StringBuilder();
  938. advertiseError.append(what).append('\n');
  939. } else {
  940. msgOutWrapper.write(Constants.encode("error: " + what + "\n")); //$NON-NLS-1$ //$NON-NLS-2$
  941. }
  942. }
  943. private void fatalError(String msg) {
  944. if (errOut != null) {
  945. try {
  946. errOut.write(Constants.encode(msg));
  947. errOut.flush();
  948. } catch (IOException e) {
  949. // Ignore write failures
  950. }
  951. } else {
  952. sendError(msg);
  953. }
  954. }
  955. /**
  956. * Send a message to the client, if it supports receiving them.
  957. * <p>
  958. * If the client doesn't support receiving messages, the message will be
  959. * discarded, with no other indication to the caller or to the client.
  960. *
  961. * @param what
  962. * string describing the problem identified by the hook. The
  963. * string must not end with an LF, and must not contain an LF.
  964. */
  965. public void sendMessage(String what) {
  966. msgOutWrapper.write(Constants.encode(what + "\n")); //$NON-NLS-1$
  967. }
  968. /**
  969. * Get an underlying stream for sending messages to the client.
  970. *
  971. * @return an underlying stream for sending messages to the client.
  972. */
  973. public OutputStream getMessageOutputStream() {
  974. return msgOutWrapper;
  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());
  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 (line == PacketLineIn.END) {
  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. FirstLine firstLine = new FirstLine(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. SubmoduleValidator.assertValidGitModulesFile(
  1383. new String(blob.getBytes(), UTF_8));
  1384. }
  1385. }
  1386. private void checkConnectivity() throws IOException {
  1387. ObjectIdSubclassMap<ObjectId> baseObjects = null;
  1388. ObjectIdSubclassMap<ObjectId> providedObjects = null;
  1389. ProgressMonitor checking = NullProgressMonitor.INSTANCE;
  1390. if (sideBand && !quiet) {
  1391. SideBandProgressMonitor m = new SideBandProgressMonitor(msgOut);
  1392. m.setDelayStart(750, TimeUnit.MILLISECONDS);
  1393. checking = m;
  1394. }
  1395. if (checkReferencedIsReachable) {
  1396. baseObjects = parser.getBaseObjectIds();
  1397. providedObjects = parser.getNewObjectIds();
  1398. }
  1399. parser = null;
  1400. try (ObjectWalk ow = new ObjectWalk(db)) {
  1401. if (baseObjects != null) {
  1402. ow.sort(RevSort.TOPO);
  1403. if (!baseObjects.isEmpty())
  1404. ow.sort(RevSort.BOUNDARY, true);
  1405. }
  1406. for (ReceiveCommand cmd : commands) {
  1407. if (cmd.getResult() != Result.NOT_ATTEMPTED)
  1408. continue;
  1409. if (cmd.getType() == ReceiveCommand.Type.DELETE)
  1410. continue;
  1411. ow.markStart(ow.parseAny(cmd.getNewId()));
  1412. }
  1413. for (ObjectId have : advertisedHaves) {
  1414. RevObject o = ow.parseAny(have);
  1415. ow.markUninteresting(o);
  1416. if (baseObjects != null && !baseObjects.isEmpty()) {
  1417. o = ow.peel(o);
  1418. if (o instanceof RevCommit)
  1419. o = ((RevCommit) o).getTree();
  1420. if (o instanceof RevTree)
  1421. ow.markUninteresting(o);
  1422. }
  1423. }
  1424. checking.beginTask(JGitText.get().countingObjects,
  1425. ProgressMonitor.UNKNOWN);
  1426. RevCommit c;
  1427. while ((c = ow.next()) != null) {
  1428. checking.update(1);
  1429. if (providedObjects != null //
  1430. && !c.has(RevFlag.UNINTERESTING) //
  1431. && !providedObjects.contains(c))
  1432. throw new MissingObjectException(c, Constants.TYPE_COMMIT);
  1433. }
  1434. RevObject o;
  1435. while ((o = ow.nextObject()) != null) {
  1436. checking.update(1);
  1437. if (o.has(RevFlag.UNINTERESTING))
  1438. continue;
  1439. if (providedObjects != null) {
  1440. if (providedObjects.contains(o))
  1441. continue;
  1442. else
  1443. throw new MissingObjectException(o, o.getType());
  1444. }
  1445. if (o instanceof RevBlob && !db.hasObject(o))
  1446. throw new MissingObjectException(o, Constants.TYPE_BLOB);
  1447. }
  1448. checking.endTask();
  1449. if (baseObjects != null) {
  1450. for (ObjectId id : baseObjects) {
  1451. o = ow.parseAny(id);
  1452. if (!o.has(RevFlag.UNINTERESTING))
  1453. throw new MissingObjectException(o, o.getType());
  1454. }
  1455. }
  1456. }
  1457. }
  1458. /**
  1459. * Validate the command list.
  1460. */
  1461. protected void validateCommands() {
  1462. for (ReceiveCommand cmd : commands) {
  1463. final Ref ref = cmd.getRef();
  1464. if (cmd.getResult() != Result.NOT_ATTEMPTED)
  1465. continue;
  1466. if (cmd.getType() == ReceiveCommand.Type.DELETE) {
  1467. if (!isAllowDeletes()) {
  1468. // Deletes are not supported on this repository.
  1469. cmd.setResult(Result.REJECTED_NODELETE);
  1470. continue;
  1471. }
  1472. if (!isAllowBranchDeletes()
  1473. && ref.getName().startsWith(Constants.R_HEADS)) {
  1474. // Branches cannot be deleted, but other refs can.
  1475. cmd.setResult(Result.REJECTED_NODELETE);
  1476. continue;
  1477. }
  1478. }
  1479. if (cmd.getType() == ReceiveCommand.Type.CREATE) {
  1480. if (!isAllowCreates()) {
  1481. cmd.setResult(Result.REJECTED_NOCREATE);
  1482. continue;
  1483. }
  1484. if (ref != null && !isAllowNonFastForwards()) {
  1485. // Creation over an existing ref is certainly not going
  1486. // to be a fast-forward update. We can reject it early.
  1487. //
  1488. cmd.setResult(Result.REJECTED_NONFASTFORWARD);
  1489. continue;
  1490. }
  1491. if (ref != null) {
  1492. // A well behaved client shouldn't have sent us a
  1493. // create command for a ref we advertised to it.
  1494. //
  1495. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1496. JGitText.get().refAlreadyExists);
  1497. continue;
  1498. }
  1499. }
  1500. if (cmd.getType() == ReceiveCommand.Type.DELETE && ref != null) {
  1501. ObjectId id = ref.getObjectId();
  1502. if (id == null) {
  1503. id = ObjectId.zeroId();
  1504. }
  1505. if (!ObjectId.zeroId().equals(cmd.getOldId())
  1506. && !id.equals(cmd.getOldId())) {
  1507. // Delete commands can be sent with the old id matching our
  1508. // advertised value, *OR* with the old id being 0{40}. Any
  1509. // other requested old id is invalid.
  1510. //
  1511. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1512. JGitText.get().invalidOldIdSent);
  1513. continue;
  1514. }
  1515. }
  1516. if (cmd.getType() == ReceiveCommand.Type.UPDATE) {
  1517. if (ref == null) {
  1518. // The ref must have been advertised in order to be updated.
  1519. //
  1520. cmd.setResult(Result.REJECTED_OTHER_REASON, JGitText.get().noSuchRef);
  1521. continue;
  1522. }
  1523. ObjectId id = ref.getObjectId();
  1524. if (id == null) {
  1525. // We cannot update unborn branch
  1526. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1527. JGitText.get().cannotUpdateUnbornBranch);
  1528. continue;
  1529. }
  1530. if (!id.equals(cmd.getOldId())) {
  1531. // A properly functioning client will send the same
  1532. // object id we advertised.
  1533. //
  1534. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1535. JGitText.get().invalidOldIdSent);
  1536. continue;
  1537. }
  1538. // Is this possibly a non-fast-forward style update?
  1539. //
  1540. RevObject oldObj, newObj;
  1541. try {
  1542. oldObj = walk.parseAny(cmd.getOldId());
  1543. } catch (IOException e) {
  1544. cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd
  1545. .getOldId().name());
  1546. continue;
  1547. }
  1548. try {
  1549. newObj = walk.parseAny(cmd.getNewId());
  1550. } catch (IOException e) {
  1551. cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd
  1552. .getNewId().name());
  1553. continue;
  1554. }
  1555. if (oldObj instanceof RevCommit && newObj instanceof RevCommit) {
  1556. try {
  1557. if (walk.isMergedInto((RevCommit) oldObj,
  1558. (RevCommit) newObj))
  1559. cmd.setTypeFastForwardUpdate();
  1560. else
  1561. cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
  1562. } catch (MissingObjectException e) {
  1563. cmd.setResult(Result.REJECTED_MISSING_OBJECT, e
  1564. .getMessage());
  1565. } catch (IOException e) {
  1566. cmd.setResult(Result.REJECTED_OTHER_REASON);
  1567. }
  1568. } else {
  1569. cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
  1570. }
  1571. if (cmd.getType() == ReceiveCommand.Type.UPDATE_NONFASTFORWARD
  1572. && !isAllowNonFastForwards()) {
  1573. cmd.setResult(Result.REJECTED_NONFASTFORWARD);
  1574. continue;
  1575. }
  1576. }
  1577. if (!cmd.getRefName().startsWith(Constants.R_REFS)
  1578. || !Repository.isValidRefName(cmd.getRefName())) {
  1579. cmd.setResult(Result.REJECTED_OTHER_REASON, JGitText.get().funnyRefname);
  1580. }
  1581. }
  1582. }
  1583. /**
  1584. * Whether any commands have been rejected so far.
  1585. *
  1586. * @return if any commands have been rejected so far.
  1587. * @since 3.6
  1588. */
  1589. protected boolean anyRejects() {
  1590. for (ReceiveCommand cmd : commands) {
  1591. if (cmd.getResult() != Result.NOT_ATTEMPTED && cmd.getResult() != Result.OK)
  1592. return true;
  1593. }
  1594. return false;
  1595. }
  1596. /**
  1597. * Set the result to fail for any command that was not processed yet.
  1598. *
  1599. * @since 3.6
  1600. */
  1601. protected void failPendingCommands() {
  1602. ReceiveCommand.abort(commands);
  1603. }
  1604. /**
  1605. * Filter the list of commands according to result.
  1606. *
  1607. * @param want
  1608. * desired status to filter by.
  1609. * @return a copy of the command list containing only those commands with the
  1610. * desired status.
  1611. */
  1612. protected List<ReceiveCommand> filterCommands(Result want) {
  1613. return ReceiveCommand.filter(commands, want);
  1614. }
  1615. /**
  1616. * Execute commands to update references.
  1617. */
  1618. protected void executeCommands() {
  1619. List<ReceiveCommand> toApply = filterCommands(Result.NOT_ATTEMPTED);
  1620. if (toApply.isEmpty())
  1621. return;
  1622. ProgressMonitor updating = NullProgressMonitor.INSTANCE;
  1623. if (sideBand) {
  1624. SideBandProgressMonitor pm = new SideBandProgressMonitor(msgOut);
  1625. pm.setDelayStart(250, TimeUnit.MILLISECONDS);
  1626. updating = pm;
  1627. }
  1628. BatchRefUpdate batch = db.getRefDatabase().newBatchUpdate();
  1629. batch.setAllowNonFastForwards(isAllowNonFastForwards());
  1630. batch.setAtomic(isAtomic());
  1631. batch.setRefLogIdent(getRefLogIdent());
  1632. batch.setRefLogMessage("push", true); //$NON-NLS-1$
  1633. batch.addCommand(toApply);
  1634. try {
  1635. batch.setPushCertificate(getPushCertificate());
  1636. batch.execute(walk, updating);
  1637. } catch (IOException err) {
  1638. for (ReceiveCommand cmd : toApply) {
  1639. if (cmd.getResult() == Result.NOT_ATTEMPTED)
  1640. cmd.reject(err);
  1641. }
  1642. }
  1643. }
  1644. /**
  1645. * Send a status report.
  1646. *
  1647. * @param forClient
  1648. * true if this report is for a Git client, false if it is for an
  1649. * end-user.
  1650. * @param unpackError
  1651. * an error that occurred during unpacking, or {@code null}
  1652. * @param out
  1653. * the reporter for sending the status strings.
  1654. * @throws java.io.IOException
  1655. * an error occurred writing the status report.
  1656. */
  1657. protected void sendStatusReport(final boolean forClient,
  1658. final Throwable unpackError, final Reporter out) throws IOException {
  1659. if (unpackError != null) {
  1660. out.sendString("unpack error " + unpackError.getMessage()); //$NON-NLS-1$
  1661. if (forClient) {
  1662. for (ReceiveCommand cmd : commands) {
  1663. out.sendString("ng " + cmd.getRefName() //$NON-NLS-1$
  1664. + " n/a (unpacker error)"); //$NON-NLS-1$
  1665. }
  1666. }
  1667. return;
  1668. }
  1669. if (forClient)
  1670. out.sendString("unpack ok"); //$NON-NLS-1$
  1671. for (ReceiveCommand cmd : commands) {
  1672. if (cmd.getResult() == Result.OK) {
  1673. if (forClient)
  1674. out.sendString("ok " + cmd.getRefName()); //$NON-NLS-1$
  1675. continue;
  1676. }
  1677. final StringBuilder r = new StringBuilder();
  1678. if (forClient)
  1679. r.append("ng ").append(cmd.getRefName()).append(" "); //$NON-NLS-1$ //$NON-NLS-2$
  1680. else
  1681. r.append(" ! [rejected] ").append(cmd.getRefName()).append(" ("); //$NON-NLS-1$ //$NON-NLS-2$
  1682. switch (cmd.getResult()) {
  1683. case NOT_ATTEMPTED:
  1684. r.append("server bug; ref not processed"); //$NON-NLS-1$
  1685. break;
  1686. case REJECTED_NOCREATE:
  1687. r.append("creation prohibited"); //$NON-NLS-1$
  1688. break;
  1689. case REJECTED_NODELETE:
  1690. r.append("deletion prohibited"); //$NON-NLS-1$
  1691. break;
  1692. case REJECTED_NONFASTFORWARD:
  1693. r.append("non-fast forward"); //$NON-NLS-1$
  1694. break;
  1695. case REJECTED_CURRENT_BRANCH:
  1696. r.append("branch is currently checked out"); //$NON-NLS-1$
  1697. break;
  1698. case REJECTED_MISSING_OBJECT:
  1699. if (cmd.getMessage() == null)
  1700. r.append("missing object(s)"); //$NON-NLS-1$
  1701. else if (cmd.getMessage().length() == Constants.OBJECT_ID_STRING_LENGTH) {
  1702. r.append("object "); //$NON-NLS-1$
  1703. r.append(cmd.getMessage());
  1704. r.append(" missing"); //$NON-NLS-1$
  1705. } else
  1706. r.append(cmd.getMessage());
  1707. break;
  1708. case REJECTED_OTHER_REASON:
  1709. if (cmd.getMessage() == null)
  1710. r.append("unspecified reason"); //$NON-NLS-1$
  1711. else
  1712. r.append(cmd.getMessage());
  1713. break;
  1714. case LOCK_FAILURE:
  1715. r.append("failed to lock"); //$NON-NLS-1$
  1716. break;
  1717. case OK:
  1718. // We shouldn't have reached this case (see 'ok' case above).
  1719. continue;
  1720. }
  1721. if (!forClient)
  1722. r.append(")"); //$NON-NLS-1$
  1723. out.sendString(r.toString());
  1724. }
  1725. }
  1726. /**
  1727. * Close and flush (if necessary) the underlying streams.
  1728. *
  1729. * @throws java.io.IOException
  1730. */
  1731. protected void close() throws IOException {
  1732. if (sideBand) {
  1733. // If we are using side band, we need to send a final
  1734. // flush-pkt to tell the remote peer the side band is
  1735. // complete and it should stop decoding. We need to
  1736. // use the original output stream as rawOut is now the
  1737. // side band data channel.
  1738. //
  1739. ((SideBandOutputStream) msgOut).flushBuffer();
  1740. ((SideBandOutputStream) rawOut).flushBuffer();
  1741. PacketLineOut plo = new PacketLineOut(origOut);
  1742. plo.setFlushOnEnd(false);
  1743. plo.end();
  1744. }
  1745. if (biDirectionalPipe) {
  1746. // If this was a native git connection, flush the pipe for
  1747. // the caller. For smart HTTP we don't do this flush and
  1748. // instead let the higher level HTTP servlet code do it.
  1749. //
  1750. if (!sideBand && msgOut != null)
  1751. msgOut.flush();
  1752. rawOut.flush();
  1753. }
  1754. }
  1755. /**
  1756. * Release any resources used by this object.
  1757. *
  1758. * @throws java.io.IOException
  1759. * the pack could not be unlocked.
  1760. */
  1761. protected void release() throws IOException {
  1762. walk.close();
  1763. unlockPack();
  1764. timeoutIn = null;
  1765. rawIn = null;
  1766. rawOut = null;
  1767. msgOut = null;
  1768. pckIn = null;
  1769. pckOut = null;
  1770. refs = null;
  1771. // Keep the capabilities. If responses are sent after this release
  1772. // we need to remember at least whether sideband communication has to be
  1773. // used
  1774. commands = null;
  1775. if (timer != null) {
  1776. try {
  1777. timer.terminate();
  1778. } finally {
  1779. timer = null;
  1780. }
  1781. }
  1782. }
  1783. /** Interface for reporting status messages. */
  1784. static abstract class Reporter {
  1785. abstract void sendString(String s) throws IOException;
  1786. }
  1787. }