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.

BaseReceivePack.java 54KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806
  1. /*
  2. * Copyright (C) 2008-2010, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.transport;
  44. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_ATOMIC;
  45. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_DELETE_REFS;
  46. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_OFS_DELTA;
  47. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_QUIET;
  48. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_REPORT_STATUS;
  49. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_PUSH_OPTIONS;
  50. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_SIDE_BAND_64K;
  51. import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_AGENT;
  52. import static org.eclipse.jgit.transport.SideBandOutputStream.CH_DATA;
  53. import static org.eclipse.jgit.transport.SideBandOutputStream.CH_ERROR;
  54. import static org.eclipse.jgit.transport.SideBandOutputStream.CH_PROGRESS;
  55. import static org.eclipse.jgit.transport.SideBandOutputStream.MAX_BUF;
  56. import java.io.EOFException;
  57. import java.io.IOException;
  58. import java.io.InputStream;
  59. import java.io.OutputStream;
  60. import java.text.MessageFormat;
  61. import java.util.ArrayList;
  62. import java.util.Collections;
  63. import java.util.HashSet;
  64. import java.util.List;
  65. import java.util.Map;
  66. import java.util.Set;
  67. import java.util.concurrent.TimeUnit;
  68. import org.eclipse.jgit.annotations.Nullable;
  69. import org.eclipse.jgit.errors.InvalidObjectIdException;
  70. import org.eclipse.jgit.errors.MissingObjectException;
  71. import org.eclipse.jgit.errors.PackProtocolException;
  72. import org.eclipse.jgit.errors.TooLargePackException;
  73. import org.eclipse.jgit.internal.JGitText;
  74. import org.eclipse.jgit.internal.storage.file.PackLock;
  75. import org.eclipse.jgit.lib.BatchRefUpdate;
  76. import org.eclipse.jgit.lib.Config;
  77. import org.eclipse.jgit.lib.Config.SectionParser;
  78. import org.eclipse.jgit.lib.Constants;
  79. import org.eclipse.jgit.lib.NullProgressMonitor;
  80. import org.eclipse.jgit.lib.ObjectChecker;
  81. import org.eclipse.jgit.lib.ObjectId;
  82. import org.eclipse.jgit.lib.ObjectIdSubclassMap;
  83. import org.eclipse.jgit.lib.ObjectInserter;
  84. import org.eclipse.jgit.lib.PersonIdent;
  85. import org.eclipse.jgit.lib.ProgressMonitor;
  86. import org.eclipse.jgit.lib.Ref;
  87. import org.eclipse.jgit.lib.Repository;
  88. import org.eclipse.jgit.revwalk.ObjectWalk;
  89. import org.eclipse.jgit.revwalk.RevBlob;
  90. import org.eclipse.jgit.revwalk.RevCommit;
  91. import org.eclipse.jgit.revwalk.RevFlag;
  92. import org.eclipse.jgit.revwalk.RevObject;
  93. import org.eclipse.jgit.revwalk.RevSort;
  94. import org.eclipse.jgit.revwalk.RevTree;
  95. import org.eclipse.jgit.revwalk.RevWalk;
  96. import org.eclipse.jgit.transport.ReceiveCommand.Result;
  97. import org.eclipse.jgit.util.io.InterruptTimer;
  98. import org.eclipse.jgit.util.io.LimitedInputStream;
  99. import org.eclipse.jgit.util.io.TimeoutInputStream;
  100. import org.eclipse.jgit.util.io.TimeoutOutputStream;
  101. /**
  102. * Base implementation of the side of a push connection that receives objects.
  103. * <p>
  104. * Contains high-level operations for initializing and closing streams,
  105. * advertising refs, reading commands, and receiving and applying a pack.
  106. * Subclasses compose these operations into full service implementations.
  107. */
  108. public abstract class BaseReceivePack {
  109. /** Data in the first line of a request, the line itself plus capabilities. */
  110. public static class FirstLine {
  111. private final String line;
  112. private final Set<String> capabilities;
  113. /**
  114. * Parse the first line of a receive-pack request.
  115. *
  116. * @param line
  117. * line from the client.
  118. */
  119. public FirstLine(String line) {
  120. final HashSet<String> caps = new HashSet<String>();
  121. final int nul = line.indexOf('\0');
  122. if (nul >= 0) {
  123. for (String c : line.substring(nul + 1).split(" ")) //$NON-NLS-1$
  124. caps.add(c);
  125. this.line = line.substring(0, nul);
  126. } else
  127. this.line = line;
  128. this.capabilities = Collections.unmodifiableSet(caps);
  129. }
  130. /** @return non-capabilities part of the line. */
  131. public String getLine() {
  132. return line;
  133. }
  134. /** @return capabilities parsed from the line. */
  135. public Set<String> getCapabilities() {
  136. return capabilities;
  137. }
  138. }
  139. /** Database we write the stored objects into. */
  140. private final Repository db;
  141. /** Revision traversal support over {@link #db}. */
  142. private final RevWalk walk;
  143. /**
  144. * Is the client connection a bi-directional socket or pipe?
  145. * <p>
  146. * If true, this class assumes it can perform multiple read and write cycles
  147. * with the client over the input and output streams. This matches the
  148. * functionality available with a standard TCP/IP connection, or a local
  149. * operating system or in-memory pipe.
  150. * <p>
  151. * If false, this class runs in a read everything then output results mode,
  152. * making it suitable for single round-trip systems RPCs such as HTTP.
  153. */
  154. private boolean biDirectionalPipe = true;
  155. /** Expecting data after the pack footer */
  156. private boolean expectDataAfterPackFooter;
  157. /** Should an incoming transfer validate objects? */
  158. private ObjectChecker objectChecker;
  159. /** Should an incoming transfer permit create requests? */
  160. private boolean allowCreates;
  161. /** Should an incoming transfer permit delete requests? */
  162. private boolean allowAnyDeletes;
  163. private boolean allowBranchDeletes;
  164. /** Should an incoming transfer permit non-fast-forward requests? */
  165. private boolean allowNonFastForwards;
  166. /** Should an incoming transfer permit push options? **/
  167. private boolean allowPushOptions;
  168. /**
  169. * Should the requested ref updates be performed as a single atomic
  170. * transaction?
  171. */
  172. private boolean atomic;
  173. private boolean allowOfsDelta;
  174. private boolean allowQuiet = true;
  175. /** Identity to record action as within the reflog. */
  176. private PersonIdent refLogIdent;
  177. /** Hook used while advertising the refs to the client. */
  178. private AdvertiseRefsHook advertiseRefsHook;
  179. /** Filter used while advertising the refs to the client. */
  180. private RefFilter refFilter;
  181. /** Timeout in seconds to wait for client interaction. */
  182. private int timeout;
  183. /** Timer to manage {@link #timeout}. */
  184. private InterruptTimer timer;
  185. private TimeoutInputStream timeoutIn;
  186. // Original stream passed to init(), since rawOut may be wrapped in a
  187. // sideband.
  188. private OutputStream origOut;
  189. /** Raw input stream. */
  190. protected InputStream rawIn;
  191. /** Raw output stream. */
  192. protected OutputStream rawOut;
  193. /** Optional message output stream. */
  194. protected OutputStream msgOut;
  195. private SideBandOutputStream errOut;
  196. /** Packet line input stream around {@link #rawIn}. */
  197. protected PacketLineIn pckIn;
  198. /** Packet line output stream around {@link #rawOut}. */
  199. protected PacketLineOut pckOut;
  200. private final MessageOutputWrapper msgOutWrapper = new MessageOutputWrapper();
  201. private PackParser parser;
  202. /** The refs we advertised as existing at the start of the connection. */
  203. private Map<String, Ref> refs;
  204. /** All SHA-1s shown to the client, which can be possible edges. */
  205. private Set<ObjectId> advertisedHaves;
  206. /** Capabilities requested by the client. */
  207. private Set<String> enabledCapabilities;
  208. String userAgent;
  209. private Set<ObjectId> clientShallowCommits;
  210. private List<ReceiveCommand> commands;
  211. private StringBuilder advertiseError;
  212. /** If {@link BasePackPushConnection#CAPABILITY_SIDE_BAND_64K} is enabled. */
  213. private boolean sideBand;
  214. private boolean quiet;
  215. /**
  216. * A list of option strings associated with a push.
  217. * @since 4.5
  218. */
  219. protected List<String> pushOptions;
  220. /**
  221. * Whether the client intends to use push options.
  222. * @since 4.5
  223. */
  224. protected boolean usePushOptions;
  225. /** Lock around the received pack file, while updating refs. */
  226. private PackLock packLock;
  227. private boolean checkReferencedIsReachable;
  228. /** Git object size limit */
  229. private long maxObjectSizeLimit;
  230. /** Total pack size limit */
  231. private long maxPackSizeLimit = -1;
  232. /** The size of the received pack, including index size */
  233. private Long packSize;
  234. private PushCertificateParser pushCertificateParser;
  235. private SignedPushConfig signedPushConfig;
  236. private PushCertificate pushCert;
  237. /**
  238. * Get the push certificate used to verify the pusher's identity.
  239. * <p>
  240. * Only valid after commands are read from the wire.
  241. *
  242. * @return the parsed certificate, or null if push certificates are disabled
  243. * or no cert was presented by the client.
  244. * @since 4.1
  245. */
  246. public PushCertificate getPushCertificate() {
  247. return pushCert;
  248. }
  249. /**
  250. * Set the push certificate used to verify the pusher's identity.
  251. * <p>
  252. * Should only be called if reconstructing an instance without going through
  253. * the normal {@link #recvCommands()} flow.
  254. *
  255. * @param cert
  256. * the push certificate to set.
  257. * @since 4.1
  258. */
  259. public void setPushCertificate(PushCertificate cert) {
  260. pushCert = cert;
  261. }
  262. /**
  263. * Create a new pack receive for an open repository.
  264. *
  265. * @param into
  266. * the destination repository.
  267. */
  268. protected BaseReceivePack(final Repository into) {
  269. db = into;
  270. walk = new RevWalk(db);
  271. TransferConfig tc = db.getConfig().get(TransferConfig.KEY);
  272. objectChecker = tc.newReceiveObjectChecker();
  273. ReceiveConfig rc = db.getConfig().get(ReceiveConfig.KEY);
  274. allowCreates = rc.allowCreates;
  275. allowAnyDeletes = true;
  276. allowBranchDeletes = rc.allowDeletes;
  277. allowNonFastForwards = rc.allowNonFastForwards;
  278. allowOfsDelta = rc.allowOfsDelta;
  279. allowPushOptions = rc.allowPushOptions;
  280. advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  281. refFilter = RefFilter.DEFAULT;
  282. advertisedHaves = new HashSet<ObjectId>();
  283. clientShallowCommits = new HashSet<ObjectId>();
  284. signedPushConfig = rc.signedPush;
  285. }
  286. /** Configuration for receive operations. */
  287. protected static class ReceiveConfig {
  288. static final SectionParser<ReceiveConfig> KEY = new SectionParser<ReceiveConfig>() {
  289. public ReceiveConfig parse(final Config cfg) {
  290. return new ReceiveConfig(cfg);
  291. }
  292. };
  293. final boolean allowCreates;
  294. final boolean allowDeletes;
  295. final boolean allowNonFastForwards;
  296. final boolean allowOfsDelta;
  297. final boolean allowPushOptions;
  298. final SignedPushConfig signedPush;
  299. ReceiveConfig(final Config config) {
  300. allowCreates = true;
  301. allowDeletes = !config.getBoolean("receive", "denydeletes", false); //$NON-NLS-1$ //$NON-NLS-2$
  302. allowNonFastForwards = !config.getBoolean("receive", //$NON-NLS-1$
  303. "denynonfastforwards", false); //$NON-NLS-1$
  304. allowOfsDelta = config.getBoolean("repack", "usedeltabaseoffset", //$NON-NLS-1$ //$NON-NLS-2$
  305. true);
  306. allowPushOptions = config.getBoolean("receive", "pushoptions", //$NON-NLS-1$ //$NON-NLS-2$
  307. false);
  308. signedPush = SignedPushConfig.KEY.parse(config);
  309. }
  310. }
  311. /**
  312. * Output stream that wraps the current {@link #msgOut}.
  313. * <p>
  314. * We don't want to expose {@link #msgOut} directly because it can change
  315. * several times over the course of a session.
  316. */
  317. class MessageOutputWrapper extends OutputStream {
  318. @Override
  319. public void write(int ch) {
  320. if (msgOut != null) {
  321. try {
  322. msgOut.write(ch);
  323. } catch (IOException e) {
  324. // Ignore write failures.
  325. }
  326. }
  327. }
  328. @Override
  329. public void write(byte[] b, int off, int len) {
  330. if (msgOut != null) {
  331. try {
  332. msgOut.write(b, off, len);
  333. } catch (IOException e) {
  334. // Ignore write failures.
  335. }
  336. }
  337. }
  338. @Override
  339. public void write(byte[] b) {
  340. write(b, 0, b.length);
  341. }
  342. @Override
  343. public void flush() {
  344. if (msgOut != null) {
  345. try {
  346. msgOut.flush();
  347. } catch (IOException e) {
  348. // Ignore write failures.
  349. }
  350. }
  351. }
  352. }
  353. /** @return the process name used for pack lock messages. */
  354. protected abstract String getLockMessageProcessName();
  355. /** @return the repository this receive completes into. */
  356. public final Repository getRepository() {
  357. return db;
  358. }
  359. /** @return the RevWalk instance used by this connection. */
  360. public final RevWalk getRevWalk() {
  361. return walk;
  362. }
  363. /**
  364. * Get refs which were advertised to the client.
  365. *
  366. * @return all refs which were advertised to the client, or null if
  367. * {@link #setAdvertisedRefs(Map, Set)} has not been called yet.
  368. */
  369. public final Map<String, Ref> getAdvertisedRefs() {
  370. return refs;
  371. }
  372. /**
  373. * Set the refs advertised by this ReceivePack.
  374. * <p>
  375. * Intended to be called from a {@link PreReceiveHook}.
  376. *
  377. * @param allRefs
  378. * explicit set of references to claim as advertised by this
  379. * ReceivePack instance. This overrides any references that
  380. * may exist in the source repository. The map is passed
  381. * to the configured {@link #getRefFilter()}. If null, assumes
  382. * all refs were advertised.
  383. * @param additionalHaves
  384. * explicit set of additional haves to claim as advertised. If
  385. * null, assumes the default set of additional haves from the
  386. * repository.
  387. */
  388. public void setAdvertisedRefs(Map<String, Ref> allRefs, Set<ObjectId> additionalHaves) {
  389. refs = allRefs != null ? allRefs : db.getAllRefs();
  390. refs = refFilter.filter(refs);
  391. Ref head = refs.get(Constants.HEAD);
  392. if (head != null && head.isSymbolic())
  393. refs.remove(Constants.HEAD);
  394. for (Ref ref : refs.values()) {
  395. if (ref.getObjectId() != null)
  396. advertisedHaves.add(ref.getObjectId());
  397. }
  398. if (additionalHaves != null)
  399. advertisedHaves.addAll(additionalHaves);
  400. else
  401. advertisedHaves.addAll(db.getAdditionalHaves());
  402. }
  403. /**
  404. * Get objects advertised to the client.
  405. *
  406. * @return the set of objects advertised to the as present in this repository,
  407. * or null if {@link #setAdvertisedRefs(Map, Set)} has not been called
  408. * yet.
  409. */
  410. public final Set<ObjectId> getAdvertisedObjects() {
  411. return advertisedHaves;
  412. }
  413. /**
  414. * @return true if this instance will validate all referenced, but not
  415. * supplied by the client, objects are reachable from another
  416. * reference.
  417. */
  418. public boolean isCheckReferencedObjectsAreReachable() {
  419. return checkReferencedIsReachable;
  420. }
  421. /**
  422. * Validate all referenced but not supplied objects are reachable.
  423. * <p>
  424. * If enabled, this instance will verify that references to objects not
  425. * contained within the received pack are already reachable through at least
  426. * one other reference displayed as part of {@link #getAdvertisedRefs()}.
  427. * <p>
  428. * This feature is useful when the application doesn't trust the client to
  429. * not provide a forged SHA-1 reference to an object, in an attempt to
  430. * access parts of the DAG that they aren't allowed to see and which have
  431. * been hidden from them via the configured {@link AdvertiseRefsHook} or
  432. * {@link RefFilter}.
  433. * <p>
  434. * Enabling this feature may imply at least some, if not all, of the same
  435. * functionality performed by {@link #setCheckReceivedObjects(boolean)}.
  436. * Applications are encouraged to enable both features, if desired.
  437. *
  438. * @param b
  439. * {@code true} to enable the additional check.
  440. */
  441. public void setCheckReferencedObjectsAreReachable(boolean b) {
  442. this.checkReferencedIsReachable = b;
  443. }
  444. /**
  445. * @return true if this class expects a bi-directional pipe opened between
  446. * the client and itself. The default is true.
  447. */
  448. public boolean isBiDirectionalPipe() {
  449. return biDirectionalPipe;
  450. }
  451. /**
  452. * @param twoWay
  453. * if true, this class will assume the socket is a fully
  454. * bidirectional pipe between the two peers and takes advantage
  455. * of that by first transmitting the known refs, then waiting to
  456. * read commands. If false, this class assumes it must read the
  457. * commands before writing output and does not perform the
  458. * initial advertising.
  459. */
  460. public void setBiDirectionalPipe(final boolean twoWay) {
  461. biDirectionalPipe = twoWay;
  462. }
  463. /** @return true if there is data expected after the pack footer. */
  464. public boolean isExpectDataAfterPackFooter() {
  465. return expectDataAfterPackFooter;
  466. }
  467. /**
  468. * @param e
  469. * true if there is additional data in InputStream after pack.
  470. */
  471. public void setExpectDataAfterPackFooter(boolean e) {
  472. expectDataAfterPackFooter = e;
  473. }
  474. /**
  475. * @return true if this instance will verify received objects are formatted
  476. * correctly. Validating objects requires more CPU time on this side
  477. * of the connection.
  478. */
  479. public boolean isCheckReceivedObjects() {
  480. return objectChecker != null;
  481. }
  482. /**
  483. * @param check
  484. * true to enable checking received objects; false to assume all
  485. * received objects are valid.
  486. * @see #setObjectChecker(ObjectChecker)
  487. */
  488. public void setCheckReceivedObjects(final boolean check) {
  489. if (check && objectChecker == null)
  490. setObjectChecker(new ObjectChecker());
  491. else if (!check && objectChecker != null)
  492. setObjectChecker(null);
  493. }
  494. /**
  495. * @param impl if non-null the object checking instance to verify each
  496. * received object with; null to disable object checking.
  497. * @since 3.4
  498. */
  499. public void setObjectChecker(ObjectChecker impl) {
  500. objectChecker = impl;
  501. }
  502. /** @return true if the client can request refs to be created. */
  503. public boolean isAllowCreates() {
  504. return allowCreates;
  505. }
  506. /**
  507. * @param canCreate
  508. * true to permit create ref commands to be processed.
  509. */
  510. public void setAllowCreates(final boolean canCreate) {
  511. allowCreates = canCreate;
  512. }
  513. /** @return true if the client can request refs to be deleted. */
  514. public boolean isAllowDeletes() {
  515. return allowAnyDeletes;
  516. }
  517. /**
  518. * @param canDelete
  519. * true to permit delete ref commands to be processed.
  520. */
  521. public void setAllowDeletes(final boolean canDelete) {
  522. allowAnyDeletes = canDelete;
  523. }
  524. /**
  525. * @return true if the client can delete from {@code refs/heads/}.
  526. * @since 3.6
  527. */
  528. public boolean isAllowBranchDeletes() {
  529. return allowBranchDeletes;
  530. }
  531. /**
  532. * @param canDelete
  533. * true to permit deletion of branches from the
  534. * {@code refs/heads/} namespace.
  535. * @since 3.6
  536. */
  537. public void setAllowBranchDeletes(boolean canDelete) {
  538. allowBranchDeletes = canDelete;
  539. }
  540. /**
  541. * @return true if the client can request non-fast-forward updates of a ref,
  542. * possibly making objects unreachable.
  543. */
  544. public boolean isAllowNonFastForwards() {
  545. return allowNonFastForwards;
  546. }
  547. /**
  548. * @param canRewind
  549. * true to permit the client to ask for non-fast-forward updates
  550. * of an existing ref.
  551. */
  552. public void setAllowNonFastForwards(final boolean canRewind) {
  553. allowNonFastForwards = canRewind;
  554. }
  555. /**
  556. * @return true if the client's commands should be performed as a single
  557. * atomic transaction.
  558. * @since 4.4
  559. */
  560. public boolean isAtomic() {
  561. return atomic;
  562. }
  563. /**
  564. * @param atomic
  565. * true to perform the client's commands as a single atomic
  566. * transaction.
  567. * @since 4.4
  568. */
  569. public void setAtomic(boolean atomic) {
  570. this.atomic = atomic;
  571. }
  572. /** @return identity of the user making the changes in the reflog. */
  573. public PersonIdent getRefLogIdent() {
  574. return refLogIdent;
  575. }
  576. /**
  577. * Set the identity of the user appearing in the affected reflogs.
  578. * <p>
  579. * The timestamp portion of the identity is ignored. A new identity with the
  580. * current timestamp will be created automatically when the updates occur
  581. * and the log records are written.
  582. *
  583. * @param pi
  584. * identity of the user. If null the identity will be
  585. * automatically determined based on the repository
  586. * configuration.
  587. */
  588. public void setRefLogIdent(final PersonIdent pi) {
  589. refLogIdent = pi;
  590. }
  591. /** @return the hook used while advertising the refs to the client */
  592. public AdvertiseRefsHook getAdvertiseRefsHook() {
  593. return advertiseRefsHook;
  594. }
  595. /** @return the filter used while advertising the refs to the client */
  596. public RefFilter getRefFilter() {
  597. return refFilter;
  598. }
  599. /**
  600. * Set the hook used while advertising the refs to the client.
  601. * <p>
  602. * If the {@link AdvertiseRefsHook} chooses to call
  603. * {@link #setAdvertisedRefs(Map,Set)}, only refs set by this hook
  604. * <em>and</em> selected by the {@link RefFilter} will be shown to the client.
  605. * Clients may still attempt to create or update a reference not advertised by
  606. * the configured {@link AdvertiseRefsHook}. These attempts should be rejected
  607. * by a matching {@link PreReceiveHook}.
  608. *
  609. * @param advertiseRefsHook
  610. * the hook; may be null to show all refs.
  611. */
  612. public void setAdvertiseRefsHook(final AdvertiseRefsHook advertiseRefsHook) {
  613. if (advertiseRefsHook != null)
  614. this.advertiseRefsHook = advertiseRefsHook;
  615. else
  616. this.advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  617. }
  618. /**
  619. * Set the filter used while advertising the refs to the client.
  620. * <p>
  621. * Only refs allowed by this filter will be shown to the client.
  622. * The filter is run against the refs specified by the
  623. * {@link AdvertiseRefsHook} (if applicable).
  624. *
  625. * @param refFilter
  626. * the filter; may be null to show all refs.
  627. */
  628. public void setRefFilter(final RefFilter refFilter) {
  629. this.refFilter = refFilter != null ? refFilter : RefFilter.DEFAULT;
  630. }
  631. /** @return timeout (in seconds) before aborting an IO operation. */
  632. public int getTimeout() {
  633. return timeout;
  634. }
  635. /**
  636. * Set the timeout before willing to abort an IO call.
  637. *
  638. * @param seconds
  639. * number of seconds to wait (with no data transfer occurring)
  640. * before aborting an IO read or write operation with the
  641. * connected client.
  642. */
  643. public void setTimeout(final int seconds) {
  644. timeout = seconds;
  645. }
  646. /**
  647. * Set the maximum allowed Git object size.
  648. * <p>
  649. * If an object is larger than the given size the pack-parsing will throw an
  650. * exception aborting the receive-pack operation.
  651. *
  652. * @param limit
  653. * the Git object size limit. If zero then there is not limit.
  654. */
  655. public void setMaxObjectSizeLimit(final long limit) {
  656. maxObjectSizeLimit = limit;
  657. }
  658. /**
  659. * Set the maximum allowed pack size.
  660. * <p>
  661. * A pack exceeding this size will be rejected.
  662. *
  663. * @param limit
  664. * the pack size limit, in bytes
  665. *
  666. * @since 3.3
  667. */
  668. public void setMaxPackSizeLimit(final long limit) {
  669. if (limit < 0)
  670. throw new IllegalArgumentException(MessageFormat.format(
  671. JGitText.get().receivePackInvalidLimit, Long.valueOf(limit)));
  672. maxPackSizeLimit = limit;
  673. }
  674. /**
  675. * Check whether the client expects a side-band stream.
  676. *
  677. * @return true if the client has advertised a side-band capability, false
  678. * otherwise.
  679. * @throws RequestNotYetReadException
  680. * if the client's request has not yet been read from the wire, so
  681. * we do not know if they expect side-band. Note that the client
  682. * may have already written the request, it just has not been
  683. * read.
  684. */
  685. public boolean isSideBand() throws RequestNotYetReadException {
  686. if (enabledCapabilities == null)
  687. throw new RequestNotYetReadException();
  688. return enabledCapabilities.contains(CAPABILITY_SIDE_BAND_64K);
  689. }
  690. /**
  691. * @return true if clients may request avoiding noisy progress messages.
  692. * @since 4.0
  693. */
  694. public boolean isAllowQuiet() {
  695. return allowQuiet;
  696. }
  697. /**
  698. * Configure if clients may request the server skip noisy messages.
  699. *
  700. * @param allow
  701. * true to allow clients to request quiet behavior; false to
  702. * refuse quiet behavior and send messages anyway. This may be
  703. * necessary if processing is slow and the client-server network
  704. * connection can timeout.
  705. * @since 4.0
  706. */
  707. public void setAllowQuiet(boolean allow) {
  708. allowQuiet = allow;
  709. }
  710. /**
  711. * @return true if the server supports the receiving of push options.
  712. * @since 4.5
  713. */
  714. public boolean isAllowPushOptions() {
  715. return allowPushOptions;
  716. }
  717. /**
  718. * Configure if the server supports the receiving of push options.
  719. *
  720. * @param allow
  721. * true to permit option strings.
  722. * @since 4.5
  723. */
  724. public void setAllowPushOptions(boolean allow) {
  725. allowPushOptions = allow;
  726. }
  727. /**
  728. * True if the client wants less verbose output.
  729. *
  730. * @return true if the client has requested the server to be less verbose.
  731. * @throws RequestNotYetReadException
  732. * if the client's request has not yet been read from the wire,
  733. * so we do not know if they expect side-band. Note that the
  734. * client may have already written the request, it just has not
  735. * been read.
  736. * @since 4.0
  737. */
  738. public boolean isQuiet() throws RequestNotYetReadException {
  739. if (enabledCapabilities == null)
  740. throw new RequestNotYetReadException();
  741. return quiet;
  742. }
  743. /**
  744. * Gets an unmodifiable view of the option strings associated with the push.
  745. *
  746. * @return an unmodifiable view of pushOptions, or null (if pushOptions is).
  747. * @throws IllegalStateException
  748. * if allowPushOptions has not been set to true.
  749. * @throws RequestNotYetReadException
  750. * if the client's request has not yet been read from the wire,
  751. * so we do not know if they expect push options. Note that the
  752. * client may have already written the request, it just has not
  753. * been read.
  754. * @since 4.5
  755. */
  756. @Nullable
  757. public List<String> getPushOptions() {
  758. if (!allowPushOptions) {
  759. // Reading push options without a prior setAllowPushOptions(true)
  760. // call doesn't make sense.
  761. throw new IllegalStateException();
  762. }
  763. if (enabledCapabilities == null) {
  764. // Push options are not available until receive() has been called.
  765. throw new RequestNotYetReadException();
  766. }
  767. if (pushOptions == null) {
  768. // The client doesn't support push options. Return null to
  769. // distinguish this from the case where the client declared support
  770. // for push options and sent an empty list of them.
  771. return null;
  772. }
  773. return Collections.unmodifiableList(pushOptions);
  774. }
  775. /**
  776. * Set the configuration for push certificate verification.
  777. *
  778. * @param cfg
  779. * new configuration; if this object is null or its {@link
  780. * SignedPushConfig#getCertNonceSeed()} is null, push certificate
  781. * verification will be disabled.
  782. * @since 4.1
  783. */
  784. public void setSignedPushConfig(SignedPushConfig cfg) {
  785. signedPushConfig = cfg;
  786. }
  787. private PushCertificateParser getPushCertificateParser() {
  788. if (pushCertificateParser == null) {
  789. pushCertificateParser = new PushCertificateParser(db, signedPushConfig);
  790. }
  791. return pushCertificateParser;
  792. }
  793. /**
  794. * Get the user agent of the client.
  795. * <p>
  796. * If the client is new enough to use {@code agent=} capability that value
  797. * will be returned. Older HTTP clients may also supply their version using
  798. * the HTTP {@code User-Agent} header. The capability overrides the HTTP
  799. * header if both are available.
  800. * <p>
  801. * When an HTTP request has been received this method returns the HTTP
  802. * {@code User-Agent} header value until capabilities have been parsed.
  803. *
  804. * @return user agent supplied by the client. Available only if the client
  805. * is new enough to advertise its user agent.
  806. * @since 4.0
  807. */
  808. public String getPeerUserAgent() {
  809. return UserAgent.getAgent(enabledCapabilities, userAgent);
  810. }
  811. /** @return all of the command received by the current request. */
  812. public List<ReceiveCommand> getAllCommands() {
  813. return Collections.unmodifiableList(commands);
  814. }
  815. /**
  816. * Send an error message to the client.
  817. * <p>
  818. * If any error messages are sent before the references are advertised to
  819. * the client, the errors will be sent instead of the advertisement and the
  820. * receive operation will be aborted. All clients should receive and display
  821. * such early stage errors.
  822. * <p>
  823. * If the reference advertisements have already been sent, messages are sent
  824. * in a side channel. If the client doesn't support receiving messages, the
  825. * message will be discarded, with no other indication to the caller or to
  826. * the client.
  827. * <p>
  828. * {@link PreReceiveHook}s should always try to use
  829. * {@link ReceiveCommand#setResult(Result, String)} with a result status of
  830. * {@link Result#REJECTED_OTHER_REASON} to indicate any reasons for
  831. * rejecting an update. Messages attached to a command are much more likely
  832. * to be returned to the client.
  833. *
  834. * @param what
  835. * string describing the problem identified by the hook. The
  836. * string must not end with an LF, and must not contain an LF.
  837. */
  838. public void sendError(final String what) {
  839. if (refs == null) {
  840. if (advertiseError == null)
  841. advertiseError = new StringBuilder();
  842. advertiseError.append(what).append('\n');
  843. } else {
  844. msgOutWrapper.write(Constants.encode("error: " + what + "\n")); //$NON-NLS-1$ //$NON-NLS-2$
  845. }
  846. }
  847. private void fatalError(String msg) {
  848. if (errOut != null) {
  849. try {
  850. errOut.write(Constants.encode(msg));
  851. errOut.flush();
  852. } catch (IOException e) {
  853. // Ignore write failures
  854. }
  855. } else {
  856. sendError(msg);
  857. }
  858. }
  859. /**
  860. * Send a message to the client, if it supports receiving them.
  861. * <p>
  862. * If the client doesn't support receiving messages, the message will be
  863. * discarded, with no other indication to the caller or to the client.
  864. *
  865. * @param what
  866. * string describing the problem identified by the hook. The
  867. * string must not end with an LF, and must not contain an LF.
  868. */
  869. public void sendMessage(final String what) {
  870. msgOutWrapper.write(Constants.encode(what + "\n")); //$NON-NLS-1$
  871. }
  872. /** @return an underlying stream for sending messages to the client. */
  873. public OutputStream getMessageOutputStream() {
  874. return msgOutWrapper;
  875. }
  876. /**
  877. * Get the size of the received pack file including the index size.
  878. *
  879. * This can only be called if the pack is already received.
  880. *
  881. * @return the size of the received pack including index size
  882. * @throws IllegalStateException
  883. * if called before the pack has been received
  884. * @since 3.3
  885. */
  886. public long getPackSize() {
  887. if (packSize != null)
  888. return packSize.longValue();
  889. throw new IllegalStateException(JGitText.get().packSizeNotSetYet);
  890. }
  891. /**
  892. * Get the commits from the client's shallow file.
  893. *
  894. * @return if the client is a shallow repository, the list of edge commits
  895. * that define the client's shallow boundary. Empty set if the client
  896. * is earlier than Git 1.9, or is a full clone.
  897. * @since 3.5
  898. */
  899. protected Set<ObjectId> getClientShallowCommits() {
  900. return clientShallowCommits;
  901. }
  902. /** @return true if any commands to be executed have been read. */
  903. protected boolean hasCommands() {
  904. return !commands.isEmpty();
  905. }
  906. /** @return true if an error occurred that should be advertised. */
  907. protected boolean hasError() {
  908. return advertiseError != null;
  909. }
  910. /**
  911. * Initialize the instance with the given streams.
  912. *
  913. * @param input
  914. * raw input to read client commands and pack data from. Caller
  915. * must ensure the input is buffered, otherwise read performance
  916. * may suffer.
  917. * @param output
  918. * response back to the Git network client. Caller must ensure
  919. * the output is buffered, otherwise write performance may
  920. * suffer.
  921. * @param messages
  922. * secondary "notice" channel to send additional messages out
  923. * through. When run over SSH this should be tied back to the
  924. * standard error channel of the command execution. For most
  925. * other network connections this should be null.
  926. */
  927. protected void init(final InputStream input, final OutputStream output,
  928. final OutputStream messages) {
  929. origOut = output;
  930. rawIn = input;
  931. rawOut = output;
  932. msgOut = messages;
  933. if (timeout > 0) {
  934. final Thread caller = Thread.currentThread();
  935. timer = new InterruptTimer(caller.getName() + "-Timer"); //$NON-NLS-1$
  936. timeoutIn = new TimeoutInputStream(rawIn, timer);
  937. TimeoutOutputStream o = new TimeoutOutputStream(rawOut, timer);
  938. timeoutIn.setTimeout(timeout * 1000);
  939. o.setTimeout(timeout * 1000);
  940. rawIn = timeoutIn;
  941. rawOut = o;
  942. }
  943. if (maxPackSizeLimit >= 0)
  944. rawIn = new LimitedInputStream(rawIn, maxPackSizeLimit) {
  945. @Override
  946. protected void limitExceeded() throws TooLargePackException {
  947. throw new TooLargePackException(limit);
  948. }
  949. };
  950. pckIn = new PacketLineIn(rawIn);
  951. pckOut = new PacketLineOut(rawOut);
  952. pckOut.setFlushOnEnd(false);
  953. enabledCapabilities = new HashSet<String>();
  954. commands = new ArrayList<ReceiveCommand>();
  955. }
  956. /** @return advertised refs, or the default if not explicitly advertised. */
  957. protected Map<String, Ref> getAdvertisedOrDefaultRefs() {
  958. if (refs == null)
  959. setAdvertisedRefs(null, null);
  960. return refs;
  961. }
  962. /**
  963. * Receive a pack from the stream and check connectivity if necessary.
  964. *
  965. * @throws IOException
  966. * an error occurred during unpacking or connectivity checking.
  967. */
  968. protected void receivePackAndCheckConnectivity() throws IOException {
  969. receivePack();
  970. if (needCheckConnectivity())
  971. checkConnectivity();
  972. parser = null;
  973. }
  974. /**
  975. * Unlock the pack written by this object.
  976. *
  977. * @throws IOException
  978. * the pack could not be unlocked.
  979. */
  980. protected void unlockPack() throws IOException {
  981. if (packLock != null) {
  982. packLock.unlock();
  983. packLock = null;
  984. }
  985. }
  986. /**
  987. * Generate an advertisement of available refs and capabilities.
  988. *
  989. * @param adv
  990. * the advertisement formatter.
  991. * @throws IOException
  992. * the formatter failed to write an advertisement.
  993. * @throws ServiceMayNotContinueException
  994. * the hook denied advertisement.
  995. */
  996. public void sendAdvertisedRefs(final RefAdvertiser adv)
  997. throws IOException, ServiceMayNotContinueException {
  998. if (advertiseError != null) {
  999. adv.writeOne("ERR " + advertiseError); //$NON-NLS-1$
  1000. return;
  1001. }
  1002. try {
  1003. advertiseRefsHook.advertiseRefs(this);
  1004. } catch (ServiceMayNotContinueException fail) {
  1005. if (fail.getMessage() != null) {
  1006. adv.writeOne("ERR " + fail.getMessage()); //$NON-NLS-1$
  1007. fail.setOutput();
  1008. }
  1009. throw fail;
  1010. }
  1011. adv.init(db);
  1012. adv.advertiseCapability(CAPABILITY_SIDE_BAND_64K);
  1013. adv.advertiseCapability(CAPABILITY_DELETE_REFS);
  1014. adv.advertiseCapability(CAPABILITY_REPORT_STATUS);
  1015. if (allowQuiet)
  1016. adv.advertiseCapability(CAPABILITY_QUIET);
  1017. String nonce = getPushCertificateParser().getAdvertiseNonce();
  1018. if (nonce != null) {
  1019. adv.advertiseCapability(nonce);
  1020. }
  1021. if (db.getRefDatabase().performsAtomicTransactions())
  1022. adv.advertiseCapability(CAPABILITY_ATOMIC);
  1023. if (allowOfsDelta)
  1024. adv.advertiseCapability(CAPABILITY_OFS_DELTA);
  1025. if (allowPushOptions) {
  1026. adv.advertiseCapability(CAPABILITY_PUSH_OPTIONS);
  1027. pushOptions = new ArrayList<>();
  1028. }
  1029. adv.advertiseCapability(OPTION_AGENT, UserAgent.get());
  1030. adv.send(getAdvertisedOrDefaultRefs());
  1031. for (ObjectId obj : advertisedHaves)
  1032. adv.advertiseHave(obj);
  1033. if (adv.isEmpty())
  1034. adv.advertiseId(ObjectId.zeroId(), "capabilities^{}"); //$NON-NLS-1$
  1035. adv.end();
  1036. }
  1037. /**
  1038. * Receive a list of commands from the input.
  1039. *
  1040. * @throws IOException
  1041. */
  1042. protected void recvCommands() throws IOException {
  1043. PushCertificateParser certParser = getPushCertificateParser();
  1044. boolean firstPkt = true;
  1045. try {
  1046. for (;;) {
  1047. String line;
  1048. try {
  1049. line = pckIn.readString();
  1050. } catch (EOFException eof) {
  1051. if (commands.isEmpty())
  1052. return;
  1053. throw eof;
  1054. }
  1055. if (line == PacketLineIn.END) {
  1056. break;
  1057. }
  1058. if (line.length() >= 48 && line.startsWith("shallow ")) { //$NON-NLS-1$
  1059. parseShallow(line.substring(8, 48));
  1060. continue;
  1061. }
  1062. if (firstPkt) {
  1063. firstPkt = false;
  1064. FirstLine firstLine = new FirstLine(line);
  1065. enabledCapabilities = firstLine.getCapabilities();
  1066. line = firstLine.getLine();
  1067. enableCapabilities();
  1068. if (line.equals(GitProtocolConstants.OPTION_PUSH_CERT)) {
  1069. certParser.receiveHeader(pckIn, !isBiDirectionalPipe());
  1070. continue;
  1071. }
  1072. }
  1073. if (line.equals(PushCertificateParser.BEGIN_SIGNATURE)) {
  1074. certParser.receiveSignature(pckIn);
  1075. continue;
  1076. }
  1077. ReceiveCommand cmd = parseCommand(line);
  1078. if (cmd.getRefName().equals(Constants.HEAD)) {
  1079. cmd.setResult(Result.REJECTED_CURRENT_BRANCH);
  1080. } else {
  1081. cmd.setRef(refs.get(cmd.getRefName()));
  1082. }
  1083. commands.add(cmd);
  1084. if (certParser.enabled()) {
  1085. certParser.addCommand(cmd);
  1086. }
  1087. }
  1088. pushCert = certParser.build();
  1089. } catch (PackProtocolException e) {
  1090. if (sideBand) {
  1091. try {
  1092. pckIn.discardUntilEnd();
  1093. } catch (IOException e2) {
  1094. // Ignore read failures attempting to discard.
  1095. }
  1096. }
  1097. fatalError(e.getMessage());
  1098. throw e;
  1099. }
  1100. }
  1101. private void parseShallow(String idStr) throws PackProtocolException {
  1102. ObjectId id;
  1103. try {
  1104. id = ObjectId.fromString(idStr);
  1105. } catch (InvalidObjectIdException e) {
  1106. throw new PackProtocolException(e.getMessage(), e);
  1107. }
  1108. clientShallowCommits.add(id);
  1109. }
  1110. static ReceiveCommand parseCommand(String line) throws PackProtocolException {
  1111. if (line == null || line.length() < 83) {
  1112. throw new PackProtocolException(
  1113. JGitText.get().errorInvalidProtocolWantedOldNewRef);
  1114. }
  1115. String oldStr = line.substring(0, 40);
  1116. String newStr = line.substring(41, 81);
  1117. ObjectId oldId, newId;
  1118. try {
  1119. oldId = ObjectId.fromString(oldStr);
  1120. newId = ObjectId.fromString(newStr);
  1121. } catch (InvalidObjectIdException e) {
  1122. throw new PackProtocolException(
  1123. JGitText.get().errorInvalidProtocolWantedOldNewRef, e);
  1124. }
  1125. String name = line.substring(82);
  1126. if (!Repository.isValidRefName(name)) {
  1127. throw new PackProtocolException(
  1128. JGitText.get().errorInvalidProtocolWantedOldNewRef);
  1129. }
  1130. return new ReceiveCommand(oldId, newId, name);
  1131. }
  1132. /** Enable capabilities based on a previously read capabilities line. */
  1133. protected void enableCapabilities() {
  1134. sideBand = isCapabilityEnabled(CAPABILITY_SIDE_BAND_64K);
  1135. quiet = allowQuiet && isCapabilityEnabled(CAPABILITY_QUIET);
  1136. usePushOptions = allowPushOptions
  1137. && isCapabilityEnabled(CAPABILITY_PUSH_OPTIONS);
  1138. if (sideBand) {
  1139. OutputStream out = rawOut;
  1140. rawOut = new SideBandOutputStream(CH_DATA, MAX_BUF, out);
  1141. msgOut = new SideBandOutputStream(CH_PROGRESS, MAX_BUF, out);
  1142. errOut = new SideBandOutputStream(CH_ERROR, MAX_BUF, out);
  1143. pckOut = new PacketLineOut(rawOut);
  1144. pckOut.setFlushOnEnd(false);
  1145. }
  1146. }
  1147. /**
  1148. * Sets the client's intention regarding push options.
  1149. *
  1150. * @param usePushOptions
  1151. * whether the client intends to use push options
  1152. * @since 4.5
  1153. */
  1154. public void setUsePushOptions(boolean usePushOptions) {
  1155. this.usePushOptions = usePushOptions;
  1156. }
  1157. /**
  1158. * Check if the peer requested a capability.
  1159. *
  1160. * @param name
  1161. * protocol name identifying the capability.
  1162. * @return true if the peer requested the capability to be enabled.
  1163. */
  1164. protected boolean isCapabilityEnabled(String name) {
  1165. return enabledCapabilities.contains(name);
  1166. }
  1167. /** @return true if a pack is expected based on the list of commands. */
  1168. protected boolean needPack() {
  1169. for (final ReceiveCommand cmd : commands) {
  1170. if (cmd.getType() != ReceiveCommand.Type.DELETE)
  1171. return true;
  1172. }
  1173. return false;
  1174. }
  1175. /**
  1176. * Receive a pack from the input and store it in the repository.
  1177. *
  1178. * @throws IOException
  1179. * an error occurred reading or indexing the pack.
  1180. */
  1181. private void receivePack() throws IOException {
  1182. // It might take the client a while to pack the objects it needs
  1183. // to send to us. We should increase our timeout so we don't
  1184. // abort while the client is computing.
  1185. //
  1186. if (timeoutIn != null)
  1187. timeoutIn.setTimeout(10 * timeout * 1000);
  1188. ProgressMonitor receiving = NullProgressMonitor.INSTANCE;
  1189. ProgressMonitor resolving = NullProgressMonitor.INSTANCE;
  1190. if (sideBand && !quiet)
  1191. resolving = new SideBandProgressMonitor(msgOut);
  1192. try (ObjectInserter ins = db.newObjectInserter()) {
  1193. String lockMsg = "jgit receive-pack"; //$NON-NLS-1$
  1194. if (getRefLogIdent() != null)
  1195. lockMsg += " from " + getRefLogIdent().toExternalString(); //$NON-NLS-1$
  1196. parser = ins.newPackParser(rawIn);
  1197. parser.setAllowThin(true);
  1198. parser.setNeedNewObjectIds(checkReferencedIsReachable);
  1199. parser.setNeedBaseObjectIds(checkReferencedIsReachable);
  1200. parser.setCheckEofAfterPackFooter(!biDirectionalPipe
  1201. && !isExpectDataAfterPackFooter());
  1202. parser.setExpectDataAfterPackFooter(isExpectDataAfterPackFooter());
  1203. parser.setObjectChecker(objectChecker);
  1204. parser.setLockMessage(lockMsg);
  1205. parser.setMaxObjectSizeLimit(maxObjectSizeLimit);
  1206. packLock = parser.parse(receiving, resolving);
  1207. packSize = Long.valueOf(parser.getPackSize());
  1208. ins.flush();
  1209. }
  1210. if (timeoutIn != null)
  1211. timeoutIn.setTimeout(timeout * 1000);
  1212. }
  1213. private boolean needCheckConnectivity() {
  1214. return isCheckReceivedObjects()
  1215. || isCheckReferencedObjectsAreReachable()
  1216. || !getClientShallowCommits().isEmpty();
  1217. }
  1218. private void checkConnectivity() throws IOException {
  1219. ObjectIdSubclassMap<ObjectId> baseObjects = null;
  1220. ObjectIdSubclassMap<ObjectId> providedObjects = null;
  1221. ProgressMonitor checking = NullProgressMonitor.INSTANCE;
  1222. if (sideBand && !quiet) {
  1223. SideBandProgressMonitor m = new SideBandProgressMonitor(msgOut);
  1224. m.setDelayStart(750, TimeUnit.MILLISECONDS);
  1225. checking = m;
  1226. }
  1227. if (checkReferencedIsReachable) {
  1228. baseObjects = parser.getBaseObjectIds();
  1229. providedObjects = parser.getNewObjectIds();
  1230. }
  1231. parser = null;
  1232. try (final ObjectWalk ow = new ObjectWalk(db)) {
  1233. if (baseObjects != null) {
  1234. ow.sort(RevSort.TOPO);
  1235. if (!baseObjects.isEmpty())
  1236. ow.sort(RevSort.BOUNDARY, true);
  1237. }
  1238. for (final ReceiveCommand cmd : commands) {
  1239. if (cmd.getResult() != Result.NOT_ATTEMPTED)
  1240. continue;
  1241. if (cmd.getType() == ReceiveCommand.Type.DELETE)
  1242. continue;
  1243. ow.markStart(ow.parseAny(cmd.getNewId()));
  1244. }
  1245. for (final ObjectId have : advertisedHaves) {
  1246. RevObject o = ow.parseAny(have);
  1247. ow.markUninteresting(o);
  1248. if (baseObjects != null && !baseObjects.isEmpty()) {
  1249. o = ow.peel(o);
  1250. if (o instanceof RevCommit)
  1251. o = ((RevCommit) o).getTree();
  1252. if (o instanceof RevTree)
  1253. ow.markUninteresting(o);
  1254. }
  1255. }
  1256. checking.beginTask(JGitText.get().countingObjects,
  1257. ProgressMonitor.UNKNOWN);
  1258. RevCommit c;
  1259. while ((c = ow.next()) != null) {
  1260. checking.update(1);
  1261. if (providedObjects != null //
  1262. && !c.has(RevFlag.UNINTERESTING) //
  1263. && !providedObjects.contains(c))
  1264. throw new MissingObjectException(c, Constants.TYPE_COMMIT);
  1265. }
  1266. RevObject o;
  1267. while ((o = ow.nextObject()) != null) {
  1268. checking.update(1);
  1269. if (o.has(RevFlag.UNINTERESTING))
  1270. continue;
  1271. if (providedObjects != null) {
  1272. if (providedObjects.contains(o))
  1273. continue;
  1274. else
  1275. throw new MissingObjectException(o, o.getType());
  1276. }
  1277. if (o instanceof RevBlob && !db.hasObject(o))
  1278. throw new MissingObjectException(o, Constants.TYPE_BLOB);
  1279. }
  1280. checking.endTask();
  1281. if (baseObjects != null) {
  1282. for (ObjectId id : baseObjects) {
  1283. o = ow.parseAny(id);
  1284. if (!o.has(RevFlag.UNINTERESTING))
  1285. throw new MissingObjectException(o, o.getType());
  1286. }
  1287. }
  1288. }
  1289. }
  1290. /** Validate the command list. */
  1291. protected void validateCommands() {
  1292. for (final ReceiveCommand cmd : commands) {
  1293. final Ref ref = cmd.getRef();
  1294. if (cmd.getResult() != Result.NOT_ATTEMPTED)
  1295. continue;
  1296. if (cmd.getType() == ReceiveCommand.Type.DELETE) {
  1297. if (!isAllowDeletes()) {
  1298. // Deletes are not supported on this repository.
  1299. cmd.setResult(Result.REJECTED_NODELETE);
  1300. continue;
  1301. }
  1302. if (!isAllowBranchDeletes()
  1303. && ref.getName().startsWith(Constants.R_HEADS)) {
  1304. // Branches cannot be deleted, but other refs can.
  1305. cmd.setResult(Result.REJECTED_NODELETE);
  1306. continue;
  1307. }
  1308. }
  1309. if (cmd.getType() == ReceiveCommand.Type.CREATE) {
  1310. if (!isAllowCreates()) {
  1311. cmd.setResult(Result.REJECTED_NOCREATE);
  1312. continue;
  1313. }
  1314. if (ref != null && !isAllowNonFastForwards()) {
  1315. // Creation over an existing ref is certainly not going
  1316. // to be a fast-forward update. We can reject it early.
  1317. //
  1318. cmd.setResult(Result.REJECTED_NONFASTFORWARD);
  1319. continue;
  1320. }
  1321. if (ref != null) {
  1322. // A well behaved client shouldn't have sent us a
  1323. // create command for a ref we advertised to it.
  1324. //
  1325. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1326. JGitText.get().refAlreadyExists);
  1327. continue;
  1328. }
  1329. }
  1330. if (cmd.getType() == ReceiveCommand.Type.DELETE && ref != null) {
  1331. ObjectId id = ref.getObjectId();
  1332. if (id == null) {
  1333. id = ObjectId.zeroId();
  1334. }
  1335. if (!ObjectId.zeroId().equals(cmd.getOldId())
  1336. && !id.equals(cmd.getOldId())) {
  1337. // Delete commands can be sent with the old id matching our
  1338. // advertised value, *OR* with the old id being 0{40}. Any
  1339. // other requested old id is invalid.
  1340. //
  1341. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1342. JGitText.get().invalidOldIdSent);
  1343. continue;
  1344. }
  1345. }
  1346. if (cmd.getType() == ReceiveCommand.Type.UPDATE) {
  1347. if (ref == null) {
  1348. // The ref must have been advertised in order to be updated.
  1349. //
  1350. cmd.setResult(Result.REJECTED_OTHER_REASON, JGitText.get().noSuchRef);
  1351. continue;
  1352. }
  1353. ObjectId id = ref.getObjectId();
  1354. if (id == null) {
  1355. // We cannot update unborn branch
  1356. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1357. JGitText.get().cannotUpdateUnbornBranch);
  1358. continue;
  1359. }
  1360. if (!id.equals(cmd.getOldId())) {
  1361. // A properly functioning client will send the same
  1362. // object id we advertised.
  1363. //
  1364. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1365. JGitText.get().invalidOldIdSent);
  1366. continue;
  1367. }
  1368. // Is this possibly a non-fast-forward style update?
  1369. //
  1370. RevObject oldObj, newObj;
  1371. try {
  1372. oldObj = walk.parseAny(cmd.getOldId());
  1373. } catch (IOException e) {
  1374. cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd
  1375. .getOldId().name());
  1376. continue;
  1377. }
  1378. try {
  1379. newObj = walk.parseAny(cmd.getNewId());
  1380. } catch (IOException e) {
  1381. cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd
  1382. .getNewId().name());
  1383. continue;
  1384. }
  1385. if (oldObj instanceof RevCommit && newObj instanceof RevCommit) {
  1386. try {
  1387. if (walk.isMergedInto((RevCommit) oldObj,
  1388. (RevCommit) newObj))
  1389. cmd.setTypeFastForwardUpdate();
  1390. else
  1391. cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
  1392. } catch (MissingObjectException e) {
  1393. cmd.setResult(Result.REJECTED_MISSING_OBJECT, e
  1394. .getMessage());
  1395. } catch (IOException e) {
  1396. cmd.setResult(Result.REJECTED_OTHER_REASON);
  1397. }
  1398. } else {
  1399. cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
  1400. }
  1401. if (cmd.getType() == ReceiveCommand.Type.UPDATE_NONFASTFORWARD
  1402. && !isAllowNonFastForwards()) {
  1403. cmd.setResult(Result.REJECTED_NONFASTFORWARD);
  1404. continue;
  1405. }
  1406. }
  1407. if (!cmd.getRefName().startsWith(Constants.R_REFS)
  1408. || !Repository.isValidRefName(cmd.getRefName())) {
  1409. cmd.setResult(Result.REJECTED_OTHER_REASON, JGitText.get().funnyRefname);
  1410. }
  1411. }
  1412. }
  1413. /**
  1414. * @return if any commands have been rejected so far.
  1415. * @since 3.6
  1416. */
  1417. protected boolean anyRejects() {
  1418. for (ReceiveCommand cmd : commands) {
  1419. if (cmd.getResult() != Result.NOT_ATTEMPTED && cmd.getResult() != Result.OK)
  1420. return true;
  1421. }
  1422. return false;
  1423. }
  1424. /**
  1425. * Set the result to fail for any command that was not processed yet.
  1426. * @since 3.6
  1427. */
  1428. protected void failPendingCommands() {
  1429. ReceiveCommand.abort(commands);
  1430. }
  1431. /**
  1432. * Filter the list of commands according to result.
  1433. *
  1434. * @param want
  1435. * desired status to filter by.
  1436. * @return a copy of the command list containing only those commands with the
  1437. * desired status.
  1438. */
  1439. protected List<ReceiveCommand> filterCommands(final Result want) {
  1440. return ReceiveCommand.filter(commands, want);
  1441. }
  1442. /** Execute commands to update references. */
  1443. protected void executeCommands() {
  1444. List<ReceiveCommand> toApply = filterCommands(Result.NOT_ATTEMPTED);
  1445. if (toApply.isEmpty())
  1446. return;
  1447. ProgressMonitor updating = NullProgressMonitor.INSTANCE;
  1448. if (sideBand) {
  1449. SideBandProgressMonitor pm = new SideBandProgressMonitor(msgOut);
  1450. pm.setDelayStart(250, TimeUnit.MILLISECONDS);
  1451. updating = pm;
  1452. }
  1453. BatchRefUpdate batch = db.getRefDatabase().newBatchUpdate();
  1454. batch.setAllowNonFastForwards(isAllowNonFastForwards());
  1455. batch.setAtomic(isAtomic());
  1456. batch.setRefLogIdent(getRefLogIdent());
  1457. batch.setRefLogMessage("push", true); //$NON-NLS-1$
  1458. batch.addCommand(toApply);
  1459. try {
  1460. batch.setPushCertificate(getPushCertificate());
  1461. batch.execute(walk, updating);
  1462. } catch (IOException err) {
  1463. for (ReceiveCommand cmd : toApply) {
  1464. if (cmd.getResult() == Result.NOT_ATTEMPTED)
  1465. cmd.reject(err);
  1466. }
  1467. }
  1468. }
  1469. /**
  1470. * Send a status report.
  1471. *
  1472. * @param forClient
  1473. * true if this report is for a Git client, false if it is for an
  1474. * end-user.
  1475. * @param unpackError
  1476. * an error that occurred during unpacking, or {@code null}
  1477. * @param out
  1478. * the reporter for sending the status strings.
  1479. * @throws IOException
  1480. * an error occurred writing the status report.
  1481. */
  1482. protected void sendStatusReport(final boolean forClient,
  1483. final Throwable unpackError, final Reporter out) throws IOException {
  1484. if (unpackError != null) {
  1485. out.sendString("unpack error " + unpackError.getMessage()); //$NON-NLS-1$
  1486. if (forClient) {
  1487. for (final ReceiveCommand cmd : commands) {
  1488. out.sendString("ng " + cmd.getRefName() //$NON-NLS-1$
  1489. + " n/a (unpacker error)"); //$NON-NLS-1$
  1490. }
  1491. }
  1492. return;
  1493. }
  1494. if (forClient)
  1495. out.sendString("unpack ok"); //$NON-NLS-1$
  1496. for (final ReceiveCommand cmd : commands) {
  1497. if (cmd.getResult() == Result.OK) {
  1498. if (forClient)
  1499. out.sendString("ok " + cmd.getRefName()); //$NON-NLS-1$
  1500. continue;
  1501. }
  1502. final StringBuilder r = new StringBuilder();
  1503. if (forClient)
  1504. r.append("ng ").append(cmd.getRefName()).append(" "); //$NON-NLS-1$ //$NON-NLS-2$
  1505. else
  1506. r.append(" ! [rejected] ").append(cmd.getRefName()).append(" ("); //$NON-NLS-1$ //$NON-NLS-2$
  1507. switch (cmd.getResult()) {
  1508. case NOT_ATTEMPTED:
  1509. r.append("server bug; ref not processed"); //$NON-NLS-1$
  1510. break;
  1511. case REJECTED_NOCREATE:
  1512. r.append("creation prohibited"); //$NON-NLS-1$
  1513. break;
  1514. case REJECTED_NODELETE:
  1515. r.append("deletion prohibited"); //$NON-NLS-1$
  1516. break;
  1517. case REJECTED_NONFASTFORWARD:
  1518. r.append("non-fast forward"); //$NON-NLS-1$
  1519. break;
  1520. case REJECTED_CURRENT_BRANCH:
  1521. r.append("branch is currently checked out"); //$NON-NLS-1$
  1522. break;
  1523. case REJECTED_MISSING_OBJECT:
  1524. if (cmd.getMessage() == null)
  1525. r.append("missing object(s)"); //$NON-NLS-1$
  1526. else if (cmd.getMessage().length() == Constants.OBJECT_ID_STRING_LENGTH) {
  1527. r.append("object "); //$NON-NLS-1$
  1528. r.append(cmd.getMessage());
  1529. r.append(" missing"); //$NON-NLS-1$
  1530. } else
  1531. r.append(cmd.getMessage());
  1532. break;
  1533. case REJECTED_OTHER_REASON:
  1534. if (cmd.getMessage() == null)
  1535. r.append("unspecified reason"); //$NON-NLS-1$
  1536. else
  1537. r.append(cmd.getMessage());
  1538. break;
  1539. case LOCK_FAILURE:
  1540. r.append("failed to lock"); //$NON-NLS-1$
  1541. break;
  1542. case OK:
  1543. // We shouldn't have reached this case (see 'ok' case above).
  1544. continue;
  1545. }
  1546. if (!forClient)
  1547. r.append(")"); //$NON-NLS-1$
  1548. out.sendString(r.toString());
  1549. }
  1550. }
  1551. /**
  1552. * Close and flush (if necessary) the underlying streams.
  1553. *
  1554. * @throws IOException
  1555. */
  1556. protected void close() throws IOException {
  1557. if (sideBand) {
  1558. // If we are using side band, we need to send a final
  1559. // flush-pkt to tell the remote peer the side band is
  1560. // complete and it should stop decoding. We need to
  1561. // use the original output stream as rawOut is now the
  1562. // side band data channel.
  1563. //
  1564. ((SideBandOutputStream) msgOut).flushBuffer();
  1565. ((SideBandOutputStream) rawOut).flushBuffer();
  1566. PacketLineOut plo = new PacketLineOut(origOut);
  1567. plo.setFlushOnEnd(false);
  1568. plo.end();
  1569. }
  1570. if (biDirectionalPipe) {
  1571. // If this was a native git connection, flush the pipe for
  1572. // the caller. For smart HTTP we don't do this flush and
  1573. // instead let the higher level HTTP servlet code do it.
  1574. //
  1575. if (!sideBand && msgOut != null)
  1576. msgOut.flush();
  1577. rawOut.flush();
  1578. }
  1579. }
  1580. /**
  1581. * Release any resources used by this object.
  1582. *
  1583. * @throws IOException
  1584. * the pack could not be unlocked.
  1585. */
  1586. protected void release() throws IOException {
  1587. walk.close();
  1588. unlockPack();
  1589. timeoutIn = null;
  1590. rawIn = null;
  1591. rawOut = null;
  1592. msgOut = null;
  1593. pckIn = null;
  1594. pckOut = null;
  1595. refs = null;
  1596. // Keep the capabilities. If responses are sent after this release
  1597. // we need to remember at least whether sideband communication has to be
  1598. // used
  1599. commands = null;
  1600. if (timer != null) {
  1601. try {
  1602. timer.terminate();
  1603. } finally {
  1604. timer = null;
  1605. }
  1606. }
  1607. }
  1608. /** Interface for reporting status messages. */
  1609. static abstract class Reporter {
  1610. abstract void sendString(String s) throws IOException;
  1611. }
  1612. }