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