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