Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

BaseReceivePack.java 45KB

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