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