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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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 static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_AGENT;
  48. import java.io.EOFException;
  49. import java.io.IOException;
  50. import java.io.InputStream;
  51. import java.io.OutputStream;
  52. import java.text.MessageFormat;
  53. import java.util.HashSet;
  54. import java.util.LinkedHashMap;
  55. import java.util.Set;
  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.internal.JGitText;
  61. import org.eclipse.jgit.lib.ObjectId;
  62. import org.eclipse.jgit.lib.ObjectIdRef;
  63. import org.eclipse.jgit.lib.Ref;
  64. import org.eclipse.jgit.lib.Repository;
  65. import org.eclipse.jgit.util.io.InterruptTimer;
  66. import org.eclipse.jgit.util.io.TimeoutInputStream;
  67. import org.eclipse.jgit.util.io.TimeoutOutputStream;
  68. /**
  69. * Base helper class for pack-based operations implementations. Provides partial
  70. * implementation of pack-protocol - refs advertising and capabilities support,
  71. * and some other helper methods.
  72. *
  73. * @see BasePackFetchConnection
  74. * @see BasePackPushConnection
  75. */
  76. abstract class BasePackConnection extends BaseConnection {
  77. /** The repository this transport fetches into, or pushes out of. */
  78. protected final Repository local;
  79. /** Remote repository location. */
  80. protected final URIish uri;
  81. /** A transport connected to {@link #uri}. */
  82. protected final Transport transport;
  83. /** Low-level input stream, if a timeout was configured. */
  84. protected TimeoutInputStream timeoutIn;
  85. /** Low-level output stream, if a timeout was configured. */
  86. protected TimeoutOutputStream timeoutOut;
  87. /** Timer to manage {@link #timeoutIn} and {@link #timeoutOut}. */
  88. private InterruptTimer myTimer;
  89. /** Input stream reading from the remote. */
  90. protected InputStream in;
  91. /** Output stream sending to the remote. */
  92. protected OutputStream out;
  93. /** Packet line decoder around {@link #in}. */
  94. protected PacketLineIn pckIn;
  95. /** Packet line encoder around {@link #out}. */
  96. protected PacketLineOut pckOut;
  97. /** Send {@link PacketLineOut#end()} before closing {@link #out}? */
  98. protected boolean outNeedsEnd;
  99. /** True if this is a stateless RPC connection. */
  100. protected boolean statelessRPC;
  101. /** Capability tokens advertised by the remote side. */
  102. private final Set<String> remoteCapablities = new HashSet<String>();
  103. /** Extra objects the remote has, but which aren't offered as refs. */
  104. protected final Set<ObjectId> additionalHaves = new HashSet<ObjectId>();
  105. BasePackConnection(final PackTransport packTransport) {
  106. transport = (Transport) packTransport;
  107. local = transport.local;
  108. uri = transport.uri;
  109. }
  110. /**
  111. * Configure this connection with the directional pipes.
  112. *
  113. * @param myIn
  114. * input stream to receive data from the peer. Caller must ensure
  115. * the input is buffered, otherwise read performance may suffer.
  116. * @param myOut
  117. * output stream to transmit data to the peer. Caller must ensure
  118. * the output is buffered, otherwise write performance may
  119. * suffer.
  120. */
  121. protected final void init(InputStream myIn, OutputStream myOut) {
  122. final int timeout = transport.getTimeout();
  123. if (timeout > 0) {
  124. final Thread caller = Thread.currentThread();
  125. if (myTimer == null) {
  126. myTimer = new InterruptTimer(caller.getName() + "-Timer"); //$NON-NLS-1$
  127. }
  128. timeoutIn = new TimeoutInputStream(myIn, myTimer);
  129. timeoutOut = new TimeoutOutputStream(myOut, myTimer);
  130. timeoutIn.setTimeout(timeout * 1000);
  131. timeoutOut.setTimeout(timeout * 1000);
  132. myIn = timeoutIn;
  133. myOut = timeoutOut;
  134. }
  135. in = myIn;
  136. out = myOut;
  137. pckIn = new PacketLineIn(in);
  138. pckOut = new PacketLineOut(out);
  139. outNeedsEnd = true;
  140. }
  141. /**
  142. * Reads the advertised references through the initialized stream.
  143. * <p>
  144. * Subclass implementations may call this method only after setting up the
  145. * input and output streams with {@link #init(InputStream, OutputStream)}.
  146. * <p>
  147. * If any errors occur, this connection is automatically closed by invoking
  148. * {@link #close()} and the exception is wrapped (if necessary) and thrown
  149. * as a {@link TransportException}.
  150. *
  151. * @throws TransportException
  152. * the reference list could not be scanned.
  153. */
  154. protected void readAdvertisedRefs() throws TransportException {
  155. try {
  156. readAdvertisedRefsImpl();
  157. } catch (TransportException err) {
  158. close();
  159. throw err;
  160. } catch (IOException err) {
  161. close();
  162. throw new TransportException(err.getMessage(), err);
  163. } catch (RuntimeException err) {
  164. close();
  165. throw new TransportException(err.getMessage(), err);
  166. }
  167. }
  168. private void readAdvertisedRefsImpl() throws IOException {
  169. final LinkedHashMap<String, Ref> avail = new LinkedHashMap<String, Ref>();
  170. for (;;) {
  171. String line;
  172. try {
  173. line = pckIn.readString();
  174. } catch (EOFException eof) {
  175. if (avail.isEmpty())
  176. throw noRepository();
  177. throw eof;
  178. }
  179. if (line == PacketLineIn.END)
  180. break;
  181. if (line.startsWith("ERR ")) { //$NON-NLS-1$
  182. // This is a customized remote service error.
  183. // Users should be informed about it.
  184. throw new RemoteRepositoryException(uri, line.substring(4));
  185. }
  186. if (avail.isEmpty()) {
  187. final int nul = line.indexOf('\0');
  188. if (nul >= 0) {
  189. // The first line (if any) may contain "hidden"
  190. // capability values after a NUL byte.
  191. for (String c : line.substring(nul + 1).split(" ")) //$NON-NLS-1$
  192. remoteCapablities.add(c);
  193. line = line.substring(0, nul);
  194. }
  195. }
  196. String name = line.substring(41, line.length());
  197. if (avail.isEmpty() && name.equals("capabilities^{}")) { //$NON-NLS-1$
  198. // special line from git-receive-pack to show
  199. // capabilities when there are no refs to advertise
  200. continue;
  201. }
  202. final ObjectId id = ObjectId.fromString(line.substring(0, 40));
  203. if (name.equals(".have")) { //$NON-NLS-1$
  204. additionalHaves.add(id);
  205. } else if (name.endsWith("^{}")) { //$NON-NLS-1$
  206. name = name.substring(0, name.length() - 3);
  207. final Ref prior = avail.get(name);
  208. if (prior == null)
  209. throw new PackProtocolException(uri, MessageFormat.format(
  210. JGitText.get().advertisementCameBefore, name, name));
  211. if (prior.getPeeledObjectId() != null)
  212. throw duplicateAdvertisement(name + "^{}"); //$NON-NLS-1$
  213. avail.put(name, new ObjectIdRef.PeeledTag(
  214. Ref.Storage.NETWORK, name, prior.getObjectId(), id));
  215. } else {
  216. final Ref prior = avail.put(name, new ObjectIdRef.PeeledNonTag(
  217. Ref.Storage.NETWORK, name, id));
  218. if (prior != null)
  219. throw duplicateAdvertisement(name);
  220. }
  221. }
  222. available(avail);
  223. }
  224. /**
  225. * Create an exception to indicate problems finding a remote repository. The
  226. * caller is expected to throw the returned exception.
  227. *
  228. * Subclasses may override this method to provide better diagnostics.
  229. *
  230. * @return a TransportException saying a repository cannot be found and
  231. * possibly why.
  232. */
  233. protected TransportException noRepository() {
  234. return new NoRemoteRepositoryException(uri, JGitText.get().notFound);
  235. }
  236. protected boolean isCapableOf(final String option) {
  237. return remoteCapablities.contains(option);
  238. }
  239. protected boolean wantCapability(final StringBuilder b, final String option) {
  240. if (!isCapableOf(option))
  241. return false;
  242. b.append(' ');
  243. b.append(option);
  244. return true;
  245. }
  246. protected void addUserAgentCapability(StringBuilder b) {
  247. String a = UserAgent.get();
  248. if (a != null && UserAgent.hasAgent(remoteCapablities)) {
  249. b.append(' ').append(OPTION_AGENT).append('=').append(a);
  250. }
  251. }
  252. @Override
  253. public String getPeerUserAgent() {
  254. return UserAgent.getAgent(remoteCapablities, super.getPeerUserAgent());
  255. }
  256. private PackProtocolException duplicateAdvertisement(final String name) {
  257. return new PackProtocolException(uri, MessageFormat.format(JGitText.get().duplicateAdvertisementsOf, name));
  258. }
  259. @Override
  260. public void close() {
  261. if (out != null) {
  262. try {
  263. if (outNeedsEnd) {
  264. outNeedsEnd = false;
  265. pckOut.end();
  266. }
  267. out.close();
  268. } catch (IOException err) {
  269. // Ignore any close errors.
  270. } finally {
  271. out = null;
  272. pckOut = null;
  273. }
  274. }
  275. if (in != null) {
  276. try {
  277. in.close();
  278. } catch (IOException err) {
  279. // Ignore any close errors.
  280. } finally {
  281. in = null;
  282. pckIn = null;
  283. }
  284. }
  285. if (myTimer != null) {
  286. try {
  287. myTimer.terminate();
  288. } finally {
  289. myTimer = null;
  290. timeoutIn = null;
  291. timeoutOut = null;
  292. }
  293. }
  294. }
  295. /** Tell the peer we are disconnecting, if it cares to know. */
  296. protected void endOut() {
  297. if (outNeedsEnd && out != null) {
  298. try {
  299. outNeedsEnd = false;
  300. pckOut.end();
  301. } catch (IOException e) {
  302. try {
  303. out.close();
  304. } catch (IOException err) {
  305. // Ignore any close errors.
  306. } finally {
  307. out = null;
  308. pckOut = null;
  309. }
  310. }
  311. }
  312. }
  313. }