turn down some warnings
[openssh.git] / clientloop.c
1 /* $OpenBSD: clientloop.c,v 1.231 2011/01/16 12:05:59 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * The main loop for the interactive session (client side).
7  *
8  * As far as I am concerned, the code I have written for this software
9  * can be used freely for any purpose.  Any derived versions of this
10  * software must be clearly marked as such, and if the derived work is
11  * incompatible with the protocol description in the RFC file, it must be
12  * called by a name other than "ssh" or "Secure Shell".
13  *
14  *
15  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  *
37  *
38  * SSH2 support added by Markus Friedl.
39  * Copyright (c) 1999, 2000, 2001 Markus Friedl.  All rights reserved.
40  *
41  * Redistribution and use in source and binary forms, with or without
42  * modification, are permitted provided that the following conditions
43  * are met:
44  * 1. Redistributions of source code must retain the above copyright
45  *    notice, this list of conditions and the following disclaimer.
46  * 2. Redistributions in binary form must reproduce the above copyright
47  *    notice, this list of conditions and the following disclaimer in the
48  *    documentation and/or other materials provided with the distribution.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
51  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
52  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
53  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
54  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
55  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
56  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
57  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
58  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
59  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
60  */
61
62 #include "includes.h"
63
64 #include <sys/types.h>
65 #include <sys/ioctl.h>
66 #include <sys/param.h>
67 #ifdef HAVE_SYS_STAT_H
68 # include <sys/stat.h>
69 #endif
70 #ifdef HAVE_SYS_TIME_H
71 # include <sys/time.h>
72 #endif
73 #include <sys/socket.h>
74
75 #include <ctype.h>
76 #include <errno.h>
77 #ifdef HAVE_PATHS_H
78 #include <paths.h>
79 #endif
80 #include <signal.h>
81 #include <stdarg.h>
82 #include <stdio.h>
83 #include <stdlib.h>
84 #include <string.h>
85 #include <termios.h>
86 #include <pwd.h>
87 #include <unistd.h>
88
89 #include "openbsd-compat/sys-queue.h"
90 #include "xmalloc.h"
91 #include "ssh.h"
92 #include "ssh1.h"
93 #include "ssh2.h"
94 #include "packet.h"
95 #include "buffer.h"
96 #include "compat.h"
97 #include "channels.h"
98 #include "dispatch.h"
99 #include "key.h"
100 #include "cipher.h"
101 #include "kex.h"
102 #include "log.h"
103 #include "readconf.h"
104 #include "clientloop.h"
105 #include "sshconnect.h"
106 #include "authfd.h"
107 #include "atomicio.h"
108 #include "sshpty.h"
109 #include "misc.h"
110 #include "match.h"
111 #include "msg.h"
112 #include "roaming.h"
113
114 #ifdef GSSAPI
115 #include "ssh-gss.h"
116 #endif
117
118 /* import options */
119 extern Options options;
120
121 /* Flag indicating that stdin should be redirected from /dev/null. */
122 extern int stdin_null_flag;
123
124 /* Flag indicating that no shell has been requested */
125 extern int no_shell_flag;
126
127 /* Control socket */
128 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
129
130 /*
131  * Name of the host we are connecting to.  This is the name given on the
132  * command line, or the HostName specified for the user-supplied name in a
133  * configuration file.
134  */
135 extern char *host;
136
137 /* Force TTY allocation */
138 extern int force_tty_flag;
139
140 /*
141  * Flag to indicate that we have received a window change signal which has
142  * not yet been processed.  This will cause a message indicating the new
143  * window size to be sent to the server a little later.  This is volatile
144  * because this is updated in a signal handler.
145  */
146 static volatile sig_atomic_t received_window_change_signal = 0;
147 static volatile sig_atomic_t received_signal = 0;
148
149 /* Flag indicating whether the user's terminal is in non-blocking mode. */
150 static int in_non_blocking_mode = 0;
151
152 /* Time when backgrounded control master using ControlPersist should exit */
153 static time_t control_persist_exit_time = 0;
154
155 /* Common data for the client loop code. */
156 volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
157 static int escape_char1;        /* Escape character. (proto1 only) */
158 static int escape_pending1;     /* Last character was an escape (proto1 only) */
159 static int last_was_cr;         /* Last character was a newline. */
160 static int exit_status;         /* Used to store the command exit status. */
161 static int stdin_eof;           /* EOF has been encountered on stderr. */
162 static Buffer stdin_buffer;     /* Buffer for stdin data. */
163 static Buffer stdout_buffer;    /* Buffer for stdout data. */
164 static Buffer stderr_buffer;    /* Buffer for stderr data. */
165 static u_int buffer_high;       /* Soft max buffer size. */
166 static int connection_in;       /* Connection to server (input). */
167 static int connection_out;      /* Connection to server (output). */
168 static int need_rekeying;       /* Set to non-zero if rekeying is requested. */
169 static int session_closed;      /* In SSH2: login session closed. */
170 static int x11_refuse_time;     /* If >0, refuse x11 opens after this time. */
171
172 static void client_init_dispatch(void);
173 int     session_ident = -1;
174
175 int     session_resumed = 0;
176
177 /* Track escape per proto2 channel */
178 struct escape_filter_ctx {
179         int escape_pending;
180         int escape_char;
181 };
182
183 /* Context for channel confirmation replies */
184 struct channel_reply_ctx {
185         const char *request_type;
186         int id, do_close;
187 };
188
189 /* Global request success/failure callbacks */
190 struct global_confirm {
191         TAILQ_ENTRY(global_confirm) entry;
192         global_confirm_cb *cb;
193         void *ctx;
194         int ref_count;
195 };
196 TAILQ_HEAD(global_confirms, global_confirm);
197 static struct global_confirms global_confirms =
198     TAILQ_HEAD_INITIALIZER(global_confirms);
199
200 /*XXX*/
201 extern Kex *xxx_kex;
202
203 void ssh_process_session2_setup(int, int, int, Buffer *);
204
205 /* Restores stdin to blocking mode. */
206
207 static void
208 leave_non_blocking(void)
209 {
210         if (in_non_blocking_mode) {
211                 unset_nonblock(fileno(stdin));
212                 in_non_blocking_mode = 0;
213         }
214 }
215
216 /* Puts stdin terminal in non-blocking mode. */
217
218 static void
219 enter_non_blocking(void)
220 {
221         in_non_blocking_mode = 1;
222         set_nonblock(fileno(stdin));
223 }
224
225 /*
226  * Signal handler for the window change signal (SIGWINCH).  This just sets a
227  * flag indicating that the window has changed.
228  */
229 /*ARGSUSED */
230 static void
231 window_change_handler(int sig)
232 {
233         received_window_change_signal = 1;
234         signal(SIGWINCH, window_change_handler);
235 }
236
237 /*
238  * Signal handler for signals that cause the program to terminate.  These
239  * signals must be trapped to restore terminal modes.
240  */
241 /*ARGSUSED */
242 static void
243 signal_handler(int sig)
244 {
245         received_signal = sig;
246         quit_pending = 1;
247 }
248
249 /*
250  * Returns current time in seconds from Jan 1, 1970 with the maximum
251  * available resolution.
252  */
253
254 static double
255 get_current_time(void)
256 {
257         struct timeval tv;
258         gettimeofday(&tv, NULL);
259         return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
260 }
261
262 /*
263  * Sets control_persist_exit_time to the absolute time when the
264  * backgrounded control master should exit due to expiry of the
265  * ControlPersist timeout.  Sets it to 0 if we are not a backgrounded
266  * control master process, or if there is no ControlPersist timeout.
267  */
268 static void
269 set_control_persist_exit_time(void)
270 {
271         if (muxserver_sock == -1 || !options.control_persist
272             || options.control_persist_timeout == 0)
273                 /* not using a ControlPersist timeout */
274                 control_persist_exit_time = 0;
275         else if (channel_still_open()) {
276                 /* some client connections are still open */
277                 if (control_persist_exit_time > 0)
278                         debug2("%s: cancel scheduled exit", __func__);
279                 control_persist_exit_time = 0;
280         } else if (control_persist_exit_time <= 0) {
281                 /* a client connection has recently closed */
282                 control_persist_exit_time = time(NULL) +
283                         (time_t)options.control_persist_timeout;
284                 debug2("%s: schedule exit in %d seconds", __func__,
285                     options.control_persist_timeout);
286         }
287         /* else we are already counting down to the timeout */
288 }
289
290 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
291 void
292 client_x11_get_proto(const char *display, const char *xauth_path,
293     u_int trusted, u_int timeout, char **_proto, char **_data)
294 {
295         char cmd[1024];
296         char line[512];
297         char xdisplay[512];
298         static char proto[512], data[512];
299         FILE *f;
300         int got_data = 0, generated = 0, do_unlink = 0, i;
301         char *xauthdir, *xauthfile;
302         struct stat st;
303         u_int now;
304
305         xauthdir = xauthfile = NULL;
306         *_proto = proto;
307         *_data = data;
308         proto[0] = data[0] = '\0';
309
310         if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
311                 debug("No xauth program.");
312         } else {
313                 if (display == NULL) {
314                         debug("x11_get_proto: DISPLAY not set");
315                         return;
316                 }
317                 /*
318                  * Handle FamilyLocal case where $DISPLAY does
319                  * not match an authorization entry.  For this we
320                  * just try "xauth list unix:displaynum.screennum".
321                  * XXX: "localhost" match to determine FamilyLocal
322                  *      is not perfect.
323                  */
324                 if (strncmp(display, "localhost:", 10) == 0) {
325                         snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
326                             display + 10);
327                         display = xdisplay;
328                 }
329                 if (trusted == 0) {
330                         xauthdir = xmalloc(MAXPATHLEN);
331                         xauthfile = xmalloc(MAXPATHLEN);
332                         mktemp_proto(xauthdir, MAXPATHLEN);
333                         if (mkdtemp(xauthdir) != NULL) {
334                                 do_unlink = 1;
335                                 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
336                                     xauthdir);
337                                 snprintf(cmd, sizeof(cmd),
338                                     "%s -f %s generate %s " SSH_X11_PROTO
339                                     " untrusted timeout %u 2>" _PATH_DEVNULL,
340                                     xauth_path, xauthfile, display, timeout);
341                                 debug2("x11_get_proto: %s", cmd);
342                                 if (system(cmd) == 0)
343                                         generated = 1;
344                                 if (x11_refuse_time == 0) {
345                                         now = time(NULL) + 1;
346                                         if (UINT_MAX - timeout < now)
347                                                 x11_refuse_time = UINT_MAX;
348                                         else
349                                                 x11_refuse_time = now + timeout;
350                                 }
351                         }
352                 }
353
354                 /*
355                  * When in untrusted mode, we read the cookie only if it was
356                  * successfully generated as an untrusted one in the step
357                  * above.
358                  */
359                 if (trusted || generated) {
360                         snprintf(cmd, sizeof(cmd),
361                             "%s %s%s list %s 2>" _PATH_DEVNULL,
362                             xauth_path,
363                             generated ? "-f " : "" ,
364                             generated ? xauthfile : "",
365                             display);
366                         debug2("x11_get_proto: %s", cmd);
367                         f = popen(cmd, "r");
368                         if (f && fgets(line, sizeof(line), f) &&
369                             sscanf(line, "%*s %511s %511s", proto, data) == 2)
370                                 got_data = 1;
371                         if (f)
372                                 pclose(f);
373                 } else
374                         error("Warning: untrusted X11 forwarding setup failed: "
375                             "xauth key data not generated");
376         }
377
378         if (do_unlink) {
379                 unlink(xauthfile);
380                 rmdir(xauthdir);
381         }
382         if (xauthdir)
383                 xfree(xauthdir);
384         if (xauthfile)
385                 xfree(xauthfile);
386
387         /*
388          * If we didn't get authentication data, just make up some
389          * data.  The forwarding code will check the validity of the
390          * response anyway, and substitute this data.  The X11
391          * server, however, will ignore this fake data and use
392          * whatever authentication mechanisms it was using otherwise
393          * for the local connection.
394          */
395         if (!got_data) {
396                 u_int32_t rnd = 0;
397
398                 logit("Warning: No xauth data; "
399                     "using fake authentication data for X11 forwarding.");
400                 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
401                 for (i = 0; i < 16; i++) {
402                         if (i % 4 == 0)
403                                 rnd = arc4random();
404                         snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
405                             rnd & 0xff);
406                         rnd >>= 8;
407                 }
408         }
409 }
410
411 /*
412  * This is called when the interactive is entered.  This checks if there is
413  * an EOF coming on stdin.  We must check this explicitly, as select() does
414  * not appear to wake up when redirecting from /dev/null.
415  */
416
417 static void
418 client_check_initial_eof_on_stdin(void)
419 {
420         int len;
421         char buf[1];
422
423         /*
424          * If standard input is to be "redirected from /dev/null", we simply
425          * mark that we have seen an EOF and send an EOF message to the
426          * server. Otherwise, we try to read a single character; it appears
427          * that for some files, such /dev/null, select() never wakes up for
428          * read for this descriptor, which means that we never get EOF.  This
429          * way we will get the EOF if stdin comes from /dev/null or similar.
430          */
431         if (stdin_null_flag) {
432                 /* Fake EOF on stdin. */
433                 debug("Sending eof.");
434                 stdin_eof = 1;
435                 packet_start(SSH_CMSG_EOF);
436                 packet_send();
437         } else {
438                 enter_non_blocking();
439
440                 /* Check for immediate EOF on stdin. */
441                 len = read(fileno(stdin), buf, 1);
442                 if (len == 0) {
443                         /*
444                          * EOF.  Record that we have seen it and send
445                          * EOF to server.
446                          */
447                         debug("Sending eof.");
448                         stdin_eof = 1;
449                         packet_start(SSH_CMSG_EOF);
450                         packet_send();
451                 } else if (len > 0) {
452                         /*
453                          * Got data.  We must store the data in the buffer,
454                          * and also process it as an escape character if
455                          * appropriate.
456                          */
457                         if ((u_char) buf[0] == escape_char1)
458                                 escape_pending1 = 1;
459                         else
460                                 buffer_append(&stdin_buffer, buf, 1);
461                 }
462                 leave_non_blocking();
463         }
464 }
465
466
467 /*
468  * Make packets from buffered stdin data, and buffer them for sending to the
469  * connection.
470  */
471
472 static void
473 client_make_packets_from_stdin_data(void)
474 {
475         u_int len;
476
477         /* Send buffered stdin data to the server. */
478         while (buffer_len(&stdin_buffer) > 0 &&
479             packet_not_very_much_data_to_write()) {
480                 len = buffer_len(&stdin_buffer);
481                 /* Keep the packets at reasonable size. */
482                 if (len > packet_get_maxsize())
483                         len = packet_get_maxsize();
484                 packet_start(SSH_CMSG_STDIN_DATA);
485                 packet_put_string(buffer_ptr(&stdin_buffer), len);
486                 packet_send();
487                 buffer_consume(&stdin_buffer, len);
488                 /* If we have a pending EOF, send it now. */
489                 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
490                         packet_start(SSH_CMSG_EOF);
491                         packet_send();
492                 }
493         }
494 }
495
496 /*
497  * Checks if the client window has changed, and sends a packet about it to
498  * the server if so.  The actual change is detected elsewhere (by a software
499  * interrupt on Unix); this just checks the flag and sends a message if
500  * appropriate.
501  */
502
503 static void
504 client_check_window_change(void)
505 {
506         struct winsize ws;
507
508         if (! received_window_change_signal)
509                 return;
510         /** XXX race */
511         received_window_change_signal = 0;
512
513         debug2("client_check_window_change: changed");
514
515         if (compat20) {
516                 channel_send_window_changes();
517         } else {
518                 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
519                         return;
520                 packet_start(SSH_CMSG_WINDOW_SIZE);
521                 packet_put_int((u_int)ws.ws_row);
522                 packet_put_int((u_int)ws.ws_col);
523                 packet_put_int((u_int)ws.ws_xpixel);
524                 packet_put_int((u_int)ws.ws_ypixel);
525                 packet_send();
526         }
527 }
528
529 static void
530 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
531 {
532         struct global_confirm *gc;
533
534         if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
535                 return;
536         if (gc->cb != NULL)
537                 gc->cb(type, seq, gc->ctx);
538         if (--gc->ref_count <= 0) {
539                 TAILQ_REMOVE(&global_confirms, gc, entry);
540                 bzero(gc, sizeof(*gc));
541                 xfree(gc);
542         }
543
544         packet_set_alive_timeouts(0);
545 }
546
547 static void
548 server_alive_check(void)
549 {
550         if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
551                 logit("Timeout, server %s not responding.", host);
552                 cleanup_exit(255);
553         }
554         packet_start(SSH2_MSG_GLOBAL_REQUEST);
555         packet_put_cstring("keepalive@openssh.com");
556         packet_put_char(1);     /* boolean: want reply */
557         packet_send();
558         /* Insert an empty placeholder to maintain ordering */
559         client_register_global_confirm(NULL, NULL);
560 }
561
562 /*
563  * Waits until the client can do something (some data becomes available on
564  * one of the file descriptors).
565  */
566 static void
567 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
568     int *maxfdp, u_int *nallocp, int rekeying)
569 {
570         struct timeval tv, *tvp;
571         int timeout_secs;
572         int ret;
573
574         /* Add any selections by the channel mechanism. */
575         channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, rekeying);
576
577         if (!compat20) {
578                 /* Read from the connection, unless our buffers are full. */
579                 if (buffer_len(&stdout_buffer) < buffer_high &&
580                     buffer_len(&stderr_buffer) < buffer_high &&
581                     channel_not_very_much_buffered_data())
582                         FD_SET(connection_in, *readsetp);
583                 /*
584                  * Read from stdin, unless we have seen EOF or have very much
585                  * buffered data to send to the server.
586                  */
587                 if (!stdin_eof && packet_not_very_much_data_to_write())
588                         FD_SET(fileno(stdin), *readsetp);
589
590                 /* Select stdout/stderr if have data in buffer. */
591                 if (buffer_len(&stdout_buffer) > 0)
592                         FD_SET(fileno(stdout), *writesetp);
593                 if (buffer_len(&stderr_buffer) > 0)
594                         FD_SET(fileno(stderr), *writesetp);
595         } else {
596                 /* channel_prepare_select could have closed the last channel */
597                 if (session_closed && !channel_still_open() &&
598                     !packet_have_data_to_write()) {
599                         /* clear mask since we did not call select() */
600                         memset(*readsetp, 0, *nallocp);
601                         memset(*writesetp, 0, *nallocp);
602                         return;
603                 } else {
604                         FD_SET(connection_in, *readsetp);
605                 }
606         }
607
608         /* Select server connection if have data to write to the server. */
609         if (packet_have_data_to_write())
610                 FD_SET(connection_out, *writesetp);
611
612         /*
613          * Wait for something to happen.  This will suspend the process until
614          * some selected descriptor can be read, written, or has some other
615          * event pending, or a timeout expires.
616          */
617
618         timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
619         if (options.server_alive_interval > 0 && compat20)
620                 timeout_secs = options.server_alive_interval;
621         set_control_persist_exit_time();
622         if (control_persist_exit_time > 0) {
623                 timeout_secs = MIN(timeout_secs,
624                         control_persist_exit_time - time(NULL));
625                 if (timeout_secs < 0)
626                         timeout_secs = 0;
627         }
628         if (timeout_secs == INT_MAX)
629                 tvp = NULL;
630         else {
631                 tv.tv_sec = timeout_secs;
632                 tv.tv_usec = 0;
633                 tvp = &tv;
634         }
635
636         ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
637         if (ret < 0) {
638                 char buf[100];
639
640                 /*
641                  * We have to clear the select masks, because we return.
642                  * We have to return, because the mainloop checks for the flags
643                  * set by the signal handlers.
644                  */
645                 memset(*readsetp, 0, *nallocp);
646                 memset(*writesetp, 0, *nallocp);
647
648                 if (errno == EINTR)
649                         return;
650                 /* Note: we might still have data in the buffers. */
651                 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
652                 buffer_append(&stderr_buffer, buf, strlen(buf));
653                 quit_pending = 1;
654         } else if (ret == 0)
655                 server_alive_check();
656 }
657
658 static void
659 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
660 {
661         /* Flush stdout and stderr buffers. */
662         if (buffer_len(bout) > 0)
663                 atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
664                     buffer_len(bout));
665         if (buffer_len(berr) > 0)
666                 atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
667                     buffer_len(berr));
668
669         leave_raw_mode(force_tty_flag);
670
671         /*
672          * Free (and clear) the buffer to reduce the amount of data that gets
673          * written to swap.
674          */
675         buffer_free(bin);
676         buffer_free(bout);
677         buffer_free(berr);
678
679         /* Send the suspend signal to the program itself. */
680         kill(getpid(), SIGTSTP);
681
682         /* Reset window sizes in case they have changed */
683         received_window_change_signal = 1;
684
685         /* OK, we have been continued by the user. Reinitialize buffers. */
686         buffer_init(bin);
687         buffer_init(bout);
688         buffer_init(berr);
689
690         enter_raw_mode(force_tty_flag);
691 }
692
693 static void
694 client_process_net_input(fd_set *readset)
695 {
696         int len, cont = 0;
697         char buf[SSH_IOBUFSZ];
698
699         /*
700          * Read input from the server, and add any such data to the buffer of
701          * the packet subsystem.
702          */
703         if (FD_ISSET(connection_in, readset)) {
704                 /* Read as much as possible. */
705                 len = roaming_read(connection_in, buf, sizeof(buf), &cont);
706                 if (len == 0 && cont == 0) {
707                         /*
708                          * Received EOF.  The remote host has closed the
709                          * connection.
710                          */
711                         snprintf(buf, sizeof buf,
712                             "Connection to %.300s closed by remote host.\r\n",
713                             host);
714                         buffer_append(&stderr_buffer, buf, strlen(buf));
715                         quit_pending = 1;
716                         return;
717                 }
718                 /*
719                  * There is a kernel bug on Solaris that causes select to
720                  * sometimes wake up even though there is no data available.
721                  */
722                 if (len < 0 &&
723                     (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
724                         len = 0;
725
726                 if (len < 0) {
727                         /*
728                          * An error has encountered.  Perhaps there is a
729                          * network problem.
730                          */
731                         snprintf(buf, sizeof buf,
732                             "Read from remote host %.300s: %.100s\r\n",
733                             host, strerror(errno));
734                         buffer_append(&stderr_buffer, buf, strlen(buf));
735                         quit_pending = 1;
736                         return;
737                 }
738                 packet_process_incoming(buf, len);
739         }
740 }
741
742 static void
743 client_status_confirm(int type, Channel *c, void *ctx)
744 {
745         struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
746         char errmsg[256];
747         int tochan;
748
749         /* XXX supress on mux _client_ quietmode */
750         tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
751             c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
752
753         if (type == SSH2_MSG_CHANNEL_SUCCESS) {
754                 debug2("%s request accepted on channel %d",
755                     cr->request_type, c->self);
756         } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
757                 if (tochan) {
758                         snprintf(errmsg, sizeof(errmsg),
759                             "%s request failed\r\n", cr->request_type);
760                 } else {
761                         snprintf(errmsg, sizeof(errmsg),
762                             "%s request failed on channel %d",
763                             cr->request_type, c->self);
764                 }
765                 /* If error occurred on primary session channel, then exit */
766                 if (cr->do_close && c->self == session_ident)
767                         fatal("%s", errmsg);
768                 /* If error occurred on mux client, append to their stderr */
769                 if (tochan)
770                         buffer_append(&c->extended, errmsg, strlen(errmsg));
771                 else
772                         error("%s", errmsg);
773                 if (cr->do_close) {
774                         chan_read_failed(c);
775                         chan_write_failed(c);
776                 }
777         }
778         xfree(cr);
779 }
780
781 static void
782 client_abandon_status_confirm(Channel *c, void *ctx)
783 {
784         xfree(ctx);
785 }
786
787 static void
788 client_expect_confirm(int id, const char *request, int do_close)
789 {
790         struct channel_reply_ctx *cr = xmalloc(sizeof(*cr));
791
792         cr->request_type = request;
793         cr->do_close = do_close;
794
795         channel_register_status_confirm(id, client_status_confirm,
796             client_abandon_status_confirm, cr);
797 }
798
799 void
800 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
801 {
802         struct global_confirm *gc, *last_gc;
803
804         /* Coalesce identical callbacks */
805         last_gc = TAILQ_LAST(&global_confirms, global_confirms);
806         if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
807                 if (++last_gc->ref_count >= INT_MAX)
808                         fatal("%s: last_gc->ref_count = %d",
809                             __func__, last_gc->ref_count);
810                 return;
811         }
812
813         gc = xmalloc(sizeof(*gc));
814         gc->cb = cb;
815         gc->ctx = ctx;
816         gc->ref_count = 1;
817         TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
818 }
819
820 static void
821 process_cmdline(void)
822 {
823         void (*handler)(int);
824         char *s, *cmd, *cancel_host;
825         int delete = 0;
826         int local = 0, remote = 0, dynamic = 0;
827         int cancel_port;
828         Forward fwd;
829
830         bzero(&fwd, sizeof(fwd));
831         fwd.listen_host = fwd.connect_host = NULL;
832
833         leave_raw_mode(force_tty_flag);
834         handler = signal(SIGINT, SIG_IGN);
835         cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
836         if (s == NULL)
837                 goto out;
838         while (isspace(*s))
839                 s++;
840         if (*s == '-')
841                 s++;    /* Skip cmdline '-', if any */
842         if (*s == '\0')
843                 goto out;
844
845         if (*s == 'h' || *s == 'H' || *s == '?') {
846                 logit("Commands:");
847                 logit("      -L[bind_address:]port:host:hostport    "
848                     "Request local forward");
849                 logit("      -R[bind_address:]port:host:hostport    "
850                     "Request remote forward");
851                 logit("      -D[bind_address:]port                  "
852                     "Request dynamic forward");
853                 logit("      -KR[bind_address:]port                 "
854                     "Cancel remote forward");
855                 if (!options.permit_local_command)
856                         goto out;
857                 logit("      !args                                  "
858                     "Execute local command");
859                 goto out;
860         }
861
862         if (*s == '!' && options.permit_local_command) {
863                 s++;
864                 ssh_local_cmd(s);
865                 goto out;
866         }
867
868         if (*s == 'K') {
869                 delete = 1;
870                 s++;
871         }
872         if (*s == 'L')
873                 local = 1;
874         else if (*s == 'R')
875                 remote = 1;
876         else if (*s == 'D')
877                 dynamic = 1;
878         else {
879                 logit("Invalid command.");
880                 goto out;
881         }
882
883         if ((local || dynamic) && delete) {
884                 logit("Not supported.");
885                 goto out;
886         }
887         if (remote && delete && !compat20) {
888                 logit("Not supported for SSH protocol version 1.");
889                 goto out;
890         }
891
892         while (isspace(*++s))
893                 ;
894
895         /* XXX update list of forwards in options */
896         if (delete) {
897                 cancel_port = 0;
898                 cancel_host = hpdelim(&s);      /* may be NULL */
899                 if (s != NULL) {
900                         cancel_port = a2port(s);
901                         cancel_host = cleanhostname(cancel_host);
902                 } else {
903                         cancel_port = a2port(cancel_host);
904                         cancel_host = NULL;
905                 }
906                 if (cancel_port <= 0) {
907                         logit("Bad forwarding close port");
908                         goto out;
909                 }
910                 channel_request_rforward_cancel(cancel_host, cancel_port);
911         } else {
912                 if (!parse_forward(&fwd, s, dynamic, remote)) {
913                         logit("Bad forwarding specification.");
914                         goto out;
915                 }
916                 if (local || dynamic) {
917                         if (channel_setup_local_fwd_listener(fwd.listen_host,
918                             fwd.listen_port, fwd.connect_host,
919                             fwd.connect_port, options.gateway_ports) < 0) {
920                                 logit("Port forwarding failed.");
921                                 goto out;
922                         }
923                 } else {
924                         if (channel_request_remote_forwarding(fwd.listen_host,
925                             fwd.listen_port, fwd.connect_host,
926                             fwd.connect_port) < 0) {
927                                 logit("Port forwarding failed.");
928                                 goto out;
929                         }
930                 }
931
932                 logit("Forwarding port.");
933         }
934
935 out:
936         signal(SIGINT, handler);
937         enter_raw_mode(force_tty_flag);
938         if (cmd)
939                 xfree(cmd);
940         if (fwd.listen_host != NULL)
941                 xfree(fwd.listen_host);
942         if (fwd.connect_host != NULL)
943                 xfree(fwd.connect_host);
944 }
945
946 /* 
947  * Process the characters one by one, call with c==NULL for proto1 case.
948  */
949 static int
950 process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
951     char *buf, int len)
952 {
953         char string[1024];
954         pid_t pid;
955         int bytes = 0;
956         u_int i;
957         u_char ch;
958         char *s;
959         int *escape_pendingp, escape_char;
960         struct escape_filter_ctx *efc;
961
962         if (c == NULL) {
963                 escape_pendingp = &escape_pending1;
964                 escape_char = escape_char1;
965         } else {
966                 if (c->filter_ctx == NULL)
967                         return 0;
968                 efc = (struct escape_filter_ctx *)c->filter_ctx;
969                 escape_pendingp = &efc->escape_pending;
970                 escape_char = efc->escape_char;
971         }
972         
973         if (len <= 0)
974                 return (0);
975
976         for (i = 0; i < (u_int)len; i++) {
977                 /* Get one character at a time. */
978                 ch = buf[i];
979
980                 if (*escape_pendingp) {
981                         /* We have previously seen an escape character. */
982                         /* Clear the flag now. */
983                         *escape_pendingp = 0;
984
985                         /* Process the escaped character. */
986                         switch (ch) {
987                         case '.':
988                                 /* Terminate the connection. */
989                                 snprintf(string, sizeof string, "%c.\r\n",
990                                     escape_char);
991                                 buffer_append(berr, string, strlen(string));
992
993                                 if (c && c->ctl_chan != -1) {
994                                         chan_read_failed(c);
995                                         chan_write_failed(c);
996                                         return 0;
997                                 } else
998                                         quit_pending = 1;
999                                 return -1;
1000
1001                         case 'Z' - 64:
1002                                 /* XXX support this for mux clients */
1003                                 if (c && c->ctl_chan != -1) {
1004  noescape:
1005                                         snprintf(string, sizeof string,
1006                                             "%c%c escape not available to "
1007                                             "multiplexed sessions\r\n",
1008                                             escape_char, ch);
1009                                         buffer_append(berr, string,
1010                                             strlen(string));
1011                                         continue;
1012                                 }
1013                                 /* Suspend the program. Inform the user */
1014                                 snprintf(string, sizeof string,
1015                                     "%c^Z [suspend ssh]\r\n", escape_char);
1016                                 buffer_append(berr, string, strlen(string));
1017
1018                                 /* Restore terminal modes and suspend. */
1019                                 client_suspend_self(bin, bout, berr);
1020
1021                                 /* We have been continued. */
1022                                 continue;
1023
1024                         case 'B':
1025                                 if (compat20) {
1026                                         snprintf(string, sizeof string,
1027                                             "%cB\r\n", escape_char);
1028                                         buffer_append(berr, string,
1029                                             strlen(string));
1030                                         channel_request_start(session_ident,
1031                                             "break", 0);
1032                                         packet_put_int(1000);
1033                                         packet_send();
1034                                 }
1035                                 continue;
1036
1037                         case 'R':
1038                                 if (compat20) {
1039                                         if (datafellows & SSH_BUG_NOREKEY)
1040                                                 logit("Server does not "
1041                                                     "support re-keying");
1042                                         else
1043                                                 need_rekeying = 1;
1044                                 }
1045                                 continue;
1046
1047                         case '&':
1048                                 if (c && c->ctl_chan != -1)
1049                                         goto noescape;
1050                                 /*
1051                                  * Detach the program (continue to serve
1052                                  * connections, but put in background and no
1053                                  * more new connections).
1054                                  */
1055                                 /* Restore tty modes. */
1056                                 leave_raw_mode(force_tty_flag);
1057
1058                                 /* Stop listening for new connections. */
1059                                 channel_stop_listening();
1060
1061                                 snprintf(string, sizeof string,
1062                                     "%c& [backgrounded]\n", escape_char);
1063                                 buffer_append(berr, string, strlen(string));
1064
1065                                 /* Fork into background. */
1066                                 pid = fork();
1067                                 if (pid < 0) {
1068                                         error("fork: %.100s", strerror(errno));
1069                                         continue;
1070                                 }
1071                                 if (pid != 0) { /* This is the parent. */
1072                                         /* The parent just exits. */
1073                                         exit(0);
1074                                 }
1075                                 /* The child continues serving connections. */
1076                                 if (compat20) {
1077                                         buffer_append(bin, "\004", 1);
1078                                         /* fake EOF on stdin */
1079                                         return -1;
1080                                 } else if (!stdin_eof) {
1081                                         /*
1082                                          * Sending SSH_CMSG_EOF alone does not
1083                                          * always appear to be enough.  So we
1084                                          * try to send an EOF character first.
1085                                          */
1086                                         packet_start(SSH_CMSG_STDIN_DATA);
1087                                         packet_put_string("\004", 1);
1088                                         packet_send();
1089                                         /* Close stdin. */
1090                                         stdin_eof = 1;
1091                                         if (buffer_len(bin) == 0) {
1092                                                 packet_start(SSH_CMSG_EOF);
1093                                                 packet_send();
1094                                         }
1095                                 }
1096                                 continue;
1097
1098                         case '?':
1099                                 if (c && c->ctl_chan != -1) {
1100                                         snprintf(string, sizeof string,
1101 "%c?\r\n\
1102 Supported escape sequences:\r\n\
1103   %c.  - terminate session\r\n\
1104   %cB  - send a BREAK to the remote system\r\n\
1105   %cR  - Request rekey (SSH protocol 2 only)\r\n\
1106   %c#  - list forwarded connections\r\n\
1107   %c?  - this message\r\n\
1108   %c%c  - send the escape character by typing it twice\r\n\
1109 (Note that escapes are only recognized immediately after newline.)\r\n",
1110                                             escape_char, escape_char,
1111                                             escape_char, escape_char,
1112                                             escape_char, escape_char,
1113                                             escape_char, escape_char);
1114                                 } else {
1115                                         snprintf(string, sizeof string,
1116 "%c?\r\n\
1117 Supported escape sequences:\r\n\
1118   %c.  - terminate connection (and any multiplexed sessions)\r\n\
1119   %cB  - send a BREAK to the remote system\r\n\
1120   %cC  - open a command line\r\n\
1121   %cR  - Request rekey (SSH protocol 2 only)\r\n\
1122   %c^Z - suspend ssh\r\n\
1123   %c#  - list forwarded connections\r\n\
1124   %c&  - background ssh (when waiting for connections to terminate)\r\n\
1125   %c?  - this message\r\n\
1126   %c%c  - send the escape character by typing it twice\r\n\
1127 (Note that escapes are only recognized immediately after newline.)\r\n",
1128                                             escape_char, escape_char,
1129                                             escape_char, escape_char,
1130                                             escape_char, escape_char,
1131                                             escape_char, escape_char,
1132                                             escape_char, escape_char,
1133                                             escape_char);
1134                                 }
1135                                 buffer_append(berr, string, strlen(string));
1136                                 continue;
1137
1138                         case '#':
1139                                 snprintf(string, sizeof string, "%c#\r\n",
1140                                     escape_char);
1141                                 buffer_append(berr, string, strlen(string));
1142                                 s = channel_open_message();
1143                                 buffer_append(berr, s, strlen(s));
1144                                 xfree(s);
1145                                 continue;
1146
1147                         case 'C':
1148                                 if (c && c->ctl_chan != -1)
1149                                         goto noescape;
1150                                 process_cmdline();
1151                                 continue;
1152
1153                         default:
1154                                 if (ch != escape_char) {
1155                                         buffer_put_char(bin, escape_char);
1156                                         bytes++;
1157                                 }
1158                                 /* Escaped characters fall through here */
1159                                 break;
1160                         }
1161                 } else {
1162                         /*
1163                          * The previous character was not an escape char.
1164                          * Check if this is an escape.
1165                          */
1166                         if (last_was_cr && ch == escape_char) {
1167                                 /*
1168                                  * It is. Set the flag and continue to
1169                                  * next character.
1170                                  */
1171                                 *escape_pendingp = 1;
1172                                 continue;
1173                         }
1174                 }
1175
1176                 /*
1177                  * Normal character.  Record whether it was a newline,
1178                  * and append it to the buffer.
1179                  */
1180                 last_was_cr = (ch == '\r' || ch == '\n');
1181                 buffer_put_char(bin, ch);
1182                 bytes++;
1183         }
1184         return bytes;
1185 }
1186
1187 static void
1188 client_process_input(fd_set *readset)
1189 {
1190         int len;
1191         char buf[SSH_IOBUFSZ];
1192
1193         /* Read input from stdin. */
1194         if (FD_ISSET(fileno(stdin), readset)) {
1195                 /* Read as much as possible. */
1196                 len = read(fileno(stdin), buf, sizeof(buf));
1197                 if (len < 0 &&
1198                     (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
1199                         return;         /* we'll try again later */
1200                 if (len <= 0) {
1201                         /*
1202                          * Received EOF or error.  They are treated
1203                          * similarly, except that an error message is printed
1204                          * if it was an error condition.
1205                          */
1206                         if (len < 0) {
1207                                 snprintf(buf, sizeof buf, "read: %.100s\r\n",
1208                                     strerror(errno));
1209                                 buffer_append(&stderr_buffer, buf, strlen(buf));
1210                         }
1211                         /* Mark that we have seen EOF. */
1212                         stdin_eof = 1;
1213                         /*
1214                          * Send an EOF message to the server unless there is
1215                          * data in the buffer.  If there is data in the
1216                          * buffer, no message will be sent now.  Code
1217                          * elsewhere will send the EOF when the buffer
1218                          * becomes empty if stdin_eof is set.
1219                          */
1220                         if (buffer_len(&stdin_buffer) == 0) {
1221                                 packet_start(SSH_CMSG_EOF);
1222                                 packet_send();
1223                         }
1224                 } else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1225                         /*
1226                          * Normal successful read, and no escape character.
1227                          * Just append the data to buffer.
1228                          */
1229                         buffer_append(&stdin_buffer, buf, len);
1230                 } else {
1231                         /*
1232                          * Normal, successful read.  But we have an escape
1233                          * character and have to process the characters one
1234                          * by one.
1235                          */
1236                         if (process_escapes(NULL, &stdin_buffer,
1237                             &stdout_buffer, &stderr_buffer, buf, len) == -1)
1238                                 return;
1239                 }
1240         }
1241 }
1242
1243 static void
1244 client_process_output(fd_set *writeset)
1245 {
1246         int len;
1247         char buf[100];
1248
1249         /* Write buffered output to stdout. */
1250         if (FD_ISSET(fileno(stdout), writeset)) {
1251                 /* Write as much data as possible. */
1252                 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1253                     buffer_len(&stdout_buffer));
1254                 if (len <= 0) {
1255                         if (errno == EINTR || errno == EAGAIN ||
1256                             errno == EWOULDBLOCK)
1257                                 len = 0;
1258                         else {
1259                                 /*
1260                                  * An error or EOF was encountered.  Put an
1261                                  * error message to stderr buffer.
1262                                  */
1263                                 snprintf(buf, sizeof buf,
1264                                     "write stdout: %.50s\r\n", strerror(errno));
1265                                 buffer_append(&stderr_buffer, buf, strlen(buf));
1266                                 quit_pending = 1;
1267                                 return;
1268                         }
1269                 }
1270                 /* Consume printed data from the buffer. */
1271                 buffer_consume(&stdout_buffer, len);
1272         }
1273         /* Write buffered output to stderr. */
1274         if (FD_ISSET(fileno(stderr), writeset)) {
1275                 /* Write as much data as possible. */
1276                 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1277                     buffer_len(&stderr_buffer));
1278                 if (len <= 0) {
1279                         if (errno == EINTR || errno == EAGAIN ||
1280                             errno == EWOULDBLOCK)
1281                                 len = 0;
1282                         else {
1283                                 /*
1284                                  * EOF or error, but can't even print
1285                                  * error message.
1286                                  */
1287                                 quit_pending = 1;
1288                                 return;
1289                         }
1290                 }
1291                 /* Consume printed characters from the buffer. */
1292                 buffer_consume(&stderr_buffer, len);
1293         }
1294 }
1295
1296 /*
1297  * Get packets from the connection input buffer, and process them as long as
1298  * there are packets available.
1299  *
1300  * Any unknown packets received during the actual
1301  * session cause the session to terminate.  This is
1302  * intended to make debugging easier since no
1303  * confirmations are sent.  Any compatible protocol
1304  * extensions must be negotiated during the
1305  * preparatory phase.
1306  */
1307
1308 static void
1309 client_process_buffered_input_packets(void)
1310 {
1311         dispatch_run(DISPATCH_NONBLOCK, &quit_pending,
1312             compat20 ? xxx_kex : NULL);
1313 }
1314
1315 /* scan buf[] for '~' before sending data to the peer */
1316
1317 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1318 void *
1319 client_new_escape_filter_ctx(int escape_char)
1320 {
1321         struct escape_filter_ctx *ret;
1322
1323         ret = xmalloc(sizeof(*ret));
1324         ret->escape_pending = 0;
1325         ret->escape_char = escape_char;
1326         return (void *)ret;
1327 }
1328
1329 /* Free the escape filter context on channel free */
1330 void
1331 client_filter_cleanup(int cid, void *ctx)
1332 {
1333         xfree(ctx);
1334 }
1335
1336 int
1337 client_simple_escape_filter(Channel *c, char *buf, int len)
1338 {
1339         if (c->extended_usage != CHAN_EXTENDED_WRITE)
1340                 return 0;
1341
1342         return process_escapes(c, &c->input, &c->output, &c->extended,
1343             buf, len);
1344 }
1345
1346 static void
1347 client_channel_closed(int id, void *arg)
1348 {
1349         channel_cancel_cleanup(id);
1350         session_closed = 1;
1351         leave_raw_mode(force_tty_flag);
1352 }
1353
1354 /*
1355  * Implements the interactive session with the server.  This is called after
1356  * the user has been authenticated, and a command has been started on the
1357  * remote host.  If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1358  * used as an escape character for terminating or suspending the session.
1359  */
1360
1361 int
1362 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1363 {
1364         fd_set *readset = NULL, *writeset = NULL;
1365         double start_time, total_time;
1366         int max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1367         u_int64_t ibytes, obytes;
1368         u_int nalloc = 0;
1369         char buf[100];
1370
1371         debug("Entering interactive session.");
1372
1373         start_time = get_current_time();
1374
1375         /* Initialize variables. */
1376         escape_pending1 = 0;
1377         last_was_cr = 1;
1378         exit_status = -1;
1379         stdin_eof = 0;
1380         buffer_high = 64 * 1024;
1381         connection_in = packet_get_connection_in();
1382         connection_out = packet_get_connection_out();
1383         max_fd = MAX(connection_in, connection_out);
1384
1385         if (!compat20) {
1386                 /* enable nonblocking unless tty */
1387                 if (!isatty(fileno(stdin)))
1388                         set_nonblock(fileno(stdin));
1389                 if (!isatty(fileno(stdout)))
1390                         set_nonblock(fileno(stdout));
1391                 if (!isatty(fileno(stderr)))
1392                         set_nonblock(fileno(stderr));
1393                 max_fd = MAX(max_fd, fileno(stdin));
1394                 max_fd = MAX(max_fd, fileno(stdout));
1395                 max_fd = MAX(max_fd, fileno(stderr));
1396         }
1397         quit_pending = 0;
1398         escape_char1 = escape_char_arg;
1399
1400         /* Initialize buffers. */
1401         buffer_init(&stdin_buffer);
1402         buffer_init(&stdout_buffer);
1403         buffer_init(&stderr_buffer);
1404
1405         client_init_dispatch();
1406
1407         /*
1408          * Set signal handlers, (e.g. to restore non-blocking mode)
1409          * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1410          */
1411         if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1412                 signal(SIGHUP, signal_handler);
1413         if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1414                 signal(SIGINT, signal_handler);
1415         if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1416                 signal(SIGQUIT, signal_handler);
1417         if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1418                 signal(SIGTERM, signal_handler);
1419         signal(SIGWINCH, window_change_handler);
1420
1421         if (have_pty)
1422                 enter_raw_mode(force_tty_flag);
1423
1424         if (compat20) {
1425                 session_ident = ssh2_chan_id;
1426                 if (escape_char_arg != SSH_ESCAPECHAR_NONE)
1427                         channel_register_filter(session_ident,
1428                             client_simple_escape_filter, NULL,
1429                             client_filter_cleanup,
1430                             client_new_escape_filter_ctx(escape_char_arg));
1431                 if (session_ident != -1)
1432                         channel_register_cleanup(session_ident,
1433                             client_channel_closed, 0);
1434         } else {
1435                 /* Check if we should immediately send eof on stdin. */
1436                 client_check_initial_eof_on_stdin();
1437         }
1438
1439         /* Main loop of the client for the interactive session mode. */
1440         while (!quit_pending) {
1441
1442                 /* Process buffered packets sent by the server. */
1443                 client_process_buffered_input_packets();
1444
1445                 if (compat20 && session_closed && !channel_still_open())
1446                         break;
1447
1448                 rekeying = (xxx_kex != NULL && !xxx_kex->done);
1449
1450                 if (rekeying) {
1451                         debug("rekeying in progress");
1452                 } else {
1453                         /*
1454                          * Make packets of buffered stdin data, and buffer
1455                          * them for sending to the server.
1456                          */
1457                         if (!compat20)
1458                                 client_make_packets_from_stdin_data();
1459
1460                         /*
1461                          * Make packets from buffered channel data, and
1462                          * enqueue them for sending to the server.
1463                          */
1464                         if (packet_not_very_much_data_to_write())
1465                                 channel_output_poll();
1466
1467                         /*
1468                          * Check if the window size has changed, and buffer a
1469                          * message about it to the server if so.
1470                          */
1471                         client_check_window_change();
1472
1473                         if (quit_pending)
1474                                 break;
1475                 }
1476                 /*
1477                  * Wait until we have something to do (something becomes
1478                  * available on one of the descriptors).
1479                  */
1480                 max_fd2 = max_fd;
1481                 client_wait_until_can_do_something(&readset, &writeset,
1482                     &max_fd2, &nalloc, rekeying);
1483
1484                 if (quit_pending)
1485                         break;
1486
1487                 /* Do channel operations unless rekeying in progress. */
1488                 if (!rekeying) {
1489                         channel_after_select(readset, writeset);
1490
1491 #ifdef GSSAPI
1492                         if (options.gss_renewal_rekey &&
1493                             ssh_gssapi_credentials_updated(GSS_C_NO_CONTEXT)) {
1494                                 debug("credentials updated - forcing rekey");
1495                                 need_rekeying = 1;
1496                         }
1497 #endif
1498
1499                         if (need_rekeying || packet_need_rekeying()) {
1500                                 debug("need rekeying");
1501                                 xxx_kex->done = 0;
1502                                 kex_send_kexinit(xxx_kex);
1503                                 need_rekeying = 0;
1504                         }
1505                 }
1506
1507                 /* Buffer input from the connection.  */
1508                 client_process_net_input(readset);
1509
1510                 if (quit_pending)
1511                         break;
1512
1513                 if (!compat20) {
1514                         /* Buffer data from stdin */
1515                         client_process_input(readset);
1516                         /*
1517                          * Process output to stdout and stderr.  Output to
1518                          * the connection is processed elsewhere (above).
1519                          */
1520                         client_process_output(writeset);
1521                 }
1522
1523                 if (session_resumed) {
1524                         connection_in = packet_get_connection_in();
1525                         connection_out = packet_get_connection_out();
1526                         max_fd = MAX(max_fd, connection_out);
1527                         max_fd = MAX(max_fd, connection_in);
1528                         session_resumed = 0;
1529                 }
1530
1531                 /*
1532                  * Send as much buffered packet data as possible to the
1533                  * sender.
1534                  */
1535                 if (FD_ISSET(connection_out, writeset))
1536                         packet_write_poll();
1537
1538                 /*
1539                  * If we are a backgrounded control master, and the
1540                  * timeout has expired without any active client
1541                  * connections, then quit.
1542                  */
1543                 if (control_persist_exit_time > 0) {
1544                         if (time(NULL) >= control_persist_exit_time) {
1545                                 debug("ControlPersist timeout expired");
1546                                 break;
1547                         }
1548                 }
1549         }
1550         if (readset)
1551                 xfree(readset);
1552         if (writeset)
1553                 xfree(writeset);
1554
1555         /* Terminate the session. */
1556
1557         /* Stop watching for window change. */
1558         signal(SIGWINCH, SIG_DFL);
1559
1560         if (compat20) {
1561                 packet_start(SSH2_MSG_DISCONNECT);
1562                 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1563                 packet_put_cstring("disconnected by user");
1564                 packet_put_cstring(""); /* language tag */
1565                 packet_send();
1566                 packet_write_wait();
1567         }
1568
1569         channel_free_all();
1570
1571         if (have_pty)
1572                 leave_raw_mode(force_tty_flag);
1573
1574         /* restore blocking io */
1575         if (!isatty(fileno(stdin)))
1576                 unset_nonblock(fileno(stdin));
1577         if (!isatty(fileno(stdout)))
1578                 unset_nonblock(fileno(stdout));
1579         if (!isatty(fileno(stderr)))
1580                 unset_nonblock(fileno(stderr));
1581
1582         /*
1583          * If there was no shell or command requested, there will be no remote
1584          * exit status to be returned.  In that case, clear error code if the
1585          * connection was deliberately terminated at this end.
1586          */
1587         if (no_shell_flag && received_signal == SIGTERM) {
1588                 received_signal = 0;
1589                 exit_status = 0;
1590         }
1591
1592         if (received_signal)
1593                 fatal("Killed by signal %d.", (int) received_signal);
1594
1595         /*
1596          * In interactive mode (with pseudo tty) display a message indicating
1597          * that the connection has been closed.
1598          */
1599         if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1600                 snprintf(buf, sizeof buf,
1601                     "Connection to %.64s closed.\r\n", host);
1602                 buffer_append(&stderr_buffer, buf, strlen(buf));
1603         }
1604
1605         /* Output any buffered data for stdout. */
1606         if (buffer_len(&stdout_buffer) > 0) {
1607                 len = atomicio(vwrite, fileno(stdout),
1608                     buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer));
1609                 if (len < 0 || (u_int)len != buffer_len(&stdout_buffer))
1610                         error("Write failed flushing stdout buffer.");
1611                 else
1612                         buffer_consume(&stdout_buffer, len);
1613         }
1614
1615         /* Output any buffered data for stderr. */
1616         if (buffer_len(&stderr_buffer) > 0) {
1617                 len = atomicio(vwrite, fileno(stderr),
1618                     buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1619                 if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1620                         error("Write failed flushing stderr buffer.");
1621                 else
1622                         buffer_consume(&stderr_buffer, len);
1623         }
1624
1625         /* Clear and free any buffers. */
1626         memset(buf, 0, sizeof(buf));
1627         buffer_free(&stdin_buffer);
1628         buffer_free(&stdout_buffer);
1629         buffer_free(&stderr_buffer);
1630
1631         /* Report bytes transferred, and transfer rates. */
1632         total_time = get_current_time() - start_time;
1633         packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
1634         packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
1635         verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1636             (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1637         if (total_time > 0)
1638                 verbose("Bytes per second: sent %.1f, received %.1f",
1639                     obytes / total_time, ibytes / total_time);
1640         /* Return the exit status of the program. */
1641         debug("Exit status %d", exit_status);
1642         return exit_status;
1643 }
1644
1645 /*********/
1646
1647 static void
1648 client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1649 {
1650         u_int data_len;
1651         char *data = packet_get_string(&data_len);
1652         packet_check_eom();
1653         buffer_append(&stdout_buffer, data, data_len);
1654         memset(data, 0, data_len);
1655         xfree(data);
1656 }
1657 static void
1658 client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1659 {
1660         u_int data_len;
1661         char *data = packet_get_string(&data_len);
1662         packet_check_eom();
1663         buffer_append(&stderr_buffer, data, data_len);
1664         memset(data, 0, data_len);
1665         xfree(data);
1666 }
1667 static void
1668 client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1669 {
1670         exit_status = packet_get_int();
1671         packet_check_eom();
1672         /* Acknowledge the exit. */
1673         packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1674         packet_send();
1675         /*
1676          * Must wait for packet to be sent since we are
1677          * exiting the loop.
1678          */
1679         packet_write_wait();
1680         /* Flag that we want to exit. */
1681         quit_pending = 1;
1682 }
1683 static void
1684 client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1685 {
1686         Channel *c = NULL;
1687         int remote_id, sock;
1688
1689         /* Read the remote channel number from the message. */
1690         remote_id = packet_get_int();
1691         packet_check_eom();
1692
1693         /*
1694          * Get a connection to the local authentication agent (this may again
1695          * get forwarded).
1696          */
1697         sock = ssh_get_authentication_socket();
1698
1699         /*
1700          * If we could not connect the agent, send an error message back to
1701          * the server. This should never happen unless the agent dies,
1702          * because authentication forwarding is only enabled if we have an
1703          * agent.
1704          */
1705         if (sock >= 0) {
1706                 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1707                     -1, 0, 0, 0, "authentication agent connection", 1);
1708                 c->remote_id = remote_id;
1709                 c->force_drain = 1;
1710         }
1711         if (c == NULL) {
1712                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1713                 packet_put_int(remote_id);
1714         } else {
1715                 /* Send a confirmation to the remote host. */
1716                 debug("Forwarding authentication connection.");
1717                 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1718                 packet_put_int(remote_id);
1719                 packet_put_int(c->self);
1720         }
1721         packet_send();
1722 }
1723
1724 static Channel *
1725 client_request_forwarded_tcpip(const char *request_type, int rchan)
1726 {
1727         Channel *c = NULL;
1728         char *listen_address, *originator_address;
1729         u_short listen_port, originator_port;
1730
1731         /* Get rest of the packet */
1732         listen_address = packet_get_string(NULL);
1733         listen_port = packet_get_int();
1734         originator_address = packet_get_string(NULL);
1735         originator_port = packet_get_int();
1736         packet_check_eom();
1737
1738         debug("client_request_forwarded_tcpip: listen %s port %d, "
1739             "originator %s port %d", listen_address, listen_port,
1740             originator_address, originator_port);
1741
1742         c = channel_connect_by_listen_address(listen_port,
1743             "forwarded-tcpip", originator_address);
1744
1745         xfree(originator_address);
1746         xfree(listen_address);
1747         return c;
1748 }
1749
1750 static Channel *
1751 client_request_x11(const char *request_type, int rchan)
1752 {
1753         Channel *c = NULL;
1754         char *originator;
1755         u_short originator_port;
1756         int sock;
1757
1758         if (!options.forward_x11) {
1759                 error("Warning: ssh server tried X11 forwarding.");
1760                 error("Warning: this is probably a break-in attempt by a "
1761                     "malicious server.");
1762                 return NULL;
1763         }
1764         if (x11_refuse_time != 0 && time(NULL) >= x11_refuse_time) {
1765                 verbose("Rejected X11 connection after ForwardX11Timeout "
1766                     "expired");
1767                 return NULL;
1768         }
1769         originator = packet_get_string(NULL);
1770         if (datafellows & SSH_BUG_X11FWD) {
1771                 debug2("buggy server: x11 request w/o originator_port");
1772                 originator_port = 0;
1773         } else {
1774                 originator_port = packet_get_int();
1775         }
1776         packet_check_eom();
1777         /* XXX check permission */
1778         debug("client_request_x11: request from %s %d", originator,
1779             originator_port);
1780         xfree(originator);
1781         sock = x11_connect_display();
1782         if (sock < 0)
1783                 return NULL;
1784         c = channel_new("x11",
1785             SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1786             CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1787         c->force_drain = 1;
1788         return c;
1789 }
1790
1791 static Channel *
1792 client_request_agent(const char *request_type, int rchan)
1793 {
1794         Channel *c = NULL;
1795         int sock;
1796
1797         if (!options.forward_agent) {
1798                 error("Warning: ssh server tried agent forwarding.");
1799                 error("Warning: this is probably a break-in attempt by a "
1800                     "malicious server.");
1801                 return NULL;
1802         }
1803         sock = ssh_get_authentication_socket();
1804         if (sock < 0)
1805                 return NULL;
1806         c = channel_new("authentication agent connection",
1807             SSH_CHANNEL_OPEN, sock, sock, -1,
1808             CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1809             "authentication agent connection", 1);
1810         c->force_drain = 1;
1811         return c;
1812 }
1813
1814 int
1815 client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
1816 {
1817         Channel *c;
1818         int fd;
1819
1820         if (tun_mode == SSH_TUNMODE_NO)
1821                 return 0;
1822
1823         if (!compat20) {
1824                 error("Tunnel forwarding is not supported for protocol 1");
1825                 return -1;
1826         }
1827
1828         debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1829
1830         /* Open local tunnel device */
1831         if ((fd = tun_open(local_tun, tun_mode)) == -1) {
1832                 error("Tunnel device open failed.");
1833                 return -1;
1834         }
1835
1836         c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1837             CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1838         c->datagram = 1;
1839
1840 #if defined(SSH_TUN_FILTER)
1841         if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1842                 channel_register_filter(c->self, sys_tun_infilter,
1843                     sys_tun_outfilter, NULL, NULL);
1844 #endif
1845
1846         packet_start(SSH2_MSG_CHANNEL_OPEN);
1847         packet_put_cstring("tun@openssh.com");
1848         packet_put_int(c->self);
1849         packet_put_int(c->local_window_max);
1850         packet_put_int(c->local_maxpacket);
1851         packet_put_int(tun_mode);
1852         packet_put_int(remote_tun);
1853         packet_send();
1854
1855         return 0;
1856 }
1857
1858 /* XXXX move to generic input handler */
1859 static void
1860 client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1861 {
1862         Channel *c = NULL;
1863         char *ctype;
1864         int rchan;
1865         u_int rmaxpack, rwindow, len;
1866
1867         ctype = packet_get_string(&len);
1868         rchan = packet_get_int();
1869         rwindow = packet_get_int();
1870         rmaxpack = packet_get_int();
1871
1872         debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1873             ctype, rchan, rwindow, rmaxpack);
1874
1875         if (strcmp(ctype, "forwarded-tcpip") == 0) {
1876                 c = client_request_forwarded_tcpip(ctype, rchan);
1877         } else if (strcmp(ctype, "x11") == 0) {
1878                 c = client_request_x11(ctype, rchan);
1879         } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1880                 c = client_request_agent(ctype, rchan);
1881         }
1882 /* XXX duplicate : */
1883         if (c != NULL) {
1884                 debug("confirm %s", ctype);
1885                 c->remote_id = rchan;
1886                 c->remote_window = rwindow;
1887                 c->remote_maxpacket = rmaxpack;
1888                 if (c->type != SSH_CHANNEL_CONNECTING) {
1889                         packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1890                         packet_put_int(c->remote_id);
1891                         packet_put_int(c->self);
1892                         packet_put_int(c->local_window);
1893                         packet_put_int(c->local_maxpacket);
1894                         packet_send();
1895                 }
1896         } else {
1897                 debug("failure %s", ctype);
1898                 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1899                 packet_put_int(rchan);
1900                 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1901                 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1902                         packet_put_cstring("open failed");
1903                         packet_put_cstring("");
1904                 }
1905                 packet_send();
1906         }
1907         xfree(ctype);
1908 }
1909 static void
1910 client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1911 {
1912         Channel *c = NULL;
1913         int exitval, id, reply, success = 0;
1914         char *rtype;
1915
1916         id = packet_get_int();
1917         rtype = packet_get_string(NULL);
1918         reply = packet_get_char();
1919
1920         debug("client_input_channel_req: channel %d rtype %s reply %d",
1921             id, rtype, reply);
1922
1923         if (id == -1) {
1924                 error("client_input_channel_req: request for channel -1");
1925         } else if ((c = channel_lookup(id)) == NULL) {
1926                 error("client_input_channel_req: channel %d: "
1927                     "unknown channel", id);
1928         } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1929                 packet_check_eom();
1930                 chan_rcvd_eow(c);
1931         } else if (strcmp(rtype, "exit-status") == 0) {
1932                 exitval = packet_get_int();
1933                 if (c->ctl_chan != -1) {
1934                         mux_exit_message(c, exitval);
1935                         success = 1;
1936                 } else if (id == session_ident) {
1937                         /* Record exit value of local session */
1938                         success = 1;
1939                         exit_status = exitval;
1940                 } else {
1941                         /* Probably for a mux channel that has already closed */
1942                         debug("%s: no sink for exit-status on channel %d",
1943                             __func__, id);
1944                 }
1945                 packet_check_eom();
1946         }
1947         if (reply && c != NULL) {
1948                 packet_start(success ?
1949                     SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1950                 packet_put_int(c->remote_id);
1951                 packet_send();
1952         }
1953         xfree(rtype);
1954 }
1955 static void
1956 client_input_global_request(int type, u_int32_t seq, void *ctxt)
1957 {
1958         char *rtype;
1959         int want_reply;
1960         int success = 0;
1961
1962         rtype = packet_get_string(NULL);
1963         want_reply = packet_get_char();
1964         debug("client_input_global_request: rtype %s want_reply %d",
1965             rtype, want_reply);
1966         if (want_reply) {
1967                 packet_start(success ?
1968                     SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1969                 packet_send();
1970                 packet_write_wait();
1971         }
1972         xfree(rtype);
1973 }
1974
1975 void
1976 client_session2_setup(int id, int want_tty, int want_subsystem,
1977     const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
1978 {
1979         int len;
1980         Channel *c = NULL;
1981
1982         debug2("%s: id %d", __func__, id);
1983
1984         if ((c = channel_lookup(id)) == NULL)
1985                 fatal("client_session2_setup: channel %d: unknown channel", id);
1986
1987         packet_set_interactive(want_tty,
1988             options.ip_qos_interactive, options.ip_qos_bulk);
1989
1990         if (want_tty) {
1991                 struct winsize ws;
1992
1993                 /* Store window size in the packet. */
1994                 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
1995                         memset(&ws, 0, sizeof(ws));
1996
1997                 channel_request_start(id, "pty-req", 1);
1998                 client_expect_confirm(id, "PTY allocation", 1);
1999                 packet_put_cstring(term != NULL ? term : "");
2000                 packet_put_int((u_int)ws.ws_col);
2001                 packet_put_int((u_int)ws.ws_row);
2002                 packet_put_int((u_int)ws.ws_xpixel);
2003                 packet_put_int((u_int)ws.ws_ypixel);
2004                 if (tiop == NULL)
2005                         tiop = get_saved_tio();
2006                 tty_make_modes(-1, tiop);
2007                 packet_send();
2008                 /* XXX wait for reply */
2009                 c->client_tty = 1;
2010         }
2011
2012         /* Transfer any environment variables from client to server */
2013         if (options.num_send_env != 0 && env != NULL) {
2014                 int i, j, matched;
2015                 char *name, *val;
2016
2017                 debug("Sending environment.");
2018                 for (i = 0; env[i] != NULL; i++) {
2019                         /* Split */
2020                         name = xstrdup(env[i]);
2021                         if ((val = strchr(name, '=')) == NULL) {
2022                                 xfree(name);
2023                                 continue;
2024                         }
2025                         *val++ = '\0';
2026
2027                         matched = 0;
2028                         for (j = 0; j < options.num_send_env; j++) {
2029                                 if (match_pattern(name, options.send_env[j])) {
2030                                         matched = 1;
2031                                         break;
2032                                 }
2033                         }
2034                         if (!matched) {
2035                                 debug3("Ignored env %s", name);
2036                                 xfree(name);
2037                                 continue;
2038                         }
2039
2040                         debug("Sending env %s = %s", name, val);
2041                         channel_request_start(id, "env", 0);
2042                         packet_put_cstring(name);
2043                         packet_put_cstring(val);
2044                         packet_send();
2045                         xfree(name);
2046                 }
2047         }
2048
2049         len = buffer_len(cmd);
2050         if (len > 0) {
2051                 if (len > 900)
2052                         len = 900;
2053                 if (want_subsystem) {
2054                         debug("Sending subsystem: %.*s",
2055                             len, (u_char*)buffer_ptr(cmd));
2056                         channel_request_start(id, "subsystem", 1);
2057                         client_expect_confirm(id, "subsystem", 1);
2058                 } else {
2059                         debug("Sending command: %.*s",
2060                             len, (u_char*)buffer_ptr(cmd));
2061                         channel_request_start(id, "exec", 1);
2062                         client_expect_confirm(id, "exec", 1);
2063                 }
2064                 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2065                 packet_send();
2066         } else {
2067                 channel_request_start(id, "shell", 1);
2068                 client_expect_confirm(id, "shell", 1);
2069                 packet_send();
2070         }
2071 }
2072
2073 static void
2074 client_init_dispatch_20(void)
2075 {
2076         dispatch_init(&dispatch_protocol_error);
2077
2078         dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2079         dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2080         dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2081         dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2082         dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2083         dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2084         dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2085         dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2086         dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2087         dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2088         dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2089         dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2090
2091         /* rekeying */
2092         dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2093
2094         /* global request reply messages */
2095         dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2096         dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2097 }
2098
2099 static void
2100 client_init_dispatch_13(void)
2101 {
2102         dispatch_init(NULL);
2103         dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2104         dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2105         dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2106         dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2107         dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2108         dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2109         dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2110         dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2111         dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
2112
2113         dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
2114             &client_input_agent_open : &deny_input_open);
2115         dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2116             &x11_input_open : &deny_input_open);
2117 }
2118
2119 static void
2120 client_init_dispatch_15(void)
2121 {
2122         client_init_dispatch_13();
2123         dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2124         dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2125 }
2126
2127 static void
2128 client_init_dispatch(void)
2129 {
2130         if (compat20)
2131                 client_init_dispatch_20();
2132         else if (compat13)
2133                 client_init_dispatch_13();
2134         else
2135                 client_init_dispatch_15();
2136 }
2137
2138 /* client specific fatal cleanup */
2139 void
2140 cleanup_exit(int i)
2141 {
2142         leave_raw_mode(force_tty_flag);
2143         leave_non_blocking();
2144         if (options.control_path != NULL && muxserver_sock != -1)
2145                 unlink(options.control_path);
2146         ssh_kill_proxy_command();
2147         _exit(i);
2148 }