View Javadoc
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  
49  package org.eclipse.jgit.transport;
50  
51  import java.io.BufferedOutputStream;
52  import java.io.IOException;
53  import java.io.InputStream;
54  import java.io.OutputStream;
55  import java.util.ArrayList;
56  import java.util.Collection;
57  import java.util.List;
58  import java.util.concurrent.Callable;
59  import java.util.concurrent.TimeUnit;
60  
61  import org.eclipse.jgit.errors.TransportException;
62  import org.eclipse.jgit.internal.JGitText;
63  import org.eclipse.jgit.util.io.IsolatedOutputStream;
64  
65  import com.jcraft.jsch.Channel;
66  import com.jcraft.jsch.ChannelExec;
67  import com.jcraft.jsch.ChannelSftp;
68  import com.jcraft.jsch.JSchException;
69  import com.jcraft.jsch.Session;
70  import com.jcraft.jsch.SftpException;
71  
72  /**
73   * Run remote commands using Jsch.
74   * <p>
75   * This class is the default session implementation using Jsch. Note that
76   * {@link org.eclipse.jgit.transport.JschConfigSessionFactory} is used to create
77   * the actual session passed to the constructor.
78   */
79  public class JschSession implements RemoteSession {
80  	final Session sock;
81  	final URIish uri;
82  
83  	/**
84  	 * Create a new session object by passing the real Jsch session and the URI
85  	 * information.
86  	 *
87  	 * @param session
88  	 *            the real Jsch session created elsewhere.
89  	 * @param uri
90  	 *            the URI information for the remote connection
91  	 */
92  	public JschSession(Session session, URIish uri) {
93  		sock = session;
94  		this.uri = uri;
95  	}
96  
97  	/** {@inheritDoc} */
98  	@Override
99  	public Process exec(String command, int timeout) throws IOException {
100 		return new JschProcess(command, timeout);
101 	}
102 
103 	/** {@inheritDoc} */
104 	@Override
105 	public void disconnect() {
106 		if (sock.isConnected())
107 			sock.disconnect();
108 	}
109 
110 	/**
111 	 * A kludge to allow {@link org.eclipse.jgit.transport.TransportSftp} to get
112 	 * an Sftp channel from Jsch. Ideally, this method would be generic, which
113 	 * would require implementing generic Sftp channel operations in the
114 	 * RemoteSession class.
115 	 *
116 	 * @return a channel suitable for Sftp operations.
117 	 * @throws com.jcraft.jsch.JSchException
118 	 *             on problems getting the channel.
119 	 * @deprecated since 5.2; use {@link #getFtpChannel()} instead
120 	 */
121 	@Deprecated
122 	public Channel getSftpChannel() throws JSchException {
123 		return sock.openChannel("sftp"); //$NON-NLS-1$
124 	}
125 
126 	/**
127 	 * {@inheritDoc}
128 	 *
129 	 * @since 5.2
130 	 */
131 	@Override
132 	public FtpChannel getFtpChannel() {
133 		return new JschFtpChannel();
134 	}
135 
136 	/**
137 	 * Implementation of Process for running a single command using Jsch.
138 	 * <p>
139 	 * Uses the Jsch session to do actual command execution and manage the
140 	 * execution.
141 	 */
142 	private class JschProcess extends Process {
143 		private ChannelExec channel;
144 
145 		final int timeout;
146 
147 		private InputStream inputStream;
148 
149 		private OutputStream outputStream;
150 
151 		private InputStream errStream;
152 
153 		/**
154 		 * Opens a channel on the session ("sock") for executing the given
155 		 * command, opens streams, and starts command execution.
156 		 *
157 		 * @param commandName
158 		 *            the command to execute
159 		 * @param tms
160 		 *            the timeout value, in seconds, for the command.
161 		 * @throws TransportException
162 		 *             on problems opening a channel or connecting to the remote
163 		 *             host
164 		 * @throws IOException
165 		 *             on problems opening streams
166 		 */
167 		JschProcess(String commandName, int tms)
168 				throws TransportException, IOException {
169 			timeout = tms;
170 			try {
171 				channel = (ChannelExec) sock.openChannel("exec"); //$NON-NLS-1$
172 				channel.setCommand(commandName);
173 				setupStreams();
174 				channel.connect(timeout > 0 ? timeout * 1000 : 0);
175 				if (!channel.isConnected()) {
176 					closeOutputStream();
177 					throw new TransportException(uri,
178 							JGitText.get().connectionFailed);
179 				}
180 			} catch (JSchException e) {
181 				closeOutputStream();
182 				throw new TransportException(uri, e.getMessage(), e);
183 			}
184 		}
185 
186 		private void closeOutputStream() {
187 			if (outputStream != null) {
188 				try {
189 					outputStream.close();
190 				} catch (IOException ioe) {
191 					// ignore
192 				}
193 			}
194 		}
195 
196 		private void setupStreams() throws IOException {
197 			inputStream = channel.getInputStream();
198 
199 			// JSch won't let us interrupt writes when we use our InterruptTimer
200 			// to break out of a long-running write operation. To work around
201 			// that we spawn a background thread to shuttle data through a pipe,
202 			// as we can issue an interrupted write out of that. Its slower, so
203 			// we only use this route if there is a timeout.
204 			OutputStream out = channel.getOutputStream();
205 			if (timeout <= 0) {
206 				outputStream = out;
207 			} else {
208 				IsolatedOutputStream i = new IsolatedOutputStream(out);
209 				outputStream = new BufferedOutputStream(i, 16 * 1024);
210 			}
211 
212 			errStream = channel.getErrStream();
213 		}
214 
215 		@Override
216 		public InputStream getInputStream() {
217 			return inputStream;
218 		}
219 
220 		@Override
221 		public OutputStream getOutputStream() {
222 			return outputStream;
223 		}
224 
225 		@Override
226 		public InputStream getErrorStream() {
227 			return errStream;
228 		}
229 
230 		@Override
231 		public int exitValue() {
232 			if (isRunning())
233 				throw new IllegalStateException();
234 			return channel.getExitStatus();
235 		}
236 
237 		private boolean isRunning() {
238 			return channel.getExitStatus() < 0 && channel.isConnected();
239 		}
240 
241 		@Override
242 		public void destroy() {
243 			if (channel.isConnected())
244 				channel.disconnect();
245 			closeOutputStream();
246 		}
247 
248 		@Override
249 		public int waitFor() throws InterruptedException {
250 			while (isRunning())
251 				Thread.sleep(100);
252 			return exitValue();
253 		}
254 	}
255 
256 	private class JschFtpChannel implements FtpChannel {
257 
258 		private ChannelSftp ftp;
259 
260 		@Override
261 		public void connect(int timeout, TimeUnit unit) throws IOException {
262 			try {
263 				ftp = (ChannelSftp) sock.openChannel("sftp"); //$NON-NLS-1$
264 				ftp.connect((int) unit.toMillis(timeout));
265 			} catch (JSchException e) {
266 				ftp = null;
267 				throw new IOException(e.getLocalizedMessage(), e);
268 			}
269 		}
270 
271 		@Override
272 		public void disconnect() {
273 			ftp.disconnect();
274 			ftp = null;
275 		}
276 
277 		private <T> T map(Callable<T> op) throws IOException {
278 			try {
279 				return op.call();
280 			} catch (Exception e) {
281 				if (e instanceof SftpException) {
282 					throw new FtpChannel.FtpException(e.getLocalizedMessage(),
283 							((SftpException) e).id, e);
284 				}
285 				throw new IOException(e.getLocalizedMessage(), e);
286 			}
287 		}
288 
289 		@Override
290 		public boolean isConnected() {
291 			return ftp != null && sock.isConnected();
292 		}
293 
294 		@Override
295 		public void cd(String path) throws IOException {
296 			map(() -> {
297 				ftp.cd(path);
298 				return null;
299 			});
300 		}
301 
302 		@Override
303 		public String pwd() throws IOException {
304 			return map(() -> ftp.pwd());
305 		}
306 
307 		@Override
308 		public Collection<DirEntry> ls(String path) throws IOException {
309 			return map(() -> {
310 				List<DirEntry> result = new ArrayList<>();
311 				for (Object e : ftp.ls(path)) {
312 					ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) e;
313 					result.add(new DirEntry() {
314 
315 						@Override
316 						public String getFilename() {
317 							return entry.getFilename();
318 						}
319 
320 						@Override
321 						public long getModifiedTime() {
322 							return entry.getAttrs().getMTime();
323 						}
324 
325 						@Override
326 						public boolean isDirectory() {
327 							return entry.getAttrs().isDir();
328 						}
329 					});
330 				}
331 				return result;
332 			});
333 		}
334 
335 		@Override
336 		public void rmdir(String path) throws IOException {
337 			map(() -> {
338 				ftp.rm(path);
339 				return null;
340 			});
341 		}
342 
343 		@Override
344 		public void mkdir(String path) throws IOException {
345 			map(() -> {
346 				ftp.mkdir(path);
347 				return null;
348 			});
349 		}
350 
351 		@Override
352 		public InputStream get(String path) throws IOException {
353 			return map(() -> ftp.get(path));
354 		}
355 
356 		@Override
357 		public OutputStream put(String path) throws IOException {
358 			return map(() -> ftp.put(path));
359 		}
360 
361 		@Override
362 		public void rm(String path) throws IOException {
363 			map(() -> {
364 				ftp.rm(path);
365 				return null;
366 			});
367 		}
368 
369 		@Override
370 		public void rename(String from, String to) throws IOException {
371 			map(() -> {
372 				// Plain FTP rename will fail if "to" exists. Jsch knows about
373 				// the FTP extension "posix-rename@openssh.com", which will
374 				// remove "to" first if it exists.
375 				if (hasPosixRename()) {
376 					ftp.rename(from, to);
377 				} else if (!to.equals(from)) {
378 					// Try to remove "to" first. With git, we typically get this
379 					// when a lock file is moved over the file locked. Note that
380 					// the check for to being equal to from may still fail in
381 					// the general case, but for use with JGit's TransportSftp
382 					// it should be good enough.
383 					delete(to);
384 					ftp.rename(from, to);
385 				}
386 				return null;
387 			});
388 		}
389 
390 		/**
391 		 * Determine whether the server has the posix-rename extension.
392 		 *
393 		 * @return {@code true} if it is supported, {@code false} otherwise
394 		 * @see <a href=
395 		 *      "https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL?annotate=HEAD">OpenSSH
396 		 *      deviations and extensions to the published SSH protocol</a>
397 		 * @see <a href=
398 		 *      "http://pubs.opengroup.org/onlinepubs/9699919799/functions/rename.html">stdio.h:
399 		 *      rename()</a>
400 		 */
401 		private boolean hasPosixRename() {
402 			return "1".equals(ftp.getExtension("posix-rename@openssh.com")); //$NON-NLS-1$//$NON-NLS-2$
403 		}
404 	}
405 }