Home | History | Annotate | Line # | Download | only in dist
      1 /*	$NetBSD: channels.c,v 1.48 2026/04/08 18:58:40 christos Exp $	*/
      2 /* $OpenBSD: channels.c,v 1.458 2026/03/28 05:16:18 djm Exp $ */
      3 
      4 /*
      5  * Author: Tatu Ylonen <ylo (at) cs.hut.fi>
      6  * Copyright (c) 1995 Tatu Ylonen <ylo (at) cs.hut.fi>, Espoo, Finland
      7  *                    All rights reserved
      8  * This file contains functions for generic socket connection forwarding.
      9  * There is also code for initiating connection forwarding for X11 connections,
     10  * arbitrary tcp/ip connections, and the authentication agent connection.
     11  *
     12  * As far as I am concerned, the code I have written for this software
     13  * can be used freely for any purpose.  Any derived versions of this
     14  * software must be clearly marked as such, and if the derived work is
     15  * incompatible with the protocol description in the RFC file, it must be
     16  * called by a name other than "ssh" or "Secure Shell".
     17  *
     18  * SSH2 support added by Markus Friedl.
     19  * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl.  All rights reserved.
     20  * Copyright (c) 1999 Dug Song.  All rights reserved.
     21  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
     22  *
     23  * Redistribution and use in source and binary forms, with or without
     24  * modification, are permitted provided that the following conditions
     25  * are met:
     26  * 1. Redistributions of source code must retain the above copyright
     27  *    notice, this list of conditions and the following disclaimer.
     28  * 2. Redistributions in binary form must reproduce the above copyright
     29  *    notice, this list of conditions and the following disclaimer in the
     30  *    documentation and/or other materials provided with the distribution.
     31  *
     32  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     33  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     34  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     35  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     36  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     37  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     38  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     39  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     40  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     41  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     42  */
     43 
     44 #include "includes.h"
     45 __RCSID("$NetBSD: channels.c,v 1.48 2026/04/08 18:58:40 christos Exp $");
     46 #include <sys/param.h>
     47 #include <sys/types.h>
     48 #include <sys/stat.h>
     49 #include <sys/ioctl.h>
     50 #include <sys/un.h>
     51 #include <sys/socket.h>
     52 #include <sys/queue.h>
     53 
     54 #include <netinet/in.h>
     55 #include <arpa/inet.h>
     56 
     57 #include <errno.h>
     58 #include <fcntl.h>
     59 #include <limits.h>
     60 #include <netdb.h>
     61 #include <poll.h>
     62 #include <stdarg.h>
     63 #include <stdint.h>
     64 #include <stdio.h>
     65 #include <stdlib.h>
     66 #include <string.h>
     67 #include <termios.h>
     68 #include <unistd.h>
     69 
     70 #include "xmalloc.h"
     71 #include "ssh.h"
     72 #include "ssh2.h"
     73 #include "ssherr.h"
     74 #include "sshbuf.h"
     75 #include "packet.h"
     76 #include "log.h"
     77 #include "misc.h"
     78 #include "channels.h"
     79 #include "compat.h"
     80 #include "canohost.h"
     81 #include "pathnames.h"
     82 #include "match.h"
     83 
     84 
     85 static int hpn_disabled = 0;
     86 static int hpn_buffer_size = 2 * 1024 * 1024;
     87 
     88 /* XXX remove once we're satisfied there's no lurking bugs */
     89 /* #define DEBUG_CHANNEL_POLL 1 */
     90 
     91 /* -- agent forwarding */
     92 #define	NUM_SOCKS	10
     93 
     94 /* -- X11 forwarding */
     95 /* X11 port for display :0 */
     96 #define X11_BASE_PORT	6000
     97 /* Maximum number of fake X11 displays to try. */
     98 #define MAX_DISPLAYS  1000
     99 
    100 /* Per-channel callback for pre/post IO actions */
    101 typedef void chan_fn(struct ssh *, Channel *c);
    102 
    103 /*
    104  * Data structure for storing which hosts are permitted for forward requests.
    105  * The local sides of any remote forwards are stored in this array to prevent
    106  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
    107  * network (which might be behind a firewall).
    108  */
    109 /* XXX: streamlocal wants a path instead of host:port */
    110 /*      Overload host_to_connect; we could just make this match Forward */
    111 /*	XXX - can we use listen_host instead of listen_path? */
    112 struct permission {
    113 	char *host_to_connect;		/* Connect to 'host'. */
    114 	int port_to_connect;		/* Connect to 'port'. */
    115 	char *listen_host;		/* Remote side should listen address. */
    116 	char *listen_path;		/* Remote side should listen path. */
    117 	int listen_port;		/* Remote side should listen port. */
    118 	Channel *downstream;		/* Downstream mux*/
    119 };
    120 
    121 /*
    122  * Stores the forwarding permission state for a single direction (local or
    123  * remote).
    124  */
    125 struct permission_set {
    126 	/*
    127 	 * List of all local permitted host/port pairs to allow for the
    128 	 * user.
    129 	 */
    130 	u_int num_permitted_user;
    131 	struct permission *permitted_user;
    132 
    133 	/*
    134 	 * List of all permitted host/port pairs to allow for the admin.
    135 	 */
    136 	u_int num_permitted_admin;
    137 	struct permission *permitted_admin;
    138 
    139 	/*
    140 	 * If this is true, all opens/listens are permitted.  This is the
    141 	 * case on the server on which we have to trust the client anyway,
    142 	 * and the user could do anything after logging in.
    143 	 */
    144 	int all_permitted;
    145 };
    146 
    147 /* Used to record timeouts per channel type */
    148 struct ssh_channel_timeout {
    149 	char *type_pattern;
    150 	int timeout_secs;
    151 };
    152 
    153 /* Master structure for channels state */
    154 struct ssh_channels {
    155 	/*
    156 	 * Pointer to an array containing all allocated channels.  The array
    157 	 * is dynamically extended as needed.
    158 	 */
    159 	Channel **channels;
    160 
    161 	/*
    162 	 * Size of the channel array.  All slots of the array must always be
    163 	 * initialized (at least the type field); unused slots set to NULL
    164 	 */
    165 	u_int channels_alloc;
    166 
    167 	/*
    168 	 * 'channel_pre*' are called just before IO to add any bits
    169 	 * relevant to channels in the c->io_want bitmasks.
    170 	 *
    171 	 * 'channel_post*': perform any appropriate operations for
    172 	 * channels which have c->io_ready events pending.
    173 	 */
    174 	chan_fn **channel_pre;
    175 	chan_fn **channel_post;
    176 
    177 	/* -- tcp forwarding */
    178 	struct permission_set local_perms;
    179 	struct permission_set remote_perms;
    180 
    181 	/* -- X11 forwarding */
    182 
    183 	/* Saved X11 local (client) display. */
    184 	char *x11_saved_display;
    185 
    186 	/* Saved X11 authentication protocol name. */
    187 	char *x11_saved_proto;
    188 
    189 	/* Saved X11 authentication data.  This is the real data. */
    190 	char *x11_saved_data;
    191 	u_int x11_saved_data_len;
    192 
    193 	/* Deadline after which all X11 connections are refused */
    194 	time_t x11_refuse_time;
    195 
    196 	/*
    197 	 * Fake X11 authentication data.  This is what the server will be
    198 	 * sending us; we should replace any occurrences of this by the
    199 	 * real data.
    200 	 */
    201 	u_char *x11_fake_data;
    202 	u_int x11_fake_data_len;
    203 
    204 	/* AF_UNSPEC or AF_INET or AF_INET6 */
    205 	int IPv4or6;
    206 
    207 	/* Channel timeouts by type */
    208 	struct ssh_channel_timeout *timeouts;
    209 	size_t ntimeouts;
    210 	/* Global timeout for all OPEN channels */
    211 	int global_deadline;
    212 	time_t lastused;
    213 	/* pattern-lists used to classify channels as bulk */
    214 	char *bulk_classifier_tty, *bulk_classifier_notty;
    215 	/* Number of active bulk channels (set by channel_handler) */
    216 	u_int nbulk;
    217 };
    218 
    219 /* helper */
    220 static void port_open_helper(struct ssh *ssh, Channel *c, const char *rtype);
    221 static const char *channel_rfwd_bind_host(const char *listen_host);
    222 
    223 /* non-blocking connect helpers */
    224 static int connect_next(struct channel_connect *);
    225 static void channel_connect_ctx_free(struct channel_connect *);
    226 static Channel *rdynamic_connect_prepare(struct ssh *, const char *,
    227     const char *);
    228 static int rdynamic_connect_finish(struct ssh *, Channel *);
    229 
    230 /* Setup helper */
    231 static void channel_handler_init(struct ssh_channels *sc);
    232 
    233 /* -- channel core */
    234 
    235 void
    236 channel_init_channels(struct ssh *ssh)
    237 {
    238 	struct ssh_channels *sc;
    239 
    240 	if ((sc = calloc(1, sizeof(*sc))) == NULL)
    241 		fatal_f("allocation failed");
    242 	sc->channels_alloc = 10;
    243 	sc->channels = xcalloc(sc->channels_alloc, sizeof(*sc->channels));
    244 	sc->IPv4or6 = AF_UNSPEC;
    245 	sc->bulk_classifier_tty = xstrdup(CHANNEL_BULK_TTY);
    246 	sc->bulk_classifier_notty = xstrdup(CHANNEL_BULK_NOTTY);
    247 	channel_handler_init(sc);
    248 
    249 	ssh->chanctxt = sc;
    250 }
    251 
    252 Channel *
    253 channel_by_id(struct ssh *ssh, int id)
    254 {
    255 	Channel *c;
    256 
    257 	if (id < 0 || (u_int)id >= ssh->chanctxt->channels_alloc) {
    258 		logit_f("%d: bad id", id);
    259 		return NULL;
    260 	}
    261 	c = ssh->chanctxt->channels[id];
    262 	if (c == NULL) {
    263 		logit_f("%d: bad id: channel free", id);
    264 		return NULL;
    265 	}
    266 	return c;
    267 }
    268 
    269 Channel *
    270 channel_by_remote_id(struct ssh *ssh, u_int remote_id)
    271 {
    272 	Channel *c;
    273 	u_int i;
    274 
    275 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
    276 		c = ssh->chanctxt->channels[i];
    277 		if (c != NULL && c->have_remote_id && c->remote_id == remote_id)
    278 			return c;
    279 	}
    280 	return NULL;
    281 }
    282 
    283 /*
    284  * Returns the channel if it is allowed to receive protocol messages.
    285  * Private channels, like listening sockets, may not receive messages.
    286  */
    287 Channel *
    288 channel_lookup(struct ssh *ssh, int id)
    289 {
    290 	Channel *c;
    291 
    292 	if ((c = channel_by_id(ssh, id)) == NULL)
    293 		return NULL;
    294 
    295 	switch (c->type) {
    296 	case SSH_CHANNEL_X11_OPEN:
    297 	case SSH_CHANNEL_LARVAL:
    298 	case SSH_CHANNEL_CONNECTING:
    299 	case SSH_CHANNEL_DYNAMIC:
    300 	case SSH_CHANNEL_RDYNAMIC_OPEN:
    301 	case SSH_CHANNEL_RDYNAMIC_FINISH:
    302 	case SSH_CHANNEL_OPENING:
    303 	case SSH_CHANNEL_OPEN:
    304 	case SSH_CHANNEL_ABANDONED:
    305 	case SSH_CHANNEL_MUX_PROXY:
    306 		return c;
    307 	}
    308 	logit("Non-public channel %d, type %d.", id, c->type);
    309 	return NULL;
    310 }
    311 
    312 /*
    313  * Add a timeout for open channels whose c->ctype (or c->xctype if it is set)
    314  * match type_pattern.
    315  */
    316 void
    317 channel_add_timeout(struct ssh *ssh, const char *type_pattern,
    318     int timeout_secs)
    319 {
    320 	struct ssh_channels *sc = ssh->chanctxt;
    321 
    322 	if (strcmp(type_pattern, "global") == 0) {
    323 		debug2_f("global channel timeout %d seconds", timeout_secs);
    324 		sc->global_deadline = timeout_secs;
    325 		return;
    326 	}
    327 	debug2_f("channel type \"%s\" timeout %d seconds",
    328 	    type_pattern, timeout_secs);
    329 	sc->timeouts = xrecallocarray(sc->timeouts, sc->ntimeouts,
    330 	    sc->ntimeouts + 1, sizeof(*sc->timeouts));
    331 	sc->timeouts[sc->ntimeouts].type_pattern = xstrdup(type_pattern);
    332 	sc->timeouts[sc->ntimeouts].timeout_secs = timeout_secs;
    333 	sc->ntimeouts++;
    334 }
    335 
    336 /* Clears all previously-added channel timeouts */
    337 void
    338 channel_clear_timeouts(struct ssh *ssh)
    339 {
    340 	struct ssh_channels *sc = ssh->chanctxt;
    341 	size_t i;
    342 
    343 	debug3_f("clearing");
    344 	for (i = 0; i < sc->ntimeouts; i++)
    345 		free(sc->timeouts[i].type_pattern);
    346 	free(sc->timeouts);
    347 	sc->timeouts = NULL;
    348 	sc->ntimeouts = 0;
    349 }
    350 
    351 static int
    352 lookup_timeout(struct ssh *ssh, const char *type)
    353 {
    354 	struct ssh_channels *sc = ssh->chanctxt;
    355 	size_t i;
    356 
    357 	for (i = 0; i < sc->ntimeouts; i++) {
    358 		if (match_pattern(type, sc->timeouts[i].type_pattern))
    359 			return sc->timeouts[i].timeout_secs;
    360 	}
    361 
    362 	return 0;
    363 }
    364 
    365 static void
    366 channel_classify(struct ssh *ssh, Channel *c)
    367 {
    368 	struct ssh_channels *sc = ssh->chanctxt;
    369 	const char *type = c->xctype == NULL ? c->ctype : c->xctype;
    370 	const char *classifier = (c->isatty || c->remote_has_tty) ?
    371 	    sc->bulk_classifier_tty : sc->bulk_classifier_notty;
    372 
    373 	c->bulk = type != NULL && match_pattern_list(type, classifier, 0) == 1;
    374 }
    375 
    376 /*
    377  * Sets "extended type" of a channel; used by session layer to add additional
    378  * information about channel types (e.g. shell, login, subsystem) that can then
    379  * be used to select timeouts.
    380  * Will reset c->inactive_deadline as a side-effect.
    381  */
    382 void
    383 channel_set_xtype(struct ssh *ssh, int id, const char *xctype)
    384 {
    385 	Channel *c;
    386 
    387 	if ((c = channel_by_id(ssh, id)) == NULL)
    388 		fatal_f("missing channel %d", id);
    389 	if (c->xctype != NULL)
    390 		free(c->xctype);
    391 	c->xctype = xstrdup(xctype);
    392 	/* Type has changed, so look up inactivity deadline again */
    393 	c->inactive_deadline = lookup_timeout(ssh, c->xctype);
    394 	channel_classify(ssh, c);
    395 	debug2_f("labeled channel %d as %s (inactive timeout %u)", id, xctype,
    396 	    c->inactive_deadline);
    397 }
    398 
    399 /*
    400  * update "last used" time on a channel.
    401  * NB. nothing else should update lastused except to clear it.
    402  */
    403 static void
    404 channel_set_used_time(struct ssh *ssh, Channel *c)
    405 {
    406 	ssh->chanctxt->lastused = monotime();
    407 	if (c != NULL)
    408 		c->lastused = ssh->chanctxt->lastused;
    409 }
    410 
    411 /*
    412  * Get the time at which a channel is due to time out for inactivity.
    413  * Returns 0 if the channel is not due to time out ever.
    414  */
    415 static time_t
    416 channel_get_expiry(struct ssh *ssh, Channel *c)
    417 {
    418 	struct ssh_channels *sc = ssh->chanctxt;
    419 	time_t expiry = 0, channel_expiry;
    420 
    421 	if (sc->lastused != 0 && sc->global_deadline != 0)
    422 		expiry = sc->lastused + sc->global_deadline;
    423 	if (c->lastused != 0 && c->inactive_deadline != 0) {
    424 		channel_expiry = c->lastused + c->inactive_deadline;
    425 		if (expiry == 0 || channel_expiry < expiry)
    426 			expiry = channel_expiry;
    427 	}
    428 	return expiry;
    429 }
    430 
    431 /* Returns non-zero if there is an open, non-interactive channel */
    432 int
    433 channel_has_bulk(struct ssh *ssh)
    434 {
    435 	return ssh->chanctxt != NULL && ssh->chanctxt->nbulk != 0;
    436 }
    437 
    438 /*
    439  * Register filedescriptors for a channel, used when allocating a channel or
    440  * when the channel consumer/producer is ready, e.g. shell exec'd
    441  */
    442 static void
    443 channel_register_fds(struct ssh *ssh, Channel *c, int rfd, int wfd, int efd,
    444     int extusage, int nonblock, int is_tty)
    445 {
    446 	int val;
    447 
    448 	if (rfd != -1)
    449 		(void)fcntl(rfd, F_SETFD, FD_CLOEXEC);
    450 	if (wfd != -1 && wfd != rfd)
    451 		(void)fcntl(wfd, F_SETFD, FD_CLOEXEC);
    452 	if (efd != -1 && efd != rfd && efd != wfd)
    453 		(void)fcntl(efd, F_SETFD, FD_CLOEXEC);
    454 
    455 	c->rfd = rfd;
    456 	c->wfd = wfd;
    457 	c->sock = (rfd == wfd) ? rfd : -1;
    458 	c->efd = efd;
    459 	c->extended_usage = extusage;
    460 
    461 	if ((c->isatty = is_tty) != 0)
    462 		debug2("channel %d: rfd %d isatty", c->self, c->rfd);
    463 
    464 	/* enable nonblocking mode */
    465 	c->restore_block = 0;
    466 	if (nonblock == CHANNEL_NONBLOCK_STDIO) {
    467 		/*
    468 		 * Special handling for stdio file descriptors: do not set
    469 		 * non-blocking mode if they are TTYs. Otherwise prepare to
    470 		 * restore their blocking state on exit to avoid interfering
    471 		 * with other programs that follow.
    472 		 */
    473 		if (rfd != -1 && !isatty(rfd) &&
    474 		    (val = fcntl(rfd, F_GETFL)) != -1 && !(val & O_NONBLOCK)) {
    475 			c->restore_flags[0] = val;
    476 			c->restore_block |= CHANNEL_RESTORE_RFD;
    477 			set_nonblock(rfd);
    478 		}
    479 		if (wfd != -1 && !isatty(wfd) &&
    480 		    (val = fcntl(wfd, F_GETFL)) != -1 && !(val & O_NONBLOCK)) {
    481 			c->restore_flags[1] = val;
    482 			c->restore_block |= CHANNEL_RESTORE_WFD;
    483 			set_nonblock(wfd);
    484 		}
    485 		if (efd != -1 && !isatty(efd) &&
    486 		    (val = fcntl(efd, F_GETFL)) != -1 && !(val & O_NONBLOCK)) {
    487 			c->restore_flags[2] = val;
    488 			c->restore_block |= CHANNEL_RESTORE_EFD;
    489 			set_nonblock(efd);
    490 		}
    491 	} else if (nonblock) {
    492 		if (rfd != -1)
    493 			set_nonblock(rfd);
    494 		if (wfd != -1)
    495 			set_nonblock(wfd);
    496 		if (efd != -1)
    497 			set_nonblock(efd);
    498 	}
    499 	/* channel might be entering a larval state, so reset global timeout */
    500 	channel_set_used_time(ssh, NULL);
    501 	channel_classify(ssh, c);
    502 }
    503 
    504 /*
    505  * Allocate a new channel object and set its type and socket.
    506  */
    507 Channel *
    508 channel_new(struct ssh *ssh, const char *ctype, int type, int rfd, int wfd,
    509     int efd, u_int window, u_int maxpack, int extusage, const char *remote_name,
    510     int nonblock)
    511 {
    512 	struct ssh_channels *sc = ssh->chanctxt;
    513 	u_int i, found = 0 /* XXXGCC12 */;
    514 	Channel *c;
    515 	int r;
    516 
    517 	/* Try to find a free slot where to put the new channel. */
    518 	for (i = 0; i < sc->channels_alloc; i++) {
    519 		if (sc->channels[i] == NULL) {
    520 			/* Found a free slot. */
    521 			found = i;
    522 			break;
    523 		}
    524 	}
    525 	if (i >= sc->channels_alloc) {
    526 		/*
    527 		 * There are no free slots. Take last+1 slot and expand
    528 		 * the array.
    529 		 */
    530 		found = sc->channels_alloc;
    531 		if (sc->channels_alloc > CHANNELS_MAX_CHANNELS)
    532 			fatal_f("internal error: channels_alloc %d too big",
    533 			    sc->channels_alloc);
    534 		sc->channels = xrecallocarray(sc->channels, sc->channels_alloc,
    535 		    sc->channels_alloc + 10, sizeof(*sc->channels));
    536 		sc->channels_alloc += 10;
    537 		debug2("channel: expanding %d", sc->channels_alloc);
    538 	}
    539 	/* Initialize and return new channel. */
    540 	c = sc->channels[found] = xcalloc(1, sizeof(Channel));
    541 	if ((c->input = sshbuf_new()) == NULL ||
    542 	    (c->output = sshbuf_new()) == NULL ||
    543 	    (c->extended = sshbuf_new()) == NULL)
    544 		fatal_f("sshbuf_new failed");
    545 	if ((r = sshbuf_set_max_size(c->input, CHAN_INPUT_MAX)) != 0)
    546 		fatal_fr(r, "sshbuf_set_max_size");
    547 	c->ostate = CHAN_OUTPUT_OPEN;
    548 	c->istate = CHAN_INPUT_OPEN;
    549 	channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, 0);
    550 	c->self = found;
    551 	c->type = type;
    552 	c->ctype = __UNCONST(ctype);
    553 	c->local_window = window;
    554 	c->local_window_max = window;
    555 	c->local_maxpacket = maxpack;
    556 	c->dynamic_window = 0;
    557 	c->remote_id = -1;
    558 	c->remote_name = xstrdup(remote_name);
    559 	c->ctl_chan = -1;
    560 	c->delayed = 1;		/* prevent call to channel_post handler */
    561 	c->inactive_deadline = lookup_timeout(ssh, c->ctype);
    562 	TAILQ_INIT(&c->status_confirms);
    563 	channel_classify(ssh, c);
    564 	debug("channel %d: new %s [%s] (inactive timeout: %u)",
    565 	    found, c->ctype, remote_name, c->inactive_deadline);
    566 	return c;
    567 }
    568 
    569 void
    570 channel_set_tty(struct ssh *ssh, Channel *c)
    571 {
    572 	c->remote_has_tty = 1;
    573 	channel_classify(ssh, c);
    574 }
    575 
    576 int
    577 channel_close_fd(struct ssh *ssh, Channel *c, int *fdp)
    578 {
    579 	int ret, fd = *fdp;
    580 
    581 	if (fd == -1)
    582 		return 0;
    583 
    584 	/* restore blocking */
    585 	if (*fdp == c->rfd &&
    586 	    (c->restore_block & CHANNEL_RESTORE_RFD) != 0)
    587 		(void)fcntl(*fdp, F_SETFL, c->restore_flags[0]);
    588 	else if (*fdp == c->wfd &&
    589 	    (c->restore_block & CHANNEL_RESTORE_WFD) != 0)
    590 		(void)fcntl(*fdp, F_SETFL, c->restore_flags[1]);
    591 	else if (*fdp == c->efd &&
    592 	    (c->restore_block & CHANNEL_RESTORE_EFD) != 0)
    593 		(void)fcntl(*fdp, F_SETFL, c->restore_flags[2]);
    594 
    595 	if (*fdp == c->rfd) {
    596 		c->io_want &= ~SSH_CHAN_IO_RFD;
    597 		c->io_ready &= ~SSH_CHAN_IO_RFD;
    598 		c->rfd = -1;
    599 		c->pfds[0] = -1;
    600 	}
    601 	if (*fdp == c->wfd) {
    602 		c->io_want &= ~SSH_CHAN_IO_WFD;
    603 		c->io_ready &= ~SSH_CHAN_IO_WFD;
    604 		c->wfd = -1;
    605 		c->pfds[1] = -1;
    606 	}
    607 	if (*fdp == c->efd) {
    608 		c->io_want &= ~SSH_CHAN_IO_EFD;
    609 		c->io_ready &= ~SSH_CHAN_IO_EFD;
    610 		c->efd = -1;
    611 		c->pfds[2] = -1;
    612 	}
    613 	if (*fdp == c->sock) {
    614 		c->io_want &= ~SSH_CHAN_IO_SOCK;
    615 		c->io_ready &= ~SSH_CHAN_IO_SOCK;
    616 		c->sock = -1;
    617 		c->pfds[3] = -1;
    618 	}
    619 
    620 	ret = close(fd);
    621 	*fdp = -1; /* probably redundant */
    622 	return ret;
    623 }
    624 
    625 /* Close all channel fd/socket. */
    626 static void
    627 channel_close_fds(struct ssh *ssh, Channel *c)
    628 {
    629 	int sock = c->sock, rfd = c->rfd, wfd = c->wfd, efd = c->efd;
    630 
    631 	channel_close_fd(ssh, c, &c->sock);
    632 	if (rfd != sock)
    633 		channel_close_fd(ssh, c, &c->rfd);
    634 	if (wfd != sock && wfd != rfd)
    635 		channel_close_fd(ssh, c, &c->wfd);
    636 	if (efd != sock && efd != rfd && efd != wfd)
    637 		channel_close_fd(ssh, c, &c->efd);
    638 }
    639 
    640 static void
    641 fwd_perm_clear(struct permission *perm)
    642 {
    643 	free(perm->host_to_connect);
    644 	free(perm->listen_host);
    645 	free(perm->listen_path);
    646 	memset(perm, 0, sizeof(*perm));
    647 }
    648 
    649 /* Returns an printable name for the specified forwarding permission list */
    650 static const char *
    651 fwd_ident(int who, int where)
    652 {
    653 	if (who == FORWARD_ADM) {
    654 		if (where == FORWARD_LOCAL)
    655 			return "admin local";
    656 		else if (where == FORWARD_REMOTE)
    657 			return "admin remote";
    658 	} else if (who == FORWARD_USER) {
    659 		if (where == FORWARD_LOCAL)
    660 			return "user local";
    661 		else if (where == FORWARD_REMOTE)
    662 			return "user remote";
    663 	}
    664 	fatal("Unknown forward permission list %d/%d", who, where);
    665 }
    666 
    667 /* Returns the forwarding permission list for the specified direction */
    668 static struct permission_set *
    669 permission_set_get(struct ssh *ssh, int where)
    670 {
    671 	struct ssh_channels *sc = ssh->chanctxt;
    672 
    673 	switch (where) {
    674 	case FORWARD_LOCAL:
    675 		return &sc->local_perms;
    676 		break;
    677 	case FORWARD_REMOTE:
    678 		return &sc->remote_perms;
    679 		break;
    680 	default:
    681 		fatal_f("invalid forwarding direction %d", where);
    682 	}
    683 }
    684 
    685 /* Returns pointers to the specified forwarding list and its element count */
    686 static void
    687 permission_set_get_array(struct ssh *ssh, int who, int where,
    688     struct permission ***permpp, u_int **npermpp)
    689 {
    690 	struct permission_set *pset = permission_set_get(ssh, where);
    691 
    692 	switch (who) {
    693 	case FORWARD_USER:
    694 		*permpp = &pset->permitted_user;
    695 		*npermpp = &pset->num_permitted_user;
    696 		break;
    697 	case FORWARD_ADM:
    698 		*permpp = &pset->permitted_admin;
    699 		*npermpp = &pset->num_permitted_admin;
    700 		break;
    701 	default:
    702 		fatal_f("invalid forwarding client %d", who);
    703 	}
    704 }
    705 
    706 /* Adds an entry to the specified forwarding list */
    707 static int
    708 permission_set_add(struct ssh *ssh, int who, int where,
    709     const char *host_to_connect, int port_to_connect,
    710     const char *listen_host, const char *listen_path, int listen_port,
    711     Channel *downstream)
    712 {
    713 	struct permission **permp;
    714 	u_int n, *npermp;
    715 
    716 	permission_set_get_array(ssh, who, where, &permp, &npermp);
    717 
    718 	if (*npermp >= INT_MAX)
    719 		fatal_f("%s overflow", fwd_ident(who, where));
    720 
    721 	*permp = xrecallocarray(*permp, *npermp, *npermp + 1, sizeof(**permp));
    722 	n = (*npermp)++;
    723 #define MAYBE_DUP(s) ((s == NULL) ? NULL : xstrdup(s))
    724 	(*permp)[n].host_to_connect = MAYBE_DUP(host_to_connect);
    725 	(*permp)[n].port_to_connect = port_to_connect;
    726 	(*permp)[n].listen_host = MAYBE_DUP(listen_host);
    727 	(*permp)[n].listen_path = MAYBE_DUP(listen_path);
    728 	(*permp)[n].listen_port = listen_port;
    729 	(*permp)[n].downstream = downstream;
    730 #undef MAYBE_DUP
    731 	return (int)n;
    732 }
    733 
    734 static void
    735 mux_remove_remote_forwardings(struct ssh *ssh, Channel *c)
    736 {
    737 	struct ssh_channels *sc = ssh->chanctxt;
    738 	struct permission_set *pset = &sc->local_perms;
    739 	struct permission *perm;
    740 	int r;
    741 	u_int i;
    742 
    743 	for (i = 0; i < pset->num_permitted_user; i++) {
    744 		perm = &pset->permitted_user[i];
    745 		if (perm->downstream != c)
    746 			continue;
    747 
    748 		/* cancel on the server, since mux client is gone */
    749 		debug("channel %d: cleanup remote forward for %s:%u",
    750 		    c->self, perm->listen_host, perm->listen_port);
    751 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
    752 		    (r = sshpkt_put_cstring(ssh,
    753 		    "cancel-tcpip-forward")) != 0 ||
    754 		    (r = sshpkt_put_u8(ssh, 0)) != 0 ||
    755 		    (r = sshpkt_put_cstring(ssh,
    756 		    channel_rfwd_bind_host(perm->listen_host))) != 0 ||
    757 		    (r = sshpkt_put_u32(ssh, perm->listen_port)) != 0 ||
    758 		    (r = sshpkt_send(ssh)) != 0) {
    759 			fatal_fr(r, "channel %i", c->self);
    760 		}
    761 		fwd_perm_clear(perm); /* unregister */
    762 	}
    763 }
    764 
    765 /* Free the channel and close its fd/socket. */
    766 void
    767 channel_free(struct ssh *ssh, Channel *c)
    768 {
    769 	struct ssh_channels *sc = ssh->chanctxt;
    770 	char *s;
    771 	u_int i, n;
    772 	Channel *other;
    773 	struct channel_confirm *cc;
    774 
    775 	for (n = 0, i = 0; i < sc->channels_alloc; i++) {
    776 		if ((other = sc->channels[i]) == NULL)
    777 			continue;
    778 		n++;
    779 		/* detach from mux client and prepare for closing */
    780 		if (c->type == SSH_CHANNEL_MUX_CLIENT &&
    781 		    other->type == SSH_CHANNEL_MUX_PROXY &&
    782 		    other->mux_ctx == c) {
    783 			other->mux_ctx = NULL;
    784 			other->type = SSH_CHANNEL_OPEN;
    785 			other->istate = CHAN_INPUT_CLOSED;
    786 			other->ostate = CHAN_OUTPUT_CLOSED;
    787 		}
    788 	}
    789 	debug("channel %d: free: %s, nchannels %u", c->self,
    790 	    c->remote_name ? c->remote_name : "???", n);
    791 
    792 	if (c->type == SSH_CHANNEL_MUX_CLIENT) {
    793 		mux_remove_remote_forwardings(ssh, c);
    794 		free(c->mux_ctx);
    795 		c->mux_ctx = NULL;
    796 	} else if (c->type == SSH_CHANNEL_MUX_LISTENER) {
    797 		free(c->mux_ctx);
    798 		c->mux_ctx = NULL;
    799 	}
    800 
    801 	if (log_level_get() >= SYSLOG_LEVEL_DEBUG3) {
    802 		s = channel_open_message(ssh);
    803 		debug3("channel %d: status: %s", c->self, s);
    804 		free(s);
    805 	}
    806 
    807 	channel_close_fds(ssh, c);
    808 	sshbuf_free(c->input);
    809 	sshbuf_free(c->output);
    810 	sshbuf_free(c->extended);
    811 	c->input = c->output = c->extended = NULL;
    812 	free(c->remote_name);
    813 	c->remote_name = NULL;
    814 	free(c->path);
    815 	c->path = NULL;
    816 	free(c->listening_addr);
    817 	c->listening_addr = NULL;
    818 	free(c->xctype);
    819 	c->xctype = NULL;
    820 	while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
    821 		if (cc->abandon_cb != NULL)
    822 			cc->abandon_cb(ssh, c, cc->ctx);
    823 		TAILQ_REMOVE(&c->status_confirms, cc, entry);
    824 		freezero(cc, sizeof(*cc));
    825 	}
    826 	if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
    827 		c->filter_cleanup(ssh, c->self, c->filter_ctx);
    828 	sc->channels[c->self] = NULL;
    829 	freezero(c, sizeof(*c));
    830 }
    831 
    832 void
    833 channel_free_all(struct ssh *ssh)
    834 {
    835 	u_int i;
    836 	struct ssh_channels *sc = ssh->chanctxt;
    837 
    838 	for (i = 0; i < sc->channels_alloc; i++)
    839 		if (sc->channels[i] != NULL)
    840 			channel_free(ssh, sc->channels[i]);
    841 
    842 	free(sc->channels);
    843 	sc->channels = NULL;
    844 	sc->channels_alloc = 0;
    845 
    846 	free(sc->x11_saved_display);
    847 	sc->x11_saved_display = NULL;
    848 
    849 	free(sc->x11_saved_proto);
    850 	sc->x11_saved_proto = NULL;
    851 
    852 	free(sc->x11_saved_data);
    853 	sc->x11_saved_data = NULL;
    854 	sc->x11_saved_data_len = 0;
    855 
    856 	free(sc->x11_fake_data);
    857 	sc->x11_fake_data = NULL;
    858 	sc->x11_fake_data_len = 0;
    859 }
    860 
    861 void
    862 channel_free_channels(struct ssh *ssh)
    863 {
    864 	struct ssh_channels *sc;
    865 
    866 	if (ssh == NULL || ssh->chanctxt == NULL)
    867 		return;
    868 	channel_free_all(ssh);
    869 	channel_clear_permission(ssh, FORWARD_USER, FORWARD_LOCAL);
    870 	channel_clear_permission(ssh, FORWARD_USER, FORWARD_REMOTE);
    871 	channel_clear_permission(ssh, FORWARD_ADM, FORWARD_LOCAL);
    872 	channel_clear_permission(ssh, FORWARD_ADM, FORWARD_REMOTE);
    873 	sc = ssh->chanctxt;
    874 	free(sc->bulk_classifier_tty);
    875 	free(sc->bulk_classifier_notty);
    876 	free(sc->channel_pre);
    877 	free(sc->channel_post);
    878 	freezero(sc, sizeof(*sc));
    879 	ssh->chanctxt = NULL;
    880 }
    881 
    882 /*
    883  * Closes the sockets/fds of all channels.  This is used to close extra file
    884  * descriptors after a fork.
    885  */
    886 void
    887 channel_close_all(struct ssh *ssh)
    888 {
    889 	u_int i;
    890 
    891 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++)
    892 		if (ssh->chanctxt->channels[i] != NULL)
    893 			channel_close_fds(ssh, ssh->chanctxt->channels[i]);
    894 }
    895 
    896 /*
    897  * Stop listening to channels.
    898  */
    899 void
    900 channel_stop_listening(struct ssh *ssh)
    901 {
    902 	u_int i;
    903 	Channel *c;
    904 
    905 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
    906 		c = ssh->chanctxt->channels[i];
    907 		if (c != NULL) {
    908 			switch (c->type) {
    909 			case SSH_CHANNEL_AUTH_SOCKET:
    910 			case SSH_CHANNEL_PORT_LISTENER:
    911 			case SSH_CHANNEL_RPORT_LISTENER:
    912 			case SSH_CHANNEL_X11_LISTENER:
    913 			case SSH_CHANNEL_UNIX_LISTENER:
    914 			case SSH_CHANNEL_RUNIX_LISTENER:
    915 				channel_close_fd(ssh, c, &c->sock);
    916 				channel_free(ssh, c);
    917 				break;
    918 			}
    919 		}
    920 	}
    921 }
    922 
    923 /*
    924  * Returns true if no channel has too much buffered data, and false if one or
    925  * more channel is overfull.
    926  */
    927 int
    928 channel_not_very_much_buffered_data(struct ssh *ssh)
    929 {
    930 	u_int i;
    931 	u_int maxsize = ssh_packet_get_maxsize(ssh);
    932 	Channel *c;
    933 
    934 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
    935 		c = ssh->chanctxt->channels[i];
    936 		if (c == NULL || c->type != SSH_CHANNEL_OPEN)
    937 			continue;
    938 		if (sshbuf_len(c->output) > maxsize) {
    939 			debug2("channel %d: big output buffer %zu > %u",
    940 			    c->self, sshbuf_len(c->output), maxsize);
    941 			return 0;
    942 		}
    943 	}
    944 	return 1;
    945 }
    946 
    947 /* Returns true if any channel is still open. */
    948 int
    949 channel_still_open(struct ssh *ssh)
    950 {
    951 	u_int i;
    952 	Channel *c;
    953 
    954 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
    955 		c = ssh->chanctxt->channels[i];
    956 		if (c == NULL)
    957 			continue;
    958 		switch (c->type) {
    959 		case SSH_CHANNEL_X11_LISTENER:
    960 		case SSH_CHANNEL_PORT_LISTENER:
    961 		case SSH_CHANNEL_RPORT_LISTENER:
    962 		case SSH_CHANNEL_MUX_LISTENER:
    963 		case SSH_CHANNEL_CLOSED:
    964 		case SSH_CHANNEL_AUTH_SOCKET:
    965 		case SSH_CHANNEL_DYNAMIC:
    966 		case SSH_CHANNEL_RDYNAMIC_OPEN:
    967 		case SSH_CHANNEL_CONNECTING:
    968 		case SSH_CHANNEL_ZOMBIE:
    969 		case SSH_CHANNEL_ABANDONED:
    970 		case SSH_CHANNEL_UNIX_LISTENER:
    971 		case SSH_CHANNEL_RUNIX_LISTENER:
    972 			continue;
    973 		case SSH_CHANNEL_LARVAL:
    974 			continue;
    975 		case SSH_CHANNEL_OPENING:
    976 		case SSH_CHANNEL_OPEN:
    977 		case SSH_CHANNEL_RDYNAMIC_FINISH:
    978 		case SSH_CHANNEL_X11_OPEN:
    979 		case SSH_CHANNEL_MUX_CLIENT:
    980 		case SSH_CHANNEL_MUX_PROXY:
    981 			return 1;
    982 		default:
    983 			fatal_f("bad channel type %d", c->type);
    984 			/* NOTREACHED */
    985 		}
    986 	}
    987 	return 0;
    988 }
    989 
    990 /* Returns true if a channel with a TTY is open. */
    991 int
    992 channel_tty_open(struct ssh *ssh)
    993 {
    994 	u_int i;
    995 	Channel *c;
    996 
    997 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
    998 		c = ssh->chanctxt->channels[i];
    999 		if (c == NULL || c->type != SSH_CHANNEL_OPEN)
   1000 			continue;
   1001 		if (c->client_tty)
   1002 			return 1;
   1003 	}
   1004 	return 0;
   1005 }
   1006 
   1007 /* Returns the id of an open channel suitable for keepaliving */
   1008 int
   1009 channel_find_open(struct ssh *ssh)
   1010 {
   1011 	u_int i;
   1012 	Channel *c;
   1013 
   1014 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
   1015 		c = ssh->chanctxt->channels[i];
   1016 		if (c == NULL || !c->have_remote_id)
   1017 			continue;
   1018 		switch (c->type) {
   1019 		case SSH_CHANNEL_CLOSED:
   1020 		case SSH_CHANNEL_DYNAMIC:
   1021 		case SSH_CHANNEL_RDYNAMIC_OPEN:
   1022 		case SSH_CHANNEL_RDYNAMIC_FINISH:
   1023 		case SSH_CHANNEL_X11_LISTENER:
   1024 		case SSH_CHANNEL_PORT_LISTENER:
   1025 		case SSH_CHANNEL_RPORT_LISTENER:
   1026 		case SSH_CHANNEL_MUX_LISTENER:
   1027 		case SSH_CHANNEL_MUX_CLIENT:
   1028 		case SSH_CHANNEL_MUX_PROXY:
   1029 		case SSH_CHANNEL_OPENING:
   1030 		case SSH_CHANNEL_CONNECTING:
   1031 		case SSH_CHANNEL_ZOMBIE:
   1032 		case SSH_CHANNEL_ABANDONED:
   1033 		case SSH_CHANNEL_UNIX_LISTENER:
   1034 		case SSH_CHANNEL_RUNIX_LISTENER:
   1035 			continue;
   1036 		case SSH_CHANNEL_LARVAL:
   1037 		case SSH_CHANNEL_AUTH_SOCKET:
   1038 		case SSH_CHANNEL_OPEN:
   1039 		case SSH_CHANNEL_X11_OPEN:
   1040 			return i;
   1041 		default:
   1042 			fatal_f("bad channel type %d", c->type);
   1043 			/* NOTREACHED */
   1044 		}
   1045 	}
   1046 	return -1;
   1047 }
   1048 
   1049 /* Returns the state of the channel's extended usage flag */
   1050 const char *
   1051 channel_format_extended_usage(const Channel *c)
   1052 {
   1053 	if (c->efd == -1)
   1054 		return "closed";
   1055 
   1056 	switch (c->extended_usage) {
   1057 	case CHAN_EXTENDED_WRITE:
   1058 		return "write";
   1059 	case CHAN_EXTENDED_READ:
   1060 		return "read";
   1061 	case CHAN_EXTENDED_IGNORE:
   1062 		return "ignore";
   1063 	default:
   1064 		return "UNKNOWN";
   1065 	}
   1066 }
   1067 
   1068 static char *
   1069 channel_format_status(const Channel *c)
   1070 {
   1071 	char *ret = NULL;
   1072 
   1073 	xasprintf(&ret, "t%d [%s] %s%u %s%u i%u/%zu o%u/%zu e[%s]/%zu "
   1074 	    "fd %d/%d/%d sock %d cc %d %s%u io 0x%02x/0x%02x %s%s",
   1075 	    c->type, c->xctype != NULL ? c->xctype : c->ctype,
   1076 	    c->have_remote_id ? "r" : "nr", c->remote_id,
   1077 	    c->mux_ctx != NULL ? "m" : "nm", c->mux_downstream_id,
   1078 	    c->istate, sshbuf_len(c->input),
   1079 	    c->ostate, sshbuf_len(c->output),
   1080 	    channel_format_extended_usage(c), sshbuf_len(c->extended),
   1081 	    c->rfd, c->wfd, c->efd, c->sock, c->ctl_chan,
   1082 	    c->have_ctl_child_id ? "c" : "nc", c->ctl_child_id,
   1083 	    c->io_want, c->io_ready,
   1084 	    c->isatty ? "T" : (c->remote_has_tty ? "RT" : ""),
   1085 	    c->bulk ? "B" : "I");
   1086 	return ret;
   1087 }
   1088 
   1089 /*
   1090  * Returns a message describing the currently open forwarded connections,
   1091  * suitable for sending to the client.  The message contains crlf pairs for
   1092  * newlines.
   1093  */
   1094 char *
   1095 channel_open_message(struct ssh *ssh)
   1096 {
   1097 	struct sshbuf *buf;
   1098 	Channel *c;
   1099 	u_int i;
   1100 	int r;
   1101 	char *cp, *ret;
   1102 
   1103 	if ((buf = sshbuf_new()) == NULL)
   1104 		fatal_f("sshbuf_new");
   1105 	if ((r = sshbuf_putf(buf,
   1106 	    "The following connections are open:\r\n")) != 0)
   1107 		fatal_fr(r, "sshbuf_putf");
   1108 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
   1109 		c = ssh->chanctxt->channels[i];
   1110 		if (c == NULL)
   1111 			continue;
   1112 		switch (c->type) {
   1113 		case SSH_CHANNEL_X11_LISTENER:
   1114 		case SSH_CHANNEL_PORT_LISTENER:
   1115 		case SSH_CHANNEL_RPORT_LISTENER:
   1116 		case SSH_CHANNEL_CLOSED:
   1117 		case SSH_CHANNEL_AUTH_SOCKET:
   1118 		case SSH_CHANNEL_ZOMBIE:
   1119 		case SSH_CHANNEL_ABANDONED:
   1120 		case SSH_CHANNEL_MUX_LISTENER:
   1121 		case SSH_CHANNEL_UNIX_LISTENER:
   1122 		case SSH_CHANNEL_RUNIX_LISTENER:
   1123 			continue;
   1124 		case SSH_CHANNEL_LARVAL:
   1125 		case SSH_CHANNEL_OPENING:
   1126 		case SSH_CHANNEL_CONNECTING:
   1127 		case SSH_CHANNEL_DYNAMIC:
   1128 		case SSH_CHANNEL_RDYNAMIC_OPEN:
   1129 		case SSH_CHANNEL_RDYNAMIC_FINISH:
   1130 		case SSH_CHANNEL_OPEN:
   1131 		case SSH_CHANNEL_X11_OPEN:
   1132 		case SSH_CHANNEL_MUX_PROXY:
   1133 		case SSH_CHANNEL_MUX_CLIENT:
   1134 			cp = channel_format_status(c);
   1135 			if ((r = sshbuf_putf(buf, "  #%d %.300s (%s)\r\n",
   1136 			    c->self, c->remote_name, cp)) != 0) {
   1137 				free(cp);
   1138 				fatal_fr(r, "sshbuf_putf");
   1139 			}
   1140 			free(cp);
   1141 			continue;
   1142 		default:
   1143 			fatal_f("bad channel type %d", c->type);
   1144 			/* NOTREACHED */
   1145 		}
   1146 	}
   1147 	if ((ret = sshbuf_dup_string(buf)) == NULL)
   1148 		fatal_f("sshbuf_dup_string");
   1149 	sshbuf_free(buf);
   1150 	return ret;
   1151 }
   1152 
   1153 void
   1154 channel_report_open(struct ssh *ssh, int level)
   1155 {
   1156 	char *open, *oopen, *cp, ident[256];
   1157 
   1158 	sshpkt_fmt_connection_id(ssh, ident, sizeof(ident));
   1159 	do_log2(level, "Connection: %s (pid %ld)", ident, (long)getpid());
   1160 	open = oopen = channel_open_message(ssh);
   1161 	while ((cp = strsep(&open, "\r\n")) != NULL) {
   1162 		if (*cp != '\0')
   1163 			do_log2(level, "%s", cp);
   1164 	}
   1165 	free(oopen);
   1166 }
   1167 
   1168 static void
   1169 open_preamble(struct ssh *ssh, const char *where, Channel *c, const char *type)
   1170 {
   1171 	int r;
   1172 
   1173 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
   1174 	    (r = sshpkt_put_cstring(ssh, type)) != 0 ||
   1175 	    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
   1176 	    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
   1177 	    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0) {
   1178 		fatal_r(r, "%s: channel %i: open", where, c->self);
   1179 	}
   1180 }
   1181 
   1182 void
   1183 channel_send_open(struct ssh *ssh, int id)
   1184 {
   1185 	Channel *c = channel_lookup(ssh, id);
   1186 	int r;
   1187 
   1188 	if (c == NULL) {
   1189 		logit("channel_send_open: %d: bad id", id);
   1190 		return;
   1191 	}
   1192 	debug2("channel %d: send open", id);
   1193 	open_preamble(ssh, __func__, c, c->ctype);
   1194 	if ((r = sshpkt_send(ssh)) != 0)
   1195 		fatal_fr(r, "channel %i", c->self);
   1196 }
   1197 
   1198 void
   1199 channel_request_start(struct ssh *ssh, int id, const char *service,
   1200     int wantconfirm)
   1201 {
   1202 	Channel *c = channel_lookup(ssh, id);
   1203 	int r;
   1204 
   1205 	if (c == NULL) {
   1206 		logit_f("%d: unknown channel id", id);
   1207 		return;
   1208 	}
   1209 	if (!c->have_remote_id)
   1210 		fatal_f("channel %d: no remote id", c->self);
   1211 
   1212 	debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
   1213 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_REQUEST)) != 0 ||
   1214 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
   1215 	    (r = sshpkt_put_cstring(ssh, service)) != 0 ||
   1216 	    (r = sshpkt_put_u8(ssh, wantconfirm)) != 0) {
   1217 		fatal_fr(r, "channel %i", c->self);
   1218 	}
   1219 }
   1220 
   1221 void
   1222 channel_register_status_confirm(struct ssh *ssh, int id,
   1223     channel_confirm_cb *cb, channel_confirm_abandon_cb *abandon_cb, void *ctx)
   1224 {
   1225 	struct channel_confirm *cc;
   1226 	Channel *c;
   1227 
   1228 	if ((c = channel_lookup(ssh, id)) == NULL)
   1229 		fatal_f("%d: bad id", id);
   1230 
   1231 	cc = xcalloc(1, sizeof(*cc));
   1232 	cc->cb = cb;
   1233 	cc->abandon_cb = abandon_cb;
   1234 	cc->ctx = ctx;
   1235 	TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
   1236 }
   1237 
   1238 void
   1239 channel_register_open_confirm(struct ssh *ssh, int id,
   1240     channel_open_fn *fn, void *ctx)
   1241 {
   1242 	Channel *c = channel_lookup(ssh, id);
   1243 
   1244 	if (c == NULL) {
   1245 		logit_f("%d: bad id", id);
   1246 		return;
   1247 	}
   1248 	c->open_confirm = fn;
   1249 	c->open_confirm_ctx = ctx;
   1250 }
   1251 
   1252 void
   1253 channel_register_cleanup(struct ssh *ssh, int id,
   1254     channel_callback_fn *fn, int do_close)
   1255 {
   1256 	Channel *c = channel_by_id(ssh, id);
   1257 
   1258 	if (c == NULL) {
   1259 		logit_f("%d: bad id", id);
   1260 		return;
   1261 	}
   1262 	c->detach_user = fn;
   1263 	c->detach_close = do_close;
   1264 }
   1265 
   1266 void
   1267 channel_cancel_cleanup(struct ssh *ssh, int id)
   1268 {
   1269 	Channel *c = channel_by_id(ssh, id);
   1270 
   1271 	if (c == NULL) {
   1272 		logit_f("%d: bad id", id);
   1273 		return;
   1274 	}
   1275 	c->detach_user = NULL;
   1276 	c->detach_close = 0;
   1277 }
   1278 
   1279 void
   1280 channel_register_filter(struct ssh *ssh, int id, channel_infilter_fn *ifn,
   1281     channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
   1282 {
   1283 	Channel *c = channel_lookup(ssh, id);
   1284 
   1285 	if (c == NULL) {
   1286 		logit_f("%d: bad id", id);
   1287 		return;
   1288 	}
   1289 	c->input_filter = ifn;
   1290 	c->output_filter = ofn;
   1291 	c->filter_ctx = ctx;
   1292 	c->filter_cleanup = cfn;
   1293 }
   1294 
   1295 void
   1296 channel_set_fds(struct ssh *ssh, int id, int rfd, int wfd, int efd,
   1297     int extusage, int nonblock, int is_tty, u_int window_max)
   1298 {
   1299 	Channel *c = channel_lookup(ssh, id);
   1300 	int r;
   1301 
   1302 	if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
   1303 		fatal("channel_activate for non-larval channel %d.", id);
   1304 	if (!c->have_remote_id)
   1305 		fatal_f("channel %d: no remote id", c->self);
   1306 
   1307 	channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, is_tty);
   1308 	c->type = SSH_CHANNEL_OPEN;
   1309 	channel_set_used_time(ssh, c);
   1310 	c->local_window = c->local_window_max = window_max;
   1311 
   1312 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
   1313 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
   1314 	    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
   1315 	    (r = sshpkt_send(ssh)) != 0)
   1316 		fatal_fr(r, "channel %i", c->self);
   1317 }
   1318 
   1319 static void
   1320 channel_pre_listener(struct ssh *ssh, Channel *c)
   1321 {
   1322 	c->io_want = SSH_CHAN_IO_SOCK_R;
   1323 }
   1324 
   1325 static void
   1326 channel_pre_connecting(struct ssh *ssh, Channel *c)
   1327 {
   1328 	debug3("channel %d: waiting for connection", c->self);
   1329 	c->io_want = SSH_CHAN_IO_SOCK_W;
   1330 }
   1331 
   1332 static int
   1333 channel_tcpwinsz(struct ssh *ssh)
   1334 {
   1335 	u_int32_t tcpwinsz = 0;
   1336 	socklen_t optsz = sizeof(tcpwinsz);
   1337 	int ret = -1;
   1338 
   1339 	/* if we aren't on a socket return 128KB*/
   1340 	if(!ssh_packet_connection_is_on_socket(ssh))
   1341 	    return(128*1024);
   1342 	ret = getsockopt(ssh_packet_get_connection_in(ssh),
   1343 			 SOL_SOCKET, SO_RCVBUF, &tcpwinsz, &optsz);
   1344 	/* return no more than SSHBUF_SIZE_MAX (currently 256MB) */
   1345 	if ((ret == 0) && tcpwinsz > SSHBUF_SIZE_MAX)
   1346 	    tcpwinsz = SSHBUF_SIZE_MAX;
   1347 	debug2("tcpwinsz: %d for connection: %d", tcpwinsz,
   1348 	       ssh_packet_get_connection_in(ssh));
   1349 	return(tcpwinsz);
   1350 }
   1351 
   1352 static void
   1353 channel_pre_open(struct ssh *ssh, Channel *c)
   1354 {
   1355 	c->io_want = 0;
   1356 	if (c->istate == CHAN_INPUT_OPEN &&
   1357 	    c->remote_window > 0 &&
   1358 	    sshbuf_len(c->input) < c->remote_window &&
   1359 	    sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
   1360 		c->io_want |= SSH_CHAN_IO_RFD;
   1361 	if (c->ostate == CHAN_OUTPUT_OPEN ||
   1362 	    c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
   1363 		if (sshbuf_len(c->output) > 0) {
   1364 			c->io_want |= SSH_CHAN_IO_WFD;
   1365 		} else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
   1366 			if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
   1367 				debug2("channel %d: "
   1368 				    "obuf_empty delayed efd %d/(%zu)", c->self,
   1369 				    c->efd, sshbuf_len(c->extended));
   1370 			else
   1371 				chan_obuf_empty(ssh, c);
   1372 		}
   1373 	}
   1374 	/** XXX check close conditions, too */
   1375 	if (c->efd != -1 && !(c->istate == CHAN_INPUT_CLOSED &&
   1376 	    c->ostate == CHAN_OUTPUT_CLOSED)) {
   1377 		if (c->extended_usage == CHAN_EXTENDED_WRITE &&
   1378 		    sshbuf_len(c->extended) > 0)
   1379 			c->io_want |= SSH_CHAN_IO_EFD_W;
   1380 		else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
   1381 		    (c->extended_usage == CHAN_EXTENDED_READ ||
   1382 		    c->extended_usage == CHAN_EXTENDED_IGNORE) &&
   1383 		    sshbuf_len(c->extended) < c->remote_window)
   1384 			c->io_want |= SSH_CHAN_IO_EFD_R;
   1385 	}
   1386 	/* XXX: What about efd? races? */
   1387 }
   1388 
   1389 /*
   1390  * This is a special state for X11 authentication spoofing.  An opened X11
   1391  * connection (when authentication spoofing is being done) remains in this
   1392  * state until the first packet has been completely read.  The authentication
   1393  * data in that packet is then substituted by the real data if it matches the
   1394  * fake data, and the channel is put into normal mode.
   1395  * XXX All this happens at the client side.
   1396  * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
   1397  */
   1398 static int
   1399 x11_open_helper(struct ssh *ssh, struct sshbuf *b)
   1400 {
   1401 	struct ssh_channels *sc = ssh->chanctxt;
   1402 	u_char *ucp;
   1403 	u_int proto_len, data_len;
   1404 
   1405 	/* Is this being called after the refusal deadline? */
   1406 	if (sc->x11_refuse_time != 0 &&
   1407 	    monotime() >= sc->x11_refuse_time) {
   1408 		verbose("Rejected X11 connection after ForwardX11Timeout "
   1409 		    "expired");
   1410 		return -1;
   1411 	}
   1412 
   1413 	/* Check if the fixed size part of the packet is in buffer. */
   1414 	if (sshbuf_len(b) < 12)
   1415 		return 0;
   1416 
   1417 	/* Parse the lengths of variable-length fields. */
   1418 	ucp = sshbuf_mutable_ptr(b);
   1419 	if (ucp[0] == 0x42) {	/* Byte order MSB first. */
   1420 		proto_len = 256 * ucp[6] + ucp[7];
   1421 		data_len = 256 * ucp[8] + ucp[9];
   1422 	} else if (ucp[0] == 0x6c) {	/* Byte order LSB first. */
   1423 		proto_len = ucp[6] + 256 * ucp[7];
   1424 		data_len = ucp[8] + 256 * ucp[9];
   1425 	} else {
   1426 		debug2("Initial X11 packet contains bad byte order byte: 0x%x",
   1427 		    ucp[0]);
   1428 		return -1;
   1429 	}
   1430 
   1431 	/* Check if the whole packet is in buffer. */
   1432 	if (sshbuf_len(b) <
   1433 	    12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
   1434 		return 0;
   1435 
   1436 	/* Check if authentication protocol matches. */
   1437 	if (proto_len != strlen(sc->x11_saved_proto) ||
   1438 	    memcmp(ucp + 12, sc->x11_saved_proto, proto_len) != 0) {
   1439 		debug2("X11 connection uses different authentication protocol.");
   1440 		return -1;
   1441 	}
   1442 	/* Check if authentication data matches our fake data. */
   1443 	if (data_len != sc->x11_fake_data_len ||
   1444 	    timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
   1445 		sc->x11_fake_data, sc->x11_fake_data_len) != 0) {
   1446 		debug2("X11 auth data does not match fake data.");
   1447 		return -1;
   1448 	}
   1449 	/* Check fake data length */
   1450 	if (sc->x11_fake_data_len != sc->x11_saved_data_len) {
   1451 		error("X11 fake_data_len %d != saved_data_len %d",
   1452 		    sc->x11_fake_data_len, sc->x11_saved_data_len);
   1453 		return -1;
   1454 	}
   1455 	/*
   1456 	 * Received authentication protocol and data match
   1457 	 * our fake data. Substitute the fake data with real
   1458 	 * data.
   1459 	 */
   1460 	memcpy(ucp + 12 + ((proto_len + 3) & ~3),
   1461 	    sc->x11_saved_data, sc->x11_saved_data_len);
   1462 	return 1;
   1463 }
   1464 
   1465 void
   1466 channel_force_close(struct ssh *ssh, Channel *c, int abandon)
   1467 {
   1468 	debug3_f("channel %d: forcibly closing", c->self);
   1469 	if (c->istate == CHAN_INPUT_OPEN)
   1470 		chan_read_failed(ssh, c);
   1471 	if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
   1472 		sshbuf_reset(c->input);
   1473 		chan_ibuf_empty(ssh, c);
   1474 	}
   1475 	if (c->ostate == CHAN_OUTPUT_OPEN ||
   1476 	    c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
   1477 		sshbuf_reset(c->output);
   1478 		chan_write_failed(ssh, c);
   1479 	}
   1480 	if (c->detach_user)
   1481 		c->detach_user(ssh, c->self, 1, NULL);
   1482 	if (c->efd != -1)
   1483 		channel_close_fd(ssh, c, &c->efd);
   1484 	if (abandon)
   1485 		c->type = SSH_CHANNEL_ABANDONED;
   1486 	/* exempt from inactivity timeouts */
   1487 	c->inactive_deadline = 0;
   1488 	c->lastused = 0;
   1489 }
   1490 
   1491 static void
   1492 channel_pre_x11_open(struct ssh *ssh, Channel *c)
   1493 {
   1494 	int ret = x11_open_helper(ssh, c->output);
   1495 
   1496 	/* c->force_drain = 1; */
   1497 
   1498 	if (ret == 1) {
   1499 		c->type = SSH_CHANNEL_OPEN;
   1500 		channel_set_used_time(ssh, c);
   1501 		channel_pre_open(ssh, c);
   1502 	} else if (ret == -1) {
   1503 		logit("X11 connection rejected because of wrong "
   1504 		    "authentication.");
   1505 		debug2("X11 rejected %d i%d/o%d",
   1506 		    c->self, c->istate, c->ostate);
   1507 		channel_force_close(ssh, c, 0);
   1508 	}
   1509 }
   1510 
   1511 static void
   1512 channel_pre_mux_client(struct ssh *ssh, Channel *c)
   1513 {
   1514 	c->io_want = 0;
   1515 	if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
   1516 	    sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
   1517 		c->io_want |= SSH_CHAN_IO_RFD;
   1518 	if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
   1519 		/* clear buffer immediately (discard any partial packet) */
   1520 		sshbuf_reset(c->input);
   1521 		chan_ibuf_empty(ssh, c);
   1522 		/* Start output drain. XXX just kill chan? */
   1523 		chan_rcvd_oclose(ssh, c);
   1524 	}
   1525 	if (c->ostate == CHAN_OUTPUT_OPEN ||
   1526 	    c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
   1527 		if (sshbuf_len(c->output) > 0)
   1528 			c->io_want |= SSH_CHAN_IO_WFD;
   1529 		else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
   1530 			chan_obuf_empty(ssh, c);
   1531 	}
   1532 }
   1533 
   1534 static inline int
   1535 socks_decode_error(Channel *c, int status, const char *func, const char *msg)
   1536 {
   1537 	if (status == SSH_ERR_MESSAGE_INCOMPLETE)
   1538 		return 0;
   1539 	else {
   1540 		debug_r(status, "%s: channel %d: decode %s",
   1541 		    func, c->self, msg);
   1542 		return -1;
   1543 	}
   1544 }
   1545 
   1546 /* try to decode a socks4 header */
   1547 static int
   1548 channel_decode_socks4(Channel *c, struct sshbuf *input, struct sshbuf *output)
   1549 {
   1550 	uint8_t socks_ver, socks_cmd, dest_addr[4];
   1551 	uint16_t dest_port;
   1552 	char *user = NULL, *host = NULL;
   1553 	int success = -1, socks4a = 0, r;
   1554 	struct sshbuf *b = NULL;
   1555 
   1556 	if (sshbuf_len(input) < 9)
   1557 		return 0;
   1558 
   1559 	/* We may not have a complete message, so work on a dup of the buffer */
   1560 	if ((b = sshbuf_fromb(input)) == NULL)
   1561 		fatal_f("sshbuf_fromb failed");
   1562 
   1563 	debug2("channel %d: decode socks4", c->self);
   1564 	if ((r = sshbuf_get_u8(b, &socks_ver)) != 0 ||
   1565 	    (r = sshbuf_get_u8(b, &socks_cmd)) != 0 ||
   1566 	    (r = sshbuf_get_u16(b, &dest_port)) != 0 ||
   1567 	    (r = sshbuf_get(b, &dest_addr, sizeof(dest_addr))) != 0 ||
   1568 	    (r = sshbuf_get_nulterminated_string(b, 1024, &user, NULL)) != 0) {
   1569 		success = socks_decode_error(c, r, __func__, "header");
   1570 		goto out;
   1571 	}
   1572 
   1573 	/* Is this a SOCKS4A request? (indicated by an address of 0.0.0.x) */
   1574 	if (dest_addr[0] == 0 && dest_addr[1] == 0 &&
   1575 	    dest_addr[2] == 0 && dest_addr[3] != 0) {
   1576 		/* If so, then the hostname follows, also nul-terminated */
   1577 		if ((r = sshbuf_get_nulterminated_string(b, 1024,
   1578 		    &host, NULL)) != 0) {
   1579 			success = socks_decode_error(c, r, __func__, "host");
   1580 			goto out;
   1581 		}
   1582 		socks4a = 1;
   1583 	} else {
   1584 		/* Plain SOCKS4 passes an IPv4 binary address; reconstruct */
   1585 		xasprintf(&host, "%d.%d.%d.%d",
   1586 		    dest_addr[0], dest_addr[1], dest_addr[2], dest_addr[3]);
   1587 	}
   1588 
   1589 	/* We have a complete SOCKS4 message; consume it from input */
   1590 	if ((r = sshbuf_consume_upto_child(input, b)) != 0)
   1591 		fatal_fr(r, "channel %d: consume", c->self);
   1592 
   1593 	/* Handle the request */
   1594 	debug2("channel %d: %s: user=\"%s\" command=%d destination=[%s]:%d",
   1595 	    c->self, socks4a ? "SOCKS4A" : "SOCKS4", user, (int)socks_cmd,
   1596 	    host, dest_port);
   1597 	if (socks_cmd != 1) {
   1598 		debug("channel %d: cannot handle %s command 0x%02x",
   1599 		    c->self, socks4a ? "SOCKS4A" : "SOCKS4", socks_cmd);
   1600 		goto out;
   1601 	}
   1602 	free(c->path);
   1603 	c->path = host;
   1604 	host = NULL; /* transferred */
   1605 	c->host_port = dest_port;
   1606 
   1607 	/* Reply to the SOCKS4 client */
   1608 	if ((r = sshbuf_put_u8(output, 0)) != 0 ||	/* vn: 0 for reply */
   1609 	    (r = sshbuf_put_u8(output, 90)) != 0 ||	/* cd: req granted */
   1610 	    (r = sshbuf_put_u16(output, 0)) != 0 ||	/* port: ignored */
   1611 	    (r = sshbuf_put_u32(output, ntohl(INADDR_ANY))) != 0) /* ignored */
   1612 		fatal_fr(r, "channel %d: compose reply", c->self);
   1613 
   1614 	/* success */
   1615 	success = 1;
   1616  out:
   1617 	sshbuf_free(b);
   1618 	free(user);
   1619 	free(host);
   1620 	return success;
   1621 }
   1622 
   1623 /* try to decode a socks5 header */
   1624 #define SSH_SOCKS5_AUTHDONE	0x1000
   1625 #define SSH_SOCKS5_NOAUTH	0x00
   1626 #define SSH_SOCKS5_IPV4		0x01
   1627 #define SSH_SOCKS5_DOMAIN	0x03
   1628 #define SSH_SOCKS5_IPV6		0x04
   1629 #define SSH_SOCKS5_CONNECT	0x01
   1630 #define SSH_SOCKS5_SUCCESS	0x00
   1631 
   1632 /*
   1633  * Handles SOCKS5 authentication. Note 'b' must be a dup of 'input'
   1634  * Returns 0 on insufficient queued date, 1 on authentication success or
   1635  * -1 on error.
   1636  */
   1637 static int
   1638 channel_socks5_check_auth(Channel *c, struct sshbuf *b, struct sshbuf *input,
   1639     struct sshbuf *output)
   1640 {
   1641 	uint8_t socks_ver;
   1642 	uint8_t nmethods, method;
   1643 	int r;
   1644 	u_int i, found;
   1645 
   1646 	/* format: ver | nmethods | methods */
   1647 	if ((r = sshbuf_get_u8(b, &socks_ver)) != 0)
   1648 		return socks_decode_error(c, r, __func__, "version");
   1649 	if (socks_ver != 5) /* shouldn't happen; checked by caller^2 */
   1650 		fatal_fr(r, "channel %d: internal error: not socks5", c->self);
   1651 	if ((r = sshbuf_get_u8(b, &nmethods)) != 0)
   1652 		return socks_decode_error(c, r, __func__, "methods");
   1653 	for (found = i = 0; i < nmethods; i++) {
   1654 		if ((r = sshbuf_get_u8(b, &method)) != 0)
   1655 			return socks_decode_error(c, r, __func__, "method");
   1656 		if (method == SSH_SOCKS5_NOAUTH)
   1657 			found = 1;
   1658 	}
   1659 	if (!found) {
   1660 		debug("channel %d: didn't request SSH_SOCKS5_NOAUTH", c->self);
   1661 		return -1;
   1662 	}
   1663 	/* Consume completed request */
   1664 	if ((r = sshbuf_consume_upto_child(input, b)) != 0)
   1665 		fatal_fr(r, "channel %d: consume", c->self);
   1666 
   1667 	/* Compose reply: version, method */
   1668 	if ((r = sshbuf_put_u8(output, 0x05)) != 0 ||
   1669 	    (r = sshbuf_put_u8(output, SSH_SOCKS5_NOAUTH)) != 0)
   1670 		fatal_fr(r, "channel %d: append reply", c->self);
   1671 	/* success */
   1672 	debug2("channel %d: socks5 auth done", c->self);
   1673 	return 1;
   1674 }
   1675 
   1676 static int
   1677 channel_decode_socks5(Channel *c, struct sshbuf *input, struct sshbuf *output)
   1678 {
   1679 	uint8_t socks_ver, socks_cmd, socks_reserved, socks_atyp, addrlen;
   1680 	uint16_t dest_port;
   1681 	char dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
   1682 	u_int af;
   1683 	int r, success = -1;;
   1684 	struct sshbuf *b = NULL;
   1685 
   1686 	debug2("channel %d: decode socks5 %s", c->self,
   1687 	    (c->flags & SSH_SOCKS5_AUTHDONE) ? "request" : "auth");
   1688 
   1689 	/* We may not have a complete message, so work on a dup of the buffer */
   1690 	if ((b = sshbuf_fromb(input)) == NULL)
   1691 		fatal_f("sshbuf_fromb failed");
   1692 
   1693 	if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
   1694 		if ((r = channel_socks5_check_auth(c, b, input, output)) != 1) {
   1695 			success = r;
   1696 			goto out;
   1697 		}
   1698 		c->flags |= SSH_SOCKS5_AUTHDONE;
   1699 		/* Continue to parse request in case client speculated ahead */
   1700 	}
   1701 
   1702 	/* Request messages (auth or connect) always start with the version */
   1703 	if ((r = sshbuf_get_u8(b, &socks_ver)) != 0) {
   1704 		success = socks_decode_error(c, r, __func__, "version");
   1705 		goto out;
   1706 	}
   1707 	if (socks_ver != 5) /* shouldn't happen */
   1708 		fatal_fr(r, "channel %d: internal error: not socks5", c->self);
   1709 
   1710 	/* Parse SOCKS5 request header */
   1711 	debug2("channel %d: socks5 post auth", c->self);
   1712 	if ((r = sshbuf_get_u8(b, &socks_cmd)) != 0 ||
   1713 	    (r = sshbuf_get_u8(b, &socks_reserved)) != 0 ||
   1714 	    (r = sshbuf_get_u8(b, &socks_atyp)) != 0) {
   1715 		success = socks_decode_error(c, r, __func__, "request header");
   1716 		goto out;
   1717 	}
   1718 
   1719 	if (socks_ver != 0x05 ||
   1720 	    socks_cmd != SSH_SOCKS5_CONNECT ||
   1721 	    socks_reserved != 0x00) {
   1722 		debug2("channel %d: only socks5 connect supported", c->self);
   1723 		goto out;
   1724 	}
   1725 
   1726 	switch (socks_atyp) {
   1727 	case SSH_SOCKS5_IPV4:
   1728 		addrlen = 4;
   1729 		af = AF_INET;
   1730 		break;
   1731 	case SSH_SOCKS5_DOMAIN:
   1732 		if ((r = sshbuf_get_u8(b, &addrlen)) != 0) {
   1733 			success = socks_decode_error(c, r, __func__, "addrlen");
   1734 			goto out;
   1735 		}
   1736 		af = -1;
   1737 		break;
   1738 	case SSH_SOCKS5_IPV6:
   1739 		addrlen = 16;
   1740 		af = AF_INET6;
   1741 		break;
   1742 	default:
   1743 		debug2("channel %d: bad socks5 atyp %d", c->self, socks_atyp);
   1744 		goto out;
   1745 	}
   1746 	if ((r = sshbuf_get(b, &dest_addr, addrlen)) != 0 ||
   1747 	    (r = sshbuf_get_u16(b, &dest_port)) != 0) {
   1748 		success = socks_decode_error(c, r, __func__, "addr/port");
   1749 		goto out;
   1750 	}
   1751 	dest_addr[addrlen] = '\0';
   1752 
   1753 	/* We have a complete SOCKS5 request; consume it from input */
   1754 	if ((r = sshbuf_consume_upto_child(input, b)) != 0)
   1755 		fatal_fr(r, "channel %d: consume", c->self);
   1756 
   1757 	free(c->path);
   1758 	c->path = NULL;
   1759 	if (socks_atyp == SSH_SOCKS5_DOMAIN)
   1760 		c->path = xstrdup(dest_addr);
   1761 	else {
   1762 		if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
   1763 			return -1;
   1764 		c->path = xstrdup(ntop);
   1765 	}
   1766 	c->host_port = dest_port;
   1767 
   1768 	debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
   1769 	    c->self, c->path, c->host_port, socks_cmd);
   1770 
   1771 	/* Reply */
   1772 	if ((r = sshbuf_put_u8(output, 0x05)) != 0 ||	/* version */
   1773 	    (r = sshbuf_put_u8(output, SSH_SOCKS5_SUCCESS)) != 0 || /* cmd */
   1774 	    (r = sshbuf_put_u8(output, 0)) != 0 ||	/* reserved, ignored */
   1775 	    (r = sshbuf_put_u8(output, SSH_SOCKS5_IPV4)) != 0 || /* addrtype */
   1776 	    (r = sshbuf_put_u32(output, ntohl(INADDR_ANY))) != 0 || /* addr */
   1777 	    (r = sshbuf_put_u16(output, dest_port)) != 0) /* port */
   1778 		fatal_fr(r, "channel %d: append reply", c->self);
   1779 
   1780 	/* success */
   1781 	success = 1;
   1782  out:
   1783 	sshbuf_free(b);
   1784 	return success;
   1785 }
   1786 
   1787 Channel *
   1788 channel_connect_stdio_fwd(struct ssh *ssh,
   1789     const char *host_to_connect, int port_to_connect,
   1790     int in, int out, int nonblock)
   1791 {
   1792 	Channel *c;
   1793 
   1794 	debug_f("%s:%d", host_to_connect, port_to_connect);
   1795 
   1796 	c = channel_new(ssh, "stdio-forward", SSH_CHANNEL_OPENING, in, out,
   1797 	    -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
   1798 	    0, "stdio-forward", nonblock);
   1799 
   1800 	c->path = xstrdup(host_to_connect);
   1801 	c->host_port = port_to_connect;
   1802 	c->listening_port = 0;
   1803 	c->force_drain = 1;
   1804 
   1805 	channel_register_fds(ssh, c, in, out, -1, 0, 1, 0);
   1806 	port_open_helper(ssh, c, port_to_connect == PORT_STREAMLOCAL ?
   1807 	    "direct-streamlocal (at) openssh.com" : "direct-tcpip");
   1808 
   1809 	return c;
   1810 }
   1811 
   1812 /* dynamic port forwarding */
   1813 static void
   1814 channel_pre_dynamic(struct ssh *ssh, Channel *c)
   1815 {
   1816 	u_int have;
   1817 	u_char ver;
   1818 	int r, ret;
   1819 
   1820 	c->io_want = 0;
   1821 	have = sshbuf_len(c->input);
   1822 	debug2("channel %d: pre_dynamic: have %d", c->self, have);
   1823 	/* sshbuf_dump(c->input, stderr); */
   1824 	/* check if the fixed size part of the packet is in buffer. */
   1825 	if (have < 3) {
   1826 		/* need more */
   1827 		c->io_want |= SSH_CHAN_IO_RFD;
   1828 		return;
   1829 	}
   1830 	/* try to guess the protocol */
   1831 	if ((r = sshbuf_peek_u8(c->input, 0, &ver)) != 0)
   1832 		fatal_fr(r, "sshbuf_peek_u8");
   1833 	switch (ver) {
   1834 	case 0x04:
   1835 		ret = channel_decode_socks4(c, c->input, c->output);
   1836 		break;
   1837 	case 0x05:
   1838 		ret = channel_decode_socks5(c, c->input, c->output);
   1839 		break;
   1840 	default:
   1841 		debug2_f("channel %d: unknown SOCKS version %u", c->self, ver);
   1842 		ret = -1;
   1843 		break;
   1844 	}
   1845 	if (ret < 0) {
   1846 		chan_mark_dead(ssh, c);
   1847 	} else if (ret == 0) {
   1848 		debug2("channel %d: pre_dynamic: need more", c->self);
   1849 		/* need more */
   1850 		c->io_want |= SSH_CHAN_IO_RFD;
   1851 		if (sshbuf_len(c->output))
   1852 			c->io_want |= SSH_CHAN_IO_WFD;
   1853 	} else {
   1854 		/* switch to the next state */
   1855 		c->type = SSH_CHANNEL_OPENING;
   1856 		port_open_helper(ssh, c, "direct-tcpip");
   1857 	}
   1858 }
   1859 
   1860 /* simulate read-error */
   1861 static void
   1862 rdynamic_close(struct ssh *ssh, Channel *c)
   1863 {
   1864 	c->type = SSH_CHANNEL_OPEN;
   1865 	channel_force_close(ssh, c, 0);
   1866 }
   1867 
   1868 /* reverse dynamic port forwarding */
   1869 static void
   1870 channel_before_prepare_io_rdynamic(struct ssh *ssh, Channel *c)
   1871 {
   1872 	const u_char *p;
   1873 	u_int have, len;
   1874 	int r, ret;
   1875 
   1876 	have = sshbuf_len(c->output);
   1877 	debug2("channel %d: pre_rdynamic: have %d", c->self, have);
   1878 	/* sshbuf_dump(c->output, stderr); */
   1879 	/* EOF received */
   1880 	if (c->flags & CHAN_EOF_RCVD) {
   1881 		if ((r = sshbuf_consume(c->output, have)) != 0)
   1882 			fatal_fr(r, "channel %d: consume", c->self);
   1883 		rdynamic_close(ssh, c);
   1884 		return;
   1885 	}
   1886 	/* check if the fixed size part of the packet is in buffer. */
   1887 	if (have < 3)
   1888 		return;
   1889 	/* try to guess the protocol */
   1890 	p = sshbuf_ptr(c->output);
   1891 	switch (p[0]) {
   1892 	case 0x04:
   1893 		/* switch input/output for reverse forwarding */
   1894 		ret = channel_decode_socks4(c, c->output, c->input);
   1895 		break;
   1896 	case 0x05:
   1897 		ret = channel_decode_socks5(c, c->output, c->input);
   1898 		break;
   1899 	default:
   1900 		ret = -1;
   1901 		break;
   1902 	}
   1903 	if (ret < 0) {
   1904 		rdynamic_close(ssh, c);
   1905 	} else if (ret == 0) {
   1906 		debug2("channel %d: pre_rdynamic: need more", c->self);
   1907 		/* send socks request to peer */
   1908 		len = sshbuf_len(c->input);
   1909 		if (len > 0 && len < c->remote_window) {
   1910 			if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
   1911 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
   1912 			    (r = sshpkt_put_stringb(ssh, c->input)) != 0 ||
   1913 			    (r = sshpkt_send(ssh)) != 0) {
   1914 				fatal_fr(r, "channel %i: rdynamic", c->self);
   1915 			}
   1916 			if ((r = sshbuf_consume(c->input, len)) != 0)
   1917 				fatal_fr(r, "channel %d: consume", c->self);
   1918 			c->remote_window -= len;
   1919 		}
   1920 	} else if (rdynamic_connect_finish(ssh, c) < 0) {
   1921 		/* the connect failed */
   1922 		rdynamic_close(ssh, c);
   1923 	}
   1924 }
   1925 
   1926 /* This is our fake X11 server socket. */
   1927 static void
   1928 channel_post_x11_listener(struct ssh *ssh, Channel *c)
   1929 {
   1930 	Channel *nc;
   1931 	struct sockaddr_storage addr;
   1932 	int r, newsock, oerrno, remote_port;
   1933 	socklen_t addrlen;
   1934 	char buf[16384], *remote_ipaddr;
   1935 
   1936 	if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
   1937 		return;
   1938 
   1939 	debug("X11 connection requested.");
   1940 	addrlen = sizeof(addr);
   1941 	newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
   1942 	if (c->single_connection) {
   1943 		oerrno = errno;
   1944 		debug2("single_connection: closing X11 listener.");
   1945 		channel_close_fd(ssh, c, &c->sock);
   1946 		chan_mark_dead(ssh, c);
   1947 		errno = oerrno;
   1948 	}
   1949 	if (newsock == -1) {
   1950 		if (errno != EINTR && errno != EWOULDBLOCK &&
   1951 		    errno != ECONNABORTED)
   1952 			error("accept: %.100s", strerror(errno));
   1953 		if (errno == EMFILE || errno == ENFILE)
   1954 			c->notbefore = monotime() + 1;
   1955 		return;
   1956 	}
   1957 	set_nodelay(newsock);
   1958 	remote_ipaddr = get_peer_ipaddr(newsock);
   1959 	remote_port = get_peer_port(newsock);
   1960 	snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
   1961 	    remote_ipaddr, remote_port);
   1962 
   1963 	nc = channel_new(ssh, "x11-connection",
   1964 	    SSH_CHANNEL_OPENING, newsock, newsock, -1,
   1965 	    c->local_window_max, c->local_maxpacket, 0, buf, 1);
   1966 	open_preamble(ssh, __func__, nc, "x11");
   1967 	if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
   1968 	    (r = sshpkt_put_u32(ssh, remote_port)) != 0) {
   1969 		fatal_fr(r, "channel %i: reply", c->self);
   1970 	}
   1971 	if ((r = sshpkt_send(ssh)) != 0)
   1972 		fatal_fr(r, "channel %i: send", c->self);
   1973 	free(remote_ipaddr);
   1974 }
   1975 
   1976 static void
   1977 port_open_helper(struct ssh *ssh, Channel *c, const char *rtype)
   1978 {
   1979 	char *local_ipaddr = get_local_ipaddr(c->sock);
   1980 	int local_port = c->sock == -1 ? 65536 : get_local_port(c->sock);
   1981 	char *remote_ipaddr = get_peer_ipaddr(c->sock);
   1982 	int remote_port = get_peer_port(c->sock);
   1983 	int r;
   1984 
   1985 	if (remote_port == -1) {
   1986 		/* Fake addr/port to appease peers that validate it (Tectia) */
   1987 		free(remote_ipaddr);
   1988 		remote_ipaddr = xstrdup("127.0.0.1");
   1989 		remote_port = 65535;
   1990 	}
   1991 
   1992 	free(c->remote_name);
   1993 	xasprintf(&c->remote_name,
   1994 	    "%s: listening port %d for %.100s port %d, "
   1995 	    "connect from %.200s port %d to %.100s port %d",
   1996 	    rtype, c->listening_port, c->path, c->host_port,
   1997 	    remote_ipaddr, remote_port, local_ipaddr, local_port);
   1998 
   1999 	open_preamble(ssh, __func__, c, rtype);
   2000 	if (strcmp(rtype, "direct-tcpip") == 0) {
   2001 		/* target host, port */
   2002 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
   2003 		    (r = sshpkt_put_u32(ssh, c->host_port)) != 0)
   2004 			fatal_fr(r, "channel %i: reply", c->self);
   2005 	} else if (strcmp(rtype, "direct-streamlocal (at) openssh.com") == 0) {
   2006 		/* target path */
   2007 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
   2008 			fatal_fr(r, "channel %i: reply", c->self);
   2009 	} else if (strcmp(rtype, "forwarded-streamlocal (at) openssh.com") == 0) {
   2010 		/* listen path */
   2011 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
   2012 			fatal_fr(r, "channel %i: reply", c->self);
   2013 	} else {
   2014 		/* listen address, port */
   2015 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
   2016 		    (r = sshpkt_put_u32(ssh, local_port)) != 0)
   2017 			fatal_fr(r, "channel %i: reply", c->self);
   2018 	}
   2019 	if (strcmp(rtype, "forwarded-streamlocal (at) openssh.com") == 0) {
   2020 		/* reserved for future owner/mode info */
   2021 		if ((r = sshpkt_put_cstring(ssh, "")) != 0)
   2022 			fatal_fr(r, "channel %i: reply", c->self);
   2023 	} else {
   2024 		/* originator host and port */
   2025 		if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
   2026 		    (r = sshpkt_put_u32(ssh, (u_int)remote_port)) != 0)
   2027 			fatal_fr(r, "channel %i: reply", c->self);
   2028 	}
   2029 	if ((r = sshpkt_send(ssh)) != 0)
   2030 		fatal_fr(r, "channel %i: send", c->self);
   2031 	free(remote_ipaddr);
   2032 	free(local_ipaddr);
   2033 }
   2034 
   2035 void
   2036 channel_set_x11_refuse_time(struct ssh *ssh, time_t refuse_time)
   2037 {
   2038 	ssh->chanctxt->x11_refuse_time = refuse_time;
   2039 }
   2040 
   2041 /*
   2042  * This socket is listening for connections to a forwarded TCP/IP port.
   2043  */
   2044 static void
   2045 channel_post_port_listener(struct ssh *ssh, Channel *c)
   2046 {
   2047 	Channel *nc;
   2048 	struct sockaddr_storage addr;
   2049 	int newsock, nextstate;
   2050 	socklen_t addrlen;
   2051 	const char *rtype;
   2052 
   2053 	if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
   2054 		return;
   2055 
   2056 	debug("Connection to port %d forwarding to %.100s port %d requested.",
   2057 	    c->listening_port, c->path, c->host_port);
   2058 
   2059 	if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
   2060 		nextstate = SSH_CHANNEL_OPENING;
   2061 		rtype = "forwarded-tcpip";
   2062 	} else if (c->type == SSH_CHANNEL_RUNIX_LISTENER) {
   2063 		nextstate = SSH_CHANNEL_OPENING;
   2064 		rtype = "forwarded-streamlocal (at) openssh.com";
   2065 	} else if (c->host_port == PORT_STREAMLOCAL) {
   2066 		nextstate = SSH_CHANNEL_OPENING;
   2067 		rtype = "direct-streamlocal (at) openssh.com";
   2068 	} else if (c->host_port == 0) {
   2069 		nextstate = SSH_CHANNEL_DYNAMIC;
   2070 		rtype = "dynamic-tcpip";
   2071 	} else {
   2072 		nextstate = SSH_CHANNEL_OPENING;
   2073 		rtype = "direct-tcpip";
   2074 	}
   2075 
   2076 	addrlen = sizeof(addr);
   2077 	newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
   2078 	if (newsock == -1) {
   2079 		if (errno != EINTR && errno != EWOULDBLOCK &&
   2080 		    errno != ECONNABORTED)
   2081 			error("accept: %.100s", strerror(errno));
   2082 		if (errno == EMFILE || errno == ENFILE)
   2083 			c->notbefore = monotime() + 1;
   2084 		return;
   2085 	}
   2086 	if (c->host_port != PORT_STREAMLOCAL)
   2087 		set_nodelay(newsock);
   2088 	nc = channel_new(ssh, rtype, nextstate, newsock, newsock, -1,
   2089 	    c->local_window_max, c->local_maxpacket, 0, rtype, 1);
   2090 	nc->listening_port = c->listening_port;
   2091 	nc->host_port = c->host_port;
   2092 	if (c->path != NULL)
   2093 		nc->path = xstrdup(c->path);
   2094 
   2095 	if (nextstate != SSH_CHANNEL_DYNAMIC)
   2096 		port_open_helper(ssh, nc, rtype);
   2097 }
   2098 
   2099 /*
   2100  * This is the authentication agent socket listening for connections from
   2101  * clients.
   2102  */
   2103 static void
   2104 channel_post_auth_listener(struct ssh *ssh, Channel *c)
   2105 {
   2106 	Channel *nc;
   2107 	int r, newsock;
   2108 	struct sockaddr_storage addr;
   2109 	socklen_t addrlen;
   2110 
   2111 	if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
   2112 		return;
   2113 
   2114 	addrlen = sizeof(addr);
   2115 	newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
   2116 	if (newsock == -1) {
   2117 		error("accept from auth socket: %.100s", strerror(errno));
   2118 		if (errno == EMFILE || errno == ENFILE)
   2119 			c->notbefore = monotime() + 1;
   2120 		return;
   2121 	}
   2122 	nc = channel_new(ssh, "agent-connection",
   2123 	    SSH_CHANNEL_OPENING, newsock, newsock, -1,
   2124 	    c->local_window_max, c->local_maxpacket,
   2125 	    0, "accepted auth socket", 1);
   2126 	open_preamble(ssh, __func__, nc,
   2127 	    c->agent_new ? "agent-connect" : "auth-agent (at) openssh.com");
   2128 	if ((r = sshpkt_send(ssh)) != 0)
   2129 		fatal_fr(r, "channel %i", c->self);
   2130 }
   2131 
   2132 static void
   2133 channel_post_connecting(struct ssh *ssh, Channel *c)
   2134 {
   2135 	int err = 0, sock, isopen, r;
   2136 	socklen_t sz = sizeof(err);
   2137 
   2138 	if ((c->io_ready & SSH_CHAN_IO_SOCK_W) == 0)
   2139 		return;
   2140 	if (!c->have_remote_id)
   2141 		fatal_f("channel %d: no remote id", c->self);
   2142 	/* for rdynamic the OPEN_CONFIRMATION has been sent already */
   2143 	isopen = (c->type == SSH_CHANNEL_RDYNAMIC_FINISH);
   2144 
   2145 	if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) == -1) {
   2146 		err = errno;
   2147 		error("getsockopt SO_ERROR failed");
   2148 	}
   2149 
   2150 	if (err == 0) {
   2151 		/* Non-blocking connection completed */
   2152 		debug("channel %d: connected to %s port %d",
   2153 		    c->self, c->connect_ctx.host, c->connect_ctx.port);
   2154 		channel_connect_ctx_free(&c->connect_ctx);
   2155 		c->type = SSH_CHANNEL_OPEN;
   2156 		channel_set_used_time(ssh, c);
   2157 		if (isopen) {
   2158 			/* no message necessary */
   2159 		} else {
   2160 			if ((r = sshpkt_start(ssh,
   2161 			    SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
   2162 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
   2163 			    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
   2164 			    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
   2165 			    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
   2166 			    (r = sshpkt_send(ssh)) != 0)
   2167 				fatal_fr(r, "channel %i open confirm", c->self);
   2168 		}
   2169 		return;
   2170 	}
   2171 	if (err == EINTR || err == EAGAIN || err == EINPROGRESS)
   2172 		return;
   2173 
   2174 	/* Non-blocking connection failed */
   2175 	debug("channel %d: connection failed: %s", c->self, strerror(err));
   2176 
   2177 	/* Try next address, if any */
   2178 	if ((sock = connect_next(&c->connect_ctx)) == -1) {
   2179 		/* Exhausted all addresses for this destination */
   2180 		error("connect_to %.100s port %d: failed.",
   2181 		    c->connect_ctx.host, c->connect_ctx.port);
   2182 		channel_connect_ctx_free(&c->connect_ctx);
   2183 		if (isopen) {
   2184 			rdynamic_close(ssh, c);
   2185 		} else {
   2186 			if ((r = sshpkt_start(ssh,
   2187 			    SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
   2188 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
   2189 			    (r = sshpkt_put_u32(ssh,
   2190 			    SSH2_OPEN_CONNECT_FAILED)) != 0 ||
   2191 			    (r = sshpkt_put_cstring(ssh, strerror(err))) != 0 ||
   2192 			    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
   2193 			    (r = sshpkt_send(ssh)) != 0)
   2194 				fatal_fr(r, "channel %i: failure", c->self);
   2195 			chan_mark_dead(ssh, c);
   2196 		}
   2197 	}
   2198 
   2199 	/* New non-blocking connection in progress */
   2200 	close(c->sock);
   2201 	c->sock = c->rfd = c->wfd = sock;
   2202 }
   2203 
   2204 static int
   2205 channel_handle_rfd(struct ssh *ssh, Channel *c)
   2206 {
   2207 	char buf[CHAN_RBUF];
   2208 	ssize_t len;
   2209 	int r;
   2210 	size_t nr = 0, have, avail, maxlen = CHANNEL_MAX_READ;
   2211 
   2212 	if ((c->io_ready & SSH_CHAN_IO_RFD) == 0)
   2213 		return 1; /* Shouldn't happen */
   2214 	if ((avail = sshbuf_avail(c->input)) == 0)
   2215 		return 1; /* Shouldn't happen */
   2216 
   2217 	/*
   2218 	 * For "simple" channels (i.e. not datagram or filtered), we can
   2219 	 * read directly to the channel buffer.
   2220 	 */
   2221 	if (c->input_filter == NULL && !c->datagram) {
   2222 		/* Only OPEN channels have valid rwin */
   2223 		if (c->type == SSH_CHANNEL_OPEN) {
   2224 			if ((have = sshbuf_len(c->input)) >= c->remote_window)
   2225 				return 1; /* shouldn't happen */
   2226 			if (maxlen > c->remote_window - have)
   2227 				maxlen = c->remote_window - have;
   2228 		}
   2229 		if (maxlen > avail)
   2230 			maxlen = avail;
   2231 		if ((r = sshbuf_read(c->rfd, c->input, maxlen, &nr)) != 0) {
   2232 			if (errno == EINTR || errno == EAGAIN)
   2233 				return 1;
   2234 			debug2("channel %d: read failed rfd %d maxlen %zu: %s",
   2235 			    c->self, c->rfd, maxlen, ssh_err(r));
   2236 			goto rfail;
   2237 		}
   2238 		if (nr != 0)
   2239 			channel_set_used_time(ssh, c);
   2240 		return 1;
   2241 	}
   2242 
   2243 	len = read(c->rfd, buf, sizeof(buf));
   2244 	if (len == -1 && (errno == EINTR || errno == EAGAIN))
   2245 		return 1;
   2246 	if (len <= 0) {
   2247 		debug2("channel %d: read<=0 rfd %d len %zd: %s",
   2248 		    c->self, c->rfd, len,
   2249 		    len == 0 ? "closed" : strerror(errno));
   2250  rfail:
   2251 		if (c->type != SSH_CHANNEL_OPEN) {
   2252 			debug2("channel %d: not open", c->self);
   2253 			chan_mark_dead(ssh, c);
   2254 			return -1;
   2255 		} else {
   2256 			chan_read_failed(ssh, c);
   2257 		}
   2258 		return -1;
   2259 	}
   2260 	channel_set_used_time(ssh, c);
   2261 	if (c->input_filter != NULL) {
   2262 		if (c->input_filter(ssh, c, buf, len) == -1) {
   2263 			debug2("channel %d: filter stops", c->self);
   2264 			chan_read_failed(ssh, c);
   2265 		}
   2266 	} else if (c->datagram) {
   2267 		if ((r = sshbuf_put_string(c->input, buf, len)) != 0)
   2268 			fatal_fr(r, "channel %i: put datagram", c->self);
   2269 	}
   2270 	return 1;
   2271 }
   2272 
   2273 static int
   2274 channel_handle_wfd(struct ssh *ssh, Channel *c)
   2275 {
   2276 	struct termios tio;
   2277 	u_char *data = NULL, *buf; /* XXX const; need filter API change */
   2278 	size_t dlen, olen = 0;
   2279 	int r, len;
   2280 
   2281 	if ((c->io_ready & SSH_CHAN_IO_WFD) == 0)
   2282 		return 1;
   2283 	if (sshbuf_len(c->output) == 0)
   2284 		return 1;
   2285 
   2286 	/* Send buffered output data to the socket. */
   2287 	olen = sshbuf_len(c->output);
   2288 	if (c->output_filter != NULL) {
   2289 		if ((buf = c->output_filter(ssh, c, &data, &dlen)) == NULL) {
   2290 			debug2("channel %d: filter stops", c->self);
   2291 			if (c->type != SSH_CHANNEL_OPEN)
   2292 				chan_mark_dead(ssh, c);
   2293 			else
   2294 				chan_write_failed(ssh, c);
   2295 			return -1;
   2296 		}
   2297 	} else if (c->datagram) {
   2298 		if ((r = sshbuf_get_string(c->output, &data, &dlen)) != 0)
   2299 			fatal_fr(r, "channel %i: get datagram", c->self);
   2300 		buf = data;
   2301 	} else {
   2302 		buf = data = sshbuf_mutable_ptr(c->output);
   2303 		dlen = sshbuf_len(c->output);
   2304 	}
   2305 
   2306 	if (c->datagram) {
   2307 		/* ignore truncated writes, datagrams might get lost */
   2308 		len = write(c->wfd, buf, dlen);
   2309 		free(data);
   2310 		if (len == -1 && (errno == EINTR || errno == EAGAIN))
   2311 			return 1;
   2312 		if (len <= 0)
   2313 			goto write_fail;
   2314 		goto out;
   2315 	}
   2316 
   2317 	len = write(c->wfd, buf, dlen);
   2318 	if (len == -1 && (errno == EINTR || errno == EAGAIN))
   2319 		return 1;
   2320 	if (len <= 0) {
   2321  write_fail:
   2322 		if (c->type != SSH_CHANNEL_OPEN) {
   2323 			debug2("channel %d: not open", c->self);
   2324 			chan_mark_dead(ssh, c);
   2325 			return -1;
   2326 		} else {
   2327 			chan_write_failed(ssh, c);
   2328 		}
   2329 		return -1;
   2330 	}
   2331 	channel_set_used_time(ssh, c);
   2332 	if (c->isatty && dlen >= 1 && buf[0] != '\r') {
   2333 		if (tcgetattr(c->wfd, &tio) == 0 &&
   2334 		    !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
   2335 			/*
   2336 			 * Simulate echo to reduce the impact of
   2337 			 * traffic analysis. We need to match the
   2338 			 * size of a SSH2_MSG_CHANNEL_DATA message
   2339 			 * (4 byte channel id + buf)
   2340 			 */
   2341 			if ((r = sshpkt_msg_ignore(ssh, 4+len)) != 0 ||
   2342 			    (r = sshpkt_send(ssh)) != 0)
   2343 				fatal_fr(r, "channel %i: ignore", c->self);
   2344 		}
   2345 	}
   2346 	if ((r = sshbuf_consume(c->output, len)) != 0)
   2347 		fatal_fr(r, "channel %i: consume", c->self);
   2348  out:
   2349 	c->local_consumed += olen - sshbuf_len(c->output);
   2350 
   2351 	return 1;
   2352 }
   2353 
   2354 static int
   2355 channel_handle_efd_write(struct ssh *ssh, Channel *c)
   2356 {
   2357 	int r;
   2358 	ssize_t len;
   2359 
   2360 	if ((c->io_ready & SSH_CHAN_IO_EFD_W) == 0)
   2361 		return 1;
   2362 	if (sshbuf_len(c->extended) == 0)
   2363 		return 1;
   2364 
   2365 	len = write(c->efd, sshbuf_ptr(c->extended),
   2366 	    sshbuf_len(c->extended));
   2367 	debug2("channel %d: written %zd to efd %d", c->self, len, c->efd);
   2368 	if (len == -1 && (errno == EINTR || errno == EAGAIN))
   2369 		return 1;
   2370 	if (len <= 0) {
   2371 		debug2("channel %d: closing write-efd %d", c->self, c->efd);
   2372 		channel_close_fd(ssh, c, &c->efd);
   2373 	} else {
   2374 		if ((r = sshbuf_consume(c->extended, len)) != 0)
   2375 			fatal_fr(r, "channel %i: consume", c->self);
   2376 		c->local_consumed += len;
   2377 		channel_set_used_time(ssh, c);
   2378 	}
   2379 	return 1;
   2380 }
   2381 
   2382 static int
   2383 channel_handle_efd_read(struct ssh *ssh, Channel *c)
   2384 {
   2385 	char buf[CHAN_RBUF];
   2386 	int r;
   2387 	ssize_t len;
   2388 
   2389 	if ((c->io_ready & SSH_CHAN_IO_EFD_R) == 0)
   2390 		return 1;
   2391 
   2392 	len = read(c->efd, buf, sizeof(buf));
   2393 	debug2("channel %d: read %zd from efd %d", c->self, len, c->efd);
   2394 	if (len == -1 && (errno == EINTR || errno == EAGAIN))
   2395 		return 1;
   2396 	if (len <= 0) {
   2397 		debug2("channel %d: closing read-efd %d", c->self, c->efd);
   2398 		channel_close_fd(ssh, c, &c->efd);
   2399 		return 1;
   2400 	}
   2401 	channel_set_used_time(ssh, c);
   2402 	if (c->extended_usage == CHAN_EXTENDED_IGNORE)
   2403 		debug3("channel %d: discard efd", c->self);
   2404 	else if ((r = sshbuf_put(c->extended, buf, len)) != 0)
   2405 		fatal_fr(r, "channel %i: append", c->self);
   2406 	return 1;
   2407 }
   2408 
   2409 static int
   2410 channel_handle_efd(struct ssh *ssh, Channel *c)
   2411 {
   2412 	if (c->efd == -1)
   2413 		return 1;
   2414 
   2415 	/** XXX handle drain efd, too */
   2416 
   2417 	if (c->extended_usage == CHAN_EXTENDED_WRITE)
   2418 		return channel_handle_efd_write(ssh, c);
   2419 	else if (c->extended_usage == CHAN_EXTENDED_READ ||
   2420 	    c->extended_usage == CHAN_EXTENDED_IGNORE)
   2421 		return channel_handle_efd_read(ssh, c);
   2422 
   2423 	return 1;
   2424 }
   2425 
   2426 static int
   2427 channel_check_window(struct ssh *ssh, Channel *c)
   2428 {
   2429 	int r;
   2430 
   2431 	if (c->type == SSH_CHANNEL_OPEN &&
   2432 	    !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
   2433 	    ((c->local_window_max - c->local_window >
   2434 	    c->local_maxpacket*3) ||
   2435 	    c->local_window < c->local_window_max/2) &&
   2436 	    c->local_consumed > 0) {
   2437 		u_int addition = 0;
   2438 		u_int32_t tcpwinsz = channel_tcpwinsz(ssh);
   2439 		/* adjust max window size if we are in a dynamic environment */
   2440 		if (c->dynamic_window && (tcpwinsz > c->local_window_max)) {
   2441 			/* grow the window somewhat aggressively to maintain
   2442 			 * pressure */
   2443 			addition = 1.5*(tcpwinsz - c->local_window_max);
   2444 			c->local_window_max += addition;
   2445 			debug("Channel: Window growth to %d by %d bytes", c->local_window_max, addition);
   2446 		}
   2447 		if (!c->have_remote_id)
   2448 			fatal_f("channel %d: no remote id", c->self);
   2449 		if ((r = sshpkt_start(ssh,
   2450 		    SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
   2451 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
   2452 		    (r = sshpkt_put_u32(ssh, c->local_consumed + addition)) != 0 ||
   2453 		    (r = sshpkt_send(ssh)) != 0) {
   2454 			fatal_fr(r, "channel %i", c->self);
   2455 		}
   2456 		debug2("channel %d: window %d sent adjust %d", c->self,
   2457 		    c->local_window,
   2458 		    c->local_consumed + addition);
   2459 		c->local_window += c->local_consumed + addition;
   2460 		c->local_consumed = 0;
   2461 	}
   2462 	return 1;
   2463 }
   2464 
   2465 static void
   2466 channel_post_open(struct ssh *ssh, Channel *c)
   2467 {
   2468 	channel_handle_rfd(ssh, c);
   2469 	channel_handle_wfd(ssh, c);
   2470 	channel_handle_efd(ssh, c);
   2471 	channel_check_window(ssh, c);
   2472 }
   2473 
   2474 static u_int
   2475 read_mux(struct ssh *ssh, Channel *c, u_int need)
   2476 {
   2477 	char buf[CHAN_RBUF];
   2478 	ssize_t len;
   2479 	u_int rlen;
   2480 	int r;
   2481 
   2482 	if (sshbuf_len(c->input) < need) {
   2483 		rlen = need - sshbuf_len(c->input);
   2484 		len = read(c->rfd, buf, MINIMUM(rlen, CHAN_RBUF));
   2485 		if (len == -1 && (errno == EINTR || errno == EAGAIN))
   2486 			return sshbuf_len(c->input);
   2487 		if (len <= 0) {
   2488 			debug2("channel %d: ctl read<=0 rfd %d len %zd",
   2489 			    c->self, c->rfd, len);
   2490 			chan_read_failed(ssh, c);
   2491 			return 0;
   2492 		} else if ((r = sshbuf_put(c->input, buf, len)) != 0)
   2493 			fatal_fr(r, "channel %i: append", c->self);
   2494 	}
   2495 	return sshbuf_len(c->input);
   2496 }
   2497 
   2498 static void
   2499 channel_post_mux_client_read(struct ssh *ssh, Channel *c)
   2500 {
   2501 	u_int need;
   2502 
   2503 	if ((c->io_ready & SSH_CHAN_IO_RFD) == 0)
   2504 		return;
   2505 	if (c->istate != CHAN_INPUT_OPEN && c->istate != CHAN_INPUT_WAIT_DRAIN)
   2506 		return;
   2507 	if (c->mux_pause)
   2508 		return;
   2509 
   2510 	/*
   2511 	 * Don't not read past the precise end of packets to
   2512 	 * avoid disrupting fd passing.
   2513 	 */
   2514 	if (read_mux(ssh, c, 4) < 4) /* read header */
   2515 		return;
   2516 	/* XXX sshbuf_peek_u32 */
   2517 	need = PEEK_U32(sshbuf_ptr(c->input));
   2518 #define CHANNEL_MUX_MAX_PACKET	(256 * 1024)
   2519 	if (need > CHANNEL_MUX_MAX_PACKET) {
   2520 		debug2("channel %d: packet too big %u > %u",
   2521 		    c->self, CHANNEL_MUX_MAX_PACKET, need);
   2522 		chan_rcvd_oclose(ssh, c);
   2523 		return;
   2524 	}
   2525 	if (read_mux(ssh, c, need + 4) < need + 4) /* read body */
   2526 		return;
   2527 	if (c->mux_rcb(ssh, c) != 0) {
   2528 		debug("channel %d: mux_rcb failed", c->self);
   2529 		chan_mark_dead(ssh, c);
   2530 		return;
   2531 	}
   2532 }
   2533 
   2534 static void
   2535 channel_post_mux_client_write(struct ssh *ssh, Channel *c)
   2536 {
   2537 	ssize_t len;
   2538 	int r;
   2539 
   2540 	if ((c->io_ready & SSH_CHAN_IO_WFD) == 0)
   2541 		return;
   2542 	if (sshbuf_len(c->output) == 0)
   2543 		return;
   2544 
   2545 	len = write(c->wfd, sshbuf_ptr(c->output), sshbuf_len(c->output));
   2546 	if (len == -1 && (errno == EINTR || errno == EAGAIN))
   2547 		return;
   2548 	if (len <= 0) {
   2549 		chan_mark_dead(ssh, c);
   2550 		return;
   2551 	}
   2552 	if ((r = sshbuf_consume(c->output, len)) != 0)
   2553 		fatal_fr(r, "channel %i: consume", c->self);
   2554 }
   2555 
   2556 static void
   2557 channel_post_mux_client(struct ssh *ssh, Channel *c)
   2558 {
   2559 	channel_post_mux_client_read(ssh, c);
   2560 	channel_post_mux_client_write(ssh, c);
   2561 }
   2562 
   2563 static void
   2564 channel_post_mux_listener(struct ssh *ssh, Channel *c)
   2565 {
   2566 	Channel *nc;
   2567 	struct sockaddr_storage addr;
   2568 	socklen_t addrlen;
   2569 	int newsock;
   2570 	uid_t euid;
   2571 	gid_t egid;
   2572 
   2573 	if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
   2574 		return;
   2575 
   2576 	debug("multiplexing control connection");
   2577 
   2578 	/*
   2579 	 * Accept connection on control socket
   2580 	 */
   2581 	memset(&addr, 0, sizeof(addr));
   2582 	addrlen = sizeof(addr);
   2583 	if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
   2584 	    &addrlen)) == -1) {
   2585 		error_f("accept: %s", strerror(errno));
   2586 		if (errno == EMFILE || errno == ENFILE)
   2587 			c->notbefore = monotime() + 1;
   2588 		return;
   2589 	}
   2590 
   2591 	if (getpeereid(newsock, &euid, &egid) == -1) {
   2592 		error_f("getpeereid failed: %s", strerror(errno));
   2593 		close(newsock);
   2594 		return;
   2595 	}
   2596 	if ((euid != 0) && (getuid() != euid)) {
   2597 		error("multiplex uid mismatch: peer euid %u != uid %u",
   2598 		    (u_int)euid, (u_int)getuid());
   2599 		close(newsock);
   2600 		return;
   2601 	}
   2602 	nc = channel_new(ssh, "mux-control", SSH_CHANNEL_MUX_CLIENT,
   2603 	    newsock, newsock, -1, c->local_window_max,
   2604 	    c->local_maxpacket, 0, "mux-control", 1);
   2605 	nc->mux_rcb = c->mux_rcb;
   2606 	debug3_f("new mux channel %d fd %d", nc->self, nc->sock);
   2607 	/* establish state */
   2608 	nc->mux_rcb(ssh, nc);
   2609 	/* mux state transitions must not elicit protocol messages */
   2610 	nc->flags |= CHAN_LOCAL;
   2611 }
   2612 
   2613 static void
   2614 channel_handler_init(struct ssh_channels *sc)
   2615 {
   2616 	chan_fn **pre, **post;
   2617 
   2618 	if ((pre = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*pre))) == NULL ||
   2619 	    (post = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*post))) == NULL)
   2620 		fatal_f("allocation failed");
   2621 
   2622 	pre[SSH_CHANNEL_OPEN] =			&channel_pre_open;
   2623 	pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open;
   2624 	pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
   2625 	pre[SSH_CHANNEL_RPORT_LISTENER] =	&channel_pre_listener;
   2626 	pre[SSH_CHANNEL_UNIX_LISTENER] =	&channel_pre_listener;
   2627 	pre[SSH_CHANNEL_RUNIX_LISTENER] =	&channel_pre_listener;
   2628 	pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
   2629 	pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
   2630 	pre[SSH_CHANNEL_CONNECTING] =		&channel_pre_connecting;
   2631 	pre[SSH_CHANNEL_DYNAMIC] =		&channel_pre_dynamic;
   2632 	pre[SSH_CHANNEL_RDYNAMIC_FINISH] =	&channel_pre_connecting;
   2633 	pre[SSH_CHANNEL_MUX_LISTENER] =		&channel_pre_listener;
   2634 	pre[SSH_CHANNEL_MUX_CLIENT] =		&channel_pre_mux_client;
   2635 
   2636 	post[SSH_CHANNEL_OPEN] =		&channel_post_open;
   2637 	post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
   2638 	post[SSH_CHANNEL_RPORT_LISTENER] =	&channel_post_port_listener;
   2639 	post[SSH_CHANNEL_UNIX_LISTENER] =	&channel_post_port_listener;
   2640 	post[SSH_CHANNEL_RUNIX_LISTENER] =	&channel_post_port_listener;
   2641 	post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
   2642 	post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
   2643 	post[SSH_CHANNEL_CONNECTING] =		&channel_post_connecting;
   2644 	post[SSH_CHANNEL_DYNAMIC] =		&channel_post_open;
   2645 	post[SSH_CHANNEL_RDYNAMIC_FINISH] =	&channel_post_connecting;
   2646 	post[SSH_CHANNEL_MUX_LISTENER] =	&channel_post_mux_listener;
   2647 	post[SSH_CHANNEL_MUX_CLIENT] =		&channel_post_mux_client;
   2648 
   2649 	sc->channel_pre = pre;
   2650 	sc->channel_post = post;
   2651 }
   2652 
   2653 /* gc dead channels */
   2654 static void
   2655 channel_garbage_collect(struct ssh *ssh, Channel *c)
   2656 {
   2657 	if (c == NULL)
   2658 		return;
   2659 	if (c->detach_user != NULL) {
   2660 		if (!chan_is_dead(ssh, c, c->detach_close))
   2661 			return;
   2662 
   2663 		debug2("channel %d: gc: notify user", c->self);
   2664 		c->detach_user(ssh, c->self, 0, NULL);
   2665 		/* if we still have a callback */
   2666 		if (c->detach_user != NULL)
   2667 			return;
   2668 		debug2("channel %d: gc: user detached", c->self);
   2669 	}
   2670 	if (!chan_is_dead(ssh, c, 1))
   2671 		return;
   2672 	debug2("channel %d: garbage collecting", c->self);
   2673 	channel_free(ssh, c);
   2674 }
   2675 
   2676 enum channel_table { CHAN_PRE, CHAN_POST };
   2677 
   2678 static void
   2679 channel_handler(struct ssh *ssh, int table, struct timespec *timeout)
   2680 {
   2681 	struct ssh_channels *sc = ssh->chanctxt;
   2682 	chan_fn **ftab = table == CHAN_PRE ? sc->channel_pre : sc->channel_post;
   2683 	u_int i, oalloc;
   2684 	Channel *c;
   2685 	time_t now;
   2686 
   2687 	now = monotime();
   2688 	for (sc->nbulk = i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
   2689 		c = sc->channels[i];
   2690 		if (c == NULL)
   2691 			continue;
   2692 		/* Count open channels in bulk state */
   2693 		if (c->type == SSH_CHANNEL_OPEN && c->bulk)
   2694 			sc->nbulk++;
   2695 		/* Try to keep IO going while rekeying */
   2696 		if (ssh_packet_is_rekeying(ssh) && c->type != SSH_CHANNEL_OPEN)
   2697 			continue;
   2698 		if (c->delayed) {
   2699 			if (table == CHAN_PRE)
   2700 				c->delayed = 0;
   2701 			else
   2702 				continue;
   2703 		}
   2704 		if (ftab[c->type] != NULL) {
   2705 			if (table == CHAN_PRE && c->type == SSH_CHANNEL_OPEN &&
   2706 			    channel_get_expiry(ssh, c) != 0 &&
   2707 			    now >= channel_get_expiry(ssh, c)) {
   2708 				/* channel closed for inactivity */
   2709 				verbose("channel %d: closing after %u seconds "
   2710 				    "of inactivity", c->self,
   2711 				    c->inactive_deadline);
   2712 				channel_force_close(ssh, c, 1);
   2713 			} else if (c->notbefore <= now) {
   2714 				/* Run handlers that are not paused. */
   2715 				(*ftab[c->type])(ssh, c);
   2716 				/* inactivity timeouts must interrupt poll() */
   2717 				if (timeout != NULL &&
   2718 				    c->type == SSH_CHANNEL_OPEN &&
   2719 				    channel_get_expiry(ssh, c) != 0) {
   2720 					ptimeout_deadline_monotime(timeout,
   2721 					    channel_get_expiry(ssh, c));
   2722 				}
   2723 			} else if (timeout != NULL) {
   2724 				/*
   2725 				 * Arrange for poll() wakeup when channel pause
   2726 				 * timer expires.
   2727 				 */
   2728 				ptimeout_deadline_monotime(timeout,
   2729 				    c->notbefore);
   2730 			}
   2731 		}
   2732 		channel_garbage_collect(ssh, c);
   2733 	}
   2734 }
   2735 
   2736 /*
   2737  * Create sockets before preparing IO.
   2738  * This is necessary for things that need to happen after reading
   2739  * the network-input but need to be completed before IO event setup, e.g.
   2740  * because they may create new channels.
   2741  */
   2742 static void
   2743 channel_before_prepare_io(struct ssh *ssh)
   2744 {
   2745 	struct ssh_channels *sc = ssh->chanctxt;
   2746 	Channel *c;
   2747 	u_int i, oalloc;
   2748 
   2749 	for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
   2750 		c = sc->channels[i];
   2751 		if (c == NULL)
   2752 			continue;
   2753 		if (c->type == SSH_CHANNEL_RDYNAMIC_OPEN)
   2754 			channel_before_prepare_io_rdynamic(ssh, c);
   2755 	}
   2756 }
   2757 
   2758 static void
   2759 dump_channel_poll(const char *func, const char *what, Channel *c,
   2760     u_int pollfd_offset, struct pollfd *pfd)
   2761 {
   2762 #ifdef DEBUG_CHANNEL_POLL
   2763 	debug3("%s: channel %d: %s r%d w%d e%d s%d c->pfds [ %d %d %d %d ] "
   2764 	    "io_want 0x%02x io_ready 0x%02x pfd[%u].fd=%d "
   2765 	    "pfd.ev 0x%02x pfd.rev 0x%02x", func, c->self, what,
   2766 	    c->rfd, c->wfd, c->efd, c->sock,
   2767 	    c->pfds[0], c->pfds[1], c->pfds[2], c->pfds[3],
   2768 	    c->io_want, c->io_ready,
   2769 	    pollfd_offset, pfd->fd, pfd->events, pfd->revents);
   2770 #endif
   2771 }
   2772 
   2773 /* Prepare pollfd entries for a single channel */
   2774 static void
   2775 channel_prepare_pollfd(Channel *c, u_int *next_pollfd,
   2776     struct pollfd *pfd, u_int npfd)
   2777 {
   2778 	u_int ev, p = *next_pollfd;
   2779 
   2780 	if (c == NULL)
   2781 		return;
   2782 	if (p + 4 > npfd) {
   2783 		/* Shouldn't happen */
   2784 		fatal_f("channel %d: bad pfd offset %u (max %u)",
   2785 		    c->self, p, npfd);
   2786 	}
   2787 	c->pfds[0] = c->pfds[1] = c->pfds[2] = c->pfds[3] = -1;
   2788 	/*
   2789 	 * prepare c->rfd
   2790 	 *
   2791 	 * This is a special case, since c->rfd might be the same as
   2792 	 * c->wfd, c->efd and/or c->sock. Handle those here if they want
   2793 	 * IO too.
   2794 	 */
   2795 	if (c->rfd != -1) {
   2796 		ev = 0;
   2797 		if ((c->io_want & SSH_CHAN_IO_RFD) != 0)
   2798 			ev |= POLLIN;
   2799 		/* rfd == wfd */
   2800 		if (c->wfd == c->rfd) {
   2801 			if ((c->io_want & SSH_CHAN_IO_WFD) != 0)
   2802 				ev |= POLLOUT;
   2803 		}
   2804 		/* rfd == efd */
   2805 		if (c->efd == c->rfd) {
   2806 			if ((c->io_want & SSH_CHAN_IO_EFD_R) != 0)
   2807 				ev |= POLLIN;
   2808 			if ((c->io_want & SSH_CHAN_IO_EFD_W) != 0)
   2809 				ev |= POLLOUT;
   2810 		}
   2811 		/* rfd == sock */
   2812 		if (c->sock == c->rfd) {
   2813 			if ((c->io_want & SSH_CHAN_IO_SOCK_R) != 0)
   2814 				ev |= POLLIN;
   2815 			if ((c->io_want & SSH_CHAN_IO_SOCK_W) != 0)
   2816 				ev |= POLLOUT;
   2817 		}
   2818 		/* Pack a pfd entry if any event armed for this fd */
   2819 		if (ev != 0) {
   2820 			c->pfds[0] = p;
   2821 			pfd[p].fd = c->rfd;
   2822 			pfd[p].events = ev;
   2823 			dump_channel_poll(__func__, "rfd", c, p, &pfd[p]);
   2824 			p++;
   2825 		}
   2826 	}
   2827 	/* prepare c->wfd if wanting IO and not already handled above */
   2828 	if (c->wfd != -1 && c->rfd != c->wfd) {
   2829 		ev = 0;
   2830 		if ((c->io_want & SSH_CHAN_IO_WFD))
   2831 			ev |= POLLOUT;
   2832 		/* Pack a pfd entry if any event armed for this fd */
   2833 		if (ev != 0) {
   2834 			c->pfds[1] = p;
   2835 			pfd[p].fd = c->wfd;
   2836 			pfd[p].events = ev;
   2837 			dump_channel_poll(__func__, "wfd", c, p, &pfd[p]);
   2838 			p++;
   2839 		}
   2840 	}
   2841 	/* prepare c->efd if wanting IO and not already handled above */
   2842 	if (c->efd != -1 && c->rfd != c->efd) {
   2843 		ev = 0;
   2844 		if ((c->io_want & SSH_CHAN_IO_EFD_R) != 0)
   2845 			ev |= POLLIN;
   2846 		if ((c->io_want & SSH_CHAN_IO_EFD_W) != 0)
   2847 			ev |= POLLOUT;
   2848 		/* Pack a pfd entry if any event armed for this fd */
   2849 		if (ev != 0) {
   2850 			c->pfds[2] = p;
   2851 			pfd[p].fd = c->efd;
   2852 			pfd[p].events = ev;
   2853 			dump_channel_poll(__func__, "efd", c, p, &pfd[p]);
   2854 			p++;
   2855 		}
   2856 	}
   2857 	/* prepare c->sock if wanting IO and not already handled above */
   2858 	if (c->sock != -1 && c->rfd != c->sock) {
   2859 		ev = 0;
   2860 		if ((c->io_want & SSH_CHAN_IO_SOCK_R) != 0)
   2861 			ev |= POLLIN;
   2862 		if ((c->io_want & SSH_CHAN_IO_SOCK_W) != 0)
   2863 			ev |= POLLOUT;
   2864 		/* Pack a pfd entry if any event armed for this fd */
   2865 		if (ev != 0) {
   2866 			c->pfds[3] = p;
   2867 			pfd[p].fd = c->sock;
   2868 			pfd[p].events = 0;
   2869 			dump_channel_poll(__func__, "sock", c, p, &pfd[p]);
   2870 			p++;
   2871 		}
   2872 	}
   2873 	*next_pollfd = p;
   2874 }
   2875 
   2876 /* * Allocate/prepare poll structure */
   2877 void
   2878 channel_prepare_poll(struct ssh *ssh, struct pollfd **pfdp, u_int *npfd_allocp,
   2879     u_int *npfd_activep, u_int npfd_reserved, struct timespec *timeout)
   2880 {
   2881 	struct ssh_channels *sc = ssh->chanctxt;
   2882 	u_int i, oalloc, p, npfd = npfd_reserved;
   2883 
   2884 	channel_before_prepare_io(ssh); /* might create a new channel */
   2885 	/* clear out I/O flags from last poll */
   2886 	for (i = 0; i < sc->channels_alloc; i++) {
   2887 		if (sc->channels[i] == NULL)
   2888 			continue;
   2889 		sc->channels[i]->io_want = sc->channels[i]->io_ready = 0;
   2890 	}
   2891 	/* Allocate 4x pollfd for each channel (rfd, wfd, efd, sock) */
   2892 	if (sc->channels_alloc >= (INT_MAX / 4) - npfd_reserved)
   2893 		fatal_f("too many channels"); /* shouldn't happen */
   2894 	npfd += sc->channels_alloc * 4;
   2895 	if (npfd > *npfd_allocp) {
   2896 		*pfdp = xrecallocarray(*pfdp, *npfd_allocp,
   2897 		    npfd, sizeof(**pfdp));
   2898 		*npfd_allocp = npfd;
   2899 	}
   2900 	*npfd_activep = npfd_reserved;
   2901 	oalloc = sc->channels_alloc;
   2902 
   2903 	channel_handler(ssh, CHAN_PRE, timeout);
   2904 
   2905 	if (oalloc != sc->channels_alloc) {
   2906 		/* shouldn't happen */
   2907 		fatal_f("channels_alloc changed during CHAN_PRE "
   2908 		    "(was %u, now %u)", oalloc, sc->channels_alloc);
   2909 	}
   2910 
   2911 	/* Prepare pollfd */
   2912 	p = npfd_reserved;
   2913 	for (i = 0; i < sc->channels_alloc; i++)
   2914 		channel_prepare_pollfd(sc->channels[i], &p, *pfdp, npfd);
   2915 	*npfd_activep = p;
   2916 }
   2917 
   2918 static void
   2919 fd_ready(Channel *c, int p, struct pollfd *pfds, u_int npfd, int fd,
   2920     const char *what, u_int revents_mask, u_int ready)
   2921 {
   2922 	struct pollfd *pfd = &pfds[p];
   2923 
   2924 	if (fd == -1)
   2925 		return;
   2926 	if (p == -1 || (u_int)p >= npfd)
   2927 		fatal_f("channel %d: bad pfd %d (max %u)", c->self, p, npfd);
   2928 	dump_channel_poll(__func__, what, c, p, pfd);
   2929 	if (pfd->fd != fd) {
   2930 		fatal("channel %d: inconsistent %s fd=%d pollfd[%u].fd %d "
   2931 		    "r%d w%d e%d s%d", c->self, what, fd, p, pfd->fd,
   2932 		    c->rfd, c->wfd, c->efd, c->sock);
   2933 	}
   2934 	if ((pfd->revents & POLLNVAL) != 0) {
   2935 		fatal("channel %d: invalid %s pollfd[%u].fd %d r%d w%d e%d s%d",
   2936 		    c->self, what, p, pfd->fd, c->rfd, c->wfd, c->efd, c->sock);
   2937 	}
   2938 	if ((pfd->revents & (revents_mask|POLLHUP|POLLERR)) != 0)
   2939 		c->io_ready |= ready & c->io_want;
   2940 }
   2941 
   2942 /*
   2943  * After poll, perform any appropriate operations for channels which have
   2944  * events pending.
   2945  */
   2946 void
   2947 channel_after_poll(struct ssh *ssh, struct pollfd *pfd, u_int npfd)
   2948 {
   2949 	struct ssh_channels *sc = ssh->chanctxt;
   2950 	u_int i;
   2951 	int p;
   2952 	Channel *c;
   2953 
   2954 #ifdef DEBUG_CHANNEL_POLL
   2955 	for (p = 0; p < (int)npfd; p++) {
   2956 		if (pfd[p].revents == 0)
   2957 			continue;
   2958 		debug_f("pfd[%u].fd %d rev 0x%04x",
   2959 		    p, pfd[p].fd, pfd[p].revents);
   2960 	}
   2961 #endif
   2962 
   2963 	/* Convert pollfd into c->io_ready */
   2964 	for (i = 0; i < sc->channels_alloc; i++) {
   2965 		c = sc->channels[i];
   2966 		if (c == NULL)
   2967 			continue;
   2968 		/* if rfd is shared with efd/sock then wfd should be too */
   2969 		if (c->rfd != -1 && c->wfd != -1 && c->rfd != c->wfd &&
   2970 		    (c->rfd == c->efd || c->rfd == c->sock)) {
   2971 			/* Shouldn't happen */
   2972 			fatal_f("channel %d: unexpected fds r%d w%d e%d s%d",
   2973 			    c->self, c->rfd, c->wfd, c->efd, c->sock);
   2974 		}
   2975 		c->io_ready = 0;
   2976 		/* rfd, potentially shared with wfd, efd and sock */
   2977 		if (c->rfd != -1 && (p = c->pfds[0]) != -1) {
   2978 			fd_ready(c, p, pfd, npfd, c->rfd,
   2979 			    "rfd", POLLIN, SSH_CHAN_IO_RFD);
   2980 			if (c->rfd == c->wfd) {
   2981 				fd_ready(c, p, pfd, npfd, c->wfd,
   2982 				    "wfd/r", POLLOUT, SSH_CHAN_IO_WFD);
   2983 			}
   2984 			if (c->rfd == c->efd) {
   2985 				fd_ready(c, p, pfd, npfd, c->efd,
   2986 				    "efdr/r", POLLIN, SSH_CHAN_IO_EFD_R);
   2987 				fd_ready(c, p, pfd, npfd, c->efd,
   2988 				    "efdw/r", POLLOUT, SSH_CHAN_IO_EFD_W);
   2989 			}
   2990 			if (c->rfd == c->sock) {
   2991 				fd_ready(c, p, pfd, npfd, c->sock,
   2992 				    "sockr/r", POLLIN, SSH_CHAN_IO_SOCK_R);
   2993 				fd_ready(c, p, pfd, npfd, c->sock,
   2994 				    "sockw/r", POLLOUT, SSH_CHAN_IO_SOCK_W);
   2995 			}
   2996 			dump_channel_poll(__func__, "rfd", c, p, pfd);
   2997 		}
   2998 		/* wfd */
   2999 		if (c->wfd != -1 && c->wfd != c->rfd &&
   3000 		    (p = c->pfds[1]) != -1) {
   3001 			fd_ready(c, p, pfd, npfd, c->wfd,
   3002 			    "wfd", POLLOUT, SSH_CHAN_IO_WFD);
   3003 			dump_channel_poll(__func__, "wfd", c, p, pfd);
   3004 		}
   3005 		/* efd */
   3006 		if (c->efd != -1 && c->efd != c->rfd &&
   3007 		    (p = c->pfds[2]) != -1) {
   3008 			fd_ready(c, p, pfd, npfd, c->efd,
   3009 			    "efdr", POLLIN, SSH_CHAN_IO_EFD_R);
   3010 			fd_ready(c, p, pfd, npfd, c->efd,
   3011 			    "efdw", POLLOUT, SSH_CHAN_IO_EFD_W);
   3012 			dump_channel_poll(__func__, "efd", c, p, pfd);
   3013 		}
   3014 		/* sock */
   3015 		if (c->sock != -1 && c->sock != c->rfd &&
   3016 		    (p = c->pfds[3]) != -1) {
   3017 			fd_ready(c, p, pfd, npfd, c->sock,
   3018 			    "sockr", POLLIN, SSH_CHAN_IO_SOCK_R);
   3019 			fd_ready(c, p, pfd, npfd, c->sock,
   3020 			    "sockw", POLLOUT, SSH_CHAN_IO_SOCK_W);
   3021 			dump_channel_poll(__func__, "sock", c, p, pfd);
   3022 		}
   3023 	}
   3024 	channel_handler(ssh, CHAN_POST, NULL);
   3025 }
   3026 
   3027 /*
   3028  * Enqueue data for channels with open or draining c->input.
   3029  * Returns non-zero if a packet was enqueued.
   3030  */
   3031 static int
   3032 channel_output_poll_input_open(struct ssh *ssh, Channel *c)
   3033 {
   3034 	size_t len, plen;
   3035 	const u_char *pkt;
   3036 	int r;
   3037 
   3038 	if ((len = sshbuf_len(c->input)) == 0) {
   3039 		if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
   3040 			/*
   3041 			 * input-buffer is empty and read-socket shutdown:
   3042 			 * tell peer, that we will not send more data:
   3043 			 * send IEOF.
   3044 			 * hack for extended data: delay EOF if EFD still
   3045 			 * in use.
   3046 			 */
   3047 			if (CHANNEL_EFD_INPUT_ACTIVE(c))
   3048 				debug2("channel %d: "
   3049 				    "ibuf_empty delayed efd %d/(%zu)",
   3050 				    c->self, c->efd, sshbuf_len(c->extended));
   3051 			else
   3052 				chan_ibuf_empty(ssh, c);
   3053 		}
   3054 		return 0;
   3055 	}
   3056 
   3057 	if (!c->have_remote_id)
   3058 		fatal_f("channel %d: no remote id", c->self);
   3059 
   3060 	if (c->datagram) {
   3061 		/* Check datagram will fit; drop if not */
   3062 		if ((r = sshbuf_get_string_direct(c->input, &pkt, &plen)) != 0)
   3063 			fatal_fr(r, "channel %i: get datagram", c->self);
   3064 		/*
   3065 		 * XXX this does tail-drop on the datagram queue which is
   3066 		 * usually suboptimal compared to head-drop. Better to have
   3067 		 * backpressure at read time? (i.e. read + discard)
   3068 		 */
   3069 		if (plen > c->remote_window || plen > c->remote_maxpacket) {
   3070 			debug("channel %d: datagram too big", c->self);
   3071 			return 0;
   3072 		}
   3073 		/* Enqueue it */
   3074 		if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
   3075 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
   3076 		    (r = sshpkt_put_string(ssh, pkt, plen)) != 0 ||
   3077 		    (r = sshpkt_send(ssh)) != 0)
   3078 			fatal_fr(r, "channel %i: send datagram", c->self);
   3079 		c->remote_window -= plen;
   3080 		return 1;
   3081 	}
   3082 
   3083 	/* Enqueue packet for buffered data. */
   3084 	if (len > c->remote_window)
   3085 		len = c->remote_window;
   3086 	if (len > c->remote_maxpacket)
   3087 		len = c->remote_maxpacket;
   3088 	if (len == 0)
   3089 		return 0;
   3090 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
   3091 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
   3092 	    (r = sshpkt_put_string(ssh, sshbuf_ptr(c->input), len)) != 0 ||
   3093 	    (r = sshpkt_send(ssh)) != 0)
   3094 		fatal_fr(r, "channel %i: send data", c->self);
   3095 	if ((r = sshbuf_consume(c->input, len)) != 0)
   3096 		fatal_fr(r, "channel %i: consume", c->self);
   3097 	c->remote_window -= len;
   3098 	return 1;
   3099 }
   3100 
   3101 /*
   3102  * Enqueue data for channels with open c->extended in read mode.
   3103  * Returns non-zero if a packet was enqueued.
   3104  */
   3105 static int
   3106 channel_output_poll_extended_read(struct ssh *ssh, Channel *c)
   3107 {
   3108 	size_t len;
   3109 	int r;
   3110 
   3111 	if ((len = sshbuf_len(c->extended)) == 0)
   3112 		return 0;
   3113 
   3114 	debug2("channel %d: rwin %u elen %zu euse %d", c->self,
   3115 	    c->remote_window, sshbuf_len(c->extended), c->extended_usage);
   3116 	if (len > c->remote_window)
   3117 		len = c->remote_window;
   3118 	if (len > c->remote_maxpacket)
   3119 		len = c->remote_maxpacket;
   3120 	if (len == 0)
   3121 		return 0;
   3122 	if (!c->have_remote_id)
   3123 		fatal_f("channel %d: no remote id", c->self);
   3124 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA)) != 0 ||
   3125 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
   3126 	    (r = sshpkt_put_u32(ssh, SSH2_EXTENDED_DATA_STDERR)) != 0 ||
   3127 	    (r = sshpkt_put_string(ssh, sshbuf_ptr(c->extended), len)) != 0 ||
   3128 	    (r = sshpkt_send(ssh)) != 0)
   3129 		fatal_fr(r, "channel %i: data", c->self);
   3130 	if ((r = sshbuf_consume(c->extended, len)) != 0)
   3131 		fatal_fr(r, "channel %i: consume", c->self);
   3132 	c->remote_window -= len;
   3133 	debug2("channel %d: sent ext data %zu", c->self, len);
   3134 	return 1;
   3135 }
   3136 
   3137 /*
   3138  * If there is data to send to the connection, enqueue some of it now.
   3139  * Returns non-zero if data was enqueued.
   3140  */
   3141 int
   3142 channel_output_poll(struct ssh *ssh)
   3143 {
   3144 	struct ssh_channels *sc = ssh->chanctxt;
   3145 	Channel *c;
   3146 	u_int i;
   3147 	int ret = 0;
   3148 
   3149 	for (i = 0; i < sc->channels_alloc; i++) {
   3150 		c = sc->channels[i];
   3151 		if (c == NULL)
   3152 			continue;
   3153 
   3154 		/*
   3155 		 * We are only interested in channels that can have buffered
   3156 		 * incoming data.
   3157 		 */
   3158 		if (c->type != SSH_CHANNEL_OPEN)
   3159 			continue;
   3160 		if ((c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
   3161 			/* XXX is this true? */
   3162 			debug3("channel %d: will not send data after close",
   3163 			    c->self);
   3164 			continue;
   3165 		}
   3166 
   3167 		/* Get the amount of buffered data for this channel. */
   3168 		if (c->istate == CHAN_INPUT_OPEN ||
   3169 		    c->istate == CHAN_INPUT_WAIT_DRAIN)
   3170 			ret |= channel_output_poll_input_open(ssh, c);
   3171 		/* Send extended data, i.e. stderr */
   3172 		if (!(c->flags & CHAN_EOF_SENT) &&
   3173 		    c->extended_usage == CHAN_EXTENDED_READ)
   3174 			ret |= channel_output_poll_extended_read(ssh, c);
   3175 	}
   3176 	return ret;
   3177 }
   3178 
   3179 /* -- mux proxy support  */
   3180 
   3181 /*
   3182  * When multiplexing channel messages for mux clients we have to deal
   3183  * with downstream messages from the mux client and upstream messages
   3184  * from the ssh server:
   3185  * 1) Handling downstream messages is straightforward and happens
   3186  *    in channel_proxy_downstream():
   3187  *    - We forward all messages (mostly) unmodified to the server.
   3188  *    - However, in order to route messages from upstream to the correct
   3189  *      downstream client, we have to replace the channel IDs used by the
   3190  *      mux clients with a unique channel ID because the mux clients might
   3191  *      use conflicting channel IDs.
   3192  *    - so we inspect and change both SSH2_MSG_CHANNEL_OPEN and
   3193  *      SSH2_MSG_CHANNEL_OPEN_CONFIRMATION messages, create a local
   3194  *      SSH_CHANNEL_MUX_PROXY channel and replace the mux clients ID
   3195  *      with the newly allocated channel ID.
   3196  * 2) Upstream messages are received by matching SSH_CHANNEL_MUX_PROXY
   3197  *    channels and processed by channel_proxy_upstream(). The local channel ID
   3198  *    is then translated back to the original mux client ID.
   3199  * 3) In both cases we need to keep track of matching SSH2_MSG_CHANNEL_CLOSE
   3200  *    messages so we can clean up SSH_CHANNEL_MUX_PROXY channels.
   3201  * 4) The SSH_CHANNEL_MUX_PROXY channels also need to closed when the
   3202  *    downstream mux client are removed.
   3203  * 5) Handling SSH2_MSG_CHANNEL_OPEN messages from the upstream server
   3204  *    requires more work, because they are not addressed to a specific
   3205  *    channel. E.g. client_request_forwarded_tcpip() needs to figure
   3206  *    out whether the request is addressed to the local client or a
   3207  *    specific downstream client based on the listen-address/port.
   3208  * 6) Agent and X11-Forwarding have a similar problem and are currently
   3209  *    not supported as the matching session/channel cannot be identified
   3210  *    easily.
   3211  */
   3212 
   3213 /*
   3214  * receive packets from downstream mux clients:
   3215  * channel callback fired on read from mux client, creates
   3216  * SSH_CHANNEL_MUX_PROXY channels and translates channel IDs
   3217  * on channel creation.
   3218  */
   3219 int
   3220 channel_proxy_downstream(struct ssh *ssh, Channel *downstream)
   3221 {
   3222 	Channel *c = NULL;
   3223 	struct sshbuf *original = NULL, *modified = NULL;
   3224 	const u_char *cp;
   3225 	char *ctype = NULL, *listen_host = NULL;
   3226 	u_char type;
   3227 	size_t have;
   3228 	int ret = -1, r;
   3229 	u_int id, remote_id, listen_port;
   3230 
   3231 	/* sshbuf_dump(downstream->input, stderr); */
   3232 	if ((r = sshbuf_get_string_direct(downstream->input, &cp, &have))
   3233 	    != 0) {
   3234 		error_fr(r, "parse");
   3235 		return -1;
   3236 	}
   3237 	if (have < 2) {
   3238 		error_f("short message");
   3239 		return -1;
   3240 	}
   3241 	type = cp[1];
   3242 	/* skip padlen + type */
   3243 	cp += 2;
   3244 	have -= 2;
   3245 	if (ssh_packet_log_type(type))
   3246 		debug3_f("channel %u: down->up: type %u",
   3247 		    downstream->self, type);
   3248 
   3249 	switch (type) {
   3250 	case SSH2_MSG_CHANNEL_OPEN:
   3251 		if ((original = sshbuf_from(cp, have)) == NULL ||
   3252 		    (modified = sshbuf_new()) == NULL) {
   3253 			error_f("alloc");
   3254 			goto out;
   3255 		}
   3256 		if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0 ||
   3257 		    (r = sshbuf_get_u32(original, &id)) != 0) {
   3258 			error_fr(r, "parse");
   3259 			goto out;
   3260 		}
   3261 		c = channel_new(ssh, "mux-proxy", SSH_CHANNEL_MUX_PROXY,
   3262 		    -1, -1, -1, 0, 0, 0, ctype, 1);
   3263 		c->mux_ctx = downstream;	/* point to mux client */
   3264 		c->mux_downstream_id = id;	/* original downstream id */
   3265 		if ((r = sshbuf_put_cstring(modified, ctype)) != 0 ||
   3266 		    (r = sshbuf_put_u32(modified, c->self)) != 0 ||
   3267 		    (r = sshbuf_putb(modified, original)) != 0) {
   3268 			error_fr(r, "compose");
   3269 			channel_free(ssh, c);
   3270 			goto out;
   3271 		}
   3272 		break;
   3273 	case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
   3274 		/*
   3275 		 * Almost the same as SSH2_MSG_CHANNEL_OPEN, except then we
   3276 		 * need to parse 'remote_id' instead of 'ctype'.
   3277 		 */
   3278 		if ((original = sshbuf_from(cp, have)) == NULL ||
   3279 		    (modified = sshbuf_new()) == NULL) {
   3280 			error_f("alloc");
   3281 			goto out;
   3282 		}
   3283 		if ((r = sshbuf_get_u32(original, &remote_id)) != 0 ||
   3284 		    (r = sshbuf_get_u32(original, &id)) != 0) {
   3285 			error_fr(r, "parse");
   3286 			goto out;
   3287 		}
   3288 		c = channel_new(ssh, "mux-proxy", SSH_CHANNEL_MUX_PROXY,
   3289 		    -1, -1, -1, 0, 0, 0, "mux-down-connect", 1);
   3290 		c->mux_ctx = downstream;	/* point to mux client */
   3291 		c->mux_downstream_id = id;
   3292 		c->remote_id = remote_id;
   3293 		c->have_remote_id = 1;
   3294 		if ((r = sshbuf_put_u32(modified, remote_id)) != 0 ||
   3295 		    (r = sshbuf_put_u32(modified, c->self)) != 0 ||
   3296 		    (r = sshbuf_putb(modified, original)) != 0) {
   3297 			error_fr(r, "compose");
   3298 			channel_free(ssh, c);
   3299 			goto out;
   3300 		}
   3301 		break;
   3302 	case SSH2_MSG_GLOBAL_REQUEST:
   3303 		if ((original = sshbuf_from(cp, have)) == NULL) {
   3304 			error_f("alloc");
   3305 			goto out;
   3306 		}
   3307 		if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0) {
   3308 			error_fr(r, "parse");
   3309 			goto out;
   3310 		}
   3311 		if (strcmp(ctype, "tcpip-forward") != 0) {
   3312 			error_f("unsupported request %s", ctype);
   3313 			goto out;
   3314 		}
   3315 		if ((r = sshbuf_get_u8(original, NULL)) != 0 ||
   3316 		    (r = sshbuf_get_cstring(original, &listen_host, NULL)) != 0 ||
   3317 		    (r = sshbuf_get_u32(original, &listen_port)) != 0) {
   3318 			error_fr(r, "parse");
   3319 			goto out;
   3320 		}
   3321 		if (listen_port > 65535) {
   3322 			error_f("tcpip-forward for %s: bad port %u",
   3323 			    listen_host, listen_port);
   3324 			goto out;
   3325 		}
   3326 		/* Record that connection to this host/port is permitted. */
   3327 		permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL, "<mux>",
   3328 		    -1, listen_host, NULL, (int)listen_port, downstream);
   3329 		break;
   3330 	case SSH2_MSG_CHANNEL_CLOSE:
   3331 		if (have < 4)
   3332 			break;
   3333 		remote_id = PEEK_U32(cp);
   3334 		if ((c = channel_by_remote_id(ssh, remote_id)) != NULL) {
   3335 			if (c->flags & CHAN_CLOSE_RCVD)
   3336 				channel_free(ssh, c);
   3337 			else
   3338 				c->flags |= CHAN_CLOSE_SENT;
   3339 		}
   3340 		break;
   3341 	}
   3342 	if (modified) {
   3343 		if ((r = sshpkt_start(ssh, type)) != 0 ||
   3344 		    (r = sshpkt_putb(ssh, modified)) != 0 ||
   3345 		    (r = sshpkt_send(ssh)) != 0) {
   3346 			error_fr(r, "send");
   3347 			goto out;
   3348 		}
   3349 	} else {
   3350 		if ((r = sshpkt_start(ssh, type)) != 0 ||
   3351 		    (r = sshpkt_put(ssh, cp, have)) != 0 ||
   3352 		    (r = sshpkt_send(ssh)) != 0) {
   3353 			error_fr(r, "send");
   3354 			goto out;
   3355 		}
   3356 	}
   3357 	ret = 0;
   3358  out:
   3359 	free(ctype);
   3360 	free(listen_host);
   3361 	sshbuf_free(original);
   3362 	sshbuf_free(modified);
   3363 	return ret;
   3364 }
   3365 
   3366 /*
   3367  * receive packets from upstream server and de-multiplex packets
   3368  * to correct downstream:
   3369  * implemented as a helper for channel input handlers,
   3370  * replaces local (proxy) channel ID with downstream channel ID.
   3371  */
   3372 int
   3373 channel_proxy_upstream(Channel *c, int type, uint32_t seq, struct ssh *ssh)
   3374 {
   3375 	struct sshbuf *b = NULL;
   3376 	Channel *downstream;
   3377 	const u_char *cp = NULL;
   3378 	size_t len;
   3379 	int r;
   3380 
   3381 	/*
   3382 	 * When receiving packets from the peer we need to check whether we
   3383 	 * need to forward the packets to the mux client. In this case we
   3384 	 * restore the original channel id and keep track of CLOSE messages,
   3385 	 * so we can cleanup the channel.
   3386 	 */
   3387 	if (c == NULL || c->type != SSH_CHANNEL_MUX_PROXY)
   3388 		return 0;
   3389 	if ((downstream = c->mux_ctx) == NULL)
   3390 		return 0;
   3391 	switch (type) {
   3392 	case SSH2_MSG_CHANNEL_CLOSE:
   3393 	case SSH2_MSG_CHANNEL_DATA:
   3394 	case SSH2_MSG_CHANNEL_EOF:
   3395 	case SSH2_MSG_CHANNEL_EXTENDED_DATA:
   3396 	case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
   3397 	case SSH2_MSG_CHANNEL_OPEN_FAILURE:
   3398 	case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
   3399 	case SSH2_MSG_CHANNEL_SUCCESS:
   3400 	case SSH2_MSG_CHANNEL_FAILURE:
   3401 	case SSH2_MSG_CHANNEL_REQUEST:
   3402 		break;
   3403 	default:
   3404 		debug2_f("channel %u: unsupported type %u", c->self, type);
   3405 		return 0;
   3406 	}
   3407 	if ((b = sshbuf_new()) == NULL) {
   3408 		error_f("alloc reply");
   3409 		goto out;
   3410 	}
   3411 	/* get remaining payload (after id) */
   3412 	cp = sshpkt_ptr(ssh, &len);
   3413 	if (cp == NULL) {
   3414 		error_f("no packet");
   3415 		goto out;
   3416 	}
   3417 	/* translate id and send to muxclient */
   3418 	if ((r = sshbuf_put_u8(b, 0)) != 0 ||	/* padlen */
   3419 	    (r = sshbuf_put_u8(b, type)) != 0 ||
   3420 	    (r = sshbuf_put_u32(b, c->mux_downstream_id)) != 0 ||
   3421 	    (r = sshbuf_put(b, cp, len)) != 0 ||
   3422 	    (r = sshbuf_put_stringb(downstream->output, b)) != 0) {
   3423 		error_fr(r, "compose muxclient");
   3424 		goto out;
   3425 	}
   3426 	/* sshbuf_dump(b, stderr); */
   3427 	if (ssh_packet_log_type(type))
   3428 		debug3_f("channel %u: up->down: type %u", c->self, type);
   3429  out:
   3430 	/* update state */
   3431 	switch (type) {
   3432 	case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
   3433 		/* record remote_id for SSH2_MSG_CHANNEL_CLOSE */
   3434 		if (cp && len > 4) {
   3435 			c->remote_id = PEEK_U32(cp);
   3436 			c->have_remote_id = 1;
   3437 		}
   3438 		break;
   3439 	case SSH2_MSG_CHANNEL_CLOSE:
   3440 		if (c->flags & CHAN_CLOSE_SENT)
   3441 			channel_free(ssh, c);
   3442 		else
   3443 			c->flags |= CHAN_CLOSE_RCVD;
   3444 		break;
   3445 	}
   3446 	sshbuf_free(b);
   3447 	return 1;
   3448 }
   3449 
   3450 /* -- protocol input */
   3451 
   3452 /* Parse a channel ID from the current packet */
   3453 static int
   3454 channel_parse_id(struct ssh *ssh, const char *where, const char *what)
   3455 {
   3456 	uint32_t id;
   3457 	int r;
   3458 
   3459 	if ((r = sshpkt_get_u32(ssh, &id)) != 0) {
   3460 		error_r(r, "%s: parse id", where);
   3461 		ssh_packet_disconnect(ssh, "Invalid %s message", what);
   3462 	}
   3463 	if (id > INT_MAX) {
   3464 		error_r(r, "%s: bad channel id %u", where, id);
   3465 		ssh_packet_disconnect(ssh, "Invalid %s channel id", what);
   3466 	}
   3467 	return (int)id;
   3468 }
   3469 
   3470 /* Lookup a channel from an ID in the current packet */
   3471 static Channel *
   3472 channel_from_packet_id(struct ssh *ssh, const char *where, const char *what)
   3473 {
   3474 	int id = channel_parse_id(ssh, where, what);
   3475 	Channel *c;
   3476 
   3477 	if ((c = channel_lookup(ssh, id)) == NULL) {
   3478 		ssh_packet_disconnect(ssh,
   3479 		    "%s packet referred to nonexistent channel %d", what, id);
   3480 	}
   3481 	return c;
   3482 }
   3483 
   3484 int
   3485 channel_input_data(int type, uint32_t seq, struct ssh *ssh)
   3486 {
   3487 	const u_char *data;
   3488 	size_t data_len, win_len;
   3489 	Channel *c = channel_from_packet_id(ssh, __func__, "data");
   3490 	int r;
   3491 
   3492 	if (channel_proxy_upstream(c, type, seq, ssh))
   3493 		return 0;
   3494 
   3495 	/* Ignore any data for non-open channels (might happen on close) */
   3496 	if (c->type != SSH_CHANNEL_OPEN &&
   3497 	    c->type != SSH_CHANNEL_RDYNAMIC_OPEN &&
   3498 	    c->type != SSH_CHANNEL_RDYNAMIC_FINISH &&
   3499 	    c->type != SSH_CHANNEL_X11_OPEN)
   3500 		return 0;
   3501 
   3502 	/* Get the data. */
   3503 	if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
   3504             (r = sshpkt_get_end(ssh)) != 0)
   3505 		fatal_fr(r, "channel %i: get data", c->self);
   3506 
   3507 	win_len = data_len;
   3508 	if (c->datagram)
   3509 		win_len += 4;  /* string length header */
   3510 
   3511 	/*
   3512 	 * The sending side reduces its window as it sends data, so we
   3513 	 * must 'fake' consumption of the data in order to ensure that window
   3514 	 * updates are sent back. Otherwise the connection might deadlock.
   3515 	 */
   3516 	if (c->ostate != CHAN_OUTPUT_OPEN) {
   3517 		if (win_len > c->local_window)
   3518 			c->local_window = 0;
   3519 		else
   3520 			c->local_window -= win_len;
   3521 		c->local_consumed += win_len;
   3522 		return 0;
   3523 	}
   3524 
   3525 	if (win_len > c->local_maxpacket) {
   3526 		logit("channel %d: rcvd big packet %zu, maxpack %u",
   3527 		    c->self, win_len, c->local_maxpacket);
   3528 		return 0;
   3529 	}
   3530 	if (win_len > c->local_window) {
   3531 		c->local_window_exceeded += win_len - c->local_window;
   3532 		logit("channel %d: rcvd too much data %zu, win %u/%u "
   3533 		    "(excess %u)", c->self, win_len, c->local_window,
   3534 		    c->local_window_max, c->local_window_exceeded);
   3535 		c->local_window = 0;
   3536 		/* Allow 10% grace before bringing the hammer down */
   3537 		if (c->local_window_exceeded > (c->local_window_max / 10)) {
   3538 			ssh_packet_disconnect(ssh, "channel %d: peer ignored "
   3539 			    "channel window", c->self);
   3540 		}
   3541 	} else {
   3542 		c->local_window -= win_len;
   3543 		c->local_window_exceeded = 0;
   3544 	}
   3545 
   3546 	if (c->datagram) {
   3547 		if ((r = sshbuf_put_string(c->output, data, data_len)) != 0)
   3548 			fatal_fr(r, "channel %i: append datagram", c->self);
   3549 	} else if ((r = sshbuf_put(c->output, data, data_len)) != 0)
   3550 		fatal_fr(r, "channel %i: append data", c->self);
   3551 
   3552 	return 0;
   3553 }
   3554 
   3555 int
   3556 channel_input_extended_data(int type, uint32_t seq, struct ssh *ssh)
   3557 {
   3558 	const u_char *data;
   3559 	size_t data_len;
   3560 	uint32_t tcode;
   3561 	Channel *c = channel_from_packet_id(ssh, __func__, "extended data");
   3562 	int r;
   3563 
   3564 	if (channel_proxy_upstream(c, type, seq, ssh))
   3565 		return 0;
   3566 	if (c->type != SSH_CHANNEL_OPEN) {
   3567 		logit("channel %d: ext data for non open", c->self);
   3568 		return 0;
   3569 	}
   3570 	if (c->flags & CHAN_EOF_RCVD) {
   3571 		if (ssh->compat & SSH_BUG_EXTEOF)
   3572 			debug("channel %d: accepting ext data after eof",
   3573 			    c->self);
   3574 		else
   3575 			ssh_packet_disconnect(ssh, "Received extended_data "
   3576 			    "after EOF on channel %d.", c->self);
   3577 	}
   3578 
   3579 	if ((r = sshpkt_get_u32(ssh, &tcode)) != 0) {
   3580 		error_fr(r, "parse tcode");
   3581 		ssh_packet_disconnect(ssh, "Invalid extended_data message");
   3582 	}
   3583 	if (c->efd == -1 ||
   3584 	    c->extended_usage != CHAN_EXTENDED_WRITE ||
   3585 	    tcode != SSH2_EXTENDED_DATA_STDERR) {
   3586 		logit("channel %d: bad ext data", c->self);
   3587 		return 0;
   3588 	}
   3589 	if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
   3590             (r = sshpkt_get_end(ssh)) != 0) {
   3591 		error_fr(r, "parse data");
   3592 		ssh_packet_disconnect(ssh, "Invalid extended_data message");
   3593 	}
   3594 
   3595 	if (data_len > c->local_window) {
   3596 		logit("channel %d: rcvd too much extended_data %zu, win %u",
   3597 		    c->self, data_len, c->local_window);
   3598 		return 0;
   3599 	}
   3600 	debug2("channel %d: rcvd ext data %zu", c->self, data_len);
   3601 	/* XXX sshpkt_getb? */
   3602 	if ((r = sshbuf_put(c->extended, data, data_len)) != 0)
   3603 		error_fr(r, "append");
   3604 	c->local_window -= data_len;
   3605 	return 0;
   3606 }
   3607 
   3608 int
   3609 channel_input_ieof(int type, uint32_t seq, struct ssh *ssh)
   3610 {
   3611 	Channel *c = channel_from_packet_id(ssh, __func__, "ieof");
   3612 	int r;
   3613 
   3614         if ((r = sshpkt_get_end(ssh)) != 0) {
   3615 		error_fr(r, "parse data");
   3616 		ssh_packet_disconnect(ssh, "Invalid ieof message");
   3617 	}
   3618 
   3619 	if (channel_proxy_upstream(c, type, seq, ssh))
   3620 		return 0;
   3621 	chan_rcvd_ieof(ssh, c);
   3622 
   3623 	/* XXX force input close */
   3624 	if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
   3625 		debug("channel %d: FORCE input drain", c->self);
   3626 		c->istate = CHAN_INPUT_WAIT_DRAIN;
   3627 		if (sshbuf_len(c->input) == 0)
   3628 			chan_ibuf_empty(ssh, c);
   3629 	}
   3630 	return 0;
   3631 }
   3632 
   3633 int
   3634 channel_input_oclose(int type, uint32_t seq, struct ssh *ssh)
   3635 {
   3636 	Channel *c = channel_from_packet_id(ssh, __func__, "oclose");
   3637 	int r;
   3638 
   3639 	if (channel_proxy_upstream(c, type, seq, ssh))
   3640 		return 0;
   3641         if ((r = sshpkt_get_end(ssh)) != 0) {
   3642 		error_fr(r, "parse data");
   3643 		ssh_packet_disconnect(ssh, "Invalid oclose message");
   3644 	}
   3645 	chan_rcvd_oclose(ssh, c);
   3646 	return 0;
   3647 }
   3648 
   3649 int
   3650 channel_input_open_confirmation(int type, uint32_t seq, struct ssh *ssh)
   3651 {
   3652 	Channel *c = channel_from_packet_id(ssh, __func__, "open confirmation");
   3653 	uint32_t remote_window, remote_maxpacket;
   3654 	int r;
   3655 
   3656 	if (channel_proxy_upstream(c, type, seq, ssh))
   3657 		return 0;
   3658 	if (c->type != SSH_CHANNEL_OPENING)
   3659 		ssh_packet_disconnect(ssh, "Received open confirmation for "
   3660 		    "non-opening channel %d.", c->self);
   3661 	/*
   3662 	 * Record the remote channel number and mark that the channel
   3663 	 * is now open.
   3664 	 */
   3665 	if ((r = sshpkt_get_u32(ssh, &c->remote_id)) != 0 ||
   3666 	    (r = sshpkt_get_u32(ssh, &remote_window)) != 0 ||
   3667 	    (r = sshpkt_get_u32(ssh, &remote_maxpacket)) != 0 ||
   3668             (r = sshpkt_get_end(ssh)) != 0) {
   3669 		error_fr(r, "window/maxpacket");
   3670 		ssh_packet_disconnect(ssh, "Invalid open confirmation message");
   3671 	}
   3672 
   3673 	c->have_remote_id = 1;
   3674 	c->remote_window = remote_window;
   3675 	c->remote_maxpacket = remote_maxpacket;
   3676 	c->type = SSH_CHANNEL_OPEN;
   3677 	if (c->open_confirm) {
   3678 		debug2_f("channel %d: callback start", c->self);
   3679 		c->open_confirm(ssh, c->self, 1, c->open_confirm_ctx);
   3680 		debug2_f("channel %d: callback done", c->self);
   3681 	}
   3682 	channel_set_used_time(ssh, c);
   3683 	debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
   3684 	    c->remote_window, c->remote_maxpacket);
   3685 	return 0;
   3686 }
   3687 
   3688 static const char *
   3689 reason2txt(int reason)
   3690 {
   3691 	switch (reason) {
   3692 	case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
   3693 		return "administratively prohibited";
   3694 	case SSH2_OPEN_CONNECT_FAILED:
   3695 		return "connect failed";
   3696 	case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
   3697 		return "unknown channel type";
   3698 	case SSH2_OPEN_RESOURCE_SHORTAGE:
   3699 		return "resource shortage";
   3700 	}
   3701 	return "unknown reason";
   3702 }
   3703 
   3704 int
   3705 channel_input_open_failure(int type, uint32_t seq, struct ssh *ssh)
   3706 {
   3707 	Channel *c = channel_from_packet_id(ssh, __func__, "open failure");
   3708 	uint32_t reason;
   3709 	char *msg = NULL;
   3710 	int r;
   3711 
   3712 	if (channel_proxy_upstream(c, type, seq, ssh))
   3713 		return 0;
   3714 	if (c->type != SSH_CHANNEL_OPENING)
   3715 		ssh_packet_disconnect(ssh, "Received open failure for "
   3716 		    "non-opening channel %d.", c->self);
   3717 	if ((r = sshpkt_get_u32(ssh, &reason)) != 0) {
   3718 		error_fr(r, "parse reason");
   3719 		ssh_packet_disconnect(ssh, "Invalid open failure message");
   3720 	}
   3721 	/* skip language */
   3722 	if ((r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
   3723 	    (r = sshpkt_get_string_direct(ssh, NULL, NULL)) != 0 ||
   3724             (r = sshpkt_get_end(ssh)) != 0) {
   3725 		error_fr(r, "parse msg/lang");
   3726 		ssh_packet_disconnect(ssh, "Invalid open failure message");
   3727 	}
   3728 	logit("channel %d: open failed: %s%s%s", c->self,
   3729 	    reason2txt(reason), msg ? ": ": "", msg ? msg : "");
   3730 	free(msg);
   3731 	if (c->open_confirm) {
   3732 		debug2_f("channel %d: callback start", c->self);
   3733 		c->open_confirm(ssh, c->self, 0, c->open_confirm_ctx);
   3734 		debug2_f("channel %d: callback done", c->self);
   3735 	}
   3736 	/* Schedule the channel for cleanup/deletion. */
   3737 	chan_mark_dead(ssh, c);
   3738 	return 0;
   3739 }
   3740 
   3741 int
   3742 channel_input_window_adjust(int type, uint32_t seq, struct ssh *ssh)
   3743 {
   3744 	int id = channel_parse_id(ssh, __func__, "window adjust");
   3745 	Channel *c;
   3746 	uint32_t adjust;
   3747 	u_int new_rwin;
   3748 	int r;
   3749 
   3750 	if ((c = channel_lookup(ssh, id)) == NULL) {
   3751 		logit("Received window adjust for non-open channel %d.", id);
   3752 		return 0;
   3753 	}
   3754 
   3755 	if (channel_proxy_upstream(c, type, seq, ssh))
   3756 		return 0;
   3757 	if ((r = sshpkt_get_u32(ssh, &adjust)) != 0 ||
   3758             (r = sshpkt_get_end(ssh)) != 0) {
   3759 		error_fr(r, "parse adjust");
   3760 		ssh_packet_disconnect(ssh, "Invalid window adjust message");
   3761 	}
   3762 	debug2("channel %d: rcvd adjust %u", c->self, adjust);
   3763 	if ((new_rwin = c->remote_window + adjust) < c->remote_window) {
   3764 		fatal("channel %d: adjust %u overflows remote window %u",
   3765 		    c->self, adjust, c->remote_window);
   3766 	}
   3767 	c->remote_window = new_rwin;
   3768 	return 0;
   3769 }
   3770 
   3771 int
   3772 channel_input_status_confirm(int type, uint32_t seq, struct ssh *ssh)
   3773 {
   3774 	int id = channel_parse_id(ssh, __func__, "status confirm");
   3775 	Channel *c;
   3776 	struct channel_confirm *cc;
   3777 
   3778 	/* Reset keepalive timeout */
   3779 	ssh_packet_set_alive_timeouts(ssh, 0);
   3780 
   3781 	debug2_f("type %d id %d", type, id);
   3782 
   3783 	if ((c = channel_lookup(ssh, id)) == NULL) {
   3784 		logit_f("%d: unknown", id);
   3785 		return 0;
   3786 	}
   3787 	if (channel_proxy_upstream(c, type, seq, ssh))
   3788 		return 0;
   3789         if (sshpkt_get_end(ssh) != 0)
   3790 		ssh_packet_disconnect(ssh, "Invalid status confirm message");
   3791 	if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
   3792 		return 0;
   3793 	cc->cb(ssh, type, c, cc->ctx);
   3794 	TAILQ_REMOVE(&c->status_confirms, cc, entry);
   3795 	freezero(cc, sizeof(*cc));
   3796 	return 0;
   3797 }
   3798 
   3799 /* -- tcp forwarding */
   3800 
   3801 void
   3802 channel_set_af(struct ssh *ssh, int af)
   3803 {
   3804 	ssh->chanctxt->IPv4or6 = af;
   3805 }
   3806 
   3807 void
   3808 channel_set_hpn(int external_hpn_disabled, int external_hpn_buffer_size)
   3809 {
   3810       	hpn_disabled = external_hpn_disabled;
   3811 	hpn_buffer_size = external_hpn_buffer_size;
   3812 	debug("HPN Disabled: %d, HPN Buffer Size: %d", hpn_disabled, hpn_buffer_size);
   3813 }
   3814 
   3815 /*
   3816  * Determine whether or not a port forward listens to loopback, the
   3817  * specified address or wildcard. On the client, a specified bind
   3818  * address will always override gateway_ports. On the server, a
   3819  * gateway_ports of 1 (``yes'') will override the client's specification
   3820  * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
   3821  * will bind to whatever address the client asked for.
   3822  *
   3823  * Special-case listen_addrs are:
   3824  *
   3825  * "0.0.0.0"               -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
   3826  * "" (empty string), "*"  -> wildcard v4/v6
   3827  * "localhost"             -> loopback v4/v6
   3828  * "127.0.0.1" / "::1"     -> accepted even if gateway_ports isn't set
   3829  */
   3830 static const char *
   3831 channel_fwd_bind_addr(struct ssh *ssh, const char *listen_addr, int *wildcardp,
   3832     int is_client, struct ForwardOptions *fwd_opts)
   3833 {
   3834 	const char *addr = NULL;
   3835 	int wildcard = 0;
   3836 
   3837 	if (listen_addr == NULL) {
   3838 		/* No address specified: default to gateway_ports setting */
   3839 		if (fwd_opts->gateway_ports)
   3840 			wildcard = 1;
   3841 	} else if (fwd_opts->gateway_ports || is_client) {
   3842 		if (((ssh->compat & SSH_OLD_FORWARD_ADDR) &&
   3843 		    strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
   3844 		    *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
   3845 		    (!is_client && fwd_opts->gateway_ports == 1)) {
   3846 			wildcard = 1;
   3847 			/*
   3848 			 * Notify client if they requested a specific listen
   3849 			 * address and it was overridden.
   3850 			 */
   3851 			if (*listen_addr != '\0' &&
   3852 			    strcmp(listen_addr, "0.0.0.0") != 0 &&
   3853 			    strcmp(listen_addr, "*") != 0) {
   3854 				ssh_packet_send_debug(ssh,
   3855 				    "Forwarding listen address "
   3856 				    "\"%s\" overridden by server "
   3857 				    "GatewayPorts", listen_addr);
   3858 			}
   3859 		} else if (strcmp(listen_addr, "localhost") != 0 ||
   3860 		    strcmp(listen_addr, "127.0.0.1") == 0 ||
   3861 		    strcmp(listen_addr, "::1") == 0) {
   3862 			/*
   3863 			 * Accept explicit localhost address when
   3864 			 * GatewayPorts=yes. The "localhost" hostname is
   3865 			 * deliberately skipped here so it will listen on all
   3866 			 * available local address families.
   3867 			 */
   3868 			addr = listen_addr;
   3869 		}
   3870 	} else if (strcmp(listen_addr, "127.0.0.1") == 0 ||
   3871 	    strcmp(listen_addr, "::1") == 0) {
   3872 		/*
   3873 		 * If a specific IPv4/IPv6 localhost address has been
   3874 		 * requested then accept it even if gateway_ports is in
   3875 		 * effect. This allows the client to prefer IPv4 or IPv6.
   3876 		 */
   3877 		addr = listen_addr;
   3878 	}
   3879 	if (wildcardp != NULL)
   3880 		*wildcardp = wildcard;
   3881 	return addr;
   3882 }
   3883 
   3884 static int
   3885 channel_setup_fwd_listener_tcpip(struct ssh *ssh, int type,
   3886     struct Forward *fwd, int *allocated_listen_port,
   3887     struct ForwardOptions *fwd_opts)
   3888 {
   3889 	Channel *c;
   3890 	int sock, r, success = 0, wildcard = 0, is_client;
   3891 	struct addrinfo hints, *ai, *aitop;
   3892 	const char *host, *addr;
   3893 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
   3894 	in_port_t *lport_p;
   3895 
   3896 	is_client = (type == SSH_CHANNEL_PORT_LISTENER);
   3897 
   3898 	if (is_client && fwd->connect_path != NULL) {
   3899 		host = fwd->connect_path;
   3900 	} else {
   3901 		host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
   3902 		    fwd->listen_host : fwd->connect_host;
   3903 		if (host == NULL) {
   3904 			error("No forward host name.");
   3905 			return 0;
   3906 		}
   3907 		if (strlen(host) >= NI_MAXHOST) {
   3908 			error("Forward host name too long.");
   3909 			return 0;
   3910 		}
   3911 	}
   3912 
   3913 	/* Determine the bind address, cf. channel_fwd_bind_addr() comment */
   3914 	addr = channel_fwd_bind_addr(ssh, fwd->listen_host, &wildcard,
   3915 	    is_client, fwd_opts);
   3916 	debug3_f("type %d wildcard %d addr %s", type, wildcard,
   3917 	    (addr == NULL) ? "NULL" : addr);
   3918 
   3919 	/*
   3920 	 * getaddrinfo returns a loopback address if the hostname is
   3921 	 * set to NULL and hints.ai_flags is not AI_PASSIVE
   3922 	 */
   3923 	memset(&hints, 0, sizeof(hints));
   3924 	hints.ai_family = ssh->chanctxt->IPv4or6;
   3925 	hints.ai_flags = wildcard ? AI_PASSIVE : 0;
   3926 	hints.ai_socktype = SOCK_STREAM;
   3927 	snprintf(strport, sizeof strport, "%d", fwd->listen_port);
   3928 	if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
   3929 		if (addr == NULL) {
   3930 			/* This really shouldn't happen */
   3931 			ssh_packet_disconnect(ssh, "getaddrinfo: fatal error: %s",
   3932 			    ssh_gai_strerror(r));
   3933 		} else {
   3934 			error_f("getaddrinfo(%.64s): %s", addr,
   3935 			    ssh_gai_strerror(r));
   3936 		}
   3937 		return 0;
   3938 	}
   3939 	if (allocated_listen_port != NULL)
   3940 		*allocated_listen_port = 0;
   3941 	for (ai = aitop; ai; ai = ai->ai_next) {
   3942 		switch (ai->ai_family) {
   3943 		case AF_INET:
   3944 			lport_p = &((struct sockaddr_in *)ai->ai_addr)->
   3945 			    sin_port;
   3946 			break;
   3947 		case AF_INET6:
   3948 			lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
   3949 			    sin6_port;
   3950 			break;
   3951 		default:
   3952 			continue;
   3953 		}
   3954 		/*
   3955 		 * If allocating a port for -R forwards, then use the
   3956 		 * same port for all address families.
   3957 		 */
   3958 		if (type == SSH_CHANNEL_RPORT_LISTENER &&
   3959 		    fwd->listen_port == 0 && allocated_listen_port != NULL &&
   3960 		    *allocated_listen_port > 0)
   3961 			*lport_p = htons(*allocated_listen_port);
   3962 
   3963 		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
   3964 		    strport, sizeof(strport),
   3965 		    NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
   3966 			error_f("getnameinfo failed");
   3967 			continue;
   3968 		}
   3969 		/* Create a port to listen for the host. */
   3970 		sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
   3971 		if (sock == -1) {
   3972 			/* this is no error since kernel may not support ipv6 */
   3973 			verbose("socket [%s]:%s: %.100s", ntop, strport,
   3974 			    strerror(errno));
   3975 			continue;
   3976 		}
   3977 
   3978 		set_reuseaddr(sock);
   3979 
   3980 		debug("Local forwarding listening on %s port %s.",
   3981 		    ntop, strport);
   3982 
   3983 		/* Bind the socket to the address. */
   3984 		if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
   3985 			/*
   3986 			 * address can be in if use ipv6 address is
   3987 			 * already bound
   3988 			 */
   3989 			verbose("bind [%s]:%s: %.100s",
   3990 			    ntop, strport, strerror(errno));
   3991 			close(sock);
   3992 			continue;
   3993 		}
   3994 		/* Start listening for connections on the socket. */
   3995 		if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
   3996 			error("listen [%s]:%s: %.100s", ntop, strport,
   3997 			    strerror(errno));
   3998 			close(sock);
   3999 			continue;
   4000 		}
   4001 
   4002 		/*
   4003 		 * fwd->listen_port == 0 requests a dynamically allocated port -
   4004 		 * record what we got.
   4005 		 */
   4006 		if (type == SSH_CHANNEL_RPORT_LISTENER &&
   4007 		    fwd->listen_port == 0 &&
   4008 		    allocated_listen_port != NULL &&
   4009 		    *allocated_listen_port == 0) {
   4010 			*allocated_listen_port = get_local_port(sock);
   4011 			debug("Allocated listen port %d",
   4012 			    *allocated_listen_port);
   4013 		}
   4014 
   4015 		/* Allocate a channel number for the socket. */
   4016 		/* explicitly test for hpn disabled option. if true use smaller window size */
   4017 		if (hpn_disabled)
   4018 		c = channel_new(ssh, "port-listener", type, sock, sock, -1,
   4019 		    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
   4020 		    0, "port listener", 1);
   4021 		else
   4022 			c = channel_new(ssh, "port listener", type, sock, sock,
   4023 			  -1, hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT,
   4024 		    	  0, "port listener", 1);
   4025 		c->path = xstrdup(host);
   4026 		c->host_port = fwd->connect_port;
   4027 		c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
   4028 		if (fwd->listen_port == 0 && allocated_listen_port != NULL &&
   4029 		    !(ssh->compat & SSH_BUG_DYNAMIC_RPORT))
   4030 			c->listening_port = *allocated_listen_port;
   4031 		else
   4032 			c->listening_port = fwd->listen_port;
   4033 		success = 1;
   4034 	}
   4035 	if (success == 0)
   4036 		error_f("cannot listen to port: %d", fwd->listen_port);
   4037 	freeaddrinfo(aitop);
   4038 	return success;
   4039 }
   4040 
   4041 static int
   4042 channel_setup_fwd_listener_streamlocal(struct ssh *ssh, int type,
   4043     struct Forward *fwd, struct ForwardOptions *fwd_opts)
   4044 {
   4045 	struct sockaddr_un sunaddr;
   4046 	const char *path;
   4047 	Channel *c;
   4048 	int port, sock;
   4049 	mode_t omask;
   4050 
   4051 	switch (type) {
   4052 	case SSH_CHANNEL_UNIX_LISTENER:
   4053 		if (fwd->connect_path != NULL) {
   4054 			if (strlen(fwd->connect_path) > sizeof(sunaddr.sun_path)) {
   4055 				error("Local connecting path too long: %s",
   4056 				    fwd->connect_path);
   4057 				return 0;
   4058 			}
   4059 			path = fwd->connect_path;
   4060 			port = PORT_STREAMLOCAL;
   4061 		} else {
   4062 			if (fwd->connect_host == NULL) {
   4063 				error("No forward host name.");
   4064 				return 0;
   4065 			}
   4066 			if (strlen(fwd->connect_host) >= NI_MAXHOST) {
   4067 				error("Forward host name too long.");
   4068 				return 0;
   4069 			}
   4070 			path = fwd->connect_host;
   4071 			port = fwd->connect_port;
   4072 		}
   4073 		break;
   4074 	case SSH_CHANNEL_RUNIX_LISTENER:
   4075 		path = fwd->listen_path;
   4076 		port = PORT_STREAMLOCAL;
   4077 		break;
   4078 	default:
   4079 		error_f("unexpected channel type %d", type);
   4080 		return 0;
   4081 	}
   4082 
   4083 	if (fwd->listen_path == NULL) {
   4084 		error("No forward path name.");
   4085 		return 0;
   4086 	}
   4087 	if (strlen(fwd->listen_path) > sizeof(sunaddr.sun_path)) {
   4088 		error("Local listening path too long: %s", fwd->listen_path);
   4089 		return 0;
   4090 	}
   4091 
   4092 	debug3_f("type %d path %s", type, fwd->listen_path);
   4093 
   4094 	/* Start a Unix domain listener. */
   4095 	omask = umask(fwd_opts->streamlocal_bind_mask);
   4096 	sock = unix_listener(fwd->listen_path, SSH_LISTEN_BACKLOG,
   4097 	    fwd_opts->streamlocal_bind_unlink);
   4098 	umask(omask);
   4099 	if (sock < 0)
   4100 		return 0;
   4101 
   4102 	debug("Local forwarding listening on path %s.", fwd->listen_path);
   4103 
   4104 	/* Allocate a channel number for the socket. */
   4105 	c = channel_new(ssh, "unix-listener", type, sock, sock, -1,
   4106 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
   4107 	    0, "unix listener", 1);
   4108 	c->path = xstrdup(path);
   4109 	c->host_port = port;
   4110 	c->listening_port = PORT_STREAMLOCAL;
   4111 	c->listening_addr = xstrdup(fwd->listen_path);
   4112 	return 1;
   4113 }
   4114 
   4115 static int
   4116 channel_cancel_rport_listener_tcpip(struct ssh *ssh,
   4117     const char *host, u_short port)
   4118 {
   4119 	u_int i;
   4120 	int found = 0;
   4121 
   4122 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
   4123 		Channel *c = ssh->chanctxt->channels[i];
   4124 		if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
   4125 			continue;
   4126 		if (strcmp(c->path, host) == 0 && c->listening_port == port) {
   4127 			debug2_f("close channel %d", i);
   4128 			channel_free(ssh, c);
   4129 			found = 1;
   4130 		}
   4131 	}
   4132 
   4133 	return found;
   4134 }
   4135 
   4136 static int
   4137 channel_cancel_rport_listener_streamlocal(struct ssh *ssh, const char *path)
   4138 {
   4139 	u_int i;
   4140 	int found = 0;
   4141 
   4142 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
   4143 		Channel *c = ssh->chanctxt->channels[i];
   4144 		if (c == NULL || c->type != SSH_CHANNEL_RUNIX_LISTENER)
   4145 			continue;
   4146 		if (c->path == NULL)
   4147 			continue;
   4148 		if (strcmp(c->path, path) == 0) {
   4149 			debug2_f("close channel %d", i);
   4150 			channel_free(ssh, c);
   4151 			found = 1;
   4152 		}
   4153 	}
   4154 
   4155 	return found;
   4156 }
   4157 
   4158 int
   4159 channel_cancel_rport_listener(struct ssh *ssh, struct Forward *fwd)
   4160 {
   4161 	if (fwd->listen_path != NULL) {
   4162 		return channel_cancel_rport_listener_streamlocal(ssh,
   4163 		    fwd->listen_path);
   4164 	} else {
   4165 		return channel_cancel_rport_listener_tcpip(ssh,
   4166 		    fwd->listen_host, fwd->listen_port);
   4167 	}
   4168 }
   4169 
   4170 static int
   4171 channel_cancel_lport_listener_tcpip(struct ssh *ssh,
   4172     const char *lhost, u_short lport, int cport,
   4173     struct ForwardOptions *fwd_opts)
   4174 {
   4175 	u_int i;
   4176 	int found = 0;
   4177 	const char *addr = channel_fwd_bind_addr(ssh, lhost, NULL, 1, fwd_opts);
   4178 
   4179 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
   4180 		Channel *c = ssh->chanctxt->channels[i];
   4181 		if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
   4182 			continue;
   4183 		if (c->listening_port != lport)
   4184 			continue;
   4185 		if (cport == CHANNEL_CANCEL_PORT_STATIC) {
   4186 			/* skip dynamic forwardings */
   4187 			if (c->host_port == 0)
   4188 				continue;
   4189 		} else {
   4190 			if (c->host_port != cport)
   4191 				continue;
   4192 		}
   4193 		if ((c->listening_addr == NULL && addr != NULL) ||
   4194 		    (c->listening_addr != NULL && addr == NULL))
   4195 			continue;
   4196 		if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
   4197 			debug2_f("close channel %d", i);
   4198 			channel_free(ssh, c);
   4199 			found = 1;
   4200 		}
   4201 	}
   4202 
   4203 	return found;
   4204 }
   4205 
   4206 static int
   4207 channel_cancel_lport_listener_streamlocal(struct ssh *ssh, const char *path)
   4208 {
   4209 	u_int i;
   4210 	int found = 0;
   4211 
   4212 	if (path == NULL) {
   4213 		error_f("no path specified.");
   4214 		return 0;
   4215 	}
   4216 
   4217 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
   4218 		Channel *c = ssh->chanctxt->channels[i];
   4219 		if (c == NULL || c->type != SSH_CHANNEL_UNIX_LISTENER)
   4220 			continue;
   4221 		if (c->listening_addr == NULL)
   4222 			continue;
   4223 		if (strcmp(c->listening_addr, path) == 0) {
   4224 			debug2_f("close channel %d", i);
   4225 			channel_free(ssh, c);
   4226 			found = 1;
   4227 		}
   4228 	}
   4229 
   4230 	return found;
   4231 }
   4232 
   4233 int
   4234 channel_cancel_lport_listener(struct ssh *ssh,
   4235     struct Forward *fwd, int cport, struct ForwardOptions *fwd_opts)
   4236 {
   4237 	if (fwd->listen_path != NULL) {
   4238 		return channel_cancel_lport_listener_streamlocal(ssh,
   4239 		    fwd->listen_path);
   4240 	} else {
   4241 		return channel_cancel_lport_listener_tcpip(ssh,
   4242 		    fwd->listen_host, fwd->listen_port, cport, fwd_opts);
   4243 	}
   4244 }
   4245 
   4246 /* protocol local port fwd, used by ssh */
   4247 int
   4248 channel_setup_local_fwd_listener(struct ssh *ssh,
   4249     struct Forward *fwd, struct ForwardOptions *fwd_opts)
   4250 {
   4251 	if (fwd->listen_path != NULL) {
   4252 		return channel_setup_fwd_listener_streamlocal(ssh,
   4253 		    SSH_CHANNEL_UNIX_LISTENER, fwd, fwd_opts);
   4254 	} else {
   4255 		return channel_setup_fwd_listener_tcpip(ssh,
   4256 		    SSH_CHANNEL_PORT_LISTENER, fwd, NULL, fwd_opts);
   4257 	}
   4258 }
   4259 
   4260 /* Matches a remote forwarding permission against a requested forwarding */
   4261 static int
   4262 remote_open_match(struct permission *allowed_open, struct Forward *fwd)
   4263 {
   4264 	int ret;
   4265 	char *lhost;
   4266 
   4267 	/* XXX add ACLs for streamlocal */
   4268 	if (fwd->listen_path != NULL)
   4269 		return 1;
   4270 
   4271 	if (fwd->listen_host == NULL || allowed_open->listen_host == NULL)
   4272 		return 0;
   4273 
   4274 	if (allowed_open->listen_port != FWD_PERMIT_ANY_PORT &&
   4275 	    allowed_open->listen_port != fwd->listen_port)
   4276 		return 0;
   4277 
   4278 	/* Match hostnames case-insensitively */
   4279 	lhost = xstrdup(fwd->listen_host);
   4280 	lowercase(lhost);
   4281 	ret = match_pattern(lhost, allowed_open->listen_host);
   4282 	free(lhost);
   4283 
   4284 	return ret;
   4285 }
   4286 
   4287 /* Checks whether a requested remote forwarding is permitted */
   4288 static int
   4289 check_rfwd_permission(struct ssh *ssh, struct Forward *fwd)
   4290 {
   4291 	struct ssh_channels *sc = ssh->chanctxt;
   4292 	struct permission_set *pset = &sc->remote_perms;
   4293 	u_int i, permit, permit_adm = 1;
   4294 	struct permission *perm;
   4295 
   4296 	/* XXX apply GatewayPorts override before checking? */
   4297 
   4298 	permit = pset->all_permitted;
   4299 	if (!permit) {
   4300 		for (i = 0; i < pset->num_permitted_user; i++) {
   4301 			perm = &pset->permitted_user[i];
   4302 			if (remote_open_match(perm, fwd)) {
   4303 				permit = 1;
   4304 				break;
   4305 			}
   4306 		}
   4307 	}
   4308 
   4309 	if (pset->num_permitted_admin > 0) {
   4310 		permit_adm = 0;
   4311 		for (i = 0; i < pset->num_permitted_admin; i++) {
   4312 			perm = &pset->permitted_admin[i];
   4313 			if (remote_open_match(perm, fwd)) {
   4314 				permit_adm = 1;
   4315 				break;
   4316 			}
   4317 		}
   4318 	}
   4319 
   4320 	return permit && permit_adm;
   4321 }
   4322 
   4323 /* protocol v2 remote port fwd, used by sshd */
   4324 int
   4325 channel_setup_remote_fwd_listener(struct ssh *ssh, struct Forward *fwd,
   4326     int *allocated_listen_port, struct ForwardOptions *fwd_opts)
   4327 {
   4328 	if (!check_rfwd_permission(ssh, fwd)) {
   4329 		ssh_packet_send_debug(ssh, "port forwarding refused");
   4330 		if (fwd->listen_path != NULL)
   4331 			/* XXX always allowed, see remote_open_match() */
   4332 			logit("Received request from %.100s port %d to "
   4333 			    "remote forward to path \"%.100s\", "
   4334 			    "but the request was denied.",
   4335 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
   4336 			    fwd->listen_path);
   4337 		else if(fwd->listen_host != NULL)
   4338 			logit("Received request from %.100s port %d to "
   4339 			    "remote forward to host %.100s port %d, "
   4340 			    "but the request was denied.",
   4341 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
   4342 			    fwd->listen_host, fwd->listen_port );
   4343 		else
   4344 			logit("Received request from %.100s port %d to remote "
   4345 			    "forward, but the request was denied.",
   4346 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
   4347 		return 0;
   4348 	}
   4349 	if (fwd->listen_path != NULL) {
   4350 		return channel_setup_fwd_listener_streamlocal(ssh,
   4351 		    SSH_CHANNEL_RUNIX_LISTENER, fwd, fwd_opts);
   4352 	} else {
   4353 		return channel_setup_fwd_listener_tcpip(ssh,
   4354 		    SSH_CHANNEL_RPORT_LISTENER, fwd, allocated_listen_port,
   4355 		    fwd_opts);
   4356 	}
   4357 }
   4358 
   4359 /*
   4360  * Translate the requested rfwd listen host to something usable for
   4361  * this server.
   4362  */
   4363 static const char *
   4364 channel_rfwd_bind_host(const char *listen_host)
   4365 {
   4366 	if (listen_host == NULL) {
   4367 		return "localhost";
   4368 	} else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
   4369 		return "";
   4370 	} else
   4371 		return listen_host;
   4372 }
   4373 
   4374 /*
   4375  * Initiate forwarding of connections to port "port" on remote host through
   4376  * the secure channel to host:port from local side.
   4377  * Returns handle (index) for updating the dynamic listen port with
   4378  * channel_update_permission().
   4379  */
   4380 int
   4381 channel_request_remote_forwarding(struct ssh *ssh, struct Forward *fwd)
   4382 {
   4383 	int r, success = 0, idx = -1;
   4384 	const char *host_to_connect, *listen_host, *listen_path;
   4385 	int port_to_connect, listen_port;
   4386 
   4387 	/* Send the forward request to the remote side. */
   4388 	if (fwd->listen_path != NULL) {
   4389 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
   4390 		    (r = sshpkt_put_cstring(ssh,
   4391 		    "streamlocal-forward (at) openssh.com")) != 0 ||
   4392 		    (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
   4393 		    (r = sshpkt_put_cstring(ssh, fwd->listen_path)) != 0 ||
   4394 		    (r = sshpkt_send(ssh)) != 0 ||
   4395 		    (r = ssh_packet_write_wait(ssh)) < 0)
   4396 			fatal_fr(r, "request streamlocal");
   4397 	} else {
   4398 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
   4399 		    (r = sshpkt_put_cstring(ssh, "tcpip-forward")) != 0 ||
   4400 		    (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
   4401 		    (r = sshpkt_put_cstring(ssh,
   4402 		    channel_rfwd_bind_host(fwd->listen_host))) != 0 ||
   4403 		    (r = sshpkt_put_u32(ssh, fwd->listen_port)) != 0 ||
   4404 		    (r = sshpkt_send(ssh)) != 0 ||
   4405 		    (r = ssh_packet_write_wait(ssh)) < 0)
   4406 			fatal_fr(r, "request tcpip-forward");
   4407 	}
   4408 	/* Assume that server accepts the request */
   4409 	success = 1;
   4410 	if (success) {
   4411 		/* Record that connection to this host/port is permitted. */
   4412 		host_to_connect = listen_host = listen_path = NULL;
   4413 		port_to_connect = listen_port = 0;
   4414 		if (fwd->connect_path != NULL) {
   4415 			host_to_connect = fwd->connect_path;
   4416 			port_to_connect = PORT_STREAMLOCAL;
   4417 		} else {
   4418 			host_to_connect = fwd->connect_host;
   4419 			port_to_connect = fwd->connect_port;
   4420 		}
   4421 		if (fwd->listen_path != NULL) {
   4422 			listen_path = fwd->listen_path;
   4423 			listen_port = PORT_STREAMLOCAL;
   4424 		} else {
   4425 			listen_host = fwd->listen_host;
   4426 			listen_port = fwd->listen_port;
   4427 		}
   4428 		idx = permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL,
   4429 		    host_to_connect, port_to_connect,
   4430 		    listen_host, listen_path, listen_port, NULL);
   4431 	}
   4432 	return idx;
   4433 }
   4434 
   4435 static int
   4436 open_match(struct permission *allowed_open, const char *requestedhost,
   4437     int requestedport)
   4438 {
   4439 	if (allowed_open->host_to_connect == NULL)
   4440 		return 0;
   4441 	if (allowed_open->port_to_connect != FWD_PERMIT_ANY_PORT &&
   4442 	    allowed_open->port_to_connect != requestedport)
   4443 		return 0;
   4444 	if (strcmp(allowed_open->host_to_connect, FWD_PERMIT_ANY_HOST) != 0 &&
   4445 	    strcmp(allowed_open->host_to_connect, requestedhost) != 0)
   4446 		return 0;
   4447 	return 1;
   4448 }
   4449 
   4450 /*
   4451  * Note that in the listen host/port case
   4452  * we don't support FWD_PERMIT_ANY_PORT and
   4453  * need to translate between the configured-host (listen_host)
   4454  * and what we've sent to the remote server (channel_rfwd_bind_host)
   4455  */
   4456 static int
   4457 open_listen_match_tcpip(struct permission *allowed_open,
   4458     const char *requestedhost, u_short requestedport, int translate)
   4459 {
   4460 	const char *allowed_host;
   4461 
   4462 	if (allowed_open->host_to_connect == NULL)
   4463 		return 0;
   4464 	if (allowed_open->listen_port != requestedport)
   4465 		return 0;
   4466 	if (!translate && allowed_open->listen_host == NULL &&
   4467 	    requestedhost == NULL)
   4468 		return 1;
   4469 	allowed_host = translate ?
   4470 	    channel_rfwd_bind_host(allowed_open->listen_host) :
   4471 	    allowed_open->listen_host;
   4472 	if (allowed_host == NULL || requestedhost == NULL ||
   4473 	    strcmp(allowed_host, requestedhost) != 0)
   4474 		return 0;
   4475 	return 1;
   4476 }
   4477 
   4478 static int
   4479 open_listen_match_streamlocal(struct permission *allowed_open,
   4480     const char *requestedpath)
   4481 {
   4482 	if (allowed_open->host_to_connect == NULL)
   4483 		return 0;
   4484 	if (allowed_open->listen_port != PORT_STREAMLOCAL)
   4485 		return 0;
   4486 	if (allowed_open->listen_path == NULL ||
   4487 	    strcmp(allowed_open->listen_path, requestedpath) != 0)
   4488 		return 0;
   4489 	return 1;
   4490 }
   4491 
   4492 /*
   4493  * Request cancellation of remote forwarding of connection host:port from
   4494  * local side.
   4495  */
   4496 static int
   4497 channel_request_rforward_cancel_tcpip(struct ssh *ssh,
   4498     const char *host, u_short port)
   4499 {
   4500 	struct ssh_channels *sc = ssh->chanctxt;
   4501 	struct permission_set *pset = &sc->local_perms;
   4502 	int r;
   4503 	u_int i;
   4504 	struct permission *perm = NULL;
   4505 
   4506 	for (i = 0; i < pset->num_permitted_user; i++) {
   4507 		perm = &pset->permitted_user[i];
   4508 		if (open_listen_match_tcpip(perm, host, port, 0))
   4509 			break;
   4510 		perm = NULL;
   4511 	}
   4512 	if (perm == NULL) {
   4513 		debug_f("requested forward not found");
   4514 		return -1;
   4515 	}
   4516 	if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
   4517 	    (r = sshpkt_put_cstring(ssh, "cancel-tcpip-forward")) != 0 ||
   4518 	    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
   4519 	    (r = sshpkt_put_cstring(ssh, channel_rfwd_bind_host(host))) != 0 ||
   4520 	    (r = sshpkt_put_u32(ssh, port)) != 0 ||
   4521 	    (r = sshpkt_send(ssh)) != 0)
   4522 		fatal_fr(r, "send cancel");
   4523 
   4524 	fwd_perm_clear(perm); /* unregister */
   4525 
   4526 	return 0;
   4527 }
   4528 
   4529 /*
   4530  * Request cancellation of remote forwarding of Unix domain socket
   4531  * path from local side.
   4532  */
   4533 static int
   4534 channel_request_rforward_cancel_streamlocal(struct ssh *ssh, const char *path)
   4535 {
   4536 	struct ssh_channels *sc = ssh->chanctxt;
   4537 	struct permission_set *pset = &sc->local_perms;
   4538 	int r;
   4539 	u_int i;
   4540 	struct permission *perm = NULL;
   4541 
   4542 	for (i = 0; i < pset->num_permitted_user; i++) {
   4543 		perm = &pset->permitted_user[i];
   4544 		if (open_listen_match_streamlocal(perm, path))
   4545 			break;
   4546 		perm = NULL;
   4547 	}
   4548 	if (perm == NULL) {
   4549 		debug_f("requested forward not found");
   4550 		return -1;
   4551 	}
   4552 	if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
   4553 	    (r = sshpkt_put_cstring(ssh,
   4554 	    "cancel-streamlocal-forward (at) openssh.com")) != 0 ||
   4555 	    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
   4556 	    (r = sshpkt_put_cstring(ssh, path)) != 0 ||
   4557 	    (r = sshpkt_send(ssh)) != 0)
   4558 		fatal_fr(r, "send cancel");
   4559 
   4560 	fwd_perm_clear(perm); /* unregister */
   4561 
   4562 	return 0;
   4563 }
   4564 
   4565 /*
   4566  * Request cancellation of remote forwarding of a connection from local side.
   4567  */
   4568 int
   4569 channel_request_rforward_cancel(struct ssh *ssh, struct Forward *fwd)
   4570 {
   4571 	if (fwd->listen_path != NULL) {
   4572 		return channel_request_rforward_cancel_streamlocal(ssh,
   4573 		    fwd->listen_path);
   4574 	} else {
   4575 		return channel_request_rforward_cancel_tcpip(ssh,
   4576 		    fwd->listen_host,
   4577 		    fwd->listen_port ? fwd->listen_port : fwd->allocated_port);
   4578 	}
   4579 }
   4580 
   4581 /*
   4582  * Permits opening to any host/port if permitted_user[] is empty.  This is
   4583  * usually called by the server, because the user could connect to any port
   4584  * anyway, and the server has no way to know but to trust the client anyway.
   4585  */
   4586 void
   4587 channel_permit_all(struct ssh *ssh, int where)
   4588 {
   4589 	struct permission_set *pset = permission_set_get(ssh, where);
   4590 
   4591 	if (pset->num_permitted_user == 0)
   4592 		pset->all_permitted = 1;
   4593 }
   4594 
   4595 /*
   4596  * Permit the specified host/port for forwarding.
   4597  */
   4598 void
   4599 channel_add_permission(struct ssh *ssh, int who, int where,
   4600     char *host, int port)
   4601 {
   4602 	int local = where == FORWARD_LOCAL;
   4603 	struct permission_set *pset = permission_set_get(ssh, where);
   4604 
   4605 	debug("allow %s forwarding to host %s port %d",
   4606 	    fwd_ident(who, where), host, port);
   4607 	/*
   4608 	 * Remote forwards set listen_host/port, local forwards set
   4609 	 * host/port_to_connect.
   4610 	 */
   4611 	permission_set_add(ssh, who, where,
   4612 	    local ? host : NULL, local ? port : 0,
   4613 	    local ? NULL : host, NULL, local ? 0 : port, NULL);
   4614 	pset->all_permitted = 0;
   4615 }
   4616 
   4617 /*
   4618  * Administratively disable forwarding.
   4619  */
   4620 void
   4621 channel_disable_admin(struct ssh *ssh, int where)
   4622 {
   4623 	channel_clear_permission(ssh, FORWARD_ADM, where);
   4624 	permission_set_add(ssh, FORWARD_ADM, where,
   4625 	    NULL, 0, NULL, NULL, 0, NULL);
   4626 }
   4627 
   4628 /*
   4629  * Clear a list of permitted opens.
   4630  */
   4631 void
   4632 channel_clear_permission(struct ssh *ssh, int who, int where)
   4633 {
   4634 	struct permission **permp;
   4635 	u_int i, *npermp;
   4636 
   4637 	permission_set_get_array(ssh, who, where, &permp, &npermp);
   4638 	for (i = 0; i < *npermp; i++)
   4639 		fwd_perm_clear((*permp) + i);
   4640 	free(*permp);
   4641 	*permp = NULL;
   4642 	*npermp = 0;
   4643 }
   4644 
   4645 /*
   4646  * Update the listen port for a dynamic remote forward, after
   4647  * the actual 'newport' has been allocated. If 'newport' < 0 is
   4648  * passed then they entry will be invalidated.
   4649  */
   4650 void
   4651 channel_update_permission(struct ssh *ssh, int idx, int newport)
   4652 {
   4653 	struct permission_set *pset = &ssh->chanctxt->local_perms;
   4654 
   4655 	if (idx < 0 || (u_int)idx >= pset->num_permitted_user) {
   4656 		debug_f("index out of range: %d num_permitted_user %d",
   4657 		    idx, pset->num_permitted_user);
   4658 		return;
   4659 	}
   4660 	debug("%s allowed port %d for forwarding to host %s port %d",
   4661 	    newport > 0 ? "Updating" : "Removing",
   4662 	    newport,
   4663 	    pset->permitted_user[idx].host_to_connect,
   4664 	    pset->permitted_user[idx].port_to_connect);
   4665 	if (newport <= 0)
   4666 		fwd_perm_clear(&pset->permitted_user[idx]);
   4667 	else {
   4668 		pset->permitted_user[idx].listen_port =
   4669 		    (ssh->compat & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
   4670 	}
   4671 }
   4672 
   4673 /* Try to start non-blocking connect to next host in cctx list */
   4674 static int
   4675 connect_next(struct channel_connect *cctx)
   4676 {
   4677 	int sock, saved_errno;
   4678 	struct sockaddr_un *sunaddr;
   4679 	char ntop[NI_MAXHOST];
   4680 	char strport[MAXIMUM(NI_MAXSERV, sizeof(sunaddr->sun_path))];
   4681 
   4682 	for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
   4683 		switch (cctx->ai->ai_family) {
   4684 		case AF_UNIX:
   4685 			/* unix:pathname instead of host:port */
   4686 			sunaddr = (struct sockaddr_un *)cctx->ai->ai_addr;
   4687 			strlcpy(ntop, "unix", sizeof(ntop));
   4688 			strlcpy(strport, sunaddr->sun_path, sizeof(strport));
   4689 			break;
   4690 		case AF_INET:
   4691 		case AF_INET6:
   4692 			if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
   4693 			    ntop, sizeof(ntop), strport, sizeof(strport),
   4694 			    NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
   4695 				error_f("getnameinfo failed");
   4696 				continue;
   4697 			}
   4698 			break;
   4699 		default:
   4700 			continue;
   4701 		}
   4702 		debug_f("start for host %.100s ([%.100s]:%s)",
   4703 		    cctx->host, ntop, strport);
   4704 		if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
   4705 		    cctx->ai->ai_protocol)) == -1) {
   4706 			if (cctx->ai->ai_next == NULL)
   4707 				error("socket: %.100s", strerror(errno));
   4708 			else
   4709 				verbose("socket: %.100s", strerror(errno));
   4710 			continue;
   4711 		}
   4712 		if (set_nonblock(sock) == -1)
   4713 			fatal_f("set_nonblock(%d)", sock);
   4714 		if (connect(sock, cctx->ai->ai_addr,
   4715 		    cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
   4716 			debug_f("host %.100s ([%.100s]:%s): %.100s",
   4717 			    cctx->host, ntop, strport, strerror(errno));
   4718 			saved_errno = errno;
   4719 			close(sock);
   4720 			errno = saved_errno;
   4721 			continue;	/* fail -- try next */
   4722 		}
   4723 		if (cctx->ai->ai_family != AF_UNIX)
   4724 			set_nodelay(sock);
   4725 		debug_f("connect host %.100s ([%.100s]:%s) in progress, fd=%d",
   4726 		    cctx->host, ntop, strport, sock);
   4727 		cctx->ai = cctx->ai->ai_next;
   4728 		return sock;
   4729 	}
   4730 	return -1;
   4731 }
   4732 
   4733 static void
   4734 channel_connect_ctx_free(struct channel_connect *cctx)
   4735 {
   4736 	free(cctx->host);
   4737 	if (cctx->aitop) {
   4738 		if (cctx->aitop->ai_family == AF_UNIX)
   4739 			free(cctx->aitop);
   4740 		else
   4741 			freeaddrinfo(cctx->aitop);
   4742 	}
   4743 	memset(cctx, 0, sizeof(*cctx));
   4744 }
   4745 
   4746 /*
   4747  * Return connecting socket to remote host:port or local socket path,
   4748  * passing back the failure reason if appropriate.
   4749  */
   4750 static int
   4751 connect_to_helper(struct ssh *ssh, const char *name, int port, int socktype,
   4752     const char *ctype, const char *rname, struct channel_connect *cctx,
   4753     int *reason, const char **errmsg)
   4754 {
   4755 	struct addrinfo hints;
   4756 	int gaierr;
   4757 	int sock = -1;
   4758 	char strport[NI_MAXSERV];
   4759 
   4760 	if (port == PORT_STREAMLOCAL) {
   4761 		struct sockaddr_un *sunaddr;
   4762 		struct addrinfo *ai;
   4763 
   4764 		if (strlen(name) > sizeof(sunaddr->sun_path)) {
   4765 			error("%.100s: %.100s", name, strerror(ENAMETOOLONG));
   4766 			return -1;
   4767 		}
   4768 
   4769 		/*
   4770 		 * Fake up a struct addrinfo for AF_UNIX connections.
   4771 		 * channel_connect_ctx_free() must check ai_family
   4772 		 * and use free() not freeaddrinfo() for AF_UNIX.
   4773 		 */
   4774 		ai = xcalloc(1, sizeof(*ai) + sizeof(*sunaddr));
   4775 		ai->ai_addr = (struct sockaddr *)(ai + 1);
   4776 		ai->ai_addrlen = sizeof(*sunaddr);
   4777 		ai->ai_family = AF_UNIX;
   4778 		ai->ai_socktype = socktype;
   4779 		ai->ai_protocol = PF_UNSPEC;
   4780 		sunaddr = (struct sockaddr_un *)ai->ai_addr;
   4781 		sunaddr->sun_family = AF_UNIX;
   4782 		strlcpy(sunaddr->sun_path, name, sizeof(sunaddr->sun_path));
   4783 		cctx->aitop = ai;
   4784 	} else {
   4785 		memset(&hints, 0, sizeof(hints));
   4786 		hints.ai_family = ssh->chanctxt->IPv4or6;
   4787 		hints.ai_socktype = socktype;
   4788 		snprintf(strport, sizeof strport, "%d", port);
   4789 		if ((gaierr = getaddrinfo(name, strport, &hints, &cctx->aitop))
   4790 		    != 0) {
   4791 			if (errmsg != NULL)
   4792 				*errmsg = ssh_gai_strerror(gaierr);
   4793 			if (reason != NULL)
   4794 				*reason = SSH2_OPEN_CONNECT_FAILED;
   4795 			error("connect_to %.100s: unknown host (%s)", name,
   4796 			    ssh_gai_strerror(gaierr));
   4797 			return -1;
   4798 		}
   4799 	}
   4800 
   4801 	cctx->host = xstrdup(name);
   4802 	cctx->port = port;
   4803 	cctx->ai = cctx->aitop;
   4804 
   4805 	if ((sock = connect_next(cctx)) == -1) {
   4806 		error("connect to %.100s port %d failed: %s",
   4807 		    name, port, strerror(errno));
   4808 		return -1;
   4809 	}
   4810 
   4811 	return sock;
   4812 }
   4813 
   4814 /* Return CONNECTING channel to remote host:port or local socket path */
   4815 static Channel *
   4816 connect_to(struct ssh *ssh, const char *host, int port,
   4817     const char *ctype, const char *rname)
   4818 {
   4819 	struct channel_connect cctx;
   4820 	Channel *c;
   4821 	int sock;
   4822 
   4823 	memset(&cctx, 0, sizeof(cctx));
   4824 	sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
   4825 	    &cctx, NULL, NULL);
   4826 	if (sock == -1) {
   4827 		channel_connect_ctx_free(&cctx);
   4828 		return NULL;
   4829 	}
   4830 	c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
   4831 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
   4832 	c->host_port = port;
   4833 	c->path = xstrdup(host);
   4834 	c->connect_ctx = cctx;
   4835 
   4836 	return c;
   4837 }
   4838 
   4839 /*
   4840  * returns either the newly connected channel or the downstream channel
   4841  * that needs to deal with this connection.
   4842  */
   4843 Channel *
   4844 channel_connect_by_listen_address(struct ssh *ssh, const char *listen_host,
   4845     u_short listen_port, const char *ctype, const char *rname)
   4846 {
   4847 	struct ssh_channels *sc = ssh->chanctxt;
   4848 	struct permission_set *pset = &sc->local_perms;
   4849 	u_int i;
   4850 	struct permission *perm;
   4851 
   4852 	for (i = 0; i < pset->num_permitted_user; i++) {
   4853 		perm = &pset->permitted_user[i];
   4854 		if (open_listen_match_tcpip(perm,
   4855 		    listen_host, listen_port, 1)) {
   4856 			if (perm->downstream)
   4857 				return perm->downstream;
   4858 			if (perm->port_to_connect == 0)
   4859 				return rdynamic_connect_prepare(ssh,
   4860 				    ctype, rname);
   4861 			return connect_to(ssh,
   4862 			    perm->host_to_connect, perm->port_to_connect,
   4863 			    ctype, rname);
   4864 		}
   4865 	}
   4866 	error("WARNING: Server requests forwarding for unknown listen_port %d",
   4867 	    listen_port);
   4868 	return NULL;
   4869 }
   4870 
   4871 Channel *
   4872 channel_connect_by_listen_path(struct ssh *ssh, const char *path,
   4873     const char *ctype, const char *rname)
   4874 {
   4875 	struct ssh_channels *sc = ssh->chanctxt;
   4876 	struct permission_set *pset = &sc->local_perms;
   4877 	u_int i;
   4878 	struct permission *perm;
   4879 
   4880 	for (i = 0; i < pset->num_permitted_user; i++) {
   4881 		perm = &pset->permitted_user[i];
   4882 		if (open_listen_match_streamlocal(perm, path)) {
   4883 			return connect_to(ssh,
   4884 			    perm->host_to_connect, perm->port_to_connect,
   4885 			    ctype, rname);
   4886 		}
   4887 	}
   4888 	error("WARNING: Server requests forwarding for unknown path %.100s",
   4889 	    path);
   4890 	return NULL;
   4891 }
   4892 
   4893 /* Check if connecting to that port is permitted and connect. */
   4894 Channel *
   4895 channel_connect_to_port(struct ssh *ssh, const char *host, u_short port,
   4896     const char *ctype, const char *rname, int *reason, const char **errmsg)
   4897 {
   4898 	struct ssh_channels *sc = ssh->chanctxt;
   4899 	struct permission_set *pset = &sc->local_perms;
   4900 	struct channel_connect cctx;
   4901 	Channel *c;
   4902 	u_int i, permit, permit_adm = 1;
   4903 	int sock;
   4904 	struct permission *perm;
   4905 
   4906 	permit = pset->all_permitted;
   4907 	if (!permit) {
   4908 		for (i = 0; i < pset->num_permitted_user; i++) {
   4909 			perm = &pset->permitted_user[i];
   4910 			if (open_match(perm, host, port)) {
   4911 				permit = 1;
   4912 				break;
   4913 			}
   4914 		}
   4915 	}
   4916 
   4917 	if (pset->num_permitted_admin > 0) {
   4918 		permit_adm = 0;
   4919 		for (i = 0; i < pset->num_permitted_admin; i++) {
   4920 			perm = &pset->permitted_admin[i];
   4921 			if (open_match(perm, host, port)) {
   4922 				permit_adm = 1;
   4923 				break;
   4924 			}
   4925 		}
   4926 	}
   4927 
   4928 	if (!permit || !permit_adm) {
   4929 		logit("Received request from %.100s port %d to connect to "
   4930 		    "host %.100s port %d, but the request was denied.",
   4931 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), host, port);
   4932 		if (reason != NULL)
   4933 			*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
   4934 		return NULL;
   4935 	}
   4936 
   4937 	memset(&cctx, 0, sizeof(cctx));
   4938 	sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
   4939 	    &cctx, reason, errmsg);
   4940 	if (sock == -1) {
   4941 		channel_connect_ctx_free(&cctx);
   4942 		return NULL;
   4943 	}
   4944 
   4945 	c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
   4946 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
   4947 	c->host_port = port;
   4948 	c->path = xstrdup(host);
   4949 	c->connect_ctx = cctx;
   4950 
   4951 	return c;
   4952 }
   4953 
   4954 /* Check if connecting to that path is permitted and connect. */
   4955 Channel *
   4956 channel_connect_to_path(struct ssh *ssh, const char *path, const char *ctype,
   4957     const char *rname)
   4958 {
   4959 	struct ssh_channels *sc = ssh->chanctxt;
   4960 	struct permission_set *pset = &sc->local_perms;
   4961 	u_int i, permit, permit_adm = 1;
   4962 	struct permission *perm;
   4963 
   4964 	permit = pset->all_permitted;
   4965 	if (!permit) {
   4966 		for (i = 0; i < pset->num_permitted_user; i++) {
   4967 			perm = &pset->permitted_user[i];
   4968 			if (open_match(perm, path, PORT_STREAMLOCAL)) {
   4969 				permit = 1;
   4970 				break;
   4971 			}
   4972 		}
   4973 	}
   4974 
   4975 	if (pset->num_permitted_admin > 0) {
   4976 		permit_adm = 0;
   4977 		for (i = 0; i < pset->num_permitted_admin; i++) {
   4978 			perm = &pset->permitted_admin[i];
   4979 			if (open_match(perm, path, PORT_STREAMLOCAL)) {
   4980 				permit_adm = 1;
   4981 				break;
   4982 			}
   4983 		}
   4984 	}
   4985 
   4986 	if (!permit || !permit_adm) {
   4987 		logit("Received request to connect to path %.100s, "
   4988 		    "but the request was denied.", path);
   4989 		return NULL;
   4990 	}
   4991 	return connect_to(ssh, path, PORT_STREAMLOCAL, ctype, rname);
   4992 }
   4993 
   4994 void
   4995 channel_send_window_changes(struct ssh *ssh)
   4996 {
   4997 	struct ssh_channels *sc = ssh->chanctxt;
   4998 	struct winsize ws;
   4999 	int r;
   5000 	u_int i;
   5001 
   5002 	for (i = 0; i < sc->channels_alloc; i++) {
   5003 		if (sc->channels[i] == NULL || !sc->channels[i]->client_tty ||
   5004 		    sc->channels[i]->type != SSH_CHANNEL_OPEN)
   5005 			continue;
   5006 		if (ioctl(sc->channels[i]->rfd, TIOCGWINSZ, &ws) == -1)
   5007 			continue;
   5008 		channel_request_start(ssh, i, "window-change", 0);
   5009 		if ((r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
   5010 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
   5011 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
   5012 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0 ||
   5013 		    (r = sshpkt_send(ssh)) != 0)
   5014 			fatal_fr(r, "channel %u; send window-change", i);
   5015 	}
   5016 }
   5017 
   5018 /* Return RDYNAMIC_OPEN channel: channel allows SOCKS, but is not connected */
   5019 static Channel *
   5020 rdynamic_connect_prepare(struct ssh *ssh, const char *ctype, const char *rname)
   5021 {
   5022 	Channel *c;
   5023 	int r;
   5024 
   5025 	c = channel_new(ssh, ctype, SSH_CHANNEL_RDYNAMIC_OPEN, -1, -1, -1,
   5026 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
   5027 	c->host_port = 0;
   5028 	c->path = NULL;
   5029 
   5030 	/*
   5031 	 * We need to open the channel before we have a FD,
   5032 	 * so that we can get SOCKS header from peer.
   5033 	 */
   5034 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
   5035 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
   5036 	    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
   5037 	    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
   5038 	    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0)
   5039 		fatal_fr(r, "channel %i; confirm", c->self);
   5040 	return c;
   5041 }
   5042 
   5043 /* Return CONNECTING socket to remote host:port or local socket path */
   5044 static int
   5045 rdynamic_connect_finish(struct ssh *ssh, Channel *c)
   5046 {
   5047 	struct ssh_channels *sc = ssh->chanctxt;
   5048 	struct permission_set *pset = &sc->local_perms;
   5049 	struct permission *perm;
   5050 	struct channel_connect cctx;
   5051 	u_int i, permit_adm = 1;
   5052 	int sock;
   5053 
   5054 	if (pset->num_permitted_admin > 0) {
   5055 		permit_adm = 0;
   5056 		for (i = 0; i < pset->num_permitted_admin; i++) {
   5057 			perm = &pset->permitted_admin[i];
   5058 			if (open_match(perm, c->path, c->host_port)) {
   5059 				permit_adm = 1;
   5060 				break;
   5061 			}
   5062 		}
   5063 	}
   5064 	if (!permit_adm) {
   5065 		debug_f("requested forward not permitted");
   5066 		return -1;
   5067 	}
   5068 
   5069 	memset(&cctx, 0, sizeof(cctx));
   5070 	sock = connect_to_helper(ssh, c->path, c->host_port, SOCK_STREAM, NULL,
   5071 	    NULL, &cctx, NULL, NULL);
   5072 	if (sock == -1)
   5073 		channel_connect_ctx_free(&cctx);
   5074 	else {
   5075 		/* similar to SSH_CHANNEL_CONNECTING but we've already sent the open */
   5076 		c->type = SSH_CHANNEL_RDYNAMIC_FINISH;
   5077 		c->connect_ctx = cctx;
   5078 		channel_register_fds(ssh, c, sock, sock, -1, 0, 1, 0);
   5079 	}
   5080 	return sock;
   5081 }
   5082 
   5083 /* -- X11 forwarding */
   5084 
   5085 /*
   5086  * Creates an internet domain socket for listening for X11 connections.
   5087  * Returns 0 and a suitable display number for the DISPLAY variable
   5088  * stored in display_numberp , or -1 if an error occurs.
   5089  */
   5090 int
   5091 x11_create_display_inet(struct ssh *ssh, int x11_display_offset,
   5092     int x11_use_localhost, int single_connection,
   5093     u_int *display_numberp, int **chanids)
   5094 {
   5095 	Channel *nc = NULL;
   5096 	int display_number, sock, port;
   5097 	struct addrinfo hints, *ai, *aitop;
   5098 	char strport[NI_MAXSERV];
   5099 	int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
   5100 
   5101 	if (chanids == NULL || x11_display_offset < 0 ||
   5102 	    x11_display_offset > UINT16_MAX - X11_BASE_PORT - MAX_DISPLAYS)
   5103 		return -1;
   5104 
   5105 	for (display_number = x11_display_offset;
   5106 	    display_number < x11_display_offset + MAX_DISPLAYS;
   5107 	    display_number++) {
   5108 		port = X11_BASE_PORT + display_number;
   5109 		memset(&hints, 0, sizeof(hints));
   5110 		hints.ai_family = ssh->chanctxt->IPv4or6;
   5111 		hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
   5112 		hints.ai_socktype = SOCK_STREAM;
   5113 		snprintf(strport, sizeof strport, "%d", port);
   5114 		if ((gaierr = getaddrinfo(NULL, strport,
   5115 		    &hints, &aitop)) != 0) {
   5116 			error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
   5117 			return -1;
   5118 		}
   5119 		for (ai = aitop; ai; ai = ai->ai_next) {
   5120 			if (ai->ai_family != AF_INET &&
   5121 			    ai->ai_family != AF_INET6)
   5122 				continue;
   5123 			sock = socket(ai->ai_family, ai->ai_socktype,
   5124 			    ai->ai_protocol);
   5125 			if (sock == -1) {
   5126 				error("socket: %.100s", strerror(errno));
   5127 				freeaddrinfo(aitop);
   5128 				return -1;
   5129 			}
   5130 			set_reuseaddr(sock);
   5131 			if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
   5132 				debug2_f("bind port %d: %.100s", port,
   5133 				    strerror(errno));
   5134 				close(sock);
   5135 				for (n = 0; n < num_socks; n++)
   5136 					close(socks[n]);
   5137 				num_socks = 0;
   5138 				break;
   5139 			}
   5140 			socks[num_socks++] = sock;
   5141 			if (num_socks == NUM_SOCKS)
   5142 				break;
   5143 		}
   5144 		freeaddrinfo(aitop);
   5145 		if (num_socks > 0)
   5146 			break;
   5147 	}
   5148 	if (display_number >= x11_display_offset + MAX_DISPLAYS) {
   5149 		error("Failed to allocate internet-domain X11 display socket.");
   5150 		return -1;
   5151 	}
   5152 	/* Start listening for connections on the socket. */
   5153 	for (n = 0; n < num_socks; n++) {
   5154 		sock = socks[n];
   5155 		if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
   5156 			error("listen: %.100s", strerror(errno));
   5157 			close(sock);
   5158 			return -1;
   5159 		}
   5160 	}
   5161 
   5162 	/* Allocate a channel for each socket. */
   5163 	*chanids = xcalloc(num_socks + 1, sizeof(**chanids));
   5164 	for (n = 0; n < num_socks; n++) {
   5165 		sock = socks[n];
   5166 		/* Is this really necassary? */
   5167 		if (hpn_disabled)
   5168 		nc = channel_new(ssh, "x11-listener",
   5169 		    SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
   5170 		    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
   5171 		    0, "X11 inet listener", 1);
   5172 		else
   5173 			nc = channel_new(ssh, "x11 listener",
   5174 			    SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
   5175 			    hpn_buffer_size, CHAN_X11_PACKET_DEFAULT,
   5176 			    0, "X11 inet listener", 1);
   5177 		nc->single_connection = single_connection;
   5178 		(*chanids)[n] = nc->self;
   5179 	}
   5180 	(*chanids)[n] = -1;
   5181 
   5182 	/* Return the display number for the DISPLAY environment variable. */
   5183 	*display_numberp = display_number;
   5184 	return 0;
   5185 }
   5186 
   5187 static int
   5188 connect_local_xsocket(u_int dnr)
   5189 {
   5190 	int sock;
   5191 	struct sockaddr_un addr;
   5192 
   5193 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
   5194 	if (sock == -1)
   5195 		error("socket: %.100s", strerror(errno));
   5196 	memset(&addr, 0, sizeof(addr));
   5197 	addr.sun_family = AF_UNIX;
   5198 	snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
   5199 	if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
   5200 		return sock;
   5201 	close(sock);
   5202 	error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
   5203 	return -1;
   5204 }
   5205 
   5206 int
   5207 x11_connect_display(struct ssh *ssh)
   5208 {
   5209 	u_int display_number;
   5210 	const char *display;
   5211 	char buf[1024], *cp;
   5212 	struct addrinfo hints, *ai, *aitop;
   5213 	char strport[NI_MAXSERV];
   5214 	int gaierr, sock = 0;
   5215 
   5216 	/* Try to open a socket for the local X server. */
   5217 	display = getenv("DISPLAY");
   5218 	if (!display) {
   5219 		error("DISPLAY not set.");
   5220 		return -1;
   5221 	}
   5222 	/*
   5223 	 * Now we decode the value of the DISPLAY variable and make a
   5224 	 * connection to the real X server.
   5225 	 */
   5226 
   5227 	/*
   5228 	 * Check if it is a unix domain socket.  Unix domain displays are in
   5229 	 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
   5230 	 */
   5231 	if (strncmp(display, "unix:", 5) == 0 ||
   5232 	    display[0] == ':') {
   5233 		/* Connect to the unix domain socket. */
   5234 		if (sscanf(strrchr(display, ':') + 1, "%u",
   5235 		    &display_number) != 1) {
   5236 			error("Could not parse display number from DISPLAY: "
   5237 			    "%.100s", display);
   5238 			return -1;
   5239 		}
   5240 		/* Create a socket. */
   5241 		sock = connect_local_xsocket(display_number);
   5242 		if (sock < 0)
   5243 			return -1;
   5244 
   5245 		/* OK, we now have a connection to the display. */
   5246 		return sock;
   5247 	}
   5248 	/*
   5249 	 * Connect to an inet socket.  The DISPLAY value is supposedly
   5250 	 * hostname:d[.s], where hostname may also be numeric IP address.
   5251 	 */
   5252 	strlcpy(buf, display, sizeof(buf));
   5253 	cp = strchr(buf, ':');
   5254 	if (!cp) {
   5255 		error("Could not find ':' in DISPLAY: %.100s", display);
   5256 		return -1;
   5257 	}
   5258 	*cp = 0;
   5259 	/*
   5260 	 * buf now contains the host name.  But first we parse the
   5261 	 * display number.
   5262 	 */
   5263 	if (sscanf(cp + 1, "%u", &display_number) != 1 ||
   5264 	    display_number > UINT16_MAX - X11_BASE_PORT) {
   5265 		error("Could not parse display number from DISPLAY: %.100s",
   5266 		    display);
   5267 		return -1;
   5268 	}
   5269 
   5270 	/* Look up the host address */
   5271 	memset(&hints, 0, sizeof(hints));
   5272 	hints.ai_family = ssh->chanctxt->IPv4or6;
   5273 	hints.ai_socktype = SOCK_STREAM;
   5274 	snprintf(strport, sizeof strport, "%u", X11_BASE_PORT + display_number);
   5275 	if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
   5276 		error("%.100s: unknown host. (%s)", buf,
   5277 		ssh_gai_strerror(gaierr));
   5278 		return -1;
   5279 	}
   5280 	for (ai = aitop; ai; ai = ai->ai_next) {
   5281 		/* Create a socket. */
   5282 		sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
   5283 		if (sock == -1) {
   5284 			debug2("socket: %.100s", strerror(errno));
   5285 			continue;
   5286 		}
   5287 		/* Connect it to the display. */
   5288 		if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
   5289 			debug2("connect %.100s port %u: %.100s", buf,
   5290 			    X11_BASE_PORT + display_number, strerror(errno));
   5291 			close(sock);
   5292 			continue;
   5293 		}
   5294 		/* Success */
   5295 		break;
   5296 	}
   5297 	freeaddrinfo(aitop);
   5298 	if (!ai) {
   5299 		error("connect %.100s port %u: %.100s", buf,
   5300 		    X11_BASE_PORT + display_number, strerror(errno));
   5301 		return -1;
   5302 	}
   5303 	set_nodelay(sock);
   5304 	return sock;
   5305 }
   5306 
   5307 /*
   5308  * Requests forwarding of X11 connections, generates fake authentication
   5309  * data, and enables authentication spoofing.
   5310  * This should be called in the client only.
   5311  */
   5312 void
   5313 x11_request_forwarding_with_spoofing(struct ssh *ssh, int client_session_id,
   5314     const char *disp, const char *proto, const char *data, int want_reply)
   5315 {
   5316 	struct ssh_channels *sc = ssh->chanctxt;
   5317 	u_int data_len = (u_int) strlen(data) / 2;
   5318 	u_int i, value;
   5319 	const char *cp;
   5320 	char *new_data;
   5321 	int r, screen_number;
   5322 
   5323 	if (sc->x11_saved_display == NULL)
   5324 		sc->x11_saved_display = xstrdup(disp);
   5325 	else if (strcmp(disp, sc->x11_saved_display) != 0) {
   5326 		error("x11_request_forwarding_with_spoofing: different "
   5327 		    "$DISPLAY already forwarded");
   5328 		return;
   5329 	}
   5330 
   5331 	cp = strchr(disp, ':');
   5332 	if (cp)
   5333 		cp = strchr(cp, '.');
   5334 	if (cp)
   5335 		screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
   5336 	else
   5337 		screen_number = 0;
   5338 
   5339 	if (sc->x11_saved_proto == NULL) {
   5340 		/* Save protocol name. */
   5341 		sc->x11_saved_proto = xstrdup(proto);
   5342 
   5343 		/* Extract real authentication data. */
   5344 		sc->x11_saved_data = xmalloc(data_len);
   5345 		for (i = 0; i < data_len; i++) {
   5346 			if (sscanf(data + 2 * i, "%2x", &value) != 1) {
   5347 				fatal("x11_request_forwarding: bad "
   5348 				    "authentication data: %.100s", data);
   5349 			}
   5350 			sc->x11_saved_data[i] = value;
   5351 		}
   5352 		sc->x11_saved_data_len = data_len;
   5353 
   5354 		/* Generate fake data of the same length. */
   5355 		sc->x11_fake_data = xmalloc(data_len);
   5356 		arc4random_buf(sc->x11_fake_data, data_len);
   5357 		sc->x11_fake_data_len = data_len;
   5358 	}
   5359 
   5360 	/* Convert the fake data into hex. */
   5361 	new_data = tohex(sc->x11_fake_data, data_len);
   5362 
   5363 	/* Send the request packet. */
   5364 	channel_request_start(ssh, client_session_id, "x11-req", want_reply);
   5365 	if ((r = sshpkt_put_u8(ssh, 0)) != 0 || /* bool: single connection */
   5366 	    (r = sshpkt_put_cstring(ssh, proto)) != 0 ||
   5367 	    (r = sshpkt_put_cstring(ssh, new_data)) != 0 ||
   5368 	    (r = sshpkt_put_u32(ssh, screen_number)) != 0 ||
   5369 	    (r = sshpkt_send(ssh)) != 0 ||
   5370 	    (r = ssh_packet_write_wait(ssh)) < 0)
   5371 		fatal_fr(r, "send x11-req");
   5372 	free(new_data);
   5373 }
   5374 
   5375 /*
   5376  * Returns whether an x11 channel was used recently (less than a second ago)
   5377  */
   5378 int
   5379 x11_channel_used_recently(struct ssh *ssh) {
   5380 	u_int i;
   5381 	Channel *c;
   5382 	time_t lastused = 0;
   5383 
   5384 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
   5385 		c = ssh->chanctxt->channels[i];
   5386 		if (c == NULL || c->ctype == NULL || c->lastused == 0 ||
   5387 		    strcmp(c->ctype, "x11-connection") != 0)
   5388 			continue;
   5389 		if (c->lastused > lastused)
   5390 			lastused = c->lastused;
   5391 	}
   5392 	return lastused != 0 && monotime() <= lastused + 1;
   5393 }
   5394