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