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

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