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