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