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