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