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