mux.c revision 263691
1/* $OpenBSD: mux.c,v 1.44 2013/07/12 00:19:58 djm Exp $ */
2/* $FreeBSD: head/crypto/openssh/mux.c 263691 2014-03-24 19:15:13Z des $ */
3/*
4 * Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19/* ssh session multiplexing support */
20
21/*
22 * TODO:
23 *   - Better signalling from master to slave, especially passing of
24 *      error messages
25 *   - Better fall-back from mux slave error to new connection.
26 *   - ExitOnForwardingFailure
27 *   - Maybe extension mechanisms for multi-X11/multi-agent forwarding
28 *   - Support ~^Z in mux slaves.
29 *   - Inspect or control sessions in master.
30 *   - If we ever support the "signal" channel request, send signals on
31 *     sessions in master.
32 */
33
34#include "includes.h"
35__RCSID("$FreeBSD: head/crypto/openssh/mux.c 263691 2014-03-24 19:15:13Z des $");
36
37#include <sys/types.h>
38#include <sys/param.h>
39#include <sys/stat.h>
40#include <sys/socket.h>
41#include <sys/un.h>
42
43#include <errno.h>
44#include <fcntl.h>
45#include <signal.h>
46#include <stdarg.h>
47#include <stddef.h>
48#include <stdlib.h>
49#include <stdio.h>
50#include <string.h>
51#include <unistd.h>
52#ifdef HAVE_PATHS_H
53#include <paths.h>
54#endif
55
56#ifdef HAVE_POLL_H
57#include <poll.h>
58#else
59# ifdef HAVE_SYS_POLL_H
60#  include <sys/poll.h>
61# endif
62#endif
63
64#ifdef HAVE_UTIL_H
65# include <util.h>
66#endif
67
68#include "openbsd-compat/sys-queue.h"
69#include "xmalloc.h"
70#include "log.h"
71#include "ssh.h"
72#include "ssh2.h"
73#include "pathnames.h"
74#include "misc.h"
75#include "match.h"
76#include "buffer.h"
77#include "channels.h"
78#include "msg.h"
79#include "packet.h"
80#include "monitor_fdpass.h"
81#include "sshpty.h"
82#include "key.h"
83#include "readconf.h"
84#include "clientloop.h"
85
86/* from ssh.c */
87extern int tty_flag;
88extern Options options;
89extern int stdin_null_flag;
90extern char *host;
91extern int subsystem_flag;
92extern Buffer command;
93extern volatile sig_atomic_t quit_pending;
94extern char *stdio_forward_host;
95extern int stdio_forward_port;
96
97/* Context for session open confirmation callback */
98struct mux_session_confirm_ctx {
99	u_int want_tty;
100	u_int want_subsys;
101	u_int want_x_fwd;
102	u_int want_agent_fwd;
103	Buffer cmd;
104	char *term;
105	struct termios tio;
106	char **env;
107	u_int rid;
108};
109
110/* Context for global channel callback */
111struct mux_channel_confirm_ctx {
112	u_int cid;	/* channel id */
113	u_int rid;	/* request id */
114	int fid;	/* forward id */
115};
116
117/* fd to control socket */
118int muxserver_sock = -1;
119
120/* client request id */
121u_int muxclient_request_id = 0;
122
123/* Multiplexing control command */
124u_int muxclient_command = 0;
125
126/* Set when signalled. */
127static volatile sig_atomic_t muxclient_terminate = 0;
128
129/* PID of multiplex server */
130static u_int muxserver_pid = 0;
131
132static Channel *mux_listener_channel = NULL;
133
134struct mux_master_state {
135	int hello_rcvd;
136};
137
138/* mux protocol messages */
139#define MUX_MSG_HELLO		0x00000001
140#define MUX_C_NEW_SESSION	0x10000002
141#define MUX_C_ALIVE_CHECK	0x10000004
142#define MUX_C_TERMINATE		0x10000005
143#define MUX_C_OPEN_FWD		0x10000006
144#define MUX_C_CLOSE_FWD		0x10000007
145#define MUX_C_NEW_STDIO_FWD	0x10000008
146#define MUX_C_STOP_LISTENING	0x10000009
147#define MUX_S_OK		0x80000001
148#define MUX_S_PERMISSION_DENIED	0x80000002
149#define MUX_S_FAILURE		0x80000003
150#define MUX_S_EXIT_MESSAGE	0x80000004
151#define MUX_S_ALIVE		0x80000005
152#define MUX_S_SESSION_OPENED	0x80000006
153#define MUX_S_REMOTE_PORT	0x80000007
154#define MUX_S_TTY_ALLOC_FAIL	0x80000008
155
156/* type codes for MUX_C_OPEN_FWD and MUX_C_CLOSE_FWD */
157#define MUX_FWD_LOCAL   1
158#define MUX_FWD_REMOTE  2
159#define MUX_FWD_DYNAMIC 3
160
161static void mux_session_confirm(int, int, void *);
162
163static int process_mux_master_hello(u_int, Channel *, Buffer *, Buffer *);
164static int process_mux_new_session(u_int, Channel *, Buffer *, Buffer *);
165static int process_mux_alive_check(u_int, Channel *, Buffer *, Buffer *);
166static int process_mux_terminate(u_int, Channel *, Buffer *, Buffer *);
167static int process_mux_open_fwd(u_int, Channel *, Buffer *, Buffer *);
168static int process_mux_close_fwd(u_int, Channel *, Buffer *, Buffer *);
169static int process_mux_stdio_fwd(u_int, Channel *, Buffer *, Buffer *);
170static int process_mux_stop_listening(u_int, Channel *, Buffer *, Buffer *);
171
172static const struct {
173	u_int type;
174	int (*handler)(u_int, Channel *, Buffer *, Buffer *);
175} mux_master_handlers[] = {
176	{ MUX_MSG_HELLO, process_mux_master_hello },
177	{ MUX_C_NEW_SESSION, process_mux_new_session },
178	{ MUX_C_ALIVE_CHECK, process_mux_alive_check },
179	{ MUX_C_TERMINATE, process_mux_terminate },
180	{ MUX_C_OPEN_FWD, process_mux_open_fwd },
181	{ MUX_C_CLOSE_FWD, process_mux_close_fwd },
182	{ MUX_C_NEW_STDIO_FWD, process_mux_stdio_fwd },
183	{ MUX_C_STOP_LISTENING, process_mux_stop_listening },
184	{ 0, NULL }
185};
186
187/* Cleanup callback fired on closure of mux slave _session_ channel */
188/* ARGSUSED */
189static void
190mux_master_session_cleanup_cb(int cid, void *unused)
191{
192	Channel *cc, *c = channel_by_id(cid);
193
194	debug3("%s: entering for channel %d", __func__, cid);
195	if (c == NULL)
196		fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
197	if (c->ctl_chan != -1) {
198		if ((cc = channel_by_id(c->ctl_chan)) == NULL)
199			fatal("%s: channel %d missing control channel %d",
200			    __func__, c->self, c->ctl_chan);
201		c->ctl_chan = -1;
202		cc->remote_id = -1;
203		chan_rcvd_oclose(cc);
204	}
205	channel_cancel_cleanup(c->self);
206}
207
208/* Cleanup callback fired on closure of mux slave _control_ channel */
209/* ARGSUSED */
210static void
211mux_master_control_cleanup_cb(int cid, void *unused)
212{
213	Channel *sc, *c = channel_by_id(cid);
214
215	debug3("%s: entering for channel %d", __func__, cid);
216	if (c == NULL)
217		fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
218	if (c->remote_id != -1) {
219		if ((sc = channel_by_id(c->remote_id)) == NULL)
220			fatal("%s: channel %d missing session channel %d",
221			    __func__, c->self, c->remote_id);
222		c->remote_id = -1;
223		sc->ctl_chan = -1;
224		if (sc->type != SSH_CHANNEL_OPEN &&
225		    sc->type != SSH_CHANNEL_OPENING) {
226			debug2("%s: channel %d: not open", __func__, sc->self);
227			chan_mark_dead(sc);
228		} else {
229			if (sc->istate == CHAN_INPUT_OPEN)
230				chan_read_failed(sc);
231			if (sc->ostate == CHAN_OUTPUT_OPEN)
232				chan_write_failed(sc);
233		}
234	}
235	channel_cancel_cleanup(c->self);
236}
237
238/* Check mux client environment variables before passing them to mux master. */
239static int
240env_permitted(char *env)
241{
242	int i, ret;
243	char name[1024], *cp;
244
245	if ((cp = strchr(env, '=')) == NULL || cp == env)
246		return 0;
247	ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
248	if (ret <= 0 || (size_t)ret >= sizeof(name)) {
249		error("env_permitted: name '%.100s...' too long", env);
250		return 0;
251	}
252
253	for (i = 0; i < options.num_send_env; i++)
254		if (match_pattern(name, options.send_env[i]))
255			return 1;
256
257	return 0;
258}
259
260/* Mux master protocol message handlers */
261
262static int
263process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
264{
265	u_int ver;
266	struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
267
268	if (state == NULL)
269		fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
270	if (state->hello_rcvd) {
271		error("%s: HELLO received twice", __func__);
272		return -1;
273	}
274	if (buffer_get_int_ret(&ver, m) != 0) {
275 malf:
276		error("%s: malformed message", __func__);
277		return -1;
278	}
279	if (ver != SSHMUX_VER) {
280		error("Unsupported multiplexing protocol version %d "
281		    "(expected %d)", ver, SSHMUX_VER);
282		return -1;
283	}
284	debug2("%s: channel %d slave version %u", __func__, c->self, ver);
285
286	/* No extensions are presently defined */
287	while (buffer_len(m) > 0) {
288		char *name = buffer_get_string_ret(m, NULL);
289		char *value = buffer_get_string_ret(m, NULL);
290
291		if (name == NULL || value == NULL) {
292			free(name);
293			free(value);
294			goto malf;
295		}
296		debug2("Unrecognised slave extension \"%s\"", name);
297		free(name);
298		free(value);
299	}
300	state->hello_rcvd = 1;
301	return 0;
302}
303
304static int
305process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
306{
307	Channel *nc;
308	struct mux_session_confirm_ctx *cctx;
309	char *reserved, *cmd, *cp;
310	u_int i, j, len, env_len, escape_char, window, packetmax;
311	int new_fd[3];
312
313	/* Reply for SSHMUX_COMMAND_OPEN */
314	cctx = xcalloc(1, sizeof(*cctx));
315	cctx->term = NULL;
316	cctx->rid = rid;
317	cmd = reserved = NULL;
318	cctx->env = NULL;
319	env_len = 0;
320	if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
321	    buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
322	    buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
323	    buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
324	    buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
325	    buffer_get_int_ret(&escape_char, m) != 0 ||
326	    (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
327	    (cmd = buffer_get_string_ret(m, &len)) == NULL) {
328 malf:
329		free(cmd);
330		free(reserved);
331		for (j = 0; j < env_len; j++)
332			free(cctx->env[j]);
333		free(cctx->env);
334		free(cctx->term);
335		free(cctx);
336		error("%s: malformed message", __func__);
337		return -1;
338	}
339	free(reserved);
340	reserved = NULL;
341
342	while (buffer_len(m) > 0) {
343#define MUX_MAX_ENV_VARS	4096
344		if ((cp = buffer_get_string_ret(m, &len)) == NULL)
345			goto malf;
346		if (!env_permitted(cp)) {
347			free(cp);
348			continue;
349		}
350		cctx->env = xrealloc(cctx->env, env_len + 2,
351		    sizeof(*cctx->env));
352		cctx->env[env_len++] = cp;
353		cctx->env[env_len] = NULL;
354		if (env_len > MUX_MAX_ENV_VARS) {
355			error(">%d environment variables received, ignoring "
356			    "additional", MUX_MAX_ENV_VARS);
357			break;
358		}
359	}
360
361	debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
362	    "term \"%s\", cmd \"%s\", env %u", __func__, c->self,
363	    cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
364	    cctx->want_subsys, cctx->term, cmd, env_len);
365
366	buffer_init(&cctx->cmd);
367	buffer_append(&cctx->cmd, cmd, strlen(cmd));
368	free(cmd);
369	cmd = NULL;
370
371	/* Gather fds from client */
372	for(i = 0; i < 3; i++) {
373		if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
374			error("%s: failed to receive fd %d from slave",
375			    __func__, i);
376			for (j = 0; j < i; j++)
377				close(new_fd[j]);
378			for (j = 0; j < env_len; j++)
379				free(cctx->env[j]);
380			free(cctx->env);
381			free(cctx->term);
382			buffer_free(&cctx->cmd);
383			free(cctx);
384
385			/* prepare reply */
386			buffer_put_int(r, MUX_S_FAILURE);
387			buffer_put_int(r, rid);
388			buffer_put_cstring(r,
389			    "did not receive file descriptors");
390			return -1;
391		}
392	}
393
394	debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
395	    new_fd[0], new_fd[1], new_fd[2]);
396
397	/* XXX support multiple child sessions in future */
398	if (c->remote_id != -1) {
399		debug2("%s: session already open", __func__);
400		/* prepare reply */
401		buffer_put_int(r, MUX_S_FAILURE);
402		buffer_put_int(r, rid);
403		buffer_put_cstring(r, "Multiple sessions not supported");
404 cleanup:
405		close(new_fd[0]);
406		close(new_fd[1]);
407		close(new_fd[2]);
408		free(cctx->term);
409		if (env_len != 0) {
410			for (i = 0; i < env_len; i++)
411				free(cctx->env[i]);
412			free(cctx->env);
413		}
414		buffer_free(&cctx->cmd);
415		free(cctx);
416		return 0;
417	}
418
419	if (options.control_master == SSHCTL_MASTER_ASK ||
420	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
421		if (!ask_permission("Allow shared connection to %s? ", host)) {
422			debug2("%s: session refused by user", __func__);
423			/* prepare reply */
424			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
425			buffer_put_int(r, rid);
426			buffer_put_cstring(r, "Permission denied");
427			goto cleanup;
428		}
429	}
430
431	/* Try to pick up ttymodes from client before it goes raw */
432	if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
433		error("%s: tcgetattr: %s", __func__, strerror(errno));
434
435	/* enable nonblocking unless tty */
436	if (!isatty(new_fd[0]))
437		set_nonblock(new_fd[0]);
438	if (!isatty(new_fd[1]))
439		set_nonblock(new_fd[1]);
440	if (!isatty(new_fd[2]))
441		set_nonblock(new_fd[2]);
442
443	window = CHAN_SES_WINDOW_DEFAULT;
444	packetmax = CHAN_SES_PACKET_DEFAULT;
445	if (cctx->want_tty) {
446		window >>= 1;
447		packetmax >>= 1;
448	}
449
450	nc = channel_new("session", SSH_CHANNEL_OPENING,
451	    new_fd[0], new_fd[1], new_fd[2], window, packetmax,
452	    CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
453
454	nc->ctl_chan = c->self;		/* link session -> control channel */
455	c->remote_id = nc->self; 	/* link control -> session channel */
456
457	if (cctx->want_tty && escape_char != 0xffffffff) {
458		channel_register_filter(nc->self,
459		    client_simple_escape_filter, NULL,
460		    client_filter_cleanup,
461		    client_new_escape_filter_ctx((int)escape_char));
462	}
463
464	debug2("%s: channel_new: %d linked to control channel %d",
465	    __func__, nc->self, nc->ctl_chan);
466
467	channel_send_open(nc->self);
468	channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
469	c->mux_pause = 1; /* stop handling messages until open_confirm done */
470	channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
471
472	/* reply is deferred, sent by mux_session_confirm */
473	return 0;
474}
475
476static int
477process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
478{
479	debug2("%s: channel %d: alive check", __func__, c->self);
480
481	/* prepare reply */
482	buffer_put_int(r, MUX_S_ALIVE);
483	buffer_put_int(r, rid);
484	buffer_put_int(r, (u_int)getpid());
485
486	return 0;
487}
488
489static int
490process_mux_terminate(u_int rid, Channel *c, Buffer *m, Buffer *r)
491{
492	debug2("%s: channel %d: terminate request", __func__, c->self);
493
494	if (options.control_master == SSHCTL_MASTER_ASK ||
495	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
496		if (!ask_permission("Terminate shared connection to %s? ",
497		    host)) {
498			debug2("%s: termination refused by user", __func__);
499			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
500			buffer_put_int(r, rid);
501			buffer_put_cstring(r, "Permission denied");
502			return 0;
503		}
504	}
505
506	quit_pending = 1;
507	buffer_put_int(r, MUX_S_OK);
508	buffer_put_int(r, rid);
509	/* XXX exit happens too soon - message never makes it to client */
510	return 0;
511}
512
513static char *
514format_forward(u_int ftype, Forward *fwd)
515{
516	char *ret;
517
518	switch (ftype) {
519	case MUX_FWD_LOCAL:
520		xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
521		    (fwd->listen_host == NULL) ?
522		    (options.gateway_ports ? "*" : "LOCALHOST") :
523		    fwd->listen_host, fwd->listen_port,
524		    fwd->connect_host, fwd->connect_port);
525		break;
526	case MUX_FWD_DYNAMIC:
527		xasprintf(&ret, "dynamic forward %.200s:%d -> *",
528		    (fwd->listen_host == NULL) ?
529		    (options.gateway_ports ? "*" : "LOCALHOST") :
530		     fwd->listen_host, fwd->listen_port);
531		break;
532	case MUX_FWD_REMOTE:
533		xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
534		    (fwd->listen_host == NULL) ?
535		    "LOCALHOST" : fwd->listen_host,
536		    fwd->listen_port,
537		    fwd->connect_host, fwd->connect_port);
538		break;
539	default:
540		fatal("%s: unknown forward type %u", __func__, ftype);
541	}
542	return ret;
543}
544
545static int
546compare_host(const char *a, const char *b)
547{
548	if (a == NULL && b == NULL)
549		return 1;
550	if (a == NULL || b == NULL)
551		return 0;
552	return strcmp(a, b) == 0;
553}
554
555static int
556compare_forward(Forward *a, Forward *b)
557{
558	if (!compare_host(a->listen_host, b->listen_host))
559		return 0;
560	if (a->listen_port != b->listen_port)
561		return 0;
562	if (!compare_host(a->connect_host, b->connect_host))
563		return 0;
564	if (a->connect_port != b->connect_port)
565		return 0;
566
567	return 1;
568}
569
570static void
571mux_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
572{
573	struct mux_channel_confirm_ctx *fctx = ctxt;
574	char *failmsg = NULL;
575	Forward *rfwd;
576	Channel *c;
577	Buffer out;
578
579	if ((c = channel_by_id(fctx->cid)) == NULL) {
580		/* no channel for reply */
581		error("%s: unknown channel", __func__);
582		return;
583	}
584	buffer_init(&out);
585	if (fctx->fid >= options.num_remote_forwards) {
586		xasprintf(&failmsg, "unknown forwarding id %d", fctx->fid);
587		goto fail;
588	}
589	rfwd = &options.remote_forwards[fctx->fid];
590	debug("%s: %s for: listen %d, connect %s:%d", __func__,
591	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
592	    rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
593	if (type == SSH2_MSG_REQUEST_SUCCESS) {
594		if (rfwd->listen_port == 0) {
595			rfwd->allocated_port = packet_get_int();
596			logit("Allocated port %u for mux remote forward"
597			    " to %s:%d", rfwd->allocated_port,
598			    rfwd->connect_host, rfwd->connect_port);
599			buffer_put_int(&out, MUX_S_REMOTE_PORT);
600			buffer_put_int(&out, fctx->rid);
601			buffer_put_int(&out, rfwd->allocated_port);
602			channel_update_permitted_opens(rfwd->handle,
603			   rfwd->allocated_port);
604		} else {
605			buffer_put_int(&out, MUX_S_OK);
606			buffer_put_int(&out, fctx->rid);
607		}
608		goto out;
609	} else {
610		if (rfwd->listen_port == 0)
611			channel_update_permitted_opens(rfwd->handle, -1);
612		xasprintf(&failmsg, "remote port forwarding failed for "
613		    "listen port %d", rfwd->listen_port);
614	}
615 fail:
616	error("%s: %s", __func__, failmsg);
617	buffer_put_int(&out, MUX_S_FAILURE);
618	buffer_put_int(&out, fctx->rid);
619	buffer_put_cstring(&out, failmsg);
620	free(failmsg);
621 out:
622	buffer_put_string(&c->output, buffer_ptr(&out), buffer_len(&out));
623	buffer_free(&out);
624	if (c->mux_pause <= 0)
625		fatal("%s: mux_pause %d", __func__, c->mux_pause);
626	c->mux_pause = 0; /* start processing messages again */
627}
628
629static int
630process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
631{
632	Forward fwd;
633	char *fwd_desc = NULL;
634	u_int ftype;
635	u_int lport, cport;
636	int i, ret = 0, freefwd = 1;
637
638	fwd.listen_host = fwd.connect_host = NULL;
639	if (buffer_get_int_ret(&ftype, m) != 0 ||
640	    (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
641	    buffer_get_int_ret(&lport, m) != 0 ||
642	    (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
643	    buffer_get_int_ret(&cport, m) != 0 ||
644	    lport > 65535 || cport > 65535) {
645		error("%s: malformed message", __func__);
646		ret = -1;
647		goto out;
648	}
649	fwd.listen_port = lport;
650	fwd.connect_port = cport;
651	if (*fwd.listen_host == '\0') {
652		free(fwd.listen_host);
653		fwd.listen_host = NULL;
654	}
655	if (*fwd.connect_host == '\0') {
656		free(fwd.connect_host);
657		fwd.connect_host = NULL;
658	}
659
660	debug2("%s: channel %d: request %s", __func__, c->self,
661	    (fwd_desc = format_forward(ftype, &fwd)));
662
663	if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
664	    ftype != MUX_FWD_DYNAMIC) {
665		logit("%s: invalid forwarding type %u", __func__, ftype);
666 invalid:
667		free(fwd.listen_host);
668		free(fwd.connect_host);
669		buffer_put_int(r, MUX_S_FAILURE);
670		buffer_put_int(r, rid);
671		buffer_put_cstring(r, "Invalid forwarding request");
672		return 0;
673	}
674	if (fwd.listen_port >= 65536) {
675		logit("%s: invalid listen port %u", __func__,
676		    fwd.listen_port);
677		goto invalid;
678	}
679	if (fwd.connect_port >= 65536 || (ftype != MUX_FWD_DYNAMIC &&
680	    ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
681		logit("%s: invalid connect port %u", __func__,
682		    fwd.connect_port);
683		goto invalid;
684	}
685	if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL) {
686		logit("%s: missing connect host", __func__);
687		goto invalid;
688	}
689
690	/* Skip forwards that have already been requested */
691	switch (ftype) {
692	case MUX_FWD_LOCAL:
693	case MUX_FWD_DYNAMIC:
694		for (i = 0; i < options.num_local_forwards; i++) {
695			if (compare_forward(&fwd,
696			    options.local_forwards + i)) {
697 exists:
698				debug2("%s: found existing forwarding",
699				    __func__);
700				buffer_put_int(r, MUX_S_OK);
701				buffer_put_int(r, rid);
702				goto out;
703			}
704		}
705		break;
706	case MUX_FWD_REMOTE:
707		for (i = 0; i < options.num_remote_forwards; i++) {
708			if (compare_forward(&fwd,
709			    options.remote_forwards + i)) {
710				if (fwd.listen_port != 0)
711					goto exists;
712				debug2("%s: found allocated port",
713				    __func__);
714				buffer_put_int(r, MUX_S_REMOTE_PORT);
715				buffer_put_int(r, rid);
716				buffer_put_int(r,
717				    options.remote_forwards[i].allocated_port);
718				goto out;
719			}
720		}
721		break;
722	}
723
724	if (options.control_master == SSHCTL_MASTER_ASK ||
725	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
726		if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
727			debug2("%s: forwarding refused by user", __func__);
728			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
729			buffer_put_int(r, rid);
730			buffer_put_cstring(r, "Permission denied");
731			goto out;
732		}
733	}
734
735	if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
736		if (!channel_setup_local_fwd_listener(fwd.listen_host,
737		    fwd.listen_port, fwd.connect_host, fwd.connect_port,
738		    options.gateway_ports)) {
739 fail:
740			logit("slave-requested %s failed", fwd_desc);
741			buffer_put_int(r, MUX_S_FAILURE);
742			buffer_put_int(r, rid);
743			buffer_put_cstring(r, "Port forwarding failed");
744			goto out;
745		}
746		add_local_forward(&options, &fwd);
747		freefwd = 0;
748	} else {
749		struct mux_channel_confirm_ctx *fctx;
750
751		fwd.handle = channel_request_remote_forwarding(fwd.listen_host,
752		    fwd.listen_port, fwd.connect_host, fwd.connect_port);
753		if (fwd.handle < 0)
754			goto fail;
755		add_remote_forward(&options, &fwd);
756		fctx = xcalloc(1, sizeof(*fctx));
757		fctx->cid = c->self;
758		fctx->rid = rid;
759		fctx->fid = options.num_remote_forwards - 1;
760		client_register_global_confirm(mux_confirm_remote_forward,
761		    fctx);
762		freefwd = 0;
763		c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
764		/* delayed reply in mux_confirm_remote_forward */
765		goto out;
766	}
767	buffer_put_int(r, MUX_S_OK);
768	buffer_put_int(r, rid);
769 out:
770	free(fwd_desc);
771	if (freefwd) {
772		free(fwd.listen_host);
773		free(fwd.connect_host);
774	}
775	return ret;
776}
777
778static int
779process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
780{
781	Forward fwd, *found_fwd;
782	char *fwd_desc = NULL;
783	const char *error_reason = NULL;
784	u_int ftype;
785	int i, listen_port, ret = 0;
786	u_int lport, cport;
787
788	fwd.listen_host = fwd.connect_host = NULL;
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