You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ReceivePack.java 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296
  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.BasePackPushConnection.CAPABILITY_DELETE_REFS;
  45. import static org.eclipse.jgit.transport.BasePackPushConnection.CAPABILITY_OFS_DELTA;
  46. import static org.eclipse.jgit.transport.BasePackPushConnection.CAPABILITY_REPORT_STATUS;
  47. import static org.eclipse.jgit.transport.BasePackPushConnection.CAPABILITY_SIDE_BAND_64K;
  48. import static org.eclipse.jgit.transport.SideBandOutputStream.CH_DATA;
  49. import static org.eclipse.jgit.transport.SideBandOutputStream.CH_PROGRESS;
  50. import static org.eclipse.jgit.transport.SideBandOutputStream.MAX_BUF;
  51. import java.io.EOFException;
  52. import java.io.IOException;
  53. import java.io.InputStream;
  54. import java.io.OutputStream;
  55. import java.text.MessageFormat;
  56. import java.util.ArrayList;
  57. import java.util.Collections;
  58. import java.util.HashSet;
  59. import java.util.List;
  60. import java.util.Map;
  61. import java.util.Set;
  62. import java.util.concurrent.TimeUnit;
  63. import org.eclipse.jgit.JGitText;
  64. import org.eclipse.jgit.errors.MissingObjectException;
  65. import org.eclipse.jgit.errors.PackProtocolException;
  66. import org.eclipse.jgit.errors.UnpackException;
  67. import org.eclipse.jgit.lib.Config;
  68. import org.eclipse.jgit.lib.Constants;
  69. import org.eclipse.jgit.lib.NullProgressMonitor;
  70. import org.eclipse.jgit.lib.ObjectId;
  71. import org.eclipse.jgit.lib.ObjectIdSubclassMap;
  72. import org.eclipse.jgit.lib.ObjectInserter;
  73. import org.eclipse.jgit.lib.PersonIdent;
  74. import org.eclipse.jgit.lib.ProgressMonitor;
  75. import org.eclipse.jgit.lib.Ref;
  76. import org.eclipse.jgit.lib.Repository;
  77. import org.eclipse.jgit.lib.Config.SectionParser;
  78. import org.eclipse.jgit.revwalk.ObjectWalk;
  79. import org.eclipse.jgit.revwalk.RevBlob;
  80. import org.eclipse.jgit.revwalk.RevCommit;
  81. import org.eclipse.jgit.revwalk.RevFlag;
  82. import org.eclipse.jgit.revwalk.RevObject;
  83. import org.eclipse.jgit.revwalk.RevSort;
  84. import org.eclipse.jgit.revwalk.RevTree;
  85. import org.eclipse.jgit.revwalk.RevWalk;
  86. import org.eclipse.jgit.storage.file.PackLock;
  87. import org.eclipse.jgit.transport.ReceiveCommand.Result;
  88. import org.eclipse.jgit.transport.RefAdvertiser.PacketLineOutRefAdvertiser;
  89. import org.eclipse.jgit.util.io.InterruptTimer;
  90. import org.eclipse.jgit.util.io.TimeoutInputStream;
  91. import org.eclipse.jgit.util.io.TimeoutOutputStream;
  92. /**
  93. * Implements the server side of a push connection, receiving objects.
  94. */
  95. public class ReceivePack {
  96. /** Data in the first line of a request, the line itself plus capabilities. */
  97. public static class FirstLine {
  98. private final String line;
  99. private final Set<String> capabilities;
  100. /**
  101. * Parse the first line of a receive-pack request.
  102. *
  103. * @param line
  104. * line from the client.
  105. */
  106. public FirstLine(String line) {
  107. final HashSet<String> caps = new HashSet<String>();
  108. final int nul = line.indexOf('\0');
  109. if (nul >= 0) {
  110. for (String c : line.substring(nul + 1).split(" "))
  111. caps.add(c);
  112. }
  113. this.line = line.substring(0, nul);
  114. this.capabilities = Collections.unmodifiableSet(caps);
  115. }
  116. /** @return non-capabilities part of the line. */
  117. public String getLine() {
  118. return line;
  119. }
  120. /** @return capabilities parsed from the line. */
  121. public Set<String> getCapabilities() {
  122. return capabilities;
  123. }
  124. }
  125. /** Database we write the stored objects into. */
  126. private final Repository db;
  127. /** Revision traversal support over {@link #db}. */
  128. private final RevWalk walk;
  129. /**
  130. * Is the client connection a bi-directional socket or pipe?
  131. * <p>
  132. * If true, this class assumes it can perform multiple read and write cycles
  133. * with the client over the input and output streams. This matches the
  134. * functionality available with a standard TCP/IP connection, or a local
  135. * operating system or in-memory pipe.
  136. * <p>
  137. * If false, this class runs in a read everything then output results mode,
  138. * making it suitable for single round-trip systems RPCs such as HTTP.
  139. */
  140. private boolean biDirectionalPipe = true;
  141. /** Should an incoming transfer validate objects? */
  142. private boolean checkReceivedObjects;
  143. /** Should an incoming transfer permit create requests? */
  144. private boolean allowCreates;
  145. /** Should an incoming transfer permit delete requests? */
  146. private boolean allowDeletes;
  147. /** Should an incoming transfer permit non-fast-forward requests? */
  148. private boolean allowNonFastForwards;
  149. private boolean allowOfsDelta;
  150. /** Identity to record action as within the reflog. */
  151. private PersonIdent refLogIdent;
  152. /** Hook used while advertising the refs to the client. */
  153. private AdvertiseRefsHook advertiseRefsHook;
  154. /** Filter used while advertising the refs to the client. */
  155. private RefFilter refFilter;
  156. /** Hook to validate the update commands before execution. */
  157. private PreReceiveHook preReceive;
  158. /** Hook to report on the commands after execution. */
  159. private PostReceiveHook postReceive;
  160. /** Timeout in seconds to wait for client interaction. */
  161. private int timeout;
  162. /** Timer to manage {@link #timeout}. */
  163. private InterruptTimer timer;
  164. private TimeoutInputStream timeoutIn;
  165. private InputStream rawIn;
  166. private OutputStream rawOut;
  167. private OutputStream msgOut;
  168. private final MessageOutputWrapper msgOutWrapper = new MessageOutputWrapper();
  169. private PacketLineIn pckIn;
  170. private PacketLineOut pckOut;
  171. private PackParser parser;
  172. /** The refs we advertised as existing at the start of the connection. */
  173. private Map<String, Ref> refs;
  174. /** All SHA-1s shown to the client, which can be possible edges. */
  175. private Set<ObjectId> advertisedHaves;
  176. /** Capabilities requested by the client. */
  177. private Set<String> enabledCapabilities;
  178. /** Commands to execute, as received by the client. */
  179. private List<ReceiveCommand> commands;
  180. /** Error to display instead of advertising the references. */
  181. private StringBuilder advertiseError;
  182. /** An exception caught while unpacking and fsck'ing the objects. */
  183. private Throwable unpackError;
  184. /** If {@link BasePackPushConnection#CAPABILITY_REPORT_STATUS} is enabled. */
  185. private boolean reportStatus;
  186. /** If {@link BasePackPushConnection#CAPABILITY_SIDE_BAND_64K} is enabled. */
  187. private boolean sideBand;
  188. /** Lock around the received pack file, while updating refs. */
  189. private PackLock packLock;
  190. private boolean checkReferencedIsReachable;
  191. /** Git object size limit */
  192. private long maxObjectSizeLimit;
  193. /**
  194. * Create a new pack receive for an open repository.
  195. *
  196. * @param into
  197. * the destination repository.
  198. */
  199. public ReceivePack(final Repository into) {
  200. db = into;
  201. walk = new RevWalk(db);
  202. final ReceiveConfig cfg = db.getConfig().get(ReceiveConfig.KEY);
  203. checkReceivedObjects = cfg.checkReceivedObjects;
  204. allowCreates = cfg.allowCreates;
  205. allowDeletes = cfg.allowDeletes;
  206. allowNonFastForwards = cfg.allowNonFastForwards;
  207. allowOfsDelta = cfg.allowOfsDelta;
  208. advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  209. refFilter = RefFilter.DEFAULT;
  210. preReceive = PreReceiveHook.NULL;
  211. postReceive = PostReceiveHook.NULL;
  212. advertisedHaves = new HashSet<ObjectId>();
  213. }
  214. private static class ReceiveConfig {
  215. static final SectionParser<ReceiveConfig> KEY = new SectionParser<ReceiveConfig>() {
  216. public ReceiveConfig parse(final Config cfg) {
  217. return new ReceiveConfig(cfg);
  218. }
  219. };
  220. final boolean checkReceivedObjects;
  221. final boolean allowCreates;
  222. final boolean allowDeletes;
  223. final boolean allowNonFastForwards;
  224. final boolean allowOfsDelta;
  225. ReceiveConfig(final Config config) {
  226. checkReceivedObjects = config.getBoolean("receive", "fsckobjects",
  227. false);
  228. allowCreates = true;
  229. allowDeletes = !config.getBoolean("receive", "denydeletes", false);
  230. allowNonFastForwards = !config.getBoolean("receive",
  231. "denynonfastforwards", false);
  232. allowOfsDelta = config.getBoolean("repack", "usedeltabaseoffset",
  233. true);
  234. }
  235. }
  236. /**
  237. * Output stream that wraps the current {@link #msgOut}.
  238. * <p>
  239. * We don't want to expose {@link #msgOut} directly because it can change
  240. * several times over the course of a session.
  241. */
  242. private class MessageOutputWrapper extends OutputStream {
  243. @Override
  244. public void write(int ch) {
  245. if (msgOut != null) {
  246. try {
  247. msgOut.write(ch);
  248. } catch (IOException e) {
  249. // Ignore write failures.
  250. }
  251. }
  252. }
  253. @Override
  254. public void write(byte[] b, int off, int len) {
  255. if (msgOut != null) {
  256. try {
  257. msgOut.write(b, off, len);
  258. } catch (IOException e) {
  259. // Ignore write failures.
  260. }
  261. }
  262. }
  263. @Override
  264. public void write(byte[] b) {
  265. write(b, 0, b.length);
  266. }
  267. @Override
  268. public void flush() {
  269. if (msgOut != null) {
  270. try {
  271. msgOut.flush();
  272. } catch (IOException e) {
  273. // Ignore write failures.
  274. }
  275. }
  276. }
  277. }
  278. /** @return the repository this receive completes into. */
  279. public final Repository getRepository() {
  280. return db;
  281. }
  282. /** @return the RevWalk instance used by this connection. */
  283. public final RevWalk getRevWalk() {
  284. return walk;
  285. }
  286. /**
  287. * Get refs which were advertised to the client.
  288. *
  289. * @return all refs which were advertised to the client, or null if
  290. * {@link #setAdvertisedRefs(Map, Set)} has not been called yet.
  291. */
  292. public final Map<String, Ref> getAdvertisedRefs() {
  293. return refs;
  294. }
  295. /**
  296. * Set the refs advertised by this ReceivePack.
  297. * <p>
  298. * Intended to be called from a {@link PreReceiveHook}.
  299. *
  300. * @param allRefs
  301. * explicit set of references to claim as advertised by this
  302. * ReceivePack instance. This overrides any references that
  303. * may exist in the source repository. The map is passed
  304. * to the configured {@link #getRefFilter()}. If null, assumes
  305. * all refs were advertised.
  306. * @param additionalHaves
  307. * explicit set of additional haves to claim as advertised. If
  308. * null, assumes the default set of additional haves from the
  309. * repository.
  310. */
  311. public void setAdvertisedRefs(Map<String, Ref> allRefs,
  312. Set<ObjectId> additionalHaves) {
  313. refs = allRefs != null ? allRefs : db.getAllRefs();
  314. refs = refFilter.filter(refs);
  315. Ref head = refs.get(Constants.HEAD);
  316. if (head != null && head.isSymbolic())
  317. refs.remove(Constants.HEAD);
  318. for (Ref ref : refs.values()) {
  319. if (ref.getObjectId() != null)
  320. advertisedHaves.add(ref.getObjectId());
  321. }
  322. if (additionalHaves != null)
  323. advertisedHaves.addAll(additionalHaves);
  324. else
  325. advertisedHaves.addAll(db.getAdditionalHaves());
  326. }
  327. /**
  328. * Get objects advertised to the client.
  329. *
  330. * @return the set of objects advertised to the as present in this repository,
  331. * or null if {@link #setAdvertisedRefs(Map, Set)} has not been called
  332. * yet.
  333. */
  334. public final Set<ObjectId> getAdvertisedObjects() {
  335. return advertisedHaves;
  336. }
  337. /**
  338. * @return true if this instance will validate all referenced, but not
  339. * supplied by the client, objects are reachable from another
  340. * reference.
  341. */
  342. public boolean isCheckReferencedObjectsAreReachable() {
  343. return checkReferencedIsReachable;
  344. }
  345. /**
  346. * Validate all referenced but not supplied objects are reachable.
  347. * <p>
  348. * If enabled, this instance will verify that references to objects not
  349. * contained within the received pack are already reachable through at least
  350. * one other reference displayed as part of {@link #getAdvertisedRefs()}.
  351. * <p>
  352. * This feature is useful when the application doesn't trust the client to
  353. * not provide a forged SHA-1 reference to an object, in an attempt to
  354. * access parts of the DAG that they aren't allowed to see and which have
  355. * been hidden from them via the configured {@link AdvertiseRefsHook} or
  356. * {@link RefFilter}.
  357. * <p>
  358. * Enabling this feature may imply at least some, if not all, of the same
  359. * functionality performed by {@link #setCheckReceivedObjects(boolean)}.
  360. * Applications are encouraged to enable both features, if desired.
  361. *
  362. * @param b
  363. * {@code true} to enable the additional check.
  364. */
  365. public void setCheckReferencedObjectsAreReachable(boolean b) {
  366. this.checkReferencedIsReachable = b;
  367. }
  368. /**
  369. * @return true if this class expects a bi-directional pipe opened between
  370. * the client and itself. The default is true.
  371. */
  372. public boolean isBiDirectionalPipe() {
  373. return biDirectionalPipe;
  374. }
  375. /**
  376. * @param twoWay
  377. * if true, this class will assume the socket is a fully
  378. * bidirectional pipe between the two peers and takes advantage
  379. * of that by first transmitting the known refs, then waiting to
  380. * read commands. If false, this class assumes it must read the
  381. * commands before writing output and does not perform the
  382. * initial advertising.
  383. */
  384. public void setBiDirectionalPipe(final boolean twoWay) {
  385. biDirectionalPipe = twoWay;
  386. }
  387. /**
  388. * @return true if this instance will verify received objects are formatted
  389. * correctly. Validating objects requires more CPU time on this side
  390. * of the connection.
  391. */
  392. public boolean isCheckReceivedObjects() {
  393. return checkReceivedObjects;
  394. }
  395. /**
  396. * @param check
  397. * true to enable checking received objects; false to assume all
  398. * received objects are valid.
  399. */
  400. public void setCheckReceivedObjects(final boolean check) {
  401. checkReceivedObjects = check;
  402. }
  403. /** @return true if the client can request refs to be created. */
  404. public boolean isAllowCreates() {
  405. return allowCreates;
  406. }
  407. /**
  408. * @param canCreate
  409. * true to permit create ref commands to be processed.
  410. */
  411. public void setAllowCreates(final boolean canCreate) {
  412. allowCreates = canCreate;
  413. }
  414. /** @return true if the client can request refs to be deleted. */
  415. public boolean isAllowDeletes() {
  416. return allowDeletes;
  417. }
  418. /**
  419. * @param canDelete
  420. * true to permit delete ref commands to be processed.
  421. */
  422. public void setAllowDeletes(final boolean canDelete) {
  423. allowDeletes = canDelete;
  424. }
  425. /**
  426. * @return true if the client can request non-fast-forward updates of a ref,
  427. * possibly making objects unreachable.
  428. */
  429. public boolean isAllowNonFastForwards() {
  430. return allowNonFastForwards;
  431. }
  432. /**
  433. * @param canRewind
  434. * true to permit the client to ask for non-fast-forward updates
  435. * of an existing ref.
  436. */
  437. public void setAllowNonFastForwards(final boolean canRewind) {
  438. allowNonFastForwards = canRewind;
  439. }
  440. /** @return identity of the user making the changes in the reflog. */
  441. public PersonIdent getRefLogIdent() {
  442. return refLogIdent;
  443. }
  444. /**
  445. * Set the identity of the user appearing in the affected reflogs.
  446. * <p>
  447. * The timestamp portion of the identity is ignored. A new identity with the
  448. * current timestamp will be created automatically when the updates occur
  449. * and the log records are written.
  450. *
  451. * @param pi
  452. * identity of the user. If null the identity will be
  453. * automatically determined based on the repository
  454. * configuration.
  455. */
  456. public void setRefLogIdent(final PersonIdent pi) {
  457. refLogIdent = pi;
  458. }
  459. /** @return the hook used while advertising the refs to the client */
  460. public AdvertiseRefsHook getAdvertiseRefsHook() {
  461. return advertiseRefsHook;
  462. }
  463. /** @return the filter used while advertising the refs to the client */
  464. public RefFilter getRefFilter() {
  465. return refFilter;
  466. }
  467. /**
  468. * Set the hook used while advertising the refs to the client.
  469. * <p>
  470. * If the {@link AdvertiseRefsHook} chooses to call
  471. * {@link #setAdvertisedRefs(Map,Set)}, only refs set by this hook
  472. * <em>and</em> selected by the {@link RefFilter} will be shown to the client.
  473. * Clients may still attempt to create or update a reference not advertised by
  474. * the configured {@link AdvertiseRefsHook}. These attempts should be rejected
  475. * by a matching {@link PreReceiveHook}.
  476. *
  477. * @param advertiseRefsHook
  478. * the hook; may be null to show all refs.
  479. */
  480. public void setAdvertiseRefsHook(final AdvertiseRefsHook advertiseRefsHook) {
  481. if (advertiseRefsHook != null)
  482. this.advertiseRefsHook = advertiseRefsHook;
  483. else
  484. this.advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  485. }
  486. /**
  487. * Set the filter used while advertising the refs to the client.
  488. * <p>
  489. * Only refs allowed by this filter will be shown to the client.
  490. * The filter is run against the refs specified by the
  491. * {@link AdvertiseRefsHook} (if applicable).
  492. *
  493. * @param refFilter
  494. * the filter; may be null to show all refs.
  495. */
  496. public void setRefFilter(final RefFilter refFilter) {
  497. this.refFilter = refFilter != null ? refFilter : RefFilter.DEFAULT;
  498. }
  499. /** @return the hook invoked before updates occur. */
  500. public PreReceiveHook getPreReceiveHook() {
  501. return preReceive;
  502. }
  503. /**
  504. * Set the hook which is invoked prior to commands being executed.
  505. * <p>
  506. * Only valid commands (those which have no obvious errors according to the
  507. * received input and this instance's configuration) are passed into the
  508. * hook. The hook may mark a command with a result of any value other than
  509. * {@link Result#NOT_ATTEMPTED} to block its execution.
  510. * <p>
  511. * The hook may be called with an empty command collection if the current
  512. * set is completely invalid.
  513. *
  514. * @param h
  515. * the hook instance; may be null to disable the hook.
  516. */
  517. public void setPreReceiveHook(final PreReceiveHook h) {
  518. preReceive = h != null ? h : PreReceiveHook.NULL;
  519. }
  520. /** @return the hook invoked after updates occur. */
  521. public PostReceiveHook getPostReceiveHook() {
  522. return postReceive;
  523. }
  524. /**
  525. * Set the hook which is invoked after commands are executed.
  526. * <p>
  527. * Only successful commands (type is {@link Result#OK}) are passed into the
  528. * hook. The hook may be called with an empty command collection if the
  529. * current set all resulted in an error.
  530. *
  531. * @param h
  532. * the hook instance; may be null to disable the hook.
  533. */
  534. public void setPostReceiveHook(final PostReceiveHook h) {
  535. postReceive = h != null ? h : PostReceiveHook.NULL;
  536. }
  537. /** @return timeout (in seconds) before aborting an IO operation. */
  538. public int getTimeout() {
  539. return timeout;
  540. }
  541. /**
  542. * Set the timeout before willing to abort an IO call.
  543. *
  544. * @param seconds
  545. * number of seconds to wait (with no data transfer occurring)
  546. * before aborting an IO read or write operation with the
  547. * connected client.
  548. */
  549. public void setTimeout(final int seconds) {
  550. timeout = seconds;
  551. }
  552. /**
  553. * Set the maximum allowed Git object size.
  554. * <p>
  555. * If an object is larger than the given size the pack-parsing will throw an
  556. * exception aborting the receive-pack operation.
  557. *
  558. * @param limit
  559. * the Git object size limit. If zero then there is not limit.
  560. */
  561. public void setMaxObjectSizeLimit(final long limit) {
  562. maxObjectSizeLimit = limit;
  563. }
  564. /** @return all of the command received by the current request. */
  565. public List<ReceiveCommand> getAllCommands() {
  566. return Collections.unmodifiableList(commands);
  567. }
  568. /**
  569. * Send an error message to the client.
  570. * <p>
  571. * If any error messages are sent before the references are advertised to
  572. * the client, the errors will be sent instead of the advertisement and the
  573. * receive operation will be aborted. All clients should receive and display
  574. * such early stage errors.
  575. * <p>
  576. * If the reference advertisements have already been sent, messages are sent
  577. * in a side channel. If the client doesn't support receiving messages, the
  578. * message will be discarded, with no other indication to the caller or to
  579. * the client.
  580. * <p>
  581. * {@link PreReceiveHook}s should always try to use
  582. * {@link ReceiveCommand#setResult(Result, String)} with a result status of
  583. * {@link Result#REJECTED_OTHER_REASON} to indicate any reasons for
  584. * rejecting an update. Messages attached to a command are much more likely
  585. * to be returned to the client.
  586. *
  587. * @param what
  588. * string describing the problem identified by the hook. The
  589. * string must not end with an LF, and must not contain an LF.
  590. */
  591. public void sendError(final String what) {
  592. if (refs == null) {
  593. if (advertiseError == null)
  594. advertiseError = new StringBuilder();
  595. advertiseError.append(what).append('\n');
  596. } else {
  597. msgOutWrapper.write(Constants.encode("error: " + what + "\n"));
  598. }
  599. }
  600. /**
  601. * Send a message to the client, if it supports receiving them.
  602. * <p>
  603. * If the client doesn't support receiving messages, the message will be
  604. * discarded, with no other indication to the caller or to the client.
  605. *
  606. * @param what
  607. * string describing the problem identified by the hook. The
  608. * string must not end with an LF, and must not contain an LF.
  609. */
  610. public void sendMessage(final String what) {
  611. msgOutWrapper.write(Constants.encode(what + "\n"));
  612. }
  613. /** @return an underlying stream for sending messages to the client. */
  614. public OutputStream getMessageOutputStream() {
  615. return msgOutWrapper;
  616. }
  617. /**
  618. * Execute the receive task on the socket.
  619. *
  620. * @param input
  621. * raw input to read client commands and pack data from. Caller
  622. * must ensure the input is buffered, otherwise read performance
  623. * may suffer.
  624. * @param output
  625. * response back to the Git network client. Caller must ensure
  626. * the output is buffered, otherwise write performance may
  627. * suffer.
  628. * @param messages
  629. * secondary "notice" channel to send additional messages out
  630. * through. When run over SSH this should be tied back to the
  631. * standard error channel of the command execution. For most
  632. * other network connections this should be null.
  633. * @throws IOException
  634. */
  635. public void receive(final InputStream input, final OutputStream output,
  636. final OutputStream messages) throws IOException {
  637. try {
  638. rawIn = input;
  639. rawOut = output;
  640. msgOut = messages;
  641. if (timeout > 0) {
  642. final Thread caller = Thread.currentThread();
  643. timer = new InterruptTimer(caller.getName() + "-Timer");
  644. timeoutIn = new TimeoutInputStream(rawIn, timer);
  645. TimeoutOutputStream o = new TimeoutOutputStream(rawOut, timer);
  646. timeoutIn.setTimeout(timeout * 1000);
  647. o.setTimeout(timeout * 1000);
  648. rawIn = timeoutIn;
  649. rawOut = o;
  650. }
  651. pckIn = new PacketLineIn(rawIn);
  652. pckOut = new PacketLineOut(rawOut);
  653. pckOut.setFlushOnEnd(false);
  654. commands = new ArrayList<ReceiveCommand>();
  655. service();
  656. } finally {
  657. walk.release();
  658. try {
  659. if (sideBand) {
  660. // If we are using side band, we need to send a final
  661. // flush-pkt to tell the remote peer the side band is
  662. // complete and it should stop decoding. We need to
  663. // use the original output stream as rawOut is now the
  664. // side band data channel.
  665. //
  666. ((SideBandOutputStream) msgOut).flushBuffer();
  667. ((SideBandOutputStream) rawOut).flushBuffer();
  668. PacketLineOut plo = new PacketLineOut(output);
  669. plo.setFlushOnEnd(false);
  670. plo.end();
  671. }
  672. if (biDirectionalPipe) {
  673. // If this was a native git connection, flush the pipe for
  674. // the caller. For smart HTTP we don't do this flush and
  675. // instead let the higher level HTTP servlet code do it.
  676. //
  677. if (!sideBand && msgOut != null)
  678. msgOut.flush();
  679. rawOut.flush();
  680. }
  681. } finally {
  682. unlockPack();
  683. timeoutIn = null;
  684. rawIn = null;
  685. rawOut = null;
  686. msgOut = null;
  687. pckIn = null;
  688. pckOut = null;
  689. refs = null;
  690. enabledCapabilities = null;
  691. commands = null;
  692. if (timer != null) {
  693. try {
  694. timer.terminate();
  695. } finally {
  696. timer = null;
  697. }
  698. }
  699. }
  700. }
  701. }
  702. private Map<String, Ref> getAdvertisedOrDefaultRefs() {
  703. if (refs == null)
  704. setAdvertisedRefs(null, null);
  705. return refs;
  706. }
  707. private void service() throws IOException {
  708. if (biDirectionalPipe) {
  709. sendAdvertisedRefs(new PacketLineOutRefAdvertiser(pckOut));
  710. pckOut.flush();
  711. } else
  712. getAdvertisedOrDefaultRefs();
  713. if (advertiseError != null)
  714. return;
  715. recvCommands();
  716. if (!commands.isEmpty()) {
  717. enableCapabilities();
  718. if (needPack()) {
  719. try {
  720. receivePack();
  721. if (needCheckConnectivity())
  722. checkConnectivity();
  723. parser = null;
  724. unpackError = null;
  725. } catch (IOException err) {
  726. unpackError = err;
  727. } catch (RuntimeException err) {
  728. unpackError = err;
  729. } catch (Error err) {
  730. unpackError = err;
  731. }
  732. }
  733. if (unpackError == null) {
  734. validateCommands();
  735. executeCommands();
  736. }
  737. unlockPack();
  738. if (reportStatus) {
  739. sendStatusReport(true, new Reporter() {
  740. void sendString(final String s) throws IOException {
  741. pckOut.writeString(s + "\n");
  742. }
  743. });
  744. pckOut.end();
  745. } else if (msgOut != null) {
  746. sendStatusReport(false, new Reporter() {
  747. void sendString(final String s) throws IOException {
  748. msgOut.write(Constants.encode(s + "\n"));
  749. }
  750. });
  751. }
  752. postReceive.onPostReceive(this,
  753. ReceiveCommand.filter(commands, Result.OK));
  754. if (unpackError != null)
  755. throw new UnpackException(unpackError);
  756. }
  757. }
  758. private void unlockPack() throws IOException {
  759. if (packLock != null) {
  760. packLock.unlock();
  761. packLock = null;
  762. }
  763. }
  764. /**
  765. * Generate an advertisement of available refs and capabilities.
  766. *
  767. * @param adv
  768. * the advertisement formatter.
  769. * @throws IOException
  770. * the formatter failed to write an advertisement.
  771. * @throws ServiceMayNotContinueException
  772. * the hook denied advertisement.
  773. */
  774. public void sendAdvertisedRefs(final RefAdvertiser adv) throws IOException,
  775. ServiceMayNotContinueException {
  776. if (advertiseError != null) {
  777. adv.writeOne("ERR " + advertiseError);
  778. return;
  779. }
  780. try {
  781. advertiseRefsHook.advertiseRefs(this);
  782. } catch (ServiceMayNotContinueException fail) {
  783. if (fail.getMessage() != null) {
  784. adv.writeOne("ERR " + fail.getMessage());
  785. fail.setOutput();
  786. }
  787. throw fail;
  788. }
  789. adv.init(db);
  790. adv.advertiseCapability(CAPABILITY_SIDE_BAND_64K);
  791. adv.advertiseCapability(CAPABILITY_DELETE_REFS);
  792. adv.advertiseCapability(CAPABILITY_REPORT_STATUS);
  793. if (allowOfsDelta)
  794. adv.advertiseCapability(CAPABILITY_OFS_DELTA);
  795. adv.send(getAdvertisedOrDefaultRefs());
  796. for (ObjectId obj : advertisedHaves)
  797. adv.advertiseHave(obj);
  798. if (adv.isEmpty())
  799. adv.advertiseId(ObjectId.zeroId(), "capabilities^{}");
  800. adv.end();
  801. }
  802. private void recvCommands() throws IOException {
  803. for (;;) {
  804. String line;
  805. try {
  806. line = pckIn.readStringRaw();
  807. } catch (EOFException eof) {
  808. if (commands.isEmpty())
  809. return;
  810. throw eof;
  811. }
  812. if (line == PacketLineIn.END)
  813. break;
  814. if (commands.isEmpty()) {
  815. final FirstLine firstLine = new FirstLine(line);
  816. enabledCapabilities = firstLine.getCapabilities();
  817. line = firstLine.getLine();
  818. }
  819. if (line.length() < 83) {
  820. final String m = JGitText.get().errorInvalidProtocolWantedOldNewRef;
  821. sendError(m);
  822. throw new PackProtocolException(m);
  823. }
  824. final ObjectId oldId = ObjectId.fromString(line.substring(0, 40));
  825. final ObjectId newId = ObjectId.fromString(line.substring(41, 81));
  826. final String name = line.substring(82);
  827. final ReceiveCommand cmd = new ReceiveCommand(oldId, newId, name);
  828. if (name.equals(Constants.HEAD)) {
  829. cmd.setResult(Result.REJECTED_CURRENT_BRANCH);
  830. } else {
  831. cmd.setRef(refs.get(cmd.getRefName()));
  832. }
  833. commands.add(cmd);
  834. }
  835. }
  836. private void enableCapabilities() {
  837. reportStatus = enabledCapabilities.contains(CAPABILITY_REPORT_STATUS);
  838. sideBand = enabledCapabilities.contains(CAPABILITY_SIDE_BAND_64K);
  839. if (sideBand) {
  840. OutputStream out = rawOut;
  841. rawOut = new SideBandOutputStream(CH_DATA, MAX_BUF, out);
  842. msgOut = new SideBandOutputStream(CH_PROGRESS, MAX_BUF, out);
  843. pckOut = new PacketLineOut(rawOut);
  844. pckOut.setFlushOnEnd(false);
  845. }
  846. }
  847. private boolean needPack() {
  848. for (final ReceiveCommand cmd : commands) {
  849. if (cmd.getType() != ReceiveCommand.Type.DELETE)
  850. return true;
  851. }
  852. return false;
  853. }
  854. private void receivePack() throws IOException {
  855. // It might take the client a while to pack the objects it needs
  856. // to send to us. We should increase our timeout so we don't
  857. // abort while the client is computing.
  858. //
  859. if (timeoutIn != null)
  860. timeoutIn.setTimeout(10 * timeout * 1000);
  861. ProgressMonitor receiving = NullProgressMonitor.INSTANCE;
  862. ProgressMonitor resolving = NullProgressMonitor.INSTANCE;
  863. if (sideBand)
  864. resolving = new SideBandProgressMonitor(msgOut);
  865. ObjectInserter ins = db.newObjectInserter();
  866. try {
  867. String lockMsg = "jgit receive-pack";
  868. if (getRefLogIdent() != null)
  869. lockMsg += " from " + getRefLogIdent().toExternalString();
  870. parser = ins.newPackParser(rawIn);
  871. parser.setAllowThin(true);
  872. parser.setNeedNewObjectIds(checkReferencedIsReachable);
  873. parser.setNeedBaseObjectIds(checkReferencedIsReachable);
  874. parser.setCheckEofAfterPackFooter(!biDirectionalPipe);
  875. parser.setObjectChecking(isCheckReceivedObjects());
  876. parser.setLockMessage(lockMsg);
  877. parser.setMaxObjectSizeLimit(maxObjectSizeLimit);
  878. packLock = parser.parse(receiving, resolving);
  879. ins.flush();
  880. } finally {
  881. ins.release();
  882. }
  883. if (timeoutIn != null)
  884. timeoutIn.setTimeout(timeout * 1000);
  885. }
  886. private boolean needCheckConnectivity() {
  887. return isCheckReceivedObjects()
  888. || isCheckReferencedObjectsAreReachable();
  889. }
  890. private void checkConnectivity() throws IOException {
  891. ObjectIdSubclassMap<ObjectId> baseObjects = null;
  892. ObjectIdSubclassMap<ObjectId> providedObjects = null;
  893. if (checkReferencedIsReachable) {
  894. baseObjects = parser.getBaseObjectIds();
  895. providedObjects = parser.getNewObjectIds();
  896. }
  897. parser = null;
  898. final ObjectWalk ow = new ObjectWalk(db);
  899. ow.setRetainBody(false);
  900. if (checkReferencedIsReachable) {
  901. ow.sort(RevSort.TOPO);
  902. if (!baseObjects.isEmpty())
  903. ow.sort(RevSort.BOUNDARY, true);
  904. }
  905. for (final ReceiveCommand cmd : commands) {
  906. if (cmd.getResult() != Result.NOT_ATTEMPTED)
  907. continue;
  908. if (cmd.getType() == ReceiveCommand.Type.DELETE)
  909. continue;
  910. ow.markStart(ow.parseAny(cmd.getNewId()));
  911. }
  912. for (final ObjectId have : advertisedHaves) {
  913. RevObject o = ow.parseAny(have);
  914. ow.markUninteresting(o);
  915. if (checkReferencedIsReachable && !baseObjects.isEmpty()) {
  916. o = ow.peel(o);
  917. if (o instanceof RevCommit)
  918. o = ((RevCommit) o).getTree();
  919. if (o instanceof RevTree)
  920. ow.markUninteresting(o);
  921. }
  922. }
  923. RevCommit c;
  924. while ((c = ow.next()) != null) {
  925. if (checkReferencedIsReachable //
  926. && !c.has(RevFlag.UNINTERESTING) //
  927. && !providedObjects.contains(c))
  928. throw new MissingObjectException(c, Constants.TYPE_COMMIT);
  929. }
  930. RevObject o;
  931. while ((o = ow.nextObject()) != null) {
  932. if (o.has(RevFlag.UNINTERESTING))
  933. continue;
  934. if (checkReferencedIsReachable) {
  935. if (providedObjects.contains(o))
  936. continue;
  937. else
  938. throw new MissingObjectException(o, o.getType());
  939. }
  940. if (o instanceof RevBlob && !db.hasObject(o))
  941. throw new MissingObjectException(o, Constants.TYPE_BLOB);
  942. }
  943. if (checkReferencedIsReachable) {
  944. for (ObjectId id : baseObjects) {
  945. o = ow.parseAny(id);
  946. if (!o.has(RevFlag.UNINTERESTING))
  947. throw new MissingObjectException(o, o.getType());
  948. }
  949. }
  950. }
  951. private void validateCommands() {
  952. for (final ReceiveCommand cmd : commands) {
  953. final Ref ref = cmd.getRef();
  954. if (cmd.getResult() != Result.NOT_ATTEMPTED)
  955. continue;
  956. if (cmd.getType() == ReceiveCommand.Type.DELETE
  957. && !isAllowDeletes()) {
  958. // Deletes are not supported on this repository.
  959. //
  960. cmd.setResult(Result.REJECTED_NODELETE);
  961. continue;
  962. }
  963. if (cmd.getType() == ReceiveCommand.Type.CREATE) {
  964. if (!isAllowCreates()) {
  965. cmd.setResult(Result.REJECTED_NOCREATE);
  966. continue;
  967. }
  968. if (ref != null && !isAllowNonFastForwards()) {
  969. // Creation over an existing ref is certainly not going
  970. // to be a fast-forward update. We can reject it early.
  971. //
  972. cmd.setResult(Result.REJECTED_NONFASTFORWARD);
  973. continue;
  974. }
  975. if (ref != null) {
  976. // A well behaved client shouldn't have sent us a
  977. // create command for a ref we advertised to it.
  978. //
  979. cmd.setResult(Result.REJECTED_OTHER_REASON, MessageFormat
  980. .format(JGitText.get().refAlreadyExists, ref));
  981. continue;
  982. }
  983. }
  984. if (cmd.getType() == ReceiveCommand.Type.DELETE && ref != null
  985. && !ObjectId.zeroId().equals(cmd.getOldId())
  986. && !ref.getObjectId().equals(cmd.getOldId())) {
  987. // Delete commands can be sent with the old id matching our
  988. // advertised value, *OR* with the old id being 0{40}. Any
  989. // other requested old id is invalid.
  990. //
  991. cmd.setResult(Result.REJECTED_OTHER_REASON,
  992. JGitText.get().invalidOldIdSent);
  993. continue;
  994. }
  995. if (cmd.getType() == ReceiveCommand.Type.UPDATE) {
  996. if (ref == null) {
  997. // The ref must have been advertised in order to be updated.
  998. //
  999. cmd.setResult(Result.REJECTED_OTHER_REASON, JGitText.get().noSuchRef);
  1000. continue;
  1001. }
  1002. if (!ref.getObjectId().equals(cmd.getOldId())) {
  1003. // A properly functioning client will send the same
  1004. // object id we advertised.
  1005. //
  1006. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1007. JGitText.get().invalidOldIdSent);
  1008. continue;
  1009. }
  1010. // Is this possibly a non-fast-forward style update?
  1011. //
  1012. RevObject oldObj, newObj;
  1013. try {
  1014. oldObj = walk.parseAny(cmd.getOldId());
  1015. } catch (IOException e) {
  1016. cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd
  1017. .getOldId().name());
  1018. continue;
  1019. }
  1020. try {
  1021. newObj = walk.parseAny(cmd.getNewId());
  1022. } catch (IOException e) {
  1023. cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd
  1024. .getNewId().name());
  1025. continue;
  1026. }
  1027. if (oldObj instanceof RevCommit && newObj instanceof RevCommit) {
  1028. try {
  1029. if (!walk.isMergedInto((RevCommit) oldObj,
  1030. (RevCommit) newObj)) {
  1031. cmd
  1032. .setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
  1033. }
  1034. } catch (MissingObjectException e) {
  1035. cmd.setResult(Result.REJECTED_MISSING_OBJECT, e
  1036. .getMessage());
  1037. } catch (IOException e) {
  1038. cmd.setResult(Result.REJECTED_OTHER_REASON);
  1039. }
  1040. } else {
  1041. cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
  1042. }
  1043. }
  1044. if (!cmd.getRefName().startsWith(Constants.R_REFS)
  1045. || !Repository.isValidRefName(cmd.getRefName())) {
  1046. cmd.setResult(Result.REJECTED_OTHER_REASON, JGitText.get().funnyRefname);
  1047. }
  1048. }
  1049. }
  1050. private void executeCommands() {
  1051. preReceive.onPreReceive(this,
  1052. ReceiveCommand.filter(commands, Result.NOT_ATTEMPTED));
  1053. List<ReceiveCommand> toApply = ReceiveCommand.filter(commands,
  1054. Result.NOT_ATTEMPTED);
  1055. ProgressMonitor updating = NullProgressMonitor.INSTANCE;
  1056. if (sideBand) {
  1057. SideBandProgressMonitor pm = new SideBandProgressMonitor(msgOut);
  1058. pm.setDelayStart(250, TimeUnit.MILLISECONDS);
  1059. updating = pm;
  1060. }
  1061. updating.beginTask(JGitText.get().updatingReferences, toApply.size());
  1062. for (ReceiveCommand cmd : toApply) {
  1063. updating.update(1);
  1064. cmd.execute(this);
  1065. }
  1066. updating.endTask();
  1067. }
  1068. private void sendStatusReport(final boolean forClient, final Reporter out)
  1069. throws IOException {
  1070. if (unpackError != null) {
  1071. out.sendString("unpack error " + unpackError.getMessage());
  1072. if (forClient) {
  1073. for (final ReceiveCommand cmd : commands) {
  1074. out.sendString("ng " + cmd.getRefName()
  1075. + " n/a (unpacker error)");
  1076. }
  1077. }
  1078. return;
  1079. }
  1080. if (forClient)
  1081. out.sendString("unpack ok");
  1082. for (final ReceiveCommand cmd : commands) {
  1083. if (cmd.getResult() == Result.OK) {
  1084. if (forClient)
  1085. out.sendString("ok " + cmd.getRefName());
  1086. continue;
  1087. }
  1088. final StringBuilder r = new StringBuilder();
  1089. r.append("ng ");
  1090. r.append(cmd.getRefName());
  1091. r.append(" ");
  1092. switch (cmd.getResult()) {
  1093. case NOT_ATTEMPTED:
  1094. r.append("server bug; ref not processed");
  1095. break;
  1096. case REJECTED_NOCREATE:
  1097. r.append("creation prohibited");
  1098. break;
  1099. case REJECTED_NODELETE:
  1100. r.append("deletion prohibited");
  1101. break;
  1102. case REJECTED_NONFASTFORWARD:
  1103. r.append("non-fast forward");
  1104. break;
  1105. case REJECTED_CURRENT_BRANCH:
  1106. r.append("branch is currently checked out");
  1107. break;
  1108. case REJECTED_MISSING_OBJECT:
  1109. if (cmd.getMessage() == null)
  1110. r.append("missing object(s)");
  1111. else if (cmd.getMessage().length() == Constants.OBJECT_ID_STRING_LENGTH)
  1112. r.append("object " + cmd.getMessage() + " missing");
  1113. else
  1114. r.append(cmd.getMessage());
  1115. break;
  1116. case REJECTED_OTHER_REASON:
  1117. if (cmd.getMessage() == null)
  1118. r.append("unspecified reason");
  1119. else
  1120. r.append(cmd.getMessage());
  1121. break;
  1122. case LOCK_FAILURE:
  1123. r.append("failed to lock");
  1124. break;
  1125. case OK:
  1126. // We shouldn't have reached this case (see 'ok' case above).
  1127. continue;
  1128. }
  1129. out.sendString(r.toString());
  1130. }
  1131. }
  1132. static abstract class Reporter {
  1133. abstract void sendString(String s) throws IOException;
  1134. }
  1135. }