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