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.

JschSession.java 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. /*
  2. * Copyright (C) 2009, Constantine Plotnikov <constantine.plotnikov@gmail.com>
  3. * Copyright (C) 2008-2009, Google Inc.
  4. * Copyright (C) 2009, Google, Inc.
  5. * Copyright (C) 2009, JetBrains s.r.o.
  6. * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  7. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> and others
  8. *
  9. * This program and the accompanying materials are made available under the
  10. * terms of the Eclipse Distribution License v. 1.0 which is available at
  11. * https://www.eclipse.org/org/documents/edl-v10.php.
  12. *
  13. * SPDX-License-Identifier: BSD-3-Clause
  14. */
  15. //TODO(ms): move to org.eclipse.jgit.ssh.jsch in 6.0
  16. package org.eclipse.jgit.transport;
  17. import java.io.BufferedOutputStream;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.OutputStream;
  21. import java.util.ArrayList;
  22. import java.util.Collection;
  23. import java.util.List;
  24. import java.util.concurrent.Callable;
  25. import java.util.concurrent.TimeUnit;
  26. import org.eclipse.jgit.errors.TransportException;
  27. import org.eclipse.jgit.internal.transport.jsch.JSchText;
  28. import org.eclipse.jgit.util.io.IsolatedOutputStream;
  29. import com.jcraft.jsch.Channel;
  30. import com.jcraft.jsch.ChannelExec;
  31. import com.jcraft.jsch.ChannelSftp;
  32. import com.jcraft.jsch.JSchException;
  33. import com.jcraft.jsch.Session;
  34. import com.jcraft.jsch.SftpException;
  35. /**
  36. * Run remote commands using Jsch.
  37. * <p>
  38. * This class is the default session implementation using Jsch. Note that
  39. * {@link org.eclipse.jgit.transport.JschConfigSessionFactory} is used to create
  40. * the actual session passed to the constructor.
  41. */
  42. public class JschSession implements RemoteSession {
  43. final Session sock;
  44. final URIish uri;
  45. /**
  46. * Create a new session object by passing the real Jsch session and the URI
  47. * information.
  48. *
  49. * @param session
  50. * the real Jsch session created elsewhere.
  51. * @param uri
  52. * the URI information for the remote connection
  53. */
  54. public JschSession(Session session, URIish uri) {
  55. sock = session;
  56. this.uri = uri;
  57. }
  58. /** {@inheritDoc} */
  59. @Override
  60. public Process exec(String command, int timeout) throws IOException {
  61. return new JschProcess(command, timeout);
  62. }
  63. /** {@inheritDoc} */
  64. @Override
  65. public void disconnect() {
  66. if (sock.isConnected())
  67. sock.disconnect();
  68. }
  69. /**
  70. * A kludge to allow {@link org.eclipse.jgit.transport.TransportSftp} to get
  71. * an Sftp channel from Jsch. Ideally, this method would be generic, which
  72. * would require implementing generic Sftp channel operations in the
  73. * RemoteSession class.
  74. *
  75. * @return a channel suitable for Sftp operations.
  76. * @throws com.jcraft.jsch.JSchException
  77. * on problems getting the channel.
  78. * @deprecated since 5.2; use {@link #getFtpChannel()} instead
  79. */
  80. @Deprecated
  81. public Channel getSftpChannel() throws JSchException {
  82. return sock.openChannel("sftp"); //$NON-NLS-1$
  83. }
  84. /**
  85. * {@inheritDoc}
  86. *
  87. * @since 5.2
  88. */
  89. @Override
  90. public FtpChannel getFtpChannel() {
  91. return new JschFtpChannel();
  92. }
  93. /**
  94. * Implementation of Process for running a single command using Jsch.
  95. * <p>
  96. * Uses the Jsch session to do actual command execution and manage the
  97. * execution.
  98. */
  99. private class JschProcess extends Process {
  100. private ChannelExec channel;
  101. final int timeout;
  102. private InputStream inputStream;
  103. private OutputStream outputStream;
  104. private InputStream errStream;
  105. /**
  106. * Opens a channel on the session ("sock") for executing the given
  107. * command, opens streams, and starts command execution.
  108. *
  109. * @param commandName
  110. * the command to execute
  111. * @param tms
  112. * the timeout value, in seconds, for the command.
  113. * @throws TransportException
  114. * on problems opening a channel or connecting to the remote
  115. * host
  116. * @throws IOException
  117. * on problems opening streams
  118. */
  119. JschProcess(String commandName, int tms)
  120. throws TransportException, IOException {
  121. timeout = tms;
  122. try {
  123. channel = (ChannelExec) sock.openChannel("exec"); //$NON-NLS-1$
  124. channel.setCommand(commandName);
  125. setupStreams();
  126. channel.connect(timeout > 0 ? timeout * 1000 : 0);
  127. if (!channel.isConnected()) {
  128. closeOutputStream();
  129. throw new TransportException(uri,
  130. JSchText.get().connectionFailed);
  131. }
  132. } catch (JSchException e) {
  133. closeOutputStream();
  134. throw new TransportException(uri, e.getMessage(), e);
  135. }
  136. }
  137. private void closeOutputStream() {
  138. if (outputStream != null) {
  139. try {
  140. outputStream.close();
  141. } catch (IOException ioe) {
  142. // ignore
  143. }
  144. }
  145. }
  146. private void setupStreams() throws IOException {
  147. inputStream = channel.getInputStream();
  148. // JSch won't let us interrupt writes when we use our InterruptTimer
  149. // to break out of a long-running write operation. To work around
  150. // that we spawn a background thread to shuttle data through a pipe,
  151. // as we can issue an interrupted write out of that. Its slower, so
  152. // we only use this route if there is a timeout.
  153. OutputStream out = channel.getOutputStream();
  154. if (timeout <= 0) {
  155. outputStream = out;
  156. } else {
  157. IsolatedOutputStream i = new IsolatedOutputStream(out);
  158. outputStream = new BufferedOutputStream(i, 16 * 1024);
  159. }
  160. errStream = channel.getErrStream();
  161. }
  162. @Override
  163. public InputStream getInputStream() {
  164. return inputStream;
  165. }
  166. @Override
  167. public OutputStream getOutputStream() {
  168. return outputStream;
  169. }
  170. @Override
  171. public InputStream getErrorStream() {
  172. return errStream;
  173. }
  174. @Override
  175. public int exitValue() {
  176. if (isRunning())
  177. throw new IllegalThreadStateException();
  178. return channel.getExitStatus();
  179. }
  180. private boolean isRunning() {
  181. return channel.getExitStatus() < 0 && channel.isConnected();
  182. }
  183. @Override
  184. public void destroy() {
  185. if (channel.isConnected())
  186. channel.disconnect();
  187. closeOutputStream();
  188. }
  189. @Override
  190. public int waitFor() throws InterruptedException {
  191. while (isRunning())
  192. Thread.sleep(100);
  193. return exitValue();
  194. }
  195. }
  196. private class JschFtpChannel implements FtpChannel {
  197. private ChannelSftp ftp;
  198. @Override
  199. public void connect(int timeout, TimeUnit unit) throws IOException {
  200. try {
  201. ftp = (ChannelSftp) sock.openChannel("sftp"); //$NON-NLS-1$
  202. ftp.connect((int) unit.toMillis(timeout));
  203. } catch (JSchException e) {
  204. ftp = null;
  205. throw new IOException(e.getLocalizedMessage(), e);
  206. }
  207. }
  208. @Override
  209. public void disconnect() {
  210. ftp.disconnect();
  211. ftp = null;
  212. }
  213. private <T> T map(Callable<T> op) throws IOException {
  214. try {
  215. return op.call();
  216. } catch (Exception e) {
  217. if (e instanceof SftpException) {
  218. throw new FtpChannel.FtpException(e.getLocalizedMessage(),
  219. ((SftpException) e).id, e);
  220. }
  221. throw new IOException(e.getLocalizedMessage(), e);
  222. }
  223. }
  224. @Override
  225. public boolean isConnected() {
  226. return ftp != null && sock.isConnected();
  227. }
  228. @Override
  229. public void cd(String path) throws IOException {
  230. map(() -> {
  231. ftp.cd(path);
  232. return null;
  233. });
  234. }
  235. @Override
  236. public String pwd() throws IOException {
  237. return map(() -> ftp.pwd());
  238. }
  239. @Override
  240. public Collection<DirEntry> ls(String path) throws IOException {
  241. return map(() -> {
  242. List<DirEntry> result = new ArrayList<>();
  243. for (Object e : ftp.ls(path)) {
  244. ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) e;
  245. result.add(new DirEntry() {
  246. @Override
  247. public String getFilename() {
  248. return entry.getFilename();
  249. }
  250. @Override
  251. public long getModifiedTime() {
  252. return entry.getAttrs().getMTime();
  253. }
  254. @Override
  255. public boolean isDirectory() {
  256. return entry.getAttrs().isDir();
  257. }
  258. });
  259. }
  260. return result;
  261. });
  262. }
  263. @Override
  264. public void rmdir(String path) throws IOException {
  265. map(() -> {
  266. ftp.rm(path);
  267. return null;
  268. });
  269. }
  270. @Override
  271. public void mkdir(String path) throws IOException {
  272. map(() -> {
  273. ftp.mkdir(path);
  274. return null;
  275. });
  276. }
  277. @Override
  278. public InputStream get(String path) throws IOException {
  279. return map(() -> ftp.get(path));
  280. }
  281. @Override
  282. public OutputStream put(String path) throws IOException {
  283. return map(() -> ftp.put(path));
  284. }
  285. @Override
  286. public void rm(String path) throws IOException {
  287. map(() -> {
  288. ftp.rm(path);
  289. return null;
  290. });
  291. }
  292. @Override
  293. public void rename(String from, String to) throws IOException {
  294. map(() -> {
  295. // Plain FTP rename will fail if "to" exists. Jsch knows about
  296. // the FTP extension "posix-rename@openssh.com", which will
  297. // remove "to" first if it exists.
  298. if (hasPosixRename()) {
  299. ftp.rename(from, to);
  300. } else if (!to.equals(from)) {
  301. // Try to remove "to" first. With git, we typically get this
  302. // when a lock file is moved over the file locked. Note that
  303. // the check for to being equal to from may still fail in
  304. // the general case, but for use with JGit's TransportSftp
  305. // it should be good enough.
  306. delete(to);
  307. ftp.rename(from, to);
  308. }
  309. return null;
  310. });
  311. }
  312. /**
  313. * Determine whether the server has the posix-rename extension.
  314. *
  315. * @return {@code true} if it is supported, {@code false} otherwise
  316. * @see <a href=
  317. * "https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL?annotate=HEAD">OpenSSH
  318. * deviations and extensions to the published SSH protocol</a>
  319. * @see <a href=
  320. * "http://pubs.opengroup.org/onlinepubs/9699919799/functions/rename.html">stdio.h:
  321. * rename()</a>
  322. */
  323. private boolean hasPosixRename() {
  324. return "1".equals(ftp.getExtension("posix-rename@openssh.com")); //$NON-NLS-1$//$NON-NLS-2$
  325. }
  326. }
  327. }