Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

TransportGitSsh.java 9.9KB

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