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