您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

BaseReceivePack.java 55KB

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