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