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