You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ReceivePack.java 67KB

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