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