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.

ReceivePack.java 39KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  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.BasePackPushConnection.CAPABILITY_DELETE_REFS;
  45. import static org.eclipse.jgit.transport.BasePackPushConnection.CAPABILITY_OFS_DELTA;
  46. import static org.eclipse.jgit.transport.BasePackPushConnection.CAPABILITY_REPORT_STATUS;
  47. import static org.eclipse.jgit.transport.BasePackPushConnection.CAPABILITY_SIDE_BAND_64K;
  48. import static org.eclipse.jgit.transport.SideBandOutputStream.CH_DATA;
  49. import static org.eclipse.jgit.transport.SideBandOutputStream.CH_PROGRESS;
  50. import static org.eclipse.jgit.transport.SideBandOutputStream.MAX_BUF;
  51. import java.io.EOFException;
  52. import java.io.IOException;
  53. import java.io.InputStream;
  54. import java.io.OutputStream;
  55. import java.text.MessageFormat;
  56. import java.util.ArrayList;
  57. import java.util.Collections;
  58. import java.util.HashSet;
  59. import java.util.List;
  60. import java.util.Map;
  61. import java.util.Set;
  62. import java.util.concurrent.TimeUnit;
  63. import org.eclipse.jgit.JGitText;
  64. import org.eclipse.jgit.errors.MissingObjectException;
  65. import org.eclipse.jgit.errors.PackProtocolException;
  66. import org.eclipse.jgit.errors.UnpackException;
  67. import org.eclipse.jgit.lib.Config;
  68. import org.eclipse.jgit.lib.Constants;
  69. import org.eclipse.jgit.lib.NullProgressMonitor;
  70. import org.eclipse.jgit.lib.ObjectId;
  71. import org.eclipse.jgit.lib.ObjectIdSubclassMap;
  72. import org.eclipse.jgit.lib.ObjectInserter;
  73. import org.eclipse.jgit.lib.PersonIdent;
  74. import org.eclipse.jgit.lib.ProgressMonitor;
  75. import org.eclipse.jgit.lib.Ref;
  76. import org.eclipse.jgit.lib.Repository;
  77. import org.eclipse.jgit.lib.Config.SectionParser;
  78. import org.eclipse.jgit.revwalk.ObjectWalk;
  79. import org.eclipse.jgit.revwalk.RevBlob;
  80. import org.eclipse.jgit.revwalk.RevCommit;
  81. import org.eclipse.jgit.revwalk.RevFlag;
  82. import org.eclipse.jgit.revwalk.RevObject;
  83. import org.eclipse.jgit.revwalk.RevSort;
  84. import org.eclipse.jgit.revwalk.RevTree;
  85. import org.eclipse.jgit.revwalk.RevWalk;
  86. import org.eclipse.jgit.storage.file.PackLock;
  87. import org.eclipse.jgit.transport.ReceiveCommand.Result;
  88. import org.eclipse.jgit.transport.RefAdvertiser.PacketLineOutRefAdvertiser;
  89. import org.eclipse.jgit.util.io.InterruptTimer;
  90. import org.eclipse.jgit.util.io.TimeoutInputStream;
  91. import org.eclipse.jgit.util.io.TimeoutOutputStream;
  92. /**
  93. * Implements the server side of a push connection, receiving objects.
  94. */
  95. public class ReceivePack {
  96. /** Data in the first line of a request, the line itself plus capabilities. */
  97. public static class FirstLine {
  98. private final String line;
  99. private final Set<String> capabilities;
  100. /**
  101. * Parse the first line of a receive-pack request.
  102. *
  103. * @param line
  104. * line from the client.
  105. */
  106. public FirstLine(String line) {
  107. final HashSet<String> caps = new HashSet<String>();
  108. final int nul = line.indexOf('\0');
  109. if (nul >= 0) {
  110. for (String c : line.substring(nul + 1).split(" "))
  111. caps.add(c);
  112. }
  113. this.line = line.substring(0, nul);
  114. this.capabilities = Collections.unmodifiableSet(caps);
  115. }
  116. /** @return non-capabilities part of the line. */
  117. public String getLine() {
  118. return line;
  119. }
  120. /** @return capabilities parsed from the line. */
  121. public Set<String> getCapabilities() {
  122. return capabilities;
  123. }
  124. }
  125. /** Database we write the stored objects into. */
  126. private final Repository db;
  127. /** Revision traversal support over {@link #db}. */
  128. private final RevWalk walk;
  129. /**
  130. * Is the client connection a bi-directional socket or pipe?
  131. * <p>
  132. * If true, this class assumes it can perform multiple read and write cycles
  133. * with the client over the input and output streams. This matches the
  134. * functionality available with a standard TCP/IP connection, or a local
  135. * operating system or in-memory pipe.
  136. * <p>
  137. * If false, this class runs in a read everything then output results mode,
  138. * making it suitable for single round-trip systems RPCs such as HTTP.
  139. */
  140. private boolean biDirectionalPipe = true;
  141. /** Should an incoming transfer validate objects? */
  142. private boolean checkReceivedObjects;
  143. /** Should an incoming transfer permit create requests? */
  144. private boolean allowCreates;
  145. /** Should an incoming transfer permit delete requests? */
  146. private boolean allowDeletes;
  147. /** Should an incoming transfer permit non-fast-forward requests? */
  148. private boolean allowNonFastForwards;
  149. private boolean allowOfsDelta;
  150. /** Identity to record action as within the reflog. */
  151. private PersonIdent refLogIdent;
  152. /** Hook used while advertising the refs to the client. */
  153. private AdvertiseRefsHook advertiseRefsHook;
  154. /** Filter used while advertising the refs to the client. */
  155. private RefFilter refFilter;
  156. /** Hook to validate the update commands before execution. */
  157. private PreReceiveHook preReceive;
  158. /** Hook to report on the commands after execution. */
  159. private PostReceiveHook postReceive;
  160. /** Timeout in seconds to wait for client interaction. */
  161. private int timeout;
  162. /** Timer to manage {@link #timeout}. */
  163. private InterruptTimer timer;
  164. private TimeoutInputStream timeoutIn;
  165. private InputStream rawIn;
  166. private OutputStream rawOut;
  167. private OutputStream msgOut;
  168. private final MessageOutputWrapper msgOutWrapper = new MessageOutputWrapper();
  169. private PacketLineIn pckIn;
  170. private PacketLineOut pckOut;
  171. private PackParser parser;
  172. /** The refs we advertised as existing at the start of the connection. */
  173. private Map<String, Ref> refs;
  174. /** All SHA-1s shown to the client, which can be possible edges. */
  175. private Set<ObjectId> advertisedHaves;
  176. /** Capabilities requested by the client. */
  177. private Set<String> enabledCapabilities;
  178. /** Commands to execute, as received by the client. */
  179. private List<ReceiveCommand> commands;
  180. /** Error to display instead of advertising the references. */
  181. private StringBuilder advertiseError;
  182. /** An exception caught while unpacking and fsck'ing the objects. */
  183. private Throwable unpackError;
  184. /** If {@link BasePackPushConnection#CAPABILITY_REPORT_STATUS} is enabled. */
  185. private boolean reportStatus;
  186. /** If {@link BasePackPushConnection#CAPABILITY_SIDE_BAND_64K} is enabled. */
  187. private boolean sideBand;
  188. /** Lock around the received pack file, while updating refs. */
  189. private PackLock packLock;
  190. private boolean checkReferencedIsReachable;
  191. /** Git object size limit */
  192. private long maxObjectSizeLimit;
  193. /**
  194. * Create a new pack receive for an open repository.
  195. *
  196. * @param into
  197. * the destination repository.
  198. */
  199. public ReceivePack(final Repository into) {
  200. db = into;
  201. walk = new RevWalk(db);
  202. final ReceiveConfig cfg = db.getConfig().get(ReceiveConfig.KEY);
  203. checkReceivedObjects = cfg.checkReceivedObjects;
  204. allowCreates = cfg.allowCreates;
  205. allowDeletes = cfg.allowDeletes;
  206. allowNonFastForwards = cfg.allowNonFastForwards;
  207. allowOfsDelta = cfg.allowOfsDelta;
  208. advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  209. refFilter = RefFilter.DEFAULT;
  210. preReceive = PreReceiveHook.NULL;
  211. postReceive = PostReceiveHook.NULL;
  212. advertisedHaves = new HashSet<ObjectId>();
  213. }
  214. private static class ReceiveConfig {
  215. static final SectionParser<ReceiveConfig> KEY = new SectionParser<ReceiveConfig>() {
  216. public ReceiveConfig parse(final Config cfg) {
  217. return new ReceiveConfig(cfg);
  218. }
  219. };
  220. final boolean checkReceivedObjects;
  221. final boolean allowCreates;
  222. final boolean allowDeletes;
  223. final boolean allowNonFastForwards;
  224. final boolean allowOfsDelta;
  225. ReceiveConfig(final Config config) {
  226. checkReceivedObjects = config.getBoolean("receive", "fsckobjects",
  227. false);
  228. allowCreates = true;
  229. allowDeletes = !config.getBoolean("receive", "denydeletes", false);
  230. allowNonFastForwards = !config.getBoolean("receive",
  231. "denynonfastforwards", false);
  232. allowOfsDelta = config.getBoolean("repack", "usedeltabaseoffset",
  233. true);
  234. }
  235. }
  236. /**
  237. * Output stream that wraps the current {@link #msgOut}.
  238. * <p>
  239. * We don't want to expose {@link #msgOut} directly because it can change
  240. * several times over the course of a session.
  241. */
  242. private class MessageOutputWrapper extends OutputStream {
  243. @Override
  244. public void write(int ch) {
  245. if (msgOut != null) {
  246. try {
  247. msgOut.write(ch);
  248. } catch (IOException e) {
  249. // Ignore write failures.
  250. }
  251. }
  252. }
  253. @Override
  254. public void write(byte[] b, int off, int len) {
  255. if (msgOut != null) {
  256. try {
  257. msgOut.write(b, off, len);
  258. } catch (IOException e) {
  259. // Ignore write failures.
  260. }
  261. }
  262. }
  263. @Override
  264. public void write(byte[] b) {
  265. write(b, 0, b.length);
  266. }
  267. @Override
  268. public void flush() {
  269. if (msgOut != null) {
  270. try {
  271. msgOut.flush();
  272. } catch (IOException e) {
  273. // Ignore write failures.
  274. }
  275. }
  276. }
  277. }
  278. /** @return the repository this receive completes into. */
  279. public final Repository getRepository() {
  280. return db;
  281. }
  282. /** @return the RevWalk instance used by this connection. */
  283. public final RevWalk getRevWalk() {
  284. return walk;
  285. }
  286. /**
  287. * Get refs which were advertised to the client.
  288. *
  289. * @return all refs which were advertised to the client, or null if
  290. * {@link #setAdvertisedRefs(Map, Set)} has not been called yet.
  291. */
  292. public final Map<String, Ref> getAdvertisedRefs() {
  293. return refs;
  294. }
  295. /**
  296. * Set the refs advertised by this ReceivePack.
  297. * <p>
  298. * Intended to be called from a {@link PreReceiveHook}.
  299. *
  300. * @param allRefs
  301. * explicit set of references to claim as advertised by this
  302. * ReceivePack instance. This overrides any references that
  303. * may exist in the source repository. The map is passed
  304. * to the configured {@link #getRefFilter()}. If null, assumes
  305. * all refs were advertised.
  306. * @param additionalHaves
  307. * explicit set of additional haves to claim as advertised. If
  308. * null, assumes the default set of additional haves from the
  309. * repository.
  310. */
  311. public void setAdvertisedRefs(Map<String, Ref> allRefs,
  312. Set<ObjectId> additionalHaves) {
  313. refs = allRefs != null ? allRefs : db.getAllRefs();
  314. refs = refFilter.filter(refs);
  315. Ref head = refs.get(Constants.HEAD);
  316. if (head != null && head.isSymbolic())
  317. refs.remove(Constants.HEAD);
  318. for (Ref ref : refs.values()) {
  319. if (ref.getObjectId() != null)
  320. advertisedHaves.add(ref.getObjectId());
  321. }
  322. if (additionalHaves != null)
  323. advertisedHaves.addAll(additionalHaves);
  324. else
  325. advertisedHaves.addAll(db.getAdditionalHaves());
  326. }
  327. /**
  328. * Get objects advertised to the client.
  329. *
  330. * @return the set of objects advertised to the as present in this repository,
  331. * or null if {@link #setAdvertisedRefs(Map, Set)} has not been called
  332. * yet.
  333. */
  334. public final Set<ObjectId> getAdvertisedObjects() {
  335. return advertisedHaves;
  336. }
  337. /**
  338. * @return true if this instance will validate all referenced, but not
  339. * supplied by the client, objects are reachable from another
  340. * reference.
  341. */
  342. public boolean isCheckReferencedObjectsAreReachable() {
  343. return checkReferencedIsReachable;
  344. }
  345. /**
  346. * Validate all referenced but not supplied objects are reachable.
  347. * <p>
  348. * If enabled, this instance will verify that references to objects not
  349. * contained within the received pack are already reachable through at least
  350. * one other reference displayed as part of {@link #getAdvertisedRefs()}.
  351. * <p>
  352. * This feature is useful when the application doesn't trust the client to
  353. * not provide a forged SHA-1 reference to an object, in an attempt to
  354. * access parts of the DAG that they aren't allowed to see and which have
  355. * been hidden from them via the configured {@link AdvertiseRefsHook} or
  356. * {@link RefFilter}.
  357. * <p>
  358. * Enabling this feature may imply at least some, if not all, of the same
  359. * functionality performed by {@link #setCheckReceivedObjects(boolean)}.
  360. * Applications are encouraged to enable both features, if desired.
  361. *
  362. * @param b
  363. * {@code true} to enable the additional check.
  364. */
  365. public void setCheckReferencedObjectsAreReachable(boolean b) {
  366. this.checkReferencedIsReachable = b;
  367. }
  368. /**
  369. * @return true if this class expects a bi-directional pipe opened between
  370. * the client and itself. The default is true.
  371. */
  372. public boolean isBiDirectionalPipe() {
  373. return biDirectionalPipe;
  374. }
  375. /**
  376. * @param twoWay
  377. * if true, this class will assume the socket is a fully
  378. * bidirectional pipe between the two peers and takes advantage
  379. * of that by first transmitting the known refs, then waiting to
  380. * read commands. If false, this class assumes it must read the
  381. * commands before writing output and does not perform the
  382. * initial advertising.
  383. */
  384. public void setBiDirectionalPipe(final boolean twoWay) {
  385. biDirectionalPipe = twoWay;
  386. }
  387. /**
  388. * @return true if this instance will verify received objects are formatted
  389. * correctly. Validating objects requires more CPU time on this side
  390. * of the connection.
  391. */
  392. public boolean isCheckReceivedObjects() {
  393. return checkReceivedObjects;
  394. }
  395. /**
  396. * @param check
  397. * true to enable checking received objects; false to assume all
  398. * received objects are valid.
  399. */
  400. public void setCheckReceivedObjects(final boolean check) {
  401. checkReceivedObjects = check;
  402. }
  403. /** @return true if the client can request refs to be created. */
  404. public boolean isAllowCreates() {
  405. return allowCreates;
  406. }
  407. /**
  408. * @param canCreate
  409. * true to permit create ref commands to be processed.
  410. */
  411. public void setAllowCreates(final boolean canCreate) {
  412. allowCreates = canCreate;
  413. }
  414. /** @return true if the client can request refs to be deleted. */
  415. public boolean isAllowDeletes() {
  416. return allowDeletes;
  417. }
  418. /**
  419. * @param canDelete
  420. * true to permit delete ref commands to be processed.
  421. */
  422. public void setAllowDeletes(final boolean canDelete) {
  423. allowDeletes = canDelete;
  424. }
  425. /**
  426. * @return true if the client can request non-fast-forward updates of a ref,
  427. * possibly making objects unreachable.
  428. */
  429. public boolean isAllowNonFastForwards() {
  430. return allowNonFastForwards;
  431. }
  432. /**
  433. * @param canRewind
  434. * true to permit the client to ask for non-fast-forward updates
  435. * of an existing ref.
  436. */
  437. public void setAllowNonFastForwards(final boolean canRewind) {
  438. allowNonFastForwards = canRewind;
  439. }
  440. /** @return identity of the user making the changes in the reflog. */
  441. public PersonIdent getRefLogIdent() {
  442. return refLogIdent;
  443. }
  444. /**
  445. * Set the identity of the user appearing in the affected reflogs.
  446. * <p>
  447. * The timestamp portion of the identity is ignored. A new identity with the
  448. * current timestamp will be created automatically when the updates occur
  449. * and the log records are written.
  450. *
  451. * @param pi
  452. * identity of the user. If null the identity will be
  453. * automatically determined based on the repository
  454. * configuration.
  455. */
  456. public void setRefLogIdent(final PersonIdent pi) {
  457. refLogIdent = pi;
  458. }
  459. /** @return the hook used while advertising the refs to the client */
  460. public AdvertiseRefsHook getAdvertiseRefsHook() {
  461. return advertiseRefsHook;
  462. }
  463. /** @return the filter used while advertising the refs to the client */
  464. public RefFilter getRefFilter() {
  465. return refFilter;
  466. }
  467. /**
  468. * Set the hook used while advertising the refs to the client.
  469. * <p>
  470. * If the {@link AdvertiseRefsHook} chooses to call
  471. * {@link #setAdvertisedRefs(Map,Set)}, only refs set by this hook
  472. * <em>and</em> selected by the {@link RefFilter} will be shown to the client.
  473. * Clients may still attempt to create or update a reference not advertised by
  474. * the configured {@link AdvertiseRefsHook}. These attempts should be rejected
  475. * by a matching {@link PreReceiveHook}.
  476. *
  477. * @param advertiseRefsHook
  478. * the hook; may be null to show all refs.
  479. */
  480. public void setAdvertiseRefsHook(final AdvertiseRefsHook advertiseRefsHook) {
  481. if (advertiseRefsHook != null)
  482. this.advertiseRefsHook = advertiseRefsHook;
  483. else
  484. this.advertiseRefsHook = AdvertiseRefsHook.DEFAULT;
  485. }
  486. /**
  487. * Set the filter used while advertising the refs to the client.
  488. * <p>
  489. * Only refs allowed by this filter will be shown to the client.
  490. * The filter is run against the refs specified by the
  491. * {@link AdvertiseRefsHook} (if applicable).
  492. *
  493. * @param refFilter
  494. * the filter; may be null to show all refs.
  495. */
  496. public void setRefFilter(final RefFilter refFilter) {
  497. this.refFilter = refFilter != null ? refFilter : RefFilter.DEFAULT;
  498. }
  499. /** @return the hook invoked before updates occur. */
  500. public PreReceiveHook getPreReceiveHook() {
  501. return preReceive;
  502. }
  503. /**
  504. * Set the hook which is invoked prior to commands being executed.
  505. * <p>
  506. * Only valid commands (those which have no obvious errors according to the
  507. * received input and this instance's configuration) are passed into the
  508. * hook. The hook may mark a command with a result of any value other than
  509. * {@link Result#NOT_ATTEMPTED} to block its execution.
  510. * <p>
  511. * The hook may be called with an empty command collection if the current
  512. * set is completely invalid.
  513. *
  514. * @param h
  515. * the hook instance; may be null to disable the hook.
  516. */
  517. public void setPreReceiveHook(final PreReceiveHook h) {
  518. preReceive = h != null ? h : PreReceiveHook.NULL;
  519. }
  520. /** @return the hook invoked after updates occur. */
  521. public PostReceiveHook getPostReceiveHook() {
  522. return postReceive;
  523. }
  524. /**
  525. * Set the hook which is invoked after commands are executed.
  526. * <p>
  527. * Only successful commands (type is {@link Result#OK}) are passed into the
  528. * hook. The hook may be called with an empty command collection if the
  529. * current set all resulted in an error.
  530. *
  531. * @param h
  532. * the hook instance; may be null to disable the hook.
  533. */
  534. public void setPostReceiveHook(final PostReceiveHook h) {
  535. postReceive = h != null ? h : PostReceiveHook.NULL;
  536. }
  537. /** @return timeout (in seconds) before aborting an IO operation. */
  538. public int getTimeout() {
  539. return timeout;
  540. }
  541. /**
  542. * Set the timeout before willing to abort an IO call.
  543. *
  544. * @param seconds
  545. * number of seconds to wait (with no data transfer occurring)
  546. * before aborting an IO read or write operation with the
  547. * connected client.
  548. */
  549. public void setTimeout(final int seconds) {
  550. timeout = seconds;
  551. }
  552. /**
  553. * Set the maximum allowed Git object size.
  554. * <p>
  555. * If an object is larger than the given size the pack-parsing will throw an
  556. * exception aborting the receive-pack operation.
  557. *
  558. * @param limit
  559. * the Git object size limit. If zero then there is not limit.
  560. */
  561. public void setMaxObjectSizeLimit(final long limit) {
  562. maxObjectSizeLimit = limit;
  563. }
  564. /**
  565. * Check whether the client expects a side-band stream.
  566. *
  567. * @return true if the client has advertised a side-band capability, false
  568. * otherwise.
  569. * @throws RequestNotYetReadException
  570. * if the client's request has not yet been read from the wire, so
  571. * we do not know if they expect side-band. Note that the client
  572. * may have already written the request, it just has not been
  573. * read.
  574. */
  575. public boolean isSideBand() throws RequestNotYetReadException {
  576. if (enabledCapabilities == null)
  577. throw new RequestNotYetReadException();
  578. return enabledCapabilities.contains(CAPABILITY_SIDE_BAND_64K);
  579. }
  580. /** @return all of the command received by the current request. */
  581. public List<ReceiveCommand> getAllCommands() {
  582. return Collections.unmodifiableList(commands);
  583. }
  584. /**
  585. * Send an error message to the client.
  586. * <p>
  587. * If any error messages are sent before the references are advertised to
  588. * the client, the errors will be sent instead of the advertisement and the
  589. * receive operation will be aborted. All clients should receive and display
  590. * such early stage errors.
  591. * <p>
  592. * If the reference advertisements have already been sent, messages are sent
  593. * in a side channel. If the client doesn't support receiving messages, the
  594. * message will be discarded, with no other indication to the caller or to
  595. * the client.
  596. * <p>
  597. * {@link PreReceiveHook}s should always try to use
  598. * {@link ReceiveCommand#setResult(Result, String)} with a result status of
  599. * {@link Result#REJECTED_OTHER_REASON} to indicate any reasons for
  600. * rejecting an update. Messages attached to a command are much more likely
  601. * to be returned to the client.
  602. *
  603. * @param what
  604. * string describing the problem identified by the hook. The
  605. * string must not end with an LF, and must not contain an LF.
  606. */
  607. public void sendError(final String what) {
  608. if (refs == null) {
  609. if (advertiseError == null)
  610. advertiseError = new StringBuilder();
  611. advertiseError.append(what).append('\n');
  612. } else {
  613. msgOutWrapper.write(Constants.encode("error: " + what + "\n"));
  614. }
  615. }
  616. /**
  617. * Send a message to the client, if it supports receiving them.
  618. * <p>
  619. * If the client doesn't support receiving messages, the message will be
  620. * discarded, with no other indication to the caller or to the client.
  621. *
  622. * @param what
  623. * string describing the problem identified by the hook. The
  624. * string must not end with an LF, and must not contain an LF.
  625. */
  626. public void sendMessage(final String what) {
  627. msgOutWrapper.write(Constants.encode(what + "\n"));
  628. }
  629. /** @return an underlying stream for sending messages to the client. */
  630. public OutputStream getMessageOutputStream() {
  631. return msgOutWrapper;
  632. }
  633. /**
  634. * Execute the receive task on the socket.
  635. *
  636. * @param input
  637. * raw input to read client commands and pack data from. Caller
  638. * must ensure the input is buffered, otherwise read performance
  639. * may suffer.
  640. * @param output
  641. * response back to the Git network client. Caller must ensure
  642. * the output is buffered, otherwise write performance may
  643. * suffer.
  644. * @param messages
  645. * secondary "notice" channel to send additional messages out
  646. * through. When run over SSH this should be tied back to the
  647. * standard error channel of the command execution. For most
  648. * other network connections this should be null.
  649. * @throws IOException
  650. */
  651. public void receive(final InputStream input, final OutputStream output,
  652. final OutputStream messages) throws IOException {
  653. try {
  654. rawIn = input;
  655. rawOut = output;
  656. msgOut = messages;
  657. if (timeout > 0) {
  658. final Thread caller = Thread.currentThread();
  659. timer = new InterruptTimer(caller.getName() + "-Timer");
  660. timeoutIn = new TimeoutInputStream(rawIn, timer);
  661. TimeoutOutputStream o = new TimeoutOutputStream(rawOut, timer);
  662. timeoutIn.setTimeout(timeout * 1000);
  663. o.setTimeout(timeout * 1000);
  664. rawIn = timeoutIn;
  665. rawOut = o;
  666. }
  667. pckIn = new PacketLineIn(rawIn);
  668. pckOut = new PacketLineOut(rawOut);
  669. pckOut.setFlushOnEnd(false);
  670. commands = new ArrayList<ReceiveCommand>();
  671. service();
  672. } finally {
  673. walk.release();
  674. try {
  675. if (sideBand) {
  676. // If we are using side band, we need to send a final
  677. // flush-pkt to tell the remote peer the side band is
  678. // complete and it should stop decoding. We need to
  679. // use the original output stream as rawOut is now the
  680. // side band data channel.
  681. //
  682. ((SideBandOutputStream) msgOut).flushBuffer();
  683. ((SideBandOutputStream) rawOut).flushBuffer();
  684. PacketLineOut plo = new PacketLineOut(output);
  685. plo.setFlushOnEnd(false);
  686. plo.end();
  687. }
  688. if (biDirectionalPipe) {
  689. // If this was a native git connection, flush the pipe for
  690. // the caller. For smart HTTP we don't do this flush and
  691. // instead let the higher level HTTP servlet code do it.
  692. //
  693. if (!sideBand && msgOut != null)
  694. msgOut.flush();
  695. rawOut.flush();
  696. }
  697. } finally {
  698. unlockPack();
  699. timeoutIn = null;
  700. rawIn = null;
  701. rawOut = null;
  702. msgOut = null;
  703. pckIn = null;
  704. pckOut = null;
  705. refs = null;
  706. enabledCapabilities = null;
  707. commands = null;
  708. if (timer != null) {
  709. try {
  710. timer.terminate();
  711. } finally {
  712. timer = null;
  713. }
  714. }
  715. }
  716. }
  717. }
  718. private Map<String, Ref> getAdvertisedOrDefaultRefs() {
  719. if (refs == null)
  720. setAdvertisedRefs(null, null);
  721. return refs;
  722. }
  723. private void service() throws IOException {
  724. if (biDirectionalPipe) {
  725. sendAdvertisedRefs(new PacketLineOutRefAdvertiser(pckOut));
  726. pckOut.flush();
  727. } else
  728. getAdvertisedOrDefaultRefs();
  729. if (advertiseError != null)
  730. return;
  731. recvCommands();
  732. if (!commands.isEmpty()) {
  733. enableCapabilities();
  734. if (needPack()) {
  735. try {
  736. receivePack();
  737. if (needCheckConnectivity())
  738. checkConnectivity();
  739. parser = null;
  740. unpackError = null;
  741. } catch (IOException err) {
  742. unpackError = err;
  743. } catch (RuntimeException err) {
  744. unpackError = err;
  745. } catch (Error err) {
  746. unpackError = err;
  747. }
  748. }
  749. if (unpackError == null) {
  750. validateCommands();
  751. executeCommands();
  752. }
  753. unlockPack();
  754. if (reportStatus) {
  755. sendStatusReport(true, new Reporter() {
  756. void sendString(final String s) throws IOException {
  757. pckOut.writeString(s + "\n");
  758. }
  759. });
  760. pckOut.end();
  761. } else if (msgOut != null) {
  762. sendStatusReport(false, new Reporter() {
  763. void sendString(final String s) throws IOException {
  764. msgOut.write(Constants.encode(s + "\n"));
  765. }
  766. });
  767. }
  768. postReceive.onPostReceive(this,
  769. ReceiveCommand.filter(commands, Result.OK));
  770. if (unpackError != null)
  771. throw new UnpackException(unpackError);
  772. }
  773. }
  774. private void unlockPack() throws IOException {
  775. if (packLock != null) {
  776. packLock.unlock();
  777. packLock = null;
  778. }
  779. }
  780. /**
  781. * Generate an advertisement of available refs and capabilities.
  782. *
  783. * @param adv
  784. * the advertisement formatter.
  785. * @throws IOException
  786. * the formatter failed to write an advertisement.
  787. * @throws ServiceMayNotContinueException
  788. * the hook denied advertisement.
  789. */
  790. public void sendAdvertisedRefs(final RefAdvertiser adv) throws IOException,
  791. ServiceMayNotContinueException {
  792. if (advertiseError != null) {
  793. adv.writeOne("ERR " + advertiseError);
  794. return;
  795. }
  796. try {
  797. advertiseRefsHook.advertiseRefs(this);
  798. } catch (ServiceMayNotContinueException fail) {
  799. if (fail.getMessage() != null) {
  800. adv.writeOne("ERR " + fail.getMessage());
  801. fail.setOutput();
  802. }
  803. throw fail;
  804. }
  805. adv.init(db);
  806. adv.advertiseCapability(CAPABILITY_SIDE_BAND_64K);
  807. adv.advertiseCapability(CAPABILITY_DELETE_REFS);
  808. adv.advertiseCapability(CAPABILITY_REPORT_STATUS);
  809. if (allowOfsDelta)
  810. adv.advertiseCapability(CAPABILITY_OFS_DELTA);
  811. adv.send(getAdvertisedOrDefaultRefs());
  812. for (ObjectId obj : advertisedHaves)
  813. adv.advertiseHave(obj);
  814. if (adv.isEmpty())
  815. adv.advertiseId(ObjectId.zeroId(), "capabilities^{}");
  816. adv.end();
  817. }
  818. private void recvCommands() throws IOException {
  819. for (;;) {
  820. String line;
  821. try {
  822. line = pckIn.readStringRaw();
  823. } catch (EOFException eof) {
  824. if (commands.isEmpty())
  825. return;
  826. throw eof;
  827. }
  828. if (line == PacketLineIn.END)
  829. break;
  830. if (commands.isEmpty()) {
  831. final FirstLine firstLine = new FirstLine(line);
  832. enabledCapabilities = firstLine.getCapabilities();
  833. line = firstLine.getLine();
  834. }
  835. if (line.length() < 83) {
  836. final String m = JGitText.get().errorInvalidProtocolWantedOldNewRef;
  837. sendError(m);
  838. throw new PackProtocolException(m);
  839. }
  840. final ObjectId oldId = ObjectId.fromString(line.substring(0, 40));
  841. final ObjectId newId = ObjectId.fromString(line.substring(41, 81));
  842. final String name = line.substring(82);
  843. final ReceiveCommand cmd = new ReceiveCommand(oldId, newId, name);
  844. if (name.equals(Constants.HEAD)) {
  845. cmd.setResult(Result.REJECTED_CURRENT_BRANCH);
  846. } else {
  847. cmd.setRef(refs.get(cmd.getRefName()));
  848. }
  849. commands.add(cmd);
  850. }
  851. }
  852. private void enableCapabilities() {
  853. reportStatus = enabledCapabilities.contains(CAPABILITY_REPORT_STATUS);
  854. sideBand = enabledCapabilities.contains(CAPABILITY_SIDE_BAND_64K);
  855. if (sideBand) {
  856. OutputStream out = rawOut;
  857. rawOut = new SideBandOutputStream(CH_DATA, MAX_BUF, out);
  858. msgOut = new SideBandOutputStream(CH_PROGRESS, MAX_BUF, out);
  859. pckOut = new PacketLineOut(rawOut);
  860. pckOut.setFlushOnEnd(false);
  861. }
  862. }
  863. private boolean needPack() {
  864. for (final ReceiveCommand cmd : commands) {
  865. if (cmd.getType() != ReceiveCommand.Type.DELETE)
  866. return true;
  867. }
  868. return false;
  869. }
  870. private void receivePack() throws IOException {
  871. // It might take the client a while to pack the objects it needs
  872. // to send to us. We should increase our timeout so we don't
  873. // abort while the client is computing.
  874. //
  875. if (timeoutIn != null)
  876. timeoutIn.setTimeout(10 * timeout * 1000);
  877. ProgressMonitor receiving = NullProgressMonitor.INSTANCE;
  878. ProgressMonitor resolving = NullProgressMonitor.INSTANCE;
  879. if (sideBand)
  880. resolving = new SideBandProgressMonitor(msgOut);
  881. ObjectInserter ins = db.newObjectInserter();
  882. try {
  883. String lockMsg = "jgit receive-pack";
  884. if (getRefLogIdent() != null)
  885. lockMsg += " from " + getRefLogIdent().toExternalString();
  886. parser = ins.newPackParser(rawIn);
  887. parser.setAllowThin(true);
  888. parser.setNeedNewObjectIds(checkReferencedIsReachable);
  889. parser.setNeedBaseObjectIds(checkReferencedIsReachable);
  890. parser.setCheckEofAfterPackFooter(!biDirectionalPipe);
  891. parser.setObjectChecking(isCheckReceivedObjects());
  892. parser.setLockMessage(lockMsg);
  893. parser.setMaxObjectSizeLimit(maxObjectSizeLimit);
  894. packLock = parser.parse(receiving, resolving);
  895. ins.flush();
  896. } finally {
  897. ins.release();
  898. }
  899. if (timeoutIn != null)
  900. timeoutIn.setTimeout(timeout * 1000);
  901. }
  902. private boolean needCheckConnectivity() {
  903. return isCheckReceivedObjects()
  904. || isCheckReferencedObjectsAreReachable();
  905. }
  906. private void checkConnectivity() throws IOException {
  907. ObjectIdSubclassMap<ObjectId> baseObjects = null;
  908. ObjectIdSubclassMap<ObjectId> providedObjects = null;
  909. if (checkReferencedIsReachable) {
  910. baseObjects = parser.getBaseObjectIds();
  911. providedObjects = parser.getNewObjectIds();
  912. }
  913. parser = null;
  914. final ObjectWalk ow = new ObjectWalk(db);
  915. ow.setRetainBody(false);
  916. if (checkReferencedIsReachable) {
  917. ow.sort(RevSort.TOPO);
  918. if (!baseObjects.isEmpty())
  919. ow.sort(RevSort.BOUNDARY, true);
  920. }
  921. for (final ReceiveCommand cmd : commands) {
  922. if (cmd.getResult() != Result.NOT_ATTEMPTED)
  923. continue;
  924. if (cmd.getType() == ReceiveCommand.Type.DELETE)
  925. continue;
  926. ow.markStart(ow.parseAny(cmd.getNewId()));
  927. }
  928. for (final ObjectId have : advertisedHaves) {
  929. RevObject o = ow.parseAny(have);
  930. ow.markUninteresting(o);
  931. if (checkReferencedIsReachable && !baseObjects.isEmpty()) {
  932. o = ow.peel(o);
  933. if (o instanceof RevCommit)
  934. o = ((RevCommit) o).getTree();
  935. if (o instanceof RevTree)
  936. ow.markUninteresting(o);
  937. }
  938. }
  939. RevCommit c;
  940. while ((c = ow.next()) != null) {
  941. if (checkReferencedIsReachable //
  942. && !c.has(RevFlag.UNINTERESTING) //
  943. && !providedObjects.contains(c))
  944. throw new MissingObjectException(c, Constants.TYPE_COMMIT);
  945. }
  946. RevObject o;
  947. while ((o = ow.nextObject()) != null) {
  948. if (o.has(RevFlag.UNINTERESTING))
  949. continue;
  950. if (checkReferencedIsReachable) {
  951. if (providedObjects.contains(o))
  952. continue;
  953. else
  954. throw new MissingObjectException(o, o.getType());
  955. }
  956. if (o instanceof RevBlob && !db.hasObject(o))
  957. throw new MissingObjectException(o, Constants.TYPE_BLOB);
  958. }
  959. if (checkReferencedIsReachable) {
  960. for (ObjectId id : baseObjects) {
  961. o = ow.parseAny(id);
  962. if (!o.has(RevFlag.UNINTERESTING))
  963. throw new MissingObjectException(o, o.getType());
  964. }
  965. }
  966. }
  967. private void validateCommands() {
  968. for (final ReceiveCommand cmd : commands) {
  969. final Ref ref = cmd.getRef();
  970. if (cmd.getResult() != Result.NOT_ATTEMPTED)
  971. continue;
  972. if (cmd.getType() == ReceiveCommand.Type.DELETE
  973. && !isAllowDeletes()) {
  974. // Deletes are not supported on this repository.
  975. //
  976. cmd.setResult(Result.REJECTED_NODELETE);
  977. continue;
  978. }
  979. if (cmd.getType() == ReceiveCommand.Type.CREATE) {
  980. if (!isAllowCreates()) {
  981. cmd.setResult(Result.REJECTED_NOCREATE);
  982. continue;
  983. }
  984. if (ref != null && !isAllowNonFastForwards()) {
  985. // Creation over an existing ref is certainly not going
  986. // to be a fast-forward update. We can reject it early.
  987. //
  988. cmd.setResult(Result.REJECTED_NONFASTFORWARD);
  989. continue;
  990. }
  991. if (ref != null) {
  992. // A well behaved client shouldn't have sent us a
  993. // create command for a ref we advertised to it.
  994. //
  995. cmd.setResult(Result.REJECTED_OTHER_REASON, MessageFormat
  996. .format(JGitText.get().refAlreadyExists, ref));
  997. continue;
  998. }
  999. }
  1000. if (cmd.getType() == ReceiveCommand.Type.DELETE && ref != null
  1001. && !ObjectId.zeroId().equals(cmd.getOldId())
  1002. && !ref.getObjectId().equals(cmd.getOldId())) {
  1003. // Delete commands can be sent with the old id matching our
  1004. // advertised value, *OR* with the old id being 0{40}. Any
  1005. // other requested old id is invalid.
  1006. //
  1007. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1008. JGitText.get().invalidOldIdSent);
  1009. continue;
  1010. }
  1011. if (cmd.getType() == ReceiveCommand.Type.UPDATE) {
  1012. if (ref == null) {
  1013. // The ref must have been advertised in order to be updated.
  1014. //
  1015. cmd.setResult(Result.REJECTED_OTHER_REASON, JGitText.get().noSuchRef);
  1016. continue;
  1017. }
  1018. if (!ref.getObjectId().equals(cmd.getOldId())) {
  1019. // A properly functioning client will send the same
  1020. // object id we advertised.
  1021. //
  1022. cmd.setResult(Result.REJECTED_OTHER_REASON,
  1023. JGitText.get().invalidOldIdSent);
  1024. continue;
  1025. }
  1026. // Is this possibly a non-fast-forward style update?
  1027. //
  1028. RevObject oldObj, newObj;
  1029. try {
  1030. oldObj = walk.parseAny(cmd.getOldId());
  1031. } catch (IOException e) {
  1032. cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd
  1033. .getOldId().name());
  1034. continue;
  1035. }
  1036. try {
  1037. newObj = walk.parseAny(cmd.getNewId());
  1038. } catch (IOException e) {
  1039. cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd
  1040. .getNewId().name());
  1041. continue;
  1042. }
  1043. if (oldObj instanceof RevCommit && newObj instanceof RevCommit) {
  1044. try {
  1045. if (!walk.isMergedInto((RevCommit) oldObj,
  1046. (RevCommit) newObj)) {
  1047. cmd
  1048. .setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
  1049. }
  1050. } catch (MissingObjectException e) {
  1051. cmd.setResult(Result.REJECTED_MISSING_OBJECT, e
  1052. .getMessage());
  1053. } catch (IOException e) {
  1054. cmd.setResult(Result.REJECTED_OTHER_REASON);
  1055. }
  1056. } else {
  1057. cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
  1058. }
  1059. }
  1060. if (!cmd.getRefName().startsWith(Constants.R_REFS)
  1061. || !Repository.isValidRefName(cmd.getRefName())) {
  1062. cmd.setResult(Result.REJECTED_OTHER_REASON, JGitText.get().funnyRefname);
  1063. }
  1064. }
  1065. }
  1066. private void executeCommands() {
  1067. preReceive.onPreReceive(this,
  1068. ReceiveCommand.filter(commands, Result.NOT_ATTEMPTED));
  1069. List<ReceiveCommand> toApply = ReceiveCommand.filter(commands,
  1070. Result.NOT_ATTEMPTED);
  1071. ProgressMonitor updating = NullProgressMonitor.INSTANCE;
  1072. if (sideBand) {
  1073. SideBandProgressMonitor pm = new SideBandProgressMonitor(msgOut);
  1074. pm.setDelayStart(250, TimeUnit.MILLISECONDS);
  1075. updating = pm;
  1076. }
  1077. updating.beginTask(JGitText.get().updatingReferences, toApply.size());
  1078. for (ReceiveCommand cmd : toApply) {
  1079. updating.update(1);
  1080. cmd.execute(this);
  1081. }
  1082. updating.endTask();
  1083. }
  1084. private void sendStatusReport(final boolean forClient, final Reporter out)
  1085. throws IOException {
  1086. if (unpackError != null) {
  1087. out.sendString("unpack error " + unpackError.getMessage());
  1088. if (forClient) {
  1089. for (final ReceiveCommand cmd : commands) {
  1090. out.sendString("ng " + cmd.getRefName()
  1091. + " n/a (unpacker error)");
  1092. }
  1093. }
  1094. return;
  1095. }
  1096. if (forClient)
  1097. out.sendString("unpack ok");
  1098. for (final ReceiveCommand cmd : commands) {
  1099. if (cmd.getResult() == Result.OK) {
  1100. if (forClient)
  1101. out.sendString("ok " + cmd.getRefName());
  1102. continue;
  1103. }
  1104. final StringBuilder r = new StringBuilder();
  1105. r.append("ng ");
  1106. r.append(cmd.getRefName());
  1107. r.append(" ");
  1108. switch (cmd.getResult()) {
  1109. case NOT_ATTEMPTED:
  1110. r.append("server bug; ref not processed");
  1111. break;
  1112. case REJECTED_NOCREATE:
  1113. r.append("creation prohibited");
  1114. break;
  1115. case REJECTED_NODELETE:
  1116. r.append("deletion prohibited");
  1117. break;
  1118. case REJECTED_NONFASTFORWARD:
  1119. r.append("non-fast forward");
  1120. break;
  1121. case REJECTED_CURRENT_BRANCH:
  1122. r.append("branch is currently checked out");
  1123. break;
  1124. case REJECTED_MISSING_OBJECT:
  1125. if (cmd.getMessage() == null)
  1126. r.append("missing object(s)");
  1127. else if (cmd.getMessage().length() == Constants.OBJECT_ID_STRING_LENGTH)
  1128. r.append("object " + cmd.getMessage() + " missing");
  1129. else
  1130. r.append(cmd.getMessage());
  1131. break;
  1132. case REJECTED_OTHER_REASON:
  1133. if (cmd.getMessage() == null)
  1134. r.append("unspecified reason");
  1135. else
  1136. r.append(cmd.getMessage());
  1137. break;
  1138. case LOCK_FAILURE:
  1139. r.append("failed to lock");
  1140. break;
  1141. case OK:
  1142. // We shouldn't have reached this case (see 'ok' case above).
  1143. continue;
  1144. }
  1145. out.sendString(r.toString());
  1146. }
  1147. }
  1148. static abstract class Reporter {
  1149. abstract void sendString(String s) throws IOException;
  1150. }
  1151. }