comparison src/ch/ethz/ssh2/Session.java @ 273:91a31873c42a ganymed

start conversion from trilead to ganymed
author Carl Byington <carl@five-ten-sg.com>
date Fri, 18 Jul 2014 11:21:46 -0700
parents
children db9b028016de
comparison
equal deleted inserted replaced
272:ce2f4e397703 273:91a31873c42a
1 /*
2 * Copyright (c) 2006-2011 Christian Plattner. All rights reserved.
3 * Please refer to the LICENSE.txt for licensing details.
4 */
5 package ch.ethz.ssh2;
6
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.io.OutputStream;
10 import java.security.SecureRandom;
11
12 import ch.ethz.ssh2.channel.Channel;
13 import ch.ethz.ssh2.channel.ChannelManager;
14 import ch.ethz.ssh2.channel.X11ServerData;
15
16 /**
17 * A <code>Session</code> is a remote execution of a program. "Program" means
18 * in this context either a shell, an application or a system command. The
19 * program may or may not have a tty. Only one single program can be started on
20 * a session. However, multiple sessions can be active simultaneously.
21 *
22 * @author Christian Plattner
23 * @version $Id: Session.java 96 2014-04-08 15:14:37Z dkocher@sudo.ch $
24 */
25 public class Session
26 {
27 private ChannelManager cm;
28 private Channel cn;
29
30 private boolean flag_pty_requested = false;
31 private boolean flag_x11_requested = false;
32 private boolean flag_execution_started = false;
33 private boolean flag_closed = false;
34
35 private String x11FakeCookie = null;
36
37 private final SecureRandom rnd;
38
39 protected Session(ChannelManager cm, SecureRandom rnd) throws IOException
40 {
41 this.cm = cm;
42 this.cn = cm.openSessionChannel();
43 this.rnd = rnd;
44 }
45
46 /**
47 * Basically just a wrapper for lazy people - identical to calling
48 * <code>requestPTY("dumb", 0, 0, 0, 0, null)</code>.
49 *
50 * @throws IOException
51 */
52 public void requestDumbPTY() throws IOException
53 {
54 requestPTY("dumb", 0, 0, 0, 0, null);
55 }
56
57 /**
58 * Basically just another wrapper for lazy people - identical to calling
59 * <code>requestPTY(term, 0, 0, 0, 0, null)</code>.
60 *
61 * @throws IOException
62 */
63 public void requestPTY(String term) throws IOException
64 {
65 requestPTY(term, 0, 0, 0, 0, null);
66 }
67
68 /**
69 * Allocate a pseudo-terminal for this session.
70 * <p/>
71 * This method may only be called before a program or shell is started in
72 * this session.
73 * <p/>
74 * Different aspects can be specified:
75 * <p/>
76 * <ul>
77 * <li>The TERM environment variable value (e.g., vt100)</li>
78 * <li>The terminal's dimensions.</li>
79 * <li>The encoded terminal modes.</li>
80 * </ul>
81 * Zero dimension parameters are ignored. The character/row dimensions
82 * override the pixel dimensions (when nonzero). Pixel dimensions refer to
83 * the drawable area of the window. The dimension parameters are only
84 * informational. The encoding of terminal modes (parameter
85 * <code>terminal_modes</code>) is described in RFC4254.
86 *
87 * @param term The TERM environment variable value (e.g., vt100)
88 * @param term_width_characters terminal width, characters (e.g., 80)
89 * @param term_height_characters terminal height, rows (e.g., 24)
90 * @param term_width_pixels terminal width, pixels (e.g., 640)
91 * @param term_height_pixels terminal height, pixels (e.g., 480)
92 * @param terminal_modes encoded terminal modes (may be <code>null</code>)
93 * @throws IOException
94 */
95 public void requestPTY(String term, int term_width_characters, int term_height_characters, int term_width_pixels,
96 int term_height_pixels, byte[] terminal_modes) throws IOException
97 {
98 if (term == null)
99 throw new IllegalArgumentException("TERM cannot be null.");
100
101 if ((terminal_modes != null) && (terminal_modes.length > 0))
102 {
103 if (terminal_modes[terminal_modes.length - 1] != 0)
104 throw new IOException("Illegal terminal modes description, does not end in zero byte");
105 }
106 else
107 terminal_modes = new byte[]{0};
108
109 synchronized (this)
110 {
111 /* The following is just a nicer error, we would catch it anyway later in the channel code */
112 if (flag_closed)
113 throw new IOException("This session is closed.");
114
115 if (flag_pty_requested)
116 throw new IOException("A PTY was already requested.");
117
118 if (flag_execution_started)
119 throw new IOException(
120 "Cannot request PTY at this stage anymore, a remote execution has already started.");
121
122 flag_pty_requested = true;
123 }
124
125 cm.requestPTY(cn, term, term_width_characters, term_height_characters, term_width_pixels, term_height_pixels,
126 terminal_modes);
127 }
128
129 /**
130 * Tells the server that the size of the terminal has changed.
131 *
132 * See {@link #requestPTY(String, int, int, int, int, byte[])} for more details about how parameters are interpreted.
133 *
134 * @param term_width_characters
135 * terminal width, characters (e.g., 80)
136 * @param term_height_characters
137 * terminal height, rows (e.g., 24)
138 * @param term_width_pixels
139 * terminal width, pixels (e.g., 640)
140 * @param term_height_pixels
141 * terminal height, pixels (e.g., 480)
142 * @throws IOException
143 */
144 public void requestWindowChange(int term_width_characters, int term_height_characters, int term_width_pixels,
145 int term_height_pixels) throws IOException
146 {
147 synchronized (this)
148 {
149 /* The following is just a nicer error, we would catch it anyway later in the channel code */
150 if (flag_closed)
151 throw new IOException("This session is closed.");
152
153 if (!flag_pty_requested)
154 throw new IOException("A PTY was not requested.");
155 }
156
157 cm.requestWindowChange(cn, term_width_characters, term_height_characters, term_width_pixels, term_height_pixels);
158 }
159
160 /**
161 * Request X11 forwarding for the current session.
162 * <p/>
163 * You have to supply the name and port of your X-server.
164 * <p/>
165 * This method may only be called before a program or shell is started in
166 * this session.
167 *
168 * @param hostname the hostname of the real (target) X11 server (e.g., 127.0.0.1)
169 * @param port the port of the real (target) X11 server (e.g., 6010)
170 * @param cookie if non-null, then present this cookie to the real X11 server
171 * @param singleConnection if true, then the server is instructed to only forward one single
172 * connection, no more connections shall be forwarded after first, or after the session
173 * channel has been closed
174 * @throws IOException
175 */
176 public void requestX11Forwarding(String hostname, int port, byte[] cookie, boolean singleConnection)
177 throws IOException
178 {
179 if (hostname == null)
180 throw new IllegalArgumentException("hostname argument may not be null");
181
182 synchronized (this)
183 {
184 /* The following is just a nicer error, we would catch it anyway later in the channel code */
185 if (flag_closed)
186 throw new IOException("This session is closed.");
187
188 if (flag_x11_requested)
189 throw new IOException("X11 forwarding was already requested.");
190
191 if (flag_execution_started)
192 throw new IOException(
193 "Cannot request X11 forwarding at this stage anymore, a remote execution has already started.");
194
195 flag_x11_requested = true;
196 }
197
198 /* X11ServerData - used to store data about the target X11 server */
199
200 X11ServerData x11data = new X11ServerData();
201
202 x11data.hostname = hostname;
203 x11data.port = port;
204 x11data.x11_magic_cookie = cookie; /* if non-null, then present this cookie to the real X11 server */
205
206 /* Generate fake cookie - this one is used between remote clients and the ganymed proxy */
207
208 byte[] fakeCookie = new byte[16];
209 String hexEncodedFakeCookie;
210
211 /* Make sure that this fake cookie is unique for this connection */
212
213 while (true)
214 {
215 rnd.nextBytes(fakeCookie);
216
217 /* Generate also hex representation of fake cookie */
218
219 StringBuilder tmp = new StringBuilder(32);
220 for (int i = 0; i < fakeCookie.length; i++)
221 {
222 String digit2 = Integer.toHexString(fakeCookie[i] & 0xff);
223 tmp.append((digit2.length() == 2) ? digit2 : "0" + digit2);
224 }
225 hexEncodedFakeCookie = tmp.toString();
226
227 /* Well, yes, chances are low, but we want to be on the safe side */
228
229 if (cm.checkX11Cookie(hexEncodedFakeCookie) == null)
230 break;
231 }
232
233 /* Ask for X11 forwarding */
234
235 cm.requestX11(cn, singleConnection, "MIT-MAGIC-COOKIE-1", hexEncodedFakeCookie, 0);
236
237 /* OK, that went fine, get ready to accept X11 connections... */
238 /* ... but only if the user has not called close() in the meantime =) */
239
240 synchronized (this)
241 {
242 if (flag_closed == false)
243 {
244 this.x11FakeCookie = hexEncodedFakeCookie;
245 cm.registerX11Cookie(hexEncodedFakeCookie, x11data);
246 }
247 }
248
249 /* Now it is safe to start remote X11 programs */
250 }
251
252 /**
253 * Execute a command on the remote machine.
254 *
255 * @param cmd The command to execute on the remote host.
256 * @throws IOException
257 */
258 public void execCommand(String cmd) throws IOException
259 {
260 this.execCommand(cmd, null);
261 }
262
263 /**
264 * Execute a command on the remote machine.
265 *
266 * @param cmd The command to execute on the remote host.
267 * @param charsetName The charset used to convert between Java Unicode Strings and byte encodings
268 * @throws IOException
269 */
270 public void execCommand(String cmd, String charsetName) throws IOException
271 {
272 if (cmd == null)
273 throw new IllegalArgumentException("cmd argument may not be null");
274
275 synchronized (this)
276 {
277 /* The following is just a nicer error, we would catch it anyway later in the channel code */
278 if (flag_closed)
279 throw new IOException("This session is closed.");
280
281 if (flag_execution_started)
282 throw new IOException("A remote execution has already started.");
283
284 flag_execution_started = true;
285 }
286
287 cm.requestExecCommand(cn, cmd, charsetName);
288 }
289
290 /**
291 * Start a shell on the remote machine.
292 *
293 * @throws IOException
294 */
295 public void startShell() throws IOException
296 {
297 synchronized (this)
298 {
299 /* The following is just a nicer error, we would catch it anyway later in the channel code */
300 if (flag_closed)
301 throw new IOException("This session is closed.");
302
303 if (flag_execution_started)
304 throw new IOException("A remote execution has already started.");
305
306 flag_execution_started = true;
307 }
308
309 cm.requestShell(cn);
310 }
311
312 /**
313 * Start a subsystem on the remote machine.
314 * Unless you know what you are doing, you will never need this.
315 *
316 * @param name the name of the subsystem.
317 * @throws IOException
318 */
319 public void startSubSystem(String name) throws IOException
320 {
321 if (name == null)
322 throw new IllegalArgumentException("name argument may not be null");
323
324 synchronized (this)
325 {
326 /* The following is just a nicer error, we would catch it anyway later in the channel code */
327 if (flag_closed)
328 throw new IOException("This session is closed.");
329
330 if (flag_execution_started)
331 throw new IOException("A remote execution has already started.");
332
333 flag_execution_started = true;
334 }
335
336 cm.requestSubSystem(cn, name);
337 }
338
339 public int getState()
340 {
341 return cn.getState();
342 }
343
344 public InputStream getStdout()
345 {
346 return cn.getStdoutStream();
347 }
348
349 public InputStream getStderr()
350 {
351 return cn.getStderrStream();
352 }
353
354 public OutputStream getStdin()
355 {
356 return cn.getStdinStream();
357 }
358
359 /**
360 * This method blocks until there is more data available on either the
361 * stdout or stderr InputStream of this <code>Session</code>. Very useful
362 * if you do not want to use two parallel threads for reading from the two
363 * InputStreams. One can also specify a timeout. NOTE: do NOT call this
364 * method if you use concurrent threads that operate on either of the two
365 * InputStreams of this <code>Session</code> (otherwise this method may
366 * block, even though more data is available).
367 *
368 * @param timeout The (non-negative) timeout in <code>ms</code>. <code>0</code> means no
369 * timeout, the call may block forever.
370 * @return <ul>
371 * <li><code>0</code> if no more data will arrive.</li>
372 * <li><code>1</code> if more data is available.</li>
373 * <li><code>-1</code> if a timeout occurred.</li>
374 * </ul>
375 * @throws IOException
376 * @deprecated This method has been replaced with a much more powerful wait-for-condition
377 * interface and therefore acts only as a wrapper.
378 */
379 public int waitUntilDataAvailable(long timeout) throws IOException
380 {
381 if (timeout < 0)
382 throw new IllegalArgumentException("timeout must not be negative!");
383
384 int conditions = cm.waitForCondition(cn, timeout, ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA
385 | ChannelCondition.EOF);
386
387 if ((conditions & ChannelCondition.TIMEOUT) != 0)
388 return -1;
389
390 if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) != 0)
391 return 1;
392
393 /* Here we do not need to check separately for CLOSED, since CLOSED implies EOF */
394
395 if ((conditions & ChannelCondition.EOF) != 0)
396 return 0;
397
398 throw new IllegalStateException("Unexpected condition result (" + conditions + ")");
399 }
400
401 /**
402 * This method blocks until certain conditions hold true on the underlying SSH-2 channel.
403 * <p/>
404 * This method returns as soon as one of the following happens:
405 * <ul>
406 * <li>at least of the specified conditions (see {@link ChannelCondition}) holds true</li>
407 * <li>timeout > 0 and a timeout occured (TIMEOUT will be set in result conditions)</a>
408 * <li>the underlying channel was closed (CLOSED will be set in result conditions)</a>
409 * </ul>
410 * <p/>
411 * In any case, the result value contains ALL current conditions, which may be more
412 * than the specified condition set (i.e., never use the "==" operator to test for conditions
413 * in the bitmask, see also comments in {@link ChannelCondition}).
414 * <p/>
415 * Note: do NOT call this method if you want to wait for STDOUT_DATA or STDERR_DATA and
416 * there are concurrent threads (e.g., StreamGobblers) that operate on either of the two
417 * InputStreams of this <code>Session</code> (otherwise this method may
418 * block, even though more data is available in the StreamGobblers).
419 *
420 * @param condition_set a bitmask based on {@link ChannelCondition} values
421 * @param timeout non-negative timeout in ms, <code>0</code> means no timeout
422 * @return all bitmask specifying all current conditions that are true
423 */
424
425 public int waitForCondition(int condition_set, long timeout) throws IOException {
426 if (timeout < 0)
427 throw new IllegalArgumentException("timeout must be non-negative!");
428
429 return cm.waitForCondition(cn, timeout, condition_set);
430 }
431
432 /**
433 * Get the exit code/status from the remote command - if available. Be
434 * careful - not all server implementations return this value. It is
435 * generally a good idea to call this method only when all data from the
436 * remote side has been consumed (see also the <code<WaitForCondition</code> method).
437 *
438 * @return An <code>Integer</code> holding the exit code, or
439 * <code>null</code> if no exit code is (yet) available.
440 */
441 public Integer getExitStatus()
442 {
443 return cn.getExitStatus();
444 }
445
446 /**
447 * Get the name of the signal by which the process on the remote side was
448 * stopped - if available and applicable. Be careful - not all server
449 * implementations return this value.
450 *
451 * @return An <code>String</code> holding the name of the signal, or
452 * <code>null</code> if the process exited normally or is still
453 * running (or if the server forgot to send this information).
454 */
455 public String getExitSignal()
456 {
457 return cn.getExitSignal();
458 }
459
460 /**
461 * Close this session. NEVER forget to call this method to free up resources -
462 * even if you got an exception from one of the other methods (or when
463 * getting an Exception on the Input- or OutputStreams). Sometimes these other
464 * methods may throw an exception, saying that the underlying channel is
465 * closed (this can happen, e.g., if the other server sent a close message.)
466 * However, as long as you have not called the <code>close()</code>
467 * method, you may be wasting (local) resources.
468 */
469 public void close()
470 {
471 synchronized (this)
472 {
473 if (flag_closed)
474 return;
475
476 flag_closed = true;
477
478 if (x11FakeCookie != null)
479 cm.unRegisterX11Cookie(x11FakeCookie, true);
480
481 try
482 {
483 cm.closeChannel(cn, "Closed due to user request", true);
484 }
485 catch (IOException ignored)
486 {
487 }
488 }
489 }
490 }