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 66KB

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