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