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

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