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