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