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