channels.c revision 60573
121259Swollman/*
221259Swollman *
321259Swollman * channels.c
421259Swollman *
521259Swollman * Author: Tatu Ylonen <ylo@cs.hut.fi>
621259Swollman *
721259Swollman * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
821259Swollman *                    All rights reserved
921259Swollman *
1021259Swollman * Created: Fri Mar 24 16:35:24 1995 ylo
1121259Swollman *
1221259Swollman * This file contains functions for generic socket connection forwarding.
1321259Swollman * There is also code for initiating connection forwarding for X11 connections,
1421259Swollman * arbitrary tcp/ip connections, and the authentication agent connection.
1521259Swollman *
1621259Swollman * SSH2 support added by Markus Friedl.
1721259Swollman */
1821259Swollman
1921259Swollman#include "includes.h"
2021259SwollmanRCSID("$Id: channels.c,v 1.57 2000/05/08 17:42:24 markus Exp $");
2121259Swollman
2221259Swollman#include "ssh.h"
2321259Swollman#include "packet.h"
2421259Swollman#include "xmalloc.h"
2521259Swollman#include "buffer.h"
2621259Swollman#include "authfd.h"
2721259Swollman#include "uidswap.h"
2821259Swollman#include "readconf.h"
2921259Swollman#include "servconf.h"
3021259Swollman
3121259Swollman#include "channels.h"
3221259Swollman#include "nchan.h"
3321259Swollman#include "compat.h"
3421404Swollman
3521259Swollman#include "ssh2.h"
3621259Swollman
3721259Swollman/* Maximum number of fake X11 displays to try. */
3821259Swollman#define MAX_DISPLAYS  1000
3921259Swollman
4021259Swollman/* Max len of agent socket */
4121259Swollman#define MAX_SOCKET_NAME 100
4221259Swollman
4321259Swollman/* default window/packet sizes for tcp/x11-fwd-channel */
4421259Swollman#define CHAN_TCP_WINDOW_DEFAULT	(8*1024)
4521259Swollman#define CHAN_TCP_PACKET_DEFAULT	(CHAN_TCP_WINDOW_DEFAULT/2)
4621259Swollman#define CHAN_X11_WINDOW_DEFAULT	(4*1024)
4721259Swollman#define CHAN_X11_PACKET_DEFAULT	(CHAN_X11_WINDOW_DEFAULT/2)
4821259Swollman
4921259Swollman/*
5021259Swollman * Pointer to an array containing all allocated channels.  The array is
5121259Swollman * dynamically extended as needed.
5221259Swollman */
5321259Swollmanstatic Channel *channels = NULL;
5421259Swollman
5521259Swollman/*
5621259Swollman * Size of the channel array.  All slots of the array must always be
5721259Swollman * initialized (at least the type field); unused slots are marked with type
5821259Swollman * SSH_CHANNEL_FREE.
5921259Swollman */
6021259Swollmanstatic int channels_alloc = 0;
6121259Swollman
6221259Swollman/*
6321259Swollman * Maximum file descriptor value used in any of the channels.  This is
6421259Swollman * updated in channel_allocate.
6521259Swollman */
6621259Swollmanstatic int channel_max_fd_value = 0;
6721259Swollman
6821259Swollman/* Name and directory of socket for authentication agent forwarding. */
6921259Swollmanstatic char *channel_forwarded_auth_socket_name = NULL;
7021259Swollmanstatic char *channel_forwarded_auth_socket_dir = NULL;
7121259Swollman
7221259Swollman/* Saved X11 authentication protocol name. */
7321259Swollmanchar *x11_saved_proto = NULL;
7421259Swollman
7521259Swollman/* Saved X11 authentication data.  This is the real data. */
7621259Swollmanchar *x11_saved_data = NULL;
7721259Swollmanunsigned int x11_saved_data_len = 0;
7821259Swollman
7921259Swollman/*
8021404Swollman * Fake X11 authentication data.  This is what the server will be sending us;
8121259Swollman * we should replace any occurrences of this by the real data.
8221259Swollman */
8321259Swollmanchar *x11_fake_data = NULL;
8421259Swollmanunsigned int x11_fake_data_len;
8521259Swollman
8621259Swollman/*
8721259Swollman * Data structure for storing which hosts are permitted for forward requests.
8821259Swollman * The local sides of any remote forwards are stored in this array to prevent
8921259Swollman * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
9021259Swollman * network (which might be behind a firewall).
9121259Swollman */
9221259Swollmantypedef struct {
9321259Swollman	char *host_to_connect;		/* Connect to 'host'. */
9421259Swollman	u_short port_to_connect;	/* Connect to 'port'. */
9521259Swollman	u_short listen_port;		/* Remote side should listen port number. */
9621259Swollman} ForwardPermission;
9721259Swollman
9821259Swollman/* List of all permitted host/port pairs to connect. */
9921259Swollmanstatic ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
10021259Swollman/* Number of permitted host/port pairs in the array. */
10121259Swollmanstatic int num_permitted_opens = 0;
10221259Swollman/*
10321259Swollman * If this is true, all opens are permitted.  This is the case on the server
10421259Swollman * on which we have to trust the client anyway, and the user could do
10521259Swollman * anything after logging in anyway.
10621259Swollman */
10721259Swollmanstatic int all_opens_permitted = 0;
10821259Swollman
10921259Swollman/* This is set to true if both sides support SSH_PROTOFLAG_HOST_IN_FWD_OPEN. */
11021259Swollmanstatic int have_hostname_in_open = 0;
11121259Swollman
11221259Swollman/* Sets specific protocol options. */
11321404Swollman
11421404Swollmanvoid
11521259Swollmanchannel_set_options(int hostname_in_open)
11621259Swollman{
11721259Swollman	have_hostname_in_open = hostname_in_open;
11821259Swollman}
11921259Swollman
12021259Swollman/*
12121259Swollman * Permits opening to any host/port in SSH_MSG_PORT_OPEN.  This is usually
12221259Swollman * called by the server, because the user could connect to any port anyway,
12321259Swollman * and the server has no way to know but to trust the client anyway.
12421259Swollman */
12521259Swollman
12621259Swollmanvoid
12721259Swollmanchannel_permit_all_opens()
12821259Swollman{
12921259Swollman	all_opens_permitted = 1;
13021259Swollman}
13121259Swollman
13221259Swollman/* lookup channel by id */
13321259Swollman
13421259SwollmanChannel *
13521259Swollmanchannel_lookup(int id)
13621259Swollman{
13721404Swollman	Channel *c;
13821404Swollman	if (id < 0 && id > channels_alloc) {
13921259Swollman		log("channel_lookup: %d: bad id", id);
14021259Swollman		return NULL;
14121259Swollman	}
14221259Swollman	c = &channels[id];
14321259Swollman	if (c->type == SSH_CHANNEL_FREE) {
14421259Swollman		log("channel_lookup: %d: bad id: channel free", id);
14521259Swollman		return NULL;
14621259Swollman	}
14721259Swollman	return c;
14821259Swollman}
14921259Swollman
15021259Swollmanvoid
15121259Swollmanset_nonblock(int fd)
15221259Swollman{
15321259Swollman	int val;
15421259Swollman	val = fcntl(fd, F_GETFL, 0);
15521259Swollman	if (val < 0) {
15621259Swollman		error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
15721259Swollman		return;
15821259Swollman	}
15921259Swollman	if (val & O_NONBLOCK)
16021259Swollman		return;
16121259Swollman	debug("fd %d setting O_NONBLOCK", fd);
16221259Swollman	val |= O_NONBLOCK;
16321259Swollman	if (fcntl(fd, F_SETFL, val) == -1)
16421259Swollman		error("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd, strerror(errno));
16521259Swollman}
16621259Swollman
16721259Swollman/*
16821259Swollman * Register filedescriptors for a channel, used when allocating a channel or
16921259Swollman * when the channel consumer/producer is ready, e.g. shell exec'd
17021259Swollman */
17121259Swollman
17221259Swollmanvoid
17321259Swollmanchannel_register_fds(Channel *c, int rfd, int wfd, int efd, int extusage)
17421259Swollman{
17521259Swollman	/* Update the maximum file descriptor value. */
17621259Swollman	if (rfd > channel_max_fd_value)
17721259Swollman		channel_max_fd_value = rfd;
17821259Swollman	if (wfd > channel_max_fd_value)
17921259Swollman		channel_max_fd_value = wfd;
18021259Swollman	if (efd > channel_max_fd_value)
18121259Swollman		channel_max_fd_value = efd;
18221259Swollman	/* XXX set close-on-exec -markus */
18321259Swollman
18421259Swollman	c->rfd = rfd;
18521259Swollman	c->wfd = wfd;
18621259Swollman	c->sock = (rfd == wfd) ? rfd : -1;
18721259Swollman	c->efd = efd;
18821259Swollman	c->extended_usage = extusage;
18921259Swollman	if (rfd != -1)
19021259Swollman		set_nonblock(rfd);
19121259Swollman	if (wfd != -1)
19221259Swollman		set_nonblock(wfd);
19321259Swollman	if (efd != -1)
19421259Swollman		set_nonblock(efd);
19521259Swollman}
19621259Swollman
19721259Swollman/*
19821259Swollman * Allocate a new channel object and set its type and socket. This will cause
19921259Swollman * remote_name to be freed.
20021259Swollman */
20121259Swollman
20221259Swollmanint
20321259Swollmanchannel_new(char *ctype, int type, int rfd, int wfd, int efd,
20421259Swollman    int window, int maxpack, int extusage, char *remote_name)
20521259Swollman{
20621259Swollman	int i, found;
20721259Swollman	Channel *c;
20821259Swollman
20921259Swollman	/* Do initial allocation if this is the first call. */
21021259Swollman	if (channels_alloc == 0) {
21121259Swollman		chan_init();
21221259Swollman		channels_alloc = 10;
21321259Swollman		channels = xmalloc(channels_alloc * sizeof(Channel));
21421259Swollman		for (i = 0; i < channels_alloc; i++)
21521259Swollman			channels[i].type = SSH_CHANNEL_FREE;
21621259Swollman		/*
21721259Swollman		 * Kludge: arrange a call to channel_stop_listening if we
21821259Swollman		 * terminate with fatal().
21921259Swollman		 */
22021259Swollman		fatal_add_cleanup((void (*) (void *)) channel_stop_listening, NULL);
22121259Swollman	}
22221259Swollman	/* Try to find a free slot where to put the new channel. */
22321259Swollman	for (found = -1, i = 0; i < channels_alloc; i++)
22421259Swollman		if (channels[i].type == SSH_CHANNEL_FREE) {
22521259Swollman			/* Found a free slot. */
22621259Swollman			found = i;
22721259Swollman			break;
22821259Swollman		}
22921259Swollman	if (found == -1) {
23021259Swollman		/* There are no free slots.  Take last+1 slot and expand the array.  */
23121259Swollman		found = channels_alloc;
23221259Swollman		channels_alloc += 10;
23321259Swollman		debug("channel: expanding %d", channels_alloc);
23421259Swollman		channels = xrealloc(channels, channels_alloc * sizeof(Channel));
23521259Swollman		for (i = found; i < channels_alloc; i++)
23621259Swollman			channels[i].type = SSH_CHANNEL_FREE;
23721259Swollman	}
23821259Swollman	/* Initialize and return new channel number. */
23921259Swollman	c = &channels[found];
24021259Swollman	buffer_init(&c->input);
24121259Swollman	buffer_init(&c->output);
24221259Swollman	buffer_init(&c->extended);
24321259Swollman	chan_init_iostates(c);
24421259Swollman	channel_register_fds(c, rfd, wfd, efd, extusage);
24521259Swollman	c->self = found;
24621259Swollman	c->type = type;
24721259Swollman	c->ctype = ctype;
24821259Swollman	c->local_window = window;
24921259Swollman	c->local_window_max = window;
25021259Swollman	c->local_consumed = 0;
25121259Swollman	c->local_maxpacket = maxpack;
25221259Swollman	c->remote_id = -1;
25321259Swollman	c->remote_name = remote_name;
25421259Swollman	c->remote_window = 0;
25521259Swollman	c->remote_maxpacket = 0;
25621259Swollman	c->cb_fn = NULL;
25721259Swollman	c->cb_arg = NULL;
25821259Swollman	c->cb_event = 0;
25921259Swollman	c->dettach_user = NULL;
26021404Swollman	debug("channel %d: new [%s]", found, remote_name);
26121404Swollman	return found;
26221404Swollman}
26321404Swollman/* old interface XXX */
26421404Swollmanint
26521404Swollmanchannel_allocate(int type, int sock, char *remote_name)
26621404Swollman{
26721404Swollman	return channel_new("", type, sock, sock, -1, 0, 0, 0, remote_name);
26821404Swollman}
26921404Swollman
27021404Swollman
27121404Swollman/* Close all channel fd/socket. */
27221404Swollman
27321404Swollmanvoid
27421259Swollmanchannel_close_fds(Channel *c)
27521259Swollman{
27621259Swollman	if (c->sock != -1) {
27721259Swollman		close(c->sock);
27821259Swollman		c->sock = -1;
27921259Swollman	}
28021259Swollman	if (c->rfd != -1) {
28121259Swollman		close(c->rfd);
28221259Swollman		c->rfd = -1;
28321259Swollman	}
28421259Swollman	if (c->wfd != -1) {
28521259Swollman		close(c->wfd);
28621259Swollman		c->wfd = -1;
28721259Swollman	}
28821259Swollman	if (c->efd != -1) {
28921259Swollman		close(c->efd);
29021259Swollman		c->efd = -1;
29121259Swollman	}
29221259Swollman}
29321404Swollman
29421404Swollman/* Free the channel and close its fd/socket. */
29521259Swollman
29621404Swollmanvoid
29721259Swollmanchannel_free(int id)
29821259Swollman{
29921259Swollman	Channel *c = channel_lookup(id);
30021259Swollman	if (c == NULL)
30121259Swollman		packet_disconnect("channel free: bad local channel %d", id);
30221259Swollman	debug("channel_free: channel %d: status: %s", id, channel_open_message());
30321259Swollman	if (c->dettach_user != NULL) {
30421259Swollman		debug("channel_free: channel %d: dettaching channel user", id);
30521259Swollman		c->dettach_user(c->self, NULL);
30621259Swollman	}
30721259Swollman	if (c->sock != -1)
30821259Swollman		shutdown(c->sock, SHUT_RDWR);
30921259Swollman	channel_close_fds(c);
31021259Swollman	buffer_free(&c->input);
31121259Swollman	buffer_free(&c->output);
31221259Swollman	buffer_free(&c->extended);
31321259Swollman	c->type = SSH_CHANNEL_FREE;
31421259Swollman	if (c->remote_name) {
31521259Swollman		xfree(c->remote_name);
31621259Swollman		c->remote_name = NULL;
31721259Swollman	}
31821259Swollman}
31921259Swollman
32021259Swollman/*
32121259Swollman * 'channel_pre*' are called just before select() to add any bits relevant to
32221259Swollman * channels in the select bitmasks.
32321259Swollman */
32421259Swollman/*
32521259Swollman * 'channel_post*': perform any appropriate operations for channels which
32621259Swollman * have events pending.
32721259Swollman */
328typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
329chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
330chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
331
332void
333channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
334{
335	FD_SET(c->sock, readset);
336}
337
338void
339channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
340{
341	if (buffer_len(&c->input) < packet_get_maxsize())
342		FD_SET(c->sock, readset);
343	if (buffer_len(&c->output) > 0)
344		FD_SET(c->sock, writeset);
345}
346
347void
348channel_pre_open_15(Channel *c, fd_set * readset, fd_set * writeset)
349{
350	/* test whether sockets are 'alive' for read/write */
351	if (c->istate == CHAN_INPUT_OPEN)
352		if (buffer_len(&c->input) < packet_get_maxsize())
353			FD_SET(c->sock, readset);
354	if (c->ostate == CHAN_OUTPUT_OPEN ||
355	    c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
356		if (buffer_len(&c->output) > 0) {
357			FD_SET(c->sock, writeset);
358		} else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
359			chan_obuf_empty(c);
360		}
361	}
362}
363
364void
365channel_pre_open_20(Channel *c, fd_set * readset, fd_set * writeset)
366{
367	if (c->istate == CHAN_INPUT_OPEN &&
368	    c->remote_window > 0 &&
369	    buffer_len(&c->input) < c->remote_window)
370		FD_SET(c->rfd, readset);
371	if (c->ostate == CHAN_OUTPUT_OPEN ||
372	    c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
373		if (buffer_len(&c->output) > 0) {
374			FD_SET(c->wfd, writeset);
375		} else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
376			chan_obuf_empty(c);
377		}
378	}
379	/** XXX check close conditions, too */
380	if (c->efd != -1) {
381		if (c->extended_usage == CHAN_EXTENDED_WRITE &&
382		    buffer_len(&c->extended) > 0)
383			FD_SET(c->efd, writeset);
384		else if (c->extended_usage == CHAN_EXTENDED_READ &&
385		    buffer_len(&c->extended) < c->remote_window)
386			FD_SET(c->efd, readset);
387	}
388}
389
390void
391channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
392{
393	if (buffer_len(&c->input) == 0) {
394		packet_start(SSH_MSG_CHANNEL_CLOSE);
395		packet_put_int(c->remote_id);
396		packet_send();
397		c->type = SSH_CHANNEL_CLOSED;
398		debug("Closing channel %d after input drain.", c->self);
399	}
400}
401
402void
403channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
404{
405	if (buffer_len(&c->output) == 0)
406		channel_free(c->self);
407	else
408		FD_SET(c->sock, writeset);
409}
410
411/*
412 * This is a special state for X11 authentication spoofing.  An opened X11
413 * connection (when authentication spoofing is being done) remains in this
414 * state until the first packet has been completely read.  The authentication
415 * data in that packet is then substituted by the real data if it matches the
416 * fake data, and the channel is put into normal mode.
417 * XXX All this happens at the client side.
418 */
419int
420x11_open_helper(Channel *c)
421{
422	unsigned char *ucp;
423	unsigned int proto_len, data_len;
424
425	/* Check if the fixed size part of the packet is in buffer. */
426	if (buffer_len(&c->output) < 12)
427		return 0;
428
429	/* Parse the lengths of variable-length fields. */
430	ucp = (unsigned char *) buffer_ptr(&c->output);
431	if (ucp[0] == 0x42) {	/* Byte order MSB first. */
432		proto_len = 256 * ucp[6] + ucp[7];
433		data_len = 256 * ucp[8] + ucp[9];
434	} else if (ucp[0] == 0x6c) {	/* Byte order LSB first. */
435		proto_len = ucp[6] + 256 * ucp[7];
436		data_len = ucp[8] + 256 * ucp[9];
437	} else {
438		debug("Initial X11 packet contains bad byte order byte: 0x%x",
439		      ucp[0]);
440		return -1;
441	}
442
443	/* Check if the whole packet is in buffer. */
444	if (buffer_len(&c->output) <
445	    12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
446		return 0;
447
448	/* Check if authentication protocol matches. */
449	if (proto_len != strlen(x11_saved_proto) ||
450	    memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
451		debug("X11 connection uses different authentication protocol.");
452		return -1;
453	}
454	/* Check if authentication data matches our fake data. */
455	if (data_len != x11_fake_data_len ||
456	    memcmp(ucp + 12 + ((proto_len + 3) & ~3),
457		x11_fake_data, x11_fake_data_len) != 0) {
458		debug("X11 auth data does not match fake data.");
459		return -1;
460	}
461	/* Check fake data length */
462	if (x11_fake_data_len != x11_saved_data_len) {
463		error("X11 fake_data_len %d != saved_data_len %d",
464		    x11_fake_data_len, x11_saved_data_len);
465		return -1;
466	}
467	/*
468	 * Received authentication protocol and data match
469	 * our fake data. Substitute the fake data with real
470	 * data.
471	 */
472	memcpy(ucp + 12 + ((proto_len + 3) & ~3),
473	    x11_saved_data, x11_saved_data_len);
474	return 1;
475}
476
477void
478channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
479{
480	int ret = x11_open_helper(c);
481	if (ret == 1) {
482		/* Start normal processing for the channel. */
483		c->type = SSH_CHANNEL_OPEN;
484		channel_pre_open_13(c, readset, writeset);
485	} else if (ret == -1) {
486		/*
487		 * We have received an X11 connection that has bad
488		 * authentication information.
489		 */
490		log("X11 connection rejected because of wrong authentication.\r\n");
491		buffer_clear(&c->input);
492		buffer_clear(&c->output);
493		close(c->sock);
494		c->sock = -1;
495		c->type = SSH_CHANNEL_CLOSED;
496		packet_start(SSH_MSG_CHANNEL_CLOSE);
497		packet_put_int(c->remote_id);
498		packet_send();
499	}
500}
501
502void
503channel_pre_x11_open(Channel *c, fd_set * readset, fd_set * writeset)
504{
505	int ret = x11_open_helper(c);
506	if (ret == 1) {
507		c->type = SSH_CHANNEL_OPEN;
508		if (compat20)
509			channel_pre_open_20(c, readset, writeset);
510		else
511			channel_pre_open_15(c, readset, writeset);
512	} else if (ret == -1) {
513		debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
514		chan_read_failed(c);	/** force close? */
515		chan_write_failed(c);
516		debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
517	}
518}
519
520/* This is our fake X11 server socket. */
521void
522channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
523{
524	struct sockaddr addr;
525	int newsock, newch;
526	socklen_t addrlen;
527	char buf[16384], *remote_hostname;
528	int remote_port;
529
530	if (FD_ISSET(c->sock, readset)) {
531		debug("X11 connection requested.");
532		addrlen = sizeof(addr);
533		newsock = accept(c->sock, &addr, &addrlen);
534		if (newsock < 0) {
535			error("accept: %.100s", strerror(errno));
536			return;
537		}
538		remote_hostname = get_remote_hostname(newsock);
539		remote_port = get_peer_port(newsock);
540		snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
541		    remote_hostname, remote_port);
542
543		newch = channel_new("x11",
544		    SSH_CHANNEL_OPENING, newsock, newsock, -1,
545		    c->local_window_max, c->local_maxpacket,
546		    0, xstrdup(buf));
547		if (compat20) {
548			packet_start(SSH2_MSG_CHANNEL_OPEN);
549			packet_put_cstring("x11");
550			packet_put_int(newch);
551			packet_put_int(c->local_window_max);
552			packet_put_int(c->local_maxpacket);
553			/* originator host and port */
554			packet_put_cstring(remote_hostname);
555			if (datafellows & SSH_BUG_X11FWD) {
556				debug("ssh2 x11 bug compat mode");
557			} else {
558				packet_put_int(remote_port);
559			}
560			packet_send();
561		} else {
562			packet_start(SSH_SMSG_X11_OPEN);
563			packet_put_int(newch);
564			if (have_hostname_in_open)
565				packet_put_string(buf, strlen(buf));
566			packet_send();
567		}
568		xfree(remote_hostname);
569	}
570}
571
572/*
573 * This socket is listening for connections to a forwarded TCP/IP port.
574 */
575void
576channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
577{
578	struct sockaddr addr;
579	int newsock, newch;
580	socklen_t addrlen;
581	char buf[1024], *remote_hostname;
582	int remote_port;
583
584	if (FD_ISSET(c->sock, readset)) {
585		debug("Connection to port %d forwarding "
586		    "to %.100s port %d requested.",
587		    c->listening_port, c->path, c->host_port);
588		addrlen = sizeof(addr);
589		newsock = accept(c->sock, &addr, &addrlen);
590		if (newsock < 0) {
591			error("accept: %.100s", strerror(errno));
592			return;
593		}
594		remote_hostname = get_remote_hostname(newsock);
595		remote_port = get_peer_port(newsock);
596		snprintf(buf, sizeof buf,
597		    "listen port %d for %.100s port %d, "
598		    "connect from %.200s port %d",
599		    c->listening_port, c->path, c->host_port,
600		    remote_hostname, remote_port);
601		newch = channel_new("direct-tcpip",
602		    SSH_CHANNEL_OPENING, newsock, newsock, -1,
603		    c->local_window_max, c->local_maxpacket,
604		    0, xstrdup(buf));
605		if (compat20) {
606			packet_start(SSH2_MSG_CHANNEL_OPEN);
607			packet_put_cstring("direct-tcpip");
608			packet_put_int(newch);
609			packet_put_int(c->local_window_max);
610			packet_put_int(c->local_maxpacket);
611			/* target host and port */
612			packet_put_string(c->path, strlen(c->path));
613			packet_put_int(c->host_port);
614			/* originator host and port */
615			packet_put_cstring(remote_hostname);
616			packet_put_int(remote_port);
617			packet_send();
618		} else {
619			packet_start(SSH_MSG_PORT_OPEN);
620			packet_put_int(newch);
621			packet_put_string(c->path, strlen(c->path));
622			packet_put_int(c->host_port);
623			if (have_hostname_in_open) {
624				packet_put_string(buf, strlen(buf));
625			}
626			packet_send();
627		}
628		xfree(remote_hostname);
629	}
630}
631
632/*
633 * This is the authentication agent socket listening for connections from
634 * clients.
635 */
636void
637channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
638{
639	struct sockaddr addr;
640	int newsock, newch;
641	socklen_t addrlen;
642
643	if (FD_ISSET(c->sock, readset)) {
644		addrlen = sizeof(addr);
645		newsock = accept(c->sock, &addr, &addrlen);
646		if (newsock < 0) {
647			error("accept from auth socket: %.100s", strerror(errno));
648			return;
649		}
650		newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
651		    xstrdup("accepted auth socket"));
652		packet_start(SSH_SMSG_AGENT_OPEN);
653		packet_put_int(newch);
654		packet_send();
655	}
656}
657
658int
659channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
660{
661	char buf[16*1024];
662	int len;
663
664	if (c->rfd != -1 &&
665	    FD_ISSET(c->rfd, readset)) {
666		len = read(c->rfd, buf, sizeof(buf));
667		if (len < 0 && (errno == EINTR || errno == EAGAIN))
668			return 1;
669		if (len <= 0) {
670			debug("channel %d: read<=0 rfd %d len %d",
671			    c->self, c->rfd, len);
672			if (compat13) {
673				buffer_consume(&c->output, buffer_len(&c->output));
674				c->type = SSH_CHANNEL_INPUT_DRAINING;
675				debug("Channel %d status set to input draining.", c->self);
676			} else {
677				chan_read_failed(c);
678			}
679			return -1;
680		}
681		buffer_append(&c->input, buf, len);
682	}
683	return 1;
684}
685int
686channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
687{
688	int len;
689
690	/* Send buffered output data to the socket. */
691	if (c->wfd != -1 &&
692	    FD_ISSET(c->wfd, writeset) &&
693	    buffer_len(&c->output) > 0) {
694		len = write(c->wfd, buffer_ptr(&c->output),
695		    buffer_len(&c->output));
696		if (len < 0 && (errno == EINTR || errno == EAGAIN))
697			return 1;
698		if (len <= 0) {
699			if (compat13) {
700				buffer_consume(&c->output, buffer_len(&c->output));
701				debug("Channel %d status set to input draining.", c->self);
702				c->type = SSH_CHANNEL_INPUT_DRAINING;
703			} else {
704				chan_write_failed(c);
705			}
706			return -1;
707		}
708		buffer_consume(&c->output, len);
709		if (compat20 && len > 0) {
710			c->local_consumed += len;
711		}
712	}
713	return 1;
714}
715int
716channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
717{
718	char buf[16*1024];
719	int len;
720
721/** XXX handle drain efd, too */
722	if (c->efd != -1) {
723		if (c->extended_usage == CHAN_EXTENDED_WRITE &&
724		    FD_ISSET(c->efd, writeset) &&
725		    buffer_len(&c->extended) > 0) {
726			len = write(c->efd, buffer_ptr(&c->extended),
727			    buffer_len(&c->extended));
728			debug("channel %d: written %d to efd %d",
729			    c->self, len, c->efd);
730			if (len > 0) {
731				buffer_consume(&c->extended, len);
732				c->local_consumed += len;
733			}
734		} else if (c->extended_usage == CHAN_EXTENDED_READ &&
735		    FD_ISSET(c->efd, readset)) {
736			len = read(c->efd, buf, sizeof(buf));
737			debug("channel %d: read %d from efd %d",
738			     c->self, len, c->efd);
739			if (len == 0) {
740				debug("channel %d: closing efd %d",
741				    c->self, c->efd);
742				close(c->efd);
743				c->efd = -1;
744			} else if (len > 0)
745				buffer_append(&c->extended, buf, len);
746		}
747	}
748	return 1;
749}
750int
751channel_check_window(Channel *c, fd_set * readset, fd_set * writeset)
752{
753	if (!(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
754	    c->local_window < c->local_window_max/2 &&
755	    c->local_consumed > 0) {
756		packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
757		packet_put_int(c->remote_id);
758		packet_put_int(c->local_consumed);
759		packet_send();
760		debug("channel %d: window %d sent adjust %d",
761		    c->self, c->local_window,
762		    c->local_consumed);
763		c->local_window += c->local_consumed;
764		c->local_consumed = 0;
765	}
766	return 1;
767}
768
769void
770channel_post_open_1(Channel *c, fd_set * readset, fd_set * writeset)
771{
772	channel_handle_rfd(c, readset, writeset);
773	channel_handle_wfd(c, readset, writeset);
774}
775
776void
777channel_post_open_2(Channel *c, fd_set * readset, fd_set * writeset)
778{
779	channel_handle_rfd(c, readset, writeset);
780	channel_handle_wfd(c, readset, writeset);
781	channel_handle_efd(c, readset, writeset);
782	channel_check_window(c, readset, writeset);
783}
784
785void
786channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
787{
788	int len;
789	/* Send buffered output data to the socket. */
790	if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
791		len = write(c->sock, buffer_ptr(&c->output),
792			    buffer_len(&c->output));
793		if (len <= 0)
794			buffer_consume(&c->output, buffer_len(&c->output));
795		else
796			buffer_consume(&c->output, len);
797	}
798}
799
800void
801channel_handler_init_20(void)
802{
803	channel_pre[SSH_CHANNEL_OPEN] =			&channel_pre_open_20;
804	channel_pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open;
805	channel_pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
806	channel_pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
807
808	channel_post[SSH_CHANNEL_OPEN] =		&channel_post_open_2;
809	channel_post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
810	channel_post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
811}
812
813void
814channel_handler_init_13(void)
815{
816	channel_pre[SSH_CHANNEL_OPEN] =			&channel_pre_open_13;
817	channel_pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open_13;
818	channel_pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
819	channel_pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
820	channel_pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
821	channel_pre[SSH_CHANNEL_INPUT_DRAINING] =	&channel_pre_input_draining;
822	channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] =	&channel_pre_output_draining;
823
824	channel_post[SSH_CHANNEL_OPEN] =		&channel_post_open_1;
825	channel_post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
826	channel_post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
827	channel_post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
828	channel_post[SSH_CHANNEL_OUTPUT_DRAINING] =	&channel_post_output_drain_13;
829}
830
831void
832channel_handler_init_15(void)
833{
834	channel_pre[SSH_CHANNEL_OPEN] =			&channel_pre_open_15;
835	channel_pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open;
836	channel_pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
837	channel_pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
838	channel_pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
839
840	channel_post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
841	channel_post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
842	channel_post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
843	channel_post[SSH_CHANNEL_OPEN] =		&channel_post_open_1;
844}
845
846void
847channel_handler_init(void)
848{
849	int i;
850	for(i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
851		channel_pre[i] = NULL;
852		channel_post[i] = NULL;
853	}
854	if (compat20)
855		channel_handler_init_20();
856	else if (compat13)
857		channel_handler_init_13();
858	else
859		channel_handler_init_15();
860}
861
862void
863channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
864{
865	static int did_init = 0;
866	int i;
867	Channel *c;
868
869	if (!did_init) {
870		channel_handler_init();
871		did_init = 1;
872	}
873	for (i = 0; i < channels_alloc; i++) {
874		c = &channels[i];
875		if (c->type == SSH_CHANNEL_FREE)
876			continue;
877		if (ftab[c->type] == NULL)
878			continue;
879		(*ftab[c->type])(c, readset, writeset);
880		chan_delete_if_full_closed(c);
881	}
882}
883
884void
885channel_prepare_select(fd_set * readset, fd_set * writeset)
886{
887	channel_handler(channel_pre, readset, writeset);
888}
889
890void
891channel_after_select(fd_set * readset, fd_set * writeset)
892{
893	channel_handler(channel_post, readset, writeset);
894}
895
896/* If there is data to send to the connection, send some of it now. */
897
898void
899channel_output_poll()
900{
901	int len, i;
902	Channel *c;
903
904	for (i = 0; i < channels_alloc; i++) {
905		c = &channels[i];
906
907		/* We are only interested in channels that can have buffered incoming data. */
908		if (compat13) {
909			if (c->type != SSH_CHANNEL_OPEN &&
910			    c->type != SSH_CHANNEL_INPUT_DRAINING)
911				continue;
912		} else {
913			if (c->type != SSH_CHANNEL_OPEN)
914				continue;
915			if (c->istate != CHAN_INPUT_OPEN &&
916			    c->istate != CHAN_INPUT_WAIT_DRAIN)
917				continue;
918		}
919		if (compat20 &&
920		    (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
921			debug("channel: %d: no data after CLOSE", c->self);
922			continue;
923		}
924
925		/* Get the amount of buffered data for this channel. */
926		len = buffer_len(&c->input);
927		if (len > 0) {
928			/* Send some data for the other side over the secure connection. */
929			if (compat20) {
930				if (len > c->remote_window)
931					len = c->remote_window;
932				if (len > c->remote_maxpacket)
933					len = c->remote_maxpacket;
934			} else {
935				if (packet_is_interactive()) {
936					if (len > 1024)
937						len = 512;
938				} else {
939					/* Keep the packets at reasonable size. */
940					if (len > packet_get_maxsize()/2)
941						len = packet_get_maxsize()/2;
942				}
943			}
944			if (len > 0) {
945				packet_start(compat20 ?
946				    SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
947				packet_put_int(c->remote_id);
948				packet_put_string(buffer_ptr(&c->input), len);
949				packet_send();
950				buffer_consume(&c->input, len);
951				c->remote_window -= len;
952				debug("channel %d: send data len %d", c->self, len);
953			}
954		} else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
955			if (compat13)
956				fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
957			/*
958			 * input-buffer is empty and read-socket shutdown:
959			 * tell peer, that we will not send more data: send IEOF
960			 */
961			chan_ibuf_empty(c);
962		}
963		/* Send extended data, i.e. stderr */
964		if (compat20 &&
965		    c->remote_window > 0 &&
966		    (len = buffer_len(&c->extended)) > 0 &&
967		    c->extended_usage == CHAN_EXTENDED_READ) {
968			if (len > c->remote_window)
969				len = c->remote_window;
970			if (len > c->remote_maxpacket)
971				len = c->remote_maxpacket;
972			packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
973			packet_put_int(c->remote_id);
974			packet_put_int(SSH2_EXTENDED_DATA_STDERR);
975			packet_put_string(buffer_ptr(&c->extended), len);
976			packet_send();
977			buffer_consume(&c->extended, len);
978			c->remote_window -= len;
979		}
980	}
981}
982
983/*
984 * This is called when a packet of type CHANNEL_DATA has just been received.
985 * The message type has already been consumed, but channel number and data is
986 * still there.
987 */
988
989void
990channel_input_data(int type, int plen)
991{
992	int id;
993	char *data;
994	unsigned int data_len;
995	Channel *c;
996
997	/* Get the channel number and verify it. */
998	id = packet_get_int();
999	c = channel_lookup(id);
1000	if (c == NULL)
1001		packet_disconnect("Received data for nonexistent channel %d.", id);
1002
1003	/* Ignore any data for non-open channels (might happen on close) */
1004	if (c->type != SSH_CHANNEL_OPEN &&
1005	    c->type != SSH_CHANNEL_X11_OPEN)
1006		return;
1007
1008	/* same for protocol 1.5 if output end is no longer open */
1009	if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
1010		return;
1011
1012	/* Get the data. */
1013	data = packet_get_string(&data_len);
1014	packet_done();
1015
1016	if (compat20){
1017		if (data_len > c->local_maxpacket) {
1018			log("channel %d: rcvd big packet %d, maxpack %d",
1019			    c->self, data_len, c->local_maxpacket);
1020		}
1021		if (data_len > c->local_window) {
1022			log("channel %d: rcvd too much data %d, win %d",
1023			    c->self, data_len, c->local_window);
1024			xfree(data);
1025			return;
1026		}
1027		c->local_window -= data_len;
1028	}else{
1029		packet_integrity_check(plen, 4 + 4 + data_len, type);
1030	}
1031	buffer_append(&c->output, data, data_len);
1032	xfree(data);
1033}
1034void
1035channel_input_extended_data(int type, int plen)
1036{
1037	int id;
1038	int tcode;
1039	char *data;
1040	unsigned int data_len;
1041	Channel *c;
1042
1043	/* Get the channel number and verify it. */
1044	id = packet_get_int();
1045	c = channel_lookup(id);
1046
1047	if (c == NULL)
1048		packet_disconnect("Received extended_data for bad channel %d.", id);
1049	if (c->type != SSH_CHANNEL_OPEN) {
1050		log("channel %d: ext data for non open", id);
1051		return;
1052	}
1053	tcode = packet_get_int();
1054	if (c->efd == -1 ||
1055	    c->extended_usage != CHAN_EXTENDED_WRITE ||
1056	    tcode != SSH2_EXTENDED_DATA_STDERR) {
1057		log("channel %d: bad ext data", c->self);
1058		return;
1059	}
1060	data = packet_get_string(&data_len);
1061	packet_done();
1062	if (data_len > c->local_window) {
1063		log("channel %d: rcvd too much extended_data %d, win %d",
1064		    c->self, data_len, c->local_window);
1065		xfree(data);
1066		return;
1067	}
1068	debug("channel %d: rcvd ext data %d", c->self, data_len);
1069	c->local_window -= data_len;
1070	buffer_append(&c->extended, data, data_len);
1071	xfree(data);
1072}
1073
1074
1075/*
1076 * Returns true if no channel has too much buffered data, and false if one or
1077 * more channel is overfull.
1078 */
1079
1080int
1081channel_not_very_much_buffered_data()
1082{
1083	unsigned int i;
1084	Channel *c;
1085
1086	for (i = 0; i < channels_alloc; i++) {
1087		c = &channels[i];
1088		if (c->type == SSH_CHANNEL_OPEN) {
1089			if (!compat20 && buffer_len(&c->input) > packet_get_maxsize()) {
1090				debug("channel %d: big input buffer %d",
1091				    c->self, buffer_len(&c->input));
1092				return 0;
1093			}
1094			if (buffer_len(&c->output) > packet_get_maxsize()) {
1095				debug("channel %d: big output buffer %d",
1096				    c->self, buffer_len(&c->output));
1097				return 0;
1098			}
1099		}
1100	}
1101	return 1;
1102}
1103
1104void
1105channel_input_ieof(int type, int plen)
1106{
1107	int id;
1108	Channel *c;
1109
1110	packet_integrity_check(plen, 4, type);
1111
1112	id = packet_get_int();
1113	c = channel_lookup(id);
1114	if (c == NULL)
1115		packet_disconnect("Received ieof for nonexistent channel %d.", id);
1116	chan_rcvd_ieof(c);
1117}
1118
1119void
1120channel_input_close(int type, int plen)
1121{
1122	int id;
1123	Channel *c;
1124
1125	packet_integrity_check(plen, 4, type);
1126
1127	id = packet_get_int();
1128	c = channel_lookup(id);
1129	if (c == NULL)
1130		packet_disconnect("Received close for nonexistent channel %d.", id);
1131
1132	/*
1133	 * Send a confirmation that we have closed the channel and no more
1134	 * data is coming for it.
1135	 */
1136	packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1137	packet_put_int(c->remote_id);
1138	packet_send();
1139
1140	/*
1141	 * If the channel is in closed state, we have sent a close request,
1142	 * and the other side will eventually respond with a confirmation.
1143	 * Thus, we cannot free the channel here, because then there would be
1144	 * no-one to receive the confirmation.  The channel gets freed when
1145	 * the confirmation arrives.
1146	 */
1147	if (c->type != SSH_CHANNEL_CLOSED) {
1148		/*
1149		 * Not a closed channel - mark it as draining, which will
1150		 * cause it to be freed later.
1151		 */
1152		buffer_consume(&c->input, buffer_len(&c->input));
1153		c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1154	}
1155}
1156
1157/* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1158void
1159channel_input_oclose(int type, int plen)
1160{
1161	int id = packet_get_int();
1162	Channel *c = channel_lookup(id);
1163	packet_integrity_check(plen, 4, type);
1164	if (c == NULL)
1165		packet_disconnect("Received oclose for nonexistent channel %d.", id);
1166	chan_rcvd_oclose(c);
1167}
1168
1169void
1170channel_input_close_confirmation(int type, int plen)
1171{
1172	int id = packet_get_int();
1173	Channel *c = channel_lookup(id);
1174
1175	packet_done();
1176	if (c == NULL)
1177		packet_disconnect("Received close confirmation for "
1178		    "out-of-range channel %d.", id);
1179	if (c->type != SSH_CHANNEL_CLOSED)
1180		packet_disconnect("Received close confirmation for "
1181		    "non-closed channel %d (type %d).", id, c->type);
1182	channel_free(c->self);
1183}
1184
1185void
1186channel_input_open_confirmation(int type, int plen)
1187{
1188	int id, remote_id;
1189	Channel *c;
1190
1191	if (!compat20)
1192		packet_integrity_check(plen, 4 + 4, type);
1193
1194	id = packet_get_int();
1195	c = channel_lookup(id);
1196
1197	if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1198		packet_disconnect("Received open confirmation for "
1199		    "non-opening channel %d.", id);
1200	remote_id = packet_get_int();
1201	/* Record the remote channel number and mark that the channel is now open. */
1202	c->remote_id = remote_id;
1203	c->type = SSH_CHANNEL_OPEN;
1204
1205	if (compat20) {
1206		c->remote_window = packet_get_int();
1207		c->remote_maxpacket = packet_get_int();
1208		packet_done();
1209		if (c->cb_fn != NULL && c->cb_event == type) {
1210			debug("callback start");
1211			c->cb_fn(c->self, c->cb_arg);
1212			debug("callback done");
1213		}
1214		debug("channel %d: open confirm rwindow %d rmax %d", c->self,
1215		    c->remote_window, c->remote_maxpacket);
1216	}
1217}
1218
1219void
1220channel_input_open_failure(int type, int plen)
1221{
1222	int id;
1223	Channel *c;
1224
1225	if (!compat20)
1226		packet_integrity_check(plen, 4, type);
1227
1228	id = packet_get_int();
1229	c = channel_lookup(id);
1230
1231	if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1232		packet_disconnect("Received open failure for "
1233		    "non-opening channel %d.", id);
1234	if (compat20) {
1235		int reason = packet_get_int();
1236		char *msg  = packet_get_string(NULL);
1237		char *lang  = packet_get_string(NULL);
1238		log("channel_open_failure: %d: reason %d: %s", id, reason, msg);
1239		packet_done();
1240		xfree(msg);
1241		xfree(lang);
1242	}
1243	/* Free the channel.  This will also close the socket. */
1244	channel_free(id);
1245}
1246
1247void
1248channel_input_channel_request(int type, int plen)
1249{
1250	int id;
1251	Channel *c;
1252
1253	id = packet_get_int();
1254	c = channel_lookup(id);
1255
1256	if (c == NULL ||
1257	    (c->type != SSH_CHANNEL_OPEN && c->type != SSH_CHANNEL_LARVAL))
1258		packet_disconnect("Received request for "
1259		    "non-open channel %d.", id);
1260	if (c->cb_fn != NULL && c->cb_event == type) {
1261		debug("callback start");
1262		c->cb_fn(c->self, c->cb_arg);
1263		debug("callback done");
1264	} else {
1265		char *service = packet_get_string(NULL);
1266		debug("channel: %d rcvd request for %s", c->self, service);
1267debug("cb_fn %p cb_event %d", c->cb_fn , c->cb_event);
1268		xfree(service);
1269	}
1270}
1271
1272void
1273channel_input_window_adjust(int type, int plen)
1274{
1275	Channel *c;
1276	int id, adjust;
1277
1278	if (!compat20)
1279		return;
1280
1281	/* Get the channel number and verify it. */
1282	id = packet_get_int();
1283	c = channel_lookup(id);
1284
1285	if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
1286		log("Received window adjust for "
1287		    "non-open channel %d.", id);
1288		return;
1289	}
1290	adjust = packet_get_int();
1291	packet_done();
1292	debug("channel %d: rcvd adjust %d", id, adjust);
1293	c->remote_window += adjust;
1294}
1295
1296/*
1297 * Stops listening for channels, and removes any unix domain sockets that we
1298 * might have.
1299 */
1300
1301void
1302channel_stop_listening()
1303{
1304	int i;
1305	for (i = 0; i < channels_alloc; i++) {
1306		switch (channels[i].type) {
1307		case SSH_CHANNEL_AUTH_SOCKET:
1308			close(channels[i].sock);
1309			remove(channels[i].path);
1310			channel_free(i);
1311			break;
1312		case SSH_CHANNEL_PORT_LISTENER:
1313		case SSH_CHANNEL_X11_LISTENER:
1314			close(channels[i].sock);
1315			channel_free(i);
1316			break;
1317		default:
1318			break;
1319		}
1320	}
1321}
1322
1323/*
1324 * Closes the sockets/fds of all channels.  This is used to close extra file
1325 * descriptors after a fork.
1326 */
1327
1328void
1329channel_close_all()
1330{
1331	int i;
1332	for (i = 0; i < channels_alloc; i++)
1333		if (channels[i].type != SSH_CHANNEL_FREE)
1334			channel_close_fds(&channels[i]);
1335}
1336
1337/* Returns the maximum file descriptor number used by the channels. */
1338
1339int
1340channel_max_fd()
1341{
1342	return channel_max_fd_value;
1343}
1344
1345/* Returns true if any channel is still open. */
1346
1347int
1348channel_still_open()
1349{
1350	unsigned int i;
1351	for (i = 0; i < channels_alloc; i++)
1352		switch (channels[i].type) {
1353		case SSH_CHANNEL_FREE:
1354		case SSH_CHANNEL_X11_LISTENER:
1355		case SSH_CHANNEL_PORT_LISTENER:
1356		case SSH_CHANNEL_CLOSED:
1357		case SSH_CHANNEL_AUTH_SOCKET:
1358			continue;
1359		case SSH_CHANNEL_LARVAL:
1360			if (!compat20)
1361				fatal("cannot happen: SSH_CHANNEL_LARVAL");
1362			continue;
1363		case SSH_CHANNEL_OPENING:
1364		case SSH_CHANNEL_OPEN:
1365		case SSH_CHANNEL_X11_OPEN:
1366			return 1;
1367		case SSH_CHANNEL_INPUT_DRAINING:
1368		case SSH_CHANNEL_OUTPUT_DRAINING:
1369			if (!compat13)
1370				fatal("cannot happen: OUT_DRAIN");
1371			return 1;
1372		default:
1373			fatal("channel_still_open: bad channel type %d", channels[i].type);
1374			/* NOTREACHED */
1375		}
1376	return 0;
1377}
1378
1379/*
1380 * Returns a message describing the currently open forwarded connections,
1381 * suitable for sending to the client.  The message contains crlf pairs for
1382 * newlines.
1383 */
1384
1385char *
1386channel_open_message()
1387{
1388	Buffer buffer;
1389	int i;
1390	char buf[512], *cp;
1391
1392	buffer_init(&buffer);
1393	snprintf(buf, sizeof buf, "The following connections are open:\r\n");
1394	buffer_append(&buffer, buf, strlen(buf));
1395	for (i = 0; i < channels_alloc; i++) {
1396		Channel *c = &channels[i];
1397		switch (c->type) {
1398		case SSH_CHANNEL_FREE:
1399		case SSH_CHANNEL_X11_LISTENER:
1400		case SSH_CHANNEL_PORT_LISTENER:
1401		case SSH_CHANNEL_CLOSED:
1402		case SSH_CHANNEL_AUTH_SOCKET:
1403			continue;
1404		case SSH_CHANNEL_LARVAL:
1405		case SSH_CHANNEL_OPENING:
1406		case SSH_CHANNEL_OPEN:
1407		case SSH_CHANNEL_X11_OPEN:
1408		case SSH_CHANNEL_INPUT_DRAINING:
1409		case SSH_CHANNEL_OUTPUT_DRAINING:
1410			snprintf(buf, sizeof buf, "  #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
1411			    c->self, c->remote_name,
1412			    c->type, c->remote_id,
1413			    c->istate, buffer_len(&c->input),
1414			    c->ostate, buffer_len(&c->output),
1415			    c->rfd, c->wfd);
1416			buffer_append(&buffer, buf, strlen(buf));
1417			continue;
1418		default:
1419			fatal("channel_open_message: bad channel type %d", c->type);
1420			/* NOTREACHED */
1421		}
1422	}
1423	buffer_append(&buffer, "\0", 1);
1424	cp = xstrdup(buffer_ptr(&buffer));
1425	buffer_free(&buffer);
1426	return cp;
1427}
1428
1429/*
1430 * Initiate forwarding of connections to local port "port" through the secure
1431 * channel to host:port from remote side.
1432 */
1433
1434void
1435channel_request_local_forwarding(u_short port, const char *host,
1436				 u_short host_port, int gateway_ports)
1437{
1438	int success, ch, sock, on = 1;
1439	struct addrinfo hints, *ai, *aitop;
1440	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1441	struct linger linger;
1442
1443	if (strlen(host) > sizeof(channels[0].path) - 1)
1444		packet_disconnect("Forward host name too long.");
1445
1446	/*
1447	 * getaddrinfo returns a loopback address if the hostname is
1448	 * set to NULL and hints.ai_flags is not AI_PASSIVE
1449	 */
1450	memset(&hints, 0, sizeof(hints));
1451	hints.ai_family = IPv4or6;
1452	hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
1453	hints.ai_socktype = SOCK_STREAM;
1454	snprintf(strport, sizeof strport, "%d", port);
1455	if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
1456		packet_disconnect("getaddrinfo: fatal error");
1457
1458	success = 0;
1459	for (ai = aitop; ai; ai = ai->ai_next) {
1460		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1461			continue;
1462		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1463		    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1464			error("channel_request_local_forwarding: getnameinfo failed");
1465			continue;
1466		}
1467		/* Create a port to listen for the host. */
1468		sock = socket(ai->ai_family, SOCK_STREAM, 0);
1469		if (sock < 0) {
1470			/* this is no error since kernel may not support ipv6 */
1471			verbose("socket: %.100s", strerror(errno));
1472			continue;
1473		}
1474		/*
1475		 * Set socket options.  We would like the socket to disappear
1476		 * as soon as it has been closed for whatever reason.
1477		 */
1478		setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
1479		linger.l_onoff = 1;
1480		linger.l_linger = 5;
1481		setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
1482		debug("Local forwarding listening on %s port %s.", ntop, strport);
1483
1484		/* Bind the socket to the address. */
1485		if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1486			/* address can be in use ipv6 address is already bound */
1487			verbose("bind: %.100s", strerror(errno));
1488			close(sock);
1489			continue;
1490		}
1491		/* Start listening for connections on the socket. */
1492		if (listen(sock, 5) < 0) {
1493			error("listen: %.100s", strerror(errno));
1494			close(sock);
1495			continue;
1496		}
1497		/* Allocate a channel number for the socket. */
1498		ch = channel_new(
1499		    "port listener", SSH_CHANNEL_PORT_LISTENER,
1500		    sock, sock, -1,
1501		    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1502		    0, xstrdup("port listener"));
1503		strlcpy(channels[ch].path, host, sizeof(channels[ch].path));
1504		channels[ch].host_port = host_port;
1505		channels[ch].listening_port = port;
1506		success = 1;
1507	}
1508	if (success == 0)
1509		packet_disconnect("cannot listen port: %d", port);
1510	freeaddrinfo(aitop);
1511}
1512
1513/*
1514 * Initiate forwarding of connections to port "port" on remote host through
1515 * the secure channel to host:port from local side.
1516 */
1517
1518void
1519channel_request_remote_forwarding(u_short listen_port, const char *host_to_connect,
1520				  u_short port_to_connect)
1521{
1522	int payload_len;
1523	/* Record locally that connection to this host/port is permitted. */
1524	if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
1525		fatal("channel_request_remote_forwarding: too many forwards");
1526
1527	permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
1528	permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
1529	permitted_opens[num_permitted_opens].listen_port = listen_port;
1530	num_permitted_opens++;
1531
1532	/* Send the forward request to the remote side. */
1533	if (compat20) {
1534		const char *address_to_bind = "0.0.0.0";
1535		packet_start(SSH2_MSG_GLOBAL_REQUEST);
1536		packet_put_cstring("tcpip-forward");
1537		packet_put_char(0);			/* boolean: want reply */
1538		packet_put_cstring(address_to_bind);
1539		packet_put_int(listen_port);
1540	} else {
1541		packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1542		packet_put_int(listen_port);
1543		packet_put_cstring(host_to_connect);
1544		packet_put_int(port_to_connect);
1545		packet_send();
1546		packet_write_wait();
1547		/*
1548		 * Wait for response from the remote side.  It will send a disconnect
1549		 * message on failure, and we will never see it here.
1550		 */
1551		packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1552	}
1553}
1554
1555/*
1556 * This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
1557 * listening for the port, and sends back a success reply (or disconnect
1558 * message if there was an error).  This never returns if there was an error.
1559 */
1560
1561void
1562channel_input_port_forward_request(int is_root, int gateway_ports)
1563{
1564	u_short port, host_port;
1565	char *hostname;
1566
1567	/* Get arguments from the packet. */
1568	port = packet_get_int();
1569	hostname = packet_get_string(NULL);
1570	host_port = packet_get_int();
1571
1572	/*
1573	 * Check that an unprivileged user is not trying to forward a
1574	 * privileged port.
1575	 */
1576	if (port < IPPORT_RESERVED && !is_root)
1577		packet_disconnect("Requested forwarding of port %d but user is not root.",
1578				  port);
1579	/*
1580	 * Initiate forwarding,
1581	 */
1582	channel_request_local_forwarding(port, hostname, host_port, gateway_ports);
1583
1584	/* Free the argument string. */
1585	xfree(hostname);
1586}
1587
1588/* XXX move to aux.c */
1589int
1590channel_connect_to(const char *host, u_short host_port)
1591{
1592	struct addrinfo hints, *ai, *aitop;
1593	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1594	int gaierr;
1595	int sock = -1;
1596
1597	memset(&hints, 0, sizeof(hints));
1598	hints.ai_family = IPv4or6;
1599	hints.ai_socktype = SOCK_STREAM;
1600	snprintf(strport, sizeof strport, "%d", host_port);
1601	if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
1602		error("%.100s: unknown host (%s)", host, gai_strerror(gaierr));
1603		return -1;
1604	}
1605	for (ai = aitop; ai; ai = ai->ai_next) {
1606		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1607			continue;
1608		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1609		    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1610			error("channel_connect_to: getnameinfo failed");
1611			continue;
1612		}
1613		/* Create the socket. */
1614		sock = socket(ai->ai_family, SOCK_STREAM, 0);
1615		if (sock < 0) {
1616			error("socket: %.100s", strerror(errno));
1617			continue;
1618		}
1619		/* Connect to the host/port. */
1620		if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1621			error("connect %.100s port %s: %.100s", ntop, strport,
1622			    strerror(errno));
1623			close(sock);
1624			continue;	/* fail -- try next */
1625		}
1626		break; /* success */
1627
1628	}
1629	freeaddrinfo(aitop);
1630	if (!ai) {
1631		error("connect %.100s port %d: failed.", host, host_port);
1632		return -1;
1633	}
1634	/* success */
1635	return sock;
1636}
1637/*
1638 * This is called after receiving PORT_OPEN message.  This attempts to
1639 * connect to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION
1640 * or CHANNEL_OPEN_FAILURE.
1641 */
1642
1643void
1644channel_input_port_open(int type, int plen)
1645{
1646	u_short host_port;
1647	char *host, *originator_string;
1648	int remote_channel, sock = -1, newch, i, denied;
1649	unsigned int host_len, originator_len;
1650
1651	/* Get remote channel number. */
1652	remote_channel = packet_get_int();
1653
1654	/* Get host name to connect to. */
1655	host = packet_get_string(&host_len);
1656
1657	/* Get port to connect to. */
1658	host_port = packet_get_int();
1659
1660	/* Get remote originator name. */
1661	if (have_hostname_in_open) {
1662		originator_string = packet_get_string(&originator_len);
1663		originator_len += 4;	/* size of packet_int */
1664	} else {
1665		originator_string = xstrdup("unknown (remote did not supply name)");
1666		originator_len = 0;	/* no originator supplied */
1667	}
1668
1669	packet_integrity_check(plen,
1670	    4 + 4 + host_len + 4 + originator_len, SSH_MSG_PORT_OPEN);
1671
1672	/* Check if opening that port is permitted. */
1673	denied = 0;
1674	if (!all_opens_permitted) {
1675		/* Go trough all permitted ports. */
1676		for (i = 0; i < num_permitted_opens; i++)
1677			if (permitted_opens[i].port_to_connect == host_port &&
1678			    strcmp(permitted_opens[i].host_to_connect, host) == 0)
1679				break;
1680
1681		/* Check if we found the requested port among those permitted. */
1682		if (i >= num_permitted_opens) {
1683			/* The port is not permitted. */
1684			log("Received request to connect to %.100s:%d, but the request was denied.",
1685			    host, host_port);
1686			denied = 1;
1687		}
1688	}
1689	sock = denied ? -1 : channel_connect_to(host, host_port);
1690	if (sock > 0) {
1691		/* Allocate a channel for this connection. */
1692		newch = channel_allocate(SSH_CHANNEL_OPEN, sock, originator_string);
1693		channels[newch].remote_id = remote_channel;
1694
1695		packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1696		packet_put_int(remote_channel);
1697		packet_put_int(newch);
1698		packet_send();
1699	} else {
1700		packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1701		packet_put_int(remote_channel);
1702		packet_send();
1703	}
1704	xfree(host);
1705}
1706
1707/*
1708 * Creates an internet domain socket for listening for X11 connections.
1709 * Returns a suitable value for the DISPLAY variable, or NULL if an error
1710 * occurs.
1711 */
1712
1713#define	NUM_SOCKS	10
1714
1715char *
1716x11_create_display_inet(int screen_number, int x11_display_offset)
1717{
1718	int display_number, sock;
1719	u_short port;
1720	struct addrinfo hints, *ai, *aitop;
1721	char strport[NI_MAXSERV];
1722	int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
1723	char display[512];
1724	char hostname[MAXHOSTNAMELEN];
1725
1726	for (display_number = x11_display_offset;
1727	     display_number < MAX_DISPLAYS;
1728	     display_number++) {
1729		port = 6000 + display_number;
1730		memset(&hints, 0, sizeof(hints));
1731		hints.ai_family = IPv4or6;
1732		hints.ai_flags = AI_PASSIVE;		/* XXX loopback only ? */
1733		hints.ai_socktype = SOCK_STREAM;
1734		snprintf(strport, sizeof strport, "%d", port);
1735		if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
1736			error("getaddrinfo: %.100s", gai_strerror(gaierr));
1737			return NULL;
1738		}
1739		for (ai = aitop; ai; ai = ai->ai_next) {
1740			if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1741				continue;
1742			sock = socket(ai->ai_family, SOCK_STREAM, 0);
1743			if (sock < 0) {
1744				error("socket: %.100s", strerror(errno));
1745				return NULL;
1746			}
1747			if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1748				debug("bind port %d: %.100s", port, strerror(errno));
1749				shutdown(sock, SHUT_RDWR);
1750				close(sock);
1751				for (n = 0; n < num_socks; n++) {
1752					shutdown(socks[n], SHUT_RDWR);
1753					close(socks[n]);
1754				}
1755				num_socks = 0;
1756				break;
1757			}
1758			socks[num_socks++] = sock;
1759			if (num_socks == NUM_SOCKS)
1760				break;
1761		}
1762		if (num_socks > 0)
1763			break;
1764	}
1765	if (display_number >= MAX_DISPLAYS) {
1766		error("Failed to allocate internet-domain X11 display socket.");
1767		return NULL;
1768	}
1769	/* Start listening for connections on the socket. */
1770	for (n = 0; n < num_socks; n++) {
1771		sock = socks[n];
1772		if (listen(sock, 5) < 0) {
1773			error("listen: %.100s", strerror(errno));
1774			shutdown(sock, SHUT_RDWR);
1775			close(sock);
1776			return NULL;
1777		}
1778	}
1779
1780	/* Set up a suitable value for the DISPLAY variable. */
1781	if (gethostname(hostname, sizeof(hostname)) < 0)
1782		fatal("gethostname: %.100s", strerror(errno));
1783	snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
1784		 display_number, screen_number);
1785
1786	/* Allocate a channel for each socket. */
1787	for (n = 0; n < num_socks; n++) {
1788		sock = socks[n];
1789		(void) channel_new("x11 listener",
1790		    SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
1791		    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
1792		    0, xstrdup("X11 inet listener"));
1793	}
1794
1795	/* Return a suitable value for the DISPLAY environment variable. */
1796	return xstrdup(display);
1797}
1798
1799#ifndef X_UNIX_PATH
1800#define X_UNIX_PATH "/tmp/.X11-unix/X"
1801#endif
1802
1803static
1804int
1805connect_local_xsocket(unsigned int dnr)
1806{
1807	static const char *const x_sockets[] = {
1808		X_UNIX_PATH "%u",
1809		"/var/X/.X11-unix/X" "%u",
1810		"/usr/spool/sockets/X11/" "%u",
1811		NULL
1812	};
1813	int sock;
1814	struct sockaddr_un addr;
1815	const char *const * path;
1816
1817	for (path = x_sockets; *path; ++path) {
1818		sock = socket(AF_UNIX, SOCK_STREAM, 0);
1819		if (sock < 0)
1820			error("socket: %.100s", strerror(errno));
1821		memset(&addr, 0, sizeof(addr));
1822		addr.sun_family = AF_UNIX;
1823		snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
1824		if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
1825			return sock;
1826		close(sock);
1827	}
1828	error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
1829	return -1;
1830}
1831
1832int
1833x11_connect_display(void)
1834{
1835	int display_number, sock = 0;
1836	const char *display;
1837	char buf[1024], *cp;
1838	struct addrinfo hints, *ai, *aitop;
1839	char strport[NI_MAXSERV];
1840	int gaierr;
1841
1842	/* Try to open a socket for the local X server. */
1843	display = getenv("DISPLAY");
1844	if (!display) {
1845		error("DISPLAY not set.");
1846		return -1;
1847	}
1848	/*
1849	 * Now we decode the value of the DISPLAY variable and make a
1850	 * connection to the real X server.
1851	 */
1852
1853	/*
1854	 * Check if it is a unix domain socket.  Unix domain displays are in
1855	 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
1856	 */
1857	if (strncmp(display, "unix:", 5) == 0 ||
1858	    display[0] == ':') {
1859		/* Connect to the unix domain socket. */
1860		if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
1861			error("Could not parse display number from DISPLAY: %.100s",
1862			      display);
1863			return -1;
1864		}
1865		/* Create a socket. */
1866		sock = connect_local_xsocket(display_number);
1867		if (sock < 0)
1868			return -1;
1869
1870		/* OK, we now have a connection to the display. */
1871		return sock;
1872	}
1873	/*
1874	 * Connect to an inet socket.  The DISPLAY value is supposedly
1875	 * hostname:d[.s], where hostname may also be numeric IP address.
1876	 */
1877	strncpy(buf, display, sizeof(buf));
1878	buf[sizeof(buf) - 1] = 0;
1879	cp = strchr(buf, ':');
1880	if (!cp) {
1881		error("Could not find ':' in DISPLAY: %.100s", display);
1882		return -1;
1883	}
1884	*cp = 0;
1885	/* buf now contains the host name.  But first we parse the display number. */
1886	if (sscanf(cp + 1, "%d", &display_number) != 1) {
1887		error("Could not parse display number from DISPLAY: %.100s",
1888		      display);
1889		return -1;
1890	}
1891
1892	/* Look up the host address */
1893	memset(&hints, 0, sizeof(hints));
1894	hints.ai_family = IPv4or6;
1895	hints.ai_socktype = SOCK_STREAM;
1896	snprintf(strport, sizeof strport, "%d", 6000 + display_number);
1897	if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
1898		error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
1899		return -1;
1900	}
1901	for (ai = aitop; ai; ai = ai->ai_next) {
1902		/* Create a socket. */
1903		sock = socket(ai->ai_family, SOCK_STREAM, 0);
1904		if (sock < 0) {
1905			debug("socket: %.100s", strerror(errno));
1906			continue;
1907		}
1908		/* Connect it to the display. */
1909		if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1910			debug("connect %.100s port %d: %.100s", buf,
1911			    6000 + display_number, strerror(errno));
1912			close(sock);
1913			continue;
1914		}
1915		/* Success */
1916		break;
1917	}
1918	freeaddrinfo(aitop);
1919	if (!ai) {
1920		error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
1921		    strerror(errno));
1922		return -1;
1923	}
1924	return sock;
1925}
1926
1927/*
1928 * This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
1929 * the remote channel number.  We should do whatever we want, and respond
1930 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
1931 */
1932
1933void
1934x11_input_open(int type, int plen)
1935{
1936	int remote_channel, sock = 0, newch;
1937	char *remote_host;
1938	unsigned int remote_len;
1939
1940	/* Get remote channel number. */
1941	remote_channel = packet_get_int();
1942
1943	/* Get remote originator name. */
1944	if (have_hostname_in_open) {
1945		remote_host = packet_get_string(&remote_len);
1946		remote_len += 4;
1947	} else {
1948		remote_host = xstrdup("unknown (remote did not supply name)");
1949		remote_len = 0;
1950	}
1951
1952	debug("Received X11 open request.");
1953	packet_integrity_check(plen, 4 + remote_len, SSH_SMSG_X11_OPEN);
1954
1955	/* Obtain a connection to the real X display. */
1956	sock = x11_connect_display();
1957	if (sock == -1) {
1958		/* Send refusal to the remote host. */
1959		packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1960		packet_put_int(remote_channel);
1961		packet_send();
1962	} else {
1963		/* Allocate a channel for this connection. */
1964		newch = channel_allocate(
1965		     (x11_saved_proto == NULL) ?
1966		     SSH_CHANNEL_OPEN : SSH_CHANNEL_X11_OPEN,
1967		     sock, remote_host);
1968		channels[newch].remote_id = remote_channel;
1969
1970		/* Send a confirmation to the remote host. */
1971		packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1972		packet_put_int(remote_channel);
1973		packet_put_int(newch);
1974		packet_send();
1975	}
1976}
1977
1978/*
1979 * Requests forwarding of X11 connections, generates fake authentication
1980 * data, and enables authentication spoofing.
1981 */
1982
1983void
1984x11_request_forwarding_with_spoofing(int client_session_id,
1985    const char *proto, const char *data)
1986{
1987	unsigned int data_len = (unsigned int) strlen(data) / 2;
1988	unsigned int i, value;
1989	char *new_data;
1990	int screen_number;
1991	const char *cp;
1992	u_int32_t rand = 0;
1993
1994	cp = getenv("DISPLAY");
1995	if (cp)
1996		cp = strchr(cp, ':');
1997	if (cp)
1998		cp = strchr(cp, '.');
1999	if (cp)
2000		screen_number = atoi(cp + 1);
2001	else
2002		screen_number = 0;
2003
2004	/* Save protocol name. */
2005	x11_saved_proto = xstrdup(proto);
2006
2007	/*
2008	 * Extract real authentication data and generate fake data of the
2009	 * same length.
2010	 */
2011	x11_saved_data = xmalloc(data_len);
2012	x11_fake_data = xmalloc(data_len);
2013	for (i = 0; i < data_len; i++) {
2014		if (sscanf(data + 2 * i, "%2x", &value) != 1)
2015			fatal("x11_request_forwarding: bad authentication data: %.100s", data);
2016		if (i % 4 == 0)
2017			rand = arc4random();
2018		x11_saved_data[i] = value;
2019		x11_fake_data[i] = rand & 0xff;
2020		rand >>= 8;
2021	}
2022	x11_saved_data_len = data_len;
2023	x11_fake_data_len = data_len;
2024
2025	/* Convert the fake data into hex. */
2026	new_data = xmalloc(2 * data_len + 1);
2027	for (i = 0; i < data_len; i++)
2028		sprintf(new_data + 2 * i, "%02x", (unsigned char) x11_fake_data[i]);
2029
2030	/* Send the request packet. */
2031	if (compat20) {
2032		channel_request_start(client_session_id, "x11-req", 0);
2033		packet_put_char(0);	/* XXX bool single connection */
2034	} else {
2035		packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
2036	}
2037	packet_put_cstring(proto);
2038	packet_put_cstring(new_data);
2039	packet_put_int(screen_number);
2040	packet_send();
2041	packet_write_wait();
2042	xfree(new_data);
2043}
2044
2045/* Sends a message to the server to request authentication fd forwarding. */
2046
2047void
2048auth_request_forwarding()
2049{
2050	packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
2051	packet_send();
2052	packet_write_wait();
2053}
2054
2055/*
2056 * Returns the name of the forwarded authentication socket.  Returns NULL if
2057 * there is no forwarded authentication socket.  The returned value points to
2058 * a static buffer.
2059 */
2060
2061char *
2062auth_get_socket_name()
2063{
2064	return channel_forwarded_auth_socket_name;
2065}
2066
2067/* removes the agent forwarding socket */
2068
2069void
2070cleanup_socket(void)
2071{
2072	remove(channel_forwarded_auth_socket_name);
2073	rmdir(channel_forwarded_auth_socket_dir);
2074}
2075
2076/*
2077 * This if called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
2078 * This starts forwarding authentication requests.
2079 */
2080
2081void
2082auth_input_request_forwarding(struct passwd * pw)
2083{
2084	int sock, newch;
2085	struct sockaddr_un sunaddr;
2086
2087	if (auth_get_socket_name() != NULL)
2088		fatal("Protocol error: authentication forwarding requested twice.");
2089
2090	/* Temporarily drop privileged uid for mkdir/bind. */
2091	temporarily_use_uid(pw->pw_uid);
2092
2093	/* Allocate a buffer for the socket name, and format the name. */
2094	channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
2095	channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
2096	strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
2097
2098	/* Create private directory for socket */
2099	if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL)
2100		packet_disconnect("mkdtemp: %.100s", strerror(errno));
2101	snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME, "%s/agent.%d",
2102		 channel_forwarded_auth_socket_dir, (int) getpid());
2103
2104	if (atexit(cleanup_socket) < 0) {
2105		int saved = errno;
2106		cleanup_socket();
2107		packet_disconnect("socket: %.100s", strerror(saved));
2108	}
2109	/* Create the socket. */
2110	sock = socket(AF_UNIX, SOCK_STREAM, 0);
2111	if (sock < 0)
2112		packet_disconnect("socket: %.100s", strerror(errno));
2113
2114	/* Bind it to the name. */
2115	memset(&sunaddr, 0, sizeof(sunaddr));
2116	sunaddr.sun_family = AF_UNIX;
2117	strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
2118		sizeof(sunaddr.sun_path));
2119
2120	if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
2121		packet_disconnect("bind: %.100s", strerror(errno));
2122
2123	/* Restore the privileged uid. */
2124	restore_uid();
2125
2126	/* Start listening on the socket. */
2127	if (listen(sock, 5) < 0)
2128		packet_disconnect("listen: %.100s", strerror(errno));
2129
2130	/* Allocate a channel for the authentication agent socket. */
2131	newch = channel_allocate(SSH_CHANNEL_AUTH_SOCKET, sock,
2132				 xstrdup("auth socket"));
2133	strlcpy(channels[newch].path, channel_forwarded_auth_socket_name,
2134	    sizeof(channels[newch].path));
2135}
2136
2137/* This is called to process an SSH_SMSG_AGENT_OPEN message. */
2138
2139void
2140auth_input_open_request(int type, int plen)
2141{
2142	int remch, sock, newch;
2143	char *dummyname;
2144
2145	packet_integrity_check(plen, 4, type);
2146
2147	/* Read the remote channel number from the message. */
2148	remch = packet_get_int();
2149
2150	/*
2151	 * Get a connection to the local authentication agent (this may again
2152	 * get forwarded).
2153	 */
2154	sock = ssh_get_authentication_socket();
2155
2156	/*
2157	 * If we could not connect the agent, send an error message back to
2158	 * the server. This should never happen unless the agent dies,
2159	 * because authentication forwarding is only enabled if we have an
2160	 * agent.
2161	 */
2162	if (sock < 0) {
2163		packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2164		packet_put_int(remch);
2165		packet_send();
2166		return;
2167	}
2168	debug("Forwarding authentication connection.");
2169
2170	/*
2171	 * Dummy host name.  This will be freed when the channel is freed; it
2172	 * will still be valid in the packet_put_string below since the
2173	 * channel cannot yet be freed at that point.
2174	 */
2175	dummyname = xstrdup("authentication agent connection");
2176
2177	newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
2178	channels[newch].remote_id = remch;
2179
2180	/* Send a confirmation to the remote host. */
2181	packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2182	packet_put_int(remch);
2183	packet_put_int(newch);
2184	packet_send();
2185}
2186
2187void
2188channel_start_open(int id)
2189{
2190	Channel *c = channel_lookup(id);
2191	if (c == NULL) {
2192		log("channel_open: %d: bad id", id);
2193		return;
2194	}
2195	debug("send channel open %d", id);
2196	packet_start(SSH2_MSG_CHANNEL_OPEN);
2197	packet_put_cstring(c->ctype);
2198	packet_put_int(c->self);
2199	packet_put_int(c->local_window);
2200	packet_put_int(c->local_maxpacket);
2201}
2202void
2203channel_open(int id)
2204{
2205	/* XXX REMOVE ME */
2206	channel_start_open(id);
2207	packet_send();
2208}
2209void
2210channel_request(int id, char *service, int wantconfirm)
2211{
2212	channel_request_start(id, service, wantconfirm);
2213	packet_send();
2214	debug("channel request %d: %s", id, service) ;
2215}
2216void
2217channel_request_start(int id, char *service, int wantconfirm)
2218{
2219	Channel *c = channel_lookup(id);
2220	if (c == NULL) {
2221		log("channel_request: %d: bad id", id);
2222		return;
2223	}
2224	packet_start(SSH2_MSG_CHANNEL_REQUEST);
2225	packet_put_int(c->remote_id);
2226	packet_put_cstring(service);
2227	packet_put_char(wantconfirm);
2228}
2229void
2230channel_register_callback(int id, int mtype, channel_callback_fn *fn, void *arg)
2231{
2232	Channel *c = channel_lookup(id);
2233	if (c == NULL) {
2234		log("channel_register_callback: %d: bad id", id);
2235		return;
2236	}
2237	c->cb_event = mtype;
2238	c->cb_fn = fn;
2239	c->cb_arg = arg;
2240}
2241void
2242channel_register_cleanup(int id, channel_callback_fn *fn)
2243{
2244	Channel *c = channel_lookup(id);
2245	if (c == NULL) {
2246		log("channel_register_cleanup: %d: bad id", id);
2247		return;
2248	}
2249	c->dettach_user = fn;
2250}
2251void
2252channel_cancel_cleanup(int id)
2253{
2254	Channel *c = channel_lookup(id);
2255	if (c == NULL) {
2256		log("channel_cancel_cleanup: %d: bad id", id);
2257		return;
2258	}
2259	c->dettach_user = NULL;
2260}
2261
2262void
2263channel_set_fds(int id, int rfd, int wfd, int efd, int extusage)
2264{
2265	Channel *c = channel_lookup(id);
2266	if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
2267		fatal("channel_activate for non-larval channel %d.", id);
2268
2269	channel_register_fds(c, rfd, wfd, efd, extusage);
2270	c->type = SSH_CHANNEL_OPEN;
2271	/* XXX window size? */
2272	c->local_window = c->local_window_max = c->local_maxpacket/2;
2273	packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2274	packet_put_int(c->remote_id);
2275	packet_put_int(c->local_window);
2276	packet_send();
2277}
2278