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