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

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