xref: /netbsd-src/crypto/external/bsd/openssh/dist/mux.c (revision d909946ca08dceb44d7d0f22ec9488679695d976)
1 /*	$NetBSD: mux.c,v 1.16 2016/08/02 13:45:12 christos Exp $	*/
2 /* $OpenBSD: mux.c,v 1.60 2016/06/03 03:14:41 dtucker Exp $ */
3 /*
4  * Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 /* ssh session multiplexing support */
20 
21 /*
22  * TODO:
23  *   - Better signalling from master to slave, especially passing of
24  *      error messages
25  *   - Better fall-back from mux slave error to new connection.
26  *   - ExitOnForwardingFailure
27  *   - Maybe extension mechanisms for multi-X11/multi-agent forwarding
28  *   - Support ~^Z in mux slaves.
29  *   - Inspect or control sessions in master.
30  *   - If we ever support the "signal" channel request, send signals on
31  *     sessions in master.
32  */
33 
34 #include "includes.h"
35 __RCSID("$NetBSD: mux.c,v 1.16 2016/08/02 13:45:12 christos Exp $");
36 #include <sys/types.h>
37 #include <sys/queue.h>
38 #include <sys/stat.h>
39 #include <sys/socket.h>
40 #include <sys/un.h>
41 
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <poll.h>
45 #include <signal.h>
46 #include <stdarg.h>
47 #include <stddef.h>
48 #include <stdlib.h>
49 #include <stdio.h>
50 #include <string.h>
51 #include <unistd.h>
52 #include <util.h>
53 #include <paths.h>
54 
55 #include "atomicio.h"
56 #include "xmalloc.h"
57 #include "log.h"
58 #include "ssh.h"
59 #include "ssh2.h"
60 #include "pathnames.h"
61 #include "misc.h"
62 #include "match.h"
63 #include "buffer.h"
64 #include "channels.h"
65 #include "msg.h"
66 #include "packet.h"
67 #include "monitor_fdpass.h"
68 #include "sshpty.h"
69 #include "key.h"
70 #include "readconf.h"
71 #include "clientloop.h"
72 
73 /* from ssh.c */
74 extern int tty_flag;
75 extern Options options;
76 extern int stdin_null_flag;
77 extern char *host;
78 extern int subsystem_flag;
79 extern Buffer command;
80 extern volatile sig_atomic_t quit_pending;
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 = xreallocarray(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 	    (options.remote_forwards[fctx->fid].connect_path == NULL &&
586 	    options.remote_forwards[fctx->fid].connect_host == NULL)) {
587 		xasprintf(&failmsg, "unknown forwarding id %d", fctx->fid);
588 		goto fail;
589 	}
590 	rfwd = &options.remote_forwards[fctx->fid];
591 	debug("%s: %s for: listen %d, connect %s:%d", __func__,
592 	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
593 	    rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
594 	    rfwd->connect_host, rfwd->connect_port);
595 	if (type == SSH2_MSG_REQUEST_SUCCESS) {
596 		if (rfwd->listen_port == 0) {
597 			rfwd->allocated_port = packet_get_int();
598 			debug("Allocated port %u for mux remote forward"
599 			    " to %s:%d", rfwd->allocated_port,
600 			    rfwd->connect_host, rfwd->connect_port);
601 			buffer_put_int(&out, MUX_S_REMOTE_PORT);
602 			buffer_put_int(&out, fctx->rid);
603 			buffer_put_int(&out, rfwd->allocated_port);
604 			channel_update_permitted_opens(rfwd->handle,
605 			   rfwd->allocated_port);
606 		} else {
607 			buffer_put_int(&out, MUX_S_OK);
608 			buffer_put_int(&out, fctx->rid);
609 		}
610 		goto out;
611 	} else {
612 		if (rfwd->listen_port == 0)
613 			channel_update_permitted_opens(rfwd->handle, -1);
614 		if (rfwd->listen_path != NULL)
615 			xasprintf(&failmsg, "remote port forwarding failed for "
616 			    "listen path %s", rfwd->listen_path);
617 		else
618 			xasprintf(&failmsg, "remote port forwarding failed for "
619 			    "listen port %d", rfwd->listen_port);
620 
621                 debug2("%s: clearing registered forwarding for listen %d, "
622 		    "connect %s:%d", __func__, rfwd->listen_port,
623 		    rfwd->connect_path ? rfwd->connect_path :
624 		    rfwd->connect_host, rfwd->connect_port);
625 
626 		free(rfwd->listen_host);
627 		free(rfwd->listen_path);
628 		free(rfwd->connect_host);
629 		free(rfwd->connect_path);
630 		memset(rfwd, 0, sizeof(*rfwd));
631 	}
632  fail:
633 	error("%s: %s", __func__, failmsg);
634 	buffer_put_int(&out, MUX_S_FAILURE);
635 	buffer_put_int(&out, fctx->rid);
636 	buffer_put_cstring(&out, failmsg);
637 	free(failmsg);
638  out:
639 	buffer_put_string(&c->output, buffer_ptr(&out), buffer_len(&out));
640 	buffer_free(&out);
641 	if (c->mux_pause <= 0)
642 		fatal("%s: mux_pause %d", __func__, c->mux_pause);
643 	c->mux_pause = 0; /* start processing messages again */
644 }
645 
646 static int
647 process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
648 {
649 	struct Forward fwd;
650 	char *fwd_desc = NULL;
651 	char *listen_addr, *connect_addr;
652 	u_int ftype;
653 	u_int lport, cport;
654 	int i, ret = 0, freefwd = 1;
655 
656 	memset(&fwd, 0, sizeof(fwd));
657 
658 	/* XXX - lport/cport check redundant */
659 	if (buffer_get_int_ret(&ftype, m) != 0 ||
660 	    (listen_addr = buffer_get_string_ret(m, NULL)) == NULL ||
661 	    buffer_get_int_ret(&lport, m) != 0 ||
662 	    (connect_addr = buffer_get_string_ret(m, NULL)) == NULL ||
663 	    buffer_get_int_ret(&cport, m) != 0 ||
664 	    (lport != (u_int)PORT_STREAMLOCAL && lport > 65535) ||
665 	    (cport != (u_int)PORT_STREAMLOCAL && cport > 65535)) {
666 		error("%s: malformed message", __func__);
667 		ret = -1;
668 		goto out;
669 	}
670 	if (*listen_addr == '\0') {
671 		free(listen_addr);
672 		listen_addr = NULL;
673 	}
674 	if (*connect_addr == '\0') {
675 		free(connect_addr);
676 		connect_addr = NULL;
677 	}
678 
679 	memset(&fwd, 0, sizeof(fwd));
680 	fwd.listen_port = lport;
681 	if (fwd.listen_port == PORT_STREAMLOCAL)
682 		fwd.listen_path = listen_addr;
683 	else
684 		fwd.listen_host = listen_addr;
685 	fwd.connect_port = cport;
686 	if (fwd.connect_port == PORT_STREAMLOCAL)
687 		fwd.connect_path = connect_addr;
688 	else
689 		fwd.connect_host = connect_addr;
690 
691 	debug2("%s: channel %d: request %s", __func__, c->self,
692 	    (fwd_desc = format_forward(ftype, &fwd)));
693 
694 	if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
695 	    ftype != MUX_FWD_DYNAMIC) {
696 		logit("%s: invalid forwarding type %u", __func__, ftype);
697  invalid:
698 		free(listen_addr);
699 		free(connect_addr);
700 		buffer_put_int(r, MUX_S_FAILURE);
701 		buffer_put_int(r, rid);
702 		buffer_put_cstring(r, "Invalid forwarding request");
703 		return 0;
704 	}
705 	if (ftype == MUX_FWD_DYNAMIC && fwd.listen_path) {
706 		logit("%s: streamlocal and dynamic forwards "
707 		    "are mutually exclusive", __func__);
708 		goto invalid;
709 	}
710 	if (fwd.listen_port != PORT_STREAMLOCAL && fwd.listen_port >= 65536) {
711 		logit("%s: invalid listen port %u", __func__,
712 		    fwd.listen_port);
713 		goto invalid;
714 	}
715 	if ((fwd.connect_port != PORT_STREAMLOCAL && fwd.connect_port >= 65536)
716 	    || (ftype != MUX_FWD_DYNAMIC && ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
717 		logit("%s: invalid connect port %u", __func__,
718 		    fwd.connect_port);
719 		goto invalid;
720 	}
721 	if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL && fwd.connect_path == NULL) {
722 		logit("%s: missing connect host", __func__);
723 		goto invalid;
724 	}
725 
726 	/* Skip forwards that have already been requested */
727 	switch (ftype) {
728 	case MUX_FWD_LOCAL:
729 	case MUX_FWD_DYNAMIC:
730 		for (i = 0; i < options.num_local_forwards; i++) {
731 			if (compare_forward(&fwd,
732 			    options.local_forwards + i)) {
733  exists:
734 				debug2("%s: found existing forwarding",
735 				    __func__);
736 				buffer_put_int(r, MUX_S_OK);
737 				buffer_put_int(r, rid);
738 				goto out;
739 			}
740 		}
741 		break;
742 	case MUX_FWD_REMOTE:
743 		for (i = 0; i < options.num_remote_forwards; i++) {
744 			if (compare_forward(&fwd,
745 			    options.remote_forwards + i)) {
746 				if (fwd.listen_port != 0)
747 					goto exists;
748 				debug2("%s: found allocated port",
749 				    __func__);
750 				buffer_put_int(r, MUX_S_REMOTE_PORT);
751 				buffer_put_int(r, rid);
752 				buffer_put_int(r,
753 				    options.remote_forwards[i].allocated_port);
754 				goto out;
755 			}
756 		}
757 		break;
758 	}
759 
760 	if (options.control_master == SSHCTL_MASTER_ASK ||
761 	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
762 		if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
763 			debug2("%s: forwarding refused by user", __func__);
764 			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
765 			buffer_put_int(r, rid);
766 			buffer_put_cstring(r, "Permission denied");
767 			goto out;
768 		}
769 	}
770 
771 	if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
772 		if (!channel_setup_local_fwd_listener(&fwd,
773 		    &options.fwd_opts)) {
774  fail:
775 			logit("slave-requested %s failed", fwd_desc);
776 			buffer_put_int(r, MUX_S_FAILURE);
777 			buffer_put_int(r, rid);
778 			buffer_put_cstring(r, "Port forwarding failed");
779 			goto out;
780 		}
781 		add_local_forward(&options, &fwd);
782 		freefwd = 0;
783 	} else {
784 		struct mux_channel_confirm_ctx *fctx;
785 
786 		fwd.handle = channel_request_remote_forwarding(&fwd);
787 		if (fwd.handle < 0)
788 			goto fail;
789 		add_remote_forward(&options, &fwd);
790 		fctx = xcalloc(1, sizeof(*fctx));
791 		fctx->cid = c->self;
792 		fctx->rid = rid;
793 		fctx->fid = options.num_remote_forwards - 1;
794 		client_register_global_confirm(mux_confirm_remote_forward,
795 		    fctx);
796 		freefwd = 0;
797 		c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
798 		/* delayed reply in mux_confirm_remote_forward */
799 		goto out;
800 	}
801 	buffer_put_int(r, MUX_S_OK);
802 	buffer_put_int(r, rid);
803  out:
804 	free(fwd_desc);
805 	if (freefwd) {
806 		free(fwd.listen_host);
807 		free(fwd.listen_path);
808 		free(fwd.connect_host);
809 		free(fwd.connect_path);
810 	}
811 	return ret;
812 }
813 
814 static int
815 process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
816 {
817 	struct Forward fwd, *found_fwd;
818 	char *fwd_desc = NULL;
819 	const char *error_reason = NULL;
820 	char *listen_addr = NULL, *connect_addr = NULL;
821 	u_int ftype;
822 	int i, ret = 0;
823 	u_int lport, cport;
824 
825 	memset(&fwd, 0, sizeof(fwd));
826 
827 	if (buffer_get_int_ret(&ftype, m) != 0 ||
828 	    (listen_addr = buffer_get_string_ret(m, NULL)) == NULL ||
829 	    buffer_get_int_ret(&lport, m) != 0 ||
830 	    (connect_addr = buffer_get_string_ret(m, NULL)) == NULL ||
831 	    buffer_get_int_ret(&cport, m) != 0 ||
832 	    (lport != (u_int)PORT_STREAMLOCAL && lport > 65535) ||
833 	    (cport != (u_int)PORT_STREAMLOCAL && cport > 65535)) {
834 		error("%s: malformed message", __func__);
835 		ret = -1;
836 		goto out;
837 	}
838 
839 	if (*listen_addr == '\0') {
840 		free(listen_addr);
841 		listen_addr = NULL;
842 	}
843 	if (*connect_addr == '\0') {
844 		free(connect_addr);
845 		connect_addr = NULL;
846 	}
847 
848 	memset(&fwd, 0, sizeof(fwd));
849 	fwd.listen_port = lport;
850 	if (fwd.listen_port == PORT_STREAMLOCAL)
851 		fwd.listen_path = listen_addr;
852 	else
853 		fwd.listen_host = listen_addr;
854 	fwd.connect_port = cport;
855 	if (fwd.connect_port == PORT_STREAMLOCAL)
856 		fwd.connect_path = connect_addr;
857 	else
858 		fwd.connect_host = connect_addr;
859 
860 	debug2("%s: channel %d: request cancel %s", __func__, c->self,
861 	    (fwd_desc = format_forward(ftype, &fwd)));
862 
863 	/* make sure this has been requested */
864 	found_fwd = NULL;
865 	switch (ftype) {
866 	case MUX_FWD_LOCAL:
867 	case MUX_FWD_DYNAMIC:
868 		for (i = 0; i < options.num_local_forwards; i++) {
869 			if (compare_forward(&fwd,
870 			    options.local_forwards + i)) {
871 				found_fwd = options.local_forwards + i;
872 				break;
873 			}
874 		}
875 		break;
876 	case MUX_FWD_REMOTE:
877 		for (i = 0; i < options.num_remote_forwards; i++) {
878 			if (compare_forward(&fwd,
879 			    options.remote_forwards + i)) {
880 				found_fwd = options.remote_forwards + i;
881 				break;
882 			}
883 		}
884 		break;
885 	}
886 
887 	if (found_fwd == NULL)
888 		error_reason = "port not forwarded";
889 	else if (ftype == MUX_FWD_REMOTE) {
890 		/*
891 		 * This shouldn't fail unless we confused the host/port
892 		 * between options.remote_forwards and permitted_opens.
893 		 * However, for dynamic allocated listen ports we need
894 		 * to use the actual listen port.
895 		 */
896 		if (channel_request_rforward_cancel(found_fwd) == -1)
897 			error_reason = "port not in permitted opens";
898 	} else {	/* local and dynamic forwards */
899 		/* Ditto */
900 		if (channel_cancel_lport_listener(&fwd, fwd.connect_port,
901 		    &options.fwd_opts) == -1)
902 			error_reason = "port not found";
903 	}
904 
905 	if (error_reason == NULL) {
906 		buffer_put_int(r, MUX_S_OK);
907 		buffer_put_int(r, rid);
908 
909 		free(found_fwd->listen_host);
910 		free(found_fwd->listen_path);
911 		free(found_fwd->connect_host);
912 		free(found_fwd->connect_path);
913 		found_fwd->listen_host = found_fwd->connect_host = NULL;
914 		found_fwd->listen_path = found_fwd->connect_path = NULL;
915 		found_fwd->listen_port = found_fwd->connect_port = 0;
916 	} else {
917 		buffer_put_int(r, MUX_S_FAILURE);
918 		buffer_put_int(r, rid);
919 		buffer_put_cstring(r, error_reason);
920 	}
921  out:
922 	free(fwd_desc);
923 	free(listen_addr);
924 	free(connect_addr);
925 
926 	return ret;
927 }
928 
929 static int
930 process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
931 {
932 	Channel *nc;
933 	char *reserved, *chost;
934 	u_int cport, i, j;
935 	int new_fd[2];
936 	struct mux_stdio_confirm_ctx *cctx;
937 
938 	chost = reserved = NULL;
939 	if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
940 	   (chost = buffer_get_string_ret(m, NULL)) == NULL ||
941 	    buffer_get_int_ret(&cport, m) != 0) {
942 		free(reserved);
943 		free(chost);
944 		error("%s: malformed message", __func__);
945 		return -1;
946 	}
947 	free(reserved);
948 
949 	debug2("%s: channel %d: request stdio fwd to %s:%u",
950 	    __func__, c->self, chost, cport);
951 
952 	/* Gather fds from client */
953 	for(i = 0; i < 2; i++) {
954 		if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
955 			error("%s: failed to receive fd %d from slave",
956 			    __func__, i);
957 			for (j = 0; j < i; j++)
958 				close(new_fd[j]);
959 			free(chost);
960 
961 			/* prepare reply */
962 			buffer_put_int(r, MUX_S_FAILURE);
963 			buffer_put_int(r, rid);
964 			buffer_put_cstring(r,
965 			    "did not receive file descriptors");
966 			return -1;
967 		}
968 	}
969 
970 	debug3("%s: got fds stdin %d, stdout %d", __func__,
971 	    new_fd[0], new_fd[1]);
972 
973 	/* XXX support multiple child sessions in future */
974 	if (c->remote_id != -1) {
975 		debug2("%s: session already open", __func__);
976 		/* prepare reply */
977 		buffer_put_int(r, MUX_S_FAILURE);
978 		buffer_put_int(r, rid);
979 		buffer_put_cstring(r, "Multiple sessions not supported");
980  cleanup:
981 		close(new_fd[0]);
982 		close(new_fd[1]);
983 		free(chost);
984 		return 0;
985 	}
986 
987 	if (options.control_master == SSHCTL_MASTER_ASK ||
988 	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
989 		if (!ask_permission("Allow forward to %s:%u? ",
990 		    chost, cport)) {
991 			debug2("%s: stdio fwd refused by user", __func__);
992 			/* prepare reply */
993 			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
994 			buffer_put_int(r, rid);
995 			buffer_put_cstring(r, "Permission denied");
996 			goto cleanup;
997 		}
998 	}
999 
1000 	/* enable nonblocking unless tty */
1001 	if (!isatty(new_fd[0]))
1002 		set_nonblock(new_fd[0]);
1003 	if (!isatty(new_fd[1]))
1004 		set_nonblock(new_fd[1]);
1005 
1006 	nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
1007 
1008 	nc->ctl_chan = c->self;		/* link session -> control channel */
1009 	c->remote_id = nc->self; 	/* link control -> session channel */
1010 
1011 	debug2("%s: channel_new: %d linked to control channel %d",
1012 	    __func__, nc->self, nc->ctl_chan);
1013 
1014 	channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
1015 
1016 	cctx = xcalloc(1, sizeof(*cctx));
1017 	cctx->rid = rid;
1018 	channel_register_open_confirm(nc->self, mux_stdio_confirm, cctx);
1019 	c->mux_pause = 1; /* stop handling messages until open_confirm done */
1020 
1021 	/* reply is deferred, sent by mux_session_confirm */
1022 	return 0;
1023 }
1024 
1025 /* Callback on open confirmation in mux master for a mux stdio fwd session. */
1026 static void
1027 mux_stdio_confirm(int id, int success, void *arg)
1028 {
1029 	struct mux_stdio_confirm_ctx *cctx = arg;
1030 	Channel *c, *cc;
1031 	Buffer reply;
1032 
1033 	if (cctx == NULL)
1034 		fatal("%s: cctx == NULL", __func__);
1035 	if ((c = channel_by_id(id)) == NULL)
1036 		fatal("%s: no channel for id %d", __func__, id);
1037 	if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1038 		fatal("%s: channel %d lacks control channel %d", __func__,
1039 		    id, c->ctl_chan);
1040 
1041 	if (!success) {
1042 		debug3("%s: sending failure reply", __func__);
1043 		/* prepare reply */
1044 		buffer_init(&reply);
1045 		buffer_put_int(&reply, MUX_S_FAILURE);
1046 		buffer_put_int(&reply, cctx->rid);
1047 		buffer_put_cstring(&reply, "Session open refused by peer");
1048 		goto done;
1049 	}
1050 
1051 	debug3("%s: sending success reply", __func__);
1052 	/* prepare reply */
1053 	buffer_init(&reply);
1054 	buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1055 	buffer_put_int(&reply, cctx->rid);
1056 	buffer_put_int(&reply, c->self);
1057 
1058  done:
1059 	/* Send reply */
1060 	buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1061 	buffer_free(&reply);
1062 
1063 	if (cc->mux_pause <= 0)
1064 		fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1065 	cc->mux_pause = 0; /* start processing messages again */
1066 	c->open_confirm_ctx = NULL;
1067 	free(cctx);
1068 }
1069 
1070 static int
1071 process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
1072 {
1073 	debug("%s: channel %d: stop listening", __func__, c->self);
1074 
1075 	if (options.control_master == SSHCTL_MASTER_ASK ||
1076 	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
1077 		if (!ask_permission("Disable further multiplexing on shared "
1078 		    "connection to %s? ", host)) {
1079 			debug2("%s: stop listen refused by user", __func__);
1080 			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
1081 			buffer_put_int(r, rid);
1082 			buffer_put_cstring(r, "Permission denied");
1083 			return 0;
1084 		}
1085 	}
1086 
1087 	if (mux_listener_channel != NULL) {
1088 		channel_free(mux_listener_channel);
1089 		client_stop_mux();
1090 		free(options.control_path);
1091 		options.control_path = NULL;
1092 		mux_listener_channel = NULL;
1093 		muxserver_sock = -1;
1094 	}
1095 
1096 	/* prepare reply */
1097 	buffer_put_int(r, MUX_S_OK);
1098 	buffer_put_int(r, rid);
1099 
1100 	return 0;
1101 }
1102 
1103 /* Channel callbacks fired on read/write from mux slave fd */
1104 static int
1105 mux_master_read_cb(Channel *c)
1106 {
1107 	struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
1108 	Buffer in, out;
1109 	const u_char *ptr;
1110 	u_int type, rid, have, i;
1111 	int ret = -1;
1112 
1113 	/* Setup ctx and  */
1114 	if (c->mux_ctx == NULL) {
1115 		state = xcalloc(1, sizeof(*state));
1116 		c->mux_ctx = state;
1117 		channel_register_cleanup(c->self,
1118 		    mux_master_control_cleanup_cb, 0);
1119 
1120 		/* Send hello */
1121 		buffer_init(&out);
1122 		buffer_put_int(&out, MUX_MSG_HELLO);
1123 		buffer_put_int(&out, SSHMUX_VER);
1124 		/* no extensions */
1125 		buffer_put_string(&c->output, buffer_ptr(&out),
1126 		    buffer_len(&out));
1127 		buffer_free(&out);
1128 		debug3("%s: channel %d: hello sent", __func__, c->self);
1129 		return 0;
1130 	}
1131 
1132 	buffer_init(&in);
1133 	buffer_init(&out);
1134 
1135 	/* Channel code ensures that we receive whole packets */
1136 	if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
1137  malf:
1138 		error("%s: malformed message", __func__);
1139 		goto out;
1140 	}
1141 	buffer_append(&in, ptr, have);
1142 
1143 	if (buffer_get_int_ret(&type, &in) != 0)
1144 		goto malf;
1145 	debug3("%s: channel %d packet type 0x%08x len %u",
1146 	    __func__, c->self, type, buffer_len(&in));
1147 
1148 	if (type == MUX_MSG_HELLO)
1149 		rid = 0;
1150 	else {
1151 		if (!state->hello_rcvd) {
1152 			error("%s: expected MUX_MSG_HELLO(0x%08x), "
1153 			    "received 0x%08x", __func__, MUX_MSG_HELLO, type);
1154 			goto out;
1155 		}
1156 		if (buffer_get_int_ret(&rid, &in) != 0)
1157 			goto malf;
1158 	}
1159 
1160 	for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
1161 		if (type == mux_master_handlers[i].type) {
1162 			ret = mux_master_handlers[i].handler(rid, c, &in, &out);
1163 			break;
1164 		}
1165 	}
1166 	if (mux_master_handlers[i].handler == NULL) {
1167 		error("%s: unsupported mux message 0x%08x", __func__, type);
1168 		buffer_put_int(&out, MUX_S_FAILURE);
1169 		buffer_put_int(&out, rid);
1170 		buffer_put_cstring(&out, "unsupported request");
1171 		ret = 0;
1172 	}
1173 	/* Enqueue reply packet */
1174 	if (buffer_len(&out) != 0) {
1175 		buffer_put_string(&c->output, buffer_ptr(&out),
1176 		    buffer_len(&out));
1177 	}
1178  out:
1179 	buffer_free(&in);
1180 	buffer_free(&out);
1181 	return ret;
1182 }
1183 
1184 void
1185 mux_exit_message(Channel *c, int exitval)
1186 {
1187 	Buffer m;
1188 	Channel *mux_chan;
1189 
1190 	debug3("%s: channel %d: exit message, exitval %d", __func__, c->self,
1191 	    exitval);
1192 
1193 	if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1194 		fatal("%s: channel %d missing mux channel %d",
1195 		    __func__, c->self, c->ctl_chan);
1196 
1197 	/* Append exit message packet to control socket output queue */
1198 	buffer_init(&m);
1199 	buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
1200 	buffer_put_int(&m, c->self);
1201 	buffer_put_int(&m, exitval);
1202 
1203 	buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1204 	buffer_free(&m);
1205 }
1206 
1207 void
1208 mux_tty_alloc_failed(Channel *c)
1209 {
1210 	Buffer m;
1211 	Channel *mux_chan;
1212 
1213 	debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
1214 
1215 	if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1216 		fatal("%s: channel %d missing mux channel %d",
1217 		    __func__, c->self, c->ctl_chan);
1218 
1219 	/* Append exit message packet to control socket output queue */
1220 	buffer_init(&m);
1221 	buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
1222 	buffer_put_int(&m, c->self);
1223 
1224 	buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1225 	buffer_free(&m);
1226 }
1227 
1228 /* Prepare a mux master to listen on a Unix domain socket. */
1229 void
1230 muxserver_listen(void)
1231 {
1232 	mode_t old_umask;
1233 	char *orig_control_path = options.control_path;
1234 	char rbuf[16+1];
1235 	u_int i, r;
1236 	int oerrno;
1237 
1238 	if (options.control_path == NULL ||
1239 	    options.control_master == SSHCTL_MASTER_NO)
1240 		return;
1241 
1242 	debug("setting up multiplex master socket");
1243 
1244 	/*
1245 	 * Use a temporary path before listen so we can pseudo-atomically
1246 	 * establish the listening socket in its final location to avoid
1247 	 * other processes racing in between bind() and listen() and hitting
1248 	 * an unready socket.
1249 	 */
1250 	for (i = 0; i < sizeof(rbuf) - 1; i++) {
1251 		r = arc4random_uniform(26+26+10);
1252 		rbuf[i] = (r < 26) ? 'a' + r :
1253 		    (r < 26*2) ? 'A' + r - 26 :
1254 		    '0' + r - 26 - 26;
1255 	}
1256 	rbuf[sizeof(rbuf) - 1] = '\0';
1257 	options.control_path = NULL;
1258 	xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
1259 	debug3("%s: temporary control path %s", __func__, options.control_path);
1260 
1261 	old_umask = umask(0177);
1262 	muxserver_sock = unix_listener(options.control_path, 64, 0);
1263 	oerrno = errno;
1264 	umask(old_umask);
1265 	if (muxserver_sock < 0) {
1266 		if (oerrno == EINVAL || oerrno == EADDRINUSE) {
1267 			error("ControlSocket %s already exists, "
1268 			    "disabling multiplexing", options.control_path);
1269  disable_mux_master:
1270 			if (muxserver_sock != -1) {
1271 				close(muxserver_sock);
1272 				muxserver_sock = -1;
1273 			}
1274 			free(orig_control_path);
1275 			free(options.control_path);
1276 			options.control_path = NULL;
1277 			options.control_master = SSHCTL_MASTER_NO;
1278 			return;
1279 		} else {
1280 			/* unix_listener() logs the error */
1281 			cleanup_exit(255);
1282 		}
1283 	}
1284 
1285 	/* Now atomically "move" the mux socket into position */
1286 	if (link(options.control_path, orig_control_path) != 0) {
1287 		if (errno != EEXIST) {
1288 			fatal("%s: link mux listener %s => %s: %s", __func__,
1289 			    options.control_path, orig_control_path,
1290 			    strerror(errno));
1291 		}
1292 		error("ControlSocket %s already exists, disabling multiplexing",
1293 		    orig_control_path);
1294 		unlink(options.control_path);
1295 		goto disable_mux_master;
1296 	}
1297 	unlink(options.control_path);
1298 	free(options.control_path);
1299 	options.control_path = orig_control_path;
1300 
1301 	set_nonblock(muxserver_sock);
1302 
1303 	mux_listener_channel = channel_new("mux listener",
1304 	    SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
1305 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1306 	    0, options.control_path, 1);
1307 	mux_listener_channel->mux_rcb = mux_master_read_cb;
1308 	debug3("%s: mux listener channel %d fd %d", __func__,
1309 	    mux_listener_channel->self, mux_listener_channel->sock);
1310 }
1311 
1312 /* Callback on open confirmation in mux master for a mux client session. */
1313 static void
1314 mux_session_confirm(int id, int success, void *arg)
1315 {
1316 	struct mux_session_confirm_ctx *cctx = arg;
1317 	const char *display;
1318 	Channel *c, *cc;
1319 	int i;
1320 	Buffer reply;
1321 
1322 	if (cctx == NULL)
1323 		fatal("%s: cctx == NULL", __func__);
1324 	if ((c = channel_by_id(id)) == NULL)
1325 		fatal("%s: no channel for id %d", __func__, id);
1326 	if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1327 		fatal("%s: channel %d lacks control channel %d", __func__,
1328 		    id, c->ctl_chan);
1329 
1330 	if (!success) {
1331 		debug3("%s: sending failure reply", __func__);
1332 		/* prepare reply */
1333 		buffer_init(&reply);
1334 		buffer_put_int(&reply, MUX_S_FAILURE);
1335 		buffer_put_int(&reply, cctx->rid);
1336 		buffer_put_cstring(&reply, "Session open refused by peer");
1337 		goto done;
1338 	}
1339 
1340 	display = getenv("DISPLAY");
1341 	if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1342 		char *proto, *data;
1343 
1344 		/* Get reasonable local authentication information. */
1345 		if (client_x11_get_proto(display, options.xauth_location,
1346 		    options.forward_x11_trusted, options.forward_x11_timeout,
1347 		    &proto, &data) == 0) {
1348 			/* Request forwarding with authentication spoofing. */
1349 			debug("Requesting X11 forwarding with authentication "
1350 			    "spoofing.");
1351 			x11_request_forwarding_with_spoofing(id, display, proto,
1352 			    data, 1);
1353 			/* XXX exit_on_forward_failure */
1354 			client_expect_confirm(id, "X11 forwarding",
1355 			    CONFIRM_WARN);
1356 		}
1357 	}
1358 
1359 	if (cctx->want_agent_fwd && options.forward_agent) {
1360 		debug("Requesting authentication agent forwarding.");
1361 		channel_request_start(id, "auth-agent-req@openssh.com", 0);
1362 		packet_send();
1363 	}
1364 
1365 	client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1366 	    cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1367 
1368 	debug3("%s: sending success reply", __func__);
1369 	/* prepare reply */
1370 	buffer_init(&reply);
1371 	buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1372 	buffer_put_int(&reply, cctx->rid);
1373 	buffer_put_int(&reply, c->self);
1374 
1375  done:
1376 	/* Send reply */
1377 	buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1378 	buffer_free(&reply);
1379 
1380 	if (cc->mux_pause <= 0)
1381 		fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1382 	cc->mux_pause = 0; /* start processing messages again */
1383 	c->open_confirm_ctx = NULL;
1384 	buffer_free(&cctx->cmd);
1385 	free(cctx->term);
1386 	if (cctx->env != NULL) {
1387 		for (i = 0; cctx->env[i] != NULL; i++)
1388 			free(cctx->env[i]);
1389 		free(cctx->env);
1390 	}
1391 	free(cctx);
1392 }
1393 
1394 /* ** Multiplexing client support */
1395 
1396 /* Exit signal handler */
1397 static void
1398 control_client_sighandler(int signo)
1399 {
1400 	muxclient_terminate = signo;
1401 }
1402 
1403 /*
1404  * Relay signal handler - used to pass some signals from mux client to
1405  * mux master.
1406  */
1407 static void
1408 control_client_sigrelay(int signo)
1409 {
1410 	int save_errno = errno;
1411 
1412 	if (muxserver_pid > 1)
1413 		kill(muxserver_pid, signo);
1414 
1415 	errno = save_errno;
1416 }
1417 
1418 static int
1419 mux_client_read(int fd, Buffer *b, u_int need)
1420 {
1421 	u_int have;
1422 	ssize_t len;
1423 	u_char *p;
1424 	struct pollfd pfd;
1425 
1426 	pfd.fd = fd;
1427 	pfd.events = POLLIN;
1428 	p = buffer_append_space(b, need);
1429 	for (have = 0; have < need; ) {
1430 		if (muxclient_terminate) {
1431 			errno = EINTR;
1432 			return -1;
1433 		}
1434 		len = read(fd, p + have, need - have);
1435 		if (len < 0) {
1436 			switch (errno) {
1437 			case EAGAIN:
1438 				(void)poll(&pfd, 1, -1);
1439 				/* FALLTHROUGH */
1440 			case EINTR:
1441 				continue;
1442 			default:
1443 				return -1;
1444 			}
1445 		}
1446 		if (len == 0) {
1447 			errno = EPIPE;
1448 			return -1;
1449 		}
1450 		have += (u_int)len;
1451 	}
1452 	return 0;
1453 }
1454 
1455 static int
1456 mux_client_write_packet(int fd, Buffer *m)
1457 {
1458 	Buffer queue;
1459 	u_int have, need;
1460 	int oerrno, len;
1461 	u_char *ptr;
1462 	struct pollfd pfd;
1463 
1464 	pfd.fd = fd;
1465 	pfd.events = POLLOUT;
1466 	buffer_init(&queue);
1467 	buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1468 
1469 	need = buffer_len(&queue);
1470 	ptr = buffer_ptr(&queue);
1471 
1472 	for (have = 0; have < need; ) {
1473 		if (muxclient_terminate) {
1474 			buffer_free(&queue);
1475 			errno = EINTR;
1476 			return -1;
1477 		}
1478 		len = write(fd, ptr + have, need - have);
1479 		if (len < 0) {
1480 			switch (errno) {
1481 			case EAGAIN:
1482 				(void)poll(&pfd, 1, -1);
1483 				/* FALLTHROUGH */
1484 			case EINTR:
1485 				continue;
1486 			default:
1487 				oerrno = errno;
1488 				buffer_free(&queue);
1489 				errno = oerrno;
1490 				return -1;
1491 			}
1492 		}
1493 		if (len == 0) {
1494 			buffer_free(&queue);
1495 			errno = EPIPE;
1496 			return -1;
1497 		}
1498 		have += (u_int)len;
1499 	}
1500 	buffer_free(&queue);
1501 	return 0;
1502 }
1503 
1504 static int
1505 mux_client_read_packet(int fd, Buffer *m)
1506 {
1507 	Buffer queue;
1508 	u_int need, have;
1509 	const u_char *ptr;
1510 	int oerrno;
1511 
1512 	buffer_init(&queue);
1513 	if (mux_client_read(fd, &queue, 4) != 0) {
1514 		if ((oerrno = errno) == EPIPE)
1515 			debug3("%s: read header failed: %s", __func__,
1516 			    strerror(errno));
1517 		buffer_free(&queue);
1518 		errno = oerrno;
1519 		return -1;
1520 	}
1521 	need = get_u32(buffer_ptr(&queue));
1522 	if (mux_client_read(fd, &queue, need) != 0) {
1523 		oerrno = errno;
1524 		debug3("%s: read body failed: %s", __func__, strerror(errno));
1525 		buffer_free(&queue);
1526 		errno = oerrno;
1527 		return -1;
1528 	}
1529 	ptr = buffer_get_string_ptr(&queue, &have);
1530 	buffer_append(m, ptr, have);
1531 	buffer_free(&queue);
1532 	return 0;
1533 }
1534 
1535 static int
1536 mux_client_hello_exchange(int fd)
1537 {
1538 	Buffer m;
1539 	u_int type, ver;
1540 
1541 	buffer_init(&m);
1542 	buffer_put_int(&m, MUX_MSG_HELLO);
1543 	buffer_put_int(&m, SSHMUX_VER);
1544 	/* no extensions */
1545 
1546 	if (mux_client_write_packet(fd, &m) != 0)
1547 		fatal("%s: write packet: %s", __func__, strerror(errno));
1548 
1549 	buffer_clear(&m);
1550 
1551 	/* Read their HELLO */
1552 	if (mux_client_read_packet(fd, &m) != 0) {
1553 		buffer_free(&m);
1554 		return -1;
1555 	}
1556 
1557 	type = buffer_get_int(&m);
1558 	if (type != MUX_MSG_HELLO)
1559 		fatal("%s: expected HELLO (%u) received %u",
1560 		    __func__, MUX_MSG_HELLO, type);
1561 	ver = buffer_get_int(&m);
1562 	if (ver != SSHMUX_VER)
1563 		fatal("Unsupported multiplexing protocol version %d "
1564 		    "(expected %d)", ver, SSHMUX_VER);
1565 	debug2("%s: master version %u", __func__, ver);
1566 	/* No extensions are presently defined */
1567 	while (buffer_len(&m) > 0) {
1568 		char *name = buffer_get_string(&m, NULL);
1569 		char *value = buffer_get_string(&m, NULL);
1570 
1571 		debug2("Unrecognised master extension \"%s\"", name);
1572 		free(name);
1573 		free(value);
1574 	}
1575 	buffer_free(&m);
1576 	return 0;
1577 }
1578 
1579 static u_int
1580 mux_client_request_alive(int fd)
1581 {
1582 	Buffer m;
1583 	char *e;
1584 	u_int pid, type, rid;
1585 
1586 	debug3("%s: entering", __func__);
1587 
1588 	buffer_init(&m);
1589 	buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1590 	buffer_put_int(&m, muxclient_request_id);
1591 
1592 	if (mux_client_write_packet(fd, &m) != 0)
1593 		fatal("%s: write packet: %s", __func__, strerror(errno));
1594 
1595 	buffer_clear(&m);
1596 
1597 	/* Read their reply */
1598 	if (mux_client_read_packet(fd, &m) != 0) {
1599 		buffer_free(&m);
1600 		return 0;
1601 	}
1602 
1603 	type = buffer_get_int(&m);
1604 	if (type != MUX_S_ALIVE) {
1605 		e = buffer_get_string(&m, NULL);
1606 		fatal("%s: master returned error: %s", __func__, e);
1607 	}
1608 
1609 	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1610 		fatal("%s: out of sequence reply: my id %u theirs %u",
1611 		    __func__, muxclient_request_id, rid);
1612 	pid = buffer_get_int(&m);
1613 	buffer_free(&m);
1614 
1615 	debug3("%s: done pid = %u", __func__, pid);
1616 
1617 	muxclient_request_id++;
1618 
1619 	return pid;
1620 }
1621 
1622 static void
1623 mux_client_request_terminate(int fd)
1624 {
1625 	Buffer m;
1626 	char *e;
1627 	u_int type, rid;
1628 
1629 	debug3("%s: entering", __func__);
1630 
1631 	buffer_init(&m);
1632 	buffer_put_int(&m, MUX_C_TERMINATE);
1633 	buffer_put_int(&m, muxclient_request_id);
1634 
1635 	if (mux_client_write_packet(fd, &m) != 0)
1636 		fatal("%s: write packet: %s", __func__, strerror(errno));
1637 
1638 	buffer_clear(&m);
1639 
1640 	/* Read their reply */
1641 	if (mux_client_read_packet(fd, &m) != 0) {
1642 		/* Remote end exited already */
1643 		if (errno == EPIPE) {
1644 			buffer_free(&m);
1645 			return;
1646 		}
1647 		fatal("%s: read from master failed: %s",
1648 		    __func__, strerror(errno));
1649 	}
1650 
1651 	type = buffer_get_int(&m);
1652 	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1653 		fatal("%s: out of sequence reply: my id %u theirs %u",
1654 		    __func__, muxclient_request_id, rid);
1655 	switch (type) {
1656 	case MUX_S_OK:
1657 		break;
1658 	case MUX_S_PERMISSION_DENIED:
1659 		e = buffer_get_string(&m, NULL);
1660 		fatal("Master refused termination request: %s", e);
1661 	case MUX_S_FAILURE:
1662 		e = buffer_get_string(&m, NULL);
1663 		fatal("%s: termination request failed: %s", __func__, e);
1664 	default:
1665 		fatal("%s: unexpected response from master 0x%08x",
1666 		    __func__, type);
1667 	}
1668 	buffer_free(&m);
1669 	muxclient_request_id++;
1670 }
1671 
1672 static int
1673 mux_client_forward(int fd, int cancel_flag, u_int ftype, struct Forward *fwd)
1674 {
1675 	Buffer m;
1676 	char *e, *fwd_desc;
1677 	u_int type, rid;
1678 
1679 	fwd_desc = format_forward(ftype, fwd);
1680 	debug("Requesting %s %s",
1681 	    cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
1682 	free(fwd_desc);
1683 
1684 	buffer_init(&m);
1685 	buffer_put_int(&m, cancel_flag ? MUX_C_CLOSE_FWD : MUX_C_OPEN_FWD);
1686 	buffer_put_int(&m, muxclient_request_id);
1687 	buffer_put_int(&m, ftype);
1688 	if (fwd->listen_path != NULL) {
1689 		buffer_put_cstring(&m, fwd->listen_path);
1690 	} else {
1691 		buffer_put_cstring(&m,
1692 		    fwd->listen_host == NULL ? "" :
1693 		    (*fwd->listen_host == '\0' ? "*" : fwd->listen_host));
1694 	}
1695 	buffer_put_int(&m, fwd->listen_port);
1696 	if (fwd->connect_path != NULL) {
1697 		buffer_put_cstring(&m, fwd->connect_path);
1698 	} else {
1699 		buffer_put_cstring(&m,
1700 		    fwd->connect_host == NULL ? "" : fwd->connect_host);
1701 	}
1702 	buffer_put_int(&m, fwd->connect_port);
1703 
1704 	if (mux_client_write_packet(fd, &m) != 0)
1705 		fatal("%s: write packet: %s", __func__, strerror(errno));
1706 
1707 	buffer_clear(&m);
1708 
1709 	/* Read their reply */
1710 	if (mux_client_read_packet(fd, &m) != 0) {
1711 		buffer_free(&m);
1712 		return -1;
1713 	}
1714 
1715 	type = buffer_get_int(&m);
1716 	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1717 		fatal("%s: out of sequence reply: my id %u theirs %u",
1718 		    __func__, muxclient_request_id, rid);
1719 	switch (type) {
1720 	case MUX_S_OK:
1721 		break;
1722 	case MUX_S_REMOTE_PORT:
1723 		if (cancel_flag)
1724 			fatal("%s: got MUX_S_REMOTE_PORT for cancel", __func__);
1725 		fwd->allocated_port = buffer_get_int(&m);
1726 		verbose("Allocated port %u for remote forward to %s:%d",
1727 		    fwd->allocated_port,
1728 		    fwd->connect_host ? fwd->connect_host : "",
1729 		    fwd->connect_port);
1730 		if (muxclient_command == SSHMUX_COMMAND_FORWARD)
1731 			fprintf(stdout, "%i\n", fwd->allocated_port);
1732 		break;
1733 	case MUX_S_PERMISSION_DENIED:
1734 		e = buffer_get_string(&m, NULL);
1735 		buffer_free(&m);
1736 		error("Master refused forwarding request: %s", e);
1737 		return -1;
1738 	case MUX_S_FAILURE:
1739 		e = buffer_get_string(&m, NULL);
1740 		buffer_free(&m);
1741 		error("%s: forwarding request failed: %s", __func__, e);
1742 		return -1;
1743 	default:
1744 		fatal("%s: unexpected response from master 0x%08x",
1745 		    __func__, type);
1746 	}
1747 	buffer_free(&m);
1748 
1749 	muxclient_request_id++;
1750 	return 0;
1751 }
1752 
1753 static int
1754 mux_client_forwards(int fd, int cancel_flag)
1755 {
1756 	int i, ret = 0;
1757 
1758 	debug3("%s: %s forwardings: %d local, %d remote", __func__,
1759 	    cancel_flag ? "cancel" : "request",
1760 	    options.num_local_forwards, options.num_remote_forwards);
1761 
1762 	/* XXX ExitOnForwardingFailure */
1763 	for (i = 0; i < options.num_local_forwards; i++) {
1764 		if (mux_client_forward(fd, cancel_flag,
1765 		    options.local_forwards[i].connect_port == 0 ?
1766 		    MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1767 		    options.local_forwards + i) != 0)
1768 			ret = -1;
1769 	}
1770 	for (i = 0; i < options.num_remote_forwards; i++) {
1771 		if (mux_client_forward(fd, cancel_flag, MUX_FWD_REMOTE,
1772 		    options.remote_forwards + i) != 0)
1773 			ret = -1;
1774 	}
1775 	return ret;
1776 }
1777 
1778 static int
1779 mux_client_request_session(int fd)
1780 {
1781 	Buffer m;
1782 	char *e, *term;
1783 	u_int i, rid, sid, esid, exitval, type, exitval_seen;
1784 	extern char **environ;
1785 	int devnull, rawmode;
1786 
1787 	debug3("%s: entering", __func__);
1788 
1789 	if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1790 		error("%s: master alive request failed", __func__);
1791 		return -1;
1792 	}
1793 
1794 	signal(SIGPIPE, SIG_IGN);
1795 
1796 	if (stdin_null_flag) {
1797 		if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1798 			fatal("open(/dev/null): %s", strerror(errno));
1799 		if (dup2(devnull, STDIN_FILENO) == -1)
1800 			fatal("dup2: %s", strerror(errno));
1801 		if (devnull > STDERR_FILENO)
1802 			close(devnull);
1803 	}
1804 
1805 	term = getenv("TERM");
1806 
1807 	buffer_init(&m);
1808 	buffer_put_int(&m, MUX_C_NEW_SESSION);
1809 	buffer_put_int(&m, muxclient_request_id);
1810 	buffer_put_cstring(&m, ""); /* reserved */
1811 	buffer_put_int(&m, tty_flag);
1812 	buffer_put_int(&m, options.forward_x11);
1813 	buffer_put_int(&m, options.forward_agent);
1814 	buffer_put_int(&m, subsystem_flag);
1815 	buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1816 	    0xffffffff : (u_int)options.escape_char);
1817 	buffer_put_cstring(&m, term == NULL ? "" : term);
1818 	buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1819 
1820 	if (options.num_send_env > 0 && environ != NULL) {
1821 		/* Pass environment */
1822 		for (i = 0; environ[i] != NULL; i++) {
1823 			if (env_permitted(environ[i])) {
1824 				buffer_put_cstring(&m, environ[i]);
1825 			}
1826 		}
1827 	}
1828 
1829 	if (mux_client_write_packet(fd, &m) != 0)
1830 		fatal("%s: write packet: %s", __func__, strerror(errno));
1831 
1832 	/* Send the stdio file descriptors */
1833 	if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1834 	    mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1835 	    mm_send_fd(fd, STDERR_FILENO) == -1)
1836 		fatal("%s: send fds failed", __func__);
1837 
1838 	debug3("%s: session request sent", __func__);
1839 
1840 	/* Read their reply */
1841 	buffer_clear(&m);
1842 	if (mux_client_read_packet(fd, &m) != 0) {
1843 		error("%s: read from master failed: %s",
1844 		    __func__, strerror(errno));
1845 		buffer_free(&m);
1846 		return -1;
1847 	}
1848 
1849 	type = buffer_get_int(&m);
1850 	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1851 		fatal("%s: out of sequence reply: my id %u theirs %u",
1852 		    __func__, muxclient_request_id, rid);
1853 	switch (type) {
1854 	case MUX_S_SESSION_OPENED:
1855 		sid = buffer_get_int(&m);
1856 		debug("%s: master session id: %u", __func__, sid);
1857 		break;
1858 	case MUX_S_PERMISSION_DENIED:
1859 		e = buffer_get_string(&m, NULL);
1860 		buffer_free(&m);
1861 		error("Master refused session request: %s", e);
1862 		return -1;
1863 	case MUX_S_FAILURE:
1864 		e = buffer_get_string(&m, NULL);
1865 		buffer_free(&m);
1866 		error("%s: session request failed: %s", __func__, e);
1867 		return -1;
1868 	default:
1869 		buffer_free(&m);
1870 		error("%s: unexpected response from master 0x%08x",
1871 		    __func__, type);
1872 		return -1;
1873 	}
1874 	muxclient_request_id++;
1875 
1876 #ifdef __OpenBSD__
1877 	if (pledge("stdio proc tty", NULL) == -1)
1878 		fatal("%s pledge(): %s", __func__, strerror(errno));
1879 #endif
1880 
1881 	signal(SIGHUP, control_client_sighandler);
1882 	signal(SIGINT, control_client_sighandler);
1883 	signal(SIGTERM, control_client_sighandler);
1884 	signal(SIGWINCH, control_client_sigrelay);
1885 
1886 	rawmode = tty_flag;
1887 	if (tty_flag)
1888 		enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1889 
1890 	/*
1891 	 * Stick around until the controlee closes the client_fd.
1892 	 * Before it does, it is expected to write an exit message.
1893 	 * This process must read the value and wait for the closure of
1894 	 * the client_fd; if this one closes early, the multiplex master will
1895 	 * terminate early too (possibly losing data).
1896 	 */
1897 	for (exitval = 255, exitval_seen = 0;;) {
1898 		buffer_clear(&m);
1899 		if (mux_client_read_packet(fd, &m) != 0)
1900 			break;
1901 		type = buffer_get_int(&m);
1902 		switch (type) {
1903 		case MUX_S_TTY_ALLOC_FAIL:
1904 			if ((esid = buffer_get_int(&m)) != sid)
1905 				fatal("%s: tty alloc fail on unknown session: "
1906 				    "my id %u theirs %u",
1907 				    __func__, sid, esid);
1908 			leave_raw_mode(options.request_tty ==
1909 			    REQUEST_TTY_FORCE);
1910 			rawmode = 0;
1911 			continue;
1912 		case MUX_S_EXIT_MESSAGE:
1913 			if ((esid = buffer_get_int(&m)) != sid)
1914 				fatal("%s: exit on unknown session: "
1915 				    "my id %u theirs %u",
1916 				    __func__, sid, esid);
1917 			if (exitval_seen)
1918 				fatal("%s: exitval sent twice", __func__);
1919 			exitval = buffer_get_int(&m);
1920 			exitval_seen = 1;
1921 			continue;
1922 		default:
1923 			e = buffer_get_string(&m, NULL);
1924 			fatal("%s: master returned error: %s", __func__, e);
1925 		}
1926 	}
1927 
1928 	close(fd);
1929 	if (rawmode)
1930 		leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1931 
1932 	if (muxclient_terminate) {
1933 		debug2("Exiting on signal %ld", (long)muxclient_terminate);
1934 		exitval = 255;
1935 	} else if (!exitval_seen) {
1936 		debug2("Control master terminated unexpectedly");
1937 		exitval = 255;
1938 	} else
1939 		debug2("Received exit status from master %d", exitval);
1940 
1941 	if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1942 		fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1943 
1944 	exit(exitval);
1945 }
1946 
1947 static int
1948 mux_client_request_stdio_fwd(int fd)
1949 {
1950 	Buffer m;
1951 	char *e;
1952 	u_int type, rid, sid;
1953 	int devnull;
1954 
1955 	debug3("%s: entering", __func__);
1956 
1957 	if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1958 		error("%s: master alive request failed", __func__);
1959 		return -1;
1960 	}
1961 
1962 	signal(SIGPIPE, SIG_IGN);
1963 
1964 	if (stdin_null_flag) {
1965 		if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1966 			fatal("open(/dev/null): %s", strerror(errno));
1967 		if (dup2(devnull, STDIN_FILENO) == -1)
1968 			fatal("dup2: %s", strerror(errno));
1969 		if (devnull > STDERR_FILENO)
1970 			close(devnull);
1971 	}
1972 
1973 	buffer_init(&m);
1974 	buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
1975 	buffer_put_int(&m, muxclient_request_id);
1976 	buffer_put_cstring(&m, ""); /* reserved */
1977 	buffer_put_cstring(&m, options.stdio_forward_host);
1978 	buffer_put_int(&m, options.stdio_forward_port);
1979 
1980 	if (mux_client_write_packet(fd, &m) != 0)
1981 		fatal("%s: write packet: %s", __func__, strerror(errno));
1982 
1983 	/* Send the stdio file descriptors */
1984 	if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1985 	    mm_send_fd(fd, STDOUT_FILENO) == -1)
1986 		fatal("%s: send fds failed", __func__);
1987 
1988 #ifdef __OpenBSD__
1989 	if (pledge("stdio proc tty", NULL) == -1)
1990 		fatal("%s pledge(): %s", __func__, strerror(errno));
1991 #endif
1992 
1993 	debug3("%s: stdio forward request sent", __func__);
1994 
1995 	/* Read their reply */
1996 	buffer_clear(&m);
1997 
1998 	if (mux_client_read_packet(fd, &m) != 0) {
1999 		error("%s: read from master failed: %s",
2000 		    __func__, strerror(errno));
2001 		buffer_free(&m);
2002 		return -1;
2003 	}
2004 
2005 	type = buffer_get_int(&m);
2006 	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
2007 		fatal("%s: out of sequence reply: my id %u theirs %u",
2008 		    __func__, muxclient_request_id, rid);
2009 	switch (type) {
2010 	case MUX_S_SESSION_OPENED:
2011 		sid = buffer_get_int(&m);
2012 		debug("%s: master session id: %u", __func__, sid);
2013 		break;
2014 	case MUX_S_PERMISSION_DENIED:
2015 		e = buffer_get_string(&m, NULL);
2016 		buffer_free(&m);
2017 		fatal("Master refused stdio forwarding request: %s", e);
2018 	case MUX_S_FAILURE:
2019 		e = buffer_get_string(&m, NULL);
2020 		buffer_free(&m);
2021 		fatal("Stdio forwarding request failed: %s", e);
2022 	default:
2023 		buffer_free(&m);
2024 		error("%s: unexpected response from master 0x%08x",
2025 		    __func__, type);
2026 		return -1;
2027 	}
2028 	muxclient_request_id++;
2029 
2030 	signal(SIGHUP, control_client_sighandler);
2031 	signal(SIGINT, control_client_sighandler);
2032 	signal(SIGTERM, control_client_sighandler);
2033 	signal(SIGWINCH, control_client_sigrelay);
2034 
2035 	/*
2036 	 * Stick around until the controlee closes the client_fd.
2037 	 */
2038 	buffer_clear(&m);
2039 	if (mux_client_read_packet(fd, &m) != 0) {
2040 		if (errno == EPIPE ||
2041 		    (errno == EINTR && muxclient_terminate != 0))
2042 			return 0;
2043 		fatal("%s: mux_client_read_packet: %s",
2044 		    __func__, strerror(errno));
2045 	}
2046 	fatal("%s: master returned unexpected message %u", __func__, type);
2047 }
2048 
2049 static void
2050 mux_client_request_stop_listening(int fd)
2051 {
2052 	Buffer m;
2053 	char *e;
2054 	u_int type, rid;
2055 
2056 	debug3("%s: entering", __func__);
2057 
2058 	buffer_init(&m);
2059 	buffer_put_int(&m, MUX_C_STOP_LISTENING);
2060 	buffer_put_int(&m, muxclient_request_id);
2061 
2062 	if (mux_client_write_packet(fd, &m) != 0)
2063 		fatal("%s: write packet: %s", __func__, strerror(errno));
2064 
2065 	buffer_clear(&m);
2066 
2067 	/* Read their reply */
2068 	if (mux_client_read_packet(fd, &m) != 0)
2069 		fatal("%s: read from master failed: %s",
2070 		    __func__, strerror(errno));
2071 
2072 	type = buffer_get_int(&m);
2073 	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
2074 		fatal("%s: out of sequence reply: my id %u theirs %u",
2075 		    __func__, muxclient_request_id, rid);
2076 	switch (type) {
2077 	case MUX_S_OK:
2078 		break;
2079 	case MUX_S_PERMISSION_DENIED:
2080 		e = buffer_get_string(&m, NULL);
2081 		fatal("Master refused stop listening request: %s", e);
2082 	case MUX_S_FAILURE:
2083 		e = buffer_get_string(&m, NULL);
2084 		fatal("%s: stop listening request failed: %s", __func__, e);
2085 	default:
2086 		fatal("%s: unexpected response from master 0x%08x",
2087 		    __func__, type);
2088 	}
2089 	buffer_free(&m);
2090 	muxclient_request_id++;
2091 }
2092 
2093 /* Multiplex client main loop. */
2094 void
2095 muxclient(const char *path)
2096 {
2097 	struct sockaddr_un addr;
2098 	int sock;
2099 	u_int pid;
2100 
2101 	if (muxclient_command == 0) {
2102 		if (options.stdio_forward_host != NULL)
2103 			muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
2104 		else
2105 			muxclient_command = SSHMUX_COMMAND_OPEN;
2106 	}
2107 
2108 	switch (options.control_master) {
2109 	case SSHCTL_MASTER_AUTO:
2110 	case SSHCTL_MASTER_AUTO_ASK:
2111 		debug("auto-mux: Trying existing master");
2112 		/* FALLTHROUGH */
2113 	case SSHCTL_MASTER_NO:
2114 		break;
2115 	default:
2116 		return;
2117 	}
2118 
2119 	memset(&addr, '\0', sizeof(addr));
2120 	addr.sun_family = AF_UNIX;
2121 	addr.sun_len = offsetof(struct sockaddr_un, sun_path) +
2122 	    strlen(path) + 1;
2123 
2124 	if (strlcpy(addr.sun_path, path,
2125 	    sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
2126 		fatal("ControlPath too long");
2127 
2128 	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
2129 		fatal("%s socket(): %s", __func__, strerror(errno));
2130 
2131 	if (connect(sock, (struct sockaddr *)&addr, addr.sun_len) == -1) {
2132 		switch (muxclient_command) {
2133 		case SSHMUX_COMMAND_OPEN:
2134 		case SSHMUX_COMMAND_STDIO_FWD:
2135 			break;
2136 		default:
2137 			fatal("Control socket connect(%.100s): %s", path,
2138 			    strerror(errno));
2139 		}
2140 		if (errno == ECONNREFUSED &&
2141 		    options.control_master != SSHCTL_MASTER_NO) {
2142 			debug("Stale control socket %.100s, unlinking", path);
2143 			unlink(path);
2144 		} else if (errno == ENOENT) {
2145 			debug("Control socket \"%.100s\" does not exist", path);
2146 		} else {
2147 			error("Control socket connect(%.100s): %s", path,
2148 			    strerror(errno));
2149 		}
2150 		close(sock);
2151 		return;
2152 	}
2153 	set_nonblock(sock);
2154 
2155 	if (mux_client_hello_exchange(sock) != 0) {
2156 		error("%s: master hello exchange failed", __func__);
2157 		close(sock);
2158 		return;
2159 	}
2160 
2161 	switch (muxclient_command) {
2162 	case SSHMUX_COMMAND_ALIVE_CHECK:
2163 		if ((pid = mux_client_request_alive(sock)) == 0)
2164 			fatal("%s: master alive check failed", __func__);
2165 		fprintf(stderr, "Master running (pid=%u)\r\n", pid);
2166 		exit(0);
2167 	case SSHMUX_COMMAND_TERMINATE:
2168 		mux_client_request_terminate(sock);
2169 		fprintf(stderr, "Exit request sent.\r\n");
2170 		exit(0);
2171 	case SSHMUX_COMMAND_FORWARD:
2172 		if (mux_client_forwards(sock, 0) != 0)
2173 			fatal("%s: master forward request failed", __func__);
2174 		exit(0);
2175 	case SSHMUX_COMMAND_OPEN:
2176 		if (mux_client_forwards(sock, 0) != 0) {
2177 			error("%s: master forward request failed", __func__);
2178 			return;
2179 		}
2180 		mux_client_request_session(sock);
2181 		return;
2182 	case SSHMUX_COMMAND_STDIO_FWD:
2183 		mux_client_request_stdio_fwd(sock);
2184 		exit(0);
2185 	case SSHMUX_COMMAND_STOP:
2186 		mux_client_request_stop_listening(sock);
2187 		fprintf(stderr, "Stop listening request sent.\r\n");
2188 		exit(0);
2189 	case SSHMUX_COMMAND_CANCEL_FWD:
2190 		if (mux_client_forwards(sock, 1) != 0)
2191 			error("%s: master cancel forward request failed",
2192 			    __func__);
2193 		exit(0);
2194 	default:
2195 		fatal("unrecognised muxclient_command %d", muxclient_command);
2196 	}
2197 }
2198