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