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.

BasePackPushConnection.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. /*
  2. * Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com>
  3. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.transport;
  45. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_ATOMIC;
  46. import java.io.IOException;
  47. import java.io.OutputStream;
  48. import java.text.MessageFormat;
  49. import java.util.Collection;
  50. import java.util.HashSet;
  51. import java.util.Map;
  52. import java.util.Set;
  53. import org.eclipse.jgit.errors.NoRemoteRepositoryException;
  54. import org.eclipse.jgit.errors.NotSupportedException;
  55. import org.eclipse.jgit.errors.PackProtocolException;
  56. import org.eclipse.jgit.errors.TooLargePackException;
  57. import org.eclipse.jgit.errors.TransportException;
  58. import org.eclipse.jgit.internal.JGitText;
  59. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  60. import org.eclipse.jgit.lib.ObjectId;
  61. import org.eclipse.jgit.lib.ProgressMonitor;
  62. import org.eclipse.jgit.lib.Ref;
  63. import org.eclipse.jgit.transport.RemoteRefUpdate.Status;
  64. /**
  65. * Push implementation using the native Git pack transfer service.
  66. * <p>
  67. * This is the canonical implementation for transferring objects to the remote
  68. * repository from the local repository by talking to the 'git-receive-pack'
  69. * service. Objects are packed on the local side into a pack file and then sent
  70. * to the remote repository.
  71. * <p>
  72. * This connection requires only a bi-directional pipe or socket, and thus is
  73. * easily wrapped up into a local process pipe, anonymous TCP socket, or a
  74. * command executed through an SSH tunnel.
  75. * <p>
  76. * This implementation honors {@link Transport#isPushThin()} option.
  77. * <p>
  78. * Concrete implementations should just call
  79. * {@link #init(java.io.InputStream, java.io.OutputStream)} and
  80. * {@link #readAdvertisedRefs()} methods in constructor or before any use. They
  81. * should also handle resources releasing in {@link #close()} method if needed.
  82. */
  83. public abstract class BasePackPushConnection extends BasePackConnection implements
  84. PushConnection {
  85. /**
  86. * The client expects a status report after the server processes the pack.
  87. * @since 2.0
  88. */
  89. public static final String CAPABILITY_REPORT_STATUS = GitProtocolConstants.CAPABILITY_REPORT_STATUS;
  90. /**
  91. * The server supports deleting refs.
  92. * @since 2.0
  93. */
  94. public static final String CAPABILITY_DELETE_REFS = GitProtocolConstants.CAPABILITY_DELETE_REFS;
  95. /**
  96. * The server supports packs with OFS deltas.
  97. * @since 2.0
  98. */
  99. public static final String CAPABILITY_OFS_DELTA = GitProtocolConstants.CAPABILITY_OFS_DELTA;
  100. /**
  101. * The client supports using the 64K side-band for progress messages.
  102. * @since 2.0
  103. */
  104. public static final String CAPABILITY_SIDE_BAND_64K = GitProtocolConstants.CAPABILITY_SIDE_BAND_64K;
  105. private final boolean thinPack;
  106. private final boolean atomic;
  107. private boolean capableAtomic;
  108. private boolean capableDeleteRefs;
  109. private boolean capableReport;
  110. private boolean capableSideBand;
  111. private boolean capableOfsDelta;
  112. private boolean sentCommand;
  113. private boolean writePack;
  114. /** Time in milliseconds spent transferring the pack data. */
  115. private long packTransferTime;
  116. /**
  117. * Create a new connection to push using the native git transport.
  118. *
  119. * @param packTransport
  120. * the transport.
  121. */
  122. public BasePackPushConnection(final PackTransport packTransport) {
  123. super(packTransport);
  124. thinPack = transport.isPushThin();
  125. atomic = transport.isPushAtomic();
  126. }
  127. public void push(final ProgressMonitor monitor,
  128. final Map<String, RemoteRefUpdate> refUpdates)
  129. throws TransportException {
  130. push(monitor, refUpdates, null);
  131. }
  132. /**
  133. * @since 3.0
  134. */
  135. public void push(final ProgressMonitor monitor,
  136. final Map<String, RemoteRefUpdate> refUpdates, OutputStream outputStream)
  137. throws TransportException {
  138. markStartedOperation();
  139. doPush(monitor, refUpdates, outputStream);
  140. }
  141. @Override
  142. protected TransportException noRepository() {
  143. // Sadly we cannot tell the "invalid URI" case from "push not allowed".
  144. // Opening a fetch connection can help us tell the difference, as any
  145. // useful repository is going to support fetch if it also would allow
  146. // push. So if fetch throws NoRemoteRepositoryException we know the
  147. // URI is wrong. Otherwise we can correctly state push isn't allowed
  148. // as the fetch connection opened successfully.
  149. //
  150. try {
  151. transport.openFetch().close();
  152. } catch (NotSupportedException e) {
  153. // Fall through.
  154. } catch (NoRemoteRepositoryException e) {
  155. // Fetch concluded the repository doesn't exist.
  156. //
  157. return e;
  158. } catch (TransportException e) {
  159. // Fall through.
  160. }
  161. return new TransportException(uri, JGitText.get().pushNotPermitted);
  162. }
  163. /**
  164. * Push one or more objects and update the remote repository.
  165. *
  166. * @param monitor
  167. * progress monitor to receive status updates.
  168. * @param refUpdates
  169. * update commands to be applied to the remote repository.
  170. * @param outputStream
  171. * output stream to write sideband messages to
  172. * @throws TransportException
  173. * if any exception occurs.
  174. * @since 3.0
  175. */
  176. protected void doPush(final ProgressMonitor monitor,
  177. final Map<String, RemoteRefUpdate> refUpdates,
  178. OutputStream outputStream) throws TransportException {
  179. try {
  180. writeCommands(refUpdates.values(), monitor, outputStream);
  181. if (writePack)
  182. writePack(refUpdates, monitor);
  183. if (sentCommand) {
  184. if (capableReport)
  185. readStatusReport(refUpdates);
  186. if (capableSideBand) {
  187. // Ensure the data channel is at EOF, so we know we have
  188. // read all side-band data from all channels and have a
  189. // complete copy of the messages (if any) buffered from
  190. // the other data channels.
  191. //
  192. int b = in.read();
  193. if (0 <= b)
  194. throw new TransportException(uri, MessageFormat.format(
  195. JGitText.get().expectedEOFReceived,
  196. Character.valueOf((char) b)));
  197. }
  198. }
  199. } catch (TransportException e) {
  200. throw e;
  201. } catch (Exception e) {
  202. throw new TransportException(uri, e.getMessage(), e);
  203. } finally {
  204. close();
  205. }
  206. }
  207. private void writeCommands(final Collection<RemoteRefUpdate> refUpdates,
  208. final ProgressMonitor monitor, OutputStream outputStream) throws IOException {
  209. final String capabilities = enableCapabilities(monitor, outputStream);
  210. if (atomic && !capableAtomic) {
  211. throw new TransportException(uri,
  212. JGitText.get().atomicPushNotSupported);
  213. }
  214. for (final RemoteRefUpdate rru : refUpdates) {
  215. if (!capableDeleteRefs && rru.isDelete()) {
  216. rru.setStatus(Status.REJECTED_NODELETE);
  217. continue;
  218. }
  219. final StringBuilder sb = new StringBuilder();
  220. ObjectId oldId = rru.getExpectedOldObjectId();
  221. if (oldId == null) {
  222. final Ref advertised = getRef(rru.getRemoteName());
  223. oldId = advertised != null ? advertised.getObjectId() : null;
  224. if (oldId == null) {
  225. oldId = ObjectId.zeroId();
  226. }
  227. }
  228. sb.append(oldId.name());
  229. sb.append(' ');
  230. sb.append(rru.getNewObjectId().name());
  231. sb.append(' ');
  232. sb.append(rru.getRemoteName());
  233. if (!sentCommand) {
  234. sentCommand = true;
  235. sb.append(capabilities);
  236. }
  237. pckOut.writeString(sb.toString());
  238. rru.setStatus(Status.AWAITING_REPORT);
  239. if (!rru.isDelete())
  240. writePack = true;
  241. }
  242. if (monitor.isCancelled())
  243. throw new TransportException(uri, JGitText.get().pushCancelled);
  244. pckOut.end();
  245. outNeedsEnd = false;
  246. }
  247. private String enableCapabilities(final ProgressMonitor monitor,
  248. OutputStream outputStream) {
  249. final StringBuilder line = new StringBuilder();
  250. if (atomic)
  251. capableAtomic = wantCapability(line, CAPABILITY_ATOMIC);
  252. capableReport = wantCapability(line, CAPABILITY_REPORT_STATUS);
  253. capableDeleteRefs = wantCapability(line, CAPABILITY_DELETE_REFS);
  254. capableOfsDelta = wantCapability(line, CAPABILITY_OFS_DELTA);
  255. capableSideBand = wantCapability(line, CAPABILITY_SIDE_BAND_64K);
  256. if (capableSideBand) {
  257. in = new SideBandInputStream(in, monitor, getMessageWriter(),
  258. outputStream);
  259. pckIn = new PacketLineIn(in);
  260. }
  261. addUserAgentCapability(line);
  262. if (line.length() > 0)
  263. line.setCharAt(0, '\0');
  264. return line.toString();
  265. }
  266. private void writePack(final Map<String, RemoteRefUpdate> refUpdates,
  267. final ProgressMonitor monitor) throws IOException {
  268. Set<ObjectId> remoteObjects = new HashSet<ObjectId>();
  269. Set<ObjectId> newObjects = new HashSet<ObjectId>();
  270. try (final PackWriter writer = new PackWriter(transport.getPackConfig(),
  271. local.newObjectReader())) {
  272. for (final Ref r : getRefs()) {
  273. // only add objects that we actually have
  274. ObjectId oid = r.getObjectId();
  275. if (local.hasObject(oid))
  276. remoteObjects.add(oid);
  277. }
  278. remoteObjects.addAll(additionalHaves);
  279. for (final RemoteRefUpdate r : refUpdates.values()) {
  280. if (!ObjectId.zeroId().equals(r.getNewObjectId()))
  281. newObjects.add(r.getNewObjectId());
  282. }
  283. writer.setIndexDisabled(true);
  284. writer.setUseCachedPacks(true);
  285. writer.setUseBitmaps(true);
  286. writer.setThin(thinPack);
  287. writer.setReuseValidatingObjects(false);
  288. writer.setDeltaBaseAsOffset(capableOfsDelta);
  289. writer.preparePack(monitor, newObjects, remoteObjects);
  290. writer.writePack(monitor, monitor, out);
  291. packTransferTime = writer.getStatistics().getTimeWriting();
  292. }
  293. }
  294. private void readStatusReport(final Map<String, RemoteRefUpdate> refUpdates)
  295. throws IOException {
  296. final String unpackLine = readStringLongTimeout();
  297. if (!unpackLine.startsWith("unpack ")) //$NON-NLS-1$
  298. throw new PackProtocolException(uri, MessageFormat.format(JGitText.get().unexpectedReportLine, unpackLine));
  299. final String unpackStatus = unpackLine.substring("unpack ".length()); //$NON-NLS-1$
  300. if (unpackStatus.startsWith("error Pack exceeds the limit of")) //$NON-NLS-1$
  301. throw new TooLargePackException(uri,
  302. unpackStatus.substring("error ".length())); //$NON-NLS-1$
  303. if (!unpackStatus.equals("ok")) //$NON-NLS-1$
  304. throw new TransportException(uri, MessageFormat.format(
  305. JGitText.get().errorOccurredDuringUnpackingOnTheRemoteEnd, unpackStatus));
  306. String refLine;
  307. while ((refLine = pckIn.readString()) != PacketLineIn.END) {
  308. boolean ok = false;
  309. int refNameEnd = -1;
  310. if (refLine.startsWith("ok ")) { //$NON-NLS-1$
  311. ok = true;
  312. refNameEnd = refLine.length();
  313. } else if (refLine.startsWith("ng ")) { //$NON-NLS-1$
  314. ok = false;
  315. refNameEnd = refLine.indexOf(" ", 3); //$NON-NLS-1$
  316. }
  317. if (refNameEnd == -1)
  318. throw new PackProtocolException(MessageFormat.format(JGitText.get().unexpectedReportLine2
  319. , uri, refLine));
  320. final String refName = refLine.substring(3, refNameEnd);
  321. final String message = (ok ? null : refLine
  322. .substring(refNameEnd + 1));
  323. final RemoteRefUpdate rru = refUpdates.get(refName);
  324. if (rru == null)
  325. throw new PackProtocolException(MessageFormat.format(JGitText.get().unexpectedRefReport, uri, refName));
  326. if (ok) {
  327. rru.setStatus(Status.OK);
  328. } else {
  329. rru.setStatus(Status.REJECTED_OTHER_REASON);
  330. rru.setMessage(message);
  331. }
  332. }
  333. for (final RemoteRefUpdate rru : refUpdates.values()) {
  334. if (rru.getStatus() == Status.AWAITING_REPORT)
  335. throw new PackProtocolException(MessageFormat.format(
  336. JGitText.get().expectedReportForRefNotReceived , uri, rru.getRemoteName()));
  337. }
  338. }
  339. private String readStringLongTimeout() throws IOException {
  340. if (timeoutIn == null)
  341. return pckIn.readString();
  342. // The remote side may need a lot of time to choke down the pack
  343. // we just sent them. There may be many deltas that need to be
  344. // resolved by the remote. Its hard to say how long the other
  345. // end is going to be silent. Taking 10x the configured timeout
  346. // or the time spent transferring the pack, whichever is larger,
  347. // gives the other side some reasonable window to process the data,
  348. // but this is just a wild guess.
  349. //
  350. final int oldTimeout = timeoutIn.getTimeout();
  351. final int sendTime = (int) Math.min(packTransferTime, 28800000L);
  352. try {
  353. int timeout = 10 * Math.max(sendTime, oldTimeout);
  354. timeoutIn.setTimeout((timeout < 0) ? Integer.MAX_VALUE : timeout);
  355. return pckIn.readString();
  356. } finally {
  357. timeoutIn.setTimeout(oldTimeout);
  358. }
  359. }
  360. }