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