xref: /titanic_41/usr/src/cmd/ssh/libssh/common/channels.c (revision a38dd497aa503e9d80665c24b521fee255609df4)
1 /*
2  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  */
5 /*
6  * Author: Tatu Ylonen <ylo@cs.hut.fi>
7  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
8  *                    All rights reserved
9  * This file contains functions for generic socket connection forwarding.
10  * There is also code for initiating connection forwarding for X11 connections,
11  * arbitrary tcp/ip connections, and the authentication agent connection.
12  *
13  * As far as I am concerned, the code I have written for this software
14  * can be used freely for any purpose.  Any derived versions of this
15  * software must be clearly marked as such, and if the derived work is
16  * incompatible with the protocol description in the RFC file, it must be
17  * called by a name other than "ssh" or "Secure Shell".
18  *
19  * SSH2 support added by Markus Friedl.
20  * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl.  All rights reserved.
21  * Copyright (c) 1999 Dug Song.  All rights reserved.
22  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
23  *
24  * Redistribution and use in source and binary forms, with or without
25  * modification, are permitted provided that the following conditions
26  * are met:
27  * 1. Redistributions of source code must retain the above copyright
28  *    notice, this list of conditions and the following disclaimer.
29  * 2. Redistributions in binary form must reproduce the above copyright
30  *    notice, this list of conditions and the following disclaimer in the
31  *    documentation and/or other materials provided with the distribution.
32  *
33  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
34  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
36  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
37  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
39  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
40  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
42  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43  */
44 
45 #include "includes.h"
46 RCSID("$OpenBSD: channels.c,v 1.183 2002/09/17 07:47:02 itojun Exp $");
47 
48 #pragma ident	"%Z%%M%	%I%	%E% SMI"
49 
50 #include "ssh.h"
51 #include "ssh1.h"
52 #include "ssh2.h"
53 #include "packet.h"
54 #include "xmalloc.h"
55 #include "log.h"
56 #include "misc.h"
57 #include "channels.h"
58 #include "compat.h"
59 #include "canohost.h"
60 #include "key.h"
61 #include "authfd.h"
62 #include "pathnames.h"
63 #include "bufaux.h"
64 
65 
66 /* -- channel core */
67 
68 /*
69  * Pointer to an array containing all allocated channels.  The array is
70  * dynamically extended as needed.
71  */
72 static Channel **channels = NULL;
73 
74 /*
75  * Size of the channel array.  All slots of the array must always be
76  * initialized (at least the type field); unused slots set to NULL
77  */
78 static int channels_alloc = 0;
79 
80 /*
81  * Maximum file descriptor value used in any of the channels.  This is
82  * updated in channel_new.
83  */
84 static int channel_max_fd = 0;
85 
86 
87 /* -- tcp forwarding */
88 
89 /*
90  * Data structure for storing which hosts are permitted for forward requests.
91  * The local sides of any remote forwards are stored in this array to prevent
92  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
93  * network (which might be behind a firewall).
94  */
95 typedef struct {
96 	char *host_to_connect;		/* Connect to 'host'. */
97 	u_short port_to_connect;	/* Connect to 'port'. */
98 	u_short listen_port;		/* Remote side should listen port number. */
99 } ForwardPermission;
100 
101 /* List of all permitted host/port pairs to connect. */
102 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
103 
104 /* Number of permitted host/port pairs in the array. */
105 static int num_permitted_opens = 0;
106 /*
107  * If this is true, all opens are permitted.  This is the case on the server
108  * on which we have to trust the client anyway, and the user could do
109  * anything after logging in anyway.
110  */
111 static int all_opens_permitted = 0;
112 
113 
114 /* -- X11 forwarding */
115 
116 /* Maximum number of fake X11 displays to try. */
117 #define MAX_DISPLAYS  1000
118 
119 /* Saved X11 authentication protocol name. */
120 static char *x11_saved_proto = NULL;
121 
122 /* Saved X11 authentication data.  This is the real data. */
123 static char *x11_saved_data = NULL;
124 static u_int x11_saved_data_len = 0;
125 
126 /*
127  * Fake X11 authentication data.  This is what the server will be sending us;
128  * we should replace any occurrences of this by the real data.
129  */
130 static u_char *x11_fake_data = NULL;
131 static u_int x11_fake_data_len;
132 
133 
134 /* -- agent forwarding */
135 
136 #define	NUM_SOCKS	10
137 
138 /* AF_UNSPEC or AF_INET or AF_INET6 */
139 static int IPv4or6 = AF_UNSPEC;
140 
141 /* helper */
142 static void port_open_helper(Channel *c, char *rtype);
143 
144 /* -- channel core */
145 
146 Channel *
147 channel_lookup(int id)
148 {
149 	Channel *c;
150 
151 	if (id < 0 || id >= channels_alloc) {
152 		log("channel_lookup: %d: bad id", id);
153 		return NULL;
154 	}
155 	c = channels[id];
156 	if (c == NULL) {
157 		log("channel_lookup: %d: bad id: channel free", id);
158 		return NULL;
159 	}
160 	return c;
161 }
162 
163 /*
164  * Register filedescriptors for a channel, used when allocating a channel or
165  * when the channel consumer/producer is ready, e.g. shell exec'd
166  */
167 
168 static void
169 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
170     int extusage, int nonblock)
171 {
172 	/* Update the maximum file descriptor value. */
173 	channel_max_fd = MAX(channel_max_fd, rfd);
174 	channel_max_fd = MAX(channel_max_fd, wfd);
175 	channel_max_fd = MAX(channel_max_fd, efd);
176 
177 	/* XXX set close-on-exec -markus */
178 
179 	c->rfd = rfd;
180 	c->wfd = wfd;
181 	c->sock = (rfd == wfd) ? rfd : -1;
182 	c->efd = efd;
183 	c->extended_usage = extusage;
184 
185 	/* XXX ugly hack: nonblock is only set by the server */
186 	if (nonblock && isatty(c->rfd)) {
187 		debug("channel %d: rfd %d isatty", c->self, c->rfd);
188 		c->isatty = 1;
189 		if (!isatty(c->wfd)) {
190 			error("channel %d: wfd %d is not a tty?",
191 			    c->self, c->wfd);
192 		}
193 	} else {
194 		c->isatty = 0;
195 	}
196 	c->wfd_isatty = isatty(c->wfd);
197 
198 	/* enable nonblocking mode */
199 	if (nonblock) {
200 		if (rfd != -1)
201 			set_nonblock(rfd);
202 		if (wfd != -1)
203 			set_nonblock(wfd);
204 		if (efd != -1)
205 			set_nonblock(efd);
206 	}
207 }
208 
209 /*
210  * Allocate a new channel object and set its type and socket. This will cause
211  * remote_name to be freed.
212  */
213 
214 Channel *
215 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
216     u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
217 {
218 	int i, found;
219 	Channel *c;
220 
221 	/* Do initial allocation if this is the first call. */
222 	if (channels_alloc == 0) {
223 		channels_alloc = 10;
224 		channels = xmalloc(channels_alloc * sizeof(Channel *));
225 		for (i = 0; i < channels_alloc; i++)
226 			channels[i] = NULL;
227 		fatal_add_cleanup((void (*) (void *)) channel_free_all, NULL);
228 	}
229 	/* Try to find a free slot where to put the new channel. */
230 	for (found = -1, i = 0; i < channels_alloc; i++)
231 		if (channels[i] == NULL) {
232 			/* Found a free slot. */
233 			found = i;
234 			break;
235 		}
236 	if (found == -1) {
237 		/* There are no free slots.  Take last+1 slot and expand the array.  */
238 		found = channels_alloc;
239 		if (channels_alloc > 10000)
240 			fatal("channel_new: internal error: channels_alloc %d "
241 			    "too big.", channels_alloc);
242 		channels = xrealloc(channels,
243 		    (channels_alloc + 10) * sizeof(Channel *));
244 		channels_alloc += 10;
245 		debug2("channel: expanding %d", channels_alloc);
246 		for (i = found; i < channels_alloc; i++)
247 			channels[i] = NULL;
248 	}
249 	/* Initialize and return new channel. */
250 	c = channels[found] = xmalloc(sizeof(Channel));
251 	memset(c, 0, sizeof(Channel));
252 	buffer_init(&c->input);
253 	buffer_init(&c->output);
254 	buffer_init(&c->extended);
255 	c->ostate = CHAN_OUTPUT_OPEN;
256 	c->istate = CHAN_INPUT_OPEN;
257 	c->flags = 0;
258 	channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
259 	c->self = found;
260 	c->type = type;
261 	c->ctype = ctype;
262 	c->local_window = window;
263 	c->local_window_max = window;
264 	c->local_consumed = 0;
265 	c->local_maxpacket = maxpack;
266 	c->remote_id = -1;
267 	c->remote_name = remote_name;
268 	c->remote_window = 0;
269 	c->remote_maxpacket = 0;
270 	c->force_drain = 0;
271 	c->single_connection = 0;
272 	c->detach_user = NULL;
273 	c->confirm = NULL;
274 	c->input_filter = NULL;
275 	debug("channel %d: new [%s]", found, remote_name);
276 	return c;
277 }
278 
279 static int
280 channel_find_maxfd(void)
281 {
282 	int i, max = 0;
283 	Channel *c;
284 
285 	for (i = 0; i < channels_alloc; i++) {
286 		c = channels[i];
287 		if (c != NULL) {
288 			max = MAX(max, c->rfd);
289 			max = MAX(max, c->wfd);
290 			max = MAX(max, c->efd);
291 		}
292 	}
293 	return max;
294 }
295 
296 int
297 channel_close_fd(int *fdp)
298 {
299 	int ret = 0, fd = *fdp;
300 
301 	if (fd != -1) {
302 		ret = close(fd);
303 		*fdp = -1;
304 		if (fd == channel_max_fd)
305 			channel_max_fd = channel_find_maxfd();
306 	}
307 	return ret;
308 }
309 
310 /* Close all channel fd/socket. */
311 
312 static void
313 channel_close_fds(Channel *c)
314 {
315 	debug3("channel_close_fds: channel %d: r %d w %d e %d",
316 	    c->self, c->rfd, c->wfd, c->efd);
317 
318 	channel_close_fd(&c->sock);
319 	channel_close_fd(&c->rfd);
320 	channel_close_fd(&c->wfd);
321 	channel_close_fd(&c->efd);
322 }
323 
324 /* Free the channel and close its fd/socket. */
325 
326 void
327 channel_free(Channel *c)
328 {
329 	char *s;
330 	int i, n;
331 
332 	for (n = 0, i = 0; i < channels_alloc; i++)
333 		if (channels[i])
334 			n++;
335 	debug("channel_free: channel %d: %s, nchannels %d", c->self,
336 	    c->remote_name ? c->remote_name : "???", n);
337 
338 	s = channel_open_message();
339 	debug3("channel_free: status: %s", s);
340 	xfree(s);
341 
342 	if (c->sock != -1)
343 		shutdown(c->sock, SHUT_RDWR);
344 	channel_close_fds(c);
345 	buffer_free(&c->input);
346 	buffer_free(&c->output);
347 	buffer_free(&c->extended);
348 	if (c->remote_name) {
349 		xfree(c->remote_name);
350 		c->remote_name = NULL;
351 	}
352 	channels[c->self] = NULL;
353 	xfree(c);
354 }
355 
356 void
357 channel_free_all(void)
358 {
359 	int i;
360 
361 	for (i = 0; i < channels_alloc; i++)
362 		if (channels[i] != NULL)
363 			channel_free(channels[i]);
364 }
365 
366 /*
367  * Closes the sockets/fds of all channels.  This is used to close extra file
368  * descriptors after a fork.
369  */
370 
371 void
372 channel_close_all(void)
373 {
374 	int i;
375 
376 	for (i = 0; i < channels_alloc; i++)
377 		if (channels[i] != NULL)
378 			channel_close_fds(channels[i]);
379 }
380 
381 /*
382  * Stop listening to channels.
383  */
384 
385 void
386 channel_stop_listening(void)
387 {
388 	int i;
389 	Channel *c;
390 
391 	for (i = 0; i < channels_alloc; i++) {
392 		c = channels[i];
393 		if (c != NULL) {
394 			switch (c->type) {
395 			case SSH_CHANNEL_AUTH_SOCKET:
396 			case SSH_CHANNEL_PORT_LISTENER:
397 			case SSH_CHANNEL_RPORT_LISTENER:
398 			case SSH_CHANNEL_X11_LISTENER:
399 				channel_close_fd(&c->sock);
400 				channel_free(c);
401 				break;
402 			}
403 		}
404 	}
405 }
406 
407 /*
408  * Returns true if no channel has too much buffered data, and false if one or
409  * more channel is overfull.
410  */
411 
412 int
413 channel_not_very_much_buffered_data(void)
414 {
415 	u_int i;
416 	Channel *c;
417 
418 	for (i = 0; i < channels_alloc; i++) {
419 		c = channels[i];
420 		if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
421 #if 0
422 			if (!compat20 &&
423 			    buffer_len(&c->input) > packet_get_maxsize()) {
424 				debug("channel %d: big input buffer %d",
425 				    c->self, buffer_len(&c->input));
426 				return 0;
427 			}
428 #endif
429 			if (buffer_len(&c->output) > packet_get_maxsize()) {
430 				debug("channel %d: big output buffer %d > %d",
431 				    c->self, buffer_len(&c->output),
432 				    packet_get_maxsize());
433 				return 0;
434 			}
435 		}
436 	}
437 	return 1;
438 }
439 
440 /* Returns true if any channel is still open. */
441 
442 int
443 channel_still_open(void)
444 {
445 	int i;
446 	Channel *c;
447 
448 	for (i = 0; i < channels_alloc; i++) {
449 		c = channels[i];
450 		if (c == NULL)
451 			continue;
452 		switch (c->type) {
453 		case SSH_CHANNEL_X11_LISTENER:
454 		case SSH_CHANNEL_PORT_LISTENER:
455 		case SSH_CHANNEL_RPORT_LISTENER:
456 		case SSH_CHANNEL_CLOSED:
457 		case SSH_CHANNEL_AUTH_SOCKET:
458 		case SSH_CHANNEL_DYNAMIC:
459 		case SSH_CHANNEL_CONNECTING:
460 		case SSH_CHANNEL_ZOMBIE:
461 			continue;
462 		case SSH_CHANNEL_LARVAL:
463 			if (!compat20)
464 				fatal("cannot happen: SSH_CHANNEL_LARVAL");
465 			continue;
466 		case SSH_CHANNEL_OPENING:
467 		case SSH_CHANNEL_OPEN:
468 		case SSH_CHANNEL_X11_OPEN:
469 			return 1;
470 		case SSH_CHANNEL_INPUT_DRAINING:
471 		case SSH_CHANNEL_OUTPUT_DRAINING:
472 			if (!compat13)
473 				fatal("cannot happen: OUT_DRAIN");
474 			return 1;
475 		default:
476 			fatal("channel_still_open: bad channel type %d", c->type);
477 			/* NOTREACHED */
478 		}
479 	}
480 	return 0;
481 }
482 
483 /* Returns the id of an open channel suitable for keepaliving */
484 
485 int
486 channel_find_open(void)
487 {
488 	int i;
489 	Channel *c;
490 
491 	for (i = 0; i < channels_alloc; i++) {
492 		c = channels[i];
493 		if (c == NULL)
494 			continue;
495 		switch (c->type) {
496 		case SSH_CHANNEL_CLOSED:
497 		case SSH_CHANNEL_DYNAMIC:
498 		case SSH_CHANNEL_X11_LISTENER:
499 		case SSH_CHANNEL_PORT_LISTENER:
500 		case SSH_CHANNEL_RPORT_LISTENER:
501 		case SSH_CHANNEL_OPENING:
502 		case SSH_CHANNEL_CONNECTING:
503 		case SSH_CHANNEL_ZOMBIE:
504 			continue;
505 		case SSH_CHANNEL_LARVAL:
506 		case SSH_CHANNEL_AUTH_SOCKET:
507 		case SSH_CHANNEL_OPEN:
508 		case SSH_CHANNEL_X11_OPEN:
509 			return i;
510 		case SSH_CHANNEL_INPUT_DRAINING:
511 		case SSH_CHANNEL_OUTPUT_DRAINING:
512 			if (!compat13)
513 				fatal("cannot happen: OUT_DRAIN");
514 			return i;
515 		default:
516 			fatal("channel_find_open: bad channel type %d", c->type);
517 			/* NOTREACHED */
518 		}
519 	}
520 	return -1;
521 }
522 
523 
524 /*
525  * Returns a message describing the currently open forwarded connections,
526  * suitable for sending to the client.  The message contains crlf pairs for
527  * newlines.
528  */
529 
530 char *
531 channel_open_message(void)
532 {
533 	Buffer buffer;
534 	Channel *c;
535 	char buf[1024], *cp;
536 	int i;
537 
538 	buffer_init(&buffer);
539 	snprintf(buf, sizeof buf, "The following connections are open:\r\n");
540 	buffer_append(&buffer, buf, strlen(buf));
541 	for (i = 0; i < channels_alloc; i++) {
542 		c = channels[i];
543 		if (c == NULL)
544 			continue;
545 		switch (c->type) {
546 		case SSH_CHANNEL_X11_LISTENER:
547 		case SSH_CHANNEL_PORT_LISTENER:
548 		case SSH_CHANNEL_RPORT_LISTENER:
549 		case SSH_CHANNEL_CLOSED:
550 		case SSH_CHANNEL_AUTH_SOCKET:
551 		case SSH_CHANNEL_ZOMBIE:
552 			continue;
553 		case SSH_CHANNEL_LARVAL:
554 		case SSH_CHANNEL_OPENING:
555 		case SSH_CHANNEL_CONNECTING:
556 		case SSH_CHANNEL_DYNAMIC:
557 		case SSH_CHANNEL_OPEN:
558 		case SSH_CHANNEL_X11_OPEN:
559 		case SSH_CHANNEL_INPUT_DRAINING:
560 		case SSH_CHANNEL_OUTPUT_DRAINING:
561 			snprintf(buf, sizeof buf, "  #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
562 			    c->self, c->remote_name,
563 			    c->type, c->remote_id,
564 			    c->istate, buffer_len(&c->input),
565 			    c->ostate, buffer_len(&c->output),
566 			    c->rfd, c->wfd);
567 			buffer_append(&buffer, buf, strlen(buf));
568 			continue;
569 		default:
570 			fatal("channel_open_message: bad channel type %d", c->type);
571 			/* NOTREACHED */
572 		}
573 	}
574 	buffer_append(&buffer, "\0", 1);
575 	cp = xstrdup(buffer_ptr(&buffer));
576 	buffer_free(&buffer);
577 	return cp;
578 }
579 
580 void
581 channel_send_open(int id)
582 {
583 	Channel *c = channel_lookup(id);
584 
585 	if (c == NULL) {
586 		log("channel_send_open: %d: bad id", id);
587 		return;
588 	}
589 	debug("send channel open %d", id);
590 	packet_start(SSH2_MSG_CHANNEL_OPEN);
591 	packet_put_cstring(c->ctype);
592 	packet_put_int(c->self);
593 	packet_put_int(c->local_window);
594 	packet_put_int(c->local_maxpacket);
595 	packet_send();
596 }
597 
598 void
599 channel_request_start(int local_id, char *service, int wantconfirm)
600 {
601 	Channel *c = channel_lookup(local_id);
602 
603 	if (c == NULL) {
604 		log("channel_request_start: %d: unknown channel id", local_id);
605 		return;
606 	}
607 	debug("channel request %d: %s", local_id, service) ;
608 	packet_start(SSH2_MSG_CHANNEL_REQUEST);
609 	packet_put_int(c->remote_id);
610 	packet_put_cstring(service);
611 	packet_put_char(wantconfirm);
612 }
613 void
614 channel_register_confirm(int id, channel_callback_fn *fn)
615 {
616 	Channel *c = channel_lookup(id);
617 
618 	if (c == NULL) {
619 		log("channel_register_comfirm: %d: bad id", id);
620 		return;
621 	}
622 	c->confirm = fn;
623 }
624 void
625 channel_register_cleanup(int id, channel_callback_fn *fn)
626 {
627 	Channel *c = channel_lookup(id);
628 
629 	if (c == NULL) {
630 		log("channel_register_cleanup: %d: bad id", id);
631 		return;
632 	}
633 	c->detach_user = fn;
634 }
635 void
636 channel_cancel_cleanup(int id)
637 {
638 	Channel *c = channel_lookup(id);
639 
640 	if (c == NULL) {
641 		log("channel_cancel_cleanup: %d: bad id", id);
642 		return;
643 	}
644 	c->detach_user = NULL;
645 }
646 void
647 channel_register_filter(int id, channel_filter_fn *fn)
648 {
649 	Channel *c = channel_lookup(id);
650 
651 	if (c == NULL) {
652 		log("channel_register_filter: %d: bad id", id);
653 		return;
654 	}
655 	c->input_filter = fn;
656 }
657 
658 void
659 channel_set_fds(int id, int rfd, int wfd, int efd,
660     int extusage, int nonblock, u_int window_max)
661 {
662 	Channel *c = channel_lookup(id);
663 
664 	if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
665 		fatal("channel_activate for non-larval channel %d.", id);
666 	channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
667 	c->type = SSH_CHANNEL_OPEN;
668 	c->local_window = c->local_window_max = window_max;
669 	packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
670 	packet_put_int(c->remote_id);
671 	packet_put_int(c->local_window);
672 	packet_send();
673 }
674 
675 void
676 channel_set_wait_for_exit(int id, int wait_for_exit)
677 {
678 	Channel *c = channel_lookup(id);
679 
680 	if (c == NULL || c->type != SSH_CHANNEL_OPEN)
681 		fatal("channel_set_wait_for_exit for non-open channel %d.", id);
682 
683 	debug3("channel_set_wait_for_exit %d, %d (type: %d)", id, wait_for_exit, c->type);
684 	c->wait_for_exit = wait_for_exit;
685 }
686 
687 /*
688  * 'channel_pre*' are called just before select() to add any bits relevant to
689  * channels in the select bitmasks.
690  */
691 /*
692  * 'channel_post*': perform any appropriate operations for channels which
693  * have events pending.
694  */
695 typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
696 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
697 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
698 
699 static void
700 channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
701 {
702 	FD_SET(c->sock, readset);
703 }
704 
705 static void
706 channel_pre_connecting(Channel *c, fd_set * readset, fd_set * writeset)
707 {
708 	debug3("channel %d: waiting for connection", c->self);
709 	FD_SET(c->sock, writeset);
710 }
711 
712 static void
713 channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
714 {
715 	if (buffer_len(&c->input) < packet_get_maxsize())
716 		FD_SET(c->sock, readset);
717 	if (buffer_len(&c->output) > 0)
718 		FD_SET(c->sock, writeset);
719 }
720 
721 static void
722 channel_pre_open(Channel *c, fd_set * readset, fd_set * writeset)
723 {
724 	u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
725 
726 	if (c->istate == CHAN_INPUT_OPEN &&
727 	    limit > 0 &&
728 	    buffer_len(&c->input) < limit)
729 		FD_SET(c->rfd, readset);
730 	if (c->ostate == CHAN_OUTPUT_OPEN ||
731 	    c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
732 		if (buffer_len(&c->output) > 0) {
733 			FD_SET(c->wfd, writeset);
734 		} else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
735 			if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
736 			       debug2("channel %d: obuf_empty delayed efd %d/(%d)",
737 				   c->self, c->efd, buffer_len(&c->extended));
738 			else
739 				chan_obuf_empty(c);
740 		}
741 	}
742 	/** XXX check close conditions, too */
743 	if (compat20 && c->efd != -1) {
744 		if (c->extended_usage == CHAN_EXTENDED_WRITE &&
745 		    buffer_len(&c->extended) > 0)
746 			FD_SET(c->efd, writeset);
747 		else if (!(c->flags & CHAN_EOF_SENT) &&
748 		    c->extended_usage == CHAN_EXTENDED_READ &&
749 		    buffer_len(&c->extended) < c->remote_window)
750 			FD_SET(c->efd, readset);
751 	}
752 }
753 
754 static void
755 channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
756 {
757 	if (buffer_len(&c->input) == 0) {
758 		packet_start(SSH_MSG_CHANNEL_CLOSE);
759 		packet_put_int(c->remote_id);
760 		packet_send();
761 		c->type = SSH_CHANNEL_CLOSED;
762 		debug("channel %d: closing after input drain.", c->self);
763 	}
764 }
765 
766 static void
767 channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
768 {
769 	if (buffer_len(&c->output) == 0)
770 		chan_mark_dead(c);
771 	else
772 		FD_SET(c->sock, writeset);
773 }
774 
775 /*
776  * This is a special state for X11 authentication spoofing.  An opened X11
777  * connection (when authentication spoofing is being done) remains in this
778  * state until the first packet has been completely read.  The authentication
779  * data in that packet is then substituted by the real data if it matches the
780  * fake data, and the channel is put into normal mode.
781  * XXX All this happens at the client side.
782  * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
783  */
784 static int
785 x11_open_helper(Buffer *b)
786 {
787 	u_char *ucp;
788 	u_int proto_len, data_len;
789 
790 	/* Check if the fixed size part of the packet is in buffer. */
791 	if (buffer_len(b) < 12)
792 		return 0;
793 
794 	/* Parse the lengths of variable-length fields. */
795 	ucp = buffer_ptr(b);
796 	if (ucp[0] == 0x42) {	/* Byte order MSB first. */
797 		proto_len = 256 * ucp[6] + ucp[7];
798 		data_len = 256 * ucp[8] + ucp[9];
799 	} else if (ucp[0] == 0x6c) {	/* Byte order LSB first. */
800 		proto_len = ucp[6] + 256 * ucp[7];
801 		data_len = ucp[8] + 256 * ucp[9];
802 	} else {
803 		debug("Initial X11 packet contains bad byte order byte: 0x%x",
804 		    ucp[0]);
805 		return -1;
806 	}
807 
808 	/* Check if the whole packet is in buffer. */
809 	if (buffer_len(b) <
810 	    12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
811 		return 0;
812 
813 	/* Check if authentication protocol matches. */
814 	if (proto_len != strlen(x11_saved_proto) ||
815 	    memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
816 		debug("X11 connection uses different authentication protocol.");
817 		return -1;
818 	}
819 	/* Check if authentication data matches our fake data. */
820 	if (data_len != x11_fake_data_len ||
821 	    memcmp(ucp + 12 + ((proto_len + 3) & ~3),
822 		x11_fake_data, x11_fake_data_len) != 0) {
823 		debug("X11 auth data does not match fake data.");
824 		return -1;
825 	}
826 	/* Check fake data length */
827 	if (x11_fake_data_len != x11_saved_data_len) {
828 		error("X11 fake_data_len %d != saved_data_len %d",
829 		    x11_fake_data_len, x11_saved_data_len);
830 		return -1;
831 	}
832 	/*
833 	 * Received authentication protocol and data match
834 	 * our fake data. Substitute the fake data with real
835 	 * data.
836 	 */
837 	memcpy(ucp + 12 + ((proto_len + 3) & ~3),
838 	    x11_saved_data, x11_saved_data_len);
839 	return 1;
840 }
841 
842 static void
843 channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
844 {
845 	int ret = x11_open_helper(&c->output);
846 
847 	if (ret == 1) {
848 		/* Start normal processing for the channel. */
849 		c->type = SSH_CHANNEL_OPEN;
850 		channel_pre_open_13(c, readset, writeset);
851 	} else if (ret == -1) {
852 		/*
853 		 * We have received an X11 connection that has bad
854 		 * authentication information.
855 		 */
856 		log("X11 connection rejected because of wrong authentication.");
857 		buffer_clear(&c->input);
858 		buffer_clear(&c->output);
859 		channel_close_fd(&c->sock);
860 		c->sock = -1;
861 		c->type = SSH_CHANNEL_CLOSED;
862 		packet_start(SSH_MSG_CHANNEL_CLOSE);
863 		packet_put_int(c->remote_id);
864 		packet_send();
865 	}
866 }
867 
868 static void
869 channel_pre_x11_open(Channel *c, fd_set * readset, fd_set * writeset)
870 {
871 	int ret = x11_open_helper(&c->output);
872 
873 	/* c->force_drain = 1; */
874 
875 	if (ret == 1) {
876 		c->type = SSH_CHANNEL_OPEN;
877 		channel_pre_open(c, readset, writeset);
878 	} else if (ret == -1) {
879 		log("X11 connection rejected because of wrong authentication.");
880 		debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
881 		chan_read_failed(c);
882 		buffer_clear(&c->input);
883 		chan_ibuf_empty(c);
884 		buffer_clear(&c->output);
885 		/* for proto v1, the peer will send an IEOF */
886 		if (compat20)
887 			chan_write_failed(c);
888 		else
889 			c->type = SSH_CHANNEL_OPEN;
890 		debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
891 	}
892 }
893 
894 /* try to decode a socks4 header */
895 static int
896 channel_decode_socks4(Channel *c, fd_set * readset, fd_set * writeset)
897 {
898 	char *p, *host;
899 	int len, have, i, found;
900 	char username[256];
901 	struct {
902 		u_int8_t version;
903 		u_int8_t command;
904 		u_int16_t dest_port;
905 		struct in_addr dest_addr;
906 	} s4_req, s4_rsp;
907 
908 	debug2("channel %d: decode socks4", c->self);
909 
910 	have = buffer_len(&c->input);
911 	len = sizeof(s4_req);
912 	if (have < len)
913 		return 0;
914 	p = buffer_ptr(&c->input);
915 	for (found = 0, i = len; i < have; i++) {
916 		if (p[i] == '\0') {
917 			found = 1;
918 			break;
919 		}
920 		if (i > 1024) {
921 			/* the peer is probably sending garbage */
922 			debug("channel %d: decode socks4: too long",
923 			    c->self);
924 			return -1;
925 		}
926 	}
927 	if (!found)
928 		return 0;
929 	buffer_get(&c->input, (char *)&s4_req.version, 1);
930 	buffer_get(&c->input, (char *)&s4_req.command, 1);
931 	buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
932 	buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
933 	have = buffer_len(&c->input);
934 	p = buffer_ptr(&c->input);
935 	len = strlen(p);
936 	debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
937 	if (len > have)
938 		fatal("channel %d: decode socks4: len %d > have %d",
939 		    c->self, len, have);
940 	strlcpy(username, p, sizeof(username));
941 	buffer_consume(&c->input, len);
942 	buffer_consume(&c->input, 1);		/* trailing '\0' */
943 
944 	host = inet_ntoa(s4_req.dest_addr);
945 	strlcpy(c->path, host, sizeof(c->path));
946 	c->host_port = ntohs(s4_req.dest_port);
947 
948 	debug("channel %d: dynamic request: socks4 host %s port %u command %u",
949 	    c->self, host, c->host_port, s4_req.command);
950 
951 	if (s4_req.command != 1) {
952 		debug("channel %d: cannot handle: socks4 cn %d",
953 		    c->self, s4_req.command);
954 		return -1;
955 	}
956 	s4_rsp.version = 0;			/* vn: 0 for reply */
957 	s4_rsp.command = 90;			/* cd: req granted */
958 	s4_rsp.dest_port = 0;			/* ignored */
959 	s4_rsp.dest_addr.s_addr = INADDR_ANY;	/* ignored */
960 	buffer_append(&c->output, (char *)&s4_rsp, sizeof(s4_rsp));
961 	return 1;
962 }
963 
964 /* try to decode a socks5 header */
965 #define SSH_SOCKS5_AUTHDONE	0x1000
966 #define SSH_SOCKS5_NOAUTH	0x00
967 #define SSH_SOCKS5_IPV4		0x01
968 #define SSH_SOCKS5_DOMAIN	0x03
969 #define SSH_SOCKS5_IPV6		0x04
970 #define SSH_SOCKS5_CONNECT	0x01
971 #define SSH_SOCKS5_SUCCESS	0x00
972 
973 /* ARGSUSED */
974 static int
975 channel_decode_socks5(Channel *c, fd_set *readset, fd_set *writeset)
976 {
977 	struct {
978 		u_int8_t version;
979 		u_int8_t command;
980 		u_int8_t reserved;
981 		u_int8_t atyp;
982 	} s5_req, s5_rsp;
983 	u_int16_t dest_port;
984 	u_char *p, dest_addr[255+1];
985 	u_int have, need, i, found, nmethods, addrlen;
986 	struct in_addr bnd_addr;
987 	int af;
988 
989 	debug2("channel %d: decode socks5", c->self);
990 	p = buffer_ptr(&c->input);
991 	if (p[0] != 0x05)
992 		return -1;
993 	have = buffer_len(&c->input);
994 	if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
995 		/* format: ver | nmethods | methods */
996 		if (have < 2)
997 			return 0;
998 		nmethods = p[1];
999 		if (have < nmethods + 2)
1000 			return 0;
1001 		/* look for method: "NO AUTHENTICATION REQUIRED" */
1002 		for (found = 0, i = 2 ; i < nmethods + 2; i++) {
1003 			if (p[i] == SSH_SOCKS5_NOAUTH) {
1004 				found = 1;
1005 				break;
1006 			}
1007 		}
1008 		if (!found) {
1009 			error("channel %d: socks5 authentication methods not implemented",
1010 			    c->self);
1011 			error("channel %d: forwarding failed: "
1012 			    "SSH_SOCKS5_NOAUTH method not found", c->self);
1013 			return -1;
1014 		}
1015 		buffer_consume(&c->input, nmethods + 2);
1016 		buffer_put_char(&c->output, 0x05);		/* version */
1017 		buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH);	/* method */
1018 		FD_SET(c->sock, writeset);
1019 		c->flags |= SSH_SOCKS5_AUTHDONE;
1020 		debug2("channel %d: socks5 auth done", c->self);
1021 		return 0;				/* need more */
1022 	}
1023 	debug2("channel %d: socks5 post auth", c->self);
1024 	if (have < sizeof(s5_req)+1)
1025 		return 0;			/* need more */
1026 	memcpy(&s5_req, p, sizeof(s5_req));
1027 	if (s5_req.version != 0x05 ||
1028 	    s5_req.command != SSH_SOCKS5_CONNECT ||
1029 	    s5_req.reserved != 0x00) {
1030 		error("channel %d: forwarding failed: "
1031 		    "only socks5 connect is supported", c->self);
1032 		return -1;
1033 	}
1034 	switch (s5_req.atyp){
1035 	case SSH_SOCKS5_IPV4:
1036 		addrlen = 4;
1037 		af = AF_INET;
1038 		break;
1039 	case SSH_SOCKS5_DOMAIN:
1040 		addrlen = p[sizeof(s5_req)];
1041 		af = -1;
1042 		break;
1043 	case SSH_SOCKS5_IPV6:
1044 		addrlen = 16;
1045 		af = AF_INET6;
1046 		break;
1047 	default:
1048 		error("channel %d: forwarding failed: "
1049 		    "bad socks5 atyp %d", c->self, s5_req.atyp);
1050 		return -1;
1051 	}
1052 	need = sizeof(s5_req) + addrlen + 2;
1053 	if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1054 		need++;
1055 	if (have < need)
1056 		return 0;
1057 	buffer_consume(&c->input, sizeof(s5_req));
1058 	if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1059 		buffer_consume(&c->input, 1);    /* host string length */
1060 	buffer_get(&c->input, (char *)&dest_addr, addrlen);
1061 	buffer_get(&c->input, (char *)&dest_port, 2);
1062 	dest_addr[addrlen] = '\0';
1063 	if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1064 		strlcpy(c->path, (char *)dest_addr, sizeof(c->path));
1065 	else if (inet_ntop(af, dest_addr, c->path, sizeof(c->path)) == NULL)
1066 		return -1;
1067 	c->host_port = ntohs(dest_port);
1068 
1069 	debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1070 	    c->self, c->path, c->host_port, s5_req.command);
1071 
1072 	s5_rsp.version = 0x05;
1073 	s5_rsp.command = SSH_SOCKS5_SUCCESS;
1074 	s5_rsp.reserved = 0;			/* ignored */
1075 	s5_rsp.atyp = SSH_SOCKS5_IPV4;
1076 	bzero(&bnd_addr, sizeof(bnd_addr));
1077 	bnd_addr.s_addr = htonl(INADDR_ANY);
1078 	dest_port = 0;				/* ignored */
1079 
1080 	buffer_append(&c->output, &s5_rsp, sizeof(s5_rsp));
1081 	buffer_append(&c->output, &bnd_addr, sizeof(struct in_addr));
1082 	buffer_append(&c->output, &dest_port, sizeof(dest_port));
1083 	return 1;
1084 }
1085 
1086 /* dynamic port forwarding */
1087 static void
1088 channel_pre_dynamic(Channel *c, fd_set * readset, fd_set * writeset)
1089 {
1090 	u_char *p;
1091 	int have, ret;
1092 
1093 	have = buffer_len(&c->input);
1094 	c->delayed = 0;
1095 	debug2("channel %d: pre_dynamic: have %d", c->self, have);
1096 	/* buffer_dump(&c->input); */
1097 	/* check if the fixed size part of the packet is in buffer. */
1098 	if (have < 3) {
1099 		/* need more */
1100 		FD_SET(c->sock, readset);
1101 		return;
1102 	}
1103 	/* try to guess the protocol */
1104 	p = buffer_ptr(&c->input);
1105 	switch (p[0]) {
1106 	case 0x04:
1107 		ret = channel_decode_socks4(c, readset, writeset);
1108 		break;
1109 	case 0x05:
1110 		ret = channel_decode_socks5(c, readset, writeset);
1111 		break;
1112 	default:
1113 		error("channel %d: forwarding failed: unknown socks "
1114 		    "version 0x%02X", c->self, p[0]);
1115 		ret = -1;
1116 		break;
1117 	}
1118 	if (ret < 0) {
1119 		chan_mark_dead(c);
1120 	} else if (ret == 0) {
1121 		debug2("channel %d: pre_dynamic: need more", c->self);
1122 		/* need more */
1123 		FD_SET(c->sock, readset);
1124 	} else {
1125 		/* switch to the next state */
1126 		c->type = SSH_CHANNEL_OPENING;
1127 		port_open_helper(c, "direct-tcpip");
1128 	}
1129 }
1130 
1131 /* This is our fake X11 server socket. */
1132 static void
1133 channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
1134 {
1135 	Channel *nc;
1136 	struct sockaddr addr;
1137 	int newsock;
1138 	socklen_t addrlen;
1139 	char buf[16384], *remote_ipaddr;
1140 	int remote_port;
1141 
1142 	if (FD_ISSET(c->sock, readset)) {
1143 		debug("X11 connection requested.");
1144 		addrlen = sizeof(addr);
1145 		newsock = accept(c->sock, &addr, &addrlen);
1146 		if (c->single_connection) {
1147 			debug("single_connection: closing X11 listener.");
1148 			channel_close_fd(&c->sock);
1149 			chan_mark_dead(c);
1150 		}
1151 		if (newsock < 0) {
1152 			error("accept: %.100s", strerror(errno));
1153 			return;
1154 		}
1155 		set_nodelay(newsock);
1156 		remote_ipaddr = get_peer_ipaddr(newsock);
1157 		remote_port = get_peer_port(newsock);
1158 		snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1159 		    remote_ipaddr, remote_port);
1160 
1161 		nc = channel_new("accepted x11 socket",
1162 		    SSH_CHANNEL_OPENING, newsock, newsock, -1,
1163 		    c->local_window_max, c->local_maxpacket,
1164 		    0, xstrdup(buf), 1);
1165 		if (compat20) {
1166 			packet_start(SSH2_MSG_CHANNEL_OPEN);
1167 			packet_put_cstring("x11");
1168 			packet_put_int(nc->self);
1169 			packet_put_int(nc->local_window_max);
1170 			packet_put_int(nc->local_maxpacket);
1171 			/* originator ipaddr and port */
1172 			packet_put_cstring(remote_ipaddr);
1173 			if (datafellows & SSH_BUG_X11FWD) {
1174 				debug("ssh2 x11 bug compat mode");
1175 			} else {
1176 				packet_put_int(remote_port);
1177 			}
1178 			packet_send();
1179 		} else {
1180 			packet_start(SSH_SMSG_X11_OPEN);
1181 			packet_put_int(nc->self);
1182 			if (packet_get_protocol_flags() &
1183 			    SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1184 				packet_put_cstring(buf);
1185 			packet_send();
1186 		}
1187 		xfree(remote_ipaddr);
1188 	}
1189 }
1190 
1191 static void
1192 port_open_helper(Channel *c, char *rtype)
1193 {
1194 	int direct;
1195 	char buf[1024];
1196 	char *remote_ipaddr = get_peer_ipaddr(c->sock);
1197 	u_short remote_port = get_peer_port(c->sock);
1198 
1199 	direct = (strcmp(rtype, "direct-tcpip") == 0);
1200 
1201 	snprintf(buf, sizeof buf,
1202 	    "%s: listening port %d for %.100s port %d, "
1203 	    "connect from %.200s port %d",
1204 	    rtype, c->listening_port, c->path, c->host_port,
1205 	    remote_ipaddr, remote_port);
1206 
1207 	xfree(c->remote_name);
1208 	c->remote_name = xstrdup(buf);
1209 
1210 	if (compat20) {
1211 		packet_start(SSH2_MSG_CHANNEL_OPEN);
1212 		packet_put_cstring(rtype);
1213 		packet_put_int(c->self);
1214 		packet_put_int(c->local_window_max);
1215 		packet_put_int(c->local_maxpacket);
1216 		if (direct) {
1217 			/* target host, port */
1218 			packet_put_cstring(c->path);
1219 			packet_put_int(c->host_port);
1220 		} else {
1221 			/* listen address, port */
1222 			packet_put_cstring(c->path);
1223 			packet_put_int(c->listening_port);
1224 		}
1225 		/* originator host and port */
1226 		packet_put_cstring(remote_ipaddr);
1227 		packet_put_int(remote_port);
1228 		packet_send();
1229 	} else {
1230 		packet_start(SSH_MSG_PORT_OPEN);
1231 		packet_put_int(c->self);
1232 		packet_put_cstring(c->path);
1233 		packet_put_int(c->host_port);
1234 		if (packet_get_protocol_flags() &
1235 		    SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1236 			packet_put_cstring(c->remote_name);
1237 		packet_send();
1238 	}
1239 	xfree(remote_ipaddr);
1240 }
1241 
1242 /*
1243  * This socket is listening for connections to a forwarded TCP/IP port.
1244  */
1245 static void
1246 channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
1247 {
1248 	Channel *nc;
1249 	struct sockaddr addr;
1250 	int newsock, nextstate;
1251 	socklen_t addrlen;
1252 	char *rtype;
1253 
1254 	if (FD_ISSET(c->sock, readset)) {
1255 		debug("Connection to port %d forwarding "
1256 		    "to %.100s port %d requested.",
1257 		    c->listening_port, c->path, c->host_port);
1258 
1259 		if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1260 			nextstate = SSH_CHANNEL_OPENING;
1261 			rtype = "forwarded-tcpip";
1262 		} else {
1263 			if (c->host_port == 0) {
1264 				nextstate = SSH_CHANNEL_DYNAMIC;
1265 				rtype = "dynamic-tcpip";
1266 			} else {
1267 				nextstate = SSH_CHANNEL_OPENING;
1268 				rtype = "direct-tcpip";
1269 			}
1270 		}
1271 
1272 		addrlen = sizeof(addr);
1273 		newsock = accept(c->sock, &addr, &addrlen);
1274 		if (newsock < 0) {
1275 			error("accept: %.100s", strerror(errno));
1276 			return;
1277 		}
1278 		set_nodelay(newsock);
1279 		nc = channel_new(rtype,
1280 		    nextstate, newsock, newsock, -1,
1281 		    c->local_window_max, c->local_maxpacket,
1282 		    0, xstrdup(rtype), 1);
1283 		nc->listening_port = c->listening_port;
1284 		nc->host_port = c->host_port;
1285 		strlcpy(nc->path, c->path, sizeof(nc->path));
1286 
1287 		if (nextstate == SSH_CHANNEL_DYNAMIC) {
1288 			/*
1289 			 * do not call the channel_post handler until
1290 			 * this flag has been reset by a pre-handler.
1291 			 * otherwise the FD_ISSET calls might overflow
1292 			 */
1293 			nc->delayed = 1;
1294 		} else {
1295 			port_open_helper(nc, rtype);
1296 		}
1297 	}
1298 }
1299 
1300 /*
1301  * This is the authentication agent socket listening for connections from
1302  * clients.
1303  */
1304 static void
1305 channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
1306 {
1307 	Channel *nc;
1308 	char *name;
1309 	int newsock;
1310 	struct sockaddr addr;
1311 	socklen_t addrlen;
1312 
1313 	if (FD_ISSET(c->sock, readset)) {
1314 		addrlen = sizeof(addr);
1315 		newsock = accept(c->sock, &addr, &addrlen);
1316 		if (newsock < 0) {
1317 			error("accept from auth socket: %.100s", strerror(errno));
1318 			return;
1319 		}
1320 		name = xstrdup("accepted auth socket");
1321 		nc = channel_new("accepted auth socket",
1322 		    SSH_CHANNEL_OPENING, newsock, newsock, -1,
1323 		    c->local_window_max, c->local_maxpacket,
1324 		    0, name, 1);
1325 		if (compat20) {
1326 			packet_start(SSH2_MSG_CHANNEL_OPEN);
1327 			packet_put_cstring("auth-agent@openssh.com");
1328 			packet_put_int(nc->self);
1329 			packet_put_int(c->local_window_max);
1330 			packet_put_int(c->local_maxpacket);
1331 		} else {
1332 			packet_start(SSH_SMSG_AGENT_OPEN);
1333 			packet_put_int(nc->self);
1334 		}
1335 		packet_send();
1336 	}
1337 }
1338 
1339 static void
1340 channel_post_connecting(Channel *c, fd_set * readset, fd_set * writeset)
1341 {
1342 	int err = 0;
1343 	socklen_t sz = sizeof(err);
1344 
1345 	if (FD_ISSET(c->sock, writeset)) {
1346 		if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1347 			err = errno;
1348 			error("getsockopt SO_ERROR failed");
1349 		}
1350 		if (err == 0) {
1351 			debug("channel %d: connected", c->self);
1352 			c->type = SSH_CHANNEL_OPEN;
1353 			if (compat20) {
1354 				packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1355 				packet_put_int(c->remote_id);
1356 				packet_put_int(c->self);
1357 				packet_put_int(c->local_window);
1358 				packet_put_int(c->local_maxpacket);
1359 			} else {
1360 				packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1361 				packet_put_int(c->remote_id);
1362 				packet_put_int(c->self);
1363 			}
1364 		} else {
1365 			debug("channel %d: not connected: %s",
1366 			    c->self, strerror(err));
1367 			if (compat20) {
1368 				packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1369 				packet_put_int(c->remote_id);
1370 				packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1371 				if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1372 					packet_put_cstring(strerror(err));
1373 					packet_put_cstring("");
1374 				}
1375 			} else {
1376 				packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1377 				packet_put_int(c->remote_id);
1378 			}
1379 			chan_mark_dead(c);
1380 		}
1381 		packet_send();
1382 	}
1383 }
1384 
1385 static int
1386 channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
1387 {
1388 	char buf[16*1024];
1389 	int len;
1390 
1391 	if (c->rfd != -1 &&
1392 	    FD_ISSET(c->rfd, readset)) {
1393 		len = read(c->rfd, buf, sizeof(buf));
1394 		if (len < 0 && (errno == EINTR || errno == EAGAIN))
1395 			return 1;
1396 		if (len <= 0) {
1397 			debug("channel %d: read<=0 rfd %d len %d",
1398 			    c->self, c->rfd, len);
1399 			if (c->type != SSH_CHANNEL_OPEN) {
1400 				debug("channel %d: not open", c->self);
1401 				chan_mark_dead(c);
1402 				return -1;
1403 			} else if (compat13) {
1404 				buffer_clear(&c->output);
1405 				c->type = SSH_CHANNEL_INPUT_DRAINING;
1406 				debug("channel %d: input draining.", c->self);
1407 			} else {
1408 				chan_read_failed(c);
1409 			}
1410 			return -1;
1411 		}
1412 		if (c->input_filter != NULL) {
1413 			if (c->input_filter(c, buf, len) == -1) {
1414 				debug("channel %d: filter stops", c->self);
1415 				chan_read_failed(c);
1416 			}
1417 		} else {
1418 			buffer_append(&c->input, buf, len);
1419 		}
1420 	}
1421 	return 1;
1422 }
1423 static int
1424 channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
1425 {
1426 	struct termios tio;
1427 	u_char *data;
1428 	u_int dlen;
1429 	int len;
1430 
1431 	/* Send buffered output data to the socket. */
1432 	if (c->wfd != -1 &&
1433 	    FD_ISSET(c->wfd, writeset) &&
1434 	    buffer_len(&c->output) > 0) {
1435 		data = buffer_ptr(&c->output);
1436 		dlen = buffer_len(&c->output);
1437 #ifdef _AIX
1438 		/* XXX: Later AIX versions can't push as much data to tty */
1439 		if (compat20 && c->wfd_isatty && dlen > 8*1024)
1440 			dlen = 8*1024;
1441 #endif
1442 		len = write(c->wfd, data, dlen);
1443 		if (len < 0 && (errno == EINTR || errno == EAGAIN))
1444 			return 1;
1445 		if (len <= 0) {
1446 			if (c->type != SSH_CHANNEL_OPEN) {
1447 				debug("channel %d: not open", c->self);
1448 				chan_mark_dead(c);
1449 				return -1;
1450 			} else if (compat13) {
1451 				buffer_clear(&c->output);
1452 				debug("channel %d: input draining.", c->self);
1453 				c->type = SSH_CHANNEL_INPUT_DRAINING;
1454 			} else {
1455 				chan_write_failed(c);
1456 			}
1457 			return -1;
1458 		}
1459 		if (compat20 && c->isatty && dlen >= 1 && data[0] != '\r') {
1460 			if (tcgetattr(c->wfd, &tio) == 0 &&
1461 			    !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1462 				/*
1463 				 * Simulate echo to reduce the impact of
1464 				 * traffic analysis. We need to match the
1465 				 * size of a SSH2_MSG_CHANNEL_DATA message
1466 				 * (4 byte channel id + data)
1467 				 */
1468 				packet_send_ignore(4 + len);
1469 				packet_send();
1470 			}
1471 		}
1472 		buffer_consume(&c->output, len);
1473 		if (compat20 && len > 0) {
1474 			c->local_consumed += len;
1475 		}
1476 	}
1477 	return 1;
1478 }
1479 static int
1480 channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
1481 {
1482 	char buf[16*1024];
1483 	int len;
1484 
1485 /** XXX handle drain efd, too */
1486 	if (c->efd != -1) {
1487 		if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1488 		    FD_ISSET(c->efd, writeset) &&
1489 		    buffer_len(&c->extended) > 0) {
1490 			len = write(c->efd, buffer_ptr(&c->extended),
1491 			    buffer_len(&c->extended));
1492 			debug2("channel %d: written %d to efd %d",
1493 			    c->self, len, c->efd);
1494 			if (len < 0 && (errno == EINTR || errno == EAGAIN))
1495 				return 1;
1496 			if (len <= 0) {
1497 				debug2("channel %d: closing write-efd %d",
1498 				    c->self, c->efd);
1499 				channel_close_fd(&c->efd);
1500 			} else {
1501 				buffer_consume(&c->extended, len);
1502 				c->local_consumed += len;
1503 			}
1504 		} else if (c->extended_usage == CHAN_EXTENDED_READ &&
1505 		    FD_ISSET(c->efd, readset)) {
1506 			len = read(c->efd, buf, sizeof(buf));
1507 			debug2("channel %d: read %d from efd %d",
1508 			    c->self, len, c->efd);
1509 			if (len < 0 && (errno == EINTR || errno == EAGAIN))
1510 				return 1;
1511 			if (len <= 0) {
1512 				debug2("channel %d: closing read-efd %d",
1513 				    c->self, c->efd);
1514 				channel_close_fd(&c->efd);
1515 			} else {
1516 				buffer_append(&c->extended, buf, len);
1517 			}
1518 		}
1519 	}
1520 	return 1;
1521 }
1522 static int
1523 channel_check_window(Channel *c)
1524 {
1525 	if (c->type == SSH_CHANNEL_OPEN &&
1526 	    !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1527 	    c->local_window < c->local_window_max/2 &&
1528 	    c->local_consumed > 0) {
1529 		packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1530 		packet_put_int(c->remote_id);
1531 		packet_put_int(c->local_consumed);
1532 		packet_send();
1533 		debug2("channel %d: window %d sent adjust %d",
1534 		    c->self, c->local_window,
1535 		    c->local_consumed);
1536 		c->local_window += c->local_consumed;
1537 		c->local_consumed = 0;
1538 	}
1539 	return 1;
1540 }
1541 
1542 static void
1543 channel_post_open(Channel *c, fd_set * readset, fd_set * writeset)
1544 {
1545 	if (c->delayed)
1546 		return;
1547 	channel_handle_rfd(c, readset, writeset);
1548 	channel_handle_wfd(c, readset, writeset);
1549 	if (!compat20)
1550 		return;
1551 	channel_handle_efd(c, readset, writeset);
1552 	channel_check_window(c);
1553 }
1554 
1555 static void
1556 channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
1557 {
1558 	int len;
1559 
1560 	/* Send buffered output data to the socket. */
1561 	if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1562 		len = write(c->sock, buffer_ptr(&c->output),
1563 			    buffer_len(&c->output));
1564 		if (len <= 0)
1565 			buffer_clear(&c->output);
1566 		else
1567 			buffer_consume(&c->output, len);
1568 	}
1569 }
1570 
1571 static void
1572 channel_handler_init_20(void)
1573 {
1574 	channel_pre[SSH_CHANNEL_OPEN] =			&channel_pre_open;
1575 	channel_pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open;
1576 	channel_pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
1577 	channel_pre[SSH_CHANNEL_RPORT_LISTENER] =	&channel_pre_listener;
1578 	channel_pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
1579 	channel_pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
1580 	channel_pre[SSH_CHANNEL_CONNECTING] =		&channel_pre_connecting;
1581 	channel_pre[SSH_CHANNEL_DYNAMIC] =		&channel_pre_dynamic;
1582 
1583 	channel_post[SSH_CHANNEL_OPEN] =		&channel_post_open;
1584 	channel_post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
1585 	channel_post[SSH_CHANNEL_RPORT_LISTENER] =	&channel_post_port_listener;
1586 	channel_post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
1587 	channel_post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
1588 	channel_post[SSH_CHANNEL_CONNECTING] =		&channel_post_connecting;
1589 	channel_post[SSH_CHANNEL_DYNAMIC] =		&channel_post_open;
1590 }
1591 
1592 static void
1593 channel_handler_init_13(void)
1594 {
1595 	channel_pre[SSH_CHANNEL_OPEN] =			&channel_pre_open_13;
1596 	channel_pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open_13;
1597 	channel_pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
1598 	channel_pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
1599 	channel_pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
1600 	channel_pre[SSH_CHANNEL_INPUT_DRAINING] =	&channel_pre_input_draining;
1601 	channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] =	&channel_pre_output_draining;
1602 	channel_pre[SSH_CHANNEL_CONNECTING] =		&channel_pre_connecting;
1603 	channel_pre[SSH_CHANNEL_DYNAMIC] =		&channel_pre_dynamic;
1604 
1605 	channel_post[SSH_CHANNEL_OPEN] =		&channel_post_open;
1606 	channel_post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
1607 	channel_post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
1608 	channel_post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
1609 	channel_post[SSH_CHANNEL_OUTPUT_DRAINING] =	&channel_post_output_drain_13;
1610 	channel_post[SSH_CHANNEL_CONNECTING] =		&channel_post_connecting;
1611 	channel_post[SSH_CHANNEL_DYNAMIC] =		&channel_post_open;
1612 }
1613 
1614 static void
1615 channel_handler_init_15(void)
1616 {
1617 	channel_pre[SSH_CHANNEL_OPEN] =			&channel_pre_open;
1618 	channel_pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open;
1619 	channel_pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
1620 	channel_pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
1621 	channel_pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
1622 	channel_pre[SSH_CHANNEL_CONNECTING] =		&channel_pre_connecting;
1623 	channel_pre[SSH_CHANNEL_DYNAMIC] =		&channel_pre_dynamic;
1624 
1625 	channel_post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
1626 	channel_post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
1627 	channel_post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
1628 	channel_post[SSH_CHANNEL_OPEN] =		&channel_post_open;
1629 	channel_post[SSH_CHANNEL_CONNECTING] =		&channel_post_connecting;
1630 	channel_post[SSH_CHANNEL_DYNAMIC] =		&channel_post_open;
1631 }
1632 
1633 static void
1634 channel_handler_init(void)
1635 {
1636 	int i;
1637 
1638 	for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1639 		channel_pre[i] = NULL;
1640 		channel_post[i] = NULL;
1641 	}
1642 	if (compat20)
1643 		channel_handler_init_20();
1644 	else if (compat13)
1645 		channel_handler_init_13();
1646 	else
1647 		channel_handler_init_15();
1648 }
1649 
1650 /* gc dead channels */
1651 static void
1652 channel_garbage_collect(Channel *c)
1653 {
1654 	if (c == NULL)
1655 		return;
1656 	if (c->detach_user != NULL) {
1657 		if (!chan_is_dead(c, 0))
1658 			return;
1659 		debug("channel %d: gc: notify user", c->self);
1660 		c->detach_user(c->self, NULL);
1661 		/* if we still have a callback */
1662 		if (c->detach_user != NULL)
1663 			return;
1664 		debug("channel %d: gc: user detached", c->self);
1665 	}
1666 	if (!c->wait_for_exit && !chan_is_dead(c, 1))
1667 		return;
1668 	debug("channel %d: garbage collecting", c->self);
1669 	channel_free(c);
1670 }
1671 
1672 static void
1673 channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
1674 {
1675 	static int did_init = 0;
1676 	int i;
1677 	Channel *c;
1678 
1679 	if (!did_init) {
1680 		channel_handler_init();
1681 		did_init = 1;
1682 	}
1683 	for (i = 0; i < channels_alloc; i++) {
1684 		c = channels[i];
1685 		if (c == NULL)
1686 			continue;
1687 		if (ftab[c->type] != NULL)
1688 			(*ftab[c->type])(c, readset, writeset);
1689 		channel_garbage_collect(c);
1690 	}
1691 }
1692 
1693 /*
1694  * Allocate/update select bitmasks and add any bits relevant to channels in
1695  * select bitmasks.
1696  */
1697 void
1698 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1699     int *nallocp, int rekeying)
1700 {
1701 	int n;
1702 	u_int sz;
1703 
1704 	n = MAX(*maxfdp, channel_max_fd);
1705 
1706 	sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1707 	/* perhaps check sz < nalloc/2 and shrink? */
1708 	if (*readsetp == NULL || sz > *nallocp) {
1709 		*readsetp = xrealloc(*readsetp, sz);
1710 		*writesetp = xrealloc(*writesetp, sz);
1711 		*nallocp = sz;
1712 	}
1713 	*maxfdp = n;
1714 	memset(*readsetp, 0, sz);
1715 	memset(*writesetp, 0, sz);
1716 
1717 	if (!rekeying)
1718 		channel_handler(channel_pre, *readsetp, *writesetp);
1719 }
1720 
1721 /*
1722  * After select, perform any appropriate operations for channels which have
1723  * events pending.
1724  */
1725 void
1726 channel_after_select(fd_set * readset, fd_set * writeset)
1727 {
1728 	channel_handler(channel_post, readset, writeset);
1729 }
1730 
1731 
1732 /* If there is data to send to the connection, enqueue some of it now. */
1733 
1734 void
1735 channel_output_poll(void)
1736 {
1737 	Channel *c;
1738 	int i;
1739 	u_int len;
1740 
1741 	for (i = 0; i < channels_alloc; i++) {
1742 		c = channels[i];
1743 		if (c == NULL)
1744 			continue;
1745 
1746 		/*
1747 		 * We are only interested in channels that can have buffered
1748 		 * incoming data.
1749 		 */
1750 		if (compat13) {
1751 			if (c->type != SSH_CHANNEL_OPEN &&
1752 			    c->type != SSH_CHANNEL_INPUT_DRAINING)
1753 				continue;
1754 		} else {
1755 			if (c->type != SSH_CHANNEL_OPEN)
1756 				continue;
1757 		}
1758 		if (compat20 &&
1759 		    (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1760 			/* XXX is this true? */
1761 			debug3("channel %d: will not send data after close", c->self);
1762 			continue;
1763 		}
1764 
1765 		/* Get the amount of buffered data for this channel. */
1766 		if ((c->istate == CHAN_INPUT_OPEN ||
1767 		    c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1768 		    (len = buffer_len(&c->input)) > 0) {
1769 			/*
1770 			 * Send some data for the other side over the secure
1771 			 * connection.
1772 			 */
1773 			if (compat20) {
1774 				if (len > c->remote_window)
1775 					len = c->remote_window;
1776 				if (len > c->remote_maxpacket)
1777 					len = c->remote_maxpacket;
1778 			} else {
1779 				if (packet_is_interactive()) {
1780 					if (len > 1024)
1781 						len = 512;
1782 				} else {
1783 					/* Keep the packets at reasonable size. */
1784 					if (len > packet_get_maxsize()/2)
1785 						len = packet_get_maxsize()/2;
1786 				}
1787 			}
1788 			if (len > 0) {
1789 				packet_start(compat20 ?
1790 				    SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1791 				packet_put_int(c->remote_id);
1792 				packet_put_string(buffer_ptr(&c->input), len);
1793 				packet_send();
1794 				buffer_consume(&c->input, len);
1795 				c->remote_window -= len;
1796 			}
1797 		} else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1798 			if (compat13)
1799 				fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1800 			/*
1801 			 * input-buffer is empty and read-socket shutdown:
1802 			 * tell peer, that we will not send more data: send IEOF.
1803 			 * hack for extended data: delay EOF if EFD still in use.
1804 			 */
1805 			if (CHANNEL_EFD_INPUT_ACTIVE(c))
1806 			       debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
1807 				   c->self, c->efd, buffer_len(&c->extended));
1808 			else
1809 				chan_ibuf_empty(c);
1810 		}
1811 		/* Send extended data, i.e. stderr */
1812 		if (compat20 &&
1813 		    !(c->flags & CHAN_EOF_SENT) &&
1814 		    c->remote_window > 0 &&
1815 		    (len = buffer_len(&c->extended)) > 0 &&
1816 		    c->extended_usage == CHAN_EXTENDED_READ) {
1817 			debug2("channel %d: rwin %u elen %u euse %d",
1818 			    c->self, c->remote_window, buffer_len(&c->extended),
1819 			    c->extended_usage);
1820 			if (len > c->remote_window)
1821 				len = c->remote_window;
1822 			if (len > c->remote_maxpacket)
1823 				len = c->remote_maxpacket;
1824 			packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
1825 			packet_put_int(c->remote_id);
1826 			packet_put_int(SSH2_EXTENDED_DATA_STDERR);
1827 			packet_put_string(buffer_ptr(&c->extended), len);
1828 			packet_send();
1829 			buffer_consume(&c->extended, len);
1830 			c->remote_window -= len;
1831 			debug2("channel %d: sent ext data %d", c->self, len);
1832 		}
1833 	}
1834 }
1835 
1836 
1837 /* -- protocol input */
1838 
1839 void
1840 channel_input_data(int type, u_int32_t seq, void *ctxt)
1841 {
1842 	int id;
1843 	char *data;
1844 	u_int data_len;
1845 	Channel *c;
1846 
1847 	/* Get the channel number and verify it. */
1848 	id = packet_get_int();
1849 	c = channel_lookup(id);
1850 	if (c == NULL)
1851 		packet_disconnect("Received data for nonexistent channel %d.", id);
1852 
1853 	/* Ignore any data for non-open channels (might happen on close) */
1854 	if (c->type != SSH_CHANNEL_OPEN &&
1855 	    c->type != SSH_CHANNEL_X11_OPEN)
1856 		return;
1857 
1858 	/* same for protocol 1.5 if output end is no longer open */
1859 	if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
1860 		return;
1861 
1862 	/* Get the data. */
1863 	data = packet_get_string(&data_len);
1864 
1865 	if (compat20) {
1866 		if (data_len > c->local_maxpacket) {
1867 			log("channel %d: rcvd big packet %d, maxpack %d",
1868 			    c->self, data_len, c->local_maxpacket);
1869 		}
1870 		if (data_len > c->local_window) {
1871 			log("channel %d: rcvd too much data %d, win %d",
1872 			    c->self, data_len, c->local_window);
1873 			xfree(data);
1874 			return;
1875 		}
1876 		c->local_window -= data_len;
1877 	}
1878 	packet_check_eom();
1879 	buffer_append(&c->output, data, data_len);
1880 	xfree(data);
1881 }
1882 
1883 void
1884 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
1885 {
1886 	int id;
1887 	char *data;
1888 	u_int data_len, tcode;
1889 	Channel *c;
1890 
1891 	/* Get the channel number and verify it. */
1892 	id = packet_get_int();
1893 	c = channel_lookup(id);
1894 
1895 	if (c == NULL)
1896 		packet_disconnect("Received extended_data for bad channel %d.", id);
1897 	if (c->type != SSH_CHANNEL_OPEN) {
1898 		log("channel %d: ext data for non open", id);
1899 		return;
1900 	}
1901 	if (c->flags & CHAN_EOF_RCVD) {
1902 		if (datafellows & SSH_BUG_EXTEOF)
1903 			debug("channel %d: accepting ext data after eof", id);
1904 		else
1905 			packet_disconnect("Received extended_data after EOF "
1906 			    "on channel %d.", id);
1907 	}
1908 	tcode = packet_get_int();
1909 	if (c->efd == -1 ||
1910 	    c->extended_usage != CHAN_EXTENDED_WRITE ||
1911 	    tcode != SSH2_EXTENDED_DATA_STDERR) {
1912 		log("channel %d: bad ext data", c->self);
1913 		return;
1914 	}
1915 	data = packet_get_string(&data_len);
1916 	packet_check_eom();
1917 	if (data_len > c->local_window) {
1918 		log("channel %d: rcvd too much extended_data %d, win %d",
1919 		    c->self, data_len, c->local_window);
1920 		xfree(data);
1921 		return;
1922 	}
1923 	debug2("channel %d: rcvd ext data %d", c->self, data_len);
1924 	c->local_window -= data_len;
1925 	buffer_append(&c->extended, data, data_len);
1926 	xfree(data);
1927 }
1928 
1929 void
1930 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
1931 {
1932 	int id;
1933 	Channel *c;
1934 
1935 	id = packet_get_int();
1936 	packet_check_eom();
1937 	c = channel_lookup(id);
1938 	if (c == NULL)
1939 		packet_disconnect("Received ieof for nonexistent channel %d.", id);
1940 	chan_rcvd_ieof(c);
1941 
1942 	/* XXX force input close */
1943 	if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
1944 		debug("channel %d: FORCE input drain", c->self);
1945 		c->istate = CHAN_INPUT_WAIT_DRAIN;
1946 		if (buffer_len(&c->input) == 0)
1947 			chan_ibuf_empty(c);
1948 	}
1949 
1950 }
1951 
1952 void
1953 channel_input_close(int type, u_int32_t seq, void *ctxt)
1954 {
1955 	int id;
1956 	Channel *c;
1957 
1958 	id = packet_get_int();
1959 	packet_check_eom();
1960 	c = channel_lookup(id);
1961 	if (c == NULL)
1962 		packet_disconnect("Received close for nonexistent channel %d.", id);
1963 
1964 	/*
1965 	 * Send a confirmation that we have closed the channel and no more
1966 	 * data is coming for it.
1967 	 */
1968 	packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1969 	packet_put_int(c->remote_id);
1970 	packet_send();
1971 
1972 	/*
1973 	 * If the channel is in closed state, we have sent a close request,
1974 	 * and the other side will eventually respond with a confirmation.
1975 	 * Thus, we cannot free the channel here, because then there would be
1976 	 * no-one to receive the confirmation.  The channel gets freed when
1977 	 * the confirmation arrives.
1978 	 */
1979 	if (c->type != SSH_CHANNEL_CLOSED) {
1980 		/*
1981 		 * Not a closed channel - mark it as draining, which will
1982 		 * cause it to be freed later.
1983 		 */
1984 		buffer_clear(&c->input);
1985 		c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1986 	}
1987 }
1988 
1989 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1990 void
1991 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
1992 {
1993 	int id = packet_get_int();
1994 	Channel *c = channel_lookup(id);
1995 
1996 	packet_check_eom();
1997 	if (c == NULL)
1998 		packet_disconnect("Received oclose for nonexistent channel %d.", id);
1999 	chan_rcvd_oclose(c);
2000 }
2001 
2002 void
2003 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
2004 {
2005 	int id = packet_get_int();
2006 	Channel *c = channel_lookup(id);
2007 
2008 	packet_check_eom();
2009 	if (c == NULL)
2010 		packet_disconnect("Received close confirmation for "
2011 		    "out-of-range channel %d.", id);
2012 	if (c->type != SSH_CHANNEL_CLOSED)
2013 		packet_disconnect("Received close confirmation for "
2014 		    "non-closed channel %d (type %d).", id, c->type);
2015 	channel_free(c);
2016 }
2017 
2018 void
2019 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
2020 {
2021 	int id, remote_id;
2022 	Channel *c;
2023 
2024 	id = packet_get_int();
2025 	c = channel_lookup(id);
2026 
2027 	if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2028 		packet_disconnect("Received open confirmation for "
2029 		    "non-opening channel %d.", id);
2030 	remote_id = packet_get_int();
2031 	/* Record the remote channel number and mark that the channel is now open. */
2032 	c->remote_id = remote_id;
2033 	c->type = SSH_CHANNEL_OPEN;
2034 
2035 	if (compat20) {
2036 		c->remote_window = packet_get_int();
2037 		c->remote_maxpacket = packet_get_int();
2038 		if (c->confirm) {
2039 			debug2("callback start");
2040 			c->confirm(c->self, NULL);
2041 			debug2("callback done");
2042 		}
2043 		debug("channel %d: open confirm rwindow %u rmax %u", c->self,
2044 		    c->remote_window, c->remote_maxpacket);
2045 	}
2046 	packet_check_eom();
2047 }
2048 
2049 static char *
2050 reason2txt(int reason)
2051 {
2052 	switch (reason) {
2053 	case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
2054 		return "administratively prohibited";
2055 	case SSH2_OPEN_CONNECT_FAILED:
2056 		return "connect failed";
2057 	case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
2058 		return "unknown channel type";
2059 	case SSH2_OPEN_RESOURCE_SHORTAGE:
2060 		return "resource shortage";
2061 	}
2062 	return "unknown reason";
2063 }
2064 
2065 void
2066 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
2067 {
2068 	int id, reason;
2069 	char *msg = NULL, *lang = NULL;
2070 	Channel *c;
2071 
2072 	id = packet_get_int();
2073 	c = channel_lookup(id);
2074 
2075 	if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2076 		packet_disconnect("Received open failure for "
2077 		    "non-opening channel %d.", id);
2078 	if (compat20) {
2079 		reason = packet_get_int();
2080 		if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2081 			msg  = packet_get_string(NULL);
2082 			lang = packet_get_string(NULL);
2083 		}
2084 		log("channel %d: open failed: %s%s%s", id,
2085 		    reason2txt(reason), msg ? ": ": "", msg ? msg : "");
2086 		if (msg != NULL)
2087 			xfree(msg);
2088 		if (lang != NULL)
2089 			xfree(lang);
2090 	}
2091 	packet_check_eom();
2092 	/* Free the channel.  This will also close the socket. */
2093 	channel_free(c);
2094 }
2095 
2096 void
2097 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
2098 {
2099 	Channel *c;
2100 	int id;
2101 	u_int adjust;
2102 
2103 	if (!compat20)
2104 		return;
2105 
2106 	/* Get the channel number and verify it. */
2107 	id = packet_get_int();
2108 	c = channel_lookup(id);
2109 
2110 	if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
2111 		log("Received window adjust for "
2112 		    "non-open channel %d.", id);
2113 		return;
2114 	}
2115 	adjust = packet_get_int();
2116 	packet_check_eom();
2117 	debug2("channel %d: rcvd adjust %u", id, adjust);
2118 	c->remote_window += adjust;
2119 }
2120 
2121 void
2122 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
2123 {
2124 	Channel *c = NULL;
2125 	u_short host_port;
2126 	char *host, *originator_string;
2127 	int remote_id, sock = -1;
2128 
2129 	remote_id = packet_get_int();
2130 	host = packet_get_string(NULL);
2131 	host_port = packet_get_int();
2132 
2133 	if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2134 		originator_string = packet_get_string(NULL);
2135 	} else {
2136 		originator_string = xstrdup("unknown (remote did not supply name)");
2137 	}
2138 	packet_check_eom();
2139 	sock = channel_connect_to(host, host_port);
2140 	if (sock != -1) {
2141 		c = channel_new("connected socket",
2142 		    SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
2143 		    originator_string, 1);
2144 		c->remote_id = remote_id;
2145 	}
2146 	if (c == NULL) {
2147 		packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2148 		packet_put_int(remote_id);
2149 		packet_send();
2150 	}
2151 	xfree(host);
2152 }
2153 
2154 
2155 /* -- tcp forwarding */
2156 
2157 void
2158 channel_set_af(int af)
2159 {
2160 	IPv4or6 = af;
2161 }
2162 
2163 static int
2164 channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port,
2165     const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2166 {
2167 	Channel *c;
2168 	int success, sock, on = 1;
2169 	struct addrinfo hints, *ai, *aitop;
2170 	const char *host;
2171 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2172 
2173 	success = 0;
2174 	host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2175 	    listen_addr : host_to_connect;
2176 
2177 	if (host == NULL) {
2178 		error("No forward host name.");
2179 		return success;
2180 	}
2181 	if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
2182 		error("Forward host name too long.");
2183 		return success;
2184 	}
2185 
2186 	/*
2187 	 * getaddrinfo returns a loopback address if the hostname is
2188 	 * set to NULL and hints.ai_flags is not AI_PASSIVE
2189 	 */
2190 	memset(&hints, 0, sizeof(hints));
2191 	hints.ai_family = IPv4or6;
2192 	hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
2193 	hints.ai_socktype = SOCK_STREAM;
2194 	snprintf(strport, sizeof strport, "%d", listen_port);
2195 	if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
2196 		packet_disconnect("getaddrinfo: fatal error");
2197 
2198 	for (ai = aitop; ai; ai = ai->ai_next) {
2199 		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2200 			continue;
2201 		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2202 		    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2203 			error("channel_setup_fwd_listener: getnameinfo failed");
2204 			continue;
2205 		}
2206 		/* Create a port to listen for the host. */
2207 		sock = socket(ai->ai_family, SOCK_STREAM, 0);
2208 		if (sock < 0) {
2209 			/* this is no error since kernel may not support ipv6 */
2210 			verbose("socket: %.100s", strerror(errno));
2211 			continue;
2212 		}
2213 		/*
2214 		 * Set socket options.
2215 		 * Allow local port reuse in TIME_WAIT.
2216 		 */
2217 		if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on,
2218 		    sizeof(on)) == -1)
2219 			error("setsockopt SO_REUSEADDR: %s", strerror(errno));
2220 
2221 		debug("Local forwarding listening on %s port %s.", ntop, strport);
2222 
2223 		/* Bind the socket to the address. */
2224 		if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2225 			/* address can be in use ipv6 address is already bound */
2226 			if (!ai->ai_next)
2227 				error("bind: %.100s", strerror(errno));
2228 			else
2229 				verbose("bind: %.100s", strerror(errno));
2230 
2231 			close(sock);
2232 			continue;
2233 		}
2234 		/* Start listening for connections on the socket. */
2235 		if (listen(sock, 5) < 0) {
2236 			error("listen: %.100s", strerror(errno));
2237 			close(sock);
2238 			continue;
2239 		}
2240 		/* Allocate a channel number for the socket. */
2241 		c = channel_new("port listener", type, sock, sock, -1,
2242 		    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2243 		    0, xstrdup("port listener"), 1);
2244 		strlcpy(c->path, host, sizeof(c->path));
2245 		c->host_port = port_to_connect;
2246 		c->listening_port = listen_port;
2247 		success = 1;
2248 	}
2249 	if (success == 0)
2250 		error("channel_setup_fwd_listener: cannot listen to port: %d",
2251 		    listen_port);
2252 	freeaddrinfo(aitop);
2253 	return success;
2254 }
2255 
2256 /* protocol local port fwd, used by ssh (and sshd in v1) */
2257 int
2258 channel_setup_local_fwd_listener(u_short listen_port,
2259     const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2260 {
2261 	return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
2262 	    NULL, listen_port, host_to_connect, port_to_connect, gateway_ports);
2263 }
2264 
2265 /* protocol v2 remote port fwd, used by sshd */
2266 int
2267 channel_setup_remote_fwd_listener(const char *listen_address,
2268     u_short listen_port, int gateway_ports)
2269 {
2270 	return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
2271 	    listen_address, listen_port, NULL, 0, gateway_ports);
2272 }
2273 
2274 /*
2275  * Initiate forwarding of connections to port "port" on remote host through
2276  * the secure channel to host:port from local side.
2277  */
2278 
2279 void
2280 channel_request_remote_forwarding(u_short listen_port,
2281     const char *host_to_connect, u_short port_to_connect)
2282 {
2283 	int type, success = 0;
2284 
2285 	/* Record locally that connection to this host/port is permitted. */
2286 	if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2287 		fatal("channel_request_remote_forwarding: too many forwards");
2288 
2289 	/* Send the forward request to the remote side. */
2290 	if (compat20) {
2291 		const char *address_to_bind = "0.0.0.0";
2292 		packet_start(SSH2_MSG_GLOBAL_REQUEST);
2293 		packet_put_cstring("tcpip-forward");
2294 		packet_put_char(1);			/* boolean: want reply */
2295 		packet_put_cstring(address_to_bind);
2296 		packet_put_int(listen_port);
2297 		packet_send();
2298 		packet_write_wait();
2299 		/* Assume that server accepts the request */
2300 		success = 1;
2301 	} else {
2302 		packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
2303 		packet_put_int(listen_port);
2304 		packet_put_cstring(host_to_connect);
2305 		packet_put_int(port_to_connect);
2306 		packet_send();
2307 		packet_write_wait();
2308 
2309 		/* Wait for response from the remote side. */
2310 		type = packet_read();
2311 		switch (type) {
2312 		case SSH_SMSG_SUCCESS:
2313 			success = 1;
2314 			break;
2315 		case SSH_SMSG_FAILURE:
2316 			log("Warning: Server denied remote port forwarding.");
2317 			break;
2318 		default:
2319 			/* Unknown packet */
2320 			packet_disconnect("Protocol error for port forward request:"
2321 			    "received packet type %d.", type);
2322 		}
2323 	}
2324 	if (success) {
2325 		permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
2326 		permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
2327 		permitted_opens[num_permitted_opens].listen_port = listen_port;
2328 		num_permitted_opens++;
2329 	}
2330 }
2331 
2332 /*
2333  * This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
2334  * listening for the port, and sends back a success reply (or disconnect
2335  * message if there was an error).  This never returns if there was an error.
2336  */
2337 
2338 void
2339 channel_input_port_forward_request(int is_root, int gateway_ports)
2340 {
2341 	u_short port, host_port;
2342 	char *hostname;
2343 
2344 	/* Get arguments from the packet. */
2345 	port = packet_get_int();
2346 	hostname = packet_get_string(NULL);
2347 	host_port = packet_get_int();
2348 
2349 #ifndef HAVE_CYGWIN
2350 	/*
2351 	 * Check that an unprivileged user is not trying to forward a
2352 	 * privileged port.
2353 	 */
2354 	if (port < IPPORT_RESERVED && !is_root)
2355 		packet_disconnect("Requested forwarding of port %d but user is not root.",
2356 				  port);
2357 #endif
2358 	/* Initiate forwarding */
2359 	channel_setup_local_fwd_listener(port, hostname, host_port, gateway_ports);
2360 
2361 	/* Free the argument string. */
2362 	xfree(hostname);
2363 }
2364 
2365 /*
2366  * Permits opening to any host/port if permitted_opens[] is empty.  This is
2367  * usually called by the server, because the user could connect to any port
2368  * anyway, and the server has no way to know but to trust the client anyway.
2369  */
2370 void
2371 channel_permit_all_opens(void)
2372 {
2373 	if (num_permitted_opens == 0)
2374 		all_opens_permitted = 1;
2375 }
2376 
2377 void
2378 channel_add_permitted_opens(char *host, int port)
2379 {
2380 	if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2381 		fatal("channel_request_remote_forwarding: too many forwards");
2382 	debug("allow port forwarding to host %s port %d", host, port);
2383 
2384 	permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
2385 	permitted_opens[num_permitted_opens].port_to_connect = port;
2386 	num_permitted_opens++;
2387 
2388 	all_opens_permitted = 0;
2389 }
2390 
2391 void
2392 channel_clear_permitted_opens(void)
2393 {
2394 	int i;
2395 
2396 	for (i = 0; i < num_permitted_opens; i++)
2397 		xfree(permitted_opens[i].host_to_connect);
2398 	num_permitted_opens = 0;
2399 
2400 }
2401 
2402 
2403 /* return socket to remote host, port */
2404 static int
2405 connect_to(const char *host, u_short port)
2406 {
2407 	struct addrinfo hints, *ai, *aitop;
2408 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2409 	int gaierr;
2410 	int sock = -1;
2411 
2412 	memset(&hints, 0, sizeof(hints));
2413 	hints.ai_family = IPv4or6;
2414 	hints.ai_socktype = SOCK_STREAM;
2415 	snprintf(strport, sizeof strport, "%d", port);
2416 	if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
2417 		error("connect_to %.100s: unknown host (%s)", host,
2418 		    gai_strerror(gaierr));
2419 		return -1;
2420 	}
2421 	for (ai = aitop; ai; ai = ai->ai_next) {
2422 		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2423 			continue;
2424 		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2425 		    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2426 			error("connect_to: getnameinfo failed");
2427 			continue;
2428 		}
2429 		sock = socket(ai->ai_family, SOCK_STREAM, 0);
2430 		if (sock < 0) {
2431 			error("socket: %.100s", strerror(errno));
2432 			continue;
2433 		}
2434 		if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0)
2435 			fatal("connect_to: F_SETFL: %s", strerror(errno));
2436 		if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
2437 		    errno != EINPROGRESS) {
2438 			error("connect_to %.100s port %s: %.100s", ntop, strport,
2439 			    strerror(errno));
2440 			close(sock);
2441 			continue;	/* fail -- try next */
2442 		}
2443 		break; /* success */
2444 
2445 	}
2446 	freeaddrinfo(aitop);
2447 	if (!ai) {
2448 		error("connect_to %.100s port %d: failed.", host, port);
2449 		return -1;
2450 	}
2451 	/* success */
2452 	set_nodelay(sock);
2453 	return sock;
2454 }
2455 
2456 int
2457 channel_connect_by_listen_address(u_short listen_port)
2458 {
2459 	int i;
2460 
2461 	for (i = 0; i < num_permitted_opens; i++)
2462 		if (permitted_opens[i].listen_port == listen_port)
2463 			return connect_to(
2464 			    permitted_opens[i].host_to_connect,
2465 			    permitted_opens[i].port_to_connect);
2466 	error("WARNING: Server requests forwarding for unknown listen_port %d",
2467 	    listen_port);
2468 	return -1;
2469 }
2470 
2471 /* Check if connecting to that port is permitted and connect. */
2472 int
2473 channel_connect_to(const char *host, u_short port)
2474 {
2475 	int i, permit;
2476 
2477 	permit = all_opens_permitted;
2478 	if (!permit) {
2479 		for (i = 0; i < num_permitted_opens; i++)
2480 			if (permitted_opens[i].port_to_connect == port &&
2481 			    strcmp(permitted_opens[i].host_to_connect, host) == 0)
2482 				permit = 1;
2483 
2484 	}
2485 	if (!permit) {
2486 		log("Received request to connect to host %.100s port %d, "
2487 		    "but the request was denied.", host, port);
2488 		return -1;
2489 	}
2490 	return connect_to(host, port);
2491 }
2492 
2493 /* -- X11 forwarding */
2494 
2495 /*
2496  * Creates an internet domain socket for listening for X11 connections.
2497  * Returns 0 and a suitable display number for the DISPLAY variable
2498  * stored in display_numberp , or -1 if an error occurs.
2499  */
2500 int
2501 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
2502     int single_connection, u_int *display_numberp)
2503 {
2504 	Channel *nc = NULL;
2505 	int display_number, sock;
2506 	u_short port;
2507 	struct addrinfo hints, *ai, *aitop;
2508 	char strport[NI_MAXSERV];
2509 	int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
2510 
2511 	for (display_number = x11_display_offset;
2512 	    display_number < MAX_DISPLAYS;
2513 	    display_number++) {
2514 		port = 6000 + display_number;
2515 		memset(&hints, 0, sizeof(hints));
2516 		hints.ai_family = IPv4or6;
2517 		hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
2518 		hints.ai_socktype = SOCK_STREAM;
2519 		snprintf(strport, sizeof strport, "%d", port);
2520 		if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
2521 			error("getaddrinfo: %.100s", gai_strerror(gaierr));
2522 			return -1;
2523 		}
2524 		for (ai = aitop; ai; ai = ai->ai_next) {
2525 			if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2526 				continue;
2527 			sock = socket(ai->ai_family, SOCK_STREAM, 0);
2528 			if (sock < 0) {
2529 				if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) {
2530 					error("socket: %.100s", strerror(errno));
2531 					return -1;
2532 				} else {
2533 					debug("x11_create_display_inet: Socket family %d not supported",
2534 						 ai->ai_family);
2535 					continue;
2536 				}
2537 			}
2538 #ifdef IPV6_V6ONLY
2539 			if (ai->ai_family == AF_INET6) {
2540 				int on = 1;
2541 				if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0)
2542 					error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno));
2543 			}
2544 #endif
2545 			if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2546 				debug("bind port %d: %.100s", port, strerror(errno));
2547 				close(sock);
2548 
2549 				if (ai->ai_next)
2550 					continue;
2551 
2552 				for (n = 0; n < num_socks; n++) {
2553 					close(socks[n]);
2554 				}
2555 				num_socks = 0;
2556 				break;
2557 			}
2558 			socks[num_socks++] = sock;
2559 #ifndef DONT_TRY_OTHER_AF
2560 			if (num_socks == NUM_SOCKS)
2561 				break;
2562 #else
2563 			if (x11_use_localhost) {
2564 				if (num_socks == NUM_SOCKS)
2565 					break;
2566 			} else {
2567 				break;
2568 			}
2569 #endif
2570 		}
2571 		freeaddrinfo(aitop);
2572 		if (num_socks > 0)
2573 			break;
2574 	}
2575 	if (display_number >= MAX_DISPLAYS) {
2576 		error("Failed to allocate internet-domain X11 display socket.");
2577 		return -1;
2578 	}
2579 	/* Start listening for connections on the socket. */
2580 	for (n = 0; n < num_socks; n++) {
2581 		sock = socks[n];
2582 		if (listen(sock, 5) < 0) {
2583 			error("listen: %.100s", strerror(errno));
2584 			close(sock);
2585 			return -1;
2586 		}
2587 	}
2588 
2589 	/* Allocate a channel for each socket. */
2590 	for (n = 0; n < num_socks; n++) {
2591 		sock = socks[n];
2592 		nc = channel_new("x11 listener",
2593 		    SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
2594 		    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2595 		    0, xstrdup("X11 inet listener"), 1);
2596 		nc->single_connection = single_connection;
2597 	}
2598 
2599 	/* Return the display number for the DISPLAY environment variable. */
2600 	*display_numberp = display_number;
2601 	return (0);
2602 }
2603 
2604 static int
2605 connect_local_xsocket(u_int dnr)
2606 {
2607 	int sock;
2608 	struct sockaddr_un addr;
2609 
2610 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
2611 	if (sock < 0)
2612 		error("socket: %.100s", strerror(errno));
2613 	memset(&addr, 0, sizeof(addr));
2614 	addr.sun_family = AF_UNIX;
2615 	snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
2616 	if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
2617 		return sock;
2618 	close(sock);
2619 	error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
2620 	return -1;
2621 }
2622 
2623 int
2624 x11_connect_display(void)
2625 {
2626 	int display_number, sock = 0;
2627 	const char *display;
2628 	char buf[1024], *cp;
2629 	struct addrinfo hints, *ai, *aitop;
2630 	char strport[NI_MAXSERV];
2631 	int gaierr;
2632 
2633 	/* Try to open a socket for the local X server. */
2634 	display = getenv("DISPLAY");
2635 	if (!display) {
2636 		error("DISPLAY not set.");
2637 		return -1;
2638 	}
2639 	/*
2640 	 * Now we decode the value of the DISPLAY variable and make a
2641 	 * connection to the real X server.
2642 	 */
2643 
2644 	/*
2645 	 * Check if it is a unix domain socket.  Unix domain displays are in
2646 	 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
2647 	 */
2648 	if (strncmp(display, "unix:", 5) == 0 ||
2649 	    display[0] == ':') {
2650 		/* Connect to the unix domain socket. */
2651 		if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
2652 			error("Could not parse display number from DISPLAY: %.100s",
2653 			    display);
2654 			return -1;
2655 		}
2656 		/* Create a socket. */
2657 		sock = connect_local_xsocket(display_number);
2658 		if (sock < 0)
2659 			return -1;
2660 
2661 		/* OK, we now have a connection to the display. */
2662 		return sock;
2663 	}
2664 	/*
2665 	 * Connect to an inet socket.  The DISPLAY value is supposedly
2666 	 * hostname:d[.s], where hostname may also be numeric IP address.
2667 	 */
2668 	strlcpy(buf, display, sizeof(buf));
2669 	cp = strchr(buf, ':');
2670 	if (!cp) {
2671 		error("Could not find ':' in DISPLAY: %.100s", display);
2672 		return -1;
2673 	}
2674 	*cp = 0;
2675 	/* buf now contains the host name.  But first we parse the display number. */
2676 	if (sscanf(cp + 1, "%d", &display_number) != 1) {
2677 		error("Could not parse display number from DISPLAY: %.100s",
2678 		    display);
2679 		return -1;
2680 	}
2681 
2682 	/* Look up the host address */
2683 	memset(&hints, 0, sizeof(hints));
2684 	hints.ai_family = IPv4or6;
2685 	hints.ai_socktype = SOCK_STREAM;
2686 	snprintf(strport, sizeof strport, "%d", 6000 + display_number);
2687 	if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
2688 		error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
2689 		return -1;
2690 	}
2691 	for (ai = aitop; ai; ai = ai->ai_next) {
2692 		/* Create a socket. */
2693 		sock = socket(ai->ai_family, SOCK_STREAM, 0);
2694 		if (sock < 0) {
2695 			debug("socket: %.100s", strerror(errno));
2696 			continue;
2697 		}
2698 		/* Connect it to the display. */
2699 		if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2700 			debug("connect %.100s port %d: %.100s", buf,
2701 			    6000 + display_number, strerror(errno));
2702 			close(sock);
2703 			continue;
2704 		}
2705 		/* Success */
2706 		break;
2707 	}
2708 	freeaddrinfo(aitop);
2709 	if (!ai) {
2710 		error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
2711 		    strerror(errno));
2712 		return -1;
2713 	}
2714 	set_nodelay(sock);
2715 	return sock;
2716 }
2717 
2718 /*
2719  * This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
2720  * the remote channel number.  We should do whatever we want, and respond
2721  * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
2722  */
2723 
2724 void
2725 x11_input_open(int type, u_int32_t seq, void *ctxt)
2726 {
2727 	Channel *c = NULL;
2728 	int remote_id, sock = 0;
2729 	char *remote_host;
2730 
2731 	debug("Received X11 open request.");
2732 
2733 	remote_id = packet_get_int();
2734 
2735 	if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2736 		remote_host = packet_get_string(NULL);
2737 	} else {
2738 		remote_host = xstrdup("unknown (remote did not supply name)");
2739 	}
2740 	packet_check_eom();
2741 
2742 	/* Obtain a connection to the real X display. */
2743 	sock = x11_connect_display();
2744 	if (sock != -1) {
2745 		/* Allocate a channel for this connection. */
2746 		c = channel_new("connected x11 socket",
2747 		    SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
2748 		    remote_host, 1);
2749 		c->remote_id = remote_id;
2750 		c->force_drain = 1;
2751 	}
2752 	if (c == NULL) {
2753 		/* Send refusal to the remote host. */
2754 		packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2755 		packet_put_int(remote_id);
2756 	} else {
2757 		/* Send a confirmation to the remote host. */
2758 		packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2759 		packet_put_int(remote_id);
2760 		packet_put_int(c->self);
2761 	}
2762 	packet_send();
2763 }
2764 
2765 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
2766 void
2767 deny_input_open(int type, u_int32_t seq, void *ctxt)
2768 {
2769 	int rchan = packet_get_int();
2770 
2771 	switch (type) {
2772 	case SSH_SMSG_AGENT_OPEN:
2773 		error("Warning: ssh server tried agent forwarding.");
2774 		break;
2775 	case SSH_SMSG_X11_OPEN:
2776 		error("Warning: ssh server tried X11 forwarding.");
2777 		break;
2778 	default:
2779 		error("deny_input_open: type %d", type);
2780 		break;
2781 	}
2782 	error("Warning: this is probably a break in attempt by a malicious server.");
2783 	packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2784 	packet_put_int(rchan);
2785 	packet_send();
2786 }
2787 
2788 /*
2789  * Requests forwarding of X11 connections, generates fake authentication
2790  * data, and enables authentication spoofing.
2791  * This should be called in the client only.
2792  */
2793 void
2794 x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
2795     const char *proto, const char *data)
2796 {
2797 	u_int data_len = (u_int) strlen(data) / 2;
2798 	u_int i, value;
2799 	char *new_data;
2800 	int screen_number;
2801 	const char *cp;
2802 	u_int32_t rand = 0;
2803 
2804 	cp = disp;
2805 	if (disp)
2806 		cp = strchr(disp, ':');
2807 	if (cp)
2808 		cp = strchr(cp, '.');
2809 	if (cp)
2810 		screen_number = atoi(cp + 1);
2811 	else
2812 		screen_number = 0;
2813 
2814 	/* Save protocol name. */
2815 	x11_saved_proto = xstrdup(proto);
2816 
2817 	/*
2818 	 * Extract real authentication data and generate fake data of the
2819 	 * same length.
2820 	 */
2821 	x11_saved_data = xmalloc(data_len);
2822 	x11_fake_data = xmalloc(data_len);
2823 	for (i = 0; i < data_len; i++) {
2824 		if (sscanf(data + 2 * i, "%2x", &value) != 1)
2825 			fatal("x11_request_forwarding: bad authentication data: %.100s", data);
2826 		if (i % 4 == 0)
2827 			rand = arc4random();
2828 		x11_saved_data[i] = value;
2829 		x11_fake_data[i] = rand & 0xff;
2830 		rand >>= 8;
2831 	}
2832 	x11_saved_data_len = data_len;
2833 	x11_fake_data_len = data_len;
2834 
2835 	/* Convert the fake data into hex. */
2836 	new_data = tohex(x11_fake_data, data_len);
2837 
2838 	/* Send the request packet. */
2839 	if (compat20) {
2840 		channel_request_start(client_session_id, "x11-req", 0);
2841 		packet_put_char(0);	/* XXX bool single connection */
2842 	} else {
2843 		packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
2844 	}
2845 	packet_put_cstring(proto);
2846 	packet_put_cstring(new_data);
2847 	packet_put_int(screen_number);
2848 	packet_send();
2849 	packet_write_wait();
2850 	xfree(new_data);
2851 }
2852 
2853 
2854 /* -- agent forwarding */
2855 
2856 /* Sends a message to the server to request authentication fd forwarding. */
2857 
2858 void
2859 auth_request_forwarding(void)
2860 {
2861 	packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
2862 	packet_send();
2863 	packet_write_wait();
2864 }
2865 
2866 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
2867 
2868 void
2869 auth_input_open_request(int type, u_int32_t seq, void *ctxt)
2870 {
2871 	Channel *c = NULL;
2872 	int remote_id, sock;
2873 	char *name;
2874 
2875 	/* Read the remote channel number from the message. */
2876 	remote_id = packet_get_int();
2877 	packet_check_eom();
2878 
2879 	/*
2880 	 * Get a connection to the local authentication agent (this may again
2881 	 * get forwarded).
2882 	 */
2883 	sock = ssh_get_authentication_socket();
2884 
2885 	/*
2886 	 * If we could not connect the agent, send an error message back to
2887 	 * the server. This should never happen unless the agent dies,
2888 	 * because authentication forwarding is only enabled if we have an
2889 	 * agent.
2890 	 */
2891 	if (sock >= 0) {
2892 		name = xstrdup("authentication agent connection");
2893 		c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
2894 		    -1, 0, 0, 0, name, 1);
2895 		c->remote_id = remote_id;
2896 		c->force_drain = 1;
2897 	}
2898 	if (c == NULL) {
2899 		packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2900 		packet_put_int(remote_id);
2901 	} else {
2902 		/* Send a confirmation to the remote host. */
2903 		debug("Forwarding authentication connection.");
2904 		packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2905 		packet_put_int(remote_id);
2906 		packet_put_int(c->self);
2907 	}
2908 	packet_send();
2909 }
2910