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