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