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.

TransportGitSsh.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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.IOException;
  48. import java.io.InputStream;
  49. import java.io.OutputStream;
  50. import java.io.PipedInputStream;
  51. import java.io.PipedOutputStream;
  52. import java.text.MessageFormat;
  53. import org.eclipse.jgit.JGitText;
  54. import org.eclipse.jgit.errors.NoRemoteRepositoryException;
  55. import org.eclipse.jgit.errors.TransportException;
  56. import org.eclipse.jgit.lib.Repository;
  57. import org.eclipse.jgit.util.QuotedString;
  58. import org.eclipse.jgit.util.io.MessageWriter;
  59. import org.eclipse.jgit.util.io.StreamCopyThread;
  60. import com.jcraft.jsch.ChannelExec;
  61. import com.jcraft.jsch.JSchException;
  62. /**
  63. * Transport through an SSH tunnel.
  64. * <p>
  65. * The SSH transport requires the remote side to have Git installed, as the
  66. * transport logs into the remote system and executes a Git helper program on
  67. * the remote side to read (or write) the remote repository's files.
  68. * <p>
  69. * This transport does not support direct SCP style of copying files, as it
  70. * assumes there are Git specific smarts on the remote side to perform object
  71. * enumeration, save file modification and hook execution.
  72. */
  73. public class TransportGitSsh extends SshTransport implements PackTransport {
  74. static boolean canHandle(final URIish uri) {
  75. if (!uri.isRemote())
  76. return false;
  77. final String scheme = uri.getScheme();
  78. if ("ssh".equals(scheme))
  79. return true;
  80. if ("ssh+git".equals(scheme))
  81. return true;
  82. if ("git+ssh".equals(scheme))
  83. return true;
  84. if (scheme == null && uri.getHost() != null && uri.getPath() != null)
  85. return true;
  86. return false;
  87. }
  88. TransportGitSsh(final Repository local, final URIish uri) {
  89. super(local, uri);
  90. }
  91. @Override
  92. public FetchConnection openFetch() throws TransportException {
  93. return new SshFetchConnection();
  94. }
  95. @Override
  96. public PushConnection openPush() throws TransportException {
  97. return new SshPushConnection();
  98. }
  99. private static void sqMinimal(final StringBuilder cmd, final String val) {
  100. if (val.matches("^[a-zA-Z0-9._/-]*$")) {
  101. // If the string matches only generally safe characters
  102. // that the shell is not going to evaluate specially we
  103. // should leave the string unquoted. Not all systems
  104. // actually run a shell and over-quoting confuses them
  105. // when it comes to the command name.
  106. //
  107. cmd.append(val);
  108. } else {
  109. sq(cmd, val);
  110. }
  111. }
  112. private static void sqAlways(final StringBuilder cmd, final String val) {
  113. sq(cmd, val);
  114. }
  115. private static void sq(final StringBuilder cmd, final String val) {
  116. if (val.length() > 0)
  117. cmd.append(QuotedString.BOURNE.quote(val));
  118. }
  119. private String commandFor(final String exe) {
  120. String path = uri.getPath();
  121. if (uri.getScheme() != null && uri.getPath().startsWith("/~"))
  122. path = (uri.getPath().substring(1));
  123. final StringBuilder cmd = new StringBuilder();
  124. final int gitspace = exe.indexOf("git ");
  125. if (gitspace >= 0) {
  126. sqMinimal(cmd, exe.substring(0, gitspace + 3));
  127. cmd.append(' ');
  128. sqMinimal(cmd, exe.substring(gitspace + 4));
  129. } else
  130. sqMinimal(cmd, exe);
  131. cmd.append(' ');
  132. sqAlways(cmd, path);
  133. return cmd.toString();
  134. }
  135. ChannelExec exec(final String exe) throws TransportException {
  136. initSession();
  137. try {
  138. final ChannelExec channel = (ChannelExec) sock.openChannel("exec");
  139. channel.setCommand(commandFor(exe));
  140. return channel;
  141. } catch (JSchException je) {
  142. throw new TransportException(uri, je.getMessage(), je);
  143. }
  144. }
  145. private void connect(ChannelExec channel) throws TransportException {
  146. try {
  147. channel.connect(getTimeout() > 0 ? getTimeout() * 1000 : 0);
  148. if (!channel.isConnected())
  149. throw new TransportException(uri, "connection failed");
  150. } catch (JSchException e) {
  151. throw new TransportException(uri, e.getMessage(), e);
  152. }
  153. }
  154. void checkExecFailure(int status, String exe, String why)
  155. throws TransportException {
  156. if (status == 127) {
  157. IOException cause = null;
  158. if (why != null && why.length() > 0)
  159. cause = new IOException(why);
  160. throw new TransportException(uri, MessageFormat.format(
  161. JGitText.get().cannotExecute, commandFor(exe)), cause);
  162. }
  163. }
  164. NoRemoteRepositoryException cleanNotFound(NoRemoteRepositoryException nf,
  165. String why) {
  166. if (why == null || why.length() == 0)
  167. return nf;
  168. String path = uri.getPath();
  169. if (uri.getScheme() != null && uri.getPath().startsWith("/~"))
  170. path = uri.getPath().substring(1);
  171. final StringBuilder pfx = new StringBuilder();
  172. pfx.append("fatal: ");
  173. sqAlways(pfx, path);
  174. pfx.append(": ");
  175. if (why.startsWith(pfx.toString()))
  176. why = why.substring(pfx.length());
  177. return new NoRemoteRepositoryException(uri, why);
  178. }
  179. // JSch won't let us interrupt writes when we use our InterruptTimer to
  180. // break out of a long-running write operation. To work around that we
  181. // spawn a background thread to shuttle data through a pipe, as we can
  182. // issue an interrupted write out of that. Its slower, so we only use
  183. // this route if there is a timeout.
  184. //
  185. private OutputStream outputStream(ChannelExec channel) throws IOException {
  186. final OutputStream out = channel.getOutputStream();
  187. if (getTimeout() <= 0)
  188. return out;
  189. final PipedInputStream pipeIn = new PipedInputStream();
  190. final StreamCopyThread copyThread = new StreamCopyThread(pipeIn, out);
  191. final PipedOutputStream pipeOut = new PipedOutputStream(pipeIn) {
  192. @Override
  193. public void flush() throws IOException {
  194. super.flush();
  195. copyThread.flush();
  196. }
  197. @Override
  198. public void close() throws IOException {
  199. super.close();
  200. try {
  201. copyThread.join(getTimeout() * 1000);
  202. } catch (InterruptedException e) {
  203. // Just wake early, the thread will terminate anyway.
  204. }
  205. }
  206. };
  207. copyThread.start();
  208. return pipeOut;
  209. }
  210. class SshFetchConnection extends BasePackFetchConnection {
  211. private ChannelExec channel;
  212. private StreamCopyThread errorThread;
  213. private int exitStatus;
  214. SshFetchConnection() throws TransportException {
  215. super(TransportGitSsh.this);
  216. try {
  217. final MessageWriter msg = new MessageWriter();
  218. setMessageWriter(msg);
  219. channel = exec(getOptionUploadPack());
  220. final InputStream upErr = channel.getErrStream();
  221. errorThread = new StreamCopyThread(upErr, msg.getRawStream());
  222. errorThread.start();
  223. init(channel.getInputStream(), outputStream(channel));
  224. connect(channel);
  225. } catch (TransportException err) {
  226. close();
  227. throw err;
  228. } catch (IOException err) {
  229. close();
  230. throw new TransportException(uri,
  231. JGitText.get().remoteHungUpUnexpectedly, err);
  232. }
  233. try {
  234. readAdvertisedRefs();
  235. } catch (NoRemoteRepositoryException notFound) {
  236. final String msgs = getMessages();
  237. checkExecFailure(exitStatus, getOptionUploadPack(), msgs);
  238. throw cleanNotFound(notFound, msgs);
  239. }
  240. }
  241. @Override
  242. public void close() {
  243. endOut();
  244. if (errorThread != null) {
  245. try {
  246. errorThread.halt();
  247. } catch (InterruptedException e) {
  248. // Stop waiting and return anyway.
  249. } finally {
  250. errorThread = null;
  251. }
  252. }
  253. super.close();
  254. if (channel != null) {
  255. try {
  256. exitStatus = channel.getExitStatus();
  257. if (channel.isConnected())
  258. channel.disconnect();
  259. } finally {
  260. channel = null;
  261. }
  262. }
  263. }
  264. }
  265. class SshPushConnection extends BasePackPushConnection {
  266. private ChannelExec channel;
  267. private StreamCopyThread errorThread;
  268. private int exitStatus;
  269. SshPushConnection() throws TransportException {
  270. super(TransportGitSsh.this);
  271. try {
  272. final MessageWriter msg = new MessageWriter();
  273. setMessageWriter(msg);
  274. channel = exec(getOptionReceivePack());
  275. final InputStream rpErr = channel.getErrStream();
  276. errorThread = new StreamCopyThread(rpErr, msg.getRawStream());
  277. errorThread.start();
  278. init(channel.getInputStream(), outputStream(channel));
  279. connect(channel);
  280. } catch (TransportException err) {
  281. close();
  282. throw err;
  283. } catch (IOException err) {
  284. close();
  285. throw new TransportException(uri,
  286. JGitText.get().remoteHungUpUnexpectedly, err);
  287. }
  288. try {
  289. readAdvertisedRefs();
  290. } catch (NoRemoteRepositoryException notFound) {
  291. final String msgs = getMessages();
  292. checkExecFailure(exitStatus, getOptionReceivePack(), msgs);
  293. throw cleanNotFound(notFound, msgs);
  294. }
  295. }
  296. @Override
  297. public void close() {
  298. endOut();
  299. if (errorThread != null) {
  300. try {
  301. errorThread.halt();
  302. } catch (InterruptedException e) {
  303. // Stop waiting and return anyway.
  304. } finally {
  305. errorThread = null;
  306. }
  307. }
  308. super.close();
  309. if (channel != null) {
  310. try {
  311. exitStatus = channel.getExitStatus();
  312. if (channel.isConnected())
  313. channel.disconnect();
  314. } finally {
  315. channel = null;
  316. }
  317. }
  318. }
  319. }
  320. }