View Javadoc
1   /*
2    * Copyright (C) 2018, Markus Duft <markus.duft@ssi-schaefer.com> and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  package org.eclipse.jgit.util;
11  
12  import java.io.IOException;
13  import java.text.MessageFormat;
14  
15  import org.eclipse.jgit.annotations.Nullable;
16  import org.eclipse.jgit.errors.CommandFailedException;
17  import org.eclipse.jgit.internal.JGitText;
18  import org.eclipse.jgit.transport.CredentialsProvider;
19  import org.eclipse.jgit.transport.RemoteSession;
20  import org.eclipse.jgit.transport.SshSessionFactory;
21  import org.eclipse.jgit.transport.URIish;
22  import org.eclipse.jgit.util.io.MessageWriter;
23  import org.eclipse.jgit.util.io.StreamCopyThread;
24  
25  /**
26   * Extra utilities to support usage of SSH.
27   *
28   * @since 5.0
29   */
30  public class SshSupport {
31  
32  	/**
33  	 * Utility to execute a remote SSH command and read the first line of
34  	 * output.
35  	 *
36  	 * @param sshUri
37  	 *            the SSH remote URI
38  	 * @param provider
39  	 *            the {@link CredentialsProvider} or <code>null</code>.
40  	 * @param fs
41  	 *            the {@link FS} implementation passed to
42  	 *            {@link SshSessionFactory}
43  	 * @param command
44  	 *            the remote command to execute.
45  	 * @param timeout
46  	 *            a timeout in seconds. The timeout may be exceeded in corner
47  	 *            cases.
48  	 * @return The entire output read from stdout.
49  	 * @throws IOException
50  	 * @throws CommandFailedException
51  	 *             if the ssh command execution failed, error message contains
52  	 *             the content of stderr.
53  	 */
54  	public static String runSshCommand(URIish sshUri,
55  			@Nullable CredentialsProvider provider, FS fs, String command,
56  			int timeout) throws IOException, CommandFailedException {
57  		RemoteSession session = null;
58  		Process process = null;
59  		StreamCopyThread errorThread = null;
60  		StreamCopyThread outThread = null;
61  		CommandFailedException failure = null;
62  		@SuppressWarnings("resource")
63  		MessageWriter stderr = new MessageWriter();
64  		String out;
65  		try (MessageWriterter.html#MessageWriter">MessageWriter stdout = new MessageWriter()) {
66  			session = SshSessionFactory.getInstance().getSession(sshUri,
67  					provider, fs, 1000 * timeout);
68  			process = session.exec(command, 0);
69  			errorThread = new StreamCopyThread(process.getErrorStream(),
70  					stderr.getRawStream());
71  			errorThread.start();
72  			outThread = new StreamCopyThread(process.getInputStream(),
73  					stdout.getRawStream());
74  			outThread.start();
75  			try {
76  				// waitFor with timeout has a bug - JSch' exitValue() throws the
77  				// wrong exception type :(
78  				if (process.waitFor() == 0) {
79  					out = stdout.toString();
80  				} else {
81  					out = null; // still running after timeout
82  				}
83  			} catch (InterruptedException e) {
84  				out = null; // error
85  			}
86  		} finally {
87  			if (errorThread != null) {
88  				try {
89  					errorThread.halt();
90  				} catch (InterruptedException e) {
91  					// Stop waiting and return anyway.
92  				} finally {
93  					errorThread = null;
94  				}
95  			}
96  			if (outThread != null) {
97  				try {
98  					outThread.halt();
99  				} catch (InterruptedException e) {
100 					// Stop waiting and return anyway.
101 				} finally {
102 					outThread = null;
103 				}
104 			}
105 			if (process != null) {
106 				if (process.exitValue() != 0) {
107 					failure = new CommandFailedException(process.exitValue(),
108 							MessageFormat.format(
109 							JGitText.get().sshCommandFailed, command,
110 							stderr.toString()));
111 				}
112 				process.destroy();
113 			}
114 			stderr.close();
115 			if (session != null) {
116 				SshSessionFactory.getInstance().releaseSession(session);
117 			}
118 		}
119 		if (failure != null) {
120 			throw failure;
121 		}
122 		return out;
123 	}
124 
125 }