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.

BasePackConnection.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /*
  2. * Copyright (C) 2008-2010, Google Inc.
  3. * Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com>
  4. * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  5. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  6. * and other copyright owners as documented in the project's IP log.
  7. *
  8. * This program and the accompanying materials are made available
  9. * under the terms of the Eclipse Distribution License v1.0 which
  10. * accompanies this distribution, is reproduced below, and is
  11. * available at http://www.eclipse.org/org/documents/edl-v10.php
  12. *
  13. * All rights reserved.
  14. *
  15. * Redistribution and use in source and binary forms, with or
  16. * without modification, are permitted provided that the following
  17. * conditions are met:
  18. *
  19. * - Redistributions of source code must retain the above copyright
  20. * notice, this list of conditions and the following disclaimer.
  21. *
  22. * - Redistributions in binary form must reproduce the above
  23. * copyright notice, this list of conditions and the following
  24. * disclaimer in the documentation and/or other materials provided
  25. * with the distribution.
  26. *
  27. * - Neither the name of the Eclipse Foundation, Inc. nor the
  28. * names of its contributors may be used to endorse or promote
  29. * products derived from this software without specific prior
  30. * written permission.
  31. *
  32. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  33. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  34. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  35. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  36. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  37. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  38. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  39. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  40. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  41. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  42. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  43. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  44. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45. */
  46. package org.eclipse.jgit.transport;
  47. import java.io.EOFException;
  48. import java.io.IOException;
  49. import java.io.InputStream;
  50. import java.io.OutputStream;
  51. import java.text.MessageFormat;
  52. import java.util.HashSet;
  53. import java.util.LinkedHashMap;
  54. import java.util.Set;
  55. import org.eclipse.jgit.JGitText;
  56. import org.eclipse.jgit.errors.NoRemoteRepositoryException;
  57. import org.eclipse.jgit.errors.PackProtocolException;
  58. import org.eclipse.jgit.errors.RemoteRepositoryException;
  59. import org.eclipse.jgit.errors.TransportException;
  60. import org.eclipse.jgit.lib.ObjectId;
  61. import org.eclipse.jgit.lib.ObjectIdRef;
  62. import org.eclipse.jgit.lib.Ref;
  63. import org.eclipse.jgit.lib.Repository;
  64. import org.eclipse.jgit.util.io.InterruptTimer;
  65. import org.eclipse.jgit.util.io.TimeoutInputStream;
  66. import org.eclipse.jgit.util.io.TimeoutOutputStream;
  67. /**
  68. * Base helper class for pack-based operations implementations. Provides partial
  69. * implementation of pack-protocol - refs advertising and capabilities support,
  70. * and some other helper methods.
  71. *
  72. * @see BasePackFetchConnection
  73. * @see BasePackPushConnection
  74. */
  75. abstract class BasePackConnection extends BaseConnection {
  76. /** The repository this transport fetches into, or pushes out of. */
  77. protected final Repository local;
  78. /** Remote repository location. */
  79. protected final URIish uri;
  80. /** A transport connected to {@link #uri}. */
  81. protected final Transport transport;
  82. /** Low-level input stream, if a timeout was configured. */
  83. protected TimeoutInputStream timeoutIn;
  84. /** Low-level output stream, if a timeout was configured. */
  85. protected TimeoutOutputStream timeoutOut;
  86. /** Timer to manage {@link #timeoutIn} and {@link #timeoutOut}. */
  87. private InterruptTimer myTimer;
  88. /** Input stream reading from the remote. */
  89. protected InputStream in;
  90. /** Output stream sending to the remote. */
  91. protected OutputStream out;
  92. /** Packet line decoder around {@link #in}. */
  93. protected PacketLineIn pckIn;
  94. /** Packet line encoder around {@link #out}. */
  95. protected PacketLineOut pckOut;
  96. /** Send {@link PacketLineOut#end()} before closing {@link #out}? */
  97. protected boolean outNeedsEnd;
  98. /** True if this is a stateless RPC connection. */
  99. protected boolean statelessRPC;
  100. /** Capability tokens advertised by the remote side. */
  101. private final Set<String> remoteCapablities = new HashSet<String>();
  102. /** Extra objects the remote has, but which aren't offered as refs. */
  103. protected final Set<ObjectId> additionalHaves = new HashSet<ObjectId>();
  104. BasePackConnection(final PackTransport packTransport) {
  105. transport = (Transport) packTransport;
  106. local = transport.local;
  107. uri = transport.uri;
  108. }
  109. /**
  110. * Configure this connection with the directional pipes.
  111. *
  112. * @param myIn
  113. * input stream to receive data from the peer. Caller must ensure
  114. * the input is buffered, otherwise read performance may suffer.
  115. * @param myOut
  116. * output stream to transmit data to the peer. Caller must ensure
  117. * the output is buffered, otherwise write performance may
  118. * suffer.
  119. */
  120. protected final void init(InputStream myIn, OutputStream myOut) {
  121. final int timeout = transport.getTimeout();
  122. if (timeout > 0) {
  123. final Thread caller = Thread.currentThread();
  124. myTimer = new InterruptTimer(caller.getName() + "-Timer");
  125. timeoutIn = new TimeoutInputStream(myIn, myTimer);
  126. timeoutOut = new TimeoutOutputStream(myOut, myTimer);
  127. timeoutIn.setTimeout(timeout * 1000);
  128. timeoutOut.setTimeout(timeout * 1000);
  129. myIn = timeoutIn;
  130. myOut = timeoutOut;
  131. }
  132. in = myIn;
  133. out = myOut;
  134. pckIn = new PacketLineIn(in);
  135. pckOut = new PacketLineOut(out);
  136. outNeedsEnd = true;
  137. }
  138. /**
  139. * Reads the advertised references through the initialized stream.
  140. * <p>
  141. * Subclass implementations may call this method only after setting up the
  142. * input and output streams with {@link #init(InputStream, OutputStream)}.
  143. * <p>
  144. * If any errors occur, this connection is automatically closed by invoking
  145. * {@link #close()} and the exception is wrapped (if necessary) and thrown
  146. * as a {@link TransportException}.
  147. *
  148. * @throws TransportException
  149. * the reference list could not be scanned.
  150. */
  151. protected void readAdvertisedRefs() throws TransportException {
  152. try {
  153. readAdvertisedRefsImpl();
  154. } catch (TransportException err) {
  155. close();
  156. throw err;
  157. } catch (IOException err) {
  158. close();
  159. throw new TransportException(err.getMessage(), err);
  160. } catch (RuntimeException err) {
  161. close();
  162. throw new TransportException(err.getMessage(), err);
  163. }
  164. }
  165. private void readAdvertisedRefsImpl() throws IOException {
  166. final LinkedHashMap<String, Ref> avail = new LinkedHashMap<String, Ref>();
  167. for (;;) {
  168. String line;
  169. try {
  170. line = pckIn.readString();
  171. } catch (EOFException eof) {
  172. if (avail.isEmpty())
  173. throw noRepository();
  174. throw eof;
  175. }
  176. if (line == PacketLineIn.END)
  177. break;
  178. if (line.startsWith("ERR ")) {
  179. // This is a customized remote service error.
  180. // Users should be informed about it.
  181. throw new RemoteRepositoryException(uri, line.substring(4));
  182. }
  183. if (avail.isEmpty()) {
  184. final int nul = line.indexOf('\0');
  185. if (nul >= 0) {
  186. // The first line (if any) may contain "hidden"
  187. // capability values after a NUL byte.
  188. for (String c : line.substring(nul + 1).split(" "))
  189. remoteCapablities.add(c);
  190. line = line.substring(0, nul);
  191. }
  192. }
  193. String name = line.substring(41, line.length());
  194. if (avail.isEmpty() && name.equals("capabilities^{}")) {
  195. // special line from git-receive-pack to show
  196. // capabilities when there are no refs to advertise
  197. continue;
  198. }
  199. final ObjectId id = ObjectId.fromString(line.substring(0, 40));
  200. if (name.equals(".have")) {
  201. additionalHaves.add(id);
  202. } else if (name.endsWith("^{}")) {
  203. name = name.substring(0, name.length() - 3);
  204. final Ref prior = avail.get(name);
  205. if (prior == null)
  206. throw new PackProtocolException(uri, MessageFormat.format(
  207. JGitText.get().advertisementCameBefore, name, name));
  208. if (prior.getPeeledObjectId() != null)
  209. throw duplicateAdvertisement(name + "^{}");
  210. avail.put(name, new ObjectIdRef.PeeledTag(
  211. Ref.Storage.NETWORK, name, prior.getObjectId(), id));
  212. } else {
  213. final Ref prior = avail.put(name, new ObjectIdRef.PeeledNonTag(
  214. Ref.Storage.NETWORK, name, id));
  215. if (prior != null)
  216. throw duplicateAdvertisement(name);
  217. }
  218. }
  219. available(avail);
  220. }
  221. /**
  222. * Create an exception to indicate problems finding a remote repository. The
  223. * caller is expected to throw the returned exception.
  224. *
  225. * Subclasses may override this method to provide better diagnostics.
  226. *
  227. * @return a TransportException saying a repository cannot be found and
  228. * possibly why.
  229. */
  230. protected TransportException noRepository() {
  231. return new NoRemoteRepositoryException(uri, JGitText.get().notFound);
  232. }
  233. protected boolean isCapableOf(final String option) {
  234. return remoteCapablities.contains(option);
  235. }
  236. protected boolean wantCapability(final StringBuilder b, final String option) {
  237. if (!isCapableOf(option))
  238. return false;
  239. b.append(' ');
  240. b.append(option);
  241. return true;
  242. }
  243. private PackProtocolException duplicateAdvertisement(final String name) {
  244. return new PackProtocolException(uri, MessageFormat.format(JGitText.get().duplicateAdvertisementsOf, name));
  245. }
  246. @Override
  247. public void close() {
  248. if (out != null) {
  249. try {
  250. if (outNeedsEnd) {
  251. outNeedsEnd = false;
  252. pckOut.end();
  253. }
  254. out.close();
  255. } catch (IOException err) {
  256. // Ignore any close errors.
  257. } finally {
  258. out = null;
  259. pckOut = null;
  260. }
  261. }
  262. if (in != null) {
  263. try {
  264. in.close();
  265. } catch (IOException err) {
  266. // Ignore any close errors.
  267. } finally {
  268. in = null;
  269. pckIn = null;
  270. }
  271. }
  272. if (myTimer != null) {
  273. try {
  274. myTimer.terminate();
  275. } finally {
  276. myTimer = null;
  277. timeoutIn = null;
  278. timeoutOut = null;
  279. }
  280. }
  281. }
  282. /** Tell the peer we are disconnecting, if it cares to know. */
  283. protected void endOut() {
  284. if (outNeedsEnd && out != null) {
  285. try {
  286. outNeedsEnd = false;
  287. pckOut.end();
  288. } catch (IOException e) {
  289. try {
  290. out.close();
  291. } catch (IOException err) {
  292. // Ignore any close errors.
  293. } finally {
  294. out = null;
  295. pckOut = null;
  296. }
  297. }
  298. }
  299. }
  300. }