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