You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BaseReceivePack.java 50KB

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