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