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.

JschSession.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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>
  8. * and other copyright owners as documented in the project's IP log.
  9. *
  10. * This program and the accompanying materials are made available
  11. * under the terms of the Eclipse Distribution License v1.0 which
  12. * accompanies this distribution, is reproduced below, and is
  13. * available at http://www.eclipse.org/org/documents/edl-v10.php
  14. *
  15. * All rights reserved.
  16. *
  17. * Redistribution and use in source and binary forms, with or
  18. * without modification, are permitted provided that the following
  19. * conditions are met:
  20. *
  21. * - Redistributions of source code must retain the above copyright
  22. * notice, this list of conditions and the following disclaimer.
  23. *
  24. * - Redistributions in binary form must reproduce the above
  25. * copyright notice, this list of conditions and the following
  26. * disclaimer in the documentation and/or other materials provided
  27. * with the distribution.
  28. *
  29. * - Neither the name of the Eclipse Foundation, Inc. nor the
  30. * names of its contributors may be used to endorse or promote
  31. * products derived from this software without specific prior
  32. * written permission.
  33. *
  34. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  35. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  36. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  37. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  38. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  39. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  41. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  42. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  43. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  44. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  45. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  46. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  47. */
  48. package org.eclipse.jgit.transport;
  49. import java.io.BufferedOutputStream;
  50. import java.io.IOException;
  51. import java.io.InputStream;
  52. import java.io.OutputStream;
  53. import java.util.ArrayList;
  54. import java.util.Collection;
  55. import java.util.List;
  56. import java.util.concurrent.Callable;
  57. import java.util.concurrent.TimeUnit;
  58. import org.eclipse.jgit.errors.TransportException;
  59. import org.eclipse.jgit.internal.JGitText;
  60. import org.eclipse.jgit.util.io.IsolatedOutputStream;
  61. import com.jcraft.jsch.Channel;
  62. import com.jcraft.jsch.ChannelExec;
  63. import com.jcraft.jsch.ChannelSftp;
  64. import com.jcraft.jsch.JSchException;
  65. import com.jcraft.jsch.Session;
  66. import com.jcraft.jsch.SftpException;
  67. /**
  68. * Run remote commands using Jsch.
  69. * <p>
  70. * This class is the default session implementation using Jsch. Note that
  71. * {@link org.eclipse.jgit.transport.JschConfigSessionFactory} is used to create
  72. * the actual session passed to the constructor.
  73. */
  74. public class JschSession implements RemoteSession {
  75. final Session sock;
  76. final URIish uri;
  77. /**
  78. * Create a new session object by passing the real Jsch session and the URI
  79. * information.
  80. *
  81. * @param session
  82. * the real Jsch session created elsewhere.
  83. * @param uri
  84. * the URI information for the remote connection
  85. */
  86. public JschSession(Session session, URIish uri) {
  87. sock = session;
  88. this.uri = uri;
  89. }
  90. /** {@inheritDoc} */
  91. @Override
  92. public Process exec(String command, int timeout) throws IOException {
  93. return new JschProcess(command, timeout);
  94. }
  95. /** {@inheritDoc} */
  96. @Override
  97. public void disconnect() {
  98. if (sock.isConnected())
  99. sock.disconnect();
  100. }
  101. /**
  102. * A kludge to allow {@link org.eclipse.jgit.transport.TransportSftp} to get
  103. * an Sftp channel from Jsch. Ideally, this method would be generic, which
  104. * would require implementing generic Sftp channel operations in the
  105. * RemoteSession class.
  106. *
  107. * @return a channel suitable for Sftp operations.
  108. * @throws com.jcraft.jsch.JSchException
  109. * on problems getting the channel.
  110. * @deprecated since 5.2; use {@link #getFtpChannel()} instead
  111. */
  112. @Deprecated
  113. public Channel getSftpChannel() throws JSchException {
  114. return sock.openChannel("sftp"); //$NON-NLS-1$
  115. }
  116. /**
  117. * {@inheritDoc}
  118. *
  119. * @since 5.2
  120. */
  121. @Override
  122. public FtpChannel getFtpChannel() {
  123. return new JschFtpChannel();
  124. }
  125. /**
  126. * Implementation of Process for running a single command using Jsch.
  127. * <p>
  128. * Uses the Jsch session to do actual command execution and manage the
  129. * execution.
  130. */
  131. private class JschProcess extends Process {
  132. private ChannelExec channel;
  133. final int timeout;
  134. private InputStream inputStream;
  135. private OutputStream outputStream;
  136. private InputStream errStream;
  137. /**
  138. * Opens a channel on the session ("sock") for executing the given
  139. * command, opens streams, and starts command execution.
  140. *
  141. * @param commandName
  142. * the command to execute
  143. * @param tms
  144. * the timeout value, in seconds, for the command.
  145. * @throws TransportException
  146. * on problems opening a channel or connecting to the remote
  147. * host
  148. * @throws IOException
  149. * on problems opening streams
  150. */
  151. JschProcess(String commandName, int tms)
  152. throws TransportException, IOException {
  153. timeout = tms;
  154. try {
  155. channel = (ChannelExec) sock.openChannel("exec"); //$NON-NLS-1$
  156. channel.setCommand(commandName);
  157. setupStreams();
  158. channel.connect(timeout > 0 ? timeout * 1000 : 0);
  159. if (!channel.isConnected()) {
  160. closeOutputStream();
  161. throw new TransportException(uri,
  162. JGitText.get().connectionFailed);
  163. }
  164. } catch (JSchException e) {
  165. closeOutputStream();
  166. throw new TransportException(uri, e.getMessage(), e);
  167. }
  168. }
  169. private void closeOutputStream() {
  170. if (outputStream != null) {
  171. try {
  172. outputStream.close();
  173. } catch (IOException ioe) {
  174. // ignore
  175. }
  176. }
  177. }
  178. private void setupStreams() throws IOException {
  179. inputStream = channel.getInputStream();
  180. // JSch won't let us interrupt writes when we use our InterruptTimer
  181. // to break out of a long-running write operation. To work around
  182. // that we spawn a background thread to shuttle data through a pipe,
  183. // as we can issue an interrupted write out of that. Its slower, so
  184. // we only use this route if there is a timeout.
  185. OutputStream out = channel.getOutputStream();
  186. if (timeout <= 0) {
  187. outputStream = out;
  188. } else {
  189. IsolatedOutputStream i = new IsolatedOutputStream(out);
  190. outputStream = new BufferedOutputStream(i, 16 * 1024);
  191. }
  192. errStream = channel.getErrStream();
  193. }
  194. @Override
  195. public InputStream getInputStream() {
  196. return inputStream;
  197. }
  198. @Override
  199. public OutputStream getOutputStream() {
  200. return outputStream;
  201. }
  202. @Override
  203. public InputStream getErrorStream() {
  204. return errStream;
  205. }
  206. @Override
  207. public int exitValue() {
  208. if (isRunning())
  209. throw new IllegalStateException();
  210. return channel.getExitStatus();
  211. }
  212. private boolean isRunning() {
  213. return channel.getExitStatus() < 0 && channel.isConnected();
  214. }
  215. @Override
  216. public void destroy() {
  217. if (channel.isConnected())
  218. channel.disconnect();
  219. closeOutputStream();
  220. }
  221. @Override
  222. public int waitFor() throws InterruptedException {
  223. while (isRunning())
  224. Thread.sleep(100);
  225. return exitValue();
  226. }
  227. }
  228. private class JschFtpChannel implements FtpChannel {
  229. private ChannelSftp ftp;
  230. @Override
  231. public void connect(int timeout, TimeUnit unit) throws IOException {
  232. try {
  233. ftp = (ChannelSftp) sock.openChannel("sftp"); //$NON-NLS-1$
  234. ftp.connect((int) unit.toMillis(timeout));
  235. } catch (JSchException e) {
  236. ftp = null;
  237. throw new IOException(e.getLocalizedMessage(), e);
  238. }
  239. }
  240. @Override
  241. public void disconnect() {
  242. ftp.disconnect();
  243. ftp = null;
  244. }
  245. private <T> T map(Callable<T> op) throws IOException {
  246. try {
  247. return op.call();
  248. } catch (Exception e) {
  249. if (e instanceof SftpException) {
  250. throw new FtpChannel.FtpException(e.getLocalizedMessage(),
  251. ((SftpException) e).id, e);
  252. }
  253. throw new IOException(e.getLocalizedMessage(), e);
  254. }
  255. }
  256. @Override
  257. public boolean isConnected() {
  258. return ftp != null && sock.isConnected();
  259. }
  260. @Override
  261. public void cd(String path) throws IOException {
  262. map(() -> {
  263. ftp.cd(path);
  264. return null;
  265. });
  266. }
  267. @Override
  268. public String pwd() throws IOException {
  269. return map(() -> ftp.pwd());
  270. }
  271. @Override
  272. public Collection<DirEntry> ls(String path) throws IOException {
  273. return map(() -> {
  274. List<DirEntry> result = new ArrayList<>();
  275. for (Object e : ftp.ls(path)) {
  276. ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) e;
  277. result.add(new DirEntry() {
  278. @Override
  279. public String getFilename() {
  280. return entry.getFilename();
  281. }
  282. @Override
  283. public long getModifiedTime() {
  284. return entry.getAttrs().getMTime();
  285. }
  286. @Override
  287. public boolean isDirectory() {
  288. return entry.getAttrs().isDir();
  289. }
  290. });
  291. }
  292. return result;
  293. });
  294. }
  295. @Override
  296. public void rmdir(String path) throws IOException {
  297. map(() -> {
  298. ftp.rm(path);
  299. return null;
  300. });
  301. }
  302. @Override
  303. public void mkdir(String path) throws IOException {
  304. map(() -> {
  305. ftp.mkdir(path);
  306. return null;
  307. });
  308. }
  309. @Override
  310. public InputStream get(String path) throws IOException {
  311. return map(() -> ftp.get(path));
  312. }
  313. @Override
  314. public OutputStream put(String path) throws IOException {
  315. return map(() -> ftp.put(path));
  316. }
  317. @Override
  318. public void rm(String path) throws IOException {
  319. map(() -> {
  320. ftp.rm(path);
  321. return null;
  322. });
  323. }
  324. @Override
  325. public void rename(String from, String to) throws IOException {
  326. map(() -> {
  327. // Plain FTP rename will fail if "to" exists. Jsch knows about
  328. // the FTP extension "posix-rename@openssh.com", which will
  329. // remove "to" first if it exists.
  330. if (hasPosixRename()) {
  331. ftp.rename(from, to);
  332. } else if (!to.equals(from)) {
  333. // Try to remove "to" first. With git, we typically get this
  334. // when a lock file is moved over the file locked. Note that
  335. // the check for to being equal to from may still fail in
  336. // the general case, but for use with JGit's TransportSftp
  337. // it should be good enough.
  338. delete(to);
  339. ftp.rename(from, to);
  340. }
  341. return null;
  342. });
  343. }
  344. /**
  345. * Determine whether the server has the posix-rename extension.
  346. *
  347. * @return {@code true} if it is supported, {@code false} otherwise
  348. * @see <a href=
  349. * "https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL?annotate=HEAD">OpenSSH
  350. * deviations and extensions to the published SSH protocol</a>
  351. * @see <a href=
  352. * "http://pubs.opengroup.org/onlinepubs/9699919799/functions/rename.html">stdio.h:
  353. * rename()</a>
  354. */
  355. private boolean hasPosixRename() {
  356. return "1".equals(ftp.getExtension("posix-rename@openssh.com")); //$NON-NLS-1$//$NON-NLS-2$
  357. }
  358. }
  359. }