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