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

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