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

BaseReceivePack.java 40KB

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