comparison src/com/trilead/ssh2/Session.java @ 0:0ce5cc452d02

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