KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > ch > ethz > ssh2 > Session


1
2 package ch.ethz.ssh2;
3
4 import java.io.IOException JavaDoc;
5 import java.io.InputStream JavaDoc;
6 import java.io.OutputStream JavaDoc;
7 import java.security.SecureRandom JavaDoc;
8
9 import ch.ethz.ssh2.channel.Channel;
10 import ch.ethz.ssh2.channel.ChannelManager;
11 import ch.ethz.ssh2.channel.X11ServerData;
12
13 /**
14  * A <code>Session</code> is a remote execution of a program. "Program" means
15  * in this context either a shell, an application or a system command. The
16  * program may or may not have a tty. Only one single program can be started on
17  * a session. However, multiple sessions can be active simultaneously.
18  *
19  * @author Christian Plattner, plattner@inf.ethz.ch
20  * @version $Id: Session.java,v 1.10 2006/11/01 14:20:24 cplattne Exp $
21  */

22 public class Session
23 {
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 JavaDoc x11FakeCookie = null;
33
34     final SecureRandom JavaDoc rnd;
35     
36     Session(ChannelManager cm, SecureRandom JavaDoc rnd) throws IOException JavaDoc
37     {
38         this.cm = cm;
39         this.cn = cm.openSessionChannel();
40         this.rnd = rnd;
41     }
42
43     /**
44      * Basically just a wrapper for lazy people - identical to calling
45      * <code>requestPTY("dumb", 0, 0, 0, 0, null)</code>.
46      *
47      * @throws IOException
48      */

49     public void requestDumbPTY() throws IOException JavaDoc
50     {
51         requestPTY("dumb", 0, 0, 0, 0, null);
52     }
53
54     /**
55      * Basically just another wrapper for lazy people - identical to calling
56      * <code>requestPTY(term, 0, 0, 0, 0, null)</code>.
57      *
58      * @throws IOException
59      */

60     public void requestPTY(String JavaDoc term) throws IOException JavaDoc
61     {
62         requestPTY(term, 0, 0, 0, 0, null);
63     }
64
65     /**
66      * Allocate a pseudo-terminal for this session.
67      * <p>
68      * This method may only be called before a program or shell is started in
69      * this session.
70      * <p>
71      * Different aspects can be specified:
72      * <p>
73      * <ul>
74      * <li>The TERM environment variable value (e.g., vt100)</li>
75      * <li>The terminal's dimensions.</li>
76      * <li>The encoded terminal modes.</li>
77      * </ul>
78      * Zero dimension parameters are ignored. The character/row dimensions
79      * override the pixel dimensions (when nonzero). Pixel dimensions refer to
80      * the drawable area of the window. The dimension parameters are only
81      * informational. The encoding of terminal modes (parameter
82      * <code>terminal_modes</code>) is described in RFC4254.
83      *
84      * @param term
85      * The TERM environment variable value (e.g., vt100)
86      * @param term_width_characters
87      * terminal width, characters (e.g., 80)
88      * @param term_height_characters
89      * terminal height, rows (e.g., 24)
90      * @param term_width_pixels
91      * terminal width, pixels (e.g., 640)
92      * @param term_height_pixels
93      * terminal height, pixels (e.g., 480)
94      * @param terminal_modes
95      * encoded terminal modes (may be <code>null</code>)
96      * @throws IOException
97      */

98     public void requestPTY(String JavaDoc term, int term_width_characters, int term_height_characters, int term_width_pixels,
99             int term_height_pixels, byte[] terminal_modes) throws IOException JavaDoc
100     {
101         if (term == null)
102             throw new IllegalArgumentException JavaDoc("TERM cannot be null.");
103
104         if ((terminal_modes != null) && (terminal_modes.length > 0))
105         {
106             if (terminal_modes[terminal_modes.length - 1] != 0)
107                 throw new IOException JavaDoc("Illegal terminal modes description, does not end in zero byte");
108         }
109         else
110             terminal_modes = new byte[] { 0 };
111
112         synchronized (this)
113         {
114             /* The following is just a nicer error, we would catch it anyway later in the channel code */
115             if (flag_closed)
116                 throw new IOException JavaDoc("This session is closed.");
117
118             if (flag_pty_requested)
119                 throw new IOException JavaDoc("A PTY was already requested.");
120
121             if (flag_execution_started)
122                 throw new IOException JavaDoc(
123                         "Cannot request PTY at this stage anymore, a remote execution has already started.");
124
125             flag_pty_requested = true;
126         }
127
128         cm.requestPTY(cn, term, term_width_characters, term_height_characters, term_width_pixels, term_height_pixels,
129                 terminal_modes);
130     }
131
132     /**
133      * Request X11 forwarding for the current session.
134      * <p>
135      * You have to supply the name and port of your X-server.
136      * <p>
137      * This method may only be called before a program or shell is started in
138      * this session.
139      *
140      * @param hostname the hostname of the real (target) X11 server (e.g., 127.0.0.1)
141      * @param port the port of the real (target) X11 server (e.g., 6010)
142      * @param cookie if non-null, then present this cookie to the real X11 server
143      * @param singleConnection if true, then the server is instructed to only forward one single
144      * connection, no more connections shall be forwarded after first, or after the session
145      * channel has been closed
146      * @throws IOException
147      */

148     public void requestX11Forwarding(String JavaDoc hostname, int port, byte[] cookie, boolean singleConnection)
149             throws IOException JavaDoc
150     {
151         if (hostname == null)
152             throw new IllegalArgumentException JavaDoc("hostname argument may not be null");
153
154         synchronized (this)
155         {
156             /* The following is just a nicer error, we would catch it anyway later in the channel code */
157             if (flag_closed)
158                 throw new IOException JavaDoc("This session is closed.");
159
160             if (flag_x11_requested)
161                 throw new IOException JavaDoc("X11 forwarding was already requested.");
162
163             if (flag_execution_started)
164                 throw new IOException JavaDoc(
165                         "Cannot request X11 forwarding at this stage anymore, a remote execution has already started.");
166
167             flag_x11_requested = true;
168         }
169
170         /* X11ServerData - used to store data about the target X11 server */
171
172         X11ServerData x11data = new X11ServerData();
173
174         x11data.hostname = hostname;
175         x11data.port = port;
176         x11data.x11_magic_cookie = cookie; /* if non-null, then present this cookie to the real X11 server */
177
178         /* Generate fake cookie - this one is used between remote clients and the ganymed proxy */
179
180         byte[] fakeCookie = new byte[16];
181         String JavaDoc hexEncodedFakeCookie;
182
183         /* Make sure that this fake cookie is unique for this connection */
184
185         while (true)
186         {
187             rnd.nextBytes(fakeCookie);
188
189             /* Generate also hex representation of fake cookie */
190
191             StringBuffer JavaDoc tmp = new StringBuffer JavaDoc(32);
192             for (int i = 0; i < fakeCookie.length; i++)
193             {
194                 String JavaDoc digit2 = Integer.toHexString(fakeCookie[i] & 0xff);
195                 tmp.append((digit2.length() == 2) ? digit2 : "0" + digit2);
196             }
197             hexEncodedFakeCookie = tmp.toString();
198
199             /* Well, yes, chances are low, but we want to be on the safe side */
200
201             if (cm.checkX11Cookie(hexEncodedFakeCookie) == null)
202                 break;
203         }
204
205         /* Ask for X11 forwarding */
206
207         cm.requestX11(cn, singleConnection, "MIT-MAGIC-COOKIE-1", hexEncodedFakeCookie, 0);
208
209         /* OK, that went fine, get ready to accept X11 connections... */
210         /* ... but only if the user has not called close() in the meantime =) */
211
212         synchronized (this)
213         {
214             if (flag_closed == false)
215             {
216                 this.x11FakeCookie = hexEncodedFakeCookie;
217                 cm.registerX11Cookie(hexEncodedFakeCookie, x11data);
218             }
219         }
220
221         /* Now it is safe to start remote X11 programs */
222     }
223
224     /**
225      * Execute a command on the remote machine.
226      *
227      * @param cmd
228      * The command to execute on the remote host.
229      * @throws IOException
230      */

231     public void execCommand(String JavaDoc cmd) throws IOException JavaDoc
232     {
233         if (cmd == null)
234             throw new IllegalArgumentException JavaDoc("cmd argument may not be null");
235
236         synchronized (this)
237         {
238             /* The following is just a nicer error, we would catch it anyway later in the channel code */
239             if (flag_closed)
240                 throw new IOException JavaDoc("This session is closed.");
241
242             if (flag_execution_started)
243                 throw new IOException JavaDoc("A remote execution has already started.");
244
245             flag_execution_started = true;
246         }
247
248         cm.requestExecCommand(cn, cmd);
249     }
250
251     /**
252      * Start a shell on the remote machine.
253      *
254      * @throws IOException
255      */

256     public void startShell() throws IOException JavaDoc
257     {
258         synchronized (this)
259         {
260             /* The following is just a nicer error, we would catch it anyway later in the channel code */
261             if (flag_closed)
262                 throw new IOException JavaDoc("This session is closed.");
263
264             if (flag_execution_started)
265                 throw new IOException JavaDoc("A remote execution has already started.");
266
267             flag_execution_started = true;
268         }
269
270         cm.requestShell(cn);
271     }
272
273     /**
274      * Start a subsystem on the remote machine.
275      * Unless you know what you are doing, you will never need this.
276      *
277      * @param name the name of the subsystem.
278      * @throws IOException
279      */

280     public void startSubSystem(String JavaDoc name) throws IOException JavaDoc
281     {
282         if (name == null)
283             throw new IllegalArgumentException JavaDoc("name argument may not be null");
284
285         synchronized (this)
286         {
287             /* The following is just a nicer error, we would catch it anyway later in the channel code */
288             if (flag_closed)
289                 throw new IOException JavaDoc("This session is closed.");
290
291             if (flag_execution_started)
292                 throw new IOException JavaDoc("A remote execution has already started.");
293
294             flag_execution_started = true;
295         }
296
297         cm.requestSubSystem(cn, name);
298     }
299
300     public InputStream JavaDoc getStdout()
301     {
302         return cn.getStdoutStream();
303     }
304
305     public InputStream JavaDoc getStderr()
306     {
307         return cn.getStderrStream();
308     }
309
310     public OutputStream JavaDoc getStdin()
311     {
312         return cn.getStdinStream();
313     }
314
315     /**
316      * This method blocks until there is more data available on either the
317      * stdout or stderr InputStream of this <code>Session</code>. Very useful
318      * if you do not want to use two parallel threads for reading from the two
319      * InputStreams. One can also specify a timeout. NOTE: do NOT call this
320      * method if you use concurrent threads that operate on either of the two
321      * InputStreams of this <code>Session</code> (otherwise this method may
322      * block, even though more data is available).
323      *
324      * @param timeout
325      * The (non-negative) timeout in <code>ms</code>. <code>0</code> means no
326      * timeout, the call may block forever.
327      * @return
328      * <ul>
329      * <li><code>0</code> if no more data will arrive.</li>
330      * <li><code>1</code> if more data is available.</li>
331      * <li><code>-1</code> if a timeout occurred.</li>
332      * </ul>
333      *
334      * @throws IOException
335      * @deprecated This method has been replaced with a much more powerful wait-for-condition
336      * interface and therefore acts only as a wrapper.
337      *
338      */

339     public int waitUntilDataAvailable(long timeout) throws IOException JavaDoc
340     {
341         if (timeout < 0)
342             throw new IllegalArgumentException JavaDoc("timeout must not be negative!");
343
344         int conditions = cm.waitForCondition(cn, timeout, ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA
345                 | ChannelCondition.EOF);
346
347         if ((conditions & ChannelCondition.TIMEOUT) != 0)
348             return -1;
349
350         if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) != 0)
351             return 1;
352
353         /* Here we do not need to check separately for CLOSED, since CLOSED implies EOF */
354
355         if ((conditions & ChannelCondition.EOF) != 0)
356             return 0;
357
358         throw new IllegalStateException JavaDoc("Unexpected condition result (" + conditions + ")");
359     }
360
361     /**
362      * This method blocks until certain conditions hold true on the underlying SSH-2 channel.
363      * <p>
364      * This method returns as soon as one of the following happens:
365      * <ul>
366      * <li>at least of the specified conditions (see {@link ChannelCondition}) holds true</li>
367      * <li>timeout > 0 and a timeout occured (TIMEOUT will be set in result conditions)</a>
368      * <li>the underlying channel was closed (CLOSED will be set in result conditions)</a>
369      * </ul>
370      * <p>
371      * In any case, the result value contains ALL current conditions, which may be more
372      * than the specified condition set (i.e., never use the "==" operator to test for conditions
373      * in the bitmask, see also comments in {@link ChannelCondition}).
374      * <p>
375      * Note: do NOT call this method if you want to wait for STDOUT_DATA or STDERR_DATA and
376      * there are concurrent threads (e.g., StreamGobblers) that operate on either of the two
377      * InputStreams of this <code>Session</code> (otherwise this method may
378      * block, even though more data is available in the StreamGobblers).
379      *
380      * @param condition_set a bitmask based on {@link ChannelCondition} values
381      * @param timeout non-negative timeout in ms, <code>0</code> means no timeout
382      * @return all bitmask specifying all current conditions that are true
383      */

384
385     public int waitForCondition(int condition_set, long timeout)
386     {
387         if (timeout < 0)
388             throw new IllegalArgumentException JavaDoc("timeout must be non-negative!");
389
390         return cm.waitForCondition(cn, timeout, condition_set);
391     }
392
393     /**
394      * Get the exit code/status from the remote command - if available. Be
395      * careful - not all server implementations return this value. It is
396      * generally a good idea to call this method only when all data from the
397      * remote side has been consumed (see also the <code<WaitForCondition</code> method).
398      *
399      * @return An <code>Integer</code> holding the exit code, or
400      * <code>null</code> if no exit code is (yet) available.
401      */

402     public Integer JavaDoc getExitStatus()
403     {
404         return cn.getExitStatus();
405     }
406
407     /**
408      * Get the name of the signal by which the process on the remote side was
409      * stopped - if available and applicable. Be careful - not all server
410      * implementations return this value.
411      *
412      * @return An <code>String</code> holding the name of the signal, or
413      * <code>null</code> if the process exited normally or is still
414      * running (or if the server forgot to send this information).
415      */

416     public String JavaDoc getExitSignal()
417     {
418         return cn.getExitSignal();
419     }
420
421     /**
422      * Close this session. NEVER forget to call this method to free up resources -
423      * even if you got an exception from one of the other methods (or when
424      * getting an Exception on the Input- or OutputStreams). Sometimes these other
425      * methods may throw an exception, saying that the underlying channel is
426      * closed (this can happen, e.g., if the other server sent a close message.)
427      * However, as long as you have not called the <code>close()</code>
428      * method, you may be wasting (local) resources.
429      *
430      */

431     public void close()
432     {
433         synchronized (this)
434         {
435             if (flag_closed)
436                 return;
437
438             flag_closed = true;
439
440             if (x11FakeCookie != null)
441                 cm.unRegisterX11Cookie(x11FakeCookie, true);
442
443             try
444             {
445                 cm.closeChannel(cn, "Closed due to user request", true);
446             }
447             catch (IOException JavaDoc ignored)
448             {
449             }
450         }
451     }
452 }
453
Popular Tags