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