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