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