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