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

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