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