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