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