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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  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 java.io.BufferedWriter;
  45. import java.io.EOFException;
  46. import java.io.IOException;
  47. import java.io.InputStream;
  48. import java.io.OutputStream;
  49. import java.io.OutputStreamWriter;
  50. import java.io.PrintWriter;
  51. import java.util.ArrayList;
  52. import java.util.Collections;
  53. import java.util.HashSet;
  54. import java.util.List;
  55. import java.util.Map;
  56. import java.util.Set;
  57. import org.eclipse.jgit.errors.MissingObjectException;
  58. import org.eclipse.jgit.errors.PackProtocolException;
  59. import org.eclipse.jgit.lib.Config;
  60. import org.eclipse.jgit.lib.Constants;
  61. import org.eclipse.jgit.lib.NullProgressMonitor;
  62. import org.eclipse.jgit.lib.ObjectId;
  63. import org.eclipse.jgit.lib.PackLock;
  64. import org.eclipse.jgit.lib.PersonIdent;
  65. import org.eclipse.jgit.lib.Ref;
  66. import org.eclipse.jgit.lib.RefUpdate;
  67. import org.eclipse.jgit.lib.Repository;
  68. import org.eclipse.jgit.lib.Config.SectionParser;
  69. import org.eclipse.jgit.revwalk.ObjectWalk;
  70. import org.eclipse.jgit.revwalk.RevCommit;
  71. import org.eclipse.jgit.revwalk.RevFlag;
  72. import org.eclipse.jgit.revwalk.RevObject;
  73. import org.eclipse.jgit.revwalk.RevWalk;
  74. import org.eclipse.jgit.transport.ReceiveCommand.Result;
  75. import org.eclipse.jgit.transport.RefAdvertiser.PacketLineOutRefAdvertiser;
  76. import org.eclipse.jgit.util.io.InterruptTimer;
  77. import org.eclipse.jgit.util.io.TimeoutInputStream;
  78. import org.eclipse.jgit.util.io.TimeoutOutputStream;
  79. /**
  80. * Implements the server side of a push connection, receiving objects.
  81. */
  82. public class ReceivePack {
  83. static final String CAPABILITY_REPORT_STATUS = BasePackPushConnection.CAPABILITY_REPORT_STATUS;
  84. static final String CAPABILITY_DELETE_REFS = BasePackPushConnection.CAPABILITY_DELETE_REFS;
  85. static final String CAPABILITY_OFS_DELTA = BasePackPushConnection.CAPABILITY_OFS_DELTA;
  86. /** Database we write the stored objects into. */
  87. private final Repository db;
  88. /** Revision traversal support over {@link #db}. */
  89. private final RevWalk walk;
  90. /**
  91. * Is the client connection a bi-directional socket or pipe?
  92. * <p>
  93. * If true, this class assumes it can perform multiple read and write cycles
  94. * with the client over the input and output streams. This matches the
  95. * functionality available with a standard TCP/IP connection, or a local
  96. * operating system or in-memory pipe.
  97. * <p>
  98. * If false, this class runs in a read everything then output results mode,
  99. * making it suitable for single round-trip systems RPCs such as HTTP.
  100. */
  101. private boolean biDirectionalPipe = true;
  102. /** Should an incoming transfer validate objects? */
  103. private boolean checkReceivedObjects;
  104. /** Should an incoming transfer permit create requests? */
  105. private boolean allowCreates;
  106. /** Should an incoming transfer permit delete requests? */
  107. private boolean allowDeletes;
  108. /** Should an incoming transfer permit non-fast-forward requests? */
  109. private boolean allowNonFastForwards;
  110. private boolean allowOfsDelta;
  111. /** Identity to record action as within the reflog. */
  112. private PersonIdent refLogIdent;
  113. /** Filter used while advertising the refs to the client. */
  114. private RefFilter refFilter;
  115. /** Hook to validate the update commands before execution. */
  116. private PreReceiveHook preReceive;
  117. /** Hook to report on the commands after execution. */
  118. private PostReceiveHook postReceive;
  119. /** Timeout in seconds to wait for client interaction. */
  120. private int timeout;
  121. /** Timer to manage {@link #timeout}. */
  122. private InterruptTimer timer;
  123. private TimeoutInputStream timeoutIn;
  124. private InputStream rawIn;
  125. private OutputStream rawOut;
  126. private PacketLineIn pckIn;
  127. private PacketLineOut pckOut;
  128. private PrintWriter msgs;
  129. /** The refs we advertised as existing at the start of the connection. */
  130. private Map<String, Ref> refs;
  131. /** Capabilities requested by the client. */
  132. private Set<String> enabledCapablities;
  133. /** Commands to execute, as received by the client. */
  134. private List<ReceiveCommand> commands;
  135. /** An exception caught while unpacking and fsck'ing the objects. */
  136. private Throwable unpackError;
  137. /** if {@link #enabledCapablities} has {@link #CAPABILITY_REPORT_STATUS} */
  138. private boolean reportStatus;
  139. /** Lock around the received pack file, while updating refs. */
  140. private PackLock packLock;
  141. /**
  142. * Create a new pack receive for an open repository.
  143. *
  144. * @param into
  145. * the destination repository.
  146. */
  147. public ReceivePack(final Repository into) {
  148. db = into;
  149. walk = new RevWalk(db);
  150. final ReceiveConfig cfg = db.getConfig().get(ReceiveConfig.KEY);
  151. checkReceivedObjects = cfg.checkReceivedObjects;
  152. allowCreates = cfg.allowCreates;
  153. allowDeletes = cfg.allowDeletes;
  154. allowNonFastForwards = cfg.allowNonFastForwards;
  155. allowOfsDelta = cfg.allowOfsDelta;
  156. refFilter = RefFilter.DEFAULT;
  157. preReceive = PreReceiveHook.NULL;
  158. postReceive = PostReceiveHook.NULL;
  159. }
  160. private static class ReceiveConfig {
  161. static final SectionParser<ReceiveConfig> KEY = new SectionParser<ReceiveConfig>() {
  162. public ReceiveConfig parse(final Config cfg) {
  163. return new ReceiveConfig(cfg);
  164. }
  165. };
  166. final boolean checkReceivedObjects;
  167. final boolean allowCreates;
  168. final boolean allowDeletes;
  169. final boolean allowNonFastForwards;
  170. final boolean allowOfsDelta;
  171. ReceiveConfig(final Config config) {
  172. checkReceivedObjects = config.getBoolean("receive", "fsckobjects",
  173. false);
  174. allowCreates = true;
  175. allowDeletes = !config.getBoolean("receive", "denydeletes", false);
  176. allowNonFastForwards = !config.getBoolean("receive",
  177. "denynonfastforwards", false);
  178. allowOfsDelta = config.getBoolean("repack", "usedeltabaseoffset",
  179. true);
  180. }
  181. }
  182. /** @return the repository this receive completes into. */
  183. public final Repository getRepository() {
  184. return db;
  185. }
  186. /** @return the RevWalk instance used by this connection. */
  187. public final RevWalk getRevWalk() {
  188. return walk;
  189. }
  190. /** @return all refs which were advertised to the client. */
  191. public final Map<String, Ref> getAdvertisedRefs() {
  192. return refs;
  193. }
  194. /**
  195. * @return true if this class expects a bi-directional pipe opened between
  196. * the client and itself. The default is true.
  197. */
  198. public boolean isBiDirectionalPipe() {
  199. return biDirectionalPipe;
  200. }
  201. /**
  202. * @param twoWay
  203. * if true, this class will assume the socket is a fully
  204. * bidirectional pipe between the two peers and takes advantage
  205. * of that by first transmitting the known refs, then waiting to
  206. * read commands. If false, this class assumes it must read the
  207. * commands before writing output and does not perform the
  208. * initial advertising.
  209. */
  210. public void setBiDirectionalPipe(final boolean twoWay) {
  211. biDirectionalPipe = twoWay;
  212. }
  213. /**
  214. * @return true if this instance will verify received objects are formatted
  215. * correctly. Validating objects requires more CPU time on this side
  216. * of the connection.
  217. */
  218. public boolean isCheckReceivedObjects() {
  219. return checkReceivedObjects;
  220. }
  221. /**
  222. * @param check
  223. * true to enable checking received objects; false to assume all
  224. * received objects are valid.
  225. */
  226. public void setCheckReceivedObjects(final boolean check) {
  227. checkReceivedObjects = check;
  228. }
  229. /** @return true if the client can request refs to be created. */
  230. public boolean isAllowCreates() {
  231. return allowCreates;
  232. }
  233. /**
  234. * @param canCreate
  235. * true to permit create ref commands to be processed.
  236. */
  237. public void setAllowCreates(final boolean canCreate) {
  238. allowCreates = canCreate;
  239. }
  240. /** @return true if the client can request refs to be deleted. */
  241. public boolean isAllowDeletes() {
  242. return allowDeletes;
  243. }
  244. /**
  245. * @param canDelete
  246. * true to permit delete ref commands to be processed.
  247. */
  248. public void setAllowDeletes(final boolean canDelete) {
  249. allowDeletes = canDelete;
  250. }
  251. /**
  252. * @return true if the client can request non-fast-forward updates of a ref,
  253. * possibly making objects unreachable.
  254. */
  255. public boolean isAllowNonFastForwards() {
  256. return allowNonFastForwards;
  257. }
  258. /**
  259. * @param canRewind
  260. * true to permit the client to ask for non-fast-forward updates
  261. * of an existing ref.
  262. */
  263. public void setAllowNonFastForwards(final boolean canRewind) {
  264. allowNonFastForwards = canRewind;
  265. }
  266. /** @return identity of the user making the changes in the reflog. */
  267. public PersonIdent getRefLogIdent() {
  268. return refLogIdent;
  269. }
  270. /**
  271. * Set the identity of the user appearing in the affected reflogs.
  272. * <p>
  273. * The timestamp portion of the identity is ignored. A new identity with the
  274. * current timestamp will be created automatically when the updates occur
  275. * and the log records are written.
  276. *
  277. * @param pi
  278. * identity of the user. If null the identity will be
  279. * automatically determined based on the repository
  280. * configuration.
  281. */
  282. public void setRefLogIdent(final PersonIdent pi) {
  283. refLogIdent = pi;
  284. }
  285. /** @return the filter used while advertising the refs to the client */
  286. public RefFilter getRefFilter() {
  287. return refFilter;
  288. }
  289. /**
  290. * Set the filter used while advertising the refs to the client.
  291. * <p>
  292. * Only refs allowed by this filter will be shown to the client.
  293. * Clients may still attempt to create or update a reference hidden
  294. * by the configured {@link RefFilter}. These attempts should be
  295. * rejected by a matching {@link PreReceiveHook}.
  296. *
  297. * @param refFilter
  298. * the filter; may be null to show all refs.
  299. */
  300. public void setRefFilter(final RefFilter refFilter) {
  301. this.refFilter = refFilter != null ? refFilter : RefFilter.DEFAULT;
  302. }
  303. /** @return get the hook invoked before updates occur. */
  304. public PreReceiveHook getPreReceiveHook() {
  305. return preReceive;
  306. }
  307. /**
  308. * Set the hook which is invoked prior to commands being executed.
  309. * <p>
  310. * Only valid commands (those which have no obvious errors according to the
  311. * received input and this instance's configuration) are passed into the
  312. * hook. The hook may mark a command with a result of any value other than
  313. * {@link Result#NOT_ATTEMPTED} to block its execution.
  314. * <p>
  315. * The hook may be called with an empty command collection if the current
  316. * set is completely invalid.
  317. *
  318. * @param h
  319. * the hook instance; may be null to disable the hook.
  320. */
  321. public void setPreReceiveHook(final PreReceiveHook h) {
  322. preReceive = h != null ? h : PreReceiveHook.NULL;
  323. }
  324. /** @return get the hook invoked after updates occur. */
  325. public PostReceiveHook getPostReceiveHook() {
  326. return postReceive;
  327. }
  328. /**
  329. * Set the hook which is invoked after commands are executed.
  330. * <p>
  331. * Only successful commands (type is {@link Result#OK}) are passed into the
  332. * hook. The hook may be called with an empty command collection if the
  333. * current set all resulted in an error.
  334. *
  335. * @param h
  336. * the hook instance; may be null to disable the hook.
  337. */
  338. public void setPostReceiveHook(final PostReceiveHook h) {
  339. postReceive = h != null ? h : PostReceiveHook.NULL;
  340. }
  341. /** @return timeout (in seconds) before aborting an IO operation. */
  342. public int getTimeout() {
  343. return timeout;
  344. }
  345. /**
  346. * Set the timeout before willing to abort an IO call.
  347. *
  348. * @param seconds
  349. * number of seconds to wait (with no data transfer occurring)
  350. * before aborting an IO read or write operation with the
  351. * connected client.
  352. */
  353. public void setTimeout(final int seconds) {
  354. timeout = seconds;
  355. }
  356. /** @return all of the command received by the current request. */
  357. public List<ReceiveCommand> getAllCommands() {
  358. return Collections.unmodifiableList(commands);
  359. }
  360. /**
  361. * Send an error message to the client, if it supports receiving them.
  362. * <p>
  363. * If the client doesn't support receiving messages, the message will be
  364. * discarded, with no other indication to the caller or to the client.
  365. * <p>
  366. * {@link PreReceiveHook}s should always try to use
  367. * {@link ReceiveCommand#setResult(Result, String)} with a result status of
  368. * {@link Result#REJECTED_OTHER_REASON} to indicate any reasons for
  369. * rejecting an update. Messages attached to a command are much more likely
  370. * to be returned to the client.
  371. *
  372. * @param what
  373. * string describing the problem identified by the hook. The
  374. * string must not end with an LF, and must not contain an LF.
  375. */
  376. public void sendError(final String what) {
  377. sendMessage("error", what);
  378. }
  379. /**
  380. * Send a message to the client, if it supports receiving them.
  381. * <p>
  382. * If the client doesn't support receiving messages, the message will be
  383. * discarded, with no other indication to the caller or to the client.
  384. *
  385. * @param what
  386. * string describing the problem identified by the hook. The
  387. * string must not end with an LF, and must not contain an LF.
  388. */
  389. public void sendMessage(final String what) {
  390. sendMessage("remote", what);
  391. }
  392. private void sendMessage(final String type, final String what) {
  393. if (msgs != null)
  394. msgs.println(type + ": " + what);
  395. }
  396. /**
  397. * Execute the receive task on the socket.
  398. *
  399. * @param input
  400. * raw input to read client commands and pack data from. Caller
  401. * must ensure the input is buffered, otherwise read performance
  402. * may suffer.
  403. * @param output
  404. * response back to the Git network client. Caller must ensure
  405. * the output is buffered, otherwise write performance may
  406. * suffer.
  407. * @param messages
  408. * secondary "notice" channel to send additional messages out
  409. * through. When run over SSH this should be tied back to the
  410. * standard error channel of the command execution. For most
  411. * other network connections this should be null.
  412. * @throws IOException
  413. */
  414. public void receive(final InputStream input, final OutputStream output,
  415. final OutputStream messages) throws IOException {
  416. try {
  417. rawIn = input;
  418. rawOut = output;
  419. if (timeout > 0) {
  420. final Thread caller = Thread.currentThread();
  421. timer = new InterruptTimer(caller.getName() + "-Timer");
  422. timeoutIn = new TimeoutInputStream(rawIn, timer);
  423. TimeoutOutputStream o = new TimeoutOutputStream(rawOut, timer);
  424. timeoutIn.setTimeout(timeout * 1000);
  425. o.setTimeout(timeout * 1000);
  426. rawIn = timeoutIn;
  427. rawOut = o;
  428. }
  429. pckIn = new PacketLineIn(rawIn);
  430. pckOut = new PacketLineOut(rawOut);
  431. if (messages != null) {
  432. msgs = new PrintWriter(new BufferedWriter(
  433. new OutputStreamWriter(messages, Constants.CHARSET),
  434. 8192)) {
  435. @Override
  436. public void println() {
  437. print('\n');
  438. }
  439. };
  440. }
  441. enabledCapablities = new HashSet<String>();
  442. commands = new ArrayList<ReceiveCommand>();
  443. service();
  444. } finally {
  445. try {
  446. if (msgs != null) {
  447. msgs.flush();
  448. }
  449. } finally {
  450. unlockPack();
  451. timeoutIn = null;
  452. rawIn = null;
  453. rawOut = null;
  454. pckIn = null;
  455. pckOut = null;
  456. msgs = null;
  457. refs = null;
  458. enabledCapablities = null;
  459. commands = null;
  460. if (timer != null) {
  461. try {
  462. timer.terminate();
  463. } finally {
  464. timer = null;
  465. }
  466. }
  467. }
  468. }
  469. }
  470. private void service() throws IOException {
  471. if (biDirectionalPipe)
  472. sendAdvertisedRefs(new PacketLineOutRefAdvertiser(pckOut));
  473. else
  474. refs = refFilter.filter(db.getAllRefs());
  475. recvCommands();
  476. if (!commands.isEmpty()) {
  477. enableCapabilities();
  478. if (needPack()) {
  479. try {
  480. receivePack();
  481. if (isCheckReceivedObjects())
  482. checkConnectivity();
  483. unpackError = null;
  484. } catch (IOException err) {
  485. unpackError = err;
  486. } catch (RuntimeException err) {
  487. unpackError = err;
  488. } catch (Error err) {
  489. unpackError = err;
  490. }
  491. }
  492. if (unpackError == null) {
  493. validateCommands();
  494. executeCommands();
  495. }
  496. unlockPack();
  497. if (reportStatus) {
  498. sendStatusReport(true, new Reporter() {
  499. void sendString(final String s) throws IOException {
  500. pckOut.writeString(s + "\n");
  501. }
  502. });
  503. pckOut.end();
  504. } else if (msgs != null) {
  505. sendStatusReport(false, new Reporter() {
  506. void sendString(final String s) throws IOException {
  507. msgs.println(s);
  508. }
  509. });
  510. msgs.flush();
  511. }
  512. postReceive.onPostReceive(this, filterCommands(Result.OK));
  513. }
  514. }
  515. private void unlockPack() {
  516. if (packLock != null) {
  517. packLock.unlock();
  518. packLock = null;
  519. }
  520. }
  521. /**
  522. * Generate an advertisement of available refs and capabilities.
  523. *
  524. * @param adv
  525. * the advertisement formatter.
  526. * @throws IOException
  527. * the formatter failed to write an advertisement.
  528. */
  529. public void sendAdvertisedRefs(final RefAdvertiser adv) throws IOException {
  530. final RevFlag advertised = walk.newFlag("ADVERTISED");
  531. adv.init(walk, advertised);
  532. adv.advertiseCapability(CAPABILITY_DELETE_REFS);
  533. adv.advertiseCapability(CAPABILITY_REPORT_STATUS);
  534. if (allowOfsDelta)
  535. adv.advertiseCapability(CAPABILITY_OFS_DELTA);
  536. refs = refFilter.filter(db.getAllRefs());
  537. final Ref head = refs.remove(Constants.HEAD);
  538. adv.send(refs);
  539. if (head != null && !head.isSymbolic())
  540. adv.advertiseHave(head.getObjectId());
  541. adv.includeAdditionalHaves();
  542. if (adv.isEmpty())
  543. adv.advertiseId(ObjectId.zeroId(), "capabilities^{}");
  544. adv.end();
  545. }
  546. private void recvCommands() throws IOException {
  547. for (;;) {
  548. String line;
  549. try {
  550. line = pckIn.readStringRaw();
  551. } catch (EOFException eof) {
  552. if (commands.isEmpty())
  553. return;
  554. throw eof;
  555. }
  556. if (line == PacketLineIn.END)
  557. break;
  558. if (commands.isEmpty()) {
  559. final int nul = line.indexOf('\0');
  560. if (nul >= 0) {
  561. for (String c : line.substring(nul + 1).split(" "))
  562. enabledCapablities.add(c);
  563. line = line.substring(0, nul);
  564. }
  565. }
  566. if (line.length() < 83) {
  567. final String m = "error: invalid protocol: wanted 'old new ref'";
  568. sendError(m);
  569. throw new PackProtocolException(m);
  570. }
  571. final ObjectId oldId = ObjectId.fromString(line.substring(0, 40));
  572. final ObjectId newId = ObjectId.fromString(line.substring(41, 81));
  573. final String name = line.substring(82);
  574. final ReceiveCommand cmd = new ReceiveCommand(oldId, newId, name);
  575. if (name.equals(Constants.HEAD)) {
  576. cmd.setResult(Result.REJECTED_CURRENT_BRANCH);
  577. } else {
  578. cmd.setRef(refs.get(cmd.getRefName()));
  579. }
  580. commands.add(cmd);
  581. }
  582. }
  583. private void enableCapabilities() {
  584. reportStatus = enabledCapablities.contains(CAPABILITY_REPORT_STATUS);
  585. }
  586. private boolean needPack() {
  587. for (final ReceiveCommand cmd : commands) {
  588. if (cmd.getType() != ReceiveCommand.Type.DELETE)
  589. return true;
  590. }
  591. return false;
  592. }
  593. private void receivePack() throws IOException {
  594. // It might take the client a while to pack the objects it needs
  595. // to send to us. We should increase our timeout so we don't
  596. // abort while the client is computing.
  597. //
  598. if (timeoutIn != null)
  599. timeoutIn.setTimeout(10 * timeout * 1000);
  600. final IndexPack ip = IndexPack.create(db, rawIn);
  601. ip.setFixThin(true);
  602. ip.setObjectChecking(isCheckReceivedObjects());
  603. ip.index(NullProgressMonitor.INSTANCE);
  604. String lockMsg = "jgit receive-pack";
  605. if (getRefLogIdent() != null)
  606. lockMsg += " from " + getRefLogIdent().toExternalString();
  607. packLock = ip.renameAndOpenPack(lockMsg);
  608. if (timeoutIn != null)
  609. timeoutIn.setTimeout(timeout * 1000);
  610. }
  611. private void checkConnectivity() throws IOException {
  612. final ObjectWalk ow = new ObjectWalk(db);
  613. for (final ReceiveCommand cmd : commands) {
  614. if (cmd.getResult() != Result.NOT_ATTEMPTED)
  615. continue;
  616. if (cmd.getType() == ReceiveCommand.Type.DELETE)
  617. continue;
  618. ow.markStart(ow.parseAny(cmd.getNewId()));
  619. }
  620. for (final Ref ref : refs.values())
  621. ow.markUninteresting(ow.parseAny(ref.getObjectId()));
  622. ow.checkConnectivity();
  623. }
  624. private void validateCommands() {
  625. for (final ReceiveCommand cmd : commands) {
  626. final Ref ref = cmd.getRef();
  627. if (cmd.getResult() != Result.NOT_ATTEMPTED)
  628. continue;
  629. if (cmd.getType() == ReceiveCommand.Type.DELETE
  630. && !isAllowDeletes()) {
  631. // Deletes are not supported on this repository.
  632. //
  633. cmd.setResult(Result.REJECTED_NODELETE);
  634. continue;
  635. }
  636. if (cmd.getType() == ReceiveCommand.Type.CREATE) {
  637. if (!isAllowCreates()) {
  638. cmd.setResult(Result.REJECTED_NOCREATE);
  639. continue;
  640. }
  641. if (ref != null && !isAllowNonFastForwards()) {
  642. // Creation over an existing ref is certainly not going
  643. // to be a fast-forward update. We can reject it early.
  644. //
  645. cmd.setResult(Result.REJECTED_NONFASTFORWARD);
  646. continue;
  647. }
  648. if (ref != null) {
  649. // A well behaved client shouldn't have sent us a
  650. // create command for a ref we advertised to it.
  651. //
  652. cmd.setResult(Result.REJECTED_OTHER_REASON, "ref exists");
  653. continue;
  654. }
  655. }
  656. if (cmd.getType() == ReceiveCommand.Type.DELETE && ref != null
  657. && !ObjectId.zeroId().equals(cmd.getOldId())
  658. && !ref.getObjectId().equals(cmd.getOldId())) {
  659. // Delete commands can be sent with the old id matching our
  660. // advertised value, *OR* with the old id being 0{40}. Any
  661. // other requested old id is invalid.
  662. //
  663. cmd.setResult(Result.REJECTED_OTHER_REASON,
  664. "invalid old id sent");
  665. continue;
  666. }
  667. if (cmd.getType() == ReceiveCommand.Type.UPDATE) {
  668. if (ref == null) {
  669. // The ref must have been advertised in order to be updated.
  670. //
  671. cmd.setResult(Result.REJECTED_OTHER_REASON, "no such ref");
  672. continue;
  673. }
  674. if (!ref.getObjectId().equals(cmd.getOldId())) {
  675. // A properly functioning client will send the same
  676. // object id we advertised.
  677. //
  678. cmd.setResult(Result.REJECTED_OTHER_REASON,
  679. "invalid old id sent");
  680. continue;
  681. }
  682. // Is this possibly a non-fast-forward style update?
  683. //
  684. RevObject oldObj, newObj;
  685. try {
  686. oldObj = walk.parseAny(cmd.getOldId());
  687. } catch (IOException e) {
  688. cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd
  689. .getOldId().name());
  690. continue;
  691. }
  692. try {
  693. newObj = walk.parseAny(cmd.getNewId());
  694. } catch (IOException e) {
  695. cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd
  696. .getNewId().name());
  697. continue;
  698. }
  699. if (oldObj instanceof RevCommit && newObj instanceof RevCommit) {
  700. try {
  701. if (!walk.isMergedInto((RevCommit) oldObj,
  702. (RevCommit) newObj)) {
  703. cmd
  704. .setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
  705. }
  706. } catch (MissingObjectException e) {
  707. cmd.setResult(Result.REJECTED_MISSING_OBJECT, e
  708. .getMessage());
  709. } catch (IOException e) {
  710. cmd.setResult(Result.REJECTED_OTHER_REASON);
  711. }
  712. } else {
  713. cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
  714. }
  715. }
  716. if (!cmd.getRefName().startsWith(Constants.R_REFS)
  717. || !Repository.isValidRefName(cmd.getRefName())) {
  718. cmd.setResult(Result.REJECTED_OTHER_REASON, "funny refname");
  719. }
  720. }
  721. }
  722. private void executeCommands() {
  723. preReceive.onPreReceive(this, filterCommands(Result.NOT_ATTEMPTED));
  724. for (final ReceiveCommand cmd : filterCommands(Result.NOT_ATTEMPTED))
  725. execute(cmd);
  726. }
  727. private void execute(final ReceiveCommand cmd) {
  728. try {
  729. final RefUpdate ru = db.updateRef(cmd.getRefName());
  730. ru.setRefLogIdent(getRefLogIdent());
  731. switch (cmd.getType()) {
  732. case DELETE:
  733. if (!ObjectId.zeroId().equals(cmd.getOldId())) {
  734. // We can only do a CAS style delete if the client
  735. // didn't bork its delete request by sending the
  736. // wrong zero id rather than the advertised one.
  737. //
  738. ru.setExpectedOldObjectId(cmd.getOldId());
  739. }
  740. ru.setForceUpdate(true);
  741. status(cmd, ru.delete(walk));
  742. break;
  743. case CREATE:
  744. case UPDATE:
  745. case UPDATE_NONFASTFORWARD:
  746. ru.setForceUpdate(isAllowNonFastForwards());
  747. ru.setExpectedOldObjectId(cmd.getOldId());
  748. ru.setNewObjectId(cmd.getNewId());
  749. ru.setRefLogMessage("push", true);
  750. status(cmd, ru.update(walk));
  751. break;
  752. }
  753. } catch (IOException err) {
  754. cmd.setResult(Result.REJECTED_OTHER_REASON, "lock error: "
  755. + err.getMessage());
  756. }
  757. }
  758. private void status(final ReceiveCommand cmd, final RefUpdate.Result result) {
  759. switch (result) {
  760. case NOT_ATTEMPTED:
  761. cmd.setResult(Result.NOT_ATTEMPTED);
  762. break;
  763. case LOCK_FAILURE:
  764. case IO_FAILURE:
  765. cmd.setResult(Result.LOCK_FAILURE);
  766. break;
  767. case NO_CHANGE:
  768. case NEW:
  769. case FORCED:
  770. case FAST_FORWARD:
  771. cmd.setResult(Result.OK);
  772. break;
  773. case REJECTED:
  774. cmd.setResult(Result.REJECTED_NONFASTFORWARD);
  775. break;
  776. case REJECTED_CURRENT_BRANCH:
  777. cmd.setResult(Result.REJECTED_CURRENT_BRANCH);
  778. break;
  779. default:
  780. cmd.setResult(Result.REJECTED_OTHER_REASON, result.name());
  781. break;
  782. }
  783. }
  784. private List<ReceiveCommand> filterCommands(final Result want) {
  785. final List<ReceiveCommand> r = new ArrayList<ReceiveCommand>(commands
  786. .size());
  787. for (final ReceiveCommand cmd : commands) {
  788. if (cmd.getResult() == want)
  789. r.add(cmd);
  790. }
  791. return r;
  792. }
  793. private void sendStatusReport(final boolean forClient, final Reporter out)
  794. throws IOException {
  795. if (unpackError != null) {
  796. out.sendString("unpack error " + unpackError.getMessage());
  797. if (forClient) {
  798. for (final ReceiveCommand cmd : commands) {
  799. out.sendString("ng " + cmd.getRefName()
  800. + " n/a (unpacker error)");
  801. }
  802. }
  803. return;
  804. }
  805. if (forClient)
  806. out.sendString("unpack ok");
  807. for (final ReceiveCommand cmd : commands) {
  808. if (cmd.getResult() == Result.OK) {
  809. if (forClient)
  810. out.sendString("ok " + cmd.getRefName());
  811. continue;
  812. }
  813. final StringBuilder r = new StringBuilder();
  814. r.append("ng ");
  815. r.append(cmd.getRefName());
  816. r.append(" ");
  817. switch (cmd.getResult()) {
  818. case NOT_ATTEMPTED:
  819. r.append("server bug; ref not processed");
  820. break;
  821. case REJECTED_NOCREATE:
  822. r.append("creation prohibited");
  823. break;
  824. case REJECTED_NODELETE:
  825. r.append("deletion prohibited");
  826. break;
  827. case REJECTED_NONFASTFORWARD:
  828. r.append("non-fast forward");
  829. break;
  830. case REJECTED_CURRENT_BRANCH:
  831. r.append("branch is currently checked out");
  832. break;
  833. case REJECTED_MISSING_OBJECT:
  834. if (cmd.getMessage() == null)
  835. r.append("missing object(s)");
  836. else if (cmd.getMessage().length() == Constants.OBJECT_ID_STRING_LENGTH)
  837. r.append("object " + cmd.getMessage() + " missing");
  838. else
  839. r.append(cmd.getMessage());
  840. break;
  841. case REJECTED_OTHER_REASON:
  842. if (cmd.getMessage() == null)
  843. r.append("unspecified reason");
  844. else
  845. r.append(cmd.getMessage());
  846. break;
  847. case LOCK_FAILURE:
  848. r.append("failed to lock");
  849. break;
  850. case OK:
  851. // We shouldn't have reached this case (see 'ok' case above).
  852. continue;
  853. }
  854. out.sendString(r.toString());
  855. }
  856. }
  857. static abstract class Reporter {
  858. abstract void sendString(String s) throws IOException;
  859. }
  860. }