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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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 java.io.IOException;
  46. import java.text.MessageFormat;
  47. import java.util.Collection;
  48. import java.util.HashSet;
  49. import java.util.Map;
  50. import java.util.Set;
  51. import org.eclipse.jgit.JGitText;
  52. import org.eclipse.jgit.errors.NoRemoteRepositoryException;
  53. import org.eclipse.jgit.errors.NotSupportedException;
  54. import org.eclipse.jgit.errors.PackProtocolException;
  55. import org.eclipse.jgit.errors.TransportException;
  56. import org.eclipse.jgit.lib.ObjectId;
  57. import org.eclipse.jgit.lib.ProgressMonitor;
  58. import org.eclipse.jgit.lib.Ref;
  59. import org.eclipse.jgit.storage.pack.PackWriter;
  60. import org.eclipse.jgit.transport.RemoteRefUpdate.Status;
  61. /**
  62. * Push implementation using the native Git pack transfer service.
  63. * <p>
  64. * This is the canonical implementation for transferring objects to the remote
  65. * repository from the local repository by talking to the 'git-receive-pack'
  66. * service. Objects are packed on the local side into a pack file and then sent
  67. * to the remote repository.
  68. * <p>
  69. * This connection requires only a bi-directional pipe or socket, and thus is
  70. * easily wrapped up into a local process pipe, anonymous TCP socket, or a
  71. * command executed through an SSH tunnel.
  72. * <p>
  73. * This implementation honors {@link Transport#isPushThin()} option.
  74. * <p>
  75. * Concrete implementations should just call
  76. * {@link #init(java.io.InputStream, java.io.OutputStream)} and
  77. * {@link #readAdvertisedRefs()} methods in constructor or before any use. They
  78. * should also handle resources releasing in {@link #close()} method if needed.
  79. */
  80. public abstract class BasePackPushConnection extends BasePackConnection implements
  81. PushConnection {
  82. /** The client expects a status report after the server processes the pack. */
  83. public static final String CAPABILITY_REPORT_STATUS = "report-status";
  84. /** The server supports deleting refs. */
  85. public static final String CAPABILITY_DELETE_REFS = "delete-refs";
  86. /** The server supports packs with OFS deltas. */
  87. public static final String CAPABILITY_OFS_DELTA = "ofs-delta";
  88. /** The client supports using the 64K side-band for progress messages. */
  89. public static final String CAPABILITY_SIDE_BAND_64K = "side-band-64k";
  90. private final boolean thinPack;
  91. private boolean capableDeleteRefs;
  92. private boolean capableReport;
  93. private boolean capableSideBand;
  94. private boolean capableOfsDelta;
  95. private boolean sentCommand;
  96. private boolean writePack;
  97. /** Time in milliseconds spent transferring the pack data. */
  98. private long packTransferTime;
  99. /**
  100. * Create a new connection to push using the native git transport.
  101. *
  102. * @param packTransport
  103. * the transport.
  104. */
  105. public BasePackPushConnection(final PackTransport packTransport) {
  106. super(packTransport);
  107. thinPack = transport.isPushThin();
  108. }
  109. public void push(final ProgressMonitor monitor,
  110. final Map<String, RemoteRefUpdate> refUpdates)
  111. throws TransportException {
  112. markStartedOperation();
  113. doPush(monitor, refUpdates);
  114. }
  115. @Override
  116. protected TransportException noRepository() {
  117. // Sadly we cannot tell the "invalid URI" case from "push not allowed".
  118. // Opening a fetch connection can help us tell the difference, as any
  119. // useful repository is going to support fetch if it also would allow
  120. // push. So if fetch throws NoRemoteRepositoryException we know the
  121. // URI is wrong. Otherwise we can correctly state push isn't allowed
  122. // as the fetch connection opened successfully.
  123. //
  124. try {
  125. transport.openFetch().close();
  126. } catch (NotSupportedException e) {
  127. // Fall through.
  128. } catch (NoRemoteRepositoryException e) {
  129. // Fetch concluded the repository doesn't exist.
  130. //
  131. return e;
  132. } catch (TransportException e) {
  133. // Fall through.
  134. }
  135. return new TransportException(uri, JGitText.get().pushNotPermitted);
  136. }
  137. /**
  138. * Push one or more objects and update the remote repository.
  139. *
  140. * @param monitor
  141. * progress monitor to receive status updates.
  142. * @param refUpdates
  143. * update commands to be applied to the remote repository.
  144. * @throws TransportException
  145. * if any exception occurs.
  146. */
  147. protected void doPush(final ProgressMonitor monitor,
  148. final Map<String, RemoteRefUpdate> refUpdates)
  149. throws TransportException {
  150. try {
  151. writeCommands(refUpdates.values(), monitor);
  152. if (writePack)
  153. writePack(refUpdates, monitor);
  154. if (sentCommand) {
  155. if (capableReport)
  156. readStatusReport(refUpdates);
  157. if (capableSideBand) {
  158. // Ensure the data channel is at EOF, so we know we have
  159. // read all side-band data from all channels and have a
  160. // complete copy of the messages (if any) buffered from
  161. // the other data channels.
  162. //
  163. int b = in.read();
  164. if (0 <= b)
  165. throw new TransportException(uri, MessageFormat.format(JGitText.get().expectedEOFReceived, (char) b));
  166. }
  167. }
  168. } catch (TransportException e) {
  169. throw e;
  170. } catch (Exception e) {
  171. throw new TransportException(uri, e.getMessage(), e);
  172. } finally {
  173. close();
  174. }
  175. }
  176. private void writeCommands(final Collection<RemoteRefUpdate> refUpdates,
  177. final ProgressMonitor monitor) throws IOException {
  178. final String capabilities = enableCapabilities(monitor);
  179. for (final RemoteRefUpdate rru : refUpdates) {
  180. if (!capableDeleteRefs && rru.isDelete()) {
  181. rru.setStatus(Status.REJECTED_NODELETE);
  182. continue;
  183. }
  184. final StringBuilder sb = new StringBuilder();
  185. final Ref advertisedRef = getRef(rru.getRemoteName());
  186. final ObjectId oldId = (advertisedRef == null ? ObjectId.zeroId()
  187. : advertisedRef.getObjectId());
  188. sb.append(oldId.name());
  189. sb.append(' ');
  190. sb.append(rru.getNewObjectId().name());
  191. sb.append(' ');
  192. sb.append(rru.getRemoteName());
  193. if (!sentCommand) {
  194. sentCommand = true;
  195. sb.append(capabilities);
  196. }
  197. pckOut.writeString(sb.toString());
  198. rru.setStatus(Status.AWAITING_REPORT);
  199. if (!rru.isDelete())
  200. writePack = true;
  201. }
  202. if (monitor.isCancelled())
  203. throw new TransportException(uri, JGitText.get().pushCancelled);
  204. pckOut.end();
  205. outNeedsEnd = false;
  206. }
  207. private String enableCapabilities(final ProgressMonitor monitor) {
  208. final StringBuilder line = new StringBuilder();
  209. capableReport = wantCapability(line, CAPABILITY_REPORT_STATUS);
  210. capableDeleteRefs = wantCapability(line, CAPABILITY_DELETE_REFS);
  211. capableOfsDelta = wantCapability(line, CAPABILITY_OFS_DELTA);
  212. capableSideBand = wantCapability(line, CAPABILITY_SIDE_BAND_64K);
  213. if (capableSideBand) {
  214. in = new SideBandInputStream(in, monitor, getMessageWriter());
  215. pckIn = new PacketLineIn(in);
  216. }
  217. if (line.length() > 0)
  218. line.setCharAt(0, '\0');
  219. return line.toString();
  220. }
  221. private void writePack(final Map<String, RemoteRefUpdate> refUpdates,
  222. final ProgressMonitor monitor) throws IOException {
  223. Set<ObjectId> remoteObjects = new HashSet<ObjectId>();
  224. Set<ObjectId> newObjects = new HashSet<ObjectId>();
  225. final PackWriter writer = new PackWriter(transport.getPackConfig(),
  226. local.newObjectReader());
  227. try {
  228. for (final Ref r : getRefs())
  229. remoteObjects.add(r.getObjectId());
  230. remoteObjects.addAll(additionalHaves);
  231. for (final RemoteRefUpdate r : refUpdates.values()) {
  232. if (!ObjectId.zeroId().equals(r.getNewObjectId()))
  233. newObjects.add(r.getNewObjectId());
  234. }
  235. writer.setUseCachedPacks(true);
  236. writer.setThin(thinPack);
  237. writer.setReuseValidatingObjects(false);
  238. writer.setDeltaBaseAsOffset(capableOfsDelta);
  239. writer.preparePack(monitor, newObjects, remoteObjects);
  240. writer.writePack(monitor, monitor, out);
  241. } finally {
  242. writer.release();
  243. }
  244. packTransferTime = writer.getStatistics().getTimeWriting();
  245. }
  246. private void readStatusReport(final Map<String, RemoteRefUpdate> refUpdates)
  247. throws IOException {
  248. final String unpackLine = readStringLongTimeout();
  249. if (!unpackLine.startsWith("unpack "))
  250. throw new PackProtocolException(uri, MessageFormat.format(JGitText.get().unexpectedReportLine, unpackLine));
  251. final String unpackStatus = unpackLine.substring("unpack ".length());
  252. if (!unpackStatus.equals("ok"))
  253. throw new TransportException(uri, MessageFormat.format(
  254. JGitText.get().errorOccurredDuringUnpackingOnTheRemoteEnd, unpackStatus));
  255. String refLine;
  256. while ((refLine = pckIn.readString()) != PacketLineIn.END) {
  257. boolean ok = false;
  258. int refNameEnd = -1;
  259. if (refLine.startsWith("ok ")) {
  260. ok = true;
  261. refNameEnd = refLine.length();
  262. } else if (refLine.startsWith("ng ")) {
  263. ok = false;
  264. refNameEnd = refLine.indexOf(" ", 3);
  265. }
  266. if (refNameEnd == -1)
  267. throw new PackProtocolException(MessageFormat.format(JGitText.get().unexpectedReportLine2
  268. , uri, refLine));
  269. final String refName = refLine.substring(3, refNameEnd);
  270. final String message = (ok ? null : refLine
  271. .substring(refNameEnd + 1));
  272. final RemoteRefUpdate rru = refUpdates.get(refName);
  273. if (rru == null)
  274. throw new PackProtocolException(MessageFormat.format(JGitText.get().unexpectedRefReport, uri, refName));
  275. if (ok) {
  276. rru.setStatus(Status.OK);
  277. } else {
  278. rru.setStatus(Status.REJECTED_OTHER_REASON);
  279. rru.setMessage(message);
  280. }
  281. }
  282. for (final RemoteRefUpdate rru : refUpdates.values()) {
  283. if (rru.getStatus() == Status.AWAITING_REPORT)
  284. throw new PackProtocolException(MessageFormat.format(
  285. JGitText.get().expectedReportForRefNotReceived , uri, rru.getRemoteName()));
  286. }
  287. }
  288. private String readStringLongTimeout() throws IOException {
  289. if (timeoutIn == null)
  290. return pckIn.readString();
  291. // The remote side may need a lot of time to choke down the pack
  292. // we just sent them. There may be many deltas that need to be
  293. // resolved by the remote. Its hard to say how long the other
  294. // end is going to be silent. Taking 10x the configured timeout
  295. // or the time spent transferring the pack, whichever is larger,
  296. // gives the other side some reasonable window to process the data,
  297. // but this is just a wild guess.
  298. //
  299. final int oldTimeout = timeoutIn.getTimeout();
  300. final int sendTime = (int) Math.min(packTransferTime, 28800000L);
  301. try {
  302. timeoutIn.setTimeout(10 * Math.max(sendTime, oldTimeout));
  303. return pckIn.readString();
  304. } finally {
  305. timeoutIn.setTimeout(oldTimeout);
  306. }
  307. }
  308. }