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