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