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

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