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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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.lib.Constants.HEAD;
  45. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_ATOMIC;
  46. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_PUSH_OPTIONS;
  47. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_REPORT_STATUS;
  48. import java.io.IOException;
  49. import java.io.InputStream;
  50. import java.io.OutputStream;
  51. import java.util.ArrayList;
  52. import java.util.Collections;
  53. import java.util.List;
  54. import java.util.Map;
  55. import java.util.Set;
  56. import org.eclipse.jgit.annotations.Nullable;
  57. import org.eclipse.jgit.errors.UnpackException;
  58. import org.eclipse.jgit.lib.ConfigConstants;
  59. import org.eclipse.jgit.lib.Constants;
  60. import org.eclipse.jgit.lib.NullProgressMonitor;
  61. import org.eclipse.jgit.lib.ObjectId;
  62. import org.eclipse.jgit.lib.Ref;
  63. import org.eclipse.jgit.lib.Repository;
  64. import org.eclipse.jgit.revwalk.RevWalk;
  65. import org.eclipse.jgit.transport.ReceiveCommand.Result;
  66. import org.eclipse.jgit.transport.RefAdvertiser.PacketLineOutRefAdvertiser;
  67. /**
  68. * Implements the server side of a push connection, receiving objects.
  69. */
  70. public class ReceivePack extends BaseReceivePack {
  71. /** Hook to validate the update commands before execution. */
  72. private PreReceiveHook preReceive;
  73. /** Hook to report on the commands after execution. */
  74. private PostReceiveHook postReceive;
  75. /** If {@link BasePackPushConnection#CAPABILITY_REPORT_STATUS} is enabled. */
  76. private boolean reportStatus;
  77. /** Whether the client intends to use push options. */
  78. private boolean usePushOptions;
  79. private List<String> pushOptions;
  80. /**
  81. * Create a new pack receive for an open repository.
  82. *
  83. * @param into
  84. * the destination repository.
  85. */
  86. public ReceivePack(Repository into) {
  87. super(into);
  88. preReceive = PreReceiveHook.NULL;
  89. postReceive = PostReceiveHook.NULL;
  90. }
  91. /**
  92. * Get the repository this receive completes into.
  93. *
  94. * @return the repository this receive completes into.
  95. */
  96. @Override
  97. public final Repository getRepository() {
  98. return db;
  99. }
  100. /**
  101. * Get the RevWalk instance used by this connection.
  102. *
  103. * @return the RevWalk instance used by this connection.
  104. */
  105. @Override
  106. public final RevWalk getRevWalk() {
  107. return walk;
  108. }
  109. /**
  110. * Get refs which were advertised to the client.
  111. *
  112. * @return all refs which were advertised to the client, or null if
  113. * {@link #setAdvertisedRefs(Map, Set)} has not been called yet.
  114. */
  115. @Override
  116. public final Map<String, Ref> getAdvertisedRefs() {
  117. return refs;
  118. }
  119. /**
  120. * Set the refs advertised by this ReceivePack.
  121. * <p>
  122. * Intended to be called from a
  123. * {@link org.eclipse.jgit.transport.PreReceiveHook}.
  124. *
  125. * @param allRefs
  126. * explicit set of references to claim as advertised by this
  127. * ReceivePack instance. This overrides any references that may
  128. * exist in the source repository. The map is passed to the
  129. * configured {@link #getRefFilter()}. If null, assumes all refs
  130. * were advertised.
  131. * @param additionalHaves
  132. * explicit set of additional haves to claim as advertised. If
  133. * null, assumes the default set of additional haves from the
  134. * repository.
  135. */
  136. @Override
  137. public void setAdvertisedRefs(Map<String, Ref> allRefs, Set<ObjectId> additionalHaves) {
  138. refs = allRefs != null ? allRefs : db.getAllRefs();
  139. refs = refFilter.filter(refs);
  140. advertisedHaves.clear();
  141. Ref head = refs.get(HEAD);
  142. if (head != null && head.isSymbolic()) {
  143. refs.remove(HEAD);
  144. }
  145. for (Ref ref : refs.values()) {
  146. if (ref.getObjectId() != null) {
  147. advertisedHaves.add(ref.getObjectId());
  148. }
  149. }
  150. if (additionalHaves != null) {
  151. advertisedHaves.addAll(additionalHaves);
  152. } else {
  153. advertisedHaves.addAll(db.getAdditionalHaves());
  154. }
  155. }
  156. /**
  157. * Get the push certificate used to verify the pusher's identity.
  158. * <p>
  159. * Only valid after commands are read from the wire.
  160. *
  161. * @return the parsed certificate, or null if push certificates are disabled
  162. * or no cert was presented by the client.
  163. * @since 4.1
  164. */
  165. @Override
  166. public PushCertificate getPushCertificate() {
  167. return pushCert;
  168. }
  169. /**
  170. * Set the push certificate used to verify the pusher's identity.
  171. * <p>
  172. * Should only be called if reconstructing an instance without going through
  173. * the normal {@link #recvCommands()} flow.
  174. *
  175. * @param cert
  176. * the push certificate to set.
  177. * @since 4.1
  178. */
  179. @Override
  180. public void setPushCertificate(PushCertificate cert) {
  181. pushCert = cert;
  182. }
  183. /**
  184. * Gets an unmodifiable view of the option strings associated with the push.
  185. *
  186. * @return an unmodifiable view of pushOptions, or null (if pushOptions is).
  187. * @since 4.5
  188. */
  189. @Nullable
  190. public List<String> getPushOptions() {
  191. if (isAllowPushOptions() && usePushOptions) {
  192. return Collections.unmodifiableList(pushOptions);
  193. }
  194. // The client doesn't support push options. Return null to
  195. // distinguish this from the case where the client declared support
  196. // for push options and sent an empty list of them.
  197. return null;
  198. }
  199. /**
  200. * Set the push options supplied by the client.
  201. * <p>
  202. * Should only be called if reconstructing an instance without going through
  203. * the normal {@link #recvCommands()} flow.
  204. *
  205. * @param options
  206. * the list of options supplied by the client. The
  207. * {@code ReceivePack} instance takes ownership of this list.
  208. * Callers are encouraged to first create a copy if the list may
  209. * be modified later.
  210. * @since 4.5
  211. */
  212. public void setPushOptions(@Nullable List<String> options) {
  213. usePushOptions = options != null;
  214. pushOptions = options;
  215. }
  216. /**
  217. * Get the hook invoked before updates occur.
  218. *
  219. * @return the hook invoked before updates occur.
  220. */
  221. public PreReceiveHook getPreReceiveHook() {
  222. return preReceive;
  223. }
  224. /**
  225. * Set the hook which is invoked prior to commands being executed.
  226. * <p>
  227. * Only valid commands (those which have no obvious errors according to the
  228. * received input and this instance's configuration) are passed into the
  229. * hook. The hook may mark a command with a result of any value other than
  230. * {@link org.eclipse.jgit.transport.ReceiveCommand.Result#NOT_ATTEMPTED} to
  231. * block its execution.
  232. * <p>
  233. * The hook may be called with an empty command collection if the current
  234. * set is completely invalid.
  235. *
  236. * @param h
  237. * the hook instance; may be null to disable the hook.
  238. */
  239. public void setPreReceiveHook(PreReceiveHook h) {
  240. preReceive = h != null ? h : PreReceiveHook.NULL;
  241. }
  242. /**
  243. * Get the hook invoked after updates occur.
  244. *
  245. * @return the hook invoked after updates occur.
  246. */
  247. public PostReceiveHook getPostReceiveHook() {
  248. return postReceive;
  249. }
  250. /**
  251. * Set the hook which is invoked after commands are executed.
  252. * <p>
  253. * Only successful commands (type is
  254. * {@link org.eclipse.jgit.transport.ReceiveCommand.Result#OK}) are passed
  255. * into the hook. The hook may be called with an empty command collection if
  256. * the current set all resulted in an error.
  257. *
  258. * @param h
  259. * the hook instance; may be null to disable the hook.
  260. */
  261. public void setPostReceiveHook(PostReceiveHook h) {
  262. postReceive = h != null ? h : PostReceiveHook.NULL;
  263. }
  264. /**
  265. * Set whether this class will report command failures as warning messages
  266. * before sending the command results.
  267. *
  268. * @param echo
  269. * if true this class will report command failures as warning
  270. * messages before sending the command results. This is usually
  271. * not necessary, but may help buggy Git clients that discard the
  272. * errors when all branches fail.
  273. * @deprecated no widely used Git versions need this any more
  274. */
  275. @Deprecated
  276. public void setEchoCommandFailures(boolean echo) {
  277. // No-op.
  278. }
  279. /**
  280. * Execute the receive task on the socket.
  281. *
  282. * @param input
  283. * raw input to read client commands and pack data from. Caller
  284. * must ensure the input is buffered, otherwise read performance
  285. * may suffer.
  286. * @param output
  287. * response back to the Git network client. Caller must ensure
  288. * the output is buffered, otherwise write performance may
  289. * suffer.
  290. * @param messages
  291. * secondary "notice" channel to send additional messages out
  292. * through. When run over SSH this should be tied back to the
  293. * standard error channel of the command execution. For most
  294. * other network connections this should be null.
  295. * @throws java.io.IOException
  296. */
  297. public void receive(final InputStream input, final OutputStream output,
  298. final OutputStream messages) throws IOException {
  299. init(input, output, messages);
  300. try {
  301. service();
  302. } finally {
  303. try {
  304. close();
  305. } finally {
  306. release();
  307. }
  308. }
  309. }
  310. /** {@inheritDoc} */
  311. @Override
  312. protected void enableCapabilities() {
  313. reportStatus = isCapabilityEnabled(CAPABILITY_REPORT_STATUS);
  314. usePushOptions = isCapabilityEnabled(CAPABILITY_PUSH_OPTIONS);
  315. super.enableCapabilities();
  316. }
  317. @Override
  318. void readPostCommands(PacketLineIn in) throws IOException {
  319. if (usePushOptions) {
  320. pushOptions = new ArrayList<>(4);
  321. for (;;) {
  322. String option = in.readString();
  323. if (option == PacketLineIn.END) {
  324. break;
  325. }
  326. pushOptions.add(option);
  327. }
  328. }
  329. }
  330. private void service() throws IOException {
  331. if (isBiDirectionalPipe()) {
  332. sendAdvertisedRefs(new PacketLineOutRefAdvertiser(pckOut));
  333. pckOut.flush();
  334. } else
  335. getAdvertisedOrDefaultRefs();
  336. if (hasError())
  337. return;
  338. recvCommands();
  339. if (hasCommands()) {
  340. Throwable unpackError = null;
  341. if (needPack()) {
  342. try {
  343. receivePackAndCheckConnectivity();
  344. } catch (IOException | RuntimeException | Error err) {
  345. unpackError = err;
  346. }
  347. }
  348. try {
  349. if (unpackError == null) {
  350. boolean atomic = isCapabilityEnabled(CAPABILITY_ATOMIC);
  351. setAtomic(atomic);
  352. validateCommands();
  353. if (atomic && anyRejects()) {
  354. failPendingCommands();
  355. }
  356. preReceive.onPreReceive(
  357. this, filterCommands(Result.NOT_ATTEMPTED));
  358. if (atomic && anyRejects()) {
  359. failPendingCommands();
  360. }
  361. executeCommands();
  362. }
  363. } finally {
  364. unlockPack();
  365. }
  366. if (reportStatus) {
  367. sendStatusReport(true, unpackError, new Reporter() {
  368. @Override
  369. void sendString(String s) throws IOException {
  370. pckOut.writeString(s + "\n"); //$NON-NLS-1$
  371. }
  372. });
  373. pckOut.end();
  374. } else if (msgOut != null) {
  375. sendStatusReport(false, unpackError, new Reporter() {
  376. @Override
  377. void sendString(String s) throws IOException {
  378. msgOut.write(Constants.encode(s + "\n")); //$NON-NLS-1$
  379. }
  380. });
  381. }
  382. if (unpackError != null) {
  383. // we already know which exception to throw. Ignore
  384. // potential additional exceptions raised in postReceiveHooks
  385. try {
  386. postReceive.onPostReceive(this, filterCommands(Result.OK));
  387. } catch (Throwable e) {
  388. // empty
  389. }
  390. throw new UnpackException(unpackError);
  391. }
  392. postReceive.onPostReceive(this, filterCommands(Result.OK));
  393. autoGc();
  394. }
  395. }
  396. private void autoGc() {
  397. Repository repo = getRepository();
  398. if (!repo.getConfig().getBoolean(ConfigConstants.CONFIG_RECEIVE_SECTION,
  399. ConfigConstants.CONFIG_KEY_AUTOGC, true)) {
  400. return;
  401. }
  402. repo.autoGC(NullProgressMonitor.INSTANCE);
  403. }
  404. /** {@inheritDoc} */
  405. @Override
  406. protected String getLockMessageProcessName() {
  407. return "jgit receive-pack"; //$NON-NLS-1$
  408. }
  409. }