Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

ReceivePack.java 65KB

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