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