mux.c revision 204917
1/* $OpenBSD: mux.c,v 1.14 2010/01/30 02:54:53 djm Exp $ */
2/*
3 * Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17
18/* ssh session multiplexing support */
19
20/*
21 * TODO:
22 *   - Better signalling from master to slave, especially passing of
23 *      error messages
24 *   - Better fall-back from mux slave error to new connection.
25 *   - ExitOnForwardingFailure
26 *   - Maybe extension mechanisms for multi-X11/multi-agent forwarding
27 *   - Support ~^Z in mux slaves.
28 *   - Inspect or control sessions in master.
29 *   - If we ever support the "signal" channel request, send signals on
30 *     sessions in master.
31 */
32
33#include "includes.h"
34
35#include <sys/types.h>
36#include <sys/param.h>
37#include <sys/stat.h>
38#include <sys/socket.h>
39#include <sys/un.h>
40
41#include <errno.h>
42#include <fcntl.h>
43#include <signal.h>
44#include <stdarg.h>
45#include <stddef.h>
46#include <stdlib.h>
47#include <stdio.h>
48#include <string.h>
49#include <unistd.h>
50#ifdef HAVE_PATHS_H
51#include <paths.h>
52#endif
53
54#ifdef HAVE_POLL_H
55#include <poll.h>
56#else
57# ifdef HAVE_SYS_POLL_H
58#  include <sys/poll.h>
59# endif
60#endif
61
62#ifdef HAVE_UTIL_H
63# include <util.h>
64#endif
65
66#ifdef HAVE_LIBUTIL_H
67# include <libutil.h>
68#endif
69
70#include "openbsd-compat/sys-queue.h"
71#include "xmalloc.h"
72#include "log.h"
73#include "ssh.h"
74#include "pathnames.h"
75#include "misc.h"
76#include "match.h"
77#include "buffer.h"
78#include "channels.h"
79#include "msg.h"
80#include "packet.h"
81#include "monitor_fdpass.h"
82#include "sshpty.h"
83#include "key.h"
84#include "readconf.h"
85#include "clientloop.h"
86
87/* from ssh.c */
88extern int tty_flag;
89extern int force_tty_flag;
90extern Options options;
91extern int stdin_null_flag;
92extern char *host;
93extern int subsystem_flag;
94extern Buffer command;
95extern volatile sig_atomic_t quit_pending;
96extern char *stdio_forward_host;
97extern int stdio_forward_port;
98
99/* Context for session open confirmation callback */
100struct mux_session_confirm_ctx {
101	u_int want_tty;
102	u_int want_subsys;
103	u_int want_x_fwd;
104	u_int want_agent_fwd;
105	Buffer cmd;
106	char *term;
107	struct termios tio;
108	char **env;
109};
110
111/* fd to control socket */
112int muxserver_sock = -1;
113
114/* client request id */
115u_int muxclient_request_id = 0;
116
117/* Multiplexing control command */
118u_int muxclient_command = 0;
119
120/* Set when signalled. */
121static volatile sig_atomic_t muxclient_terminate = 0;
122
123/* PID of multiplex server */
124static u_int muxserver_pid = 0;
125
126static Channel *mux_listener_channel = NULL;
127
128struct mux_master_state {
129	int hello_rcvd;
130};
131
132/* mux protocol messages */
133#define MUX_MSG_HELLO		0x00000001
134#define MUX_C_NEW_SESSION	0x10000002
135#define MUX_C_ALIVE_CHECK	0x10000004
136#define MUX_C_TERMINATE		0x10000005
137#define MUX_C_OPEN_FWD		0x10000006
138#define MUX_C_CLOSE_FWD		0x10000007
139#define MUX_C_NEW_STDIO_FWD	0x10000008
140#define MUX_S_OK		0x80000001
141#define MUX_S_PERMISSION_DENIED	0x80000002
142#define MUX_S_FAILURE		0x80000003
143#define MUX_S_EXIT_MESSAGE	0x80000004
144#define MUX_S_ALIVE		0x80000005
145#define MUX_S_SESSION_OPENED	0x80000006
146
147/* type codes for MUX_C_OPEN_FWD and MUX_C_CLOSE_FWD */
148#define MUX_FWD_LOCAL   1
149#define MUX_FWD_REMOTE  2
150#define MUX_FWD_DYNAMIC 3
151
152static void mux_session_confirm(int, void *);
153
154static int process_mux_master_hello(u_int, Channel *, Buffer *, Buffer *);
155static int process_mux_new_session(u_int, Channel *, Buffer *, Buffer *);
156static int process_mux_alive_check(u_int, Channel *, Buffer *, Buffer *);
157static int process_mux_terminate(u_int, Channel *, Buffer *, Buffer *);
158static int process_mux_open_fwd(u_int, Channel *, Buffer *, Buffer *);
159static int process_mux_close_fwd(u_int, Channel *, Buffer *, Buffer *);
160static int process_mux_stdio_fwd(u_int, Channel *, Buffer *, Buffer *);
161
162static const struct {
163	u_int type;
164	int (*handler)(u_int, Channel *, Buffer *, Buffer *);
165} mux_master_handlers[] = {
166	{ MUX_MSG_HELLO, process_mux_master_hello },
167	{ MUX_C_NEW_SESSION, process_mux_new_session },
168	{ MUX_C_ALIVE_CHECK, process_mux_alive_check },
169	{ MUX_C_TERMINATE, process_mux_terminate },
170	{ MUX_C_OPEN_FWD, process_mux_open_fwd },
171	{ MUX_C_CLOSE_FWD, process_mux_close_fwd },
172	{ MUX_C_NEW_STDIO_FWD, process_mux_stdio_fwd },
173	{ 0, NULL }
174};
175
176/* Cleanup callback fired on closure of mux slave _session_ channel */
177/* ARGSUSED */
178static void
179mux_master_session_cleanup_cb(int cid, void *unused)
180{
181	Channel *cc, *c = channel_by_id(cid);
182
183	debug3("%s: entering for channel %d", __func__, cid);
184	if (c == NULL)
185		fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
186	if (c->ctl_chan != -1) {
187		if ((cc = channel_by_id(c->ctl_chan)) == NULL)
188			fatal("%s: channel %d missing control channel %d",
189			    __func__, c->self, c->ctl_chan);
190		c->ctl_chan = -1;
191		cc->remote_id = -1;
192		chan_rcvd_oclose(cc);
193	}
194	channel_cancel_cleanup(c->self);
195}
196
197/* Cleanup callback fired on closure of mux slave _control_ channel */
198/* ARGSUSED */
199static void
200mux_master_control_cleanup_cb(int cid, void *unused)
201{
202	Channel *sc, *c = channel_by_id(cid);
203
204	debug3("%s: entering for channel %d", __func__, cid);
205	if (c == NULL)
206		fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
207	if (c->remote_id != -1) {
208		if ((sc = channel_by_id(c->remote_id)) == NULL)
209			debug2("%s: channel %d n session channel %d",
210			    __func__, c->self, c->remote_id);
211		c->remote_id = -1;
212		sc->ctl_chan = -1;
213		if (sc->type != SSH_CHANNEL_OPEN) {
214			debug2("%s: channel %d: not open", __func__, sc->self);
215			chan_mark_dead(sc);
216		} else {
217			if (sc->istate == CHAN_INPUT_OPEN)
218				chan_read_failed(sc);
219			if (sc->ostate == CHAN_OUTPUT_OPEN)
220				chan_write_failed(sc);
221		}
222	}
223	channel_cancel_cleanup(c->self);
224}
225
226/* Check mux client environment variables before passing them to mux master. */
227static int
228env_permitted(char *env)
229{
230	int i, ret;
231	char name[1024], *cp;
232
233	if ((cp = strchr(env, '=')) == NULL || cp == env)
234		return 0;
235	ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
236	if (ret <= 0 || (size_t)ret >= sizeof(name)) {
237		error("env_permitted: name '%.100s...' too long", env);
238		return 0;
239	}
240
241	for (i = 0; i < options.num_send_env; i++)
242		if (match_pattern(name, options.send_env[i]))
243			return 1;
244
245	return 0;
246}
247
248/* Mux master protocol message handlers */
249
250static int
251process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
252{
253	u_int ver;
254	struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
255
256	if (state == NULL)
257		fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
258	if (state->hello_rcvd) {
259		error("%s: HELLO received twice", __func__);
260		return -1;
261	}
262	if (buffer_get_int_ret(&ver, m) != 0) {
263 malf:
264		error("%s: malformed message", __func__);
265		return -1;
266	}
267	if (ver != SSHMUX_VER) {
268		error("Unsupported multiplexing protocol version %d "
269		    "(expected %d)", ver, SSHMUX_VER);
270		return -1;
271	}
272	debug2("%s: channel %d slave version %u", __func__, c->self, ver);
273
274	/* No extensions are presently defined */
275	while (buffer_len(m) > 0) {
276		char *name = buffer_get_string_ret(m, NULL);
277		char *value = buffer_get_string_ret(m, NULL);
278
279		if (name == NULL || value == NULL) {
280			if (name != NULL)
281				xfree(name);
282			goto malf;
283		}
284		debug2("Unrecognised slave extension \"%s\"", name);
285		xfree(name);
286		xfree(value);
287	}
288	state->hello_rcvd = 1;
289	return 0;
290}
291
292static int
293process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
294{
295	Channel *nc;
296	struct mux_session_confirm_ctx *cctx;
297	char *reserved, *cmd, *cp;
298	u_int i, j, len, env_len, escape_char, window, packetmax;
299	int new_fd[3];
300
301	/* Reply for SSHMUX_COMMAND_OPEN */
302	cctx = xcalloc(1, sizeof(*cctx));
303	cctx->term = NULL;
304	cmd = reserved = NULL;
305	if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
306	    buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
307	    buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
308	    buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
309	    buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
310	    buffer_get_int_ret(&escape_char, m) != 0 ||
311	    (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
312	    (cmd = buffer_get_string_ret(m, &len)) == NULL) {
313 malf:
314		if (cmd != NULL)
315			xfree(cmd);
316		if (reserved != NULL)
317			xfree(reserved);
318		if (cctx->term != NULL)
319			xfree(cctx->term);
320		error("%s: malformed message", __func__);
321		return -1;
322	}
323	xfree(reserved);
324	reserved = NULL;
325
326	cctx->env = NULL;
327	env_len = 0;
328	while (buffer_len(m) > 0) {
329#define MUX_MAX_ENV_VARS	4096
330		if ((cp = buffer_get_string_ret(m, &len)) == NULL) {
331			xfree(cmd);
332			goto malf;
333		}
334		if (!env_permitted(cp)) {
335			xfree(cp);
336			continue;
337		}
338		cctx->env = xrealloc(cctx->env, env_len + 2,
339		    sizeof(*cctx->env));
340		cctx->env[env_len++] = cp;
341		cctx->env[env_len] = NULL;
342		if (env_len > MUX_MAX_ENV_VARS) {
343			error(">%d environment variables received, ignoring "
344			    "additional", MUX_MAX_ENV_VARS);
345			break;
346		}
347	}
348
349	debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
350	    "term \"%s\", cmd \"%s\", env %u", __func__, c->self,
351	    cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
352	    cctx->want_subsys, cctx->term, cmd, env_len);
353
354	buffer_init(&cctx->cmd);
355	buffer_append(&cctx->cmd, cmd, strlen(cmd));
356	xfree(cmd);
357	cmd = NULL;
358
359	/* Gather fds from client */
360	for(i = 0; i < 3; i++) {
361		if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
362			error("%s: failed to receive fd %d from slave",
363			    __func__, i);
364			for (j = 0; j < i; j++)
365				close(new_fd[j]);
366			for (j = 0; j < env_len; j++)
367				xfree(cctx->env[j]);
368			if (env_len > 0)
369				xfree(cctx->env);
370			xfree(cctx->term);
371			buffer_free(&cctx->cmd);
372			xfree(cctx);
373
374			/* prepare reply */
375			buffer_put_int(r, MUX_S_FAILURE);
376			buffer_put_int(r, rid);
377			buffer_put_cstring(r,
378			    "did not receive file descriptors");
379			return -1;
380		}
381	}
382
383	debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
384	    new_fd[0], new_fd[1], new_fd[2]);
385
386	/* XXX support multiple child sessions in future */
387	if (c->remote_id != -1) {
388		debug2("%s: session already open", __func__);
389		/* prepare reply */
390		buffer_put_int(r, MUX_S_FAILURE);
391		buffer_put_int(r, rid);
392		buffer_put_cstring(r, "Multiple sessions not supported");
393 cleanup:
394		close(new_fd[0]);
395		close(new_fd[1]);
396		close(new_fd[2]);
397		xfree(cctx->term);
398		if (env_len != 0) {
399			for (i = 0; i < env_len; i++)
400				xfree(cctx->env[i]);
401			xfree(cctx->env);
402		}
403		buffer_free(&cctx->cmd);
404		return 0;
405	}
406
407	if (options.control_master == SSHCTL_MASTER_ASK ||
408	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
409		if (!ask_permission("Allow shared connection to %s? ", host)) {
410			debug2("%s: session refused by user", __func__);
411			/* prepare reply */
412			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
413			buffer_put_int(r, rid);
414			buffer_put_cstring(r, "Permission denied");
415			goto cleanup;
416		}
417	}
418
419	/* Try to pick up ttymodes from client before it goes raw */
420	if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
421		error("%s: tcgetattr: %s", __func__, strerror(errno));
422
423	/* enable nonblocking unless tty */
424	if (!isatty(new_fd[0]))
425		set_nonblock(new_fd[0]);
426	if (!isatty(new_fd[1]))
427		set_nonblock(new_fd[1]);
428	if (!isatty(new_fd[2]))
429		set_nonblock(new_fd[2]);
430
431	window = CHAN_SES_WINDOW_DEFAULT;
432	packetmax = CHAN_SES_PACKET_DEFAULT;
433	if (cctx->want_tty) {
434		window >>= 1;
435		packetmax >>= 1;
436	}
437
438	nc = channel_new("session", SSH_CHANNEL_OPENING,
439	    new_fd[0], new_fd[1], new_fd[2], window, packetmax,
440	    CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
441
442	nc->ctl_chan = c->self;		/* link session -> control channel */
443	c->remote_id = nc->self; 	/* link control -> session channel */
444
445	if (cctx->want_tty && escape_char != 0xffffffff) {
446		channel_register_filter(nc->self,
447		    client_simple_escape_filter, NULL,
448		    client_filter_cleanup,
449		    client_new_escape_filter_ctx((int)escape_char));
450	}
451
452	debug2("%s: channel_new: %d linked to control channel %d",
453	    __func__, nc->self, nc->ctl_chan);
454
455	channel_send_open(nc->self);
456	channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
457	channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 0);
458
459	/* prepare reply */
460	/* XXX defer until mux_session_confirm() fires */
461	buffer_put_int(r, MUX_S_SESSION_OPENED);
462	buffer_put_int(r, rid);
463	buffer_put_int(r, nc->self);
464
465	return 0;
466}
467
468static int
469process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
470{
471	debug2("%s: channel %d: alive check", __func__, c->self);
472
473	/* prepare reply */
474	buffer_put_int(r, MUX_S_ALIVE);
475	buffer_put_int(r, rid);
476	buffer_put_int(r, (u_int)getpid());
477
478	return 0;
479}
480
481static int
482process_mux_terminate(u_int rid, Channel *c, Buffer *m, Buffer *r)
483{
484	debug2("%s: channel %d: terminate request", __func__, c->self);
485
486	if (options.control_master == SSHCTL_MASTER_ASK ||
487	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
488		if (!ask_permission("Terminate shared connection to %s? ",
489		    host)) {
490			debug2("%s: termination refused by user", __func__);
491			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
492			buffer_put_int(r, rid);
493			buffer_put_cstring(r, "Permission denied");
494			return 0;
495		}
496	}
497
498	quit_pending = 1;
499	buffer_put_int(r, MUX_S_OK);
500	buffer_put_int(r, rid);
501	/* XXX exit happens too soon - message never makes it to client */
502	return 0;
503}
504
505static char *
506format_forward(u_int ftype, Forward *fwd)
507{
508	char *ret;
509
510	switch (ftype) {
511	case MUX_FWD_LOCAL:
512		xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
513		    (fwd->listen_host == NULL) ?
514		    (options.gateway_ports ? "*" : "LOCALHOST") :
515		    fwd->listen_host, fwd->listen_port,
516		    fwd->connect_host, fwd->connect_port);
517		break;
518	case MUX_FWD_DYNAMIC:
519		xasprintf(&ret, "dynamic forward %.200s:%d -> *",
520		    (fwd->listen_host == NULL) ?
521		    (options.gateway_ports ? "*" : "LOCALHOST") :
522		     fwd->listen_host, fwd->listen_port);
523		break;
524	case MUX_FWD_REMOTE:
525		xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
526		    (fwd->listen_host == NULL) ?
527		    "LOCALHOST" : fwd->listen_host,
528		    fwd->listen_port,
529		    fwd->connect_host, fwd->connect_port);
530		break;
531	default:
532		fatal("%s: unknown forward type %u", __func__, ftype);
533	}
534	return ret;
535}
536
537static int
538compare_host(const char *a, const char *b)
539{
540	if (a == NULL && b == NULL)
541		return 1;
542	if (a == NULL || b == NULL)
543		return 0;
544	return strcmp(a, b) == 0;
545}
546
547static int
548compare_forward(Forward *a, Forward *b)
549{
550	if (!compare_host(a->listen_host, b->listen_host))
551		return 0;
552	if (a->listen_port != b->listen_port)
553		return 0;
554	if (!compare_host(a->connect_host, b->connect_host))
555		return 0;
556	if (a->connect_port != b->connect_port)
557		return 0;
558
559	return 1;
560}
561
562static int
563process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
564{
565	Forward fwd;
566	char *fwd_desc = NULL;
567	u_int ftype;
568	int i, ret = 0, freefwd = 1;
569
570	fwd.listen_host = fwd.connect_host = NULL;
571	if (buffer_get_int_ret(&ftype, m) != 0 ||
572	    (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
573	    buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
574	    (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
575	    buffer_get_int_ret(&fwd.connect_port, m) != 0) {
576		error("%s: malformed message", __func__);
577		ret = -1;
578		goto out;
579	}
580
581	if (*fwd.listen_host == '\0') {
582		xfree(fwd.listen_host);
583		fwd.listen_host = NULL;
584	}
585	if (*fwd.connect_host == '\0') {
586		xfree(fwd.connect_host);
587		fwd.connect_host = NULL;
588	}
589
590	debug2("%s: channel %d: request %s", __func__, c->self,
591	    (fwd_desc = format_forward(ftype, &fwd)));
592
593	if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
594	    ftype != MUX_FWD_DYNAMIC) {
595		logit("%s: invalid forwarding type %u", __func__, ftype);
596 invalid:
597		xfree(fwd.listen_host);
598		xfree(fwd.connect_host);
599		buffer_put_int(r, MUX_S_FAILURE);
600		buffer_put_int(r, rid);
601		buffer_put_cstring(r, "Invalid forwarding request");
602		return 0;
603	}
604	/* XXX support rport0 forwarding with reply of port assigned */
605	if (fwd.listen_port == 0 || fwd.listen_port >= 65536) {
606		logit("%s: invalid listen port %u", __func__,
607		    fwd.listen_port);
608		goto invalid;
609	}
610	if (fwd.connect_port >= 65536 || (ftype != MUX_FWD_DYNAMIC &&
611	    ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
612		logit("%s: invalid connect port %u", __func__,
613		    fwd.connect_port);
614		goto invalid;
615	}
616	if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL) {
617		logit("%s: missing connect host", __func__);
618		goto invalid;
619	}
620
621	/* Skip forwards that have already been requested */
622	switch (ftype) {
623	case MUX_FWD_LOCAL:
624	case MUX_FWD_DYNAMIC:
625		for (i = 0; i < options.num_local_forwards; i++) {
626			if (compare_forward(&fwd,
627			    options.local_forwards + i)) {
628 exists:
629				debug2("%s: found existing forwarding",
630				    __func__);
631				buffer_put_int(r, MUX_S_OK);
632				buffer_put_int(r, rid);
633				goto out;
634			}
635		}
636		break;
637	case MUX_FWD_REMOTE:
638		for (i = 0; i < options.num_remote_forwards; i++) {
639			if (compare_forward(&fwd,
640			    options.remote_forwards + i))
641				goto exists;
642		}
643		break;
644	}
645
646	if (options.control_master == SSHCTL_MASTER_ASK ||
647	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
648		if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
649			debug2("%s: forwarding refused by user", __func__);
650			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
651			buffer_put_int(r, rid);
652			buffer_put_cstring(r, "Permission denied");
653			goto out;
654		}
655	}
656
657	if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
658		if (options.num_local_forwards + 1 >=
659		    SSH_MAX_FORWARDS_PER_DIRECTION ||
660		    channel_setup_local_fwd_listener(fwd.listen_host,
661		    fwd.listen_port, fwd.connect_host, fwd.connect_port,
662		    options.gateway_ports) < 0) {
663 fail:
664			logit("slave-requested %s failed", fwd_desc);
665			buffer_put_int(r, MUX_S_FAILURE);
666			buffer_put_int(r, rid);
667			buffer_put_cstring(r, "Port forwarding failed");
668			goto out;
669		}
670		add_local_forward(&options, &fwd);
671		freefwd = 0;
672	} else {
673		/* XXX wait for remote to confirm */
674		if (options.num_remote_forwards + 1 >=
675		    SSH_MAX_FORWARDS_PER_DIRECTION ||
676		    channel_request_remote_forwarding(fwd.listen_host,
677		    fwd.listen_port, fwd.connect_host, fwd.connect_port) < 0)
678			goto fail;
679		add_remote_forward(&options, &fwd);
680		freefwd = 0;
681	}
682	buffer_put_int(r, MUX_S_OK);
683	buffer_put_int(r, rid);
684 out:
685	if (fwd_desc != NULL)
686		xfree(fwd_desc);
687	if (freefwd) {
688		if (fwd.listen_host != NULL)
689			xfree(fwd.listen_host);
690		if (fwd.connect_host != NULL)
691			xfree(fwd.connect_host);
692	}
693	return ret;
694}
695
696static int
697process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
698{
699	Forward fwd;
700	char *fwd_desc = NULL;
701	u_int ftype;
702	int ret = 0;
703
704	fwd.listen_host = fwd.connect_host = NULL;
705	if (buffer_get_int_ret(&ftype, m) != 0 ||
706	    (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
707	    buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
708	    (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
709	    buffer_get_int_ret(&fwd.connect_port, m) != 0) {
710		error("%s: malformed message", __func__);
711		ret = -1;
712		goto out;
713	}
714
715	if (*fwd.listen_host == '\0') {
716		xfree(fwd.listen_host);
717		fwd.listen_host = NULL;
718	}
719	if (*fwd.connect_host == '\0') {
720		xfree(fwd.connect_host);
721		fwd.connect_host = NULL;
722	}
723
724	debug2("%s: channel %d: request %s", __func__, c->self,
725	    (fwd_desc = format_forward(ftype, &fwd)));
726
727	/* XXX implement this */
728	buffer_put_int(r, MUX_S_FAILURE);
729	buffer_put_int(r, rid);
730	buffer_put_cstring(r, "unimplemented");
731
732 out:
733	if (fwd_desc != NULL)
734		xfree(fwd_desc);
735	if (fwd.listen_host != NULL)
736		xfree(fwd.listen_host);
737	if (fwd.connect_host != NULL)
738		xfree(fwd.connect_host);
739
740	return ret;
741}
742
743static int
744process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
745{
746	Channel *nc;
747	char *reserved, *chost;
748	u_int cport, i, j;
749	int new_fd[2];
750
751	chost = reserved = NULL;
752	if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
753	   (chost = buffer_get_string_ret(m, NULL)) == NULL ||
754	    buffer_get_int_ret(&cport, m) != 0) {
755		if (reserved != NULL)
756			xfree(reserved);
757		if (chost != NULL)
758			xfree(chost);
759		error("%s: malformed message", __func__);
760		return -1;
761	}
762	xfree(reserved);
763
764	debug2("%s: channel %d: request stdio fwd to %s:%u",
765	    __func__, c->self, chost, cport);
766
767	/* Gather fds from client */
768	for(i = 0; i < 2; i++) {
769		if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
770			error("%s: failed to receive fd %d from slave",
771			    __func__, i);
772			for (j = 0; j < i; j++)
773				close(new_fd[j]);
774			xfree(chost);
775
776			/* prepare reply */
777			buffer_put_int(r, MUX_S_FAILURE);
778			buffer_put_int(r, rid);
779			buffer_put_cstring(r,
780			    "did not receive file descriptors");
781			return -1;
782		}
783	}
784
785	debug3("%s: got fds stdin %d, stdout %d", __func__,
786	    new_fd[0], new_fd[1]);
787
788	/* XXX support multiple child sessions in future */
789	if (c->remote_id != -1) {
790		debug2("%s: session already open", __func__);
791		/* prepare reply */
792		buffer_put_int(r, MUX_S_FAILURE);
793		buffer_put_int(r, rid);
794		buffer_put_cstring(r, "Multiple sessions not supported");
795 cleanup:
796		close(new_fd[0]);
797		close(new_fd[1]);
798		xfree(chost);
799		return 0;
800	}
801
802	if (options.control_master == SSHCTL_MASTER_ASK ||
803	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
804		if (!ask_permission("Allow forward to to %s:%u? ",
805		    chost, cport)) {
806			debug2("%s: stdio fwd refused by user", __func__);
807			/* prepare reply */
808			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
809			buffer_put_int(r, rid);
810			buffer_put_cstring(r, "Permission denied");
811			goto cleanup;
812		}
813	}
814
815	/* enable nonblocking unless tty */
816	if (!isatty(new_fd[0]))
817		set_nonblock(new_fd[0]);
818	if (!isatty(new_fd[1]))
819		set_nonblock(new_fd[1]);
820
821	nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
822
823	nc->ctl_chan = c->self;		/* link session -> control channel */
824	c->remote_id = nc->self; 	/* link control -> session channel */
825
826	debug2("%s: channel_new: %d linked to control channel %d",
827	    __func__, nc->self, nc->ctl_chan);
828
829	channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 0);
830
831	/* prepare reply */
832	/* XXX defer until channel confirmed */
833	buffer_put_int(r, MUX_S_SESSION_OPENED);
834	buffer_put_int(r, rid);
835	buffer_put_int(r, nc->self);
836
837	return 0;
838}
839
840/* Channel callbacks fired on read/write from mux slave fd */
841static int
842mux_master_read_cb(Channel *c)
843{
844	struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
845	Buffer in, out;
846	void *ptr;
847	u_int type, rid, have, i;
848	int ret = -1;
849
850	/* Setup ctx and  */
851	if (c->mux_ctx == NULL) {
852		state = xcalloc(1, sizeof(state));
853		c->mux_ctx = state;
854		channel_register_cleanup(c->self,
855		    mux_master_control_cleanup_cb, 0);
856
857		/* Send hello */
858		buffer_init(&out);
859		buffer_put_int(&out, MUX_MSG_HELLO);
860		buffer_put_int(&out, SSHMUX_VER);
861		/* no extensions */
862		buffer_put_string(&c->output, buffer_ptr(&out),
863		    buffer_len(&out));
864		buffer_free(&out);
865		debug3("%s: channel %d: hello sent", __func__, c->self);
866		return 0;
867	}
868
869	buffer_init(&in);
870	buffer_init(&out);
871
872	/* Channel code ensures that we receive whole packets */
873	if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
874 malf:
875		error("%s: malformed message", __func__);
876		goto out;
877	}
878	buffer_append(&in, ptr, have);
879
880	if (buffer_get_int_ret(&type, &in) != 0)
881		goto malf;
882	debug3("%s: channel %d packet type 0x%08x len %u",
883	    __func__, c->self, type, buffer_len(&in));
884
885	if (type == MUX_MSG_HELLO)
886		rid = 0;
887	else {
888		if (!state->hello_rcvd) {
889			error("%s: expected MUX_MSG_HELLO(0x%08x), "
890			    "received 0x%08x", __func__, MUX_MSG_HELLO, type);
891			goto out;
892		}
893		if (buffer_get_int_ret(&rid, &in) != 0)
894			goto malf;
895	}
896
897	for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
898		if (type == mux_master_handlers[i].type) {
899			ret = mux_master_handlers[i].handler(rid, c, &in, &out);
900			break;
901		}
902	}
903	if (mux_master_handlers[i].handler == NULL) {
904		error("%s: unsupported mux message 0x%08x", __func__, type);
905		buffer_put_int(&out, MUX_S_FAILURE);
906		buffer_put_int(&out, rid);
907		buffer_put_cstring(&out, "unsupported request");
908		ret = 0;
909	}
910	/* Enqueue reply packet */
911	if (buffer_len(&out) != 0) {
912		buffer_put_string(&c->output, buffer_ptr(&out),
913		    buffer_len(&out));
914	}
915 out:
916	buffer_free(&in);
917	buffer_free(&out);
918	return ret;
919}
920
921void
922mux_exit_message(Channel *c, int exitval)
923{
924	Buffer m;
925	Channel *mux_chan;
926
927	debug3("%s: channel %d: exit message, evitval %d", __func__, c->self,
928	    exitval);
929
930	if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
931		fatal("%s: channel %d missing mux channel %d",
932		    __func__, c->self, c->ctl_chan);
933
934	/* Append exit message packet to control socket output queue */
935	buffer_init(&m);
936	buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
937	buffer_put_int(&m, c->self);
938	buffer_put_int(&m, exitval);
939
940	buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
941	buffer_free(&m);
942}
943
944/* Prepare a mux master to listen on a Unix domain socket. */
945void
946muxserver_listen(void)
947{
948	struct sockaddr_un addr;
949	socklen_t sun_len;
950	mode_t old_umask;
951
952	if (options.control_path == NULL ||
953	    options.control_master == SSHCTL_MASTER_NO)
954		return;
955
956	debug("setting up multiplex master socket");
957
958	memset(&addr, '\0', sizeof(addr));
959	addr.sun_family = AF_UNIX;
960	sun_len = offsetof(struct sockaddr_un, sun_path) +
961	    strlen(options.control_path) + 1;
962
963	if (strlcpy(addr.sun_path, options.control_path,
964	    sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
965		fatal("ControlPath too long");
966
967	if ((muxserver_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
968		fatal("%s socket(): %s", __func__, strerror(errno));
969
970	old_umask = umask(0177);
971	if (bind(muxserver_sock, (struct sockaddr *)&addr, sun_len) == -1) {
972		muxserver_sock = -1;
973		if (errno == EINVAL || errno == EADDRINUSE) {
974			error("ControlSocket %s already exists, "
975			    "disabling multiplexing", options.control_path);
976			close(muxserver_sock);
977			muxserver_sock = -1;
978			xfree(options.control_path);
979			options.control_path = NULL;
980			options.control_master = SSHCTL_MASTER_NO;
981			return;
982		} else
983			fatal("%s bind(): %s", __func__, strerror(errno));
984	}
985	umask(old_umask);
986
987	if (listen(muxserver_sock, 64) == -1)
988		fatal("%s listen(): %s", __func__, strerror(errno));
989
990	set_nonblock(muxserver_sock);
991
992	mux_listener_channel = channel_new("mux listener",
993	    SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
994	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
995	    0, addr.sun_path, 1);
996	mux_listener_channel->mux_rcb = mux_master_read_cb;
997	debug3("%s: mux listener channel %d fd %d", __func__,
998	    mux_listener_channel->self, mux_listener_channel->sock);
999}
1000
1001/* Callback on open confirmation in mux master for a mux client session. */
1002static void
1003mux_session_confirm(int id, void *arg)
1004{
1005	struct mux_session_confirm_ctx *cctx = arg;
1006	const char *display;
1007	Channel *c;
1008	int i;
1009
1010	if (cctx == NULL)
1011		fatal("%s: cctx == NULL", __func__);
1012	if ((c = channel_by_id(id)) == NULL)
1013		fatal("%s: no channel for id %d", __func__, id);
1014
1015	display = getenv("DISPLAY");
1016	if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1017		char *proto, *data;
1018		/* Get reasonable local authentication information. */
1019		client_x11_get_proto(display, options.xauth_location,
1020		    options.forward_x11_trusted, &proto, &data);
1021		/* Request forwarding with authentication spoofing. */
1022		debug("Requesting X11 forwarding with authentication spoofing.");
1023		x11_request_forwarding_with_spoofing(id, display, proto, data);
1024		/* XXX wait for reply */
1025	}
1026
1027	if (cctx->want_agent_fwd && options.forward_agent) {
1028		debug("Requesting authentication agent forwarding.");
1029		channel_request_start(id, "auth-agent-req@openssh.com", 0);
1030		packet_send();
1031	}
1032
1033	client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1034	    cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1035
1036	c->open_confirm_ctx = NULL;
1037	buffer_free(&cctx->cmd);
1038	xfree(cctx->term);
1039	if (cctx->env != NULL) {
1040		for (i = 0; cctx->env[i] != NULL; i++)
1041			xfree(cctx->env[i]);
1042		xfree(cctx->env);
1043	}
1044	xfree(cctx);
1045}
1046
1047/* ** Multiplexing client support */
1048
1049/* Exit signal handler */
1050static void
1051control_client_sighandler(int signo)
1052{
1053	muxclient_terminate = signo;
1054}
1055
1056/*
1057 * Relay signal handler - used to pass some signals from mux client to
1058 * mux master.
1059 */
1060static void
1061control_client_sigrelay(int signo)
1062{
1063	int save_errno = errno;
1064
1065	if (muxserver_pid > 1)
1066		kill(muxserver_pid, signo);
1067
1068	errno = save_errno;
1069}
1070
1071static int
1072mux_client_read(int fd, Buffer *b, u_int need)
1073{
1074	u_int have;
1075	ssize_t len;
1076	u_char *p;
1077	struct pollfd pfd;
1078
1079	pfd.fd = fd;
1080	pfd.events = POLLIN;
1081	p = buffer_append_space(b, need);
1082	for (have = 0; have < need; ) {
1083		if (muxclient_terminate) {
1084			errno = EINTR;
1085			return -1;
1086		}
1087		len = read(fd, p + have, need - have);
1088		if (len < 0) {
1089			switch (errno) {
1090#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1091			case EWOULDBLOCK:
1092#endif
1093			case EAGAIN:
1094				(void)poll(&pfd, 1, -1);
1095				/* FALLTHROUGH */
1096			case EINTR:
1097				continue;
1098			default:
1099				return -1;
1100			}
1101		}
1102		if (len == 0) {
1103			errno = EPIPE;
1104			return -1;
1105		}
1106		have += (u_int)len;
1107	}
1108	return 0;
1109}
1110
1111static int
1112mux_client_write_packet(int fd, Buffer *m)
1113{
1114	Buffer queue;
1115	u_int have, need;
1116	int oerrno, len;
1117	u_char *ptr;
1118	struct pollfd pfd;
1119
1120	pfd.fd = fd;
1121	pfd.events = POLLOUT;
1122	buffer_init(&queue);
1123	buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1124
1125	need = buffer_len(&queue);
1126	ptr = buffer_ptr(&queue);
1127
1128	for (have = 0; have < need; ) {
1129		if (muxclient_terminate) {
1130			buffer_free(&queue);
1131			errno = EINTR;
1132			return -1;
1133		}
1134		len = write(fd, ptr + have, need - have);
1135		if (len < 0) {
1136			switch (errno) {
1137#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1138			case EWOULDBLOCK:
1139#endif
1140			case EAGAIN:
1141				(void)poll(&pfd, 1, -1);
1142				/* FALLTHROUGH */
1143			case EINTR:
1144				continue;
1145			default:
1146				oerrno = errno;
1147				buffer_free(&queue);
1148				errno = oerrno;
1149				return -1;
1150			}
1151		}
1152		if (len == 0) {
1153			buffer_free(&queue);
1154			errno = EPIPE;
1155			return -1;
1156		}
1157		have += (u_int)len;
1158	}
1159	buffer_free(&queue);
1160	return 0;
1161}
1162
1163static int
1164mux_client_read_packet(int fd, Buffer *m)
1165{
1166	Buffer queue;
1167	u_int need, have;
1168	void *ptr;
1169	int oerrno;
1170
1171	buffer_init(&queue);
1172	if (mux_client_read(fd, &queue, 4) != 0) {
1173		if ((oerrno = errno) == EPIPE)
1174		debug3("%s: read header failed: %s", __func__, strerror(errno));
1175		errno = oerrno;
1176		return -1;
1177	}
1178	need = get_u32(buffer_ptr(&queue));
1179	if (mux_client_read(fd, &queue, need) != 0) {
1180		oerrno = errno;
1181		debug3("%s: read body failed: %s", __func__, strerror(errno));
1182		errno = oerrno;
1183		return -1;
1184	}
1185	ptr = buffer_get_string_ptr(&queue, &have);
1186	buffer_append(m, ptr, have);
1187	buffer_free(&queue);
1188	return 0;
1189}
1190
1191static int
1192mux_client_hello_exchange(int fd)
1193{
1194	Buffer m;
1195	u_int type, ver;
1196
1197	buffer_init(&m);
1198	buffer_put_int(&m, MUX_MSG_HELLO);
1199	buffer_put_int(&m, SSHMUX_VER);
1200	/* no extensions */
1201
1202	if (mux_client_write_packet(fd, &m) != 0)
1203		fatal("%s: write packet: %s", __func__, strerror(errno));
1204
1205	buffer_clear(&m);
1206
1207	/* Read their HELLO */
1208	if (mux_client_read_packet(fd, &m) != 0) {
1209		buffer_free(&m);
1210		return -1;
1211	}
1212
1213	type = buffer_get_int(&m);
1214	if (type != MUX_MSG_HELLO)
1215		fatal("%s: expected HELLO (%u) received %u",
1216		    __func__, MUX_MSG_HELLO, type);
1217	ver = buffer_get_int(&m);
1218	if (ver != SSHMUX_VER)
1219		fatal("Unsupported multiplexing protocol version %d "
1220		    "(expected %d)", ver, SSHMUX_VER);
1221	debug2("%s: master version %u", __func__, ver);
1222	/* No extensions are presently defined */
1223	while (buffer_len(&m) > 0) {
1224		char *name = buffer_get_string(&m, NULL);
1225		char *value = buffer_get_string(&m, NULL);
1226
1227		debug2("Unrecognised master extension \"%s\"", name);
1228		xfree(name);
1229		xfree(value);
1230	}
1231	buffer_free(&m);
1232	return 0;
1233}
1234
1235static u_int
1236mux_client_request_alive(int fd)
1237{
1238	Buffer m;
1239	char *e;
1240	u_int pid, type, rid;
1241
1242	debug3("%s: entering", __func__);
1243
1244	buffer_init(&m);
1245	buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1246	buffer_put_int(&m, muxclient_request_id);
1247
1248	if (mux_client_write_packet(fd, &m) != 0)
1249		fatal("%s: write packet: %s", __func__, strerror(errno));
1250
1251	buffer_clear(&m);
1252
1253	/* Read their reply */
1254	if (mux_client_read_packet(fd, &m) != 0) {
1255		buffer_free(&m);
1256		return 0;
1257	}
1258
1259	type = buffer_get_int(&m);
1260	if (type != MUX_S_ALIVE) {
1261		e = buffer_get_string(&m, NULL);
1262		fatal("%s: master returned error: %s", __func__, e);
1263	}
1264
1265	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1266		fatal("%s: out of sequence reply: my id %u theirs %u",
1267		    __func__, muxclient_request_id, rid);
1268	pid = buffer_get_int(&m);
1269	buffer_free(&m);
1270
1271	debug3("%s: done pid = %u", __func__, pid);
1272
1273	muxclient_request_id++;
1274
1275	return pid;
1276}
1277
1278static void
1279mux_client_request_terminate(int fd)
1280{
1281	Buffer m;
1282	char *e;
1283	u_int type, rid;
1284
1285	debug3("%s: entering", __func__);
1286
1287	buffer_init(&m);
1288	buffer_put_int(&m, MUX_C_TERMINATE);
1289	buffer_put_int(&m, muxclient_request_id);
1290
1291	if (mux_client_write_packet(fd, &m) != 0)
1292		fatal("%s: write packet: %s", __func__, strerror(errno));
1293
1294	buffer_clear(&m);
1295
1296	/* Read their reply */
1297	if (mux_client_read_packet(fd, &m) != 0) {
1298		/* Remote end exited already */
1299		if (errno == EPIPE) {
1300			buffer_free(&m);
1301			return;
1302		}
1303		fatal("%s: read from master failed: %s",
1304		    __func__, strerror(errno));
1305	}
1306
1307	type = buffer_get_int(&m);
1308	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1309		fatal("%s: out of sequence reply: my id %u theirs %u",
1310		    __func__, muxclient_request_id, rid);
1311	switch (type) {
1312	case MUX_S_OK:
1313		break;
1314	case MUX_S_PERMISSION_DENIED:
1315		e = buffer_get_string(&m, NULL);
1316		fatal("Master refused termination request: %s", e);
1317	case MUX_S_FAILURE:
1318		e = buffer_get_string(&m, NULL);
1319		fatal("%s: termination request failed: %s", __func__, e);
1320	default:
1321		fatal("%s: unexpected response from master 0x%08x",
1322		    __func__, type);
1323	}
1324	buffer_free(&m);
1325	muxclient_request_id++;
1326}
1327
1328static int
1329mux_client_request_forward(int fd, u_int ftype, Forward *fwd)
1330{
1331	Buffer m;
1332	char *e, *fwd_desc;
1333	u_int type, rid;
1334
1335	fwd_desc = format_forward(ftype, fwd);
1336	debug("Requesting %s", fwd_desc);
1337	xfree(fwd_desc);
1338
1339	buffer_init(&m);
1340	buffer_put_int(&m, MUX_C_OPEN_FWD);
1341	buffer_put_int(&m, muxclient_request_id);
1342	buffer_put_int(&m, ftype);
1343	buffer_put_cstring(&m,
1344	    fwd->listen_host == NULL ? "" : fwd->listen_host);
1345	buffer_put_int(&m, fwd->listen_port);
1346	buffer_put_cstring(&m,
1347	    fwd->connect_host == NULL ? "" : fwd->connect_host);
1348	buffer_put_int(&m, fwd->connect_port);
1349
1350	if (mux_client_write_packet(fd, &m) != 0)
1351		fatal("%s: write packet: %s", __func__, strerror(errno));
1352
1353	buffer_clear(&m);
1354
1355	/* Read their reply */
1356	if (mux_client_read_packet(fd, &m) != 0) {
1357		buffer_free(&m);
1358		return -1;
1359	}
1360
1361	type = buffer_get_int(&m);
1362	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1363		fatal("%s: out of sequence reply: my id %u theirs %u",
1364		    __func__, muxclient_request_id, rid);
1365	switch (type) {
1366	case MUX_S_OK:
1367		break;
1368	case MUX_S_PERMISSION_DENIED:
1369		e = buffer_get_string(&m, NULL);
1370		buffer_free(&m);
1371		error("Master refused forwarding request: %s", e);
1372		return -1;
1373	case MUX_S_FAILURE:
1374		e = buffer_get_string(&m, NULL);
1375		buffer_free(&m);
1376		error("%s: session request failed: %s", __func__, e);
1377		return -1;
1378	default:
1379		fatal("%s: unexpected response from master 0x%08x",
1380		    __func__, type);
1381	}
1382	buffer_free(&m);
1383
1384	muxclient_request_id++;
1385	return 0;
1386}
1387
1388static int
1389mux_client_request_forwards(int fd)
1390{
1391	int i;
1392
1393	debug3("%s: requesting forwardings: %d local, %d remote", __func__,
1394	    options.num_local_forwards, options.num_remote_forwards);
1395
1396	/* XXX ExitOnForwardingFailure */
1397	for (i = 0; i < options.num_local_forwards; i++) {
1398		if (mux_client_request_forward(fd,
1399		    options.local_forwards[i].connect_port == 0 ?
1400		    MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1401		    options.local_forwards + i) != 0)
1402			return -1;
1403	}
1404	for (i = 0; i < options.num_remote_forwards; i++) {
1405		if (mux_client_request_forward(fd, MUX_FWD_REMOTE,
1406		    options.remote_forwards + i) != 0)
1407			return -1;
1408	}
1409	return 0;
1410}
1411
1412static int
1413mux_client_request_session(int fd)
1414{
1415	Buffer m;
1416	char *e, *term;
1417	u_int i, rid, sid, esid, exitval, type, exitval_seen;
1418	extern char **environ;
1419	int devnull;
1420
1421	debug3("%s: entering", __func__);
1422
1423	if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1424		error("%s: master alive request failed", __func__);
1425		return -1;
1426	}
1427
1428	signal(SIGPIPE, SIG_IGN);
1429
1430	if (stdin_null_flag) {
1431		if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1432			fatal("open(/dev/null): %s", strerror(errno));
1433		if (dup2(devnull, STDIN_FILENO) == -1)
1434			fatal("dup2: %s", strerror(errno));
1435		if (devnull > STDERR_FILENO)
1436			close(devnull);
1437	}
1438
1439	term = getenv("TERM");
1440
1441	buffer_init(&m);
1442	buffer_put_int(&m, MUX_C_NEW_SESSION);
1443	buffer_put_int(&m, muxclient_request_id);
1444	buffer_put_cstring(&m, ""); /* reserved */
1445	buffer_put_int(&m, tty_flag);
1446	buffer_put_int(&m, options.forward_x11);
1447	buffer_put_int(&m, options.forward_agent);
1448	buffer_put_int(&m, subsystem_flag);
1449	buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1450	    0xffffffff : (u_int)options.escape_char);
1451	buffer_put_cstring(&m, term == NULL ? "" : term);
1452	buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1453
1454	if (options.num_send_env > 0 && environ != NULL) {
1455		/* Pass environment */
1456		for (i = 0; environ[i] != NULL; i++) {
1457			if (env_permitted(environ[i])) {
1458				buffer_put_cstring(&m, environ[i]);
1459			}
1460		}
1461	}
1462
1463	if (mux_client_write_packet(fd, &m) != 0)
1464		fatal("%s: write packet: %s", __func__, strerror(errno));
1465
1466	/* Send the stdio file descriptors */
1467	if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1468	    mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1469	    mm_send_fd(fd, STDERR_FILENO) == -1)
1470		fatal("%s: send fds failed", __func__);
1471
1472	debug3("%s: session request sent", __func__);
1473
1474	/* Read their reply */
1475	buffer_clear(&m);
1476	if (mux_client_read_packet(fd, &m) != 0) {
1477		error("%s: read from master failed: %s",
1478		    __func__, strerror(errno));
1479		buffer_free(&m);
1480		return -1;
1481	}
1482
1483	type = buffer_get_int(&m);
1484	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1485		fatal("%s: out of sequence reply: my id %u theirs %u",
1486		    __func__, muxclient_request_id, rid);
1487	switch (type) {
1488	case MUX_S_SESSION_OPENED:
1489		sid = buffer_get_int(&m);
1490		debug("%s: master session id: %u", __func__, sid);
1491		break;
1492	case MUX_S_PERMISSION_DENIED:
1493		e = buffer_get_string(&m, NULL);
1494		buffer_free(&m);
1495		error("Master refused forwarding request: %s", e);
1496		return -1;
1497	case MUX_S_FAILURE:
1498		e = buffer_get_string(&m, NULL);
1499		buffer_free(&m);
1500		error("%s: forwarding request failed: %s", __func__, e);
1501		return -1;
1502	default:
1503		buffer_free(&m);
1504		error("%s: unexpected response from master 0x%08x",
1505		    __func__, type);
1506		return -1;
1507	}
1508	muxclient_request_id++;
1509
1510	signal(SIGHUP, control_client_sighandler);
1511	signal(SIGINT, control_client_sighandler);
1512	signal(SIGTERM, control_client_sighandler);
1513	signal(SIGWINCH, control_client_sigrelay);
1514
1515	if (tty_flag)
1516		enter_raw_mode(force_tty_flag);
1517
1518	/*
1519	 * Stick around until the controlee closes the client_fd.
1520	 * Before it does, it is expected to write an exit message.
1521	 * This process must read the value and wait for the closure of
1522	 * the client_fd; if this one closes early, the multiplex master will
1523	 * terminate early too (possibly losing data).
1524	 */
1525	for (exitval = 255, exitval_seen = 0;;) {
1526		buffer_clear(&m);
1527		if (mux_client_read_packet(fd, &m) != 0)
1528			break;
1529		type = buffer_get_int(&m);
1530		if (type != MUX_S_EXIT_MESSAGE) {
1531			e = buffer_get_string(&m, NULL);
1532			fatal("%s: master returned error: %s", __func__, e);
1533		}
1534		if ((esid = buffer_get_int(&m)) != sid)
1535			fatal("%s: exit on unknown session: my id %u theirs %u",
1536			    __func__, sid, esid);
1537		debug("%s: master session id: %u", __func__, sid);
1538		if (exitval_seen)
1539			fatal("%s: exitval sent twice", __func__);
1540		exitval = buffer_get_int(&m);
1541		exitval_seen = 1;
1542	}
1543
1544	close(fd);
1545	leave_raw_mode(force_tty_flag);
1546
1547	if (muxclient_terminate) {
1548		debug2("Exiting on signal %d", muxclient_terminate);
1549		exitval = 255;
1550	} else if (!exitval_seen) {
1551		debug2("Control master terminated unexpectedly");
1552		exitval = 255;
1553	} else
1554		debug2("Received exit status from master %d", exitval);
1555
1556	if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1557		fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1558
1559	exit(exitval);
1560}
1561
1562static int
1563mux_client_request_stdio_fwd(int fd)
1564{
1565	Buffer m;
1566	char *e;
1567	u_int type, rid, sid;
1568	int devnull;
1569
1570	debug3("%s: entering", __func__);
1571
1572	if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1573		error("%s: master alive request failed", __func__);
1574		return -1;
1575	}
1576
1577	signal(SIGPIPE, SIG_IGN);
1578
1579	if (stdin_null_flag) {
1580		if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1581			fatal("open(/dev/null): %s", strerror(errno));
1582		if (dup2(devnull, STDIN_FILENO) == -1)
1583			fatal("dup2: %s", strerror(errno));
1584		if (devnull > STDERR_FILENO)
1585			close(devnull);
1586	}
1587
1588	buffer_init(&m);
1589	buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
1590	buffer_put_int(&m, muxclient_request_id);
1591	buffer_put_cstring(&m, ""); /* reserved */
1592	buffer_put_cstring(&m, stdio_forward_host);
1593	buffer_put_int(&m, stdio_forward_port);
1594
1595	if (mux_client_write_packet(fd, &m) != 0)
1596		fatal("%s: write packet: %s", __func__, strerror(errno));
1597
1598	/* Send the stdio file descriptors */
1599	if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1600	    mm_send_fd(fd, STDOUT_FILENO) == -1)
1601		fatal("%s: send fds failed", __func__);
1602
1603	debug3("%s: stdio forward request sent", __func__);
1604
1605	/* Read their reply */
1606	buffer_clear(&m);
1607
1608	if (mux_client_read_packet(fd, &m) != 0) {
1609		error("%s: read from master failed: %s",
1610		    __func__, strerror(errno));
1611		buffer_free(&m);
1612		return -1;
1613	}
1614
1615	type = buffer_get_int(&m);
1616	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1617		fatal("%s: out of sequence reply: my id %u theirs %u",
1618		    __func__, muxclient_request_id, rid);
1619	switch (type) {
1620	case MUX_S_SESSION_OPENED:
1621		sid = buffer_get_int(&m);
1622		debug("%s: master session id: %u", __func__, sid);
1623		break;
1624	case MUX_S_PERMISSION_DENIED:
1625		e = buffer_get_string(&m, NULL);
1626		buffer_free(&m);
1627		fatal("Master refused forwarding request: %s", e);
1628	case MUX_S_FAILURE:
1629		e = buffer_get_string(&m, NULL);
1630		buffer_free(&m);
1631		fatal("%s: stdio forwarding request failed: %s", __func__, e);
1632	default:
1633		buffer_free(&m);
1634		error("%s: unexpected response from master 0x%08x",
1635		    __func__, type);
1636		return -1;
1637	}
1638	muxclient_request_id++;
1639
1640	signal(SIGHUP, control_client_sighandler);
1641	signal(SIGINT, control_client_sighandler);
1642	signal(SIGTERM, control_client_sighandler);
1643	signal(SIGWINCH, control_client_sigrelay);
1644
1645	/*
1646	 * Stick around until the controlee closes the client_fd.
1647	 */
1648	buffer_clear(&m);
1649	if (mux_client_read_packet(fd, &m) != 0) {
1650		if (errno == EPIPE ||
1651		    (errno == EINTR && muxclient_terminate != 0))
1652			return 0;
1653		fatal("%s: mux_client_read_packet: %s",
1654		    __func__, strerror(errno));
1655	}
1656	fatal("%s: master returned unexpected message %u", __func__, type);
1657}
1658
1659/* Multiplex client main loop. */
1660void
1661muxclient(const char *path)
1662{
1663	struct sockaddr_un addr;
1664	socklen_t sun_len;
1665	int sock;
1666	u_int pid;
1667
1668	if (muxclient_command == 0) {
1669		if (stdio_forward_host != NULL)
1670			muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
1671		else
1672			muxclient_command = SSHMUX_COMMAND_OPEN;
1673	}
1674
1675	switch (options.control_master) {
1676	case SSHCTL_MASTER_AUTO:
1677	case SSHCTL_MASTER_AUTO_ASK:
1678		debug("auto-mux: Trying existing master");
1679		/* FALLTHROUGH */
1680	case SSHCTL_MASTER_NO:
1681		break;
1682	default:
1683		return;
1684	}
1685
1686	memset(&addr, '\0', sizeof(addr));
1687	addr.sun_family = AF_UNIX;
1688	sun_len = offsetof(struct sockaddr_un, sun_path) +
1689	    strlen(path) + 1;
1690
1691	if (strlcpy(addr.sun_path, path,
1692	    sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1693		fatal("ControlPath too long");
1694
1695	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1696		fatal("%s socket(): %s", __func__, strerror(errno));
1697
1698	if (connect(sock, (struct sockaddr *)&addr, sun_len) == -1) {
1699		switch (muxclient_command) {
1700		case SSHMUX_COMMAND_OPEN:
1701		case SSHMUX_COMMAND_STDIO_FWD:
1702			break;
1703		default:
1704			fatal("Control socket connect(%.100s): %s", path,
1705			    strerror(errno));
1706		}
1707		if (errno == ENOENT)
1708			debug("Control socket \"%.100s\" does not exist", path);
1709		else {
1710			error("Control socket connect(%.100s): %s", path,
1711			    strerror(errno));
1712		}
1713		close(sock);
1714		return;
1715	}
1716	set_nonblock(sock);
1717
1718	if (mux_client_hello_exchange(sock) != 0) {
1719		error("%s: master hello exchange failed", __func__);
1720		close(sock);
1721		return;
1722	}
1723
1724	switch (muxclient_command) {
1725	case SSHMUX_COMMAND_ALIVE_CHECK:
1726		if ((pid = mux_client_request_alive(sock)) == 0)
1727			fatal("%s: master alive check failed", __func__);
1728		fprintf(stderr, "Master running (pid=%d)\r\n", pid);
1729		exit(0);
1730	case SSHMUX_COMMAND_TERMINATE:
1731		mux_client_request_terminate(sock);
1732		fprintf(stderr, "Exit request sent.\r\n");
1733		exit(0);
1734	case SSHMUX_COMMAND_OPEN:
1735		if (mux_client_request_forwards(sock) != 0) {
1736			error("%s: master forward request failed", __func__);
1737			return;
1738		}
1739		mux_client_request_session(sock);
1740		return;
1741	case SSHMUX_COMMAND_STDIO_FWD:
1742		mux_client_request_stdio_fwd(sock);
1743		exit(0);
1744	default:
1745		fatal("unrecognised muxclient_command %d", muxclient_command);
1746	}
1747}
1748