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