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