1/* $OpenBSD: mux.c,v 1.38 2013/01/02 00:32:07 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#include "openbsd-compat/sys-queue.h"
67#include "xmalloc.h"
68#include "log.h"
69#include "ssh.h"
70#include "ssh2.h"
71#include "pathnames.h"
72#include "misc.h"
73#include "match.h"
74#include "buffer.h"
75#include "channels.h"
76#include "msg.h"
77#include "packet.h"
78#include "monitor_fdpass.h"
79#include "sshpty.h"
80#include "key.h"
81#include "readconf.h"
82#include "clientloop.h"
83
84/* from ssh.c */
85extern int tty_flag;
86extern Options options;
87extern int stdin_null_flag;
88extern char *host;
89extern int subsystem_flag;
90extern Buffer command;
91extern volatile sig_atomic_t quit_pending;
92extern char *stdio_forward_host;
93extern int stdio_forward_port;
94
95/* Context for session open confirmation callback */
96struct mux_session_confirm_ctx {
97	u_int want_tty;
98	u_int want_subsys;
99	u_int want_x_fwd;
100	u_int want_agent_fwd;
101	Buffer cmd;
102	char *term;
103	struct termios tio;
104	char **env;
105	u_int rid;
106};
107
108/* Context for global channel callback */
109struct mux_channel_confirm_ctx {
110	u_int cid;	/* channel id */
111	u_int rid;	/* request id */
112	int fid;	/* forward id */
113};
114
115/* fd to control socket */
116int muxserver_sock = -1;
117
118/* client request id */
119u_int muxclient_request_id = 0;
120
121/* Multiplexing control command */
122u_int muxclient_command = 0;
123
124/* Set when signalled. */
125static volatile sig_atomic_t muxclient_terminate = 0;
126
127/* PID of multiplex server */
128static u_int muxserver_pid = 0;
129
130static Channel *mux_listener_channel = NULL;
131
132struct mux_master_state {
133	int hello_rcvd;
134};
135
136/* mux protocol messages */
137#define MUX_MSG_HELLO		0x00000001
138#define MUX_C_NEW_SESSION	0x10000002
139#define MUX_C_ALIVE_CHECK	0x10000004
140#define MUX_C_TERMINATE		0x10000005
141#define MUX_C_OPEN_FWD		0x10000006
142#define MUX_C_CLOSE_FWD		0x10000007
143#define MUX_C_NEW_STDIO_FWD	0x10000008
144#define MUX_C_STOP_LISTENING	0x10000009
145#define MUX_S_OK		0x80000001
146#define MUX_S_PERMISSION_DENIED	0x80000002
147#define MUX_S_FAILURE		0x80000003
148#define MUX_S_EXIT_MESSAGE	0x80000004
149#define MUX_S_ALIVE		0x80000005
150#define MUX_S_SESSION_OPENED	0x80000006
151#define MUX_S_REMOTE_PORT	0x80000007
152#define MUX_S_TTY_ALLOC_FAIL	0x80000008
153
154/* type codes for MUX_C_OPEN_FWD and MUX_C_CLOSE_FWD */
155#define MUX_FWD_LOCAL   1
156#define MUX_FWD_REMOTE  2
157#define MUX_FWD_DYNAMIC 3
158
159static void mux_session_confirm(int, int, void *);
160
161static int process_mux_master_hello(u_int, Channel *, Buffer *, Buffer *);
162static int process_mux_new_session(u_int, Channel *, Buffer *, Buffer *);
163static int process_mux_alive_check(u_int, Channel *, Buffer *, Buffer *);
164static int process_mux_terminate(u_int, Channel *, Buffer *, Buffer *);
165static int process_mux_open_fwd(u_int, Channel *, Buffer *, Buffer *);
166static int process_mux_close_fwd(u_int, Channel *, Buffer *, Buffer *);
167static int process_mux_stdio_fwd(u_int, Channel *, Buffer *, Buffer *);
168static int process_mux_stop_listening(u_int, Channel *, Buffer *, Buffer *);
169
170static const struct {
171	u_int type;
172	int (*handler)(u_int, Channel *, Buffer *, Buffer *);
173} mux_master_handlers[] = {
174	{ MUX_MSG_HELLO, process_mux_master_hello },
175	{ MUX_C_NEW_SESSION, process_mux_new_session },
176	{ MUX_C_ALIVE_CHECK, process_mux_alive_check },
177	{ MUX_C_TERMINATE, process_mux_terminate },
178	{ MUX_C_OPEN_FWD, process_mux_open_fwd },
179	{ MUX_C_CLOSE_FWD, process_mux_close_fwd },
180	{ MUX_C_NEW_STDIO_FWD, process_mux_stdio_fwd },
181	{ MUX_C_STOP_LISTENING, process_mux_stop_listening },
182	{ 0, NULL }
183};
184
185/* Cleanup callback fired on closure of mux slave _session_ channel */
186/* ARGSUSED */
187void
188mux_master_session_cleanup_cb(int cid, void *unused)
189{
190	Channel *cc, *c = channel_by_id(cid);
191
192	debug3("%s: entering for channel %d", __func__, cid);
193	if (c == NULL)
194		fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
195	if (c->ctl_chan != -1) {
196		if ((cc = channel_by_id(c->ctl_chan)) == NULL)
197			fatal("%s: channel %d missing control channel %d",
198			    __func__, c->self, c->ctl_chan);
199		c->ctl_chan = -1;
200		cc->remote_id = -1;
201		chan_rcvd_oclose(cc);
202	}
203	channel_cancel_cleanup(c->self);
204}
205
206/* Cleanup callback fired on closure of mux slave _control_ channel */
207/* ARGSUSED */
208static void
209mux_master_control_cleanup_cb(int cid, void *unused)
210{
211	Channel *sc, *c = channel_by_id(cid);
212
213	debug3("%s: entering for channel %d", __func__, cid);
214	if (c == NULL)
215		fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
216	if (c->remote_id != -1) {
217		if ((sc = channel_by_id(c->remote_id)) == NULL)
218			fatal("%s: channel %d missing session channel %d",
219			    __func__, c->self, c->remote_id);
220		c->remote_id = -1;
221		sc->ctl_chan = -1;
222		if (sc->type != SSH_CHANNEL_OPEN) {
223			debug2("%s: channel %d: not open", __func__, sc->self);
224			chan_mark_dead(sc);
225		} else {
226			if (sc->istate == CHAN_INPUT_OPEN)
227				chan_read_failed(sc);
228			if (sc->ostate == CHAN_OUTPUT_OPEN)
229				chan_write_failed(sc);
230		}
231	}
232	channel_cancel_cleanup(c->self);
233}
234
235/* Check mux client environment variables before passing them to mux master. */
236static int
237env_permitted(char *env)
238{
239	int i, ret;
240	char name[1024], *cp;
241
242	if ((cp = strchr(env, '=')) == NULL || cp == env)
243		return 0;
244	ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
245	if (ret <= 0 || (size_t)ret >= sizeof(name)) {
246		error("env_permitted: name '%.100s...' too long", env);
247		return 0;
248	}
249
250	for (i = 0; i < options.num_send_env; i++)
251		if (match_pattern(name, options.send_env[i]))
252			return 1;
253
254	return 0;
255}
256
257/* Mux master protocol message handlers */
258
259static int
260process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
261{
262	u_int ver;
263	struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
264
265	if (state == NULL)
266		fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
267	if (state->hello_rcvd) {
268		error("%s: HELLO received twice", __func__);
269		return -1;
270	}
271	if (buffer_get_int_ret(&ver, m) != 0) {
272 malf:
273		error("%s: malformed message", __func__);
274		return -1;
275	}
276	if (ver != SSHMUX_VER) {
277		error("Unsupported multiplexing protocol version %d "
278		    "(expected %d)", ver, SSHMUX_VER);
279		return -1;
280	}
281	debug2("%s: channel %d slave version %u", __func__, c->self, ver);
282
283	/* No extensions are presently defined */
284	while (buffer_len(m) > 0) {
285		char *name = buffer_get_string_ret(m, NULL);
286		char *value = buffer_get_string_ret(m, NULL);
287
288		if (name == NULL || value == NULL) {
289			if (name != NULL)
290				xfree(name);
291			goto malf;
292		}
293		debug2("Unrecognised slave extension \"%s\"", name);
294		xfree(name);
295		xfree(value);
296	}
297	state->hello_rcvd = 1;
298	return 0;
299}
300
301static int
302process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
303{
304	Channel *nc;
305	struct mux_session_confirm_ctx *cctx;
306	char *reserved, *cmd, *cp;
307	u_int i, j, len, env_len, escape_char, window, packetmax;
308	int new_fd[3];
309
310	/* Reply for SSHMUX_COMMAND_OPEN */
311	cctx = xcalloc(1, sizeof(*cctx));
312	cctx->term = NULL;
313	cctx->rid = rid;
314	cmd = reserved = NULL;
315	cctx->env = NULL;
316	env_len = 0;
317	if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
318	    buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
319	    buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
320	    buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
321	    buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
322	    buffer_get_int_ret(&escape_char, m) != 0 ||
323	    (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
324	    (cmd = buffer_get_string_ret(m, &len)) == NULL) {
325 malf:
326		if (cmd != NULL)
327			xfree(cmd);
328		if (reserved != NULL)
329			xfree(reserved);
330		for (j = 0; j < env_len; j++)
331			xfree(cctx->env[j]);
332		if (env_len > 0)
333			xfree(cctx->env);
334		if (cctx->term != NULL)
335			xfree(cctx->term);
336		xfree(cctx);
337		error("%s: malformed message", __func__);
338		return -1;
339	}
340	xfree(reserved);
341	reserved = NULL;
342
343	while (buffer_len(m) > 0) {
344#define MUX_MAX_ENV_VARS	4096
345		if ((cp = buffer_get_string_ret(m, &len)) == NULL)
346			goto malf;
347		if (!env_permitted(cp)) {
348			xfree(cp);
349			continue;
350		}
351		cctx->env = xrealloc(cctx->env, env_len + 2,
352		    sizeof(*cctx->env));
353		cctx->env[env_len++] = cp;
354		cctx->env[env_len] = NULL;
355		if (env_len > MUX_MAX_ENV_VARS) {
356			error(">%d environment variables received, ignoring "
357			    "additional", MUX_MAX_ENV_VARS);
358			break;
359		}
360	}
361
362	debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
363	    "term \"%s\", cmd \"%s\", env %u", __func__, c->self,
364	    cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
365	    cctx->want_subsys, cctx->term, cmd, env_len);
366
367	buffer_init(&cctx->cmd);
368	buffer_append(&cctx->cmd, cmd, strlen(cmd));
369	xfree(cmd);
370	cmd = NULL;
371
372	/* Gather fds from client */
373	for(i = 0; i < 3; i++) {
374		if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
375			error("%s: failed to receive fd %d from slave",
376			    __func__, i);
377			for (j = 0; j < i; j++)
378				close(new_fd[j]);
379			for (j = 0; j < env_len; j++)
380				xfree(cctx->env[j]);
381			if (env_len > 0)
382				xfree(cctx->env);
383			xfree(cctx->term);
384			buffer_free(&cctx->cmd);
385			xfree(cctx);
386
387			/* prepare reply */
388			buffer_put_int(r, MUX_S_FAILURE);
389			buffer_put_int(r, rid);
390			buffer_put_cstring(r,
391			    "did not receive file descriptors");
392			return -1;
393		}
394	}
395
396	debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
397	    new_fd[0], new_fd[1], new_fd[2]);
398
399	/* XXX support multiple child sessions in future */
400	if (c->remote_id != -1) {
401		debug2("%s: session already open", __func__);
402		/* prepare reply */
403		buffer_put_int(r, MUX_S_FAILURE);
404		buffer_put_int(r, rid);
405		buffer_put_cstring(r, "Multiple sessions not supported");
406 cleanup:
407		close(new_fd[0]);
408		close(new_fd[1]);
409		close(new_fd[2]);
410		xfree(cctx->term);
411		if (env_len != 0) {
412			for (i = 0; i < env_len; i++)
413				xfree(cctx->env[i]);
414			xfree(cctx->env);
415		}
416		buffer_free(&cctx->cmd);
417		xfree(cctx);
418		return 0;
419	}
420
421	if (options.control_master == SSHCTL_MASTER_ASK ||
422	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
423		if (!ask_permission("Allow shared connection to %s? ", host)) {
424			debug2("%s: session refused by user", __func__);
425			/* prepare reply */
426			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
427			buffer_put_int(r, rid);
428			buffer_put_cstring(r, "Permission denied");
429			goto cleanup;
430		}
431	}
432
433	/* Try to pick up ttymodes from client before it goes raw */
434	if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
435		error("%s: tcgetattr: %s", __func__, strerror(errno));
436
437	/* enable nonblocking unless tty */
438	if (!isatty(new_fd[0]))
439		set_nonblock(new_fd[0]);
440	if (!isatty(new_fd[1]))
441		set_nonblock(new_fd[1]);
442	if (!isatty(new_fd[2]))
443		set_nonblock(new_fd[2]);
444
445	window = CHAN_SES_WINDOW_DEFAULT;
446	packetmax = CHAN_SES_PACKET_DEFAULT;
447	if (cctx->want_tty) {
448		window >>= 1;
449		packetmax >>= 1;
450	}
451
452	nc = channel_new("session", SSH_CHANNEL_OPENING,
453	    new_fd[0], new_fd[1], new_fd[2], window, packetmax,
454	    CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
455
456	nc->ctl_chan = c->self;		/* link session -> control channel */
457	c->remote_id = nc->self; 	/* link control -> session channel */
458
459	if (cctx->want_tty && escape_char != 0xffffffff) {
460		channel_register_filter(nc->self,
461		    client_simple_escape_filter, NULL,
462		    client_filter_cleanup,
463		    client_new_escape_filter_ctx((int)escape_char));
464	}
465
466	debug2("%s: channel_new: %d linked to control channel %d",
467	    __func__, nc->self, nc->ctl_chan);
468
469	channel_send_open(nc->self);
470	channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
471	c->mux_pause = 1; /* stop handling messages until open_confirm done */
472	channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
473
474	/* reply is deferred, sent by mux_session_confirm */
475	return 0;
476}
477
478static int
479process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
480{
481	debug2("%s: channel %d: alive check", __func__, c->self);
482
483	/* prepare reply */
484	buffer_put_int(r, MUX_S_ALIVE);
485	buffer_put_int(r, rid);
486	buffer_put_int(r, (u_int)getpid());
487
488	return 0;
489}
490
491static int
492process_mux_terminate(u_int rid, Channel *c, Buffer *m, Buffer *r)
493{
494	debug2("%s: channel %d: terminate request", __func__, c->self);
495
496	if (options.control_master == SSHCTL_MASTER_ASK ||
497	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
498		if (!ask_permission("Terminate shared connection to %s? ",
499		    host)) {
500			debug2("%s: termination refused by user", __func__);
501			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
502			buffer_put_int(r, rid);
503			buffer_put_cstring(r, "Permission denied");
504			return 0;
505		}
506	}
507
508	quit_pending = 1;
509	buffer_put_int(r, MUX_S_OK);
510	buffer_put_int(r, rid);
511	/* XXX exit happens too soon - message never makes it to client */
512	return 0;
513}
514
515static char *
516format_forward(u_int ftype, Forward *fwd)
517{
518	char *ret;
519
520	switch (ftype) {
521	case MUX_FWD_LOCAL:
522		xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
523		    (fwd->listen_host == NULL) ?
524		    (options.gateway_ports ? "*" : "LOCALHOST") :
525		    fwd->listen_host, fwd->listen_port,
526		    fwd->connect_host, fwd->connect_port);
527		break;
528	case MUX_FWD_DYNAMIC:
529		xasprintf(&ret, "dynamic forward %.200s:%d -> *",
530		    (fwd->listen_host == NULL) ?
531		    (options.gateway_ports ? "*" : "LOCALHOST") :
532		     fwd->listen_host, fwd->listen_port);
533		break;
534	case MUX_FWD_REMOTE:
535		xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
536		    (fwd->listen_host == NULL) ?
537		    "LOCALHOST" : fwd->listen_host,
538		    fwd->listen_port,
539		    fwd->connect_host, fwd->connect_port);
540		break;
541	default:
542		fatal("%s: unknown forward type %u", __func__, ftype);
543	}
544	return ret;
545}
546
547static int
548compare_host(const char *a, const char *b)
549{
550	if (a == NULL && b == NULL)
551		return 1;
552	if (a == NULL || b == NULL)
553		return 0;
554	return strcmp(a, b) == 0;
555}
556
557static int
558compare_forward(Forward *a, Forward *b)
559{
560	if (!compare_host(a->listen_host, b->listen_host))
561		return 0;
562	if (a->listen_port != b->listen_port)
563		return 0;
564	if (!compare_host(a->connect_host, b->connect_host))
565		return 0;
566	if (a->connect_port != b->connect_port)
567		return 0;
568
569	return 1;
570}
571
572static void
573mux_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
574{
575	struct mux_channel_confirm_ctx *fctx = ctxt;
576	char *failmsg = NULL;
577	Forward *rfwd;
578	Channel *c;
579	Buffer out;
580
581	if ((c = channel_by_id(fctx->cid)) == NULL) {
582		/* no channel for reply */
583		error("%s: unknown channel", __func__);
584		return;
585	}
586	buffer_init(&out);
587	if (fctx->fid >= options.num_remote_forwards) {
588		xasprintf(&failmsg, "unknown forwarding id %d", fctx->fid);
589		goto fail;
590	}
591	rfwd = &options.remote_forwards[fctx->fid];
592	debug("%s: %s for: listen %d, connect %s:%d", __func__,
593	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
594	    rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
595	if (type == SSH2_MSG_REQUEST_SUCCESS) {
596		if (rfwd->listen_port == 0) {
597			rfwd->allocated_port = packet_get_int();
598			logit("Allocated port %u for mux remote forward"
599			    " to %s:%d", rfwd->allocated_port,
600			    rfwd->connect_host, rfwd->connect_port);
601			buffer_put_int(&out, MUX_S_REMOTE_PORT);
602			buffer_put_int(&out, fctx->rid);
603			buffer_put_int(&out, rfwd->allocated_port);
604			channel_update_permitted_opens(rfwd->handle,
605			   rfwd->allocated_port);
606		} else {
607			buffer_put_int(&out, MUX_S_OK);
608			buffer_put_int(&out, fctx->rid);
609		}
610		goto out;
611	} else {
612		if (rfwd->listen_port == 0)
613			channel_update_permitted_opens(rfwd->handle, -1);
614		xasprintf(&failmsg, "remote port forwarding failed for "
615		    "listen port %d", rfwd->listen_port);
616	}
617 fail:
618	error("%s: %s", __func__, failmsg);
619	buffer_put_int(&out, MUX_S_FAILURE);
620	buffer_put_int(&out, fctx->rid);
621	buffer_put_cstring(&out, failmsg);
622	xfree(failmsg);
623 out:
624	buffer_put_string(&c->output, buffer_ptr(&out), buffer_len(&out));
625	buffer_free(&out);
626	if (c->mux_pause <= 0)
627		fatal("%s: mux_pause %d", __func__, c->mux_pause);
628	c->mux_pause = 0; /* start processing messages again */
629}
630
631static int
632process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
633{
634	Forward fwd;
635	char *fwd_desc = NULL;
636	u_int ftype;
637	int i, ret = 0, freefwd = 1;
638
639	fwd.listen_host = fwd.connect_host = NULL;
640	if (buffer_get_int_ret(&ftype, m) != 0 ||
641	    (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
642	    buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
643	    (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
644	    buffer_get_int_ret(&fwd.connect_port, m) != 0) {
645		error("%s: malformed message", __func__);
646		ret = -1;
647		goto out;
648	}
649
650	if (*fwd.listen_host == '\0') {
651		xfree(fwd.listen_host);
652		fwd.listen_host = NULL;
653	}
654	if (*fwd.connect_host == '\0') {
655		xfree(fwd.connect_host);
656		fwd.connect_host = NULL;
657	}
658
659	debug2("%s: channel %d: request %s", __func__, c->self,
660	    (fwd_desc = format_forward(ftype, &fwd)));
661
662	if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
663	    ftype != MUX_FWD_DYNAMIC) {
664		logit("%s: invalid forwarding type %u", __func__, ftype);
665 invalid:
666		if (fwd.listen_host)
667			xfree(fwd.listen_host);
668		if (fwd.connect_host)
669			xfree(fwd.connect_host);
670		buffer_put_int(r, MUX_S_FAILURE);
671		buffer_put_int(r, rid);
672		buffer_put_cstring(r, "Invalid forwarding request");
673		return 0;
674	}
675	if (fwd.listen_port >= 65536) {
676		logit("%s: invalid listen port %u", __func__,
677		    fwd.listen_port);
678		goto invalid;
679	}
680	if (fwd.connect_port >= 65536 || (ftype != MUX_FWD_DYNAMIC &&
681	    ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
682		logit("%s: invalid connect port %u", __func__,
683		    fwd.connect_port);
684		goto invalid;
685	}
686	if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL) {
687		logit("%s: missing connect host", __func__);
688		goto invalid;
689	}
690
691	/* Skip forwards that have already been requested */
692	switch (ftype) {
693	case MUX_FWD_LOCAL:
694	case MUX_FWD_DYNAMIC:
695		for (i = 0; i < options.num_local_forwards; i++) {
696			if (compare_forward(&fwd,
697			    options.local_forwards + i)) {
698 exists:
699				debug2("%s: found existing forwarding",
700				    __func__);
701				buffer_put_int(r, MUX_S_OK);
702				buffer_put_int(r, rid);
703				goto out;
704			}
705		}
706		break;
707	case MUX_FWD_REMOTE:
708		for (i = 0; i < options.num_remote_forwards; i++) {
709			if (compare_forward(&fwd,
710			    options.remote_forwards + i)) {
711				if (fwd.listen_port != 0)
712					goto exists;
713				debug2("%s: found allocated port",
714				    __func__);
715				buffer_put_int(r, MUX_S_REMOTE_PORT);
716				buffer_put_int(r, rid);
717				buffer_put_int(r,
718				    options.remote_forwards[i].allocated_port);
719				goto out;
720			}
721		}
722		break;
723	}
724
725	if (options.control_master == SSHCTL_MASTER_ASK ||
726	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
727		if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
728			debug2("%s: forwarding refused by user", __func__);
729			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
730			buffer_put_int(r, rid);
731			buffer_put_cstring(r, "Permission denied");
732			goto out;
733		}
734	}
735
736	if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
737		if (!channel_setup_local_fwd_listener(fwd.listen_host,
738		    fwd.listen_port, fwd.connect_host, fwd.connect_port,
739		    options.gateway_ports)) {
740 fail:
741			logit("slave-requested %s failed", fwd_desc);
742			buffer_put_int(r, MUX_S_FAILURE);
743			buffer_put_int(r, rid);
744			buffer_put_cstring(r, "Port forwarding failed");
745			goto out;
746		}
747		add_local_forward(&options, &fwd);
748		freefwd = 0;
749	} else {
750		struct mux_channel_confirm_ctx *fctx;
751
752		fwd.handle = channel_request_remote_forwarding(fwd.listen_host,
753		    fwd.listen_port, fwd.connect_host, fwd.connect_port);
754		if (fwd.handle < 0)
755			goto fail;
756		add_remote_forward(&options, &fwd);
757		fctx = xcalloc(1, sizeof(*fctx));
758		fctx->cid = c->self;
759		fctx->rid = rid;
760		fctx->fid = options.num_remote_forwards - 1;
761		client_register_global_confirm(mux_confirm_remote_forward,
762		    fctx);
763		freefwd = 0;
764		c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
765		/* delayed reply in mux_confirm_remote_forward */
766		goto out;
767	}
768	buffer_put_int(r, MUX_S_OK);
769	buffer_put_int(r, rid);
770 out:
771	if (fwd_desc != NULL)
772		xfree(fwd_desc);
773	if (freefwd) {
774		if (fwd.listen_host != NULL)
775			xfree(fwd.listen_host);
776		if (fwd.connect_host != NULL)
777			xfree(fwd.connect_host);
778	}
779	return ret;
780}
781
782static int
783process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
784{
785	Forward fwd, *found_fwd;
786	char *fwd_desc = NULL;
787	const char *error_reason = NULL;
788	u_int ftype;
789	int i, listen_port, ret = 0;
790
791	fwd.listen_host = fwd.connect_host = NULL;
792	if (buffer_get_int_ret(&ftype, m) != 0 ||
793	    (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
794	    buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
795	    (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
796	    buffer_get_int_ret(&fwd.connect_port, m) != 0) {
797		error("%s: malformed message", __func__);
798		ret = -1;
799		goto out;
800	}
801
802	if (*fwd.listen_host == '\0') {
803		xfree(fwd.listen_host);
804		fwd.listen_host = NULL;
805	}
806	if (*fwd.connect_host == '\0') {
807		xfree(fwd.connect_host);
808		fwd.connect_host = NULL;
809	}
810
811	debug2("%s: channel %d: request cancel %s", __func__, c->self,
812	    (fwd_desc = format_forward(ftype, &fwd)));
813
814	/* make sure this has been requested */
815	found_fwd = NULL;
816	switch (ftype) {
817	case MUX_FWD_LOCAL:
818	case MUX_FWD_DYNAMIC:
819		for (i = 0; i < options.num_local_forwards; i++) {
820			if (compare_forward(&fwd,
821			    options.local_forwards + i)) {
822				found_fwd = options.local_forwards + i;
823				break;
824			}
825		}
826		break;
827	case MUX_FWD_REMOTE:
828		for (i = 0; i < options.num_remote_forwards; i++) {
829			if (compare_forward(&fwd,
830			    options.remote_forwards + i)) {
831				found_fwd = options.remote_forwards + i;
832				break;
833			}
834		}
835		break;
836	}
837
838	if (found_fwd == NULL)
839		error_reason = "port not forwarded";
840	else if (ftype == MUX_FWD_REMOTE) {
841		/*
842		 * This shouldn't fail unless we confused the host/port
843		 * between options.remote_forwards and permitted_opens.
844		 * However, for dynamic allocated listen ports we need
845		 * to lookup the actual listen port.
846		 */
847	        listen_port = (fwd.listen_port == 0) ?
848		    found_fwd->allocated_port : fwd.listen_port;
849		if (channel_request_rforward_cancel(fwd.listen_host,
850		    listen_port) == -1)
851			error_reason = "port not in permitted opens";
852	} else {	/* local and dynamic forwards */
853		/* Ditto */
854		if (channel_cancel_lport_listener(fwd.listen_host,
855		    fwd.listen_port, fwd.connect_port,
856		    options.gateway_ports) == -1)
857			error_reason = "port not found";
858	}
859
860	if (error_reason == NULL) {
861		buffer_put_int(r, MUX_S_OK);
862		buffer_put_int(r, rid);
863
864		if (found_fwd->listen_host != NULL)
865			xfree(found_fwd->listen_host);
866		if (found_fwd->connect_host != NULL)
867			xfree(found_fwd->connect_host);
868		found_fwd->listen_host = found_fwd->connect_host = NULL;
869		found_fwd->listen_port = found_fwd->connect_port = 0;
870	} else {
871		buffer_put_int(r, MUX_S_FAILURE);
872		buffer_put_int(r, rid);
873		buffer_put_cstring(r, error_reason);
874	}
875 out:
876	if (fwd_desc != NULL)
877		xfree(fwd_desc);
878	if (fwd.listen_host != NULL)
879		xfree(fwd.listen_host);
880	if (fwd.connect_host != NULL)
881		xfree(fwd.connect_host);
882
883	return ret;
884}
885
886static int
887process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
888{
889	Channel *nc;
890	char *reserved, *chost;
891	u_int cport, i, j;
892	int new_fd[2];
893
894	chost = reserved = NULL;
895	if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
896	   (chost = buffer_get_string_ret(m, NULL)) == NULL ||
897	    buffer_get_int_ret(&cport, m) != 0) {
898		if (reserved != NULL)
899			xfree(reserved);
900		if (chost != NULL)
901			xfree(chost);
902		error("%s: malformed message", __func__);
903		return -1;
904	}
905	xfree(reserved);
906
907	debug2("%s: channel %d: request stdio fwd to %s:%u",
908	    __func__, c->self, chost, cport);
909
910	/* Gather fds from client */
911	for(i = 0; i < 2; i++) {
912		if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
913			error("%s: failed to receive fd %d from slave",
914			    __func__, i);
915			for (j = 0; j < i; j++)
916				close(new_fd[j]);
917			xfree(chost);
918
919			/* prepare reply */
920			buffer_put_int(r, MUX_S_FAILURE);
921			buffer_put_int(r, rid);
922			buffer_put_cstring(r,
923			    "did not receive file descriptors");
924			return -1;
925		}
926	}
927
928	debug3("%s: got fds stdin %d, stdout %d", __func__,
929	    new_fd[0], new_fd[1]);
930
931	/* XXX support multiple child sessions in future */
932	if (c->remote_id != -1) {
933		debug2("%s: session already open", __func__);
934		/* prepare reply */
935		buffer_put_int(r, MUX_S_FAILURE);
936		buffer_put_int(r, rid);
937		buffer_put_cstring(r, "Multiple sessions not supported");
938 cleanup:
939		close(new_fd[0]);
940		close(new_fd[1]);
941		xfree(chost);
942		return 0;
943	}
944
945	if (options.control_master == SSHCTL_MASTER_ASK ||
946	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
947		if (!ask_permission("Allow forward to %s:%u? ",
948		    chost, cport)) {
949			debug2("%s: stdio fwd refused by user", __func__);
950			/* prepare reply */
951			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
952			buffer_put_int(r, rid);
953			buffer_put_cstring(r, "Permission denied");
954			goto cleanup;
955		}
956	}
957
958	/* enable nonblocking unless tty */
959	if (!isatty(new_fd[0]))
960		set_nonblock(new_fd[0]);
961	if (!isatty(new_fd[1]))
962		set_nonblock(new_fd[1]);
963
964	nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
965
966	nc->ctl_chan = c->self;		/* link session -> control channel */
967	c->remote_id = nc->self; 	/* link control -> session channel */
968
969	debug2("%s: channel_new: %d linked to control channel %d",
970	    __func__, nc->self, nc->ctl_chan);
971
972	channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
973
974	/* prepare reply */
975	/* XXX defer until channel confirmed */
976	buffer_put_int(r, MUX_S_SESSION_OPENED);
977	buffer_put_int(r, rid);
978	buffer_put_int(r, nc->self);
979
980	return 0;
981}
982
983static int
984process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
985{
986	debug("%s: channel %d: stop listening", __func__, c->self);
987
988	if (options.control_master == SSHCTL_MASTER_ASK ||
989	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
990		if (!ask_permission("Disable further multiplexing on shared "
991		    "connection to %s? ", host)) {
992			debug2("%s: stop listen refused by user", __func__);
993			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
994			buffer_put_int(r, rid);
995			buffer_put_cstring(r, "Permission denied");
996			return 0;
997		}
998	}
999
1000	if (mux_listener_channel != NULL) {
1001		channel_free(mux_listener_channel);
1002		client_stop_mux();
1003		xfree(options.control_path);
1004		options.control_path = NULL;
1005		mux_listener_channel = NULL;
1006		muxserver_sock = -1;
1007	}
1008
1009	/* prepare reply */
1010	buffer_put_int(r, MUX_S_OK);
1011	buffer_put_int(r, rid);
1012
1013	return 0;
1014}
1015
1016/* Channel callbacks fired on read/write from mux slave fd */
1017static int
1018mux_master_read_cb(Channel *c)
1019{
1020	struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
1021	Buffer in, out;
1022	void *ptr;
1023	u_int type, rid, have, i;
1024	int ret = -1;
1025
1026	/* Setup ctx and  */
1027	if (c->mux_ctx == NULL) {
1028		state = xcalloc(1, sizeof(*state));
1029		c->mux_ctx = state;
1030		channel_register_cleanup(c->self,
1031		    mux_master_control_cleanup_cb, 0);
1032
1033		/* Send hello */
1034		buffer_init(&out);
1035		buffer_put_int(&out, MUX_MSG_HELLO);
1036		buffer_put_int(&out, SSHMUX_VER);
1037		/* no extensions */
1038		buffer_put_string(&c->output, buffer_ptr(&out),
1039		    buffer_len(&out));
1040		buffer_free(&out);
1041		debug3("%s: channel %d: hello sent", __func__, c->self);
1042		return 0;
1043	}
1044
1045	buffer_init(&in);
1046	buffer_init(&out);
1047
1048	/* Channel code ensures that we receive whole packets */
1049	if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
1050 malf:
1051		error("%s: malformed message", __func__);
1052		goto out;
1053	}
1054	buffer_append(&in, ptr, have);
1055
1056	if (buffer_get_int_ret(&type, &in) != 0)
1057		goto malf;
1058	debug3("%s: channel %d packet type 0x%08x len %u",
1059	    __func__, c->self, type, buffer_len(&in));
1060
1061	if (type == MUX_MSG_HELLO)
1062		rid = 0;
1063	else {
1064		if (!state->hello_rcvd) {
1065			error("%s: expected MUX_MSG_HELLO(0x%08x), "
1066			    "received 0x%08x", __func__, MUX_MSG_HELLO, type);
1067			goto out;
1068		}
1069		if (buffer_get_int_ret(&rid, &in) != 0)
1070			goto malf;
1071	}
1072
1073	for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
1074		if (type == mux_master_handlers[i].type) {
1075			ret = mux_master_handlers[i].handler(rid, c, &in, &out);
1076			break;
1077		}
1078	}
1079	if (mux_master_handlers[i].handler == NULL) {
1080		error("%s: unsupported mux message 0x%08x", __func__, type);
1081		buffer_put_int(&out, MUX_S_FAILURE);
1082		buffer_put_int(&out, rid);
1083		buffer_put_cstring(&out, "unsupported request");
1084		ret = 0;
1085	}
1086	/* Enqueue reply packet */
1087	if (buffer_len(&out) != 0) {
1088		buffer_put_string(&c->output, buffer_ptr(&out),
1089		    buffer_len(&out));
1090	}
1091 out:
1092	buffer_free(&in);
1093	buffer_free(&out);
1094	return ret;
1095}
1096
1097void
1098mux_exit_message(Channel *c, int exitval)
1099{
1100	Buffer m;
1101	Channel *mux_chan;
1102
1103	debug3("%s: channel %d: exit message, evitval %d", __func__, c->self,
1104	    exitval);
1105
1106	if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1107		fatal("%s: channel %d missing mux channel %d",
1108		    __func__, c->self, c->ctl_chan);
1109
1110	/* Append exit message packet to control socket output queue */
1111	buffer_init(&m);
1112	buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
1113	buffer_put_int(&m, c->self);
1114	buffer_put_int(&m, exitval);
1115
1116	buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1117	buffer_free(&m);
1118}
1119
1120void
1121mux_tty_alloc_failed(Channel *c)
1122{
1123	Buffer m;
1124	Channel *mux_chan;
1125
1126	debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
1127
1128	if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1129		fatal("%s: channel %d missing mux channel %d",
1130		    __func__, c->self, c->ctl_chan);
1131
1132	/* Append exit message packet to control socket output queue */
1133	buffer_init(&m);
1134	buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
1135	buffer_put_int(&m, c->self);
1136
1137	buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1138	buffer_free(&m);
1139}
1140
1141/* Prepare a mux master to listen on a Unix domain socket. */
1142void
1143muxserver_listen(void)
1144{
1145	struct sockaddr_un addr;
1146	socklen_t sun_len;
1147	mode_t old_umask;
1148	char *orig_control_path = options.control_path;
1149	char rbuf[16+1];
1150	u_int i, r;
1151
1152	if (options.control_path == NULL ||
1153	    options.control_master == SSHCTL_MASTER_NO)
1154		return;
1155
1156	debug("setting up multiplex master socket");
1157
1158	/*
1159	 * Use a temporary path before listen so we can pseudo-atomically
1160	 * establish the listening socket in its final location to avoid
1161	 * other processes racing in between bind() and listen() and hitting
1162	 * an unready socket.
1163	 */
1164	for (i = 0; i < sizeof(rbuf) - 1; i++) {
1165		r = arc4random_uniform(26+26+10);
1166		rbuf[i] = (r < 26) ? 'a' + r :
1167		    (r < 26*2) ? 'A' + r - 26 :
1168		    '0' + r - 26 - 26;
1169	}
1170	rbuf[sizeof(rbuf) - 1] = '\0';
1171	options.control_path = NULL;
1172	xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
1173	debug3("%s: temporary control path %s", __func__, options.control_path);
1174
1175	memset(&addr, '\0', sizeof(addr));
1176	addr.sun_family = AF_UNIX;
1177	sun_len = offsetof(struct sockaddr_un, sun_path) +
1178	    strlen(options.control_path) + 1;
1179
1180	if (strlcpy(addr.sun_path, options.control_path,
1181	    sizeof(addr.sun_path)) >= sizeof(addr.sun_path)) {
1182		error("ControlPath \"%s\" too long for Unix domain socket",
1183		    options.control_path);
1184		goto disable_mux_master;
1185	}
1186
1187	if ((muxserver_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1188		fatal("%s socket(): %s", __func__, strerror(errno));
1189
1190	old_umask = umask(0177);
1191	if (bind(muxserver_sock, (struct sockaddr *)&addr, sun_len) == -1) {
1192		if (errno == EINVAL || errno == EADDRINUSE) {
1193			error("ControlSocket %s already exists, "
1194			    "disabling multiplexing", options.control_path);
1195 disable_mux_master:
1196			if (muxserver_sock != -1) {
1197				close(muxserver_sock);
1198				muxserver_sock = -1;
1199			}
1200			xfree(orig_control_path);
1201			xfree(options.control_path);
1202			options.control_path = NULL;
1203			options.control_master = SSHCTL_MASTER_NO;
1204			return;
1205		} else
1206			fatal("%s bind(): %s", __func__, strerror(errno));
1207	}
1208	umask(old_umask);
1209
1210	if (listen(muxserver_sock, 64) == -1)
1211		fatal("%s listen(): %s", __func__, strerror(errno));
1212
1213	/* Now atomically "move" the mux socket into position */
1214	if (link(options.control_path, orig_control_path) != 0) {
1215		if (errno != EEXIST) {
1216			fatal("%s: link mux listener %s => %s: %s", __func__,
1217			    options.control_path, orig_control_path,
1218			    strerror(errno));
1219		}
1220		error("ControlSocket %s already exists, disabling multiplexing",
1221		    orig_control_path);
1222		unlink(options.control_path);
1223		goto disable_mux_master;
1224	}
1225	unlink(options.control_path);
1226	xfree(options.control_path);
1227	options.control_path = orig_control_path;
1228
1229	set_nonblock(muxserver_sock);
1230
1231	mux_listener_channel = channel_new("mux listener",
1232	    SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
1233	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1234	    0, options.control_path, 1);
1235	mux_listener_channel->mux_rcb = mux_master_read_cb;
1236	debug3("%s: mux listener channel %d fd %d", __func__,
1237	    mux_listener_channel->self, mux_listener_channel->sock);
1238}
1239
1240/* Callback on open confirmation in mux master for a mux client session. */
1241static void
1242mux_session_confirm(int id, int success, void *arg)
1243{
1244	struct mux_session_confirm_ctx *cctx = arg;
1245	const char *display;
1246	Channel *c, *cc;
1247	int i;
1248	Buffer reply;
1249
1250	if (cctx == NULL)
1251		fatal("%s: cctx == NULL", __func__);
1252	if ((c = channel_by_id(id)) == NULL)
1253		fatal("%s: no channel for id %d", __func__, id);
1254	if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1255		fatal("%s: channel %d lacks control channel %d", __func__,
1256		    id, c->ctl_chan);
1257
1258	if (!success) {
1259		debug3("%s: sending failure reply", __func__);
1260		/* prepare reply */
1261		buffer_init(&reply);
1262		buffer_put_int(&reply, MUX_S_FAILURE);
1263		buffer_put_int(&reply, cctx->rid);
1264		buffer_put_cstring(&reply, "Session open refused by peer");
1265		goto done;
1266	}
1267
1268	display = getenv("DISPLAY");
1269	if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1270		char *proto, *data;
1271
1272		/* Get reasonable local authentication information. */
1273		client_x11_get_proto(display, options.xauth_location,
1274		    options.forward_x11_trusted, options.forward_x11_timeout,
1275		    &proto, &data);
1276		/* Request forwarding with authentication spoofing. */
1277		debug("Requesting X11 forwarding with authentication "
1278		    "spoofing.");
1279		x11_request_forwarding_with_spoofing(id, display, proto,
1280		    data, 1);
1281		client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1282		/* XXX exit_on_forward_failure */
1283	}
1284
1285	if (cctx->want_agent_fwd && options.forward_agent) {
1286		debug("Requesting authentication agent forwarding.");
1287		channel_request_start(id, "auth-agent-req@openssh.com", 0);
1288		packet_send();
1289	}
1290
1291	client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1292	    cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1293
1294	debug3("%s: sending success reply", __func__);
1295	/* prepare reply */
1296	buffer_init(&reply);
1297	buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1298	buffer_put_int(&reply, cctx->rid);
1299	buffer_put_int(&reply, c->self);
1300
1301 done:
1302	/* Send reply */
1303	buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1304	buffer_free(&reply);
1305
1306	if (cc->mux_pause <= 0)
1307		fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1308	cc->mux_pause = 0; /* start processing messages again */
1309	c->open_confirm_ctx = NULL;
1310	buffer_free(&cctx->cmd);
1311	xfree(cctx->term);
1312	if (cctx->env != NULL) {
1313		for (i = 0; cctx->env[i] != NULL; i++)
1314			xfree(cctx->env[i]);
1315		xfree(cctx->env);
1316	}
1317	xfree(cctx);
1318}
1319
1320/* ** Multiplexing client support */
1321
1322/* Exit signal handler */
1323static void
1324control_client_sighandler(int signo)
1325{
1326	muxclient_terminate = signo;
1327}
1328
1329/*
1330 * Relay signal handler - used to pass some signals from mux client to
1331 * mux master.
1332 */
1333static void
1334control_client_sigrelay(int signo)
1335{
1336	int save_errno = errno;
1337
1338	if (muxserver_pid > 1)
1339		kill(muxserver_pid, signo);
1340
1341	errno = save_errno;
1342}
1343
1344static int
1345mux_client_read(int fd, Buffer *b, u_int need)
1346{
1347	u_int have;
1348	ssize_t len;
1349	u_char *p;
1350	struct pollfd pfd;
1351
1352	pfd.fd = fd;
1353	pfd.events = POLLIN;
1354	p = buffer_append_space(b, need);
1355	for (have = 0; have < need; ) {
1356		if (muxclient_terminate) {
1357			errno = EINTR;
1358			return -1;
1359		}
1360		len = read(fd, p + have, need - have);
1361		if (len < 0) {
1362			switch (errno) {
1363#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1364			case EWOULDBLOCK:
1365#endif
1366			case EAGAIN:
1367				(void)poll(&pfd, 1, -1);
1368				/* FALLTHROUGH */
1369			case EINTR:
1370				continue;
1371			default:
1372				return -1;
1373			}
1374		}
1375		if (len == 0) {
1376			errno = EPIPE;
1377			return -1;
1378		}
1379		have += (u_int)len;
1380	}
1381	return 0;
1382}
1383
1384static int
1385mux_client_write_packet(int fd, Buffer *m)
1386{
1387	Buffer queue;
1388	u_int have, need;
1389	int oerrno, len;
1390	u_char *ptr;
1391	struct pollfd pfd;
1392
1393	pfd.fd = fd;
1394	pfd.events = POLLOUT;
1395	buffer_init(&queue);
1396	buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1397
1398	need = buffer_len(&queue);
1399	ptr = buffer_ptr(&queue);
1400
1401	for (have = 0; have < need; ) {
1402		if (muxclient_terminate) {
1403			buffer_free(&queue);
1404			errno = EINTR;
1405			return -1;
1406		}
1407		len = write(fd, ptr + have, need - have);
1408		if (len < 0) {
1409			switch (errno) {
1410#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1411			case EWOULDBLOCK:
1412#endif
1413			case EAGAIN:
1414				(void)poll(&pfd, 1, -1);
1415				/* FALLTHROUGH */
1416			case EINTR:
1417				continue;
1418			default:
1419				oerrno = errno;
1420				buffer_free(&queue);
1421				errno = oerrno;
1422				return -1;
1423			}
1424		}
1425		if (len == 0) {
1426			buffer_free(&queue);
1427			errno = EPIPE;
1428			return -1;
1429		}
1430		have += (u_int)len;
1431	}
1432	buffer_free(&queue);
1433	return 0;
1434}
1435
1436static int
1437mux_client_read_packet(int fd, Buffer *m)
1438{
1439	Buffer queue;
1440	u_int need, have;
1441	void *ptr;
1442	int oerrno;
1443
1444	buffer_init(&queue);
1445	if (mux_client_read(fd, &queue, 4) != 0) {
1446		if ((oerrno = errno) == EPIPE)
1447		debug3("%s: read header failed: %s", __func__, strerror(errno));
1448		errno = oerrno;
1449		return -1;
1450	}
1451	need = get_u32(buffer_ptr(&queue));
1452	if (mux_client_read(fd, &queue, need) != 0) {
1453		oerrno = errno;
1454		debug3("%s: read body failed: %s", __func__, strerror(errno));
1455		errno = oerrno;
1456		return -1;
1457	}
1458	ptr = buffer_get_string_ptr(&queue, &have);
1459	buffer_append(m, ptr, have);
1460	buffer_free(&queue);
1461	return 0;
1462}
1463
1464static int
1465mux_client_hello_exchange(int fd)
1466{
1467	Buffer m;
1468	u_int type, ver;
1469
1470	buffer_init(&m);
1471	buffer_put_int(&m, MUX_MSG_HELLO);
1472	buffer_put_int(&m, SSHMUX_VER);
1473	/* no extensions */
1474
1475	if (mux_client_write_packet(fd, &m) != 0)
1476		fatal("%s: write packet: %s", __func__, strerror(errno));
1477
1478	buffer_clear(&m);
1479
1480	/* Read their HELLO */
1481	if (mux_client_read_packet(fd, &m) != 0) {
1482		buffer_free(&m);
1483		return -1;
1484	}
1485
1486	type = buffer_get_int(&m);
1487	if (type != MUX_MSG_HELLO)
1488		fatal("%s: expected HELLO (%u) received %u",
1489		    __func__, MUX_MSG_HELLO, type);
1490	ver = buffer_get_int(&m);
1491	if (ver != SSHMUX_VER)
1492		fatal("Unsupported multiplexing protocol version %d "
1493		    "(expected %d)", ver, SSHMUX_VER);
1494	debug2("%s: master version %u", __func__, ver);
1495	/* No extensions are presently defined */
1496	while (buffer_len(&m) > 0) {
1497		char *name = buffer_get_string(&m, NULL);
1498		char *value = buffer_get_string(&m, NULL);
1499
1500		debug2("Unrecognised master extension \"%s\"", name);
1501		xfree(name);
1502		xfree(value);
1503	}
1504	buffer_free(&m);
1505	return 0;
1506}
1507
1508static u_int
1509mux_client_request_alive(int fd)
1510{
1511	Buffer m;
1512	char *e;
1513	u_int pid, type, rid;
1514
1515	debug3("%s: entering", __func__);
1516
1517	buffer_init(&m);
1518	buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1519	buffer_put_int(&m, muxclient_request_id);
1520
1521	if (mux_client_write_packet(fd, &m) != 0)
1522		fatal("%s: write packet: %s", __func__, strerror(errno));
1523
1524	buffer_clear(&m);
1525
1526	/* Read their reply */
1527	if (mux_client_read_packet(fd, &m) != 0) {
1528		buffer_free(&m);
1529		return 0;
1530	}
1531
1532	type = buffer_get_int(&m);
1533	if (type != MUX_S_ALIVE) {
1534		e = buffer_get_string(&m, NULL);
1535		fatal("%s: master returned error: %s", __func__, e);
1536	}
1537
1538	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1539		fatal("%s: out of sequence reply: my id %u theirs %u",
1540		    __func__, muxclient_request_id, rid);
1541	pid = buffer_get_int(&m);
1542	buffer_free(&m);
1543
1544	debug3("%s: done pid = %u", __func__, pid);
1545
1546	muxclient_request_id++;
1547
1548	return pid;
1549}
1550
1551static void
1552mux_client_request_terminate(int fd)
1553{
1554	Buffer m;
1555	char *e;
1556	u_int type, rid;
1557
1558	debug3("%s: entering", __func__);
1559
1560	buffer_init(&m);
1561	buffer_put_int(&m, MUX_C_TERMINATE);
1562	buffer_put_int(&m, muxclient_request_id);
1563
1564	if (mux_client_write_packet(fd, &m) != 0)
1565		fatal("%s: write packet: %s", __func__, strerror(errno));
1566
1567	buffer_clear(&m);
1568
1569	/* Read their reply */
1570	if (mux_client_read_packet(fd, &m) != 0) {
1571		/* Remote end exited already */
1572		if (errno == EPIPE) {
1573			buffer_free(&m);
1574			return;
1575		}
1576		fatal("%s: read from master failed: %s",
1577		    __func__, strerror(errno));
1578	}
1579
1580	type = buffer_get_int(&m);
1581	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1582		fatal("%s: out of sequence reply: my id %u theirs %u",
1583		    __func__, muxclient_request_id, rid);
1584	switch (type) {
1585	case MUX_S_OK:
1586		break;
1587	case MUX_S_PERMISSION_DENIED:
1588		e = buffer_get_string(&m, NULL);
1589		fatal("Master refused termination request: %s", e);
1590	case MUX_S_FAILURE:
1591		e = buffer_get_string(&m, NULL);
1592		fatal("%s: termination request failed: %s", __func__, e);
1593	default:
1594		fatal("%s: unexpected response from master 0x%08x",
1595		    __func__, type);
1596	}
1597	buffer_free(&m);
1598	muxclient_request_id++;
1599}
1600
1601static int
1602mux_client_forward(int fd, int cancel_flag, u_int ftype, Forward *fwd)
1603{
1604	Buffer m;
1605	char *e, *fwd_desc;
1606	u_int type, rid;
1607
1608	fwd_desc = format_forward(ftype, fwd);
1609	debug("Requesting %s %s",
1610	    cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
1611	xfree(fwd_desc);
1612
1613	buffer_init(&m);
1614	buffer_put_int(&m, cancel_flag ? MUX_C_CLOSE_FWD : MUX_C_OPEN_FWD);
1615	buffer_put_int(&m, muxclient_request_id);
1616	buffer_put_int(&m, ftype);
1617	buffer_put_cstring(&m,
1618	    fwd->listen_host == NULL ? "" : fwd->listen_host);
1619	buffer_put_int(&m, fwd->listen_port);
1620	buffer_put_cstring(&m,
1621	    fwd->connect_host == NULL ? "" : fwd->connect_host);
1622	buffer_put_int(&m, fwd->connect_port);
1623
1624	if (mux_client_write_packet(fd, &m) != 0)
1625		fatal("%s: write packet: %s", __func__, strerror(errno));
1626
1627	buffer_clear(&m);
1628
1629	/* Read their reply */
1630	if (mux_client_read_packet(fd, &m) != 0) {
1631		buffer_free(&m);
1632		return -1;
1633	}
1634
1635	type = buffer_get_int(&m);
1636	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1637		fatal("%s: out of sequence reply: my id %u theirs %u",
1638		    __func__, muxclient_request_id, rid);
1639	switch (type) {
1640	case MUX_S_OK:
1641		break;
1642	case MUX_S_REMOTE_PORT:
1643		if (cancel_flag)
1644			fatal("%s: got MUX_S_REMOTE_PORT for cancel", __func__);
1645		fwd->allocated_port = buffer_get_int(&m);
1646		logit("Allocated port %u for remote forward to %s:%d",
1647		    fwd->allocated_port,
1648		    fwd->connect_host ? fwd->connect_host : "",
1649		    fwd->connect_port);
1650		if (muxclient_command == SSHMUX_COMMAND_FORWARD)
1651			fprintf(stdout, "%u\n", fwd->allocated_port);
1652		break;
1653	case MUX_S_PERMISSION_DENIED:
1654		e = buffer_get_string(&m, NULL);
1655		buffer_free(&m);
1656		error("Master refused forwarding request: %s", e);
1657		return -1;
1658	case MUX_S_FAILURE:
1659		e = buffer_get_string(&m, NULL);
1660		buffer_free(&m);
1661		error("%s: forwarding request failed: %s", __func__, e);
1662		return -1;
1663	default:
1664		fatal("%s: unexpected response from master 0x%08x",
1665		    __func__, type);
1666	}
1667	buffer_free(&m);
1668
1669	muxclient_request_id++;
1670	return 0;
1671}
1672
1673static int
1674mux_client_forwards(int fd, int cancel_flag)
1675{
1676	int i, ret = 0;
1677
1678	debug3("%s: %s forwardings: %d local, %d remote", __func__,
1679	    cancel_flag ? "cancel" : "request",
1680	    options.num_local_forwards, options.num_remote_forwards);
1681
1682	/* XXX ExitOnForwardingFailure */
1683	for (i = 0; i < options.num_local_forwards; i++) {
1684		if (mux_client_forward(fd, cancel_flag,
1685		    options.local_forwards[i].connect_port == 0 ?
1686		    MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1687		    options.local_forwards + i) != 0)
1688			ret = -1;
1689	}
1690	for (i = 0; i < options.num_remote_forwards; i++) {
1691		if (mux_client_forward(fd, cancel_flag, MUX_FWD_REMOTE,
1692		    options.remote_forwards + i) != 0)
1693			ret = -1;
1694	}
1695	return ret;
1696}
1697
1698static int
1699mux_client_request_session(int fd)
1700{
1701	Buffer m;
1702	char *e, *term;
1703	u_int i, rid, sid, esid, exitval, type, exitval_seen;
1704	extern char **environ;
1705	int devnull, rawmode;
1706
1707	debug3("%s: entering", __func__);
1708
1709	if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1710		error("%s: master alive request failed", __func__);
1711		return -1;
1712	}
1713
1714	signal(SIGPIPE, SIG_IGN);
1715
1716	if (stdin_null_flag) {
1717		if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1718			fatal("open(/dev/null): %s", strerror(errno));
1719		if (dup2(devnull, STDIN_FILENO) == -1)
1720			fatal("dup2: %s", strerror(errno));
1721		if (devnull > STDERR_FILENO)
1722			close(devnull);
1723	}
1724
1725	term = getenv("TERM");
1726
1727	buffer_init(&m);
1728	buffer_put_int(&m, MUX_C_NEW_SESSION);
1729	buffer_put_int(&m, muxclient_request_id);
1730	buffer_put_cstring(&m, ""); /* reserved */
1731	buffer_put_int(&m, tty_flag);
1732	buffer_put_int(&m, options.forward_x11);
1733	buffer_put_int(&m, options.forward_agent);
1734	buffer_put_int(&m, subsystem_flag);
1735	buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1736	    0xffffffff : (u_int)options.escape_char);
1737	buffer_put_cstring(&m, term == NULL ? "" : term);
1738	buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1739
1740	if (options.num_send_env > 0 && environ != NULL) {
1741		/* Pass environment */
1742		for (i = 0; environ[i] != NULL; i++) {
1743			if (env_permitted(environ[i])) {
1744				buffer_put_cstring(&m, environ[i]);
1745			}
1746		}
1747	}
1748
1749	if (mux_client_write_packet(fd, &m) != 0)
1750		fatal("%s: write packet: %s", __func__, strerror(errno));
1751
1752	/* Send the stdio file descriptors */
1753	if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1754	    mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1755	    mm_send_fd(fd, STDERR_FILENO) == -1)
1756		fatal("%s: send fds failed", __func__);
1757
1758	debug3("%s: session request sent", __func__);
1759
1760	/* Read their reply */
1761	buffer_clear(&m);
1762	if (mux_client_read_packet(fd, &m) != 0) {
1763		error("%s: read from master failed: %s",
1764		    __func__, strerror(errno));
1765		buffer_free(&m);
1766		return -1;
1767	}
1768
1769	type = buffer_get_int(&m);
1770	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1771		fatal("%s: out of sequence reply: my id %u theirs %u",
1772		    __func__, muxclient_request_id, rid);
1773	switch (type) {
1774	case MUX_S_SESSION_OPENED:
1775		sid = buffer_get_int(&m);
1776		debug("%s: master session id: %u", __func__, sid);
1777		break;
1778	case MUX_S_PERMISSION_DENIED:
1779		e = buffer_get_string(&m, NULL);
1780		buffer_free(&m);
1781		error("Master refused session request: %s", e);
1782		return -1;
1783	case MUX_S_FAILURE:
1784		e = buffer_get_string(&m, NULL);
1785		buffer_free(&m);
1786		error("%s: session request failed: %s", __func__, e);
1787		return -1;
1788	default:
1789		buffer_free(&m);
1790		error("%s: unexpected response from master 0x%08x",
1791		    __func__, type);
1792		return -1;
1793	}
1794	muxclient_request_id++;
1795
1796	signal(SIGHUP, control_client_sighandler);
1797	signal(SIGINT, control_client_sighandler);
1798	signal(SIGTERM, control_client_sighandler);
1799	signal(SIGWINCH, control_client_sigrelay);
1800
1801	rawmode = tty_flag;
1802	if (tty_flag)
1803		enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1804
1805	/*
1806	 * Stick around until the controlee closes the client_fd.
1807	 * Before it does, it is expected to write an exit message.
1808	 * This process must read the value and wait for the closure of
1809	 * the client_fd; if this one closes early, the multiplex master will
1810	 * terminate early too (possibly losing data).
1811	 */
1812	for (exitval = 255, exitval_seen = 0;;) {
1813		buffer_clear(&m);
1814		if (mux_client_read_packet(fd, &m) != 0)
1815			break;
1816		type = buffer_get_int(&m);
1817		switch (type) {
1818		case MUX_S_TTY_ALLOC_FAIL:
1819			if ((esid = buffer_get_int(&m)) != sid)
1820				fatal("%s: tty alloc fail on unknown session: "
1821				    "my id %u theirs %u",
1822				    __func__, sid, esid);
1823			leave_raw_mode(options.request_tty ==
1824			    REQUEST_TTY_FORCE);
1825			rawmode = 0;
1826			continue;
1827		case MUX_S_EXIT_MESSAGE:
1828			if ((esid = buffer_get_int(&m)) != sid)
1829				fatal("%s: exit on unknown session: "
1830				    "my id %u theirs %u",
1831				    __func__, sid, esid);
1832			if (exitval_seen)
1833				fatal("%s: exitval sent twice", __func__);
1834			exitval = buffer_get_int(&m);
1835			exitval_seen = 1;
1836			continue;
1837		default:
1838			e = buffer_get_string(&m, NULL);
1839			fatal("%s: master returned error: %s", __func__, e);
1840		}
1841	}
1842
1843	close(fd);
1844	if (rawmode)
1845		leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1846
1847	if (muxclient_terminate) {
1848		debug2("Exiting on signal %d", muxclient_terminate);
1849		exitval = 255;
1850	} else if (!exitval_seen) {
1851		debug2("Control master terminated unexpectedly");
1852		exitval = 255;
1853	} else
1854		debug2("Received exit status from master %d", exitval);
1855
1856	if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1857		fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1858
1859	exit(exitval);
1860}
1861
1862static int
1863mux_client_request_stdio_fwd(int fd)
1864{
1865	Buffer m;
1866	char *e;
1867	u_int type, rid, sid;
1868	int devnull;
1869
1870	debug3("%s: entering", __func__);
1871
1872	if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1873		error("%s: master alive request failed", __func__);
1874		return -1;
1875	}
1876
1877	signal(SIGPIPE, SIG_IGN);
1878
1879	if (stdin_null_flag) {
1880		if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1881			fatal("open(/dev/null): %s", strerror(errno));
1882		if (dup2(devnull, STDIN_FILENO) == -1)
1883			fatal("dup2: %s", strerror(errno));
1884		if (devnull > STDERR_FILENO)
1885			close(devnull);
1886	}
1887
1888	buffer_init(&m);
1889	buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
1890	buffer_put_int(&m, muxclient_request_id);
1891	buffer_put_cstring(&m, ""); /* reserved */
1892	buffer_put_cstring(&m, stdio_forward_host);
1893	buffer_put_int(&m, stdio_forward_port);
1894
1895	if (mux_client_write_packet(fd, &m) != 0)
1896		fatal("%s: write packet: %s", __func__, strerror(errno));
1897
1898	/* Send the stdio file descriptors */
1899	if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1900	    mm_send_fd(fd, STDOUT_FILENO) == -1)
1901		fatal("%s: send fds failed", __func__);
1902
1903	debug3("%s: stdio forward request sent", __func__);
1904
1905	/* Read their reply */
1906	buffer_clear(&m);
1907
1908	if (mux_client_read_packet(fd, &m) != 0) {
1909		error("%s: read from master failed: %s",
1910		    __func__, strerror(errno));
1911		buffer_free(&m);
1912		return -1;
1913	}
1914
1915	type = buffer_get_int(&m);
1916	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1917		fatal("%s: out of sequence reply: my id %u theirs %u",
1918		    __func__, muxclient_request_id, rid);
1919	switch (type) {
1920	case MUX_S_SESSION_OPENED:
1921		sid = buffer_get_int(&m);
1922		debug("%s: master session id: %u", __func__, sid);
1923		break;
1924	case MUX_S_PERMISSION_DENIED:
1925		e = buffer_get_string(&m, NULL);
1926		buffer_free(&m);
1927		fatal("Master refused stdio forwarding request: %s", e);
1928	case MUX_S_FAILURE:
1929		e = buffer_get_string(&m, NULL);
1930		buffer_free(&m);
1931		fatal("%s: stdio forwarding request failed: %s", __func__, e);
1932	default:
1933		buffer_free(&m);
1934		error("%s: unexpected response from master 0x%08x",
1935		    __func__, type);
1936		return -1;
1937	}
1938	muxclient_request_id++;
1939
1940	signal(SIGHUP, control_client_sighandler);
1941	signal(SIGINT, control_client_sighandler);
1942	signal(SIGTERM, control_client_sighandler);
1943	signal(SIGWINCH, control_client_sigrelay);
1944
1945	/*
1946	 * Stick around until the controlee closes the client_fd.
1947	 */
1948	buffer_clear(&m);
1949	if (mux_client_read_packet(fd, &m) != 0) {
1950		if (errno == EPIPE ||
1951		    (errno == EINTR && muxclient_terminate != 0))
1952			return 0;
1953		fatal("%s: mux_client_read_packet: %s",
1954		    __func__, strerror(errno));
1955	}
1956	fatal("%s: master returned unexpected message %u", __func__, type);
1957}
1958
1959static void
1960mux_client_request_stop_listening(int fd)
1961{
1962	Buffer m;
1963	char *e;
1964	u_int type, rid;
1965
1966	debug3("%s: entering", __func__);
1967
1968	buffer_init(&m);
1969	buffer_put_int(&m, MUX_C_STOP_LISTENING);
1970	buffer_put_int(&m, muxclient_request_id);
1971
1972	if (mux_client_write_packet(fd, &m) != 0)
1973		fatal("%s: write packet: %s", __func__, strerror(errno));
1974
1975	buffer_clear(&m);
1976
1977	/* Read their reply */
1978	if (mux_client_read_packet(fd, &m) != 0)
1979		fatal("%s: read from master failed: %s",
1980		    __func__, strerror(errno));
1981
1982	type = buffer_get_int(&m);
1983	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1984		fatal("%s: out of sequence reply: my id %u theirs %u",
1985		    __func__, muxclient_request_id, rid);
1986	switch (type) {
1987	case MUX_S_OK:
1988		break;
1989	case MUX_S_PERMISSION_DENIED:
1990		e = buffer_get_string(&m, NULL);
1991		fatal("Master refused stop listening request: %s", e);
1992	case MUX_S_FAILURE:
1993		e = buffer_get_string(&m, NULL);
1994		fatal("%s: stop listening request failed: %s", __func__, e);
1995	default:
1996		fatal("%s: unexpected response from master 0x%08x",
1997		    __func__, type);
1998	}
1999	buffer_free(&m);
2000	muxclient_request_id++;
2001}
2002
2003/* Multiplex client main loop. */
2004void
2005muxclient(const char *path)
2006{
2007	struct sockaddr_un addr;
2008	socklen_t sun_len;
2009	int sock;
2010	u_int pid;
2011
2012	if (muxclient_command == 0) {
2013		if (stdio_forward_host != NULL)
2014			muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
2015		else
2016			muxclient_command = SSHMUX_COMMAND_OPEN;
2017	}
2018
2019	switch (options.control_master) {
2020	case SSHCTL_MASTER_AUTO:
2021	case SSHCTL_MASTER_AUTO_ASK:
2022		debug("auto-mux: Trying existing master");
2023		/* FALLTHROUGH */
2024	case SSHCTL_MASTER_NO:
2025		break;
2026	default:
2027		return;
2028	}
2029
2030	memset(&addr, '\0', sizeof(addr));
2031	addr.sun_family = AF_UNIX;
2032	sun_len = offsetof(struct sockaddr_un, sun_path) +
2033	    strlen(path) + 1;
2034
2035	if (strlcpy(addr.sun_path, path,
2036	    sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
2037		fatal("ControlPath too long");
2038
2039	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
2040		fatal("%s socket(): %s", __func__, strerror(errno));
2041
2042	if (connect(sock, (struct sockaddr *)&addr, sun_len) == -1) {
2043		switch (muxclient_command) {
2044		case SSHMUX_COMMAND_OPEN:
2045		case SSHMUX_COMMAND_STDIO_FWD:
2046			break;
2047		default:
2048			fatal("Control socket connect(%.100s): %s", path,
2049			    strerror(errno));
2050		}
2051		if (errno == ECONNREFUSED &&
2052		    options.control_master != SSHCTL_MASTER_NO) {
2053			debug("Stale control socket %.100s, unlinking", path);
2054			unlink(path);
2055		} else if (errno == ENOENT) {
2056			debug("Control socket \"%.100s\" does not exist", path);
2057		} else {
2058			error("Control socket connect(%.100s): %s", path,
2059			    strerror(errno));
2060		}
2061		close(sock);
2062		return;
2063	}
2064	set_nonblock(sock);
2065
2066	if (mux_client_hello_exchange(sock) != 0) {
2067		error("%s: master hello exchange failed", __func__);
2068		close(sock);
2069		return;
2070	}
2071
2072	switch (muxclient_command) {
2073	case SSHMUX_COMMAND_ALIVE_CHECK:
2074		if ((pid = mux_client_request_alive(sock)) == 0)
2075			fatal("%s: master alive check failed", __func__);
2076		fprintf(stderr, "Master running (pid=%d)\r\n", pid);
2077		exit(0);
2078	case SSHMUX_COMMAND_TERMINATE:
2079		mux_client_request_terminate(sock);
2080		fprintf(stderr, "Exit request sent.\r\n");
2081		exit(0);
2082	case SSHMUX_COMMAND_FORWARD:
2083		if (mux_client_forwards(sock, 0) != 0)
2084			fatal("%s: master forward request failed", __func__);
2085		exit(0);
2086	case SSHMUX_COMMAND_OPEN:
2087		if (mux_client_forwards(sock, 0) != 0) {
2088			error("%s: master forward request failed", __func__);
2089			return;
2090		}
2091		mux_client_request_session(sock);
2092		return;
2093	case SSHMUX_COMMAND_STDIO_FWD:
2094		mux_client_request_stdio_fwd(sock);
2095		exit(0);
2096	case SSHMUX_COMMAND_STOP:
2097		mux_client_request_stop_listening(sock);
2098		fprintf(stderr, "Stop listening request sent.\r\n");
2099		exit(0);
2100	case SSHMUX_COMMAND_CANCEL_FWD:
2101		if (mux_client_forwards(sock, 1) != 0)
2102			error("%s: master cancel forward request failed",
2103			    __func__);
2104		exit(0);
2105	default:
2106		fatal("unrecognised muxclient_command %d", muxclient_command);
2107	}
2108}
2109