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

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