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