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	fwd.listen_host = fwd.connect_host = NULL;
637	if (buffer_get_int_ret(&ftype, m) != 0 ||
638	    (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
639	    buffer_get_int_ret(&lport, m) != 0 ||
640	    (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
641	    buffer_get_int_ret(&cport, m) != 0 ||
642	    lport > 65535 || cport > 65535) {
643		error("%s: malformed message", __func__);
644		ret = -1;
645		goto out;
646	}
647	fwd.listen_port = lport;
648	fwd.connect_port = cport;
649	if (*fwd.listen_host == '\0') {
650		free(fwd.listen_host);
651		fwd.listen_host = NULL;
652	}
653	if (*fwd.connect_host == '\0') {
654		free(fwd.connect_host);
655		fwd.connect_host = NULL;
656	}
657
658	debug2("%s: channel %d: request %s", __func__, c->self,
659	    (fwd_desc = format_forward(ftype, &fwd)));
660
661	if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
662	    ftype != MUX_FWD_DYNAMIC) {
663		logit("%s: invalid forwarding type %u", __func__, ftype);
664 invalid:
665		free(fwd.listen_host);
666		free(fwd.connect_host);
667		buffer_put_int(r, MUX_S_FAILURE);
668		buffer_put_int(r, rid);
669		buffer_put_cstring(r, "Invalid forwarding request");
670		return 0;
671	}
672	if (fwd.listen_port >= 65536) {
673		logit("%s: invalid listen port %u", __func__,
674		    fwd.listen_port);
675		goto invalid;
676	}
677	if (fwd.connect_port >= 65536 || (ftype != MUX_FWD_DYNAMIC &&
678	    ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
679		logit("%s: invalid connect port %u", __func__,
680		    fwd.connect_port);
681		goto invalid;
682	}
683	if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL) {
684		logit("%s: missing connect host", __func__);
685		goto invalid;
686	}
687
688	/* Skip forwards that have already been requested */
689	switch (ftype) {
690	case MUX_FWD_LOCAL:
691	case MUX_FWD_DYNAMIC:
692		for (i = 0; i < options.num_local_forwards; i++) {
693			if (compare_forward(&fwd,
694			    options.local_forwards + i)) {
695 exists:
696				debug2("%s: found existing forwarding",
697				    __func__);
698				buffer_put_int(r, MUX_S_OK);
699				buffer_put_int(r, rid);
700				goto out;
701			}
702		}
703		break;
704	case MUX_FWD_REMOTE:
705		for (i = 0; i < options.num_remote_forwards; i++) {
706			if (compare_forward(&fwd,
707			    options.remote_forwards + i)) {
708				if (fwd.listen_port != 0)
709					goto exists;
710				debug2("%s: found allocated port",
711				    __func__);
712				buffer_put_int(r, MUX_S_REMOTE_PORT);
713				buffer_put_int(r, rid);
714				buffer_put_int(r,
715				    options.remote_forwards[i].allocated_port);
716				goto out;
717			}
718		}
719		break;
720	}
721
722	if (options.control_master == SSHCTL_MASTER_ASK ||
723	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
724		if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
725			debug2("%s: forwarding refused by user", __func__);
726			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
727			buffer_put_int(r, rid);
728			buffer_put_cstring(r, "Permission denied");
729			goto out;
730		}
731	}
732
733	if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
734		if (!channel_setup_local_fwd_listener(fwd.listen_host,
735		    fwd.listen_port, fwd.connect_host, fwd.connect_port,
736		    options.gateway_ports)) {
737 fail:
738			logit("slave-requested %s failed", fwd_desc);
739			buffer_put_int(r, MUX_S_FAILURE);
740			buffer_put_int(r, rid);
741			buffer_put_cstring(r, "Port forwarding failed");
742			goto out;
743		}
744		add_local_forward(&options, &fwd);
745		freefwd = 0;
746	} else {
747		struct mux_channel_confirm_ctx *fctx;
748
749		fwd.handle = channel_request_remote_forwarding(fwd.listen_host,
750		    fwd.listen_port, fwd.connect_host, fwd.connect_port);
751		if (fwd.handle < 0)
752			goto fail;
753		add_remote_forward(&options, &fwd);
754		fctx = xcalloc(1, sizeof(*fctx));
755		fctx->cid = c->self;
756		fctx->rid = rid;
757		fctx->fid = options.num_remote_forwards - 1;
758		client_register_global_confirm(mux_confirm_remote_forward,
759		    fctx);
760		freefwd = 0;
761		c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
762		/* delayed reply in mux_confirm_remote_forward */
763		goto out;
764	}
765	buffer_put_int(r, MUX_S_OK);
766	buffer_put_int(r, rid);
767 out:
768	free(fwd_desc);
769	if (freefwd) {
770		free(fwd.listen_host);
771		free(fwd.connect_host);
772	}
773	return ret;
774}
775
776static int
777process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
778{
779	Forward fwd, *found_fwd;
780	char *fwd_desc = NULL;
781	const char *error_reason = NULL;
782	u_int ftype;
783	int i, listen_port, ret = 0;
784	u_int lport, cport;
785
786	fwd.listen_host = fwd.connect_host = NULL;
787	if (buffer_get_int_ret(&ftype, m) != 0 ||
788	    (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
789	    buffer_get_int_ret(&lport, m) != 0 ||
790	    (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
791	    buffer_get_int_ret(&cport, m) != 0 ||
792	    lport > 65535 || cport > 65535) {
793		error("%s: malformed message", __func__);
794		ret = -1;
795		goto out;
796	}
797	fwd.listen_port = lport;
798	fwd.connect_port = cport;
799
800	if (*fwd.listen_host == '\0') {
801		free(fwd.listen_host);
802		fwd.listen_host = NULL;
803	}
804	if (*fwd.connect_host == '\0') {
805		free(fwd.connect_host);
806		fwd.connect_host = NULL;
807	}
808
809	debug2("%s: channel %d: request cancel %s", __func__, c->self,
810	    (fwd_desc = format_forward(ftype, &fwd)));
811
812	/* make sure this has been requested */
813	found_fwd = NULL;
814	switch (ftype) {
815	case MUX_FWD_LOCAL:
816	case MUX_FWD_DYNAMIC:
817		for (i = 0; i < options.num_local_forwards; i++) {
818			if (compare_forward(&fwd,
819			    options.local_forwards + i)) {
820				found_fwd = options.local_forwards + i;
821				break;
822			}
823		}
824		break;
825	case MUX_FWD_REMOTE:
826		for (i = 0; i < options.num_remote_forwards; i++) {
827			if (compare_forward(&fwd,
828			    options.remote_forwards + i)) {
829				found_fwd = options.remote_forwards + i;
830				break;
831			}
832		}
833		break;
834	}
835
836	if (found_fwd == NULL)
837		error_reason = "port not forwarded";
838	else if (ftype == MUX_FWD_REMOTE) {
839		/*
840		 * This shouldn't fail unless we confused the host/port
841		 * between options.remote_forwards and permitted_opens.
842		 * However, for dynamic allocated listen ports we need
843		 * to lookup the actual listen port.
844		 */
845	        listen_port = (fwd.listen_port == 0) ?
846		    found_fwd->allocated_port : fwd.listen_port;
847		if (channel_request_rforward_cancel(fwd.listen_host,
848		    listen_port) == -1)
849			error_reason = "port not in permitted opens";
850	} else {	/* local and dynamic forwards */
851		/* Ditto */
852		if (channel_cancel_lport_listener(fwd.listen_host,
853		    fwd.listen_port, fwd.connect_port,
854		    options.gateway_ports) == -1)
855			error_reason = "port not found";
856	}
857
858	if (error_reason == NULL) {
859		buffer_put_int(r, MUX_S_OK);
860		buffer_put_int(r, rid);
861
862		free(found_fwd->listen_host);
863		free(found_fwd->connect_host);
864		found_fwd->listen_host = found_fwd->connect_host = NULL;
865		found_fwd->listen_port = found_fwd->connect_port = 0;
866	} else {
867		buffer_put_int(r, MUX_S_FAILURE);
868		buffer_put_int(r, rid);
869		buffer_put_cstring(r, error_reason);
870	}
871 out:
872	free(fwd_desc);
873	free(fwd.listen_host);
874	free(fwd.connect_host);
875
876	return ret;
877}
878
879static int
880process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
881{
882	Channel *nc;
883	char *reserved, *chost;
884	u_int cport, i, j;
885	int new_fd[2];
886
887	chost = reserved = NULL;
888	if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
889	   (chost = buffer_get_string_ret(m, NULL)) == NULL ||
890	    buffer_get_int_ret(&cport, m) != 0) {
891		free(reserved);
892		free(chost);
893		error("%s: malformed message", __func__);
894		return -1;
895	}
896	free(reserved);
897
898	debug2("%s: channel %d: request stdio fwd to %s:%u",
899	    __func__, c->self, chost, cport);
900
901	/* Gather fds from client */
902	for(i = 0; i < 2; i++) {
903		if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
904			error("%s: failed to receive fd %d from slave",
905			    __func__, i);
906			for (j = 0; j < i; j++)
907				close(new_fd[j]);
908			free(chost);
909
910			/* prepare reply */
911			buffer_put_int(r, MUX_S_FAILURE);
912			buffer_put_int(r, rid);
913			buffer_put_cstring(r,
914			    "did not receive file descriptors");
915			return -1;
916		}
917	}
918
919	debug3("%s: got fds stdin %d, stdout %d", __func__,
920	    new_fd[0], new_fd[1]);
921
922	/* XXX support multiple child sessions in future */
923	if (c->remote_id != -1) {
924		debug2("%s: session already open", __func__);
925		/* prepare reply */
926		buffer_put_int(r, MUX_S_FAILURE);
927		buffer_put_int(r, rid);
928		buffer_put_cstring(r, "Multiple sessions not supported");
929 cleanup:
930		close(new_fd[0]);
931		close(new_fd[1]);
932		free(chost);
933		return 0;
934	}
935
936	if (options.control_master == SSHCTL_MASTER_ASK ||
937	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
938		if (!ask_permission("Allow forward to %s:%u? ",
939		    chost, cport)) {
940			debug2("%s: stdio fwd refused by user", __func__);
941			/* prepare reply */
942			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
943			buffer_put_int(r, rid);
944			buffer_put_cstring(r, "Permission denied");
945			goto cleanup;
946		}
947	}
948
949	/* enable nonblocking unless tty */
950	if (!isatty(new_fd[0]))
951		set_nonblock(new_fd[0]);
952	if (!isatty(new_fd[1]))
953		set_nonblock(new_fd[1]);
954
955	nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
956
957	nc->ctl_chan = c->self;		/* link session -> control channel */
958	c->remote_id = nc->self; 	/* link control -> session channel */
959
960	debug2("%s: channel_new: %d linked to control channel %d",
961	    __func__, nc->self, nc->ctl_chan);
962
963	channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
964
965	/* prepare reply */
966	/* XXX defer until channel confirmed */
967	buffer_put_int(r, MUX_S_SESSION_OPENED);
968	buffer_put_int(r, rid);
969	buffer_put_int(r, nc->self);
970
971	return 0;
972}
973
974static int
975process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
976{
977	debug("%s: channel %d: stop listening", __func__, c->self);
978
979	if (options.control_master == SSHCTL_MASTER_ASK ||
980	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
981		if (!ask_permission("Disable further multiplexing on shared "
982		    "connection to %s? ", host)) {
983			debug2("%s: stop listen refused by user", __func__);
984			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
985			buffer_put_int(r, rid);
986			buffer_put_cstring(r, "Permission denied");
987			return 0;
988		}
989	}
990
991	if (mux_listener_channel != NULL) {
992		channel_free(mux_listener_channel);
993		client_stop_mux();
994		free(options.control_path);
995		options.control_path = NULL;
996		mux_listener_channel = NULL;
997		muxserver_sock = -1;
998	}
999
1000	/* prepare reply */
1001	buffer_put_int(r, MUX_S_OK);
1002	buffer_put_int(r, rid);
1003
1004	return 0;
1005}
1006
1007/* Channel callbacks fired on read/write from mux slave fd */
1008static int
1009mux_master_read_cb(Channel *c)
1010{
1011	struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
1012	Buffer in, out;
1013	void *ptr;
1014	u_int type, rid, have, i;
1015	int ret = -1;
1016
1017	/* Setup ctx and  */
1018	if (c->mux_ctx == NULL) {
1019		state = xcalloc(1, sizeof(*state));
1020		c->mux_ctx = state;
1021		channel_register_cleanup(c->self,
1022		    mux_master_control_cleanup_cb, 0);
1023
1024		/* Send hello */
1025		buffer_init(&out);
1026		buffer_put_int(&out, MUX_MSG_HELLO);
1027		buffer_put_int(&out, SSHMUX_VER);
1028		/* no extensions */
1029		buffer_put_string(&c->output, buffer_ptr(&out),
1030		    buffer_len(&out));
1031		buffer_free(&out);
1032		debug3("%s: channel %d: hello sent", __func__, c->self);
1033		return 0;
1034	}
1035
1036	buffer_init(&in);
1037	buffer_init(&out);
1038
1039	/* Channel code ensures that we receive whole packets */
1040	if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
1041 malf:
1042		error("%s: malformed message", __func__);
1043		goto out;
1044	}
1045	buffer_append(&in, ptr, have);
1046
1047	if (buffer_get_int_ret(&type, &in) != 0)
1048		goto malf;
1049	debug3("%s: channel %d packet type 0x%08x len %u",
1050	    __func__, c->self, type, buffer_len(&in));
1051
1052	if (type == MUX_MSG_HELLO)
1053		rid = 0;
1054	else {
1055		if (!state->hello_rcvd) {
1056			error("%s: expected MUX_MSG_HELLO(0x%08x), "
1057			    "received 0x%08x", __func__, MUX_MSG_HELLO, type);
1058			goto out;
1059		}
1060		if (buffer_get_int_ret(&rid, &in) != 0)
1061			goto malf;
1062	}
1063
1064	for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
1065		if (type == mux_master_handlers[i].type) {
1066			ret = mux_master_handlers[i].handler(rid, c, &in, &out);
1067			break;
1068		}
1069	}
1070	if (mux_master_handlers[i].handler == NULL) {
1071		error("%s: unsupported mux message 0x%08x", __func__, type);
1072		buffer_put_int(&out, MUX_S_FAILURE);
1073		buffer_put_int(&out, rid);
1074		buffer_put_cstring(&out, "unsupported request");
1075		ret = 0;
1076	}
1077	/* Enqueue reply packet */
1078	if (buffer_len(&out) != 0) {
1079		buffer_put_string(&c->output, buffer_ptr(&out),
1080		    buffer_len(&out));
1081	}
1082 out:
1083	buffer_free(&in);
1084	buffer_free(&out);
1085	return ret;
1086}
1087
1088void
1089mux_exit_message(Channel *c, int exitval)
1090{
1091	Buffer m;
1092	Channel *mux_chan;
1093
1094	debug3("%s: channel %d: exit message, exitval %d", __func__, c->self,
1095	    exitval);
1096
1097	if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1098		fatal("%s: channel %d missing mux channel %d",
1099		    __func__, c->self, c->ctl_chan);
1100
1101	/* Append exit message packet to control socket output queue */
1102	buffer_init(&m);
1103	buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
1104	buffer_put_int(&m, c->self);
1105	buffer_put_int(&m, exitval);
1106
1107	buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1108	buffer_free(&m);
1109}
1110
1111void
1112mux_tty_alloc_failed(Channel *c)
1113{
1114	Buffer m;
1115	Channel *mux_chan;
1116
1117	debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
1118
1119	if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1120		fatal("%s: channel %d missing mux channel %d",
1121		    __func__, c->self, c->ctl_chan);
1122
1123	/* Append exit message packet to control socket output queue */
1124	buffer_init(&m);
1125	buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
1126	buffer_put_int(&m, c->self);
1127
1128	buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1129	buffer_free(&m);
1130}
1131
1132/* Prepare a mux master to listen on a Unix domain socket. */
1133void
1134muxserver_listen(void)
1135{
1136	struct sockaddr_un addr;
1137	socklen_t sun_len;
1138	mode_t old_umask;
1139	char *orig_control_path = options.control_path;
1140	char rbuf[16+1];
1141	u_int i, r;
1142
1143	if (options.control_path == NULL ||
1144	    options.control_master == SSHCTL_MASTER_NO)
1145		return;
1146
1147	debug("setting up multiplex master socket");
1148
1149	/*
1150	 * Use a temporary path before listen so we can pseudo-atomically
1151	 * establish the listening socket in its final location to avoid
1152	 * other processes racing in between bind() and listen() and hitting
1153	 * an unready socket.
1154	 */
1155	for (i = 0; i < sizeof(rbuf) - 1; i++) {
1156		r = arc4random_uniform(26+26+10);
1157		rbuf[i] = (r < 26) ? 'a' + r :
1158		    (r < 26*2) ? 'A' + r - 26 :
1159		    '0' + r - 26 - 26;
1160	}
1161	rbuf[sizeof(rbuf) - 1] = '\0';
1162	options.control_path = NULL;
1163	xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
1164	debug3("%s: temporary control path %s", __func__, options.control_path);
1165
1166	memset(&addr, '\0', sizeof(addr));
1167	addr.sun_family = AF_UNIX;
1168	sun_len = offsetof(struct sockaddr_un, sun_path) +
1169	    strlen(options.control_path) + 1;
1170
1171	if (strlcpy(addr.sun_path, options.control_path,
1172	    sizeof(addr.sun_path)) >= sizeof(addr.sun_path)) {
1173		error("ControlPath \"%s\" too long for Unix domain socket",
1174		    options.control_path);
1175		goto disable_mux_master;
1176	}
1177
1178	if ((muxserver_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1179		fatal("%s socket(): %s", __func__, strerror(errno));
1180
1181	old_umask = umask(0177);
1182	if (bind(muxserver_sock, (struct sockaddr *)&addr, sun_len) == -1) {
1183		if (errno == EINVAL || errno == EADDRINUSE) {
1184			error("ControlSocket %s already exists, "
1185			    "disabling multiplexing", options.control_path);
1186 disable_mux_master:
1187			if (muxserver_sock != -1) {
1188				close(muxserver_sock);
1189				muxserver_sock = -1;
1190			}
1191			free(orig_control_path);
1192			free(options.control_path);
1193			options.control_path = NULL;
1194			options.control_master = SSHCTL_MASTER_NO;
1195			return;
1196		} else
1197			fatal("%s bind(): %s", __func__, strerror(errno));
1198	}
1199	umask(old_umask);
1200
1201	if (listen(muxserver_sock, 64) == -1)
1202		fatal("%s listen(): %s", __func__, strerror(errno));
1203
1204	/* Now atomically "move" the mux socket into position */
1205	if (link(options.control_path, orig_control_path) != 0) {
1206		if (errno != EEXIST) {
1207			fatal("%s: link mux listener %s => %s: %s", __func__,
1208			    options.control_path, orig_control_path,
1209			    strerror(errno));
1210		}
1211		error("ControlSocket %s already exists, disabling multiplexing",
1212		    orig_control_path);
1213		unlink(options.control_path);
1214		goto disable_mux_master;
1215	}
1216	unlink(options.control_path);
1217	free(options.control_path);
1218	options.control_path = orig_control_path;
1219
1220	set_nonblock(muxserver_sock);
1221
1222	mux_listener_channel = channel_new("mux listener",
1223	    SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
1224	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1225	    0, options.control_path, 1);
1226	mux_listener_channel->mux_rcb = mux_master_read_cb;
1227	debug3("%s: mux listener channel %d fd %d", __func__,
1228	    mux_listener_channel->self, mux_listener_channel->sock);
1229}
1230
1231/* Callback on open confirmation in mux master for a mux client session. */
1232static void
1233mux_session_confirm(int id, int success, void *arg)
1234{
1235	struct mux_session_confirm_ctx *cctx = arg;
1236	const char *display;
1237	Channel *c, *cc;
1238	int i;
1239	Buffer reply;
1240
1241	if (cctx == NULL)
1242		fatal("%s: cctx == NULL", __func__);
1243	if ((c = channel_by_id(id)) == NULL)
1244		fatal("%s: no channel for id %d", __func__, id);
1245	if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1246		fatal("%s: channel %d lacks control channel %d", __func__,
1247		    id, c->ctl_chan);
1248
1249	if (!success) {
1250		debug3("%s: sending failure reply", __func__);
1251		/* prepare reply */
1252		buffer_init(&reply);
1253		buffer_put_int(&reply, MUX_S_FAILURE);
1254		buffer_put_int(&reply, cctx->rid);
1255		buffer_put_cstring(&reply, "Session open refused by peer");
1256		goto done;
1257	}
1258
1259	display = getenv("DISPLAY");
1260	if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1261		char *proto, *data;
1262
1263		/* Get reasonable local authentication information. */
1264		client_x11_get_proto(display, options.xauth_location,
1265		    options.forward_x11_trusted, options.forward_x11_timeout,
1266		    &proto, &data);
1267		/* Request forwarding with authentication spoofing. */
1268		debug("Requesting X11 forwarding with authentication "
1269		    "spoofing.");
1270		x11_request_forwarding_with_spoofing(id, display, proto,
1271		    data, 1);
1272		client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1273		/* XXX exit_on_forward_failure */
1274	}
1275
1276	if (cctx->want_agent_fwd && options.forward_agent) {
1277		debug("Requesting authentication agent forwarding.");
1278		channel_request_start(id, "auth-agent-req@openssh.com", 0);
1279		packet_send();
1280	}
1281
1282	client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1283	    cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1284
1285	debug3("%s: sending success reply", __func__);
1286	/* prepare reply */
1287	buffer_init(&reply);
1288	buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1289	buffer_put_int(&reply, cctx->rid);
1290	buffer_put_int(&reply, c->self);
1291
1292 done:
1293	/* Send reply */
1294	buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1295	buffer_free(&reply);
1296
1297	if (cc->mux_pause <= 0)
1298		fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1299	cc->mux_pause = 0; /* start processing messages again */
1300	c->open_confirm_ctx = NULL;
1301	buffer_free(&cctx->cmd);
1302	free(cctx->term);
1303	if (cctx->env != NULL) {
1304		for (i = 0; cctx->env[i] != NULL; i++)
1305			free(cctx->env[i]);
1306		free(cctx->env);
1307	}
1308	free(cctx);
1309}
1310
1311/* ** Multiplexing client support */
1312
1313/* Exit signal handler */
1314static void
1315control_client_sighandler(int signo)
1316{
1317	muxclient_terminate = signo;
1318}
1319
1320/*
1321 * Relay signal handler - used to pass some signals from mux client to
1322 * mux master.
1323 */
1324static void
1325control_client_sigrelay(int signo)
1326{
1327	int save_errno = errno;
1328
1329	if (muxserver_pid > 1)
1330		kill(muxserver_pid, signo);
1331
1332	errno = save_errno;
1333}
1334
1335static int
1336mux_client_read(int fd, Buffer *b, u_int need)
1337{
1338	u_int have;
1339	ssize_t len;
1340	u_char *p;
1341	struct pollfd pfd;
1342
1343	pfd.fd = fd;
1344	pfd.events = POLLIN;
1345	p = buffer_append_space(b, need);
1346	for (have = 0; have < need; ) {
1347		if (muxclient_terminate) {
1348			errno = EINTR;
1349			return -1;
1350		}
1351		len = read(fd, p + have, need - have);
1352		if (len < 0) {
1353			switch (errno) {
1354#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1355			case EWOULDBLOCK:
1356#endif
1357			case EAGAIN:
1358				(void)poll(&pfd, 1, -1);
1359				/* FALLTHROUGH */
1360			case EINTR:
1361				continue;
1362			default:
1363				return -1;
1364			}
1365		}
1366		if (len == 0) {
1367			errno = EPIPE;
1368			return -1;
1369		}
1370		have += (u_int)len;
1371	}
1372	return 0;
1373}
1374
1375static int
1376mux_client_write_packet(int fd, Buffer *m)
1377{
1378	Buffer queue;
1379	u_int have, need;
1380	int oerrno, len;
1381	u_char *ptr;
1382	struct pollfd pfd;
1383
1384	pfd.fd = fd;
1385	pfd.events = POLLOUT;
1386	buffer_init(&queue);
1387	buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1388
1389	need = buffer_len(&queue);
1390	ptr = buffer_ptr(&queue);
1391
1392	for (have = 0; have < need; ) {
1393		if (muxclient_terminate) {
1394			buffer_free(&queue);
1395			errno = EINTR;
1396			return -1;
1397		}
1398		len = write(fd, ptr + have, need - have);
1399		if (len < 0) {
1400			switch (errno) {
1401#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1402			case EWOULDBLOCK:
1403#endif
1404			case EAGAIN:
1405				(void)poll(&pfd, 1, -1);
1406				/* FALLTHROUGH */
1407			case EINTR:
1408				continue;
1409			default:
1410				oerrno = errno;
1411				buffer_free(&queue);
1412				errno = oerrno;
1413				return -1;
1414			}
1415		}
1416		if (len == 0) {
1417			buffer_free(&queue);
1418			errno = EPIPE;
1419			return -1;
1420		}
1421		have += (u_int)len;
1422	}
1423	buffer_free(&queue);
1424	return 0;
1425}
1426
1427static int
1428mux_client_read_packet(int fd, Buffer *m)
1429{
1430	Buffer queue;
1431	u_int need, have;
1432	void *ptr;
1433	int oerrno;
1434
1435	buffer_init(&queue);
1436	if (mux_client_read(fd, &queue, 4) != 0) {
1437		if ((oerrno = errno) == EPIPE)
1438			debug3("%s: read header failed: %s", __func__,
1439			    strerror(errno));
1440		buffer_free(&queue);
1441		errno = oerrno;
1442		return -1;
1443	}
1444	need = get_u32(buffer_ptr(&queue));
1445	if (mux_client_read(fd, &queue, need) != 0) {
1446		oerrno = errno;
1447		debug3("%s: read body failed: %s", __func__, strerror(errno));
1448		buffer_free(&queue);
1449		errno = oerrno;
1450		return -1;
1451	}
1452	ptr = buffer_get_string_ptr(&queue, &have);
1453	buffer_append(m, ptr, have);
1454	buffer_free(&queue);
1455	return 0;
1456}
1457
1458static int
1459mux_client_hello_exchange(int fd)
1460{
1461	Buffer m;
1462	u_int type, ver;
1463
1464	buffer_init(&m);
1465	buffer_put_int(&m, MUX_MSG_HELLO);
1466	buffer_put_int(&m, SSHMUX_VER);
1467	/* no extensions */
1468
1469	if (mux_client_write_packet(fd, &m) != 0)
1470		fatal("%s: write packet: %s", __func__, strerror(errno));
1471
1472	buffer_clear(&m);
1473
1474	/* Read their HELLO */
1475	if (mux_client_read_packet(fd, &m) != 0) {
1476		buffer_free(&m);
1477		return -1;
1478	}
1479
1480	type = buffer_get_int(&m);
1481	if (type != MUX_MSG_HELLO)
1482		fatal("%s: expected HELLO (%u) received %u",
1483		    __func__, MUX_MSG_HELLO, type);
1484	ver = buffer_get_int(&m);
1485	if (ver != SSHMUX_VER)
1486		fatal("Unsupported multiplexing protocol version %d "
1487		    "(expected %d)", ver, SSHMUX_VER);
1488	debug2("%s: master version %u", __func__, ver);
1489	/* No extensions are presently defined */
1490	while (buffer_len(&m) > 0) {
1491		char *name = buffer_get_string(&m, NULL);
1492		char *value = buffer_get_string(&m, NULL);
1493
1494		debug2("Unrecognised master extension \"%s\"", name);
1495		free(name);
1496		free(value);
1497	}
1498	buffer_free(&m);
1499	return 0;
1500}
1501
1502static u_int
1503mux_client_request_alive(int fd)
1504{
1505	Buffer m;
1506	char *e;
1507	u_int pid, type, rid;
1508
1509	debug3("%s: entering", __func__);
1510
1511	buffer_init(&m);
1512	buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1513	buffer_put_int(&m, muxclient_request_id);
1514
1515	if (mux_client_write_packet(fd, &m) != 0)
1516		fatal("%s: write packet: %s", __func__, strerror(errno));
1517
1518	buffer_clear(&m);
1519
1520	/* Read their reply */
1521	if (mux_client_read_packet(fd, &m) != 0) {
1522		buffer_free(&m);
1523		return 0;
1524	}
1525
1526	type = buffer_get_int(&m);
1527	if (type != MUX_S_ALIVE) {
1528		e = buffer_get_string(&m, NULL);
1529		fatal("%s: master returned error: %s", __func__, e);
1530	}
1531
1532	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1533		fatal("%s: out of sequence reply: my id %u theirs %u",
1534		    __func__, muxclient_request_id, rid);
1535	pid = buffer_get_int(&m);
1536	buffer_free(&m);
1537
1538	debug3("%s: done pid = %u", __func__, pid);
1539
1540	muxclient_request_id++;
1541
1542	return pid;
1543}
1544
1545static void
1546mux_client_request_terminate(int fd)
1547{
1548	Buffer m;
1549	char *e;
1550	u_int type, rid;
1551
1552	debug3("%s: entering", __func__);
1553
1554	buffer_init(&m);
1555	buffer_put_int(&m, MUX_C_TERMINATE);
1556	buffer_put_int(&m, muxclient_request_id);
1557
1558	if (mux_client_write_packet(fd, &m) != 0)
1559		fatal("%s: write packet: %s", __func__, strerror(errno));
1560
1561	buffer_clear(&m);
1562
1563	/* Read their reply */
1564	if (mux_client_read_packet(fd, &m) != 0) {
1565		/* Remote end exited already */
1566		if (errno == EPIPE) {
1567			buffer_free(&m);
1568			return;
1569		}
1570		fatal("%s: read from master failed: %s",
1571		    __func__, strerror(errno));
1572	}
1573
1574	type = buffer_get_int(&m);
1575	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1576		fatal("%s: out of sequence reply: my id %u theirs %u",
1577		    __func__, muxclient_request_id, rid);
1578	switch (type) {
1579	case MUX_S_OK:
1580		break;
1581	case MUX_S_PERMISSION_DENIED:
1582		e = buffer_get_string(&m, NULL);
1583		fatal("Master refused termination request: %s", e);
1584	case MUX_S_FAILURE:
1585		e = buffer_get_string(&m, NULL);
1586		fatal("%s: termination request failed: %s", __func__, e);
1587	default:
1588		fatal("%s: unexpected response from master 0x%08x",
1589		    __func__, type);
1590	}
1591	buffer_free(&m);
1592	muxclient_request_id++;
1593}
1594
1595static int
1596mux_client_forward(int fd, int cancel_flag, u_int ftype, Forward *fwd)
1597{
1598	Buffer m;
1599	char *e, *fwd_desc;
1600	u_int type, rid;
1601
1602	fwd_desc = format_forward(ftype, fwd);
1603	debug("Requesting %s %s",
1604	    cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
1605	free(fwd_desc);
1606
1607	buffer_init(&m);
1608	buffer_put_int(&m, cancel_flag ? MUX_C_CLOSE_FWD : MUX_C_OPEN_FWD);
1609	buffer_put_int(&m, muxclient_request_id);
1610	buffer_put_int(&m, ftype);
1611	buffer_put_cstring(&m,
1612	    fwd->listen_host == NULL ? "" : fwd->listen_host);
1613	buffer_put_int(&m, fwd->listen_port);
1614	buffer_put_cstring(&m,
1615	    fwd->connect_host == NULL ? "" : fwd->connect_host);
1616	buffer_put_int(&m, fwd->connect_port);
1617
1618	if (mux_client_write_packet(fd, &m) != 0)
1619		fatal("%s: write packet: %s", __func__, strerror(errno));
1620
1621	buffer_clear(&m);
1622
1623	/* Read their reply */
1624	if (mux_client_read_packet(fd, &m) != 0) {
1625		buffer_free(&m);
1626		return -1;
1627	}
1628
1629	type = buffer_get_int(&m);
1630	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1631		fatal("%s: out of sequence reply: my id %u theirs %u",
1632		    __func__, muxclient_request_id, rid);
1633	switch (type) {
1634	case MUX_S_OK:
1635		break;
1636	case MUX_S_REMOTE_PORT:
1637		if (cancel_flag)
1638			fatal("%s: got MUX_S_REMOTE_PORT for cancel", __func__);
1639		fwd->allocated_port = buffer_get_int(&m);
1640		logit("Allocated port %u for remote forward to %s:%d",
1641		    fwd->allocated_port,
1642		    fwd->connect_host ? fwd->connect_host : "",
1643		    fwd->connect_port);
1644		if (muxclient_command == SSHMUX_COMMAND_FORWARD)
1645			fprintf(stdout, "%u\n", fwd->allocated_port);
1646		break;
1647	case MUX_S_PERMISSION_DENIED:
1648		e = buffer_get_string(&m, NULL);
1649		buffer_free(&m);
1650		error("Master refused forwarding request: %s", e);
1651		return -1;
1652	case MUX_S_FAILURE:
1653		e = buffer_get_string(&m, NULL);
1654		buffer_free(&m);
1655		error("%s: forwarding request failed: %s", __func__, e);
1656		return -1;
1657	default:
1658		fatal("%s: unexpected response from master 0x%08x",
1659		    __func__, type);
1660	}
1661	buffer_free(&m);
1662
1663	muxclient_request_id++;
1664	return 0;
1665}
1666
1667static int
1668mux_client_forwards(int fd, int cancel_flag)
1669{
1670	int i, ret = 0;
1671
1672	debug3("%s: %s forwardings: %d local, %d remote", __func__,
1673	    cancel_flag ? "cancel" : "request",
1674	    options.num_local_forwards, options.num_remote_forwards);
1675
1676	/* XXX ExitOnForwardingFailure */
1677	for (i = 0; i < options.num_local_forwards; i++) {
1678		if (mux_client_forward(fd, cancel_flag,
1679		    options.local_forwards[i].connect_port == 0 ?
1680		    MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1681		    options.local_forwards + i) != 0)
1682			ret = -1;
1683	}
1684	for (i = 0; i < options.num_remote_forwards; i++) {
1685		if (mux_client_forward(fd, cancel_flag, MUX_FWD_REMOTE,
1686		    options.remote_forwards + i) != 0)
1687			ret = -1;
1688	}
1689	return ret;
1690}
1691
1692static int
1693mux_client_request_session(int fd)
1694{
1695	Buffer m;
1696	char *e, *term;
1697	u_int i, rid, sid, esid, exitval, type, exitval_seen;
1698	extern char **environ;
1699	int devnull, rawmode;
1700
1701	debug3("%s: entering", __func__);
1702
1703	if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1704		error("%s: master alive request failed", __func__);
1705		return -1;
1706	}
1707
1708	signal(SIGPIPE, SIG_IGN);
1709
1710	if (stdin_null_flag) {
1711		if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1712			fatal("open(/dev/null): %s", strerror(errno));
1713		if (dup2(devnull, STDIN_FILENO) == -1)
1714			fatal("dup2: %s", strerror(errno));
1715		if (devnull > STDERR_FILENO)
1716			close(devnull);
1717	}
1718
1719	term = getenv("TERM");
1720
1721	buffer_init(&m);
1722	buffer_put_int(&m, MUX_C_NEW_SESSION);
1723	buffer_put_int(&m, muxclient_request_id);
1724	buffer_put_cstring(&m, ""); /* reserved */
1725	buffer_put_int(&m, tty_flag);
1726	buffer_put_int(&m, options.forward_x11);
1727	buffer_put_int(&m, options.forward_agent);
1728	buffer_put_int(&m, subsystem_flag);
1729	buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1730	    0xffffffff : (u_int)options.escape_char);
1731	buffer_put_cstring(&m, term == NULL ? "" : term);
1732	buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1733
1734	if (options.num_send_env > 0 && environ != NULL) {
1735		/* Pass environment */
1736		for (i = 0; environ[i] != NULL; i++) {
1737			if (env_permitted(environ[i])) {
1738				buffer_put_cstring(&m, environ[i]);
1739			}
1740		}
1741	}
1742
1743	if (mux_client_write_packet(fd, &m) != 0)
1744		fatal("%s: write packet: %s", __func__, strerror(errno));
1745
1746	/* Send the stdio file descriptors */
1747	if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1748	    mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1749	    mm_send_fd(fd, STDERR_FILENO) == -1)
1750		fatal("%s: send fds failed", __func__);
1751
1752	debug3("%s: session request sent", __func__);
1753
1754	/* Read their reply */
1755	buffer_clear(&m);
1756	if (mux_client_read_packet(fd, &m) != 0) {
1757		error("%s: read from master failed: %s",
1758		    __func__, strerror(errno));
1759		buffer_free(&m);
1760		return -1;
1761	}
1762
1763	type = buffer_get_int(&m);
1764	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1765		fatal("%s: out of sequence reply: my id %u theirs %u",
1766		    __func__, muxclient_request_id, rid);
1767	switch (type) {
1768	case MUX_S_SESSION_OPENED:
1769		sid = buffer_get_int(&m);
1770		debug("%s: master session id: %u", __func__, sid);
1771		break;
1772	case MUX_S_PERMISSION_DENIED:
1773		e = buffer_get_string(&m, NULL);
1774		buffer_free(&m);
1775		error("Master refused session request: %s", e);
1776		return -1;
1777	case MUX_S_FAILURE:
1778		e = buffer_get_string(&m, NULL);
1779		buffer_free(&m);
1780		error("%s: session request failed: %s", __func__, e);
1781		return -1;
1782	default:
1783		buffer_free(&m);
1784		error("%s: unexpected response from master 0x%08x",
1785		    __func__, type);
1786		return -1;
1787	}
1788	muxclient_request_id++;
1789
1790	signal(SIGHUP, control_client_sighandler);
1791	signal(SIGINT, control_client_sighandler);
1792	signal(SIGTERM, control_client_sighandler);
1793	signal(SIGWINCH, control_client_sigrelay);
1794
1795	rawmode = tty_flag;
1796	if (tty_flag)
1797		enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1798
1799	/*
1800	 * Stick around until the controlee closes the client_fd.
1801	 * Before it does, it is expected to write an exit message.
1802	 * This process must read the value and wait for the closure of
1803	 * the client_fd; if this one closes early, the multiplex master will
1804	 * terminate early too (possibly losing data).
1805	 */
1806	for (exitval = 255, exitval_seen = 0;;) {
1807		buffer_clear(&m);
1808		if (mux_client_read_packet(fd, &m) != 0)
1809			break;
1810		type = buffer_get_int(&m);
1811		switch (type) {
1812		case MUX_S_TTY_ALLOC_FAIL:
1813			if ((esid = buffer_get_int(&m)) != sid)
1814				fatal("%s: tty alloc fail on unknown session: "
1815				    "my id %u theirs %u",
1816				    __func__, sid, esid);
1817			leave_raw_mode(options.request_tty ==
1818			    REQUEST_TTY_FORCE);
1819			rawmode = 0;
1820			continue;
1821		case MUX_S_EXIT_MESSAGE:
1822			if ((esid = buffer_get_int(&m)) != sid)
1823				fatal("%s: exit on unknown session: "
1824				    "my id %u theirs %u",
1825				    __func__, sid, esid);
1826			if (exitval_seen)
1827				fatal("%s: exitval sent twice", __func__);
1828			exitval = buffer_get_int(&m);
1829			exitval_seen = 1;
1830			continue;
1831		default:
1832			e = buffer_get_string(&m, NULL);
1833			fatal("%s: master returned error: %s", __func__, e);
1834		}
1835	}
1836
1837	close(fd);
1838	if (rawmode)
1839		leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1840
1841	if (muxclient_terminate) {
1842		debug2("Exiting on signal %ld", (long)muxclient_terminate);
1843		exitval = 255;
1844	} else if (!exitval_seen) {
1845		debug2("Control master terminated unexpectedly");
1846		exitval = 255;
1847	} else
1848		debug2("Received exit status from master %d", exitval);
1849
1850	if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1851		fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1852
1853	exit(exitval);
1854}
1855
1856static int
1857mux_client_request_stdio_fwd(int fd)
1858{
1859	Buffer m;
1860	char *e;
1861	u_int type, rid, sid;
1862	int devnull;
1863
1864	debug3("%s: entering", __func__);
1865
1866	if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1867		error("%s: master alive request failed", __func__);
1868		return -1;
1869	}
1870
1871	signal(SIGPIPE, SIG_IGN);
1872
1873	if (stdin_null_flag) {
1874		if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1875			fatal("open(/dev/null): %s", strerror(errno));
1876		if (dup2(devnull, STDIN_FILENO) == -1)
1877			fatal("dup2: %s", strerror(errno));
1878		if (devnull > STDERR_FILENO)
1879			close(devnull);
1880	}
1881
1882	buffer_init(&m);
1883	buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
1884	buffer_put_int(&m, muxclient_request_id);
1885	buffer_put_cstring(&m, ""); /* reserved */
1886	buffer_put_cstring(&m, stdio_forward_host);
1887	buffer_put_int(&m, stdio_forward_port);
1888
1889	if (mux_client_write_packet(fd, &m) != 0)
1890		fatal("%s: write packet: %s", __func__, strerror(errno));
1891
1892	/* Send the stdio file descriptors */
1893	if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1894	    mm_send_fd(fd, STDOUT_FILENO) == -1)
1895		fatal("%s: send fds failed", __func__);
1896
1897	debug3("%s: stdio forward request sent", __func__);
1898
1899	/* Read their reply */
1900	buffer_clear(&m);
1901
1902	if (mux_client_read_packet(fd, &m) != 0) {
1903		error("%s: read from master failed: %s",
1904		    __func__, strerror(errno));
1905		buffer_free(&m);
1906		return -1;
1907	}
1908
1909	type = buffer_get_int(&m);
1910	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1911		fatal("%s: out of sequence reply: my id %u theirs %u",
1912		    __func__, muxclient_request_id, rid);
1913	switch (type) {
1914	case MUX_S_SESSION_OPENED:
1915		sid = buffer_get_int(&m);
1916		debug("%s: master session id: %u", __func__, sid);
1917		break;
1918	case MUX_S_PERMISSION_DENIED:
1919		e = buffer_get_string(&m, NULL);
1920		buffer_free(&m);
1921		fatal("Master refused stdio forwarding request: %s", e);
1922	case MUX_S_FAILURE:
1923		e = buffer_get_string(&m, NULL);
1924		buffer_free(&m);
1925		fatal("%s: stdio forwarding request failed: %s", __func__, e);
1926	default:
1927		buffer_free(&m);
1928		error("%s: unexpected response from master 0x%08x",
1929		    __func__, type);
1930		return -1;
1931	}
1932	muxclient_request_id++;
1933
1934	signal(SIGHUP, control_client_sighandler);
1935	signal(SIGINT, control_client_sighandler);
1936	signal(SIGTERM, control_client_sighandler);
1937	signal(SIGWINCH, control_client_sigrelay);
1938
1939	/*
1940	 * Stick around until the controlee closes the client_fd.
1941	 */
1942	buffer_clear(&m);
1943	if (mux_client_read_packet(fd, &m) != 0) {
1944		if (errno == EPIPE ||
1945		    (errno == EINTR && muxclient_terminate != 0))
1946			return 0;
1947		fatal("%s: mux_client_read_packet: %s",
1948		    __func__, strerror(errno));
1949	}
1950	fatal("%s: master returned unexpected message %u", __func__, type);
1951}
1952
1953static void
1954mux_client_request_stop_listening(int fd)
1955{
1956	Buffer m;
1957	char *e;
1958	u_int type, rid;
1959
1960	debug3("%s: entering", __func__);
1961
1962	buffer_init(&m);
1963	buffer_put_int(&m, MUX_C_STOP_LISTENING);
1964	buffer_put_int(&m, muxclient_request_id);
1965
1966	if (mux_client_write_packet(fd, &m) != 0)
1967		fatal("%s: write packet: %s", __func__, strerror(errno));
1968
1969	buffer_clear(&m);
1970
1971	/* Read their reply */
1972	if (mux_client_read_packet(fd, &m) != 0)
1973		fatal("%s: read from master failed: %s",
1974		    __func__, strerror(errno));
1975
1976	type = buffer_get_int(&m);
1977	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1978		fatal("%s: out of sequence reply: my id %u theirs %u",
1979		    __func__, muxclient_request_id, rid);
1980	switch (type) {
1981	case MUX_S_OK:
1982		break;
1983	case MUX_S_PERMISSION_DENIED:
1984		e = buffer_get_string(&m, NULL);
1985		fatal("Master refused stop listening request: %s", e);
1986	case MUX_S_FAILURE:
1987		e = buffer_get_string(&m, NULL);
1988		fatal("%s: stop listening request failed: %s", __func__, e);
1989	default:
1990		fatal("%s: unexpected response from master 0x%08x",
1991		    __func__, type);
1992	}
1993	buffer_free(&m);
1994	muxclient_request_id++;
1995}
1996
1997/* Multiplex client main loop. */
1998void
1999muxclient(const char *path)
2000{
2001	struct sockaddr_un addr;
2002	socklen_t sun_len;
2003	int sock;
2004	u_int pid;
2005
2006	if (muxclient_command == 0) {
2007		if (stdio_forward_host != NULL)
2008			muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
2009		else
2010			muxclient_command = SSHMUX_COMMAND_OPEN;
2011	}
2012
2013	switch (options.control_master) {
2014	case SSHCTL_MASTER_AUTO:
2015	case SSHCTL_MASTER_AUTO_ASK:
2016		debug("auto-mux: Trying existing master");
2017		/* FALLTHROUGH */
2018	case SSHCTL_MASTER_NO:
2019		break;
2020	default:
2021		return;
2022	}
2023
2024	memset(&addr, '\0', sizeof(addr));
2025	addr.sun_family = AF_UNIX;
2026	sun_len = offsetof(struct sockaddr_un, sun_path) +
2027	    strlen(path) + 1;
2028
2029	if (strlcpy(addr.sun_path, path,
2030	    sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
2031		fatal("ControlPath too long");
2032
2033	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
2034		fatal("%s socket(): %s", __func__, strerror(errno));
2035
2036	if (connect(sock, (struct sockaddr *)&addr, sun_len) == -1) {
2037		switch (muxclient_command) {
2038		case SSHMUX_COMMAND_OPEN:
2039		case SSHMUX_COMMAND_STDIO_FWD:
2040			break;
2041		default:
2042			fatal("Control socket connect(%.100s): %s", path,
2043			    strerror(errno));
2044		}
2045		if (errno == ECONNREFUSED &&
2046		    options.control_master != SSHCTL_MASTER_NO) {
2047			debug("Stale control socket %.100s, unlinking", path);
2048			unlink(path);
2049		} else if (errno == ENOENT) {
2050			debug("Control socket \"%.100s\" does not exist", path);
2051		} else {
2052			error("Control socket connect(%.100s): %s", path,
2053			    strerror(errno));
2054		}
2055		close(sock);
2056		return;
2057	}
2058	set_nonblock(sock);
2059
2060	if (mux_client_hello_exchange(sock) != 0) {
2061		error("%s: master hello exchange failed", __func__);
2062		close(sock);
2063		return;
2064	}
2065
2066	switch (muxclient_command) {
2067	case SSHMUX_COMMAND_ALIVE_CHECK:
2068		if ((pid = mux_client_request_alive(sock)) == 0)
2069			fatal("%s: master alive check failed", __func__);
2070		fprintf(stderr, "Master running (pid=%d)\r\n", pid);
2071		exit(0);
2072	case SSHMUX_COMMAND_TERMINATE:
2073		mux_client_request_terminate(sock);
2074		fprintf(stderr, "Exit request sent.\r\n");
2075		exit(0);
2076	case SSHMUX_COMMAND_FORWARD:
2077		if (mux_client_forwards(sock, 0) != 0)
2078			fatal("%s: master forward request failed", __func__);
2079		exit(0);
2080	case SSHMUX_COMMAND_OPEN:
2081		if (mux_client_forwards(sock, 0) != 0) {
2082			error("%s: master forward request failed", __func__);
2083			return;
2084		}
2085		mux_client_request_session(sock);
2086		return;
2087	case SSHMUX_COMMAND_STDIO_FWD:
2088		mux_client_request_stdio_fwd(sock);
2089		exit(0);
2090	case SSHMUX_COMMAND_STOP:
2091		mux_client_request_stop_listening(sock);
2092		fprintf(stderr, "Stop listening request sent.\r\n");
2093		exit(0);
2094	case SSHMUX_COMMAND_CANCEL_FWD:
2095		if (mux_client_forwards(sock, 1) != 0)
2096			error("%s: master cancel forward request failed",
2097			    __func__);
2098		exit(0);
2099	default:
2100		fatal("unrecognised muxclient_command %d", muxclient_command);
2101	}
2102}
2103