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