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