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