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