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