]> andersk Git - openssh.git/blob - clientloop.c
- stevesk@cvs.openbsd.org 2001/04/14 16:33:20
[openssh.git] / clientloop.c
1 /*
2  * Author: Tatu Ylonen <ylo@cs.hut.fi>
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  * The main loop for the interactive session (client side).
6  *
7  * As far as I am concerned, the code I have written for this software
8  * can be used freely for any purpose.  Any derived versions of this
9  * software must be clearly marked as such, and if the derived work is
10  * incompatible with the protocol description in the RFC file, it must be
11  * called by a name other than "ssh" or "Secure Shell".
12  *
13  *
14  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
26  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
29  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35  *
36  *
37  * SSH2 support added by Markus Friedl.
38  * Copyright (c) 1999,2000 Markus Friedl.  All rights reserved.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
50  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
51  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
52  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
53  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
54  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
55  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
56  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
57  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
58  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
59  */
60
61 #include "includes.h"
62 RCSID("$OpenBSD: clientloop.c,v 1.62 2001/04/14 16:33:20 stevesk Exp $");
63
64 #include "ssh.h"
65 #include "ssh1.h"
66 #include "ssh2.h"
67 #include "xmalloc.h"
68 #include "packet.h"
69 #include "buffer.h"
70 #include "compat.h"
71 #include "channels.h"
72 #include "dispatch.h"
73 #include "buffer.h"
74 #include "bufaux.h"
75 #include "key.h"
76 #include "kex.h"
77 #include "log.h"
78 #include "readconf.h"
79 #include "clientloop.h"
80 #include "authfd.h"
81 #include "atomicio.h"
82 #include "sshtty.h"
83
84 /* import options */
85 extern Options options;
86
87 /* Flag indicating that stdin should be redirected from /dev/null. */
88 extern int stdin_null_flag;
89
90 /*
91  * Name of the host we are connecting to.  This is the name given on the
92  * command line, or the HostName specified for the user-supplied name in a
93  * configuration file.
94  */
95 extern char *host;
96
97 /*
98  * Flag to indicate that we have received a window change signal which has
99  * not yet been processed.  This will cause a message indicating the new
100  * window size to be sent to the server a little later.  This is volatile
101  * because this is updated in a signal handler.
102  */
103 static volatile int received_window_change_signal = 0;
104
105 /* Flag indicating whether the user\'s terminal is in non-blocking mode. */
106 static int in_non_blocking_mode = 0;
107
108 /* Common data for the client loop code. */
109 static int quit_pending;        /* Set to non-zero to quit the client loop. */
110 static int escape_char;         /* Escape character. */
111 static int escape_pending;      /* Last character was the escape character */
112 static int last_was_cr;         /* Last character was a newline. */
113 static int exit_status;         /* Used to store the exit status of the command. */
114 static int stdin_eof;           /* EOF has been encountered on standard error. */
115 static Buffer stdin_buffer;     /* Buffer for stdin data. */
116 static Buffer stdout_buffer;    /* Buffer for stdout data. */
117 static Buffer stderr_buffer;    /* Buffer for stderr data. */
118 static u_long stdin_bytes, stdout_bytes, stderr_bytes;
119 static u_int buffer_high;/* Soft max buffer size. */
120 static int connection_in;       /* Connection to server (input). */
121 static int connection_out;      /* Connection to server (output). */
122 static int need_rekeying;       /* Set to non-zero if rekeying is requested. */
123 static int session_closed = 0;  /* In SSH2: login session closed. */
124
125 void    client_init_dispatch(void);
126 int     session_ident = -1;
127
128 /*XXX*/
129 extern Kex *xxx_kex;
130
131 /* Restores stdin to blocking mode. */
132
133 void
134 leave_non_blocking(void)
135 {
136         if (in_non_blocking_mode) {
137                 (void) fcntl(fileno(stdin), F_SETFL, 0);
138                 in_non_blocking_mode = 0;
139                 fatal_remove_cleanup((void (*) (void *)) leave_non_blocking, NULL);
140         }
141 }
142
143 /* Puts stdin terminal in non-blocking mode. */
144
145 void
146 enter_non_blocking(void)
147 {
148         in_non_blocking_mode = 1;
149         (void) fcntl(fileno(stdin), F_SETFL, O_NONBLOCK);
150         fatal_add_cleanup((void (*) (void *)) leave_non_blocking, NULL);
151 }
152
153 /*
154  * Signal handler for the window change signal (SIGWINCH).  This just sets a
155  * flag indicating that the window has changed.
156  */
157
158 void
159 window_change_handler(int sig)
160 {
161         received_window_change_signal = 1;
162         signal(SIGWINCH, window_change_handler);
163 }
164
165 /*
166  * Signal handler for signals that cause the program to terminate.  These
167  * signals must be trapped to restore terminal modes.
168  */
169
170 void
171 signal_handler(int sig)
172 {
173         if (in_raw_mode())
174                 leave_raw_mode();
175         if (in_non_blocking_mode)
176                 leave_non_blocking();
177         channel_stop_listening();
178         packet_close();
179         fatal("Killed by signal %d.", sig);
180 }
181
182 /*
183  * Returns current time in seconds from Jan 1, 1970 with the maximum
184  * available resolution.
185  */
186
187 double
188 get_current_time(void)
189 {
190         struct timeval tv;
191         gettimeofday(&tv, NULL);
192         return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
193 }
194
195 /*
196  * This is called when the interactive is entered.  This checks if there is
197  * an EOF coming on stdin.  We must check this explicitly, as select() does
198  * not appear to wake up when redirecting from /dev/null.
199  */
200
201 void
202 client_check_initial_eof_on_stdin(void)
203 {
204         int len;
205         char buf[1];
206
207         /*
208          * If standard input is to be "redirected from /dev/null", we simply
209          * mark that we have seen an EOF and send an EOF message to the
210          * server. Otherwise, we try to read a single character; it appears
211          * that for some files, such /dev/null, select() never wakes up for
212          * read for this descriptor, which means that we never get EOF.  This
213          * way we will get the EOF if stdin comes from /dev/null or similar.
214          */
215         if (stdin_null_flag) {
216                 /* Fake EOF on stdin. */
217                 debug("Sending eof.");
218                 stdin_eof = 1;
219                 packet_start(SSH_CMSG_EOF);
220                 packet_send();
221         } else {
222                 enter_non_blocking();
223
224                 /* Check for immediate EOF on stdin. */
225                 len = read(fileno(stdin), buf, 1);
226                 if (len == 0) {
227                         /* EOF.  Record that we have seen it and send EOF to server. */
228                         debug("Sending eof.");
229                         stdin_eof = 1;
230                         packet_start(SSH_CMSG_EOF);
231                         packet_send();
232                 } else if (len > 0) {
233                         /*
234                          * Got data.  We must store the data in the buffer,
235                          * and also process it as an escape character if
236                          * appropriate.
237                          */
238                         if ((u_char) buf[0] == escape_char)
239                                 escape_pending = 1;
240                         else
241                                 buffer_append(&stdin_buffer, buf, 1);
242                 }
243                 leave_non_blocking();
244         }
245 }
246
247
248 /*
249  * Make packets from buffered stdin data, and buffer them for sending to the
250  * connection.
251  */
252
253 void
254 client_make_packets_from_stdin_data(void)
255 {
256         u_int len;
257
258         /* Send buffered stdin data to the server. */
259         while (buffer_len(&stdin_buffer) > 0 &&
260                packet_not_very_much_data_to_write()) {
261                 len = buffer_len(&stdin_buffer);
262                 /* Keep the packets at reasonable size. */
263                 if (len > packet_get_maxsize())
264                         len = packet_get_maxsize();
265                 packet_start(SSH_CMSG_STDIN_DATA);
266                 packet_put_string(buffer_ptr(&stdin_buffer), len);
267                 packet_send();
268                 buffer_consume(&stdin_buffer, len);
269                 stdin_bytes += len;
270                 /* If we have a pending EOF, send it now. */
271                 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
272                         packet_start(SSH_CMSG_EOF);
273                         packet_send();
274                 }
275         }
276 }
277
278 /*
279  * Checks if the client window has changed, and sends a packet about it to
280  * the server if so.  The actual change is detected elsewhere (by a software
281  * interrupt on Unix); this just checks the flag and sends a message if
282  * appropriate.
283  */
284
285 void
286 client_check_window_change(void)
287 {
288         struct winsize ws;
289
290         if (! received_window_change_signal)
291                 return;
292         /** XXX race */
293         received_window_change_signal = 0;
294
295         if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
296                 return;
297
298         debug2("client_check_window_change: changed");
299
300         if (compat20) {
301                 channel_request_start(session_ident, "window-change", 0);
302                 packet_put_int(ws.ws_col);
303                 packet_put_int(ws.ws_row);
304                 packet_put_int(ws.ws_xpixel);
305                 packet_put_int(ws.ws_ypixel);
306                 packet_send();
307         } else {
308                 packet_start(SSH_CMSG_WINDOW_SIZE);
309                 packet_put_int(ws.ws_row);
310                 packet_put_int(ws.ws_col);
311                 packet_put_int(ws.ws_xpixel);
312                 packet_put_int(ws.ws_ypixel);
313                 packet_send();
314         }
315 }
316
317 /*
318  * Waits until the client can do something (some data becomes available on
319  * one of the file descriptors).
320  */
321
322 void
323 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
324     int *maxfdp, int rekeying)
325 {
326         /* Add any selections by the channel mechanism. */
327         channel_prepare_select(readsetp, writesetp, maxfdp, rekeying);
328
329         if (!compat20) {
330                 /* Read from the connection, unless our buffers are full. */
331                 if (buffer_len(&stdout_buffer) < buffer_high &&
332                     buffer_len(&stderr_buffer) < buffer_high &&
333                     channel_not_very_much_buffered_data())
334                         FD_SET(connection_in, *readsetp);
335                 /*
336                  * Read from stdin, unless we have seen EOF or have very much
337                  * buffered data to send to the server.
338                  */
339                 if (!stdin_eof && packet_not_very_much_data_to_write())
340                         FD_SET(fileno(stdin), *readsetp);
341
342                 /* Select stdout/stderr if have data in buffer. */
343                 if (buffer_len(&stdout_buffer) > 0)
344                         FD_SET(fileno(stdout), *writesetp);
345                 if (buffer_len(&stderr_buffer) > 0)
346                         FD_SET(fileno(stderr), *writesetp);
347         } else {
348                 FD_SET(connection_in, *readsetp);
349         }
350
351         /* Select server connection if have data to write to the server. */
352         if (packet_have_data_to_write())
353                 FD_SET(connection_out, *writesetp);
354
355         /*
356          * Wait for something to happen.  This will suspend the process until
357          * some selected descriptor can be read, written, or has some other
358          * event pending. Note: if you want to implement SSH_MSG_IGNORE
359          * messages to fool traffic analysis, this might be the place to do
360          * it: just have a random timeout for the select, and send a random
361          * SSH_MSG_IGNORE packet when the timeout expires.
362          */
363
364         if (select((*maxfdp)+1, *readsetp, *writesetp, NULL, NULL) < 0) {
365                 char buf[100];
366
367                 /*
368                  * We have to clear the select masks, because we return.
369                  * We have to return, because the mainloop checks for the flags
370                  * set by the signal handlers.
371                  */
372                 memset(*readsetp, 0, *maxfdp);
373                 memset(*writesetp, 0, *maxfdp);
374
375                 if (errno == EINTR)
376                         return;
377                 /* Note: we might still have data in the buffers. */
378                 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
379                 buffer_append(&stderr_buffer, buf, strlen(buf));
380                 quit_pending = 1;
381         }
382 }
383
384 void
385 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
386 {
387         struct winsize oldws, newws;
388
389         /* Flush stdout and stderr buffers. */
390         if (buffer_len(bout) > 0)
391                 atomicio(write, fileno(stdout), buffer_ptr(bout), buffer_len(bout));
392         if (buffer_len(berr) > 0)
393                 atomicio(write, fileno(stderr), buffer_ptr(berr), buffer_len(berr));
394
395         leave_raw_mode();
396
397         /*
398          * Free (and clear) the buffer to reduce the amount of data that gets
399          * written to swap.
400          */
401         buffer_free(bin);
402         buffer_free(bout);
403         buffer_free(berr);
404
405         /* Save old window size. */
406         ioctl(fileno(stdin), TIOCGWINSZ, &oldws);
407
408         /* Send the suspend signal to the program itself. */
409         kill(getpid(), SIGTSTP);
410
411         /* Check if the window size has changed. */
412         if (ioctl(fileno(stdin), TIOCGWINSZ, &newws) >= 0 &&
413             (oldws.ws_row != newws.ws_row ||
414              oldws.ws_col != newws.ws_col ||
415              oldws.ws_xpixel != newws.ws_xpixel ||
416              oldws.ws_ypixel != newws.ws_ypixel))
417                 received_window_change_signal = 1;
418
419         /* OK, we have been continued by the user. Reinitialize buffers. */
420         buffer_init(bin);
421         buffer_init(bout);
422         buffer_init(berr);
423
424         enter_raw_mode();
425 }
426
427 void
428 client_process_net_input(fd_set * readset)
429 {
430         int len;
431         char buf[8192];
432
433         /*
434          * Read input from the server, and add any such data to the buffer of
435          * the packet subsystem.
436          */
437         if (FD_ISSET(connection_in, readset)) {
438                 /* Read as much as possible. */
439                 len = read(connection_in, buf, sizeof(buf));
440                 if (len == 0) {
441                         /* Received EOF.  The remote host has closed the connection. */
442                         snprintf(buf, sizeof buf, "Connection to %.300s closed by remote host.\r\n",
443                                  host);
444                         buffer_append(&stderr_buffer, buf, strlen(buf));
445                         quit_pending = 1;
446                         return;
447                 }
448                 /*
449                  * There is a kernel bug on Solaris that causes select to
450                  * sometimes wake up even though there is no data available.
451                  */
452                 if (len < 0 && (errno == EAGAIN || errno == EINTR))
453                         len = 0;
454
455                 if (len < 0) {
456                         /* An error has encountered.  Perhaps there is a network problem. */
457                         snprintf(buf, sizeof buf, "Read from remote host %.300s: %.100s\r\n",
458                                  host, strerror(errno));
459                         buffer_append(&stderr_buffer, buf, strlen(buf));
460                         quit_pending = 1;
461                         return;
462                 }
463                 packet_process_incoming(buf, len);
464         }
465 }
466
467 /* process the characters one by one */
468 int
469 process_escapes(Buffer *bin, Buffer *bout, Buffer *berr, char *buf, int len)
470 {
471         char string[1024];
472         pid_t pid;
473         int bytes = 0;
474         u_int i;
475         u_char ch;
476         char *s;
477
478         for (i = 0; i < len; i++) {
479                 /* Get one character at a time. */
480                 ch = buf[i];
481
482                 if (escape_pending) {
483                         /* We have previously seen an escape character. */
484                         /* Clear the flag now. */
485                         escape_pending = 0;
486
487                         /* Process the escaped character. */
488                         switch (ch) {
489                         case '.':
490                                 /* Terminate the connection. */
491                                 snprintf(string, sizeof string, "%c.\r\n", escape_char);
492                                 buffer_append(berr, string, strlen(string));
493
494                                 quit_pending = 1;
495                                 return -1;
496
497                         case 'Z' - 64:
498                                 /* Suspend the program. */
499                                 /* Print a message to that effect to the user. */
500                                 snprintf(string, sizeof string, "%c^Z [suspend ssh]\r\n", escape_char);
501                                 buffer_append(berr, string, strlen(string));
502
503                                 /* Restore terminal modes and suspend. */
504                                 client_suspend_self(bin, bout, berr);
505
506                                 /* We have been continued. */
507                                 continue;
508
509                         case 'R':
510                                 if (compat20) {
511                                         if (datafellows & SSH_BUG_NOREKEY)
512                                                 log("Server does not support re-keying");
513                                         else
514                                                 need_rekeying = 1;
515                                 }
516                                 continue;
517
518                         case '&':
519                                 /* XXX does not work yet with proto 2 */
520                                 if (compat20)
521                                         continue;
522                                 /*
523                                  * Detach the program (continue to serve connections,
524                                  * but put in background and no more new connections).
525                                  */
526                                 if (!stdin_eof) {
527                                         /*
528                                          * Sending SSH_CMSG_EOF alone does not always appear
529                                          * to be enough.  So we try to send an EOF character
530                                          * first.
531                                          */
532                                         packet_start(SSH_CMSG_STDIN_DATA);
533                                         packet_put_string("\004", 1);
534                                         packet_send();
535                                         /* Close stdin. */
536                                         stdin_eof = 1;
537                                         if (buffer_len(bin) == 0) {
538                                                 packet_start(SSH_CMSG_EOF);
539                                                 packet_send();
540                                         }
541                                 }
542                                 /* Restore tty modes. */
543                                 leave_raw_mode();
544
545                                 /* Stop listening for new connections. */
546                                 channel_stop_listening();
547
548                                 printf("%c& [backgrounded]\n", escape_char);
549
550                                 /* Fork into background. */
551                                 pid = fork();
552                                 if (pid < 0) {
553                                         error("fork: %.100s", strerror(errno));
554                                         continue;
555                                 }
556                                 if (pid != 0) { /* This is the parent. */
557                                         /* The parent just exits. */
558                                         exit(0);
559                                 }
560                                 /* The child continues serving connections. */
561                                 continue; /*XXX ? */
562
563                         case '?':
564                                 snprintf(string, sizeof string,
565 "%c?\r\n\
566 Supported escape sequences:\r\n\
567 ~.  - terminate connection\r\n\
568 ~^Z - suspend ssh\r\n\
569 ~#  - list forwarded connections\r\n\
570 ~&  - background ssh (when waiting for connections to terminate)\r\n\
571 ~?  - this message\r\n\
572 ~~  - send the escape character by typing it twice\r\n\
573 (Note that escapes are only recognized immediately after newline.)\r\n",
574                                          escape_char);
575                                 buffer_append(berr, string, strlen(string));
576                                 continue;
577
578                         case '#':
579                                 snprintf(string, sizeof string, "%c#\r\n", escape_char);
580                                 buffer_append(berr, string, strlen(string));
581                                 s = channel_open_message();
582                                 buffer_append(berr, s, strlen(s));
583                                 xfree(s);
584                                 continue;
585
586                         default:
587                                 if (ch != escape_char) {
588                                         buffer_put_char(bin, escape_char);
589                                         bytes++;
590                                 }
591                                 /* Escaped characters fall through here */
592                                 break;
593                         }
594                 } else {
595                         /*
596                          * The previous character was not an escape char. Check if this
597                          * is an escape.
598                          */
599                         if (last_was_cr && ch == escape_char) {
600                                 /* It is. Set the flag and continue to next character. */
601                                 escape_pending = 1;
602                                 continue;
603                         }
604                 }
605
606                 /*
607                  * Normal character.  Record whether it was a newline,
608                  * and append it to the buffer.
609                  */
610                 last_was_cr = (ch == '\r' || ch == '\n');
611                 buffer_put_char(bin, ch);
612                 bytes++;
613         }
614         return bytes;
615 }
616
617 void
618 client_process_input(fd_set * readset)
619 {
620         int len;
621         char buf[8192];
622
623         /* Read input from stdin. */
624         if (FD_ISSET(fileno(stdin), readset)) {
625                 /* Read as much as possible. */
626                 len = read(fileno(stdin), buf, sizeof(buf));
627                 if (len <= 0) {
628                         /*
629                          * Received EOF or error.  They are treated
630                          * similarly, except that an error message is printed
631                          * if it was an error condition.
632                          */
633                         if (len < 0) {
634                                 snprintf(buf, sizeof buf, "read: %.100s\r\n", strerror(errno));
635                                 buffer_append(&stderr_buffer, buf, strlen(buf));
636                         }
637                         /* Mark that we have seen EOF. */
638                         stdin_eof = 1;
639                         /*
640                          * Send an EOF message to the server unless there is
641                          * data in the buffer.  If there is data in the
642                          * buffer, no message will be sent now.  Code
643                          * elsewhere will send the EOF when the buffer
644                          * becomes empty if stdin_eof is set.
645                          */
646                         if (buffer_len(&stdin_buffer) == 0) {
647                                 packet_start(SSH_CMSG_EOF);
648                                 packet_send();
649                         }
650                 } else if (escape_char == -1) {
651                         /*
652                          * Normal successful read, and no escape character.
653                          * Just append the data to buffer.
654                          */
655                         buffer_append(&stdin_buffer, buf, len);
656                 } else {
657                         /*
658                          * Normal, successful read.  But we have an escape character
659                          * and have to process the characters one by one.
660                          */
661                         if (process_escapes(&stdin_buffer, &stdout_buffer,
662                             &stderr_buffer, buf, len) == -1)
663                                 return;
664                 }
665         }
666 }
667
668 void
669 client_process_output(fd_set * writeset)
670 {
671         int len;
672         char buf[100];
673
674         /* Write buffered output to stdout. */
675         if (FD_ISSET(fileno(stdout), writeset)) {
676                 /* Write as much data as possible. */
677                 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
678                     buffer_len(&stdout_buffer));
679                 if (len <= 0) {
680                         if (errno == EAGAIN)
681                                 len = 0;
682                         else {
683                                 /*
684                                  * An error or EOF was encountered.  Put an
685                                  * error message to stderr buffer.
686                                  */
687                                 snprintf(buf, sizeof buf, "write stdout: %.50s\r\n", strerror(errno));
688                                 buffer_append(&stderr_buffer, buf, strlen(buf));
689                                 quit_pending = 1;
690                                 return;
691                         }
692                 }
693                 /* Consume printed data from the buffer. */
694                 buffer_consume(&stdout_buffer, len);
695                 stdout_bytes += len;
696         }
697         /* Write buffered output to stderr. */
698         if (FD_ISSET(fileno(stderr), writeset)) {
699                 /* Write as much data as possible. */
700                 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
701                     buffer_len(&stderr_buffer));
702                 if (len <= 0) {
703                         if (errno == EAGAIN)
704                                 len = 0;
705                         else {
706                                 /* EOF or error, but can't even print error message. */
707                                 quit_pending = 1;
708                                 return;
709                         }
710                 }
711                 /* Consume printed characters from the buffer. */
712                 buffer_consume(&stderr_buffer, len);
713                 stderr_bytes += len;
714         }
715 }
716
717 /*
718  * Get packets from the connection input buffer, and process them as long as
719  * there are packets available.
720  *
721  * Any unknown packets received during the actual
722  * session cause the session to terminate.  This is
723  * intended to make debugging easier since no
724  * confirmations are sent.  Any compatible protocol
725  * extensions must be negotiated during the
726  * preparatory phase.
727  */
728
729 void
730 client_process_buffered_input_packets(void)
731 {
732         dispatch_run(DISPATCH_NONBLOCK, &quit_pending, compat20 ? xxx_kex : NULL);
733 }
734
735 /* scan buf[] for '~' before sending data to the peer */
736
737 int
738 simple_escape_filter(Channel *c, char *buf, int len)
739 {
740         /* XXX we assume c->extended is writeable */
741         return process_escapes(&c->input, &c->output, &c->extended, buf, len);
742 }
743
744 void
745 client_channel_closed(int id, void *arg)
746 {
747         if (id != session_ident)
748                 error("client_channel_closed: id %d != session_ident %d",
749                     id, session_ident);
750         session_closed = 1;
751         if (in_raw_mode())
752                 leave_raw_mode();
753 }
754
755 /*
756  * Implements the interactive session with the server.  This is called after
757  * the user has been authenticated, and a command has been started on the
758  * remote host.  If escape_char != -1, it is the character used as an escape
759  * character for terminating or suspending the session.
760  */
761
762 int
763 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
764 {
765         fd_set *readset = NULL, *writeset = NULL;
766         double start_time, total_time;
767         int max_fd = 0, len, rekeying = 0;
768         char buf[100];
769
770         debug("Entering interactive session.");
771
772         start_time = get_current_time();
773
774         /* Initialize variables. */
775         escape_pending = 0;
776         last_was_cr = 1;
777         exit_status = -1;
778         stdin_eof = 0;
779         buffer_high = 64 * 1024;
780         connection_in = packet_get_connection_in();
781         connection_out = packet_get_connection_out();
782         max_fd = MAX(connection_in, connection_out);
783
784         if (!compat20) {
785                 max_fd = MAX(max_fd, fileno(stdin));
786                 max_fd = MAX(max_fd, fileno(stdout));
787                 max_fd = MAX(max_fd, fileno(stderr));
788         }
789         stdin_bytes = 0;
790         stdout_bytes = 0;
791         stderr_bytes = 0;
792         quit_pending = 0;
793         escape_char = escape_char_arg;
794
795         /* Initialize buffers. */
796         buffer_init(&stdin_buffer);
797         buffer_init(&stdout_buffer);
798         buffer_init(&stderr_buffer);
799
800         client_init_dispatch();
801
802         /* Set signal handlers to restore non-blocking mode.  */
803         signal(SIGINT, signal_handler);
804         signal(SIGQUIT, signal_handler);
805         signal(SIGTERM, signal_handler);
806         signal(SIGPIPE, SIG_IGN);
807         if (have_pty)
808                 signal(SIGWINCH, window_change_handler);
809
810         if (have_pty)
811                 enter_raw_mode();
812
813         if (compat20) {
814                 session_ident = ssh2_chan_id;
815                 if (escape_char != -1)
816                         channel_register_filter(session_ident,
817                             simple_escape_filter);
818                 if (session_ident != -1)
819                         channel_register_cleanup(session_ident,
820                             client_channel_closed);
821         } else {
822                 /* Check if we should immediately send eof on stdin. */
823                 client_check_initial_eof_on_stdin();
824         }
825
826         /* Main loop of the client for the interactive session mode. */
827         while (!quit_pending) {
828
829                 /* Process buffered packets sent by the server. */
830                 client_process_buffered_input_packets();
831
832                 if (compat20 && session_closed && !channel_still_open())
833                         break;
834
835                 rekeying = (xxx_kex != NULL && !xxx_kex->done);
836
837                 if (rekeying) {
838                         debug("rekeying in progress");
839                 } else {
840                         /*
841                          * Make packets of buffered stdin data, and buffer
842                          * them for sending to the server.
843                          */
844                         if (!compat20)
845                                 client_make_packets_from_stdin_data();
846
847                         /*
848                          * Make packets from buffered channel data, and
849                          * enqueue them for sending to the server.
850                          */
851                         if (packet_not_very_much_data_to_write())
852                                 channel_output_poll();
853
854                         /*
855                          * Check if the window size has changed, and buffer a
856                          * message about it to the server if so.
857                          */
858                         client_check_window_change();
859
860                         if (quit_pending)
861                                 break;
862                 }
863                 /*
864                  * Wait until we have something to do (something becomes
865                  * available on one of the descriptors).
866                  */
867                 client_wait_until_can_do_something(&readset, &writeset,
868                     &max_fd, rekeying);
869
870                 if (quit_pending)
871                         break;
872
873                 /* Do channel operations unless rekeying in progress. */
874                 if (!rekeying) {
875                         channel_after_select(readset, writeset);
876
877                         if (need_rekeying) {
878                                 debug("user requests rekeying");
879                                 xxx_kex->done = 0;
880                                 kex_send_kexinit(xxx_kex);
881                                 need_rekeying = 0;
882                         }
883                 }
884
885                 /* Buffer input from the connection.  */
886                 client_process_net_input(readset);
887
888                 if (quit_pending)
889                         break;
890
891                 if (!compat20) {
892                         /* Buffer data from stdin */
893                         client_process_input(readset);
894                         /*
895                          * Process output to stdout and stderr.  Output to
896                          * the connection is processed elsewhere (above).
897                          */
898                         client_process_output(writeset);
899                 }
900
901                 /* Send as much buffered packet data as possible to the sender. */
902                 if (FD_ISSET(connection_out, writeset))
903                         packet_write_poll();
904         }
905         if (readset)
906                 xfree(readset);
907         if (writeset)
908                 xfree(writeset);
909
910         /* Terminate the session. */
911
912         /* Stop watching for window change. */
913         if (have_pty)
914                 signal(SIGWINCH, SIG_DFL);
915
916         /* Stop listening for connections. */
917         channel_stop_listening();
918
919         /*
920          * In interactive mode (with pseudo tty) display a message indicating
921          * that the connection has been closed.
922          */
923         if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
924                 snprintf(buf, sizeof buf, "Connection to %.64s closed.\r\n", host);
925                 buffer_append(&stderr_buffer, buf, strlen(buf));
926         }
927         /* Output any buffered data for stdout. */
928         while (buffer_len(&stdout_buffer) > 0) {
929                 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
930                     buffer_len(&stdout_buffer));
931                 if (len <= 0) {
932                         error("Write failed flushing stdout buffer.");
933                         break;
934                 }
935                 buffer_consume(&stdout_buffer, len);
936                 stdout_bytes += len;
937         }
938
939         /* Output any buffered data for stderr. */
940         while (buffer_len(&stderr_buffer) > 0) {
941                 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
942                     buffer_len(&stderr_buffer));
943                 if (len <= 0) {
944                         error("Write failed flushing stderr buffer.");
945                         break;
946                 }
947                 buffer_consume(&stderr_buffer, len);
948                 stderr_bytes += len;
949         }
950
951         if (have_pty)
952                 leave_raw_mode();
953
954         /* Clear and free any buffers. */
955         memset(buf, 0, sizeof(buf));
956         buffer_free(&stdin_buffer);
957         buffer_free(&stdout_buffer);
958         buffer_free(&stderr_buffer);
959
960         /* Report bytes transferred, and transfer rates. */
961         total_time = get_current_time() - start_time;
962         debug("Transferred: stdin %lu, stdout %lu, stderr %lu bytes in %.1f seconds",
963               stdin_bytes, stdout_bytes, stderr_bytes, total_time);
964         if (total_time > 0)
965                 debug("Bytes per second: stdin %.1f, stdout %.1f, stderr %.1f",
966                       stdin_bytes / total_time, stdout_bytes / total_time,
967                       stderr_bytes / total_time);
968
969         /* Return the exit status of the program. */
970         debug("Exit status %d", exit_status);
971         return exit_status;
972 }
973
974 /*********/
975
976 void
977 client_input_stdout_data(int type, int plen, void *ctxt)
978 {
979         u_int data_len;
980         char *data = packet_get_string(&data_len);
981         packet_integrity_check(plen, 4 + data_len, type);
982         buffer_append(&stdout_buffer, data, data_len);
983         memset(data, 0, data_len);
984         xfree(data);
985 }
986 void
987 client_input_stderr_data(int type, int plen, void *ctxt)
988 {
989         u_int data_len;
990         char *data = packet_get_string(&data_len);
991         packet_integrity_check(plen, 4 + data_len, type);
992         buffer_append(&stderr_buffer, data, data_len);
993         memset(data, 0, data_len);
994         xfree(data);
995 }
996 void
997 client_input_exit_status(int type, int plen, void *ctxt)
998 {
999         packet_integrity_check(plen, 4, type);
1000         exit_status = packet_get_int();
1001         /* Acknowledge the exit. */
1002         packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1003         packet_send();
1004         /*
1005          * Must wait for packet to be sent since we are
1006          * exiting the loop.
1007          */
1008         packet_write_wait();
1009         /* Flag that we want to exit. */
1010         quit_pending = 1;
1011 }
1012
1013 Channel *
1014 client_request_forwarded_tcpip(const char *request_type, int rchan)
1015 {
1016         Channel* c = NULL;
1017         char *listen_address, *originator_address;
1018         int listen_port, originator_port;
1019         int sock, newch;
1020
1021         /* Get rest of the packet */
1022         listen_address = packet_get_string(NULL);
1023         listen_port = packet_get_int();
1024         originator_address = packet_get_string(NULL);
1025         originator_port = packet_get_int();
1026         packet_done();
1027
1028         debug("client_request_forwarded_tcpip: listen %s port %d, originator %s port %d",
1029             listen_address, listen_port, originator_address, originator_port);
1030
1031         sock = channel_connect_by_listen_adress(listen_port);
1032         if (sock >= 0) {
1033                 newch = channel_new("forwarded-tcpip",
1034                     SSH_CHANNEL_CONNECTING, sock, sock, -1,
1035                     CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_WINDOW_DEFAULT, 0,
1036                     xstrdup(originator_address), 1);
1037                 c = channel_lookup(newch);
1038         }
1039         xfree(originator_address);
1040         xfree(listen_address);
1041         return c;
1042 }
1043
1044 Channel*
1045 client_request_x11(const char *request_type, int rchan)
1046 {
1047         Channel *c = NULL;
1048         char *originator;
1049         int originator_port;
1050         int sock, newch;
1051
1052         if (!options.forward_x11) {
1053                 error("Warning: ssh server tried X11 forwarding.");
1054                 error("Warning: this is probably a break in attempt by a malicious server.");
1055                 return NULL;
1056         }
1057         originator = packet_get_string(NULL);
1058         if (datafellows & SSH_BUG_X11FWD) {
1059                 debug2("buggy server: x11 request w/o originator_port");
1060                 originator_port = 0;
1061         } else {
1062                 originator_port = packet_get_int();
1063         }
1064         packet_done();
1065         /* XXX check permission */
1066         debug("client_request_x11: request from %s %d", originator,
1067             originator_port);
1068         sock = x11_connect_display();
1069         if (sock >= 0) {
1070                 newch = channel_new("x11",
1071                     SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1072                     CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0,
1073                     xstrdup("x11"), 1);
1074                 c = channel_lookup(newch);
1075         }
1076         xfree(originator);
1077         return c;
1078 }
1079
1080 Channel*
1081 client_request_agent(const char *request_type, int rchan)
1082 {
1083         Channel *c = NULL;
1084         int sock, newch;
1085
1086         if (!options.forward_agent) {
1087                 error("Warning: ssh server tried agent forwarding.");
1088                 error("Warning: this is probably a break in attempt by a malicious server.");
1089                 return NULL;
1090         }
1091         sock =  ssh_get_authentication_socket();
1092         if (sock >= 0) {
1093                 newch = channel_new("authentication agent connection",
1094                     SSH_CHANNEL_OPEN, sock, sock, -1,
1095                     CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_WINDOW_DEFAULT, 0,
1096                     xstrdup("authentication agent connection"), 1);
1097                 c = channel_lookup(newch);
1098         }
1099         return c;
1100 }
1101
1102 /* XXXX move to generic input handler */
1103 void
1104 client_input_channel_open(int type, int plen, void *ctxt)
1105 {
1106         Channel *c = NULL;
1107         char *ctype;
1108         u_int len;
1109         int rchan;
1110         int rmaxpack;
1111         int rwindow;
1112
1113         ctype = packet_get_string(&len);
1114         rchan = packet_get_int();
1115         rwindow = packet_get_int();
1116         rmaxpack = packet_get_int();
1117
1118         debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1119             ctype, rchan, rwindow, rmaxpack);
1120
1121         if (strcmp(ctype, "forwarded-tcpip") == 0) {
1122                 c = client_request_forwarded_tcpip(ctype, rchan);
1123         } else if (strcmp(ctype, "x11") == 0) {
1124                 c = client_request_x11(ctype, rchan);
1125         } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1126                 c = client_request_agent(ctype, rchan);
1127         }
1128 /* XXX duplicate : */
1129         if (c != NULL) {
1130                 debug("confirm %s", ctype);
1131                 c->remote_id = rchan;
1132                 c->remote_window = rwindow;
1133                 c->remote_maxpacket = rmaxpack;
1134
1135                 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1136                 packet_put_int(c->remote_id);
1137                 packet_put_int(c->self);
1138                 packet_put_int(c->local_window);
1139                 packet_put_int(c->local_maxpacket);
1140                 packet_send();
1141         } else {
1142                 debug("failure %s", ctype);
1143                 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1144                 packet_put_int(rchan);
1145                 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1146                 packet_put_cstring("bla bla");
1147                 packet_put_cstring("");
1148                 packet_send();
1149         }
1150         xfree(ctype);
1151 }
1152 void
1153 client_input_channel_req(int type, int plen, void *ctxt)
1154 {
1155         Channel *c = NULL;
1156         int id, reply, success = 0;
1157         char *rtype;
1158
1159         id = packet_get_int();
1160         rtype = packet_get_string(NULL);
1161         reply = packet_get_char();
1162
1163         debug("client_input_channel_req: channel %d rtype %s reply %d",
1164             id, rtype, reply);
1165
1166         if (session_ident == -1) {
1167                 error("client_input_channel_req: no channel %d", session_ident);
1168         } else if (id != session_ident) {
1169                 error("client_input_channel_req: channel %d: wrong channel: %d",
1170                     session_ident, id);
1171         }
1172         c = channel_lookup(id);
1173         if (c == NULL) {
1174                 error("client_input_channel_req: channel %d: unknown channel", id);
1175         } else if (strcmp(rtype, "exit-status") == 0) {
1176                 success = 1;
1177                 exit_status = packet_get_int();
1178                 packet_done();
1179         }
1180         if (reply) {
1181                 packet_start(success ?
1182                     SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1183                 packet_put_int(c->remote_id);
1184                 packet_send();
1185         }
1186         xfree(rtype);
1187 }
1188
1189 void
1190 client_init_dispatch_20(void)
1191 {
1192         dispatch_init(&dispatch_protocol_error);
1193         dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
1194         dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
1195         dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
1196         dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1197         dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
1198         dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1199         dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1200         dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
1201         dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1202
1203         /* rekeying */
1204         dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1205 }
1206 void
1207 client_init_dispatch_13(void)
1208 {
1209         dispatch_init(NULL);
1210         dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
1211         dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
1212         dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
1213         dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1214         dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1215         dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
1216         dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
1217         dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
1218         dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
1219
1220         dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
1221             &auth_input_open_request : &deny_input_open);
1222         dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
1223             &x11_input_open : &deny_input_open);
1224 }
1225 void
1226 client_init_dispatch_15(void)
1227 {
1228         client_init_dispatch_13();
1229         dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
1230         dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
1231 }
1232 void
1233 client_init_dispatch(void)
1234 {
1235         if (compat20)
1236                 client_init_dispatch_20();
1237         else if (compat13)
1238                 client_init_dispatch_13();
1239         else
1240                 client_init_dispatch_15();
1241 }
This page took 0.154825 seconds and 5 git commands to generate.