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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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.File;
  48. import java.io.IOException;
  49. import java.io.InputStream;
  50. import java.text.MessageFormat;
  51. import java.util.ArrayList;
  52. import java.util.Arrays;
  53. import java.util.Collections;
  54. import java.util.EnumSet;
  55. import java.util.LinkedHashSet;
  56. import java.util.List;
  57. import java.util.Set;
  58. import org.eclipse.jgit.errors.NoRemoteRepositoryException;
  59. import org.eclipse.jgit.errors.NotSupportedException;
  60. import org.eclipse.jgit.errors.TransportException;
  61. import org.eclipse.jgit.internal.JGitText;
  62. import org.eclipse.jgit.lib.Constants;
  63. import org.eclipse.jgit.lib.Repository;
  64. import org.eclipse.jgit.util.FS;
  65. import org.eclipse.jgit.util.QuotedString;
  66. import org.eclipse.jgit.util.SystemReader;
  67. import org.eclipse.jgit.util.io.MessageWriter;
  68. import org.eclipse.jgit.util.io.StreamCopyThread;
  69. /**
  70. * Transport through an SSH tunnel.
  71. * <p>
  72. * The SSH transport requires the remote side to have Git installed, as the
  73. * transport logs into the remote system and executes a Git helper program on
  74. * the remote side to read (or write) the remote repository's files.
  75. * <p>
  76. * This transport does not support direct SCP style of copying files, as it
  77. * assumes there are Git specific smarts on the remote side to perform object
  78. * enumeration, save file modification and hook execution.
  79. */
  80. public class TransportGitSsh extends SshTransport implements PackTransport {
  81. static final TransportProtocol PROTO_SSH = new TransportProtocol() {
  82. private final String[] schemeNames = { "ssh", "ssh+git", "git+ssh" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  83. private final Set<String> schemeSet = Collections
  84. .unmodifiableSet(new LinkedHashSet<String>(Arrays
  85. .asList(schemeNames)));
  86. public String getName() {
  87. return JGitText.get().transportProtoSSH;
  88. }
  89. public Set<String> getSchemes() {
  90. return schemeSet;
  91. }
  92. public Set<URIishField> getRequiredFields() {
  93. return Collections.unmodifiableSet(EnumSet.of(URIishField.HOST,
  94. URIishField.PATH));
  95. }
  96. public Set<URIishField> getOptionalFields() {
  97. return Collections.unmodifiableSet(EnumSet.of(URIishField.USER,
  98. URIishField.PASS, URIishField.PORT));
  99. }
  100. public int getDefaultPort() {
  101. return 22;
  102. }
  103. @Override
  104. public boolean canHandle(URIish uri, Repository local, String remoteName) {
  105. if (uri.getScheme() == null) {
  106. // scp-style URI "host:path" does not have scheme.
  107. return uri.getHost() != null
  108. && uri.getPath() != null
  109. && uri.getHost().length() != 0
  110. && uri.getPath().length() != 0;
  111. }
  112. return super.canHandle(uri, local, remoteName);
  113. }
  114. public Transport open(URIish uri, Repository local, String remoteName)
  115. throws NotSupportedException {
  116. return new TransportGitSsh(local, uri);
  117. }
  118. @Override
  119. public Transport open(URIish uri) throws NotSupportedException, TransportException {
  120. return new TransportGitSsh(uri);
  121. }
  122. };
  123. TransportGitSsh(final Repository local, final URIish uri) {
  124. super(local, uri);
  125. initSshSessionFactory();
  126. }
  127. TransportGitSsh(final URIish uri) {
  128. super(uri);
  129. initSshSessionFactory();
  130. }
  131. private void initSshSessionFactory() {
  132. if (useExtSession()) {
  133. setSshSessionFactory(new SshSessionFactory() {
  134. @Override
  135. public RemoteSession getSession(URIish uri2,
  136. CredentialsProvider credentialsProvider, FS fs, int tms)
  137. throws TransportException {
  138. return new ExtSession();
  139. }
  140. });
  141. }
  142. }
  143. @Override
  144. public FetchConnection openFetch() throws TransportException {
  145. return new SshFetchConnection();
  146. }
  147. @Override
  148. public PushConnection openPush() throws TransportException {
  149. return new SshPushConnection();
  150. }
  151. String commandFor(final String exe) {
  152. String path = uri.getPath();
  153. if (uri.getScheme() != null && uri.getPath().startsWith("/~")) //$NON-NLS-1$
  154. path = (uri.getPath().substring(1));
  155. final StringBuilder cmd = new StringBuilder();
  156. cmd.append(exe);
  157. cmd.append(' ');
  158. cmd.append(QuotedString.BOURNE.quote(path));
  159. return cmd.toString();
  160. }
  161. void checkExecFailure(int status, String exe, String why)
  162. throws TransportException {
  163. if (status == 127) {
  164. IOException cause = null;
  165. if (why != null && why.length() > 0)
  166. cause = new IOException(why);
  167. throw new TransportException(uri, MessageFormat.format(
  168. JGitText.get().cannotExecute, commandFor(exe)), cause);
  169. }
  170. }
  171. NoRemoteRepositoryException cleanNotFound(NoRemoteRepositoryException nf,
  172. String why) {
  173. if (why == null || why.length() == 0)
  174. return nf;
  175. String path = uri.getPath();
  176. if (uri.getScheme() != null && uri.getPath().startsWith("/~")) //$NON-NLS-1$
  177. path = uri.getPath().substring(1);
  178. final StringBuilder pfx = new StringBuilder();
  179. pfx.append("fatal: "); //$NON-NLS-1$
  180. pfx.append(QuotedString.BOURNE.quote(path));
  181. pfx.append(": "); //$NON-NLS-1$
  182. if (why.startsWith(pfx.toString()))
  183. why = why.substring(pfx.length());
  184. return new NoRemoteRepositoryException(uri, why);
  185. }
  186. private static boolean useExtSession() {
  187. return SystemReader.getInstance().getenv("GIT_SSH") != null; //$NON-NLS-1$
  188. }
  189. private class ExtSession implements RemoteSession {
  190. public Process exec(String command, int timeout)
  191. throws TransportException {
  192. String ssh = SystemReader.getInstance().getenv("GIT_SSH"); //$NON-NLS-1$
  193. boolean putty = ssh.toLowerCase().contains("plink"); //$NON-NLS-1$
  194. List<String> args = new ArrayList<String>();
  195. args.add(ssh);
  196. if (putty && !ssh.toLowerCase().contains("tortoiseplink")) //$NON-NLS-1$
  197. args.add("-batch"); //$NON-NLS-1$
  198. if (0 < getURI().getPort()) {
  199. args.add(putty ? "-P" : "-p"); //$NON-NLS-1$ //$NON-NLS-2$
  200. args.add(String.valueOf(getURI().getPort()));
  201. }
  202. if (getURI().getUser() != null)
  203. args.add(getURI().getUser() + "@" + getURI().getHost()); //$NON-NLS-1$
  204. else
  205. args.add(getURI().getHost());
  206. args.add(command);
  207. ProcessBuilder pb = new ProcessBuilder();
  208. pb.command(args);
  209. File directory = local.getDirectory();
  210. if (directory != null)
  211. pb.environment().put(Constants.GIT_DIR_KEY,
  212. directory.getPath());
  213. try {
  214. return pb.start();
  215. } catch (IOException err) {
  216. throw new TransportException(err.getMessage(), err);
  217. }
  218. }
  219. public void disconnect() {
  220. // Nothing to do
  221. }
  222. }
  223. class SshFetchConnection extends BasePackFetchConnection {
  224. private final Process process;
  225. private StreamCopyThread errorThread;
  226. SshFetchConnection() throws TransportException {
  227. super(TransportGitSsh.this);
  228. try {
  229. process = getSession().exec(commandFor(getOptionUploadPack()),
  230. getTimeout());
  231. final MessageWriter msg = new MessageWriter();
  232. setMessageWriter(msg);
  233. final InputStream upErr = process.getErrorStream();
  234. errorThread = new StreamCopyThread(upErr, msg.getRawStream());
  235. errorThread.start();
  236. init(process.getInputStream(), process.getOutputStream());
  237. } catch (TransportException err) {
  238. close();
  239. throw err;
  240. } catch (IOException err) {
  241. close();
  242. throw new TransportException(uri,
  243. JGitText.get().remoteHungUpUnexpectedly, err);
  244. }
  245. try {
  246. readAdvertisedRefs();
  247. } catch (NoRemoteRepositoryException notFound) {
  248. final String msgs = getMessages();
  249. checkExecFailure(process.exitValue(), getOptionUploadPack(),
  250. msgs);
  251. throw cleanNotFound(notFound, msgs);
  252. }
  253. }
  254. @Override
  255. public void close() {
  256. endOut();
  257. if (errorThread != null) {
  258. try {
  259. errorThread.halt();
  260. } catch (InterruptedException e) {
  261. // Stop waiting and return anyway.
  262. } finally {
  263. errorThread = null;
  264. }
  265. }
  266. super.close();
  267. if (process != null)
  268. process.destroy();
  269. }
  270. }
  271. class SshPushConnection extends BasePackPushConnection {
  272. private final Process process;
  273. private StreamCopyThread errorThread;
  274. SshPushConnection() throws TransportException {
  275. super(TransportGitSsh.this);
  276. try {
  277. process = getSession().exec(commandFor(getOptionReceivePack()),
  278. getTimeout());
  279. final MessageWriter msg = new MessageWriter();
  280. setMessageWriter(msg);
  281. final InputStream rpErr = process.getErrorStream();
  282. errorThread = new StreamCopyThread(rpErr, msg.getRawStream());
  283. errorThread.start();
  284. init(process.getInputStream(), process.getOutputStream());
  285. } catch (TransportException err) {
  286. close();
  287. throw err;
  288. } catch (IOException err) {
  289. close();
  290. throw new TransportException(uri,
  291. JGitText.get().remoteHungUpUnexpectedly, err);
  292. }
  293. try {
  294. readAdvertisedRefs();
  295. } catch (NoRemoteRepositoryException notFound) {
  296. final String msgs = getMessages();
  297. checkExecFailure(process.exitValue(), getOptionReceivePack(),
  298. msgs);
  299. throw cleanNotFound(notFound, msgs);
  300. }
  301. }
  302. @Override
  303. public void close() {
  304. endOut();
  305. if (errorThread != null) {
  306. try {
  307. errorThread.halt();
  308. } catch (InterruptedException e) {
  309. // Stop waiting and return anyway.
  310. } finally {
  311. errorThread = null;
  312. }
  313. }
  314. super.close();
  315. if (process != null)
  316. process.destroy();
  317. }
  318. }
  319. }