]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - clientloop.c
Vendor import of OpenSSH 6.9p1.
[FreeBSD/FreeBSD.git] / clientloop.c
1 /* $OpenBSD: clientloop.c,v 1.274 2015/07/01 02:26:31 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/param.h>  /* MIN MAX */
65 #include <sys/types.h>
66 #include <sys/ioctl.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 #include <limits.h>
89
90 #include "openbsd-compat/sys-queue.h"
91 #include "xmalloc.h"
92 #include "ssh.h"
93 #include "ssh1.h"
94 #include "ssh2.h"
95 #include "packet.h"
96 #include "buffer.h"
97 #include "compat.h"
98 #include "channels.h"
99 #include "dispatch.h"
100 #include "key.h"
101 #include "cipher.h"
102 #include "kex.h"
103 #include "log.h"
104 #include "misc.h"
105 #include "readconf.h"
106 #include "clientloop.h"
107 #include "sshconnect.h"
108 #include "authfd.h"
109 #include "atomicio.h"
110 #include "sshpty.h"
111 #include "match.h"
112 #include "msg.h"
113 #include "roaming.h"
114 #include "ssherr.h"
115 #include "hostfile.h"
116
117 /* import options */
118 extern Options options;
119
120 /* Flag indicating that stdin should be redirected from /dev/null. */
121 extern int stdin_null_flag;
122
123 /* Flag indicating that no shell has been requested */
124 extern int no_shell_flag;
125
126 /* Control socket */
127 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
128
129 /*
130  * Name of the host we are connecting to.  This is the name given on the
131  * command line, or the HostName specified for the user-supplied name in a
132  * configuration file.
133  */
134 extern char *host;
135
136 /*
137  * Flag to indicate that we have received a window change signal which has
138  * not yet been processed.  This will cause a message indicating the new
139  * window size to be sent to the server a little later.  This is volatile
140  * because this is updated in a signal handler.
141  */
142 static volatile sig_atomic_t received_window_change_signal = 0;
143 static volatile sig_atomic_t received_signal = 0;
144
145 /* Flag indicating whether the user's terminal is in non-blocking mode. */
146 static int in_non_blocking_mode = 0;
147
148 /* Time when backgrounded control master using ControlPersist should exit */
149 static time_t control_persist_exit_time = 0;
150
151 /* Common data for the client loop code. */
152 volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
153 static int escape_char1;        /* Escape character. (proto1 only) */
154 static int escape_pending1;     /* Last character was an escape (proto1 only) */
155 static int last_was_cr;         /* Last character was a newline. */
156 static int exit_status;         /* Used to store the command exit status. */
157 static int stdin_eof;           /* EOF has been encountered on stderr. */
158 static Buffer stdin_buffer;     /* Buffer for stdin data. */
159 static Buffer stdout_buffer;    /* Buffer for stdout data. */
160 static Buffer stderr_buffer;    /* Buffer for stderr data. */
161 static u_int buffer_high;       /* Soft max buffer size. */
162 static int connection_in;       /* Connection to server (input). */
163 static int connection_out;      /* Connection to server (output). */
164 static int need_rekeying;       /* Set to non-zero if rekeying is requested. */
165 static int session_closed;      /* In SSH2: login session closed. */
166 static u_int x11_refuse_time;   /* If >0, refuse x11 opens after this time. */
167
168 static void client_init_dispatch(void);
169 int     session_ident = -1;
170
171 int     session_resumed = 0;
172
173 /* Track escape per proto2 channel */
174 struct escape_filter_ctx {
175         int escape_pending;
176         int escape_char;
177 };
178
179 /* Context for channel confirmation replies */
180 struct channel_reply_ctx {
181         const char *request_type;
182         int id;
183         enum confirm_action action;
184 };
185
186 /* Global request success/failure callbacks */
187 struct global_confirm {
188         TAILQ_ENTRY(global_confirm) entry;
189         global_confirm_cb *cb;
190         void *ctx;
191         int ref_count;
192 };
193 TAILQ_HEAD(global_confirms, global_confirm);
194 static struct global_confirms global_confirms =
195     TAILQ_HEAD_INITIALIZER(global_confirms);
196
197 void ssh_process_session2_setup(int, int, int, Buffer *);
198
199 /* Restores stdin to blocking mode. */
200
201 static void
202 leave_non_blocking(void)
203 {
204         if (in_non_blocking_mode) {
205                 unset_nonblock(fileno(stdin));
206                 in_non_blocking_mode = 0;
207         }
208 }
209
210 /* Puts stdin terminal in non-blocking mode. */
211
212 static void
213 enter_non_blocking(void)
214 {
215         in_non_blocking_mode = 1;
216         set_nonblock(fileno(stdin));
217 }
218
219 /*
220  * Signal handler for the window change signal (SIGWINCH).  This just sets a
221  * flag indicating that the window has changed.
222  */
223 /*ARGSUSED */
224 static void
225 window_change_handler(int sig)
226 {
227         received_window_change_signal = 1;
228         signal(SIGWINCH, window_change_handler);
229 }
230
231 /*
232  * Signal handler for signals that cause the program to terminate.  These
233  * signals must be trapped to restore terminal modes.
234  */
235 /*ARGSUSED */
236 static void
237 signal_handler(int sig)
238 {
239         received_signal = sig;
240         quit_pending = 1;
241 }
242
243 /*
244  * Returns current time in seconds from Jan 1, 1970 with the maximum
245  * available resolution.
246  */
247
248 static double
249 get_current_time(void)
250 {
251         struct timeval tv;
252         gettimeofday(&tv, NULL);
253         return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
254 }
255
256 /*
257  * Sets control_persist_exit_time to the absolute time when the
258  * backgrounded control master should exit due to expiry of the
259  * ControlPersist timeout.  Sets it to 0 if we are not a backgrounded
260  * control master process, or if there is no ControlPersist timeout.
261  */
262 static void
263 set_control_persist_exit_time(void)
264 {
265         if (muxserver_sock == -1 || !options.control_persist
266             || options.control_persist_timeout == 0) {
267                 /* not using a ControlPersist timeout */
268                 control_persist_exit_time = 0;
269         } else if (channel_still_open()) {
270                 /* some client connections are still open */
271                 if (control_persist_exit_time > 0)
272                         debug2("%s: cancel scheduled exit", __func__);
273                 control_persist_exit_time = 0;
274         } else if (control_persist_exit_time <= 0) {
275                 /* a client connection has recently closed */
276                 control_persist_exit_time = monotime() +
277                         (time_t)options.control_persist_timeout;
278                 debug2("%s: schedule exit in %d seconds", __func__,
279                     options.control_persist_timeout);
280         }
281         /* else we are already counting down to the timeout */
282 }
283
284 #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
285 static int
286 client_x11_display_valid(const char *display)
287 {
288         size_t i, dlen;
289
290         dlen = strlen(display);
291         for (i = 0; i < dlen; i++) {
292                 if (!isalnum((u_char)display[i]) &&
293                     strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
294                         debug("Invalid character '%c' in DISPLAY", display[i]);
295                         return 0;
296                 }
297         }
298         return 1;
299 }
300
301 #define SSH_X11_PROTO           "MIT-MAGIC-COOKIE-1"
302 #define X11_TIMEOUT_SLACK       60
303 void
304 client_x11_get_proto(const char *display, const char *xauth_path,
305     u_int trusted, u_int timeout, char **_proto, char **_data)
306 {
307         char cmd[1024];
308         char line[512];
309         char xdisplay[512];
310         static char proto[512], data[512];
311         FILE *f;
312         int got_data = 0, generated = 0, do_unlink = 0, i;
313         char *xauthdir, *xauthfile;
314         struct stat st;
315         u_int now, x11_timeout_real;
316
317         xauthdir = xauthfile = NULL;
318         *_proto = proto;
319         *_data = data;
320         proto[0] = data[0] = '\0';
321
322         if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
323                 debug("No xauth program.");
324         } else if (!client_x11_display_valid(display)) {
325                 logit("DISPLAY '%s' invalid, falling back to fake xauth data",
326                     display);
327         } else {
328                 if (display == NULL) {
329                         debug("x11_get_proto: DISPLAY not set");
330                         return;
331                 }
332                 /*
333                  * Handle FamilyLocal case where $DISPLAY does
334                  * not match an authorization entry.  For this we
335                  * just try "xauth list unix:displaynum.screennum".
336                  * XXX: "localhost" match to determine FamilyLocal
337                  *      is not perfect.
338                  */
339                 if (strncmp(display, "localhost:", 10) == 0) {
340                         snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
341                             display + 10);
342                         display = xdisplay;
343                 }
344                 if (trusted == 0) {
345                         xauthdir = xmalloc(PATH_MAX);
346                         xauthfile = xmalloc(PATH_MAX);
347                         mktemp_proto(xauthdir, PATH_MAX);
348                         /*
349                          * The authentication cookie should briefly outlive
350                          * ssh's willingness to forward X11 connections to
351                          * avoid nasty fail-open behaviour in the X server.
352                          */
353                         if (timeout >= UINT_MAX - X11_TIMEOUT_SLACK)
354                                 x11_timeout_real = UINT_MAX;
355                         else
356                                 x11_timeout_real = timeout + X11_TIMEOUT_SLACK;
357                         if (mkdtemp(xauthdir) != NULL) {
358                                 do_unlink = 1;
359                                 snprintf(xauthfile, PATH_MAX, "%s/xauthfile",
360                                     xauthdir);
361                                 snprintf(cmd, sizeof(cmd),
362                                     "%s -f %s generate %s " SSH_X11_PROTO
363                                     " untrusted timeout %u 2>" _PATH_DEVNULL,
364                                     xauth_path, xauthfile, display,
365                                     x11_timeout_real);
366                                 debug2("x11_get_proto: %s", cmd);
367                                 if (x11_refuse_time == 0) {
368                                         now = monotime() + 1;
369                                         if (UINT_MAX - timeout < now)
370                                                 x11_refuse_time = UINT_MAX;
371                                         else
372                                                 x11_refuse_time = now + timeout;
373                                         channel_set_x11_refuse_time(
374                                             x11_refuse_time);
375                                 }
376                                 if (system(cmd) == 0)
377                                         generated = 1;
378                         }
379                 }
380
381                 /*
382                  * When in untrusted mode, we read the cookie only if it was
383                  * successfully generated as an untrusted one in the step
384                  * above.
385                  */
386                 if (trusted || generated) {
387                         snprintf(cmd, sizeof(cmd),
388                             "%s %s%s list %s 2>" _PATH_DEVNULL,
389                             xauth_path,
390                             generated ? "-f " : "" ,
391                             generated ? xauthfile : "",
392                             display);
393                         debug2("x11_get_proto: %s", cmd);
394                         f = popen(cmd, "r");
395                         if (f && fgets(line, sizeof(line), f) &&
396                             sscanf(line, "%*s %511s %511s", proto, data) == 2)
397                                 got_data = 1;
398                         if (f)
399                                 pclose(f);
400                 } else
401                         error("Warning: untrusted X11 forwarding setup failed: "
402                             "xauth key data not generated");
403         }
404
405         if (do_unlink) {
406                 unlink(xauthfile);
407                 rmdir(xauthdir);
408         }
409         free(xauthdir);
410         free(xauthfile);
411
412         /*
413          * If we didn't get authentication data, just make up some
414          * data.  The forwarding code will check the validity of the
415          * response anyway, and substitute this data.  The X11
416          * server, however, will ignore this fake data and use
417          * whatever authentication mechanisms it was using otherwise
418          * for the local connection.
419          */
420         if (!got_data) {
421                 u_int32_t rnd = 0;
422
423                 logit("Warning: No xauth data; "
424                     "using fake authentication data for X11 forwarding.");
425                 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
426                 for (i = 0; i < 16; i++) {
427                         if (i % 4 == 0)
428                                 rnd = arc4random();
429                         snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
430                             rnd & 0xff);
431                         rnd >>= 8;
432                 }
433         }
434 }
435
436 /*
437  * This is called when the interactive is entered.  This checks if there is
438  * an EOF coming on stdin.  We must check this explicitly, as select() does
439  * not appear to wake up when redirecting from /dev/null.
440  */
441
442 static void
443 client_check_initial_eof_on_stdin(void)
444 {
445         int len;
446         char buf[1];
447
448         /*
449          * If standard input is to be "redirected from /dev/null", we simply
450          * mark that we have seen an EOF and send an EOF message to the
451          * server. Otherwise, we try to read a single character; it appears
452          * that for some files, such /dev/null, select() never wakes up for
453          * read for this descriptor, which means that we never get EOF.  This
454          * way we will get the EOF if stdin comes from /dev/null or similar.
455          */
456         if (stdin_null_flag) {
457                 /* Fake EOF on stdin. */
458                 debug("Sending eof.");
459                 stdin_eof = 1;
460                 packet_start(SSH_CMSG_EOF);
461                 packet_send();
462         } else {
463                 enter_non_blocking();
464
465                 /* Check for immediate EOF on stdin. */
466                 len = read(fileno(stdin), buf, 1);
467                 if (len == 0) {
468                         /*
469                          * EOF.  Record that we have seen it and send
470                          * EOF to server.
471                          */
472                         debug("Sending eof.");
473                         stdin_eof = 1;
474                         packet_start(SSH_CMSG_EOF);
475                         packet_send();
476                 } else if (len > 0) {
477                         /*
478                          * Got data.  We must store the data in the buffer,
479                          * and also process it as an escape character if
480                          * appropriate.
481                          */
482                         if ((u_char) buf[0] == escape_char1)
483                                 escape_pending1 = 1;
484                         else
485                                 buffer_append(&stdin_buffer, buf, 1);
486                 }
487                 leave_non_blocking();
488         }
489 }
490
491
492 /*
493  * Make packets from buffered stdin data, and buffer them for sending to the
494  * connection.
495  */
496
497 static void
498 client_make_packets_from_stdin_data(void)
499 {
500         u_int len;
501
502         /* Send buffered stdin data to the server. */
503         while (buffer_len(&stdin_buffer) > 0 &&
504             packet_not_very_much_data_to_write()) {
505                 len = buffer_len(&stdin_buffer);
506                 /* Keep the packets at reasonable size. */
507                 if (len > packet_get_maxsize())
508                         len = packet_get_maxsize();
509                 packet_start(SSH_CMSG_STDIN_DATA);
510                 packet_put_string(buffer_ptr(&stdin_buffer), len);
511                 packet_send();
512                 buffer_consume(&stdin_buffer, len);
513                 /* If we have a pending EOF, send it now. */
514                 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
515                         packet_start(SSH_CMSG_EOF);
516                         packet_send();
517                 }
518         }
519 }
520
521 /*
522  * Checks if the client window has changed, and sends a packet about it to
523  * the server if so.  The actual change is detected elsewhere (by a software
524  * interrupt on Unix); this just checks the flag and sends a message if
525  * appropriate.
526  */
527
528 static void
529 client_check_window_change(void)
530 {
531         struct winsize ws;
532
533         if (! received_window_change_signal)
534                 return;
535         /** XXX race */
536         received_window_change_signal = 0;
537
538         debug2("client_check_window_change: changed");
539
540         if (compat20) {
541                 channel_send_window_changes();
542         } else {
543                 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
544                         return;
545                 packet_start(SSH_CMSG_WINDOW_SIZE);
546                 packet_put_int((u_int)ws.ws_row);
547                 packet_put_int((u_int)ws.ws_col);
548                 packet_put_int((u_int)ws.ws_xpixel);
549                 packet_put_int((u_int)ws.ws_ypixel);
550                 packet_send();
551         }
552 }
553
554 static int
555 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
556 {
557         struct global_confirm *gc;
558
559         if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
560                 return 0;
561         if (gc->cb != NULL)
562                 gc->cb(type, seq, gc->ctx);
563         if (--gc->ref_count <= 0) {
564                 TAILQ_REMOVE(&global_confirms, gc, entry);
565                 explicit_bzero(gc, sizeof(*gc));
566                 free(gc);
567         }
568
569         packet_set_alive_timeouts(0);
570         return 0;
571 }
572
573 static void
574 server_alive_check(void)
575 {
576         if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
577                 logit("Timeout, server %s not responding.", host);
578                 cleanup_exit(255);
579         }
580         packet_start(SSH2_MSG_GLOBAL_REQUEST);
581         packet_put_cstring("keepalive@openssh.com");
582         packet_put_char(1);     /* boolean: want reply */
583         packet_send();
584         /* Insert an empty placeholder to maintain ordering */
585         client_register_global_confirm(NULL, NULL);
586 }
587
588 /*
589  * Waits until the client can do something (some data becomes available on
590  * one of the file descriptors).
591  */
592 static void
593 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
594     int *maxfdp, u_int *nallocp, int rekeying)
595 {
596         struct timeval tv, *tvp;
597         int timeout_secs;
598         time_t minwait_secs = 0, server_alive_time = 0, now = monotime();
599         int ret;
600
601         /* Add any selections by the channel mechanism. */
602         channel_prepare_select(readsetp, writesetp, maxfdp, nallocp,
603             &minwait_secs, rekeying);
604
605         if (!compat20) {
606                 /* Read from the connection, unless our buffers are full. */
607                 if (buffer_len(&stdout_buffer) < buffer_high &&
608                     buffer_len(&stderr_buffer) < buffer_high &&
609                     channel_not_very_much_buffered_data())
610                         FD_SET(connection_in, *readsetp);
611                 /*
612                  * Read from stdin, unless we have seen EOF or have very much
613                  * buffered data to send to the server.
614                  */
615                 if (!stdin_eof && packet_not_very_much_data_to_write())
616                         FD_SET(fileno(stdin), *readsetp);
617
618                 /* Select stdout/stderr if have data in buffer. */
619                 if (buffer_len(&stdout_buffer) > 0)
620                         FD_SET(fileno(stdout), *writesetp);
621                 if (buffer_len(&stderr_buffer) > 0)
622                         FD_SET(fileno(stderr), *writesetp);
623         } else {
624                 /* channel_prepare_select could have closed the last channel */
625                 if (session_closed && !channel_still_open() &&
626                     !packet_have_data_to_write()) {
627                         /* clear mask since we did not call select() */
628                         memset(*readsetp, 0, *nallocp);
629                         memset(*writesetp, 0, *nallocp);
630                         return;
631                 } else {
632                         FD_SET(connection_in, *readsetp);
633                 }
634         }
635
636         /* Select server connection if have data to write to the server. */
637         if (packet_have_data_to_write())
638                 FD_SET(connection_out, *writesetp);
639
640         /*
641          * Wait for something to happen.  This will suspend the process until
642          * some selected descriptor can be read, written, or has some other
643          * event pending, or a timeout expires.
644          */
645
646         timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
647         if (options.server_alive_interval > 0 && compat20) {
648                 timeout_secs = options.server_alive_interval;
649                 server_alive_time = now + options.server_alive_interval;
650         }
651         if (options.rekey_interval > 0 && compat20 && !rekeying)
652                 timeout_secs = MIN(timeout_secs, packet_get_rekey_timeout());
653         set_control_persist_exit_time();
654         if (control_persist_exit_time > 0) {
655                 timeout_secs = MIN(timeout_secs,
656                         control_persist_exit_time - now);
657                 if (timeout_secs < 0)
658                         timeout_secs = 0;
659         }
660         if (minwait_secs != 0)
661                 timeout_secs = MIN(timeout_secs, (int)minwait_secs);
662         if (timeout_secs == INT_MAX)
663                 tvp = NULL;
664         else {
665                 tv.tv_sec = timeout_secs;
666                 tv.tv_usec = 0;
667                 tvp = &tv;
668         }
669
670         ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
671         if (ret < 0) {
672                 char buf[100];
673
674                 /*
675                  * We have to clear the select masks, because we return.
676                  * We have to return, because the mainloop checks for the flags
677                  * set by the signal handlers.
678                  */
679                 memset(*readsetp, 0, *nallocp);
680                 memset(*writesetp, 0, *nallocp);
681
682                 if (errno == EINTR)
683                         return;
684                 /* Note: we might still have data in the buffers. */
685                 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
686                 buffer_append(&stderr_buffer, buf, strlen(buf));
687                 quit_pending = 1;
688         } else if (ret == 0) {
689                 /*
690                  * Timeout.  Could have been either keepalive or rekeying.
691                  * Keepalive we check here, rekeying is checked in clientloop.
692                  */
693                 if (server_alive_time != 0 && server_alive_time <= monotime())
694                         server_alive_check();
695         }
696
697 }
698
699 static void
700 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
701 {
702         /* Flush stdout and stderr buffers. */
703         if (buffer_len(bout) > 0)
704                 atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
705                     buffer_len(bout));
706         if (buffer_len(berr) > 0)
707                 atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
708                     buffer_len(berr));
709
710         leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
711
712         /*
713          * Free (and clear) the buffer to reduce the amount of data that gets
714          * written to swap.
715          */
716         buffer_free(bin);
717         buffer_free(bout);
718         buffer_free(berr);
719
720         /* Send the suspend signal to the program itself. */
721         kill(getpid(), SIGTSTP);
722
723         /* Reset window sizes in case they have changed */
724         received_window_change_signal = 1;
725
726         /* OK, we have been continued by the user. Reinitialize buffers. */
727         buffer_init(bin);
728         buffer_init(bout);
729         buffer_init(berr);
730
731         enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
732 }
733
734 static void
735 client_process_net_input(fd_set *readset)
736 {
737         int len, cont = 0;
738         char buf[SSH_IOBUFSZ];
739
740         /*
741          * Read input from the server, and add any such data to the buffer of
742          * the packet subsystem.
743          */
744         if (FD_ISSET(connection_in, readset)) {
745                 /* Read as much as possible. */
746                 len = roaming_read(connection_in, buf, sizeof(buf), &cont);
747                 if (len == 0 && cont == 0) {
748                         /*
749                          * Received EOF.  The remote host has closed the
750                          * connection.
751                          */
752                         snprintf(buf, sizeof buf,
753                             "Connection to %.300s closed by remote host.\r\n",
754                             host);
755                         buffer_append(&stderr_buffer, buf, strlen(buf));
756                         quit_pending = 1;
757                         return;
758                 }
759                 /*
760                  * There is a kernel bug on Solaris that causes select to
761                  * sometimes wake up even though there is no data available.
762                  */
763                 if (len < 0 &&
764                     (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
765                         len = 0;
766
767                 if (len < 0) {
768                         /*
769                          * An error has encountered.  Perhaps there is a
770                          * network problem.
771                          */
772                         snprintf(buf, sizeof buf,
773                             "Read from remote host %.300s: %.100s\r\n",
774                             host, strerror(errno));
775                         buffer_append(&stderr_buffer, buf, strlen(buf));
776                         quit_pending = 1;
777                         return;
778                 }
779                 packet_process_incoming(buf, len);
780         }
781 }
782
783 static void
784 client_status_confirm(int type, Channel *c, void *ctx)
785 {
786         struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
787         char errmsg[256];
788         int tochan;
789
790         /*
791          * If a TTY was explicitly requested, then a failure to allocate
792          * one is fatal.
793          */
794         if (cr->action == CONFIRM_TTY &&
795             (options.request_tty == REQUEST_TTY_FORCE ||
796             options.request_tty == REQUEST_TTY_YES))
797                 cr->action = CONFIRM_CLOSE;
798
799         /* XXX supress on mux _client_ quietmode */
800         tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
801             c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
802
803         if (type == SSH2_MSG_CHANNEL_SUCCESS) {
804                 debug2("%s request accepted on channel %d",
805                     cr->request_type, c->self);
806         } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
807                 if (tochan) {
808                         snprintf(errmsg, sizeof(errmsg),
809                             "%s request failed\r\n", cr->request_type);
810                 } else {
811                         snprintf(errmsg, sizeof(errmsg),
812                             "%s request failed on channel %d",
813                             cr->request_type, c->self);
814                 }
815                 /* If error occurred on primary session channel, then exit */
816                 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
817                         fatal("%s", errmsg);
818                 /*
819                  * If error occurred on mux client, append to
820                  * their stderr.
821                  */
822                 if (tochan) {
823                         buffer_append(&c->extended, errmsg,
824                             strlen(errmsg));
825                 } else
826                         error("%s", errmsg);
827                 if (cr->action == CONFIRM_TTY) {
828                         /*
829                          * If a TTY allocation error occurred, then arrange
830                          * for the correct TTY to leave raw mode.
831                          */
832                         if (c->self == session_ident)
833                                 leave_raw_mode(0);
834                         else
835                                 mux_tty_alloc_failed(c);
836                 } else if (cr->action == CONFIRM_CLOSE) {
837                         chan_read_failed(c);
838                         chan_write_failed(c);
839                 }
840         }
841         free(cr);
842 }
843
844 static void
845 client_abandon_status_confirm(Channel *c, void *ctx)
846 {
847         free(ctx);
848 }
849
850 void
851 client_expect_confirm(int id, const char *request,
852     enum confirm_action action)
853 {
854         struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
855
856         cr->request_type = request;
857         cr->action = action;
858
859         channel_register_status_confirm(id, client_status_confirm,
860             client_abandon_status_confirm, cr);
861 }
862
863 void
864 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
865 {
866         struct global_confirm *gc, *last_gc;
867
868         /* Coalesce identical callbacks */
869         last_gc = TAILQ_LAST(&global_confirms, global_confirms);
870         if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
871                 if (++last_gc->ref_count >= INT_MAX)
872                         fatal("%s: last_gc->ref_count = %d",
873                             __func__, last_gc->ref_count);
874                 return;
875         }
876
877         gc = xcalloc(1, sizeof(*gc));
878         gc->cb = cb;
879         gc->ctx = ctx;
880         gc->ref_count = 1;
881         TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
882 }
883
884 static void
885 process_cmdline(void)
886 {
887         void (*handler)(int);
888         char *s, *cmd;
889         int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
890         struct Forward fwd;
891
892         memset(&fwd, 0, sizeof(fwd));
893
894         leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
895         handler = signal(SIGINT, SIG_IGN);
896         cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
897         if (s == NULL)
898                 goto out;
899         while (isspace((u_char)*s))
900                 s++;
901         if (*s == '-')
902                 s++;    /* Skip cmdline '-', if any */
903         if (*s == '\0')
904                 goto out;
905
906         if (*s == 'h' || *s == 'H' || *s == '?') {
907                 logit("Commands:");
908                 logit("      -L[bind_address:]port:host:hostport    "
909                     "Request local forward");
910                 logit("      -R[bind_address:]port:host:hostport    "
911                     "Request remote forward");
912                 logit("      -D[bind_address:]port                  "
913                     "Request dynamic forward");
914                 logit("      -KL[bind_address:]port                 "
915                     "Cancel local forward");
916                 logit("      -KR[bind_address:]port                 "
917                     "Cancel remote forward");
918                 logit("      -KD[bind_address:]port                 "
919                     "Cancel dynamic forward");
920                 if (!options.permit_local_command)
921                         goto out;
922                 logit("      !args                                  "
923                     "Execute local command");
924                 goto out;
925         }
926
927         if (*s == '!' && options.permit_local_command) {
928                 s++;
929                 ssh_local_cmd(s);
930                 goto out;
931         }
932
933         if (*s == 'K') {
934                 delete = 1;
935                 s++;
936         }
937         if (*s == 'L')
938                 local = 1;
939         else if (*s == 'R')
940                 remote = 1;
941         else if (*s == 'D')
942                 dynamic = 1;
943         else {
944                 logit("Invalid command.");
945                 goto out;
946         }
947
948         if (delete && !compat20) {
949                 logit("Not supported for SSH protocol version 1.");
950                 goto out;
951         }
952
953         while (isspace((u_char)*++s))
954                 ;
955
956         /* XXX update list of forwards in options */
957         if (delete) {
958                 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
959                 if (!parse_forward(&fwd, s, 1, 0)) {
960                         logit("Bad forwarding close specification.");
961                         goto out;
962                 }
963                 if (remote)
964                         ok = channel_request_rforward_cancel(&fwd) == 0;
965                 else if (dynamic)
966                         ok = channel_cancel_lport_listener(&fwd,
967                             0, &options.fwd_opts) > 0;
968                 else
969                         ok = channel_cancel_lport_listener(&fwd,
970                             CHANNEL_CANCEL_PORT_STATIC,
971                             &options.fwd_opts) > 0;
972                 if (!ok) {
973                         logit("Unkown port forwarding.");
974                         goto out;
975                 }
976                 logit("Canceled forwarding.");
977         } else {
978                 if (!parse_forward(&fwd, s, dynamic, remote)) {
979                         logit("Bad forwarding specification.");
980                         goto out;
981                 }
982                 if (local || dynamic) {
983                         if (!channel_setup_local_fwd_listener(&fwd,
984                             &options.fwd_opts)) {
985                                 logit("Port forwarding failed.");
986                                 goto out;
987                         }
988                 } else {
989                         if (channel_request_remote_forwarding(&fwd) < 0) {
990                                 logit("Port forwarding failed.");
991                                 goto out;
992                         }
993                 }
994                 logit("Forwarding port.");
995         }
996
997 out:
998         signal(SIGINT, handler);
999         enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1000         free(cmd);
1001         free(fwd.listen_host);
1002         free(fwd.listen_path);
1003         free(fwd.connect_host);
1004         free(fwd.connect_path);
1005 }
1006
1007 /* reasons to suppress output of an escape command in help output */
1008 #define SUPPRESS_NEVER          0       /* never suppress, always show */
1009 #define SUPPRESS_PROTO1         1       /* don't show in protocol 1 sessions */
1010 #define SUPPRESS_MUXCLIENT      2       /* don't show in mux client sessions */
1011 #define SUPPRESS_MUXMASTER      4       /* don't show in mux master sessions */
1012 #define SUPPRESS_SYSLOG         8       /* don't show when logging to syslog */
1013 struct escape_help_text {
1014         const char *cmd;
1015         const char *text;
1016         unsigned int flags;
1017 };
1018 static struct escape_help_text esc_txt[] = {
1019     {".",  "terminate session", SUPPRESS_MUXMASTER},
1020     {".",  "terminate connection (and any multiplexed sessions)",
1021         SUPPRESS_MUXCLIENT},
1022     {"B",  "send a BREAK to the remote system", SUPPRESS_PROTO1},
1023     {"C",  "open a command line", SUPPRESS_MUXCLIENT},
1024     {"R",  "request rekey", SUPPRESS_PROTO1},
1025     {"V/v",  "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
1026     {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
1027     {"#",  "list forwarded connections", SUPPRESS_NEVER},
1028     {"&",  "background ssh (when waiting for connections to terminate)",
1029         SUPPRESS_MUXCLIENT},
1030     {"?", "this message", SUPPRESS_NEVER},
1031 };
1032
1033 static void
1034 print_escape_help(Buffer *b, int escape_char, int protocol2, int mux_client,
1035     int using_stderr)
1036 {
1037         unsigned int i, suppress_flags;
1038         char string[1024];
1039
1040         snprintf(string, sizeof string, "%c?\r\n"
1041             "Supported escape sequences:\r\n", escape_char);
1042         buffer_append(b, string, strlen(string));
1043
1044         suppress_flags = (protocol2 ? 0 : SUPPRESS_PROTO1) |
1045             (mux_client ? SUPPRESS_MUXCLIENT : 0) |
1046             (mux_client ? 0 : SUPPRESS_MUXMASTER) |
1047             (using_stderr ? 0 : SUPPRESS_SYSLOG);
1048
1049         for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
1050                 if (esc_txt[i].flags & suppress_flags)
1051                         continue;
1052                 snprintf(string, sizeof string, " %c%-3s - %s\r\n",
1053                     escape_char, esc_txt[i].cmd, esc_txt[i].text);
1054                 buffer_append(b, string, strlen(string));
1055         }
1056
1057         snprintf(string, sizeof string,
1058             " %c%c   - send the escape character by typing it twice\r\n"
1059             "(Note that escapes are only recognized immediately after "
1060             "newline.)\r\n", escape_char, escape_char);
1061         buffer_append(b, string, strlen(string));
1062 }
1063
1064 /* 
1065  * Process the characters one by one, call with c==NULL for proto1 case.
1066  */
1067 static int
1068 process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
1069     char *buf, int len)
1070 {
1071         char string[1024];
1072         pid_t pid;
1073         int bytes = 0;
1074         u_int i;
1075         u_char ch;
1076         char *s;
1077         int *escape_pendingp, escape_char;
1078         struct escape_filter_ctx *efc;
1079
1080         if (c == NULL) {
1081                 escape_pendingp = &escape_pending1;
1082                 escape_char = escape_char1;
1083         } else {
1084                 if (c->filter_ctx == NULL)
1085                         return 0;
1086                 efc = (struct escape_filter_ctx *)c->filter_ctx;
1087                 escape_pendingp = &efc->escape_pending;
1088                 escape_char = efc->escape_char;
1089         }
1090         
1091         if (len <= 0)
1092                 return (0);
1093
1094         for (i = 0; i < (u_int)len; i++) {
1095                 /* Get one character at a time. */
1096                 ch = buf[i];
1097
1098                 if (*escape_pendingp) {
1099                         /* We have previously seen an escape character. */
1100                         /* Clear the flag now. */
1101                         *escape_pendingp = 0;
1102
1103                         /* Process the escaped character. */
1104                         switch (ch) {
1105                         case '.':
1106                                 /* Terminate the connection. */
1107                                 snprintf(string, sizeof string, "%c.\r\n",
1108                                     escape_char);
1109                                 buffer_append(berr, string, strlen(string));
1110
1111                                 if (c && c->ctl_chan != -1) {
1112                                         chan_read_failed(c);
1113                                         chan_write_failed(c);
1114                                         if (c->detach_user)
1115                                                 c->detach_user(c->self, NULL);
1116                                         c->type = SSH_CHANNEL_ABANDONED;
1117                                         buffer_clear(&c->input);
1118                                         chan_ibuf_empty(c);
1119                                         return 0;
1120                                 } else
1121                                         quit_pending = 1;
1122                                 return -1;
1123
1124                         case 'Z' - 64:
1125                                 /* XXX support this for mux clients */
1126                                 if (c && c->ctl_chan != -1) {
1127                                         char b[16];
1128  noescape:
1129                                         if (ch == 'Z' - 64)
1130                                                 snprintf(b, sizeof b, "^Z");
1131                                         else
1132                                                 snprintf(b, sizeof b, "%c", ch);
1133                                         snprintf(string, sizeof string,
1134                                             "%c%s escape not available to "
1135                                             "multiplexed sessions\r\n",
1136                                             escape_char, b);
1137                                         buffer_append(berr, string,
1138                                             strlen(string));
1139                                         continue;
1140                                 }
1141                                 /* Suspend the program. Inform the user */
1142                                 snprintf(string, sizeof string,
1143                                     "%c^Z [suspend ssh]\r\n", escape_char);
1144                                 buffer_append(berr, string, strlen(string));
1145
1146                                 /* Restore terminal modes and suspend. */
1147                                 client_suspend_self(bin, bout, berr);
1148
1149                                 /* We have been continued. */
1150                                 continue;
1151
1152                         case 'B':
1153                                 if (compat20) {
1154                                         snprintf(string, sizeof string,
1155                                             "%cB\r\n", escape_char);
1156                                         buffer_append(berr, string,
1157                                             strlen(string));
1158                                         channel_request_start(c->self,
1159                                             "break", 0);
1160                                         packet_put_int(1000);
1161                                         packet_send();
1162                                 }
1163                                 continue;
1164
1165                         case 'R':
1166                                 if (compat20) {
1167                                         if (datafellows & SSH_BUG_NOREKEY)
1168                                                 logit("Server does not "
1169                                                     "support re-keying");
1170                                         else
1171                                                 need_rekeying = 1;
1172                                 }
1173                                 continue;
1174
1175                         case 'V':
1176                                 /* FALLTHROUGH */
1177                         case 'v':
1178                                 if (c && c->ctl_chan != -1)
1179                                         goto noescape;
1180                                 if (!log_is_on_stderr()) {
1181                                         snprintf(string, sizeof string,
1182                                             "%c%c [Logging to syslog]\r\n",
1183                                              escape_char, ch);
1184                                         buffer_append(berr, string,
1185                                             strlen(string));
1186                                         continue;
1187                                 }
1188                                 if (ch == 'V' && options.log_level >
1189                                     SYSLOG_LEVEL_QUIET)
1190                                         log_change_level(--options.log_level);
1191                                 if (ch == 'v' && options.log_level <
1192                                     SYSLOG_LEVEL_DEBUG3)
1193                                         log_change_level(++options.log_level);
1194                                 snprintf(string, sizeof string,
1195                                     "%c%c [LogLevel %s]\r\n", escape_char, ch,
1196                                     log_level_name(options.log_level));
1197                                 buffer_append(berr, string, strlen(string));
1198                                 continue;
1199
1200                         case '&':
1201                                 if (c && c->ctl_chan != -1)
1202                                         goto noescape;
1203                                 /*
1204                                  * Detach the program (continue to serve
1205                                  * connections, but put in background and no
1206                                  * more new connections).
1207                                  */
1208                                 /* Restore tty modes. */
1209                                 leave_raw_mode(
1210                                     options.request_tty == REQUEST_TTY_FORCE);
1211
1212                                 /* Stop listening for new connections. */
1213                                 channel_stop_listening();
1214
1215                                 snprintf(string, sizeof string,
1216                                     "%c& [backgrounded]\n", escape_char);
1217                                 buffer_append(berr, string, strlen(string));
1218
1219                                 /* Fork into background. */
1220                                 pid = fork();
1221                                 if (pid < 0) {
1222                                         error("fork: %.100s", strerror(errno));
1223                                         continue;
1224                                 }
1225                                 if (pid != 0) { /* This is the parent. */
1226                                         /* The parent just exits. */
1227                                         exit(0);
1228                                 }
1229                                 /* The child continues serving connections. */
1230                                 if (compat20) {
1231                                         buffer_append(bin, "\004", 1);
1232                                         /* fake EOF on stdin */
1233                                         return -1;
1234                                 } else if (!stdin_eof) {
1235                                         /*
1236                                          * Sending SSH_CMSG_EOF alone does not
1237                                          * always appear to be enough.  So we
1238                                          * try to send an EOF character first.
1239                                          */
1240                                         packet_start(SSH_CMSG_STDIN_DATA);
1241                                         packet_put_string("\004", 1);
1242                                         packet_send();
1243                                         /* Close stdin. */
1244                                         stdin_eof = 1;
1245                                         if (buffer_len(bin) == 0) {
1246                                                 packet_start(SSH_CMSG_EOF);
1247                                                 packet_send();
1248                                         }
1249                                 }
1250                                 continue;
1251
1252                         case '?':
1253                                 print_escape_help(berr, escape_char, compat20,
1254                                     (c && c->ctl_chan != -1),
1255                                     log_is_on_stderr());
1256                                 continue;
1257
1258                         case '#':
1259                                 snprintf(string, sizeof string, "%c#\r\n",
1260                                     escape_char);
1261                                 buffer_append(berr, string, strlen(string));
1262                                 s = channel_open_message();
1263                                 buffer_append(berr, s, strlen(s));
1264                                 free(s);
1265                                 continue;
1266
1267                         case 'C':
1268                                 if (c && c->ctl_chan != -1)
1269                                         goto noescape;
1270                                 process_cmdline();
1271                                 continue;
1272
1273                         default:
1274                                 if (ch != escape_char) {
1275                                         buffer_put_char(bin, escape_char);
1276                                         bytes++;
1277                                 }
1278                                 /* Escaped characters fall through here */
1279                                 break;
1280                         }
1281                 } else {
1282                         /*
1283                          * The previous character was not an escape char.
1284                          * Check if this is an escape.
1285                          */
1286                         if (last_was_cr && ch == escape_char) {
1287                                 /*
1288                                  * It is. Set the flag and continue to
1289                                  * next character.
1290                                  */
1291                                 *escape_pendingp = 1;
1292                                 continue;
1293                         }
1294                 }
1295
1296                 /*
1297                  * Normal character.  Record whether it was a newline,
1298                  * and append it to the buffer.
1299                  */
1300                 last_was_cr = (ch == '\r' || ch == '\n');
1301                 buffer_put_char(bin, ch);
1302                 bytes++;
1303         }
1304         return bytes;
1305 }
1306
1307 static void
1308 client_process_input(fd_set *readset)
1309 {
1310         int len;
1311         char buf[SSH_IOBUFSZ];
1312
1313         /* Read input from stdin. */
1314         if (FD_ISSET(fileno(stdin), readset)) {
1315                 /* Read as much as possible. */
1316                 len = read(fileno(stdin), buf, sizeof(buf));
1317                 if (len < 0 &&
1318                     (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
1319                         return;         /* we'll try again later */
1320                 if (len <= 0) {
1321                         /*
1322                          * Received EOF or error.  They are treated
1323                          * similarly, except that an error message is printed
1324                          * if it was an error condition.
1325                          */
1326                         if (len < 0) {
1327                                 snprintf(buf, sizeof buf, "read: %.100s\r\n",
1328                                     strerror(errno));
1329                                 buffer_append(&stderr_buffer, buf, strlen(buf));
1330                         }
1331                         /* Mark that we have seen EOF. */
1332                         stdin_eof = 1;
1333                         /*
1334                          * Send an EOF message to the server unless there is
1335                          * data in the buffer.  If there is data in the
1336                          * buffer, no message will be sent now.  Code
1337                          * elsewhere will send the EOF when the buffer
1338                          * becomes empty if stdin_eof is set.
1339                          */
1340                         if (buffer_len(&stdin_buffer) == 0) {
1341                                 packet_start(SSH_CMSG_EOF);
1342                                 packet_send();
1343                         }
1344                 } else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1345                         /*
1346                          * Normal successful read, and no escape character.
1347                          * Just append the data to buffer.
1348                          */
1349                         buffer_append(&stdin_buffer, buf, len);
1350                 } else {
1351                         /*
1352                          * Normal, successful read.  But we have an escape
1353                          * character and have to process the characters one
1354                          * by one.
1355                          */
1356                         if (process_escapes(NULL, &stdin_buffer,
1357                             &stdout_buffer, &stderr_buffer, buf, len) == -1)
1358                                 return;
1359                 }
1360         }
1361 }
1362
1363 static void
1364 client_process_output(fd_set *writeset)
1365 {
1366         int len;
1367         char buf[100];
1368
1369         /* Write buffered output to stdout. */
1370         if (FD_ISSET(fileno(stdout), writeset)) {
1371                 /* Write as much data as possible. */
1372                 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1373                     buffer_len(&stdout_buffer));
1374                 if (len <= 0) {
1375                         if (errno == EINTR || errno == EAGAIN ||
1376                             errno == EWOULDBLOCK)
1377                                 len = 0;
1378                         else {
1379                                 /*
1380                                  * An error or EOF was encountered.  Put an
1381                                  * error message to stderr buffer.
1382                                  */
1383                                 snprintf(buf, sizeof buf,
1384                                     "write stdout: %.50s\r\n", strerror(errno));
1385                                 buffer_append(&stderr_buffer, buf, strlen(buf));
1386                                 quit_pending = 1;
1387                                 return;
1388                         }
1389                 }
1390                 /* Consume printed data from the buffer. */
1391                 buffer_consume(&stdout_buffer, len);
1392         }
1393         /* Write buffered output to stderr. */
1394         if (FD_ISSET(fileno(stderr), writeset)) {
1395                 /* Write as much data as possible. */
1396                 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1397                     buffer_len(&stderr_buffer));
1398                 if (len <= 0) {
1399                         if (errno == EINTR || errno == EAGAIN ||
1400                             errno == EWOULDBLOCK)
1401                                 len = 0;
1402                         else {
1403                                 /*
1404                                  * EOF or error, but can't even print
1405                                  * error message.
1406                                  */
1407                                 quit_pending = 1;
1408                                 return;
1409                         }
1410                 }
1411                 /* Consume printed characters from the buffer. */
1412                 buffer_consume(&stderr_buffer, len);
1413         }
1414 }
1415
1416 /*
1417  * Get packets from the connection input buffer, and process them as long as
1418  * there are packets available.
1419  *
1420  * Any unknown packets received during the actual
1421  * session cause the session to terminate.  This is
1422  * intended to make debugging easier since no
1423  * confirmations are sent.  Any compatible protocol
1424  * extensions must be negotiated during the
1425  * preparatory phase.
1426  */
1427
1428 static void
1429 client_process_buffered_input_packets(void)
1430 {
1431         dispatch_run(DISPATCH_NONBLOCK, &quit_pending, active_state);
1432 }
1433
1434 /* scan buf[] for '~' before sending data to the peer */
1435
1436 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1437 void *
1438 client_new_escape_filter_ctx(int escape_char)
1439 {
1440         struct escape_filter_ctx *ret;
1441
1442         ret = xcalloc(1, sizeof(*ret));
1443         ret->escape_pending = 0;
1444         ret->escape_char = escape_char;
1445         return (void *)ret;
1446 }
1447
1448 /* Free the escape filter context on channel free */
1449 void
1450 client_filter_cleanup(int cid, void *ctx)
1451 {
1452         free(ctx);
1453 }
1454
1455 int
1456 client_simple_escape_filter(Channel *c, char *buf, int len)
1457 {
1458         if (c->extended_usage != CHAN_EXTENDED_WRITE)
1459                 return 0;
1460
1461         return process_escapes(c, &c->input, &c->output, &c->extended,
1462             buf, len);
1463 }
1464
1465 static void
1466 client_channel_closed(int id, void *arg)
1467 {
1468         channel_cancel_cleanup(id);
1469         session_closed = 1;
1470         leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1471 }
1472
1473 /*
1474  * Implements the interactive session with the server.  This is called after
1475  * the user has been authenticated, and a command has been started on the
1476  * remote host.  If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1477  * used as an escape character for terminating or suspending the session.
1478  */
1479
1480 int
1481 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1482 {
1483         fd_set *readset = NULL, *writeset = NULL;
1484         double start_time, total_time;
1485         int r, max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1486         u_int64_t ibytes, obytes;
1487         u_int nalloc = 0;
1488         char buf[100];
1489
1490         debug("Entering interactive session.");
1491
1492         start_time = get_current_time();
1493
1494         /* Initialize variables. */
1495         escape_pending1 = 0;
1496         last_was_cr = 1;
1497         exit_status = -1;
1498         stdin_eof = 0;
1499         buffer_high = 64 * 1024;
1500         connection_in = packet_get_connection_in();
1501         connection_out = packet_get_connection_out();
1502         max_fd = MAX(connection_in, connection_out);
1503
1504         if (!compat20) {
1505                 /* enable nonblocking unless tty */
1506                 if (!isatty(fileno(stdin)))
1507                         set_nonblock(fileno(stdin));
1508                 if (!isatty(fileno(stdout)))
1509                         set_nonblock(fileno(stdout));
1510                 if (!isatty(fileno(stderr)))
1511                         set_nonblock(fileno(stderr));
1512                 max_fd = MAX(max_fd, fileno(stdin));
1513                 max_fd = MAX(max_fd, fileno(stdout));
1514                 max_fd = MAX(max_fd, fileno(stderr));
1515         }
1516         quit_pending = 0;
1517         escape_char1 = escape_char_arg;
1518
1519         /* Initialize buffers. */
1520         buffer_init(&stdin_buffer);
1521         buffer_init(&stdout_buffer);
1522         buffer_init(&stderr_buffer);
1523
1524         client_init_dispatch();
1525
1526         /*
1527          * Set signal handlers, (e.g. to restore non-blocking mode)
1528          * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1529          */
1530         if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1531                 signal(SIGHUP, signal_handler);
1532         if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1533                 signal(SIGINT, signal_handler);
1534         if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1535                 signal(SIGQUIT, signal_handler);
1536         if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1537                 signal(SIGTERM, signal_handler);
1538         signal(SIGWINCH, window_change_handler);
1539
1540         if (have_pty)
1541                 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1542
1543         if (compat20) {
1544                 session_ident = ssh2_chan_id;
1545                 if (session_ident != -1) {
1546                         if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1547                                 channel_register_filter(session_ident,
1548                                     client_simple_escape_filter, NULL,
1549                                     client_filter_cleanup,
1550                                     client_new_escape_filter_ctx(
1551                                     escape_char_arg));
1552                         }
1553                         channel_register_cleanup(session_ident,
1554                             client_channel_closed, 0);
1555                 }
1556         } else {
1557                 /* Check if we should immediately send eof on stdin. */
1558                 client_check_initial_eof_on_stdin();
1559         }
1560
1561         /* Main loop of the client for the interactive session mode. */
1562         while (!quit_pending) {
1563
1564                 /* Process buffered packets sent by the server. */
1565                 client_process_buffered_input_packets();
1566
1567                 if (compat20 && session_closed && !channel_still_open())
1568                         break;
1569
1570                 rekeying = (active_state->kex != NULL && !active_state->kex->done);
1571
1572                 if (rekeying) {
1573                         debug("rekeying in progress");
1574                 } else {
1575                         /*
1576                          * Make packets of buffered stdin data, and buffer
1577                          * them for sending to the server.
1578                          */
1579                         if (!compat20)
1580                                 client_make_packets_from_stdin_data();
1581
1582                         /*
1583                          * Make packets from buffered channel data, and
1584                          * enqueue them for sending to the server.
1585                          */
1586                         if (packet_not_very_much_data_to_write())
1587                                 channel_output_poll();
1588
1589                         /*
1590                          * Check if the window size has changed, and buffer a
1591                          * message about it to the server if so.
1592                          */
1593                         client_check_window_change();
1594
1595                         if (quit_pending)
1596                                 break;
1597                 }
1598                 /*
1599                  * Wait until we have something to do (something becomes
1600                  * available on one of the descriptors).
1601                  */
1602                 max_fd2 = max_fd;
1603                 client_wait_until_can_do_something(&readset, &writeset,
1604                     &max_fd2, &nalloc, rekeying);
1605
1606                 if (quit_pending)
1607                         break;
1608
1609                 /* Do channel operations unless rekeying in progress. */
1610                 if (!rekeying) {
1611                         channel_after_select(readset, writeset);
1612                         if (need_rekeying || packet_need_rekeying()) {
1613                                 debug("need rekeying");
1614                                 active_state->kex->done = 0;
1615                                 if ((r = kex_send_kexinit(active_state)) != 0)
1616                                         fatal("%s: kex_send_kexinit: %s",
1617                                             __func__, ssh_err(r));
1618                                 need_rekeying = 0;
1619                         }
1620                 }
1621
1622                 /* Buffer input from the connection.  */
1623                 client_process_net_input(readset);
1624
1625                 if (quit_pending)
1626                         break;
1627
1628                 if (!compat20) {
1629                         /* Buffer data from stdin */
1630                         client_process_input(readset);
1631                         /*
1632                          * Process output to stdout and stderr.  Output to
1633                          * the connection is processed elsewhere (above).
1634                          */
1635                         client_process_output(writeset);
1636                 }
1637
1638                 if (session_resumed) {
1639                         connection_in = packet_get_connection_in();
1640                         connection_out = packet_get_connection_out();
1641                         max_fd = MAX(max_fd, connection_out);
1642                         max_fd = MAX(max_fd, connection_in);
1643                         session_resumed = 0;
1644                 }
1645
1646                 /*
1647                  * Send as much buffered packet data as possible to the
1648                  * sender.
1649                  */
1650                 if (FD_ISSET(connection_out, writeset))
1651                         packet_write_poll();
1652
1653                 /*
1654                  * If we are a backgrounded control master, and the
1655                  * timeout has expired without any active client
1656                  * connections, then quit.
1657                  */
1658                 if (control_persist_exit_time > 0) {
1659                         if (monotime() >= control_persist_exit_time) {
1660                                 debug("ControlPersist timeout expired");
1661                                 break;
1662                         }
1663                 }
1664         }
1665         free(readset);
1666         free(writeset);
1667
1668         /* Terminate the session. */
1669
1670         /* Stop watching for window change. */
1671         signal(SIGWINCH, SIG_DFL);
1672
1673         if (compat20) {
1674                 packet_start(SSH2_MSG_DISCONNECT);
1675                 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1676                 packet_put_cstring("disconnected by user");
1677                 packet_put_cstring(""); /* language tag */
1678                 packet_send();
1679                 packet_write_wait();
1680         }
1681
1682         channel_free_all();
1683
1684         if (have_pty)
1685                 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1686
1687         /* restore blocking io */
1688         if (!isatty(fileno(stdin)))
1689                 unset_nonblock(fileno(stdin));
1690         if (!isatty(fileno(stdout)))
1691                 unset_nonblock(fileno(stdout));
1692         if (!isatty(fileno(stderr)))
1693                 unset_nonblock(fileno(stderr));
1694
1695         /*
1696          * If there was no shell or command requested, there will be no remote
1697          * exit status to be returned.  In that case, clear error code if the
1698          * connection was deliberately terminated at this end.
1699          */
1700         if (no_shell_flag && received_signal == SIGTERM) {
1701                 received_signal = 0;
1702                 exit_status = 0;
1703         }
1704
1705         if (received_signal)
1706                 fatal("Killed by signal %d.", (int) received_signal);
1707
1708         /*
1709          * In interactive mode (with pseudo tty) display a message indicating
1710          * that the connection has been closed.
1711          */
1712         if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1713                 snprintf(buf, sizeof buf,
1714                     "Connection to %.64s closed.\r\n", host);
1715                 buffer_append(&stderr_buffer, buf, strlen(buf));
1716         }
1717
1718         /* Output any buffered data for stdout. */
1719         if (buffer_len(&stdout_buffer) > 0) {
1720                 len = atomicio(vwrite, fileno(stdout),
1721                     buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer));
1722                 if (len < 0 || (u_int)len != buffer_len(&stdout_buffer))
1723                         error("Write failed flushing stdout buffer.");
1724                 else
1725                         buffer_consume(&stdout_buffer, len);
1726         }
1727
1728         /* Output any buffered data for stderr. */
1729         if (buffer_len(&stderr_buffer) > 0) {
1730                 len = atomicio(vwrite, fileno(stderr),
1731                     buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1732                 if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1733                         error("Write failed flushing stderr buffer.");
1734                 else
1735                         buffer_consume(&stderr_buffer, len);
1736         }
1737
1738         /* Clear and free any buffers. */
1739         memset(buf, 0, sizeof(buf));
1740         buffer_free(&stdin_buffer);
1741         buffer_free(&stdout_buffer);
1742         buffer_free(&stderr_buffer);
1743
1744         /* Report bytes transferred, and transfer rates. */
1745         total_time = get_current_time() - start_time;
1746         packet_get_bytes(&ibytes, &obytes);
1747         verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1748             (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1749         if (total_time > 0)
1750                 verbose("Bytes per second: sent %.1f, received %.1f",
1751                     obytes / total_time, ibytes / total_time);
1752         /* Return the exit status of the program. */
1753         debug("Exit status %d", exit_status);
1754         return exit_status;
1755 }
1756
1757 /*********/
1758
1759 static int
1760 client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1761 {
1762         u_int data_len;
1763         char *data = packet_get_string(&data_len);
1764         packet_check_eom();
1765         buffer_append(&stdout_buffer, data, data_len);
1766         explicit_bzero(data, data_len);
1767         free(data);
1768         return 0;
1769 }
1770 static int
1771 client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1772 {
1773         u_int data_len;
1774         char *data = packet_get_string(&data_len);
1775         packet_check_eom();
1776         buffer_append(&stderr_buffer, data, data_len);
1777         explicit_bzero(data, data_len);
1778         free(data);
1779         return 0;
1780 }
1781 static int
1782 client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1783 {
1784         exit_status = packet_get_int();
1785         packet_check_eom();
1786         /* Acknowledge the exit. */
1787         packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1788         packet_send();
1789         /*
1790          * Must wait for packet to be sent since we are
1791          * exiting the loop.
1792          */
1793         packet_write_wait();
1794         /* Flag that we want to exit. */
1795         quit_pending = 1;
1796         return 0;
1797 }
1798
1799 static int
1800 client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1801 {
1802         Channel *c = NULL;
1803         int r, remote_id, sock;
1804
1805         /* Read the remote channel number from the message. */
1806         remote_id = packet_get_int();
1807         packet_check_eom();
1808
1809         /*
1810          * Get a connection to the local authentication agent (this may again
1811          * get forwarded).
1812          */
1813         if ((r = ssh_get_authentication_socket(&sock)) != 0 &&
1814             r != SSH_ERR_AGENT_NOT_PRESENT)
1815                 debug("%s: ssh_get_authentication_socket: %s",
1816                     __func__, ssh_err(r));
1817
1818
1819         /*
1820          * If we could not connect the agent, send an error message back to
1821          * the server. This should never happen unless the agent dies,
1822          * because authentication forwarding is only enabled if we have an
1823          * agent.
1824          */
1825         if (sock >= 0) {
1826                 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1827                     -1, 0, 0, 0, "authentication agent connection", 1);
1828                 c->remote_id = remote_id;
1829                 c->force_drain = 1;
1830         }
1831         if (c == NULL) {
1832                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1833                 packet_put_int(remote_id);
1834         } else {
1835                 /* Send a confirmation to the remote host. */
1836                 debug("Forwarding authentication connection.");
1837                 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1838                 packet_put_int(remote_id);
1839                 packet_put_int(c->self);
1840         }
1841         packet_send();
1842         return 0;
1843 }
1844
1845 static Channel *
1846 client_request_forwarded_tcpip(const char *request_type, int rchan)
1847 {
1848         Channel *c = NULL;
1849         char *listen_address, *originator_address;
1850         u_short listen_port, originator_port;
1851
1852         /* Get rest of the packet */
1853         listen_address = packet_get_string(NULL);
1854         listen_port = packet_get_int();
1855         originator_address = packet_get_string(NULL);
1856         originator_port = packet_get_int();
1857         packet_check_eom();
1858
1859         debug("%s: listen %s port %d, originator %s port %d", __func__,
1860             listen_address, listen_port, originator_address, originator_port);
1861
1862         c = channel_connect_by_listen_address(listen_address, listen_port,
1863             "forwarded-tcpip", originator_address);
1864
1865         free(originator_address);
1866         free(listen_address);
1867         return c;
1868 }
1869
1870 static Channel *
1871 client_request_forwarded_streamlocal(const char *request_type, int rchan)
1872 {
1873         Channel *c = NULL;
1874         char *listen_path;
1875
1876         /* Get the remote path. */
1877         listen_path = packet_get_string(NULL);
1878         /* XXX: Skip reserved field for now. */
1879         if (packet_get_string_ptr(NULL) == NULL)
1880                 fatal("%s: packet_get_string_ptr failed", __func__);
1881         packet_check_eom();
1882
1883         debug("%s: %s", __func__, listen_path);
1884
1885         c = channel_connect_by_listen_path(listen_path,
1886             "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1887         free(listen_path);
1888         return c;
1889 }
1890
1891 static Channel *
1892 client_request_x11(const char *request_type, int rchan)
1893 {
1894         Channel *c = NULL;
1895         char *originator;
1896         u_short originator_port;
1897         int sock;
1898
1899         if (!options.forward_x11) {
1900                 error("Warning: ssh server tried X11 forwarding.");
1901                 error("Warning: this is probably a break-in attempt by a "
1902                     "malicious server.");
1903                 return NULL;
1904         }
1905         if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
1906                 verbose("Rejected X11 connection after ForwardX11Timeout "
1907                     "expired");
1908                 return NULL;
1909         }
1910         originator = packet_get_string(NULL);
1911         if (datafellows & SSH_BUG_X11FWD) {
1912                 debug2("buggy server: x11 request w/o originator_port");
1913                 originator_port = 0;
1914         } else {
1915                 originator_port = packet_get_int();
1916         }
1917         packet_check_eom();
1918         /* XXX check permission */
1919         debug("client_request_x11: request from %s %d", originator,
1920             originator_port);
1921         free(originator);
1922         sock = x11_connect_display();
1923         if (sock < 0)
1924                 return NULL;
1925         c = channel_new("x11",
1926             SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1927             CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1928         c->force_drain = 1;
1929         return c;
1930 }
1931
1932 static Channel *
1933 client_request_agent(const char *request_type, int rchan)
1934 {
1935         Channel *c = NULL;
1936         int r, sock;
1937
1938         if (!options.forward_agent) {
1939                 error("Warning: ssh server tried agent forwarding.");
1940                 error("Warning: this is probably a break-in attempt by a "
1941                     "malicious server.");
1942                 return NULL;
1943         }
1944         if ((r = ssh_get_authentication_socket(&sock)) != 0) {
1945                 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1946                         debug("%s: ssh_get_authentication_socket: %s",
1947                             __func__, ssh_err(r));
1948                 return NULL;
1949         }
1950         c = channel_new("authentication agent connection",
1951             SSH_CHANNEL_OPEN, sock, sock, -1,
1952             CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1953             "authentication agent connection", 1);
1954         c->force_drain = 1;
1955         return c;
1956 }
1957
1958 int
1959 client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
1960 {
1961         Channel *c;
1962         int fd;
1963
1964         if (tun_mode == SSH_TUNMODE_NO)
1965                 return 0;
1966
1967         if (!compat20) {
1968                 error("Tunnel forwarding is not supported for protocol 1");
1969                 return -1;
1970         }
1971
1972         debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1973
1974         /* Open local tunnel device */
1975         if ((fd = tun_open(local_tun, tun_mode)) == -1) {
1976                 error("Tunnel device open failed.");
1977                 return -1;
1978         }
1979
1980         c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1981             CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1982         c->datagram = 1;
1983
1984 #if defined(SSH_TUN_FILTER)
1985         if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1986                 channel_register_filter(c->self, sys_tun_infilter,
1987                     sys_tun_outfilter, NULL, NULL);
1988 #endif
1989
1990         packet_start(SSH2_MSG_CHANNEL_OPEN);
1991         packet_put_cstring("tun@openssh.com");
1992         packet_put_int(c->self);
1993         packet_put_int(c->local_window_max);
1994         packet_put_int(c->local_maxpacket);
1995         packet_put_int(tun_mode);
1996         packet_put_int(remote_tun);
1997         packet_send();
1998
1999         return 0;
2000 }
2001
2002 /* XXXX move to generic input handler */
2003 static int
2004 client_input_channel_open(int type, u_int32_t seq, void *ctxt)
2005 {
2006         Channel *c = NULL;
2007         char *ctype;
2008         int rchan;
2009         u_int rmaxpack, rwindow, len;
2010
2011         ctype = packet_get_string(&len);
2012         rchan = packet_get_int();
2013         rwindow = packet_get_int();
2014         rmaxpack = packet_get_int();
2015
2016         debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
2017             ctype, rchan, rwindow, rmaxpack);
2018
2019         if (strcmp(ctype, "forwarded-tcpip") == 0) {
2020                 c = client_request_forwarded_tcpip(ctype, rchan);
2021         } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
2022                 c = client_request_forwarded_streamlocal(ctype, rchan);
2023         } else if (strcmp(ctype, "x11") == 0) {
2024                 c = client_request_x11(ctype, rchan);
2025         } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
2026                 c = client_request_agent(ctype, rchan);
2027         }
2028 /* XXX duplicate : */
2029         if (c != NULL) {
2030                 debug("confirm %s", ctype);
2031                 c->remote_id = rchan;
2032                 c->remote_window = rwindow;
2033                 c->remote_maxpacket = rmaxpack;
2034                 if (c->type != SSH_CHANNEL_CONNECTING) {
2035                         packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
2036                         packet_put_int(c->remote_id);
2037                         packet_put_int(c->self);
2038                         packet_put_int(c->local_window);
2039                         packet_put_int(c->local_maxpacket);
2040                         packet_send();
2041                 }
2042         } else {
2043                 debug("failure %s", ctype);
2044                 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
2045                 packet_put_int(rchan);
2046                 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
2047                 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2048                         packet_put_cstring("open failed");
2049                         packet_put_cstring("");
2050                 }
2051                 packet_send();
2052         }
2053         free(ctype);
2054         return 0;
2055 }
2056
2057 static int
2058 client_input_channel_req(int type, u_int32_t seq, void *ctxt)
2059 {
2060         Channel *c = NULL;
2061         int exitval, id, reply, success = 0;
2062         char *rtype;
2063
2064         id = packet_get_int();
2065         rtype = packet_get_string(NULL);
2066         reply = packet_get_char();
2067
2068         debug("client_input_channel_req: channel %d rtype %s reply %d",
2069             id, rtype, reply);
2070
2071         if (id == -1) {
2072                 error("client_input_channel_req: request for channel -1");
2073         } else if ((c = channel_lookup(id)) == NULL) {
2074                 error("client_input_channel_req: channel %d: "
2075                     "unknown channel", id);
2076         } else if (strcmp(rtype, "eow@openssh.com") == 0) {
2077                 packet_check_eom();
2078                 chan_rcvd_eow(c);
2079         } else if (strcmp(rtype, "exit-status") == 0) {
2080                 exitval = packet_get_int();
2081                 if (c->ctl_chan != -1) {
2082                         mux_exit_message(c, exitval);
2083                         success = 1;
2084                 } else if (id == session_ident) {
2085                         /* Record exit value of local session */
2086                         success = 1;
2087                         exit_status = exitval;
2088                 } else {
2089                         /* Probably for a mux channel that has already closed */
2090                         debug("%s: no sink for exit-status on channel %d",
2091                             __func__, id);
2092                 }
2093                 packet_check_eom();
2094         }
2095         if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
2096                 packet_start(success ?
2097                     SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
2098                 packet_put_int(c->remote_id);
2099                 packet_send();
2100         }
2101         free(rtype);
2102         return 0;
2103 }
2104
2105 struct hostkeys_update_ctx {
2106         /* The hostname and (optionally) IP address string for the server */
2107         char *host_str, *ip_str;
2108
2109         /*
2110          * Keys received from the server and a flag for each indicating
2111          * whether they already exist in known_hosts.
2112          * keys_seen is filled in by hostkeys_find() and later (for new
2113          * keys) by client_global_hostkeys_private_confirm().
2114          */
2115         struct sshkey **keys;
2116         int *keys_seen;
2117         size_t nkeys;
2118
2119         size_t nnew;
2120
2121         /*
2122          * Keys that are in known_hosts, but were not present in the update
2123          * from the server (i.e. scheduled to be deleted).
2124          * Filled in by hostkeys_find().
2125          */
2126         struct sshkey **old_keys;
2127         size_t nold;
2128 };
2129
2130 static void
2131 hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
2132 {
2133         size_t i;
2134
2135         if (ctx == NULL)
2136                 return;
2137         for (i = 0; i < ctx->nkeys; i++)
2138                 sshkey_free(ctx->keys[i]);
2139         free(ctx->keys);
2140         free(ctx->keys_seen);
2141         for (i = 0; i < ctx->nold; i++)
2142                 sshkey_free(ctx->old_keys[i]);
2143         free(ctx->old_keys);
2144         free(ctx->host_str);
2145         free(ctx->ip_str);
2146         free(ctx);
2147 }
2148
2149 static int
2150 hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
2151 {
2152         struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2153         size_t i;
2154         struct sshkey **tmp;
2155
2156         if (l->status != HKF_STATUS_MATCHED || l->key == NULL ||
2157             l->key->type == KEY_RSA1)
2158                 return 0;
2159
2160         /* Mark off keys we've already seen for this host */
2161         for (i = 0; i < ctx->nkeys; i++) {
2162                 if (sshkey_equal(l->key, ctx->keys[i])) {
2163                         debug3("%s: found %s key at %s:%ld", __func__,
2164                             sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
2165                         ctx->keys_seen[i] = 1;
2166                         return 0;
2167                 }
2168         }
2169         /* This line contained a key that not offered by the server */
2170         debug3("%s: deprecated %s key at %s:%ld", __func__,
2171             sshkey_ssh_name(l->key), l->path, l->linenum);
2172         if ((tmp = reallocarray(ctx->old_keys, ctx->nold + 1,
2173             sizeof(*ctx->old_keys))) == NULL)
2174                 fatal("%s: reallocarray failed nold = %zu",
2175                     __func__, ctx->nold);
2176         ctx->old_keys = tmp;
2177         ctx->old_keys[ctx->nold++] = l->key;
2178         l->key = NULL;
2179
2180         return 0;
2181 }
2182
2183 static void
2184 update_known_hosts(struct hostkeys_update_ctx *ctx)
2185 {
2186         int r, was_raw = 0;
2187         int loglevel = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK ?
2188             SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
2189         char *fp, *response;
2190         size_t i;
2191
2192         for (i = 0; i < ctx->nkeys; i++) {
2193                 if (ctx->keys_seen[i] != 2)
2194                         continue;
2195                 if ((fp = sshkey_fingerprint(ctx->keys[i],
2196                     options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
2197                         fatal("%s: sshkey_fingerprint failed", __func__);
2198                 do_log2(loglevel, "Learned new hostkey: %s %s",
2199                     sshkey_type(ctx->keys[i]), fp);
2200                 free(fp);
2201         }
2202         for (i = 0; i < ctx->nold; i++) {
2203                 if ((fp = sshkey_fingerprint(ctx->old_keys[i],
2204                     options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
2205                         fatal("%s: sshkey_fingerprint failed", __func__);
2206                 do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
2207                     sshkey_type(ctx->old_keys[i]), fp);
2208                 free(fp);
2209         }
2210         if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
2211                 if (get_saved_tio() != NULL) {
2212                         leave_raw_mode(1);
2213                         was_raw = 1;
2214                 }
2215                 response = NULL;
2216                 for (i = 0; !quit_pending && i < 3; i++) {
2217                         free(response);
2218                         response = read_passphrase("Accept updated hostkeys? "
2219                             "(yes/no): ", RP_ECHO);
2220                         if (strcasecmp(response, "yes") == 0)
2221                                 break;
2222                         else if (quit_pending || response == NULL ||
2223                             strcasecmp(response, "no") == 0) {
2224                                 options.update_hostkeys = 0;
2225                                 break;
2226                         } else {
2227                                 do_log2(loglevel, "Please enter "
2228                                     "\"yes\" or \"no\"");
2229                         }
2230                 }
2231                 if (quit_pending || i >= 3 || response == NULL)
2232                         options.update_hostkeys = 0;
2233                 free(response);
2234                 if (was_raw)
2235                         enter_raw_mode(1);
2236         }
2237
2238         /*
2239          * Now that all the keys are verified, we can go ahead and replace
2240          * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
2241          * cancel the operation).
2242          */
2243         if (options.update_hostkeys != 0 &&
2244             (r = hostfile_replace_entries(options.user_hostfiles[0],
2245             ctx->host_str, ctx->ip_str, ctx->keys, ctx->nkeys,
2246             options.hash_known_hosts, 0,
2247             options.fingerprint_hash)) != 0)
2248                 error("%s: hostfile_replace_entries failed: %s",
2249                     __func__, ssh_err(r));
2250 }
2251
2252 static void
2253 client_global_hostkeys_private_confirm(int type, u_int32_t seq, void *_ctx)
2254 {
2255         struct ssh *ssh = active_state; /* XXX */
2256         struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2257         size_t i, ndone;
2258         struct sshbuf *signdata;
2259         int r;
2260         const u_char *sig;
2261         size_t siglen;
2262
2263         if (ctx->nnew == 0)
2264                 fatal("%s: ctx->nnew == 0", __func__); /* sanity */
2265         if (type != SSH2_MSG_REQUEST_SUCCESS) {
2266                 error("Server failed to confirm ownership of "
2267                     "private host keys");
2268                 hostkeys_update_ctx_free(ctx);
2269                 return;
2270         }
2271         if ((signdata = sshbuf_new()) == NULL)
2272                 fatal("%s: sshbuf_new failed", __func__);
2273         /* Don't want to accidentally accept an unbound signature */
2274         if (ssh->kex->session_id_len == 0)
2275                 fatal("%s: ssh->kex->session_id_len == 0", __func__);
2276         /*
2277          * Expect a signature for each of the ctx->nnew private keys we
2278          * haven't seen before. They will be in the same order as the
2279          * ctx->keys where the corresponding ctx->keys_seen[i] == 0.
2280          */
2281         for (ndone = i = 0; i < ctx->nkeys; i++) {
2282                 if (ctx->keys_seen[i])
2283                         continue;
2284                 /* Prepare data to be signed: session ID, unique string, key */
2285                 sshbuf_reset(signdata);
2286                 if ( (r = sshbuf_put_cstring(signdata,
2287                     "hostkeys-prove-00@openssh.com")) != 0 ||
2288                     (r = sshbuf_put_string(signdata, ssh->kex->session_id,
2289                     ssh->kex->session_id_len)) != 0 ||
2290                     (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
2291                         fatal("%s: failed to prepare signature: %s",
2292                             __func__, ssh_err(r));
2293                 /* Extract and verify signature */
2294                 if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
2295                         error("%s: couldn't parse message: %s",
2296                             __func__, ssh_err(r));
2297                         goto out;
2298                 }
2299                 if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
2300                     sshbuf_ptr(signdata), sshbuf_len(signdata), 0)) != 0) {
2301                         error("%s: server gave bad signature for %s key %zu",
2302                             __func__, sshkey_type(ctx->keys[i]), i);
2303                         goto out;
2304                 }
2305                 /* Key is good. Mark it as 'seen' */
2306                 ctx->keys_seen[i] = 2;
2307                 ndone++;
2308         }
2309         if (ndone != ctx->nnew)
2310                 fatal("%s: ndone != ctx->nnew (%zu / %zu)", __func__,
2311                     ndone, ctx->nnew);  /* Shouldn't happen */
2312         ssh_packet_check_eom(ssh);
2313
2314         /* Make the edits to known_hosts */
2315         update_known_hosts(ctx);
2316  out:
2317         hostkeys_update_ctx_free(ctx);
2318 }
2319
2320 /*
2321  * Handle hostkeys-00@openssh.com global request to inform the client of all
2322  * the server's hostkeys. The keys are checked against the user's
2323  * HostkeyAlgorithms preference before they are accepted.
2324  */
2325 static int
2326 client_input_hostkeys(void)
2327 {
2328         struct ssh *ssh = active_state; /* XXX */
2329         const u_char *blob = NULL;
2330         size_t i, len = 0;
2331         struct sshbuf *buf = NULL;
2332         struct sshkey *key = NULL, **tmp;
2333         int r;
2334         char *fp;
2335         static int hostkeys_seen = 0; /* XXX use struct ssh */
2336         extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
2337         struct hostkeys_update_ctx *ctx = NULL;
2338
2339         if (hostkeys_seen)
2340                 fatal("%s: server already sent hostkeys", __func__);
2341         if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
2342             options.batch_mode)
2343                 return 1; /* won't ask in batchmode, so don't even try */
2344         if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
2345                 return 1;
2346
2347         ctx = xcalloc(1, sizeof(*ctx));
2348         while (ssh_packet_remaining(ssh) > 0) {
2349                 sshkey_free(key);
2350                 key = NULL;
2351                 if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
2352                         error("%s: couldn't parse message: %s",
2353                             __func__, ssh_err(r));
2354                         goto out;
2355                 }
2356                 if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
2357                         error("%s: parse key: %s", __func__, ssh_err(r));
2358                         goto out;
2359                 }
2360                 fp = sshkey_fingerprint(key, options.fingerprint_hash,
2361                     SSH_FP_DEFAULT);
2362                 debug3("%s: received %s key %s", __func__,
2363                     sshkey_type(key), fp);
2364                 free(fp);
2365                 /* Check that the key is accepted in HostkeyAlgorithms */
2366                 if (options.hostkeyalgorithms != NULL &&
2367                     match_pattern_list(sshkey_ssh_name(key),
2368                     options.hostkeyalgorithms, 0) != 1) {
2369                         debug3("%s: %s key not permitted by HostkeyAlgorithms",
2370                             __func__, sshkey_ssh_name(key));
2371                         continue;
2372                 }
2373                 /* Skip certs */
2374                 if (sshkey_is_cert(key)) {
2375                         debug3("%s: %s key is a certificate; skipping",
2376                             __func__, sshkey_ssh_name(key));
2377                         continue;
2378                 }
2379                 /* Ensure keys are unique */
2380                 for (i = 0; i < ctx->nkeys; i++) {
2381                         if (sshkey_equal(key, ctx->keys[i])) {
2382                                 error("%s: received duplicated %s host key",
2383                                     __func__, sshkey_ssh_name(key));
2384                                 goto out;
2385                         }
2386                 }
2387                 /* Key is good, record it */
2388                 if ((tmp = reallocarray(ctx->keys, ctx->nkeys + 1,
2389                     sizeof(*ctx->keys))) == NULL)
2390                         fatal("%s: reallocarray failed nkeys = %zu",
2391                             __func__, ctx->nkeys);
2392                 ctx->keys = tmp;
2393                 ctx->keys[ctx->nkeys++] = key;
2394                 key = NULL;
2395         }
2396
2397         if (ctx->nkeys == 0) {
2398                 debug("%s: server sent no hostkeys", __func__);
2399                 goto out;
2400         }
2401
2402         if ((ctx->keys_seen = calloc(ctx->nkeys,
2403             sizeof(*ctx->keys_seen))) == NULL)
2404                 fatal("%s: calloc failed", __func__);
2405
2406         get_hostfile_hostname_ipaddr(host,
2407             options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
2408             options.port, &ctx->host_str,
2409             options.check_host_ip ? &ctx->ip_str : NULL);
2410
2411         /* Find which keys we already know about. */
2412         if ((r = hostkeys_foreach(options.user_hostfiles[0], hostkeys_find,
2413             ctx, ctx->host_str, ctx->ip_str,
2414             HKF_WANT_PARSE_KEY|HKF_WANT_MATCH)) != 0) {
2415                 error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
2416                 goto out;
2417         }
2418
2419         /* Figure out if we have any new keys to add */
2420         ctx->nnew = 0;
2421         for (i = 0; i < ctx->nkeys; i++) {
2422                 if (!ctx->keys_seen[i])
2423                         ctx->nnew++;
2424         }
2425
2426         debug3("%s: %zu keys from server: %zu new, %zu retained. %zu to remove",
2427             __func__, ctx->nkeys, ctx->nnew, ctx->nkeys - ctx->nnew, ctx->nold);
2428
2429         if (ctx->nnew == 0 && ctx->nold != 0) {
2430                 /* We have some keys to remove. Just do it. */
2431                 update_known_hosts(ctx);
2432         } else if (ctx->nnew != 0) {
2433                 /*
2434                  * We have received hitherto-unseen keys from the server.
2435                  * Ask the server to confirm ownership of the private halves.
2436                  */
2437                 debug3("%s: asking server to prove ownership for %zu keys",
2438                     __func__, ctx->nnew);
2439                 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2440                     (r = sshpkt_put_cstring(ssh,
2441                     "hostkeys-prove-00@openssh.com")) != 0 ||
2442                     (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
2443                         fatal("%s: cannot prepare packet: %s",
2444                             __func__, ssh_err(r));
2445                 if ((buf = sshbuf_new()) == NULL)
2446                         fatal("%s: sshbuf_new", __func__);
2447                 for (i = 0; i < ctx->nkeys; i++) {
2448                         if (ctx->keys_seen[i])
2449                                 continue;
2450                         sshbuf_reset(buf);
2451                         if ((r = sshkey_putb(ctx->keys[i], buf)) != 0)
2452                                 fatal("%s: sshkey_putb: %s",
2453                                     __func__, ssh_err(r));
2454                         if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
2455                                 fatal("%s: sshpkt_put_string: %s",
2456                                     __func__, ssh_err(r));
2457                 }
2458                 if ((r = sshpkt_send(ssh)) != 0)
2459                         fatal("%s: sshpkt_send: %s", __func__, ssh_err(r));
2460                 client_register_global_confirm(
2461                     client_global_hostkeys_private_confirm, ctx);
2462                 ctx = NULL;  /* will be freed in callback */
2463         }
2464
2465         /* Success */
2466  out:
2467         hostkeys_update_ctx_free(ctx);
2468         sshkey_free(key);
2469         sshbuf_free(buf);
2470         /*
2471          * NB. Return success for all cases. The server doesn't need to know
2472          * what the client does with its hosts file.
2473          */
2474         return 1;
2475 }
2476
2477 static int
2478 client_input_global_request(int type, u_int32_t seq, void *ctxt)
2479 {
2480         char *rtype;
2481         int want_reply;
2482         int success = 0;
2483
2484         rtype = packet_get_cstring(NULL);
2485         want_reply = packet_get_char();
2486         debug("client_input_global_request: rtype %s want_reply %d",
2487             rtype, want_reply);
2488         if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
2489                 success = client_input_hostkeys();
2490         if (want_reply) {
2491                 packet_start(success ?
2492                     SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
2493                 packet_send();
2494                 packet_write_wait();
2495         }
2496         free(rtype);
2497         return 0;
2498 }
2499
2500 void
2501 client_session2_setup(int id, int want_tty, int want_subsystem,
2502     const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
2503 {
2504         int len;
2505         Channel *c = NULL;
2506
2507         debug2("%s: id %d", __func__, id);
2508
2509         if ((c = channel_lookup(id)) == NULL)
2510                 fatal("client_session2_setup: channel %d: unknown channel", id);
2511
2512         packet_set_interactive(want_tty,
2513             options.ip_qos_interactive, options.ip_qos_bulk);
2514
2515         if (want_tty) {
2516                 struct winsize ws;
2517
2518                 /* Store window size in the packet. */
2519                 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2520                         memset(&ws, 0, sizeof(ws));
2521
2522                 channel_request_start(id, "pty-req", 1);
2523                 client_expect_confirm(id, "PTY allocation", CONFIRM_TTY);
2524                 packet_put_cstring(term != NULL ? term : "");
2525                 packet_put_int((u_int)ws.ws_col);
2526                 packet_put_int((u_int)ws.ws_row);
2527                 packet_put_int((u_int)ws.ws_xpixel);
2528                 packet_put_int((u_int)ws.ws_ypixel);
2529                 if (tiop == NULL)
2530                         tiop = get_saved_tio();
2531                 tty_make_modes(-1, tiop);
2532                 packet_send();
2533                 /* XXX wait for reply */
2534                 c->client_tty = 1;
2535         }
2536
2537         /* Transfer any environment variables from client to server */
2538         if (options.num_send_env != 0 && env != NULL) {
2539                 int i, j, matched;
2540                 char *name, *val;
2541
2542                 debug("Sending environment.");
2543                 for (i = 0; env[i] != NULL; i++) {
2544                         /* Split */
2545                         name = xstrdup(env[i]);
2546                         if ((val = strchr(name, '=')) == NULL) {
2547                                 free(name);
2548                                 continue;
2549                         }
2550                         *val++ = '\0';
2551
2552                         matched = 0;
2553                         for (j = 0; j < options.num_send_env; j++) {
2554                                 if (match_pattern(name, options.send_env[j])) {
2555                                         matched = 1;
2556                                         break;
2557                                 }
2558                         }
2559                         if (!matched) {
2560                                 debug3("Ignored env %s", name);
2561                                 free(name);
2562                                 continue;
2563                         }
2564
2565                         debug("Sending env %s = %s", name, val);
2566                         channel_request_start(id, "env", 0);
2567                         packet_put_cstring(name);
2568                         packet_put_cstring(val);
2569                         packet_send();
2570                         free(name);
2571                 }
2572         }
2573
2574         len = buffer_len(cmd);
2575         if (len > 0) {
2576                 if (len > 900)
2577                         len = 900;
2578                 if (want_subsystem) {
2579                         debug("Sending subsystem: %.*s",
2580                             len, (u_char*)buffer_ptr(cmd));
2581                         channel_request_start(id, "subsystem", 1);
2582                         client_expect_confirm(id, "subsystem", CONFIRM_CLOSE);
2583                 } else {
2584                         debug("Sending command: %.*s",
2585                             len, (u_char*)buffer_ptr(cmd));
2586                         channel_request_start(id, "exec", 1);
2587                         client_expect_confirm(id, "exec", CONFIRM_CLOSE);
2588                 }
2589                 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2590                 packet_send();
2591         } else {
2592                 channel_request_start(id, "shell", 1);
2593                 client_expect_confirm(id, "shell", CONFIRM_CLOSE);
2594                 packet_send();
2595         }
2596 }
2597
2598 static void
2599 client_init_dispatch_20(void)
2600 {
2601         dispatch_init(&dispatch_protocol_error);
2602
2603         dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2604         dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2605         dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2606         dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2607         dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2608         dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2609         dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2610         dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2611         dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2612         dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2613         dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2614         dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2615
2616         /* rekeying */
2617         dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2618
2619         /* global request reply messages */
2620         dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2621         dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2622 }
2623
2624 static void
2625 client_init_dispatch_13(void)
2626 {
2627         dispatch_init(NULL);
2628         dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2629         dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2630         dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2631         dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2632         dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2633         dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2634         dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2635         dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2636         dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
2637
2638         dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
2639             &client_input_agent_open : &deny_input_open);
2640         dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2641             &x11_input_open : &deny_input_open);
2642 }
2643
2644 static void
2645 client_init_dispatch_15(void)
2646 {
2647         client_init_dispatch_13();
2648         dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2649         dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2650 }
2651
2652 static void
2653 client_init_dispatch(void)
2654 {
2655         if (compat20)
2656                 client_init_dispatch_20();
2657         else if (compat13)
2658                 client_init_dispatch_13();
2659         else
2660                 client_init_dispatch_15();
2661 }
2662
2663 void
2664 client_stop_mux(void)
2665 {
2666         if (options.control_path != NULL && muxserver_sock != -1)
2667                 unlink(options.control_path);
2668         /*
2669          * If we are in persist mode, or don't have a shell, signal that we
2670          * should close when all active channels are closed.
2671          */
2672         if (options.control_persist || no_shell_flag) {
2673                 session_closed = 1;
2674                 setproctitle("[stopped mux]");
2675         }
2676 }
2677
2678 /* client specific fatal cleanup */
2679 void
2680 cleanup_exit(int i)
2681 {
2682         leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2683         leave_non_blocking();
2684         if (options.control_path != NULL && muxserver_sock != -1)
2685                 unlink(options.control_path);
2686         ssh_kill_proxy_command();
2687         _exit(i);
2688 }