xref: /netbsd-src/crypto/external/bsd/openssh/dist/mux.c (revision 6a493d6bc668897c91594964a732d38505b70cbb)
1 /*	$NetBSD: mux.c,v 1.9 2013/11/08 19:18:25 christos Exp $	*/
2 /* $OpenBSD: mux.c,v 1.44 2013/07/12 00:19:58 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.9 2013/11/08 19:18:25 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 		    sc->type != SSH_CHANNEL_OPENING) {
214 			debug2("%s: channel %d: not open", __func__, sc->self);
215 			chan_mark_dead(sc);
216 		} else {
217 			if (sc->istate == CHAN_INPUT_OPEN)
218 				chan_read_failed(sc);
219 			if (sc->ostate == CHAN_OUTPUT_OPEN)
220 				chan_write_failed(sc);
221 		}
222 	}
223 	channel_cancel_cleanup(c->self);
224 }
225 
226 /* Check mux client environment variables before passing them to mux master. */
227 static int
228 env_permitted(char *env)
229 {
230 	int i, ret;
231 	char name[1024], *cp;
232 
233 	if ((cp = strchr(env, '=')) == NULL || cp == env)
234 		return 0;
235 	ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
236 	if (ret <= 0 || (size_t)ret >= sizeof(name)) {
237 		error("env_permitted: name '%.100s...' too long", env);
238 		return 0;
239 	}
240 
241 	for (i = 0; i < options.num_send_env; i++)
242 		if (match_pattern(name, options.send_env[i]))
243 			return 1;
244 
245 	return 0;
246 }
247 
248 /* Mux master protocol message handlers */
249 
250 static int
251 process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
252 {
253 	u_int ver;
254 	struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
255 
256 	if (state == NULL)
257 		fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
258 	if (state->hello_rcvd) {
259 		error("%s: HELLO received twice", __func__);
260 		return -1;
261 	}
262 	if (buffer_get_int_ret(&ver, m) != 0) {
263  malf:
264 		error("%s: malformed message", __func__);
265 		return -1;
266 	}
267 	if (ver != SSHMUX_VER) {
268 		error("Unsupported multiplexing protocol version %d "
269 		    "(expected %d)", ver, SSHMUX_VER);
270 		return -1;
271 	}
272 	debug2("%s: channel %d slave version %u", __func__, c->self, ver);
273 
274 	/* No extensions are presently defined */
275 	while (buffer_len(m) > 0) {
276 		char *name = buffer_get_string_ret(m, NULL);
277 		char *value = buffer_get_string_ret(m, NULL);
278 
279 		if (name == NULL || value == NULL) {
280 			free(name);
281 			free(value);
282 			goto malf;
283 		}
284 		debug2("Unrecognised slave extension \"%s\"", name);
285 		free(name);
286 		free(value);
287 	}
288 	state->hello_rcvd = 1;
289 	return 0;
290 }
291 
292 static int
293 process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
294 {
295 	Channel *nc;
296 	struct mux_session_confirm_ctx *cctx;
297 	char *reserved, *cmd, *cp;
298 	u_int i, j, len, env_len, escape_char, window, packetmax;
299 	int new_fd[3];
300 
301 	/* Reply for SSHMUX_COMMAND_OPEN */
302 	cctx = xcalloc(1, sizeof(*cctx));
303 	cctx->term = NULL;
304 	cctx->rid = rid;
305 	cmd = reserved = NULL;
306 	cctx->env = NULL;
307 	env_len = 0;
308 	if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
309 	    buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
310 	    buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
311 	    buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
312 	    buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
313 	    buffer_get_int_ret(&escape_char, m) != 0 ||
314 	    (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
315 	    (cmd = buffer_get_string_ret(m, &len)) == NULL) {
316  malf:
317 		free(cmd);
318 		free(reserved);
319 		for (j = 0; j < env_len; j++)
320 			free(cctx->env[j]);
321 		free(cctx->env);
322 		free(cctx->term);
323 		free(cctx);
324 		error("%s: malformed message", __func__);
325 		return -1;
326 	}
327 	free(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 			free(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 	free(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 				free(cctx->env[j]);
368 			free(cctx->env);
369 			free(cctx->term);
370 			buffer_free(&cctx->cmd);
371 			free(cctx);
372 
373 			/* prepare reply */
374 			buffer_put_int(r, MUX_S_FAILURE);
375 			buffer_put_int(r, rid);
376 			buffer_put_cstring(r,
377 			    "did not receive file descriptors");
378 			return -1;
379 		}
380 	}
381 
382 	debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
383 	    new_fd[0], new_fd[1], new_fd[2]);
384 
385 	/* XXX support multiple child sessions in future */
386 	if (c->remote_id != -1) {
387 		debug2("%s: session already open", __func__);
388 		/* prepare reply */
389 		buffer_put_int(r, MUX_S_FAILURE);
390 		buffer_put_int(r, rid);
391 		buffer_put_cstring(r, "Multiple sessions not supported");
392  cleanup:
393 		close(new_fd[0]);
394 		close(new_fd[1]);
395 		close(new_fd[2]);
396 		free(cctx->term);
397 		if (env_len != 0) {
398 			for (i = 0; i < env_len; i++)
399 				free(cctx->env[i]);
400 			free(cctx->env);
401 		}
402 		buffer_free(&cctx->cmd);
403 		free(cctx);
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 			channel_update_permitted_opens(rfwd->handle,
591 			   rfwd->allocated_port);
592 		} else {
593 			buffer_put_int(&out, MUX_S_OK);
594 			buffer_put_int(&out, fctx->rid);
595 		}
596 		goto out;
597 	} else {
598 		if (rfwd->listen_port == 0)
599 			channel_update_permitted_opens(rfwd->handle, -1);
600 		xasprintf(&failmsg, "remote port forwarding failed for "
601 		    "listen port %d", rfwd->listen_port);
602 	}
603  fail:
604 	error("%s: %s", __func__, failmsg);
605 	buffer_put_int(&out, MUX_S_FAILURE);
606 	buffer_put_int(&out, fctx->rid);
607 	buffer_put_cstring(&out, failmsg);
608 	free(failmsg);
609  out:
610 	buffer_put_string(&c->output, buffer_ptr(&out), buffer_len(&out));
611 	buffer_free(&out);
612 	if (c->mux_pause <= 0)
613 		fatal("%s: mux_pause %d", __func__, c->mux_pause);
614 	c->mux_pause = 0; /* start processing messages again */
615 }
616 
617 static int
618 process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
619 {
620 	Forward fwd;
621 	char *fwd_desc = NULL;
622 	u_int ftype;
623 	u_int lport, cport;
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(&lport, m) != 0 ||
630 	    (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
631 	    buffer_get_int_ret(&cport, m) != 0 ||
632 	    lport > 65535 || cport > 65535) {
633 		error("%s: malformed message", __func__);
634 		ret = -1;
635 		goto out;
636 	}
637 	fwd.listen_port = lport;
638 	fwd.connect_port = cport;
639 	if (*fwd.listen_host == '\0') {
640 		free(fwd.listen_host);
641 		fwd.listen_host = NULL;
642 	}
643 	if (*fwd.connect_host == '\0') {
644 		free(fwd.connect_host);
645 		fwd.connect_host = NULL;
646 	}
647 
648 	debug2("%s: channel %d: request %s", __func__, c->self,
649 	    (fwd_desc = format_forward(ftype, &fwd)));
650 
651 	if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
652 	    ftype != MUX_FWD_DYNAMIC) {
653 		logit("%s: invalid forwarding type %u", __func__, ftype);
654  invalid:
655 		free(fwd.listen_host);
656 		free(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)) {
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 	free(fwd_desc);
759 	if (freefwd) {
760 		free(fwd.listen_host);
761 		free(fwd.connect_host);
762 	}
763 	return ret;
764 }
765 
766 static int
767 process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
768 {
769 	Forward fwd, *found_fwd;
770 	char *fwd_desc = NULL;
771 	const char *error_reason = NULL;
772 	u_int ftype;
773 	int i, listen_port, ret = 0;
774 	u_int lport, cport;
775 
776 	fwd.listen_host = fwd.connect_host = NULL;
777 	if (buffer_get_int_ret(&ftype, m) != 0 ||
778 	    (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
779 	    buffer_get_int_ret(&lport, m) != 0 ||
780 	    (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
781 	    buffer_get_int_ret(&cport, m) != 0 ||
782 	    lport > 65535 || cport > 65535) {
783 		error("%s: malformed message", __func__);
784 		ret = -1;
785 		goto out;
786 	}
787 	fwd.listen_port = lport;
788 	fwd.connect_port = cport;
789 
790 	if (*fwd.listen_host == '\0') {
791 		free(fwd.listen_host);
792 		fwd.listen_host = NULL;
793 	}
794 	if (*fwd.connect_host == '\0') {
795 		free(fwd.connect_host);
796 		fwd.connect_host = NULL;
797 	}
798 
799 	debug2("%s: channel %d: request cancel %s", __func__, c->self,
800 	    (fwd_desc = format_forward(ftype, &fwd)));
801 
802 	/* make sure this has been requested */
803 	found_fwd = NULL;
804 	switch (ftype) {
805 	case MUX_FWD_LOCAL:
806 	case MUX_FWD_DYNAMIC:
807 		for (i = 0; i < options.num_local_forwards; i++) {
808 			if (compare_forward(&fwd,
809 			    options.local_forwards + i)) {
810 				found_fwd = options.local_forwards + i;
811 				break;
812 			}
813 		}
814 		break;
815 	case MUX_FWD_REMOTE:
816 		for (i = 0; i < options.num_remote_forwards; i++) {
817 			if (compare_forward(&fwd,
818 			    options.remote_forwards + i)) {
819 				found_fwd = options.remote_forwards + i;
820 				break;
821 			}
822 		}
823 		break;
824 	}
825 
826 	if (found_fwd == NULL)
827 		error_reason = "port not forwarded";
828 	else if (ftype == MUX_FWD_REMOTE) {
829 		/*
830 		 * This shouldn't fail unless we confused the host/port
831 		 * between options.remote_forwards and permitted_opens.
832 		 * However, for dynamic allocated listen ports we need
833 		 * to lookup the actual listen port.
834 		 */
835 	        listen_port = (fwd.listen_port == 0) ?
836 		    found_fwd->allocated_port : fwd.listen_port;
837 		if (channel_request_rforward_cancel(fwd.listen_host,
838 		    listen_port) == -1)
839 			error_reason = "port not in permitted opens";
840 	} else {	/* local and dynamic forwards */
841 		/* Ditto */
842 		if (channel_cancel_lport_listener(fwd.listen_host,
843 		    fwd.listen_port, fwd.connect_port,
844 		    options.gateway_ports) == -1)
845 			error_reason = "port not found";
846 	}
847 
848 	if (error_reason == NULL) {
849 		buffer_put_int(r, MUX_S_OK);
850 		buffer_put_int(r, rid);
851 
852 		free(found_fwd->listen_host);
853 		free(found_fwd->connect_host);
854 		found_fwd->listen_host = found_fwd->connect_host = NULL;
855 		found_fwd->listen_port = found_fwd->connect_port = 0;
856 	} else {
857 		buffer_put_int(r, MUX_S_FAILURE);
858 		buffer_put_int(r, rid);
859 		buffer_put_cstring(r, error_reason);
860 	}
861  out:
862 	free(fwd_desc);
863 	free(fwd.listen_host);
864 	free(fwd.connect_host);
865 
866 	return ret;
867 }
868 
869 static int
870 process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
871 {
872 	Channel *nc;
873 	char *reserved, *chost;
874 	u_int cport, i, j;
875 	int new_fd[2];
876 
877 	chost = reserved = NULL;
878 	if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
879 	   (chost = buffer_get_string_ret(m, NULL)) == NULL ||
880 	    buffer_get_int_ret(&cport, m) != 0) {
881 		free(reserved);
882 		free(chost);
883 		error("%s: malformed message", __func__);
884 		return -1;
885 	}
886 	free(reserved);
887 
888 	debug2("%s: channel %d: request stdio fwd to %s:%u",
889 	    __func__, c->self, chost, cport);
890 
891 	/* Gather fds from client */
892 	for(i = 0; i < 2; i++) {
893 		if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
894 			error("%s: failed to receive fd %d from slave",
895 			    __func__, i);
896 			for (j = 0; j < i; j++)
897 				close(new_fd[j]);
898 			free(chost);
899 
900 			/* prepare reply */
901 			buffer_put_int(r, MUX_S_FAILURE);
902 			buffer_put_int(r, rid);
903 			buffer_put_cstring(r,
904 			    "did not receive file descriptors");
905 			return -1;
906 		}
907 	}
908 
909 	debug3("%s: got fds stdin %d, stdout %d", __func__,
910 	    new_fd[0], new_fd[1]);
911 
912 	/* XXX support multiple child sessions in future */
913 	if (c->remote_id != -1) {
914 		debug2("%s: session already open", __func__);
915 		/* prepare reply */
916 		buffer_put_int(r, MUX_S_FAILURE);
917 		buffer_put_int(r, rid);
918 		buffer_put_cstring(r, "Multiple sessions not supported");
919  cleanup:
920 		close(new_fd[0]);
921 		close(new_fd[1]);
922 		free(chost);
923 		return 0;
924 	}
925 
926 	if (options.control_master == SSHCTL_MASTER_ASK ||
927 	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
928 		if (!ask_permission("Allow forward to %s:%u? ",
929 		    chost, cport)) {
930 			debug2("%s: stdio fwd refused by user", __func__);
931 			/* prepare reply */
932 			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
933 			buffer_put_int(r, rid);
934 			buffer_put_cstring(r, "Permission denied");
935 			goto cleanup;
936 		}
937 	}
938 
939 	/* enable nonblocking unless tty */
940 	if (!isatty(new_fd[0]))
941 		set_nonblock(new_fd[0]);
942 	if (!isatty(new_fd[1]))
943 		set_nonblock(new_fd[1]);
944 
945 	nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
946 
947 	nc->ctl_chan = c->self;		/* link session -> control channel */
948 	c->remote_id = nc->self; 	/* link control -> session channel */
949 
950 	debug2("%s: channel_new: %d linked to control channel %d",
951 	    __func__, nc->self, nc->ctl_chan);
952 
953 	channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
954 
955 	/* prepare reply */
956 	/* XXX defer until channel confirmed */
957 	buffer_put_int(r, MUX_S_SESSION_OPENED);
958 	buffer_put_int(r, rid);
959 	buffer_put_int(r, nc->self);
960 
961 	return 0;
962 }
963 
964 static int
965 process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
966 {
967 	debug("%s: channel %d: stop listening", __func__, c->self);
968 
969 	if (options.control_master == SSHCTL_MASTER_ASK ||
970 	    options.control_master == SSHCTL_MASTER_AUTO_ASK) {
971 		if (!ask_permission("Disable further multiplexing on shared "
972 		    "connection to %s? ", host)) {
973 			debug2("%s: stop listen refused by user", __func__);
974 			buffer_put_int(r, MUX_S_PERMISSION_DENIED);
975 			buffer_put_int(r, rid);
976 			buffer_put_cstring(r, "Permission denied");
977 			return 0;
978 		}
979 	}
980 
981 	if (mux_listener_channel != NULL) {
982 		channel_free(mux_listener_channel);
983 		client_stop_mux();
984 		free(options.control_path);
985 		options.control_path = NULL;
986 		mux_listener_channel = NULL;
987 		muxserver_sock = -1;
988 	}
989 
990 	/* prepare reply */
991 	buffer_put_int(r, MUX_S_OK);
992 	buffer_put_int(r, rid);
993 
994 	return 0;
995 }
996 
997 /* Channel callbacks fired on read/write from mux slave fd */
998 static int
999 mux_master_read_cb(Channel *c)
1000 {
1001 	struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
1002 	Buffer in, out;
1003 	void *ptr;
1004 	u_int type, rid, have, i;
1005 	int ret = -1;
1006 
1007 	/* Setup ctx and  */
1008 	if (c->mux_ctx == NULL) {
1009 		state = xcalloc(1, sizeof(*state));
1010 		c->mux_ctx = state;
1011 		channel_register_cleanup(c->self,
1012 		    mux_master_control_cleanup_cb, 0);
1013 
1014 		/* Send hello */
1015 		buffer_init(&out);
1016 		buffer_put_int(&out, MUX_MSG_HELLO);
1017 		buffer_put_int(&out, SSHMUX_VER);
1018 		/* no extensions */
1019 		buffer_put_string(&c->output, buffer_ptr(&out),
1020 		    buffer_len(&out));
1021 		buffer_free(&out);
1022 		debug3("%s: channel %d: hello sent", __func__, c->self);
1023 		return 0;
1024 	}
1025 
1026 	buffer_init(&in);
1027 	buffer_init(&out);
1028 
1029 	/* Channel code ensures that we receive whole packets */
1030 	if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
1031  malf:
1032 		error("%s: malformed message", __func__);
1033 		goto out;
1034 	}
1035 	buffer_append(&in, ptr, have);
1036 
1037 	if (buffer_get_int_ret(&type, &in) != 0)
1038 		goto malf;
1039 	debug3("%s: channel %d packet type 0x%08x len %u",
1040 	    __func__, c->self, type, buffer_len(&in));
1041 
1042 	if (type == MUX_MSG_HELLO)
1043 		rid = 0;
1044 	else {
1045 		if (!state->hello_rcvd) {
1046 			error("%s: expected MUX_MSG_HELLO(0x%08x), "
1047 			    "received 0x%08x", __func__, MUX_MSG_HELLO, type);
1048 			goto out;
1049 		}
1050 		if (buffer_get_int_ret(&rid, &in) != 0)
1051 			goto malf;
1052 	}
1053 
1054 	for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
1055 		if (type == mux_master_handlers[i].type) {
1056 			ret = mux_master_handlers[i].handler(rid, c, &in, &out);
1057 			break;
1058 		}
1059 	}
1060 	if (mux_master_handlers[i].handler == NULL) {
1061 		error("%s: unsupported mux message 0x%08x", __func__, type);
1062 		buffer_put_int(&out, MUX_S_FAILURE);
1063 		buffer_put_int(&out, rid);
1064 		buffer_put_cstring(&out, "unsupported request");
1065 		ret = 0;
1066 	}
1067 	/* Enqueue reply packet */
1068 	if (buffer_len(&out) != 0) {
1069 		buffer_put_string(&c->output, buffer_ptr(&out),
1070 		    buffer_len(&out));
1071 	}
1072  out:
1073 	buffer_free(&in);
1074 	buffer_free(&out);
1075 	return ret;
1076 }
1077 
1078 void
1079 mux_exit_message(Channel *c, int exitval)
1080 {
1081 	Buffer m;
1082 	Channel *mux_chan;
1083 
1084 	debug3("%s: channel %d: exit message, exitval %d", __func__, c->self,
1085 	    exitval);
1086 
1087 	if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1088 		fatal("%s: channel %d missing mux channel %d",
1089 		    __func__, c->self, c->ctl_chan);
1090 
1091 	/* Append exit message packet to control socket output queue */
1092 	buffer_init(&m);
1093 	buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
1094 	buffer_put_int(&m, c->self);
1095 	buffer_put_int(&m, exitval);
1096 
1097 	buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1098 	buffer_free(&m);
1099 }
1100 
1101 void
1102 mux_tty_alloc_failed(Channel *c)
1103 {
1104 	Buffer m;
1105 	Channel *mux_chan;
1106 
1107 	debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
1108 
1109 	if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1110 		fatal("%s: channel %d missing mux channel %d",
1111 		    __func__, c->self, c->ctl_chan);
1112 
1113 	/* Append exit message packet to control socket output queue */
1114 	buffer_init(&m);
1115 	buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
1116 	buffer_put_int(&m, c->self);
1117 
1118 	buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1119 	buffer_free(&m);
1120 }
1121 
1122 /* Prepare a mux master to listen on a Unix domain socket. */
1123 void
1124 muxserver_listen(void)
1125 {
1126 	struct sockaddr_un addr;
1127 	mode_t old_umask;
1128 	char *orig_control_path = options.control_path;
1129 	char rbuf[16+1];
1130 	u_int i, r;
1131 
1132 	if (options.control_path == NULL ||
1133 	    options.control_master == SSHCTL_MASTER_NO)
1134 		return;
1135 
1136 	debug("setting up multiplex master socket");
1137 
1138 	/*
1139 	 * Use a temporary path before listen so we can pseudo-atomically
1140 	 * establish the listening socket in its final location to avoid
1141 	 * other processes racing in between bind() and listen() and hitting
1142 	 * an unready socket.
1143 	 */
1144 	for (i = 0; i < sizeof(rbuf) - 1; i++) {
1145 		r = arc4random_uniform(26+26+10);
1146 		rbuf[i] = (r < 26) ? 'a' + r :
1147 		    (r < 26*2) ? 'A' + r - 26 :
1148 		    '0' + r - 26 - 26;
1149 	}
1150 	rbuf[sizeof(rbuf) - 1] = '\0';
1151 	options.control_path = NULL;
1152 	xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
1153 	debug3("%s: temporary control path %s", __func__, options.control_path);
1154 
1155 	memset(&addr, '\0', sizeof(addr));
1156 	addr.sun_family = AF_UNIX;
1157 	addr.sun_len = offsetof(struct sockaddr_un, sun_path) +
1158 	    strlen(options.control_path) + 1;
1159 
1160 	if (strlcpy(addr.sun_path, options.control_path,
1161 	    sizeof(addr.sun_path)) >= sizeof(addr.sun_path)) {
1162 		error("ControlPath \"%s\" too long for Unix domain socket",
1163 		    options.control_path);
1164 		goto disable_mux_master;
1165 	}
1166 
1167 	if ((muxserver_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1168 		fatal("%s socket(): %s", __func__, strerror(errno));
1169 
1170 	old_umask = umask(0177);
1171 	if (bind(muxserver_sock, (struct sockaddr *)&addr, addr.sun_len) == -1) {
1172 		if (errno == EINVAL || errno == EADDRINUSE) {
1173 			error("ControlSocket %s already exists, "
1174 			    "disabling multiplexing", options.control_path);
1175  disable_mux_master:
1176 			if (muxserver_sock != -1) {
1177 				close(muxserver_sock);
1178 				muxserver_sock = -1;
1179 			}
1180 			free(orig_control_path);
1181 			free(options.control_path);
1182 			options.control_path = NULL;
1183 			options.control_master = SSHCTL_MASTER_NO;
1184 			return;
1185 		} else
1186 			fatal("%s bind(): %s", __func__, strerror(errno));
1187 	}
1188 	umask(old_umask);
1189 
1190 	if (listen(muxserver_sock, 64) == -1)
1191 		fatal("%s listen(): %s", __func__, strerror(errno));
1192 
1193 	/* Now atomically "move" the mux socket into position */
1194 	if (link(options.control_path, orig_control_path) != 0) {
1195 		if (errno != EEXIST) {
1196 			fatal("%s: link mux listener %s => %s: %s", __func__,
1197 			    options.control_path, orig_control_path,
1198 			    strerror(errno));
1199 		}
1200 		error("ControlSocket %s already exists, disabling multiplexing",
1201 		    orig_control_path);
1202 		unlink(options.control_path);
1203 		goto disable_mux_master;
1204 	}
1205 	unlink(options.control_path);
1206 	free(options.control_path);
1207 	options.control_path = orig_control_path;
1208 
1209 	set_nonblock(muxserver_sock);
1210 
1211 	mux_listener_channel = channel_new("mux listener",
1212 	    SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
1213 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1214 	    0, options.control_path, 1);
1215 	mux_listener_channel->mux_rcb = mux_master_read_cb;
1216 	debug3("%s: mux listener channel %d fd %d", __func__,
1217 	    mux_listener_channel->self, mux_listener_channel->sock);
1218 }
1219 
1220 /* Callback on open confirmation in mux master for a mux client session. */
1221 static void
1222 mux_session_confirm(int id, int success, void *arg)
1223 {
1224 	struct mux_session_confirm_ctx *cctx = arg;
1225 	const char *display;
1226 	Channel *c, *cc;
1227 	int i;
1228 	Buffer reply;
1229 
1230 	if (cctx == NULL)
1231 		fatal("%s: cctx == NULL", __func__);
1232 	if ((c = channel_by_id(id)) == NULL)
1233 		fatal("%s: no channel for id %d", __func__, id);
1234 	if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1235 		fatal("%s: channel %d lacks control channel %d", __func__,
1236 		    id, c->ctl_chan);
1237 
1238 	if (!success) {
1239 		debug3("%s: sending failure reply", __func__);
1240 		/* prepare reply */
1241 		buffer_init(&reply);
1242 		buffer_put_int(&reply, MUX_S_FAILURE);
1243 		buffer_put_int(&reply, cctx->rid);
1244 		buffer_put_cstring(&reply, "Session open refused by peer");
1245 		goto done;
1246 	}
1247 
1248 	display = getenv("DISPLAY");
1249 	if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1250 		char *proto, *data;
1251 
1252 		/* Get reasonable local authentication information. */
1253 		client_x11_get_proto(display, options.xauth_location,
1254 		    options.forward_x11_trusted, options.forward_x11_timeout,
1255 		    &proto, &data);
1256 		/* Request forwarding with authentication spoofing. */
1257 		debug("Requesting X11 forwarding with authentication "
1258 		    "spoofing.");
1259 		x11_request_forwarding_with_spoofing(id, display, proto,
1260 		    data, 1);
1261 		client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1262 		/* XXX exit_on_forward_failure */
1263 	}
1264 
1265 	if (cctx->want_agent_fwd && options.forward_agent) {
1266 		debug("Requesting authentication agent forwarding.");
1267 		channel_request_start(id, "auth-agent-req@openssh.com", 0);
1268 		packet_send();
1269 	}
1270 
1271 	client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1272 	    cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1273 
1274 	debug3("%s: sending success reply", __func__);
1275 	/* prepare reply */
1276 	buffer_init(&reply);
1277 	buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1278 	buffer_put_int(&reply, cctx->rid);
1279 	buffer_put_int(&reply, c->self);
1280 
1281  done:
1282 	/* Send reply */
1283 	buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1284 	buffer_free(&reply);
1285 
1286 	if (cc->mux_pause <= 0)
1287 		fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1288 	cc->mux_pause = 0; /* start processing messages again */
1289 	c->open_confirm_ctx = NULL;
1290 	buffer_free(&cctx->cmd);
1291 	free(cctx->term);
1292 	if (cctx->env != NULL) {
1293 		for (i = 0; cctx->env[i] != NULL; i++)
1294 			free(cctx->env[i]);
1295 		free(cctx->env);
1296 	}
1297 	free(cctx);
1298 }
1299 
1300 /* ** Multiplexing client support */
1301 
1302 /* Exit signal handler */
1303 static void
1304 control_client_sighandler(int signo)
1305 {
1306 	muxclient_terminate = signo;
1307 }
1308 
1309 /*
1310  * Relay signal handler - used to pass some signals from mux client to
1311  * mux master.
1312  */
1313 static void
1314 control_client_sigrelay(int signo)
1315 {
1316 	int save_errno = errno;
1317 
1318 	if (muxserver_pid > 1)
1319 		kill(muxserver_pid, signo);
1320 
1321 	errno = save_errno;
1322 }
1323 
1324 static int
1325 mux_client_read(int fd, Buffer *b, u_int need)
1326 {
1327 	u_int have;
1328 	ssize_t len;
1329 	u_char *p;
1330 	struct pollfd pfd;
1331 
1332 	pfd.fd = fd;
1333 	pfd.events = POLLIN;
1334 	p = buffer_append_space(b, need);
1335 	for (have = 0; have < need; ) {
1336 		if (muxclient_terminate) {
1337 			errno = EINTR;
1338 			return -1;
1339 		}
1340 		len = read(fd, p + have, need - have);
1341 		if (len < 0) {
1342 			switch (errno) {
1343 			case EAGAIN:
1344 				(void)poll(&pfd, 1, -1);
1345 				/* FALLTHROUGH */
1346 			case EINTR:
1347 				continue;
1348 			default:
1349 				return -1;
1350 			}
1351 		}
1352 		if (len == 0) {
1353 			errno = EPIPE;
1354 			return -1;
1355 		}
1356 		have += (u_int)len;
1357 	}
1358 	return 0;
1359 }
1360 
1361 static int
1362 mux_client_write_packet(int fd, Buffer *m)
1363 {
1364 	Buffer queue;
1365 	u_int have, need;
1366 	int oerrno, len;
1367 	u_char *ptr;
1368 	struct pollfd pfd;
1369 
1370 	pfd.fd = fd;
1371 	pfd.events = POLLOUT;
1372 	buffer_init(&queue);
1373 	buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1374 
1375 	need = buffer_len(&queue);
1376 	ptr = buffer_ptr(&queue);
1377 
1378 	for (have = 0; have < need; ) {
1379 		if (muxclient_terminate) {
1380 			buffer_free(&queue);
1381 			errno = EINTR;
1382 			return -1;
1383 		}
1384 		len = write(fd, ptr + have, need - have);
1385 		if (len < 0) {
1386 			switch (errno) {
1387 			case EAGAIN:
1388 				(void)poll(&pfd, 1, -1);
1389 				/* FALLTHROUGH */
1390 			case EINTR:
1391 				continue;
1392 			default:
1393 				oerrno = errno;
1394 				buffer_free(&queue);
1395 				errno = oerrno;
1396 				return -1;
1397 			}
1398 		}
1399 		if (len == 0) {
1400 			buffer_free(&queue);
1401 			errno = EPIPE;
1402 			return -1;
1403 		}
1404 		have += (u_int)len;
1405 	}
1406 	buffer_free(&queue);
1407 	return 0;
1408 }
1409 
1410 static int
1411 mux_client_read_packet(int fd, Buffer *m)
1412 {
1413 	Buffer queue;
1414 	u_int need, have;
1415 	void *ptr;
1416 	int oerrno;
1417 
1418 	buffer_init(&queue);
1419 	if (mux_client_read(fd, &queue, 4) != 0) {
1420 		if ((oerrno = errno) == EPIPE)
1421 			debug3("%s: read header failed: %s", __func__,
1422 			    strerror(errno));
1423 		buffer_free(&queue);
1424 		errno = oerrno;
1425 		return -1;
1426 	}
1427 	need = get_u32(buffer_ptr(&queue));
1428 	if (mux_client_read(fd, &queue, need) != 0) {
1429 		oerrno = errno;
1430 		debug3("%s: read body failed: %s", __func__, strerror(errno));
1431 		buffer_free(&queue);
1432 		errno = oerrno;
1433 		return -1;
1434 	}
1435 	ptr = buffer_get_string_ptr(&queue, &have);
1436 	buffer_append(m, ptr, have);
1437 	buffer_free(&queue);
1438 	return 0;
1439 }
1440 
1441 static int
1442 mux_client_hello_exchange(int fd)
1443 {
1444 	Buffer m;
1445 	u_int type, ver;
1446 
1447 	buffer_init(&m);
1448 	buffer_put_int(&m, MUX_MSG_HELLO);
1449 	buffer_put_int(&m, SSHMUX_VER);
1450 	/* no extensions */
1451 
1452 	if (mux_client_write_packet(fd, &m) != 0)
1453 		fatal("%s: write packet: %s", __func__, strerror(errno));
1454 
1455 	buffer_clear(&m);
1456 
1457 	/* Read their HELLO */
1458 	if (mux_client_read_packet(fd, &m) != 0) {
1459 		buffer_free(&m);
1460 		return -1;
1461 	}
1462 
1463 	type = buffer_get_int(&m);
1464 	if (type != MUX_MSG_HELLO)
1465 		fatal("%s: expected HELLO (%u) received %u",
1466 		    __func__, MUX_MSG_HELLO, type);
1467 	ver = buffer_get_int(&m);
1468 	if (ver != SSHMUX_VER)
1469 		fatal("Unsupported multiplexing protocol version %d "
1470 		    "(expected %d)", ver, SSHMUX_VER);
1471 	debug2("%s: master version %u", __func__, ver);
1472 	/* No extensions are presently defined */
1473 	while (buffer_len(&m) > 0) {
1474 		char *name = buffer_get_string(&m, NULL);
1475 		char *value = buffer_get_string(&m, NULL);
1476 
1477 		debug2("Unrecognised master extension \"%s\"", name);
1478 		free(name);
1479 		free(value);
1480 	}
1481 	buffer_free(&m);
1482 	return 0;
1483 }
1484 
1485 static u_int
1486 mux_client_request_alive(int fd)
1487 {
1488 	Buffer m;
1489 	char *e;
1490 	u_int pid, type, rid;
1491 
1492 	debug3("%s: entering", __func__);
1493 
1494 	buffer_init(&m);
1495 	buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1496 	buffer_put_int(&m, muxclient_request_id);
1497 
1498 	if (mux_client_write_packet(fd, &m) != 0)
1499 		fatal("%s: write packet: %s", __func__, strerror(errno));
1500 
1501 	buffer_clear(&m);
1502 
1503 	/* Read their reply */
1504 	if (mux_client_read_packet(fd, &m) != 0) {
1505 		buffer_free(&m);
1506 		return 0;
1507 	}
1508 
1509 	type = buffer_get_int(&m);
1510 	if (type != MUX_S_ALIVE) {
1511 		e = buffer_get_string(&m, NULL);
1512 		fatal("%s: master returned error: %s", __func__, e);
1513 	}
1514 
1515 	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1516 		fatal("%s: out of sequence reply: my id %u theirs %u",
1517 		    __func__, muxclient_request_id, rid);
1518 	pid = buffer_get_int(&m);
1519 	buffer_free(&m);
1520 
1521 	debug3("%s: done pid = %u", __func__, pid);
1522 
1523 	muxclient_request_id++;
1524 
1525 	return pid;
1526 }
1527 
1528 static void
1529 mux_client_request_terminate(int fd)
1530 {
1531 	Buffer m;
1532 	char *e;
1533 	u_int type, rid;
1534 
1535 	debug3("%s: entering", __func__);
1536 
1537 	buffer_init(&m);
1538 	buffer_put_int(&m, MUX_C_TERMINATE);
1539 	buffer_put_int(&m, muxclient_request_id);
1540 
1541 	if (mux_client_write_packet(fd, &m) != 0)
1542 		fatal("%s: write packet: %s", __func__, strerror(errno));
1543 
1544 	buffer_clear(&m);
1545 
1546 	/* Read their reply */
1547 	if (mux_client_read_packet(fd, &m) != 0) {
1548 		/* Remote end exited already */
1549 		if (errno == EPIPE) {
1550 			buffer_free(&m);
1551 			return;
1552 		}
1553 		fatal("%s: read from master failed: %s",
1554 		    __func__, strerror(errno));
1555 	}
1556 
1557 	type = buffer_get_int(&m);
1558 	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1559 		fatal("%s: out of sequence reply: my id %u theirs %u",
1560 		    __func__, muxclient_request_id, rid);
1561 	switch (type) {
1562 	case MUX_S_OK:
1563 		break;
1564 	case MUX_S_PERMISSION_DENIED:
1565 		e = buffer_get_string(&m, NULL);
1566 		fatal("Master refused termination request: %s", e);
1567 	case MUX_S_FAILURE:
1568 		e = buffer_get_string(&m, NULL);
1569 		fatal("%s: termination request failed: %s", __func__, e);
1570 	default:
1571 		fatal("%s: unexpected response from master 0x%08x",
1572 		    __func__, type);
1573 	}
1574 	buffer_free(&m);
1575 	muxclient_request_id++;
1576 }
1577 
1578 static int
1579 mux_client_forward(int fd, int cancel_flag, u_int ftype, Forward *fwd)
1580 {
1581 	Buffer m;
1582 	char *e, *fwd_desc;
1583 	u_int type, rid;
1584 
1585 	fwd_desc = format_forward(ftype, fwd);
1586 	debug("Requesting %s %s",
1587 	    cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
1588 	free(fwd_desc);
1589 
1590 	buffer_init(&m);
1591 	buffer_put_int(&m, cancel_flag ? MUX_C_CLOSE_FWD : MUX_C_OPEN_FWD);
1592 	buffer_put_int(&m, muxclient_request_id);
1593 	buffer_put_int(&m, ftype);
1594 	buffer_put_cstring(&m,
1595 	    fwd->listen_host == NULL ? "" : fwd->listen_host);
1596 	buffer_put_int(&m, fwd->listen_port);
1597 	buffer_put_cstring(&m,
1598 	    fwd->connect_host == NULL ? "" : fwd->connect_host);
1599 	buffer_put_int(&m, fwd->connect_port);
1600 
1601 	if (mux_client_write_packet(fd, &m) != 0)
1602 		fatal("%s: write packet: %s", __func__, strerror(errno));
1603 
1604 	buffer_clear(&m);
1605 
1606 	/* Read their reply */
1607 	if (mux_client_read_packet(fd, &m) != 0) {
1608 		buffer_free(&m);
1609 		return -1;
1610 	}
1611 
1612 	type = buffer_get_int(&m);
1613 	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1614 		fatal("%s: out of sequence reply: my id %u theirs %u",
1615 		    __func__, muxclient_request_id, rid);
1616 	switch (type) {
1617 	case MUX_S_OK:
1618 		break;
1619 	case MUX_S_REMOTE_PORT:
1620 		if (cancel_flag)
1621 			fatal("%s: got MUX_S_REMOTE_PORT for cancel", __func__);
1622 		fwd->allocated_port = buffer_get_int(&m);
1623 		logit("Allocated port %u for remote forward to %s:%d",
1624 		    fwd->allocated_port,
1625 		    fwd->connect_host ? fwd->connect_host : "",
1626 		    fwd->connect_port);
1627 		if (muxclient_command == SSHMUX_COMMAND_FORWARD)
1628 			fprintf(stdout, "%u\n", fwd->allocated_port);
1629 		break;
1630 	case MUX_S_PERMISSION_DENIED:
1631 		e = buffer_get_string(&m, NULL);
1632 		buffer_free(&m);
1633 		error("Master refused forwarding request: %s", e);
1634 		return -1;
1635 	case MUX_S_FAILURE:
1636 		e = buffer_get_string(&m, NULL);
1637 		buffer_free(&m);
1638 		error("%s: forwarding request failed: %s", __func__, e);
1639 		return -1;
1640 	default:
1641 		fatal("%s: unexpected response from master 0x%08x",
1642 		    __func__, type);
1643 	}
1644 	buffer_free(&m);
1645 
1646 	muxclient_request_id++;
1647 	return 0;
1648 }
1649 
1650 static int
1651 mux_client_forwards(int fd, int cancel_flag)
1652 {
1653 	int i, ret = 0;
1654 
1655 	debug3("%s: %s forwardings: %d local, %d remote", __func__,
1656 	    cancel_flag ? "cancel" : "request",
1657 	    options.num_local_forwards, options.num_remote_forwards);
1658 
1659 	/* XXX ExitOnForwardingFailure */
1660 	for (i = 0; i < options.num_local_forwards; i++) {
1661 		if (mux_client_forward(fd, cancel_flag,
1662 		    options.local_forwards[i].connect_port == 0 ?
1663 		    MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1664 		    options.local_forwards + i) != 0)
1665 			ret = -1;
1666 	}
1667 	for (i = 0; i < options.num_remote_forwards; i++) {
1668 		if (mux_client_forward(fd, cancel_flag, MUX_FWD_REMOTE,
1669 		    options.remote_forwards + i) != 0)
1670 			ret = -1;
1671 	}
1672 	return ret;
1673 }
1674 
1675 static int
1676 mux_client_request_session(int fd)
1677 {
1678 	Buffer m;
1679 	char *e, *term;
1680 	u_int i, rid, sid, esid, exitval, type, exitval_seen;
1681 	extern char **environ;
1682 	int devnull, rawmode;
1683 
1684 	debug3("%s: entering", __func__);
1685 
1686 	if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1687 		error("%s: master alive request failed", __func__);
1688 		return -1;
1689 	}
1690 
1691 	signal(SIGPIPE, SIG_IGN);
1692 
1693 	if (stdin_null_flag) {
1694 		if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1695 			fatal("open(/dev/null): %s", strerror(errno));
1696 		if (dup2(devnull, STDIN_FILENO) == -1)
1697 			fatal("dup2: %s", strerror(errno));
1698 		if (devnull > STDERR_FILENO)
1699 			close(devnull);
1700 	}
1701 
1702 	term = getenv("TERM");
1703 
1704 	buffer_init(&m);
1705 	buffer_put_int(&m, MUX_C_NEW_SESSION);
1706 	buffer_put_int(&m, muxclient_request_id);
1707 	buffer_put_cstring(&m, ""); /* reserved */
1708 	buffer_put_int(&m, tty_flag);
1709 	buffer_put_int(&m, options.forward_x11);
1710 	buffer_put_int(&m, options.forward_agent);
1711 	buffer_put_int(&m, subsystem_flag);
1712 	buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1713 	    0xffffffff : (u_int)options.escape_char);
1714 	buffer_put_cstring(&m, term == NULL ? "" : term);
1715 	buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1716 
1717 	if (options.num_send_env > 0 && environ != NULL) {
1718 		/* Pass environment */
1719 		for (i = 0; environ[i] != NULL; i++) {
1720 			if (env_permitted(environ[i])) {
1721 				buffer_put_cstring(&m, environ[i]);
1722 			}
1723 		}
1724 	}
1725 
1726 	if (mux_client_write_packet(fd, &m) != 0)
1727 		fatal("%s: write packet: %s", __func__, strerror(errno));
1728 
1729 	/* Send the stdio file descriptors */
1730 	if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1731 	    mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1732 	    mm_send_fd(fd, STDERR_FILENO) == -1)
1733 		fatal("%s: send fds failed", __func__);
1734 
1735 	debug3("%s: session request sent", __func__);
1736 
1737 	/* Read their reply */
1738 	buffer_clear(&m);
1739 	if (mux_client_read_packet(fd, &m) != 0) {
1740 		error("%s: read from master failed: %s",
1741 		    __func__, strerror(errno));
1742 		buffer_free(&m);
1743 		return -1;
1744 	}
1745 
1746 	type = buffer_get_int(&m);
1747 	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1748 		fatal("%s: out of sequence reply: my id %u theirs %u",
1749 		    __func__, muxclient_request_id, rid);
1750 	switch (type) {
1751 	case MUX_S_SESSION_OPENED:
1752 		sid = buffer_get_int(&m);
1753 		debug("%s: master session id: %u", __func__, sid);
1754 		break;
1755 	case MUX_S_PERMISSION_DENIED:
1756 		e = buffer_get_string(&m, NULL);
1757 		buffer_free(&m);
1758 		error("Master refused session request: %s", e);
1759 		return -1;
1760 	case MUX_S_FAILURE:
1761 		e = buffer_get_string(&m, NULL);
1762 		buffer_free(&m);
1763 		error("%s: session request failed: %s", __func__, e);
1764 		return -1;
1765 	default:
1766 		buffer_free(&m);
1767 		error("%s: unexpected response from master 0x%08x",
1768 		    __func__, type);
1769 		return -1;
1770 	}
1771 	muxclient_request_id++;
1772 
1773 	signal(SIGHUP, control_client_sighandler);
1774 	signal(SIGINT, control_client_sighandler);
1775 	signal(SIGTERM, control_client_sighandler);
1776 	signal(SIGWINCH, control_client_sigrelay);
1777 
1778 	rawmode = tty_flag;
1779 	if (tty_flag)
1780 		enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1781 
1782 	/*
1783 	 * Stick around until the controlee closes the client_fd.
1784 	 * Before it does, it is expected to write an exit message.
1785 	 * This process must read the value and wait for the closure of
1786 	 * the client_fd; if this one closes early, the multiplex master will
1787 	 * terminate early too (possibly losing data).
1788 	 */
1789 	for (exitval = 255, exitval_seen = 0;;) {
1790 		buffer_clear(&m);
1791 		if (mux_client_read_packet(fd, &m) != 0)
1792 			break;
1793 		type = buffer_get_int(&m);
1794 		switch (type) {
1795 		case MUX_S_TTY_ALLOC_FAIL:
1796 			if ((esid = buffer_get_int(&m)) != sid)
1797 				fatal("%s: tty alloc fail on unknown session: "
1798 				    "my id %u theirs %u",
1799 				    __func__, sid, esid);
1800 			leave_raw_mode(options.request_tty ==
1801 			    REQUEST_TTY_FORCE);
1802 			rawmode = 0;
1803 			continue;
1804 		case MUX_S_EXIT_MESSAGE:
1805 			if ((esid = buffer_get_int(&m)) != sid)
1806 				fatal("%s: exit on unknown session: "
1807 				    "my id %u theirs %u",
1808 				    __func__, sid, esid);
1809 			if (exitval_seen)
1810 				fatal("%s: exitval sent twice", __func__);
1811 			exitval = buffer_get_int(&m);
1812 			exitval_seen = 1;
1813 			continue;
1814 		default:
1815 			e = buffer_get_string(&m, NULL);
1816 			fatal("%s: master returned error: %s", __func__, e);
1817 		}
1818 	}
1819 
1820 	close(fd);
1821 	if (rawmode)
1822 		leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1823 
1824 	if (muxclient_terminate) {
1825 		debug2("Exiting on signal %ld", (long)muxclient_terminate);
1826 		exitval = 255;
1827 	} else if (!exitval_seen) {
1828 		debug2("Control master terminated unexpectedly");
1829 		exitval = 255;
1830 	} else
1831 		debug2("Received exit status from master %d", exitval);
1832 
1833 	if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1834 		fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1835 
1836 	exit(exitval);
1837 }
1838 
1839 static int
1840 mux_client_request_stdio_fwd(int fd)
1841 {
1842 	Buffer m;
1843 	char *e;
1844 	u_int type, rid, sid;
1845 	int devnull;
1846 
1847 	debug3("%s: entering", __func__);
1848 
1849 	if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1850 		error("%s: master alive request failed", __func__);
1851 		return -1;
1852 	}
1853 
1854 	signal(SIGPIPE, SIG_IGN);
1855 
1856 	if (stdin_null_flag) {
1857 		if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1858 			fatal("open(/dev/null): %s", strerror(errno));
1859 		if (dup2(devnull, STDIN_FILENO) == -1)
1860 			fatal("dup2: %s", strerror(errno));
1861 		if (devnull > STDERR_FILENO)
1862 			close(devnull);
1863 	}
1864 
1865 	buffer_init(&m);
1866 	buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
1867 	buffer_put_int(&m, muxclient_request_id);
1868 	buffer_put_cstring(&m, ""); /* reserved */
1869 	buffer_put_cstring(&m, stdio_forward_host);
1870 	buffer_put_int(&m, stdio_forward_port);
1871 
1872 	if (mux_client_write_packet(fd, &m) != 0)
1873 		fatal("%s: write packet: %s", __func__, strerror(errno));
1874 
1875 	/* Send the stdio file descriptors */
1876 	if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1877 	    mm_send_fd(fd, STDOUT_FILENO) == -1)
1878 		fatal("%s: send fds failed", __func__);
1879 
1880 	debug3("%s: stdio forward request sent", __func__);
1881 
1882 	/* Read their reply */
1883 	buffer_clear(&m);
1884 
1885 	if (mux_client_read_packet(fd, &m) != 0) {
1886 		error("%s: read from master failed: %s",
1887 		    __func__, strerror(errno));
1888 		buffer_free(&m);
1889 		return -1;
1890 	}
1891 
1892 	type = buffer_get_int(&m);
1893 	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1894 		fatal("%s: out of sequence reply: my id %u theirs %u",
1895 		    __func__, muxclient_request_id, rid);
1896 	switch (type) {
1897 	case MUX_S_SESSION_OPENED:
1898 		sid = buffer_get_int(&m);
1899 		debug("%s: master session id: %u", __func__, sid);
1900 		break;
1901 	case MUX_S_PERMISSION_DENIED:
1902 		e = buffer_get_string(&m, NULL);
1903 		buffer_free(&m);
1904 		fatal("Master refused stdio forwarding request: %s", e);
1905 	case MUX_S_FAILURE:
1906 		e = buffer_get_string(&m, NULL);
1907 		buffer_free(&m);
1908 		fatal("%s: stdio forwarding request failed: %s", __func__, e);
1909 	default:
1910 		buffer_free(&m);
1911 		error("%s: unexpected response from master 0x%08x",
1912 		    __func__, type);
1913 		return -1;
1914 	}
1915 	muxclient_request_id++;
1916 
1917 	signal(SIGHUP, control_client_sighandler);
1918 	signal(SIGINT, control_client_sighandler);
1919 	signal(SIGTERM, control_client_sighandler);
1920 	signal(SIGWINCH, control_client_sigrelay);
1921 
1922 	/*
1923 	 * Stick around until the controlee closes the client_fd.
1924 	 */
1925 	buffer_clear(&m);
1926 	if (mux_client_read_packet(fd, &m) != 0) {
1927 		if (errno == EPIPE ||
1928 		    (errno == EINTR && muxclient_terminate != 0))
1929 			return 0;
1930 		fatal("%s: mux_client_read_packet: %s",
1931 		    __func__, strerror(errno));
1932 	}
1933 	fatal("%s: master returned unexpected message %u", __func__, type);
1934 }
1935 
1936 static void
1937 mux_client_request_stop_listening(int fd)
1938 {
1939 	Buffer m;
1940 	char *e;
1941 	u_int type, rid;
1942 
1943 	debug3("%s: entering", __func__);
1944 
1945 	buffer_init(&m);
1946 	buffer_put_int(&m, MUX_C_STOP_LISTENING);
1947 	buffer_put_int(&m, muxclient_request_id);
1948 
1949 	if (mux_client_write_packet(fd, &m) != 0)
1950 		fatal("%s: write packet: %s", __func__, strerror(errno));
1951 
1952 	buffer_clear(&m);
1953 
1954 	/* Read their reply */
1955 	if (mux_client_read_packet(fd, &m) != 0)
1956 		fatal("%s: read from master failed: %s",
1957 		    __func__, strerror(errno));
1958 
1959 	type = buffer_get_int(&m);
1960 	if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1961 		fatal("%s: out of sequence reply: my id %u theirs %u",
1962 		    __func__, muxclient_request_id, rid);
1963 	switch (type) {
1964 	case MUX_S_OK:
1965 		break;
1966 	case MUX_S_PERMISSION_DENIED:
1967 		e = buffer_get_string(&m, NULL);
1968 		fatal("Master refused stop listening request: %s", e);
1969 	case MUX_S_FAILURE:
1970 		e = buffer_get_string(&m, NULL);
1971 		fatal("%s: stop listening request failed: %s", __func__, e);
1972 	default:
1973 		fatal("%s: unexpected response from master 0x%08x",
1974 		    __func__, type);
1975 	}
1976 	buffer_free(&m);
1977 	muxclient_request_id++;
1978 }
1979 
1980 /* Multiplex client main loop. */
1981 void
1982 muxclient(const char *path)
1983 {
1984 	struct sockaddr_un addr;
1985 	int sock;
1986 	u_int pid;
1987 
1988 	if (muxclient_command == 0) {
1989 		if (stdio_forward_host != NULL)
1990 			muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
1991 		else
1992 			muxclient_command = SSHMUX_COMMAND_OPEN;
1993 	}
1994 
1995 	switch (options.control_master) {
1996 	case SSHCTL_MASTER_AUTO:
1997 	case SSHCTL_MASTER_AUTO_ASK:
1998 		debug("auto-mux: Trying existing master");
1999 		/* FALLTHROUGH */
2000 	case SSHCTL_MASTER_NO:
2001 		break;
2002 	default:
2003 		return;
2004 	}
2005 
2006 	memset(&addr, '\0', sizeof(addr));
2007 	addr.sun_family = AF_UNIX;
2008 	addr.sun_len = offsetof(struct sockaddr_un, sun_path) +
2009 	    strlen(path) + 1;
2010 
2011 	if (strlcpy(addr.sun_path, path,
2012 	    sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
2013 		fatal("ControlPath too long");
2014 
2015 	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
2016 		fatal("%s socket(): %s", __func__, strerror(errno));
2017 
2018 	if (connect(sock, (struct sockaddr *)&addr, addr.sun_len) == -1) {
2019 		switch (muxclient_command) {
2020 		case SSHMUX_COMMAND_OPEN:
2021 		case SSHMUX_COMMAND_STDIO_FWD:
2022 			break;
2023 		default:
2024 			fatal("Control socket connect(%.100s): %s", path,
2025 			    strerror(errno));
2026 		}
2027 		if (errno == ECONNREFUSED &&
2028 		    options.control_master != SSHCTL_MASTER_NO) {
2029 			debug("Stale control socket %.100s, unlinking", path);
2030 			unlink(path);
2031 		} else if (errno == ENOENT) {
2032 			debug("Control socket \"%.100s\" does not exist", path);
2033 		} else {
2034 			error("Control socket connect(%.100s): %s", path,
2035 			    strerror(errno));
2036 		}
2037 		close(sock);
2038 		return;
2039 	}
2040 	set_nonblock(sock);
2041 
2042 	if (mux_client_hello_exchange(sock) != 0) {
2043 		error("%s: master hello exchange failed", __func__);
2044 		close(sock);
2045 		return;
2046 	}
2047 
2048 	switch (muxclient_command) {
2049 	case SSHMUX_COMMAND_ALIVE_CHECK:
2050 		if ((pid = mux_client_request_alive(sock)) == 0)
2051 			fatal("%s: master alive check failed", __func__);
2052 		fprintf(stderr, "Master running (pid=%d)\r\n", pid);
2053 		exit(0);
2054 	case SSHMUX_COMMAND_TERMINATE:
2055 		mux_client_request_terminate(sock);
2056 		fprintf(stderr, "Exit request sent.\r\n");
2057 		exit(0);
2058 	case SSHMUX_COMMAND_FORWARD:
2059 		if (mux_client_forwards(sock, 0) != 0)
2060 			fatal("%s: master forward request failed", __func__);
2061 		exit(0);
2062 	case SSHMUX_COMMAND_OPEN:
2063 		if (mux_client_forwards(sock, 0) != 0) {
2064 			error("%s: master forward request failed", __func__);
2065 			return;
2066 		}
2067 		mux_client_request_session(sock);
2068 		return;
2069 	case SSHMUX_COMMAND_STDIO_FWD:
2070 		mux_client_request_stdio_fwd(sock);
2071 		exit(0);
2072 	case SSHMUX_COMMAND_STOP:
2073 		mux_client_request_stop_listening(sock);
2074 		fprintf(stderr, "Stop listening request sent.\r\n");
2075 		exit(0);
2076 	case SSHMUX_COMMAND_CANCEL_FWD:
2077 		if (mux_client_forwards(sock, 1) != 0)
2078 			error("%s: master cancel forward request failed",
2079 			    __func__);
2080 		exit(0);
2081 	default:
2082 		fatal("unrecognised muxclient_command %d", muxclient_command);
2083 	}
2084 }
2085