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

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