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