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