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