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