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

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