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