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