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