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

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