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