Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ReceivePack.java 66KB

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