Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

BaseReceivePack.java 45KB

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