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

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