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

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