summaryrefslogtreecommitdiffstats
path: root/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ShellSession.java
blob: 09228246470fa48eccc9438c3b23a18aa319fab3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/*****************************************************************************
 * Copyright (c) 2013 Ken Gilmer
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Ken Gilmer - initial API and implementation
 *     Jessica Zhang - Adopt for Yocto Tools plugin
 *******************************************************************************/
package org.yocto.remote.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.swt.widgets.Display;

public class ShellSession {
	/**
	 * Bash shell
	 */
	public static final int SHELL_TYPE_BASH = 1;
	/**
	 * sh shell
	 */
	public static final int SHELL_TYPE_SH = 2;
	private volatile boolean interrupt = false;
	/**
	 * String used to isolate command execution
	 */
	public static final String TERMINATOR = "build$";
	public static final String LT = System.getProperty("line.separator");
	private Process process;

	private OutputStream pos = null;

	private String shellPath = null;
	private final String initCmd;
	private final File root;
	private final File builddir;

	private OutputStreamWriter out;

	public static String getFilePath(String file) throws IOException {
		File f = new File(file);

		if (!f.exists() || f.isDirectory()) {
			throw new IOException("Path passed is not a file: " + file);
		}

		StringBuffer sb = new StringBuffer();

		String elems[] = file.split(File.separator);

		for (int i = 0; i < elems.length - 1; ++i) {
			sb.append(elems[i]);
			sb.append(File.separator);
		}

		return sb.toString();
	}

	public ShellSession(int shellType, File root, File builddir, String initCmd, OutputStream out) throws IOException {
		this.root = root;
		this.builddir = builddir;
		this.initCmd  = initCmd;
		if (out == null) {
			this.out = new OutputStreamWriter(null);
		} else {
			this.out = new OutputStreamWriter(out);
		}
		if (shellType == SHELL_TYPE_SH) {
			shellPath = "/bin/sh";
		}
		shellPath  = "/bin/bash";

		initializeShell();
	}

	private void initializeShell() throws IOException {
		process = Runtime.getRuntime().exec(shellPath);
		pos = process.getOutputStream();

		if (root != null) {
			execute("cd " + root.getAbsolutePath());
		}

		if (initCmd != null) {
			execute("source " + initCmd + " " + builddir.getAbsolutePath());
		}
	}

	synchronized
	public String execute(String command, int[] retCode) throws IOException {
		String errorMessage = null;

		interrupt = false;
		out.write(command);
		out.write(LT);

		sendToProcessAndTerminate(command);

		if (process.getErrorStream().available() > 0) {
			byte[] msg = new byte[process.getErrorStream().available()];

			process.getErrorStream().read(msg, 0, msg.length);
			String msg_str = new String(msg);
			out.write(msg_str);
			out.write(LT);
			if (!msg_str.contains("WARNING"))
				errorMessage = "Error while executing: " + command + LT + new String(msg);
		}

		BufferedReader br = new BufferedReader(new InputStreamReader(process
				.getInputStream()));

		StringBuffer sb = new StringBuffer();
		String line = null;

		while (true) {
			line = br.readLine();
			if (line != null) {
				sb.append(line);
				sb.append(LT);
				out.write(line);
				out.write(LT);
			}
			if (line.endsWith(TERMINATOR))
				break;
		}
 		if (interrupt) {
			process.destroy();
			initializeShell();
			interrupt = false;
		}else if (line != null && retCode != null) {
			try {
				retCode[0]=Integer.parseInt(line.substring(0,line.lastIndexOf(TERMINATOR)));
			}catch (NumberFormatException e) {
				throw new IOException("Can NOT get return code" + command + LT + line);
			}
		}
		out.flush();
		if (errorMessage != null) {
			throw new IOException(errorMessage);
		}
		return sb.toString();
	}

	synchronized
	public void execute(String command) throws IOException {
		interrupt = false;
		String errorMessage = null;

		sendToProcessAndTerminate(command);
		boolean cancel = false;
		try {
			InputStream is = process.getInputStream();
			InputStream es = process.getErrorStream();
			String info;
			while (!cancel) {
				info = null;
				StringBuffer buffer = new StringBuffer();
				int c;
				while (is.available() > 0) {
					c = is.read();
					char ch = (char) c;
					buffer.append(ch);
					if (ch == '\n') {
						info = buffer.toString();
						if (!info.trim().endsWith(TERMINATOR)) {
							out.write(info);
							out.write(LT);
							buffer.delete(0, buffer.length());
						} else {
							cancel = true;
							break;
						}
					}
				}
				while (es.available() > 0) {
					c = es.read();
					char ch = (char) c;
					buffer.append(ch);
					if (ch == '\n') {
						info = buffer.toString();
						if (!info.contains("WARNING"))
							errorMessage += info;
						out.write(info);
						out.write(LT);
						buffer.delete(0, buffer.length());
					}
				}
			}
		} catch (IOException e) {
			try {
				throw new InvocationTargetException(e);
			} catch (InvocationTargetException e1) {
				e1.printStackTrace();
			}
		}
		out.flush();
		if (errorMessage != null) {
			throw new IOException(errorMessage);
		}
		if (interrupt) {
			process.destroy();
			initializeShell();
			interrupt = false;
		}
	}
	synchronized
	public boolean ensureKnownHostKey(String user, String host) throws IOException {

		boolean loadKeysMatch = false;
		boolean accepted = false;
		Process proc = Runtime.getRuntime().exec("ssh -o LogLevel=DEBUG3 " + user + "@" + host);
		Pattern patternLoad = Pattern.compile("^debug3: load_hostkeys: loaded (\\d+) keys");
		Pattern patternAuthSucceeded = Pattern.compile("^debug1: Authentication succeeded.*");

		try {
			InputStream es = proc.getErrorStream();
			String info;
			while (!loadKeysMatch) {
				info = null;
				StringBuffer buffer = new StringBuffer();
				int c;
				while (es.available() > 0) {
					c = es.read();
					char ch = (char) c;
					buffer.append(ch);
					if (ch == '\r') {
						info = buffer.toString().trim();
						Matcher m = patternLoad.matcher(info);
						if(m.matches()) {
							int keys = new Integer(m.group(1));
							if (keys == 0) {
								proc.destroy();
								DialogRunnable runnable = new DialogRunnable("Host authenticity", "The authenticity of host '" + host + "(" + host + ")' can't be established.\nAre you sure you want to continue connecting ?", DialogRunnable.QUESTION);
								Display.getDefault().syncExec(runnable);
								accepted = runnable.result;
								if (accepted){
									proc = Runtime.getRuntime().exec("ssh -o StrictHostKeyChecking=no " + user + "@" + host);//add host key to known_hosts
									try {
										Thread.sleep(2000); //wait for process to finish
									} catch (InterruptedException e) {
										e.printStackTrace();
									}
									proc.destroy();
								} else {
									Display.getDefault().syncExec( new DialogRunnable("Host authenticity", "Host key verification failed.", DialogRunnable.ERROR));
								}
							} else {
								String errorMsg = "";
								// wait to check if key is the same and authentication succeeds
								while (es.available() > 0) {
									c = es.read();
									ch = (char) c;
									buffer.append(ch);
									if (ch == '\r') {
										info = buffer.toString().trim();
										Matcher mAuthS = patternAuthSucceeded.matcher(info);
										if(mAuthS.matches()) {
											accepted = true;
											break;
										} else {
											if (!info.startsWith("debug"))
												errorMsg += info + "\n";
										}
										try {
											Thread.sleep(100);
										} catch (InterruptedException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
										buffer.delete(0, buffer.length());
									}
								}
								if (!accepted && !errorMsg.isEmpty()) {
									Display.getDefault().syncExec( new DialogRunnable("Host authenticity", errorMsg, DialogRunnable.ERROR));
								}
							}
							loadKeysMatch = true;
							break;
						}
						buffer.delete(0, buffer.length());
					}
				}
			}
			es.close();
		} catch (IOException e) {
			try {
				throw new InvocationTargetException(e);
			} catch (InvocationTargetException e1) {
				e1.printStackTrace();
			}
		}
		return accepted;
	}

	/**
	 * Send command string to shell process and add special terminator string so
	 * reader knows when output is complete.
	 *
	 * @param command
	 * @throws IOException
	 */
	private void sendToProcessAndTerminate(String command) throws IOException {
		pos.write(command.getBytes());
		pos.write(LT.getBytes());
		pos.flush();
		pos.write("echo $?".getBytes());
		pos.write(TERMINATOR.getBytes());
		pos.write(LT.getBytes());
		pos.flush();
	}

	/**
	 * Interrupt any running processes.
	 */
	public void interrupt() {
		interrupt = true;
	}
}