1 /* $OpenBSD: mux.c,v 1.44 2013/07/12 00:19:58 djm Exp $ */
4 * Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
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.
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.
19 /* ssh session multiplexing support */
23 * - Better signalling from master to slave, especially passing of
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
37 #include <sys/types.h>
38 #include <sys/param.h>
40 #include <sys/socket.h>
59 # ifdef HAVE_SYS_POLL_H
60 # include <sys/poll.h>
68 #include "openbsd-compat/sys-queue.h"
73 #include "pathnames.h"
80 #include "monitor_fdpass.h"
84 #include "clientloop.h"
88 extern Options options;
89 extern int stdin_null_flag;
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;
97 /* Context for session open confirmation callback */
98 struct mux_session_confirm_ctx {
102 u_int want_agent_fwd;
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 */
117 /* fd to control socket */
118 int muxserver_sock = -1;
120 /* client request id */
121 u_int muxclient_request_id = 0;
123 /* Multiplexing control command */
124 u_int muxclient_command = 0;
126 /* Set when signalled. */
127 static volatile sig_atomic_t muxclient_terminate = 0;
129 /* PID of multiplex server */
130 static u_int muxserver_pid = 0;
132 static Channel *mux_listener_channel = NULL;
134 struct mux_master_state {
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
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
161 static void mux_session_confirm(int, int, void *);
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 *);
172 static const struct {
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 },
187 /* Cleanup callback fired on closure of mux slave _session_ channel */
190 mux_master_session_cleanup_cb(int cid, void *unused)
192 Channel *cc, *c = channel_by_id(cid);
194 debug3("%s: entering for channel %d", __func__, cid);
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);
203 chan_rcvd_oclose(cc);
205 channel_cancel_cleanup(c->self);
208 /* Cleanup callback fired on closure of mux slave _control_ channel */
211 mux_master_control_cleanup_cb(int cid, void *unused)
213 Channel *sc, *c = channel_by_id(cid);
215 debug3("%s: entering for channel %d", __func__, cid);
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);
224 if (sc->type != SSH_CHANNEL_OPEN &&
225 sc->type != SSH_CHANNEL_OPENING) {
226 debug2("%s: channel %d: not open", __func__, sc->self);
229 if (sc->istate == CHAN_INPUT_OPEN)
230 chan_read_failed(sc);
231 if (sc->ostate == CHAN_OUTPUT_OPEN)
232 chan_write_failed(sc);
235 channel_cancel_cleanup(c->self);
238 /* Check mux client environment variables before passing them to mux master. */
240 env_permitted(char *env)
243 char name[1024], *cp;
245 if ((cp = strchr(env, '=')) == NULL || cp == env)
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);
253 for (i = 0; i < options.num_send_env; i++)
254 if (match_pattern(name, options.send_env[i]))
260 /* Mux master protocol message handlers */
263 process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
266 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
269 fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
270 if (state->hello_rcvd) {
271 error("%s: HELLO received twice", __func__);
274 if (buffer_get_int_ret(&ver, m) != 0) {
276 error("%s: malformed message", __func__);
279 if (ver != SSHMUX_VER) {
280 error("Unsupported multiplexing protocol version %d "
281 "(expected %d)", ver, SSHMUX_VER);
284 debug2("%s: channel %d slave version %u", __func__, c->self, ver);
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);
291 if (name == NULL || value == NULL) {
296 debug2("Unrecognised slave extension \"%s\"", name);
300 state->hello_rcvd = 1;
305 process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
308 struct mux_session_confirm_ctx *cctx;
309 char *reserved, *cmd, *cp;
310 u_int i, j, len, env_len, escape_char, window, packetmax;
313 /* Reply for SSHMUX_COMMAND_OPEN */
314 cctx = xcalloc(1, sizeof(*cctx));
317 cmd = reserved = NULL;
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) {
331 for (j = 0; j < env_len; j++)
336 error("%s: malformed message", __func__);
342 while (buffer_len(m) > 0) {
343 #define MUX_MAX_ENV_VARS 4096
344 if ((cp = buffer_get_string_ret(m, &len)) == NULL)
346 if (!env_permitted(cp)) {
350 cctx->env = xrealloc(cctx->env, env_len + 2,
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);
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);
366 buffer_init(&cctx->cmd);
367 buffer_append(&cctx->cmd, cmd, strlen(cmd));
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",
376 for (j = 0; j < i; j++)
378 for (j = 0; j < env_len; j++)
382 buffer_free(&cctx->cmd);
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");
394 debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
395 new_fd[0], new_fd[1], new_fd[2]);
397 /* XXX support multiple child sessions in future */
398 if (c->remote_id != -1) {
399 debug2("%s: session already open", __func__);
401 buffer_put_int(r, MUX_S_FAILURE);
402 buffer_put_int(r, rid);
403 buffer_put_cstring(r, "Multiple sessions not supported");
410 for (i = 0; i < env_len; i++)
414 buffer_free(&cctx->cmd);
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__);
424 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
425 buffer_put_int(r, rid);
426 buffer_put_cstring(r, "Permission denied");
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));
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]);
443 window = CHAN_SES_WINDOW_DEFAULT;
444 packetmax = CHAN_SES_PACKET_DEFAULT;
445 if (cctx->want_tty) {
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);
454 nc->ctl_chan = c->self; /* link session -> control channel */
455 c->remote_id = nc->self; /* link control -> session channel */
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));
464 debug2("%s: channel_new: %d linked to control channel %d",
465 __func__, nc->self, nc->ctl_chan);
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);
472 /* reply is deferred, sent by mux_session_confirm */
477 process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
479 debug2("%s: channel %d: alive check", __func__, c->self);
482 buffer_put_int(r, MUX_S_ALIVE);
483 buffer_put_int(r, rid);
484 buffer_put_int(r, (u_int)getpid());
490 process_mux_terminate(u_int rid, Channel *c, Buffer *m, Buffer *r)
492 debug2("%s: channel %d: terminate request", __func__, c->self);
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? ",
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");
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 */
514 format_forward(u_int ftype, Forward *fwd)
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);
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);
533 xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
534 (fwd->listen_host == NULL) ?
535 "LOCALHOST" : fwd->listen_host,
537 fwd->connect_host, fwd->connect_port);
540 fatal("%s: unknown forward type %u", __func__, ftype);
546 compare_host(const char *a, const char *b)
548 if (a == NULL && b == NULL)
550 if (a == NULL || b == NULL)
552 return strcmp(a, b) == 0;
556 compare_forward(Forward *a, Forward *b)
558 if (!compare_host(a->listen_host, b->listen_host))
560 if (a->listen_port != b->listen_port)
562 if (!compare_host(a->connect_host, b->connect_host))
564 if (a->connect_port != b->connect_port)
571 mux_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
573 struct mux_channel_confirm_ctx *fctx = ctxt;
574 char *failmsg = NULL;
579 if ((c = channel_by_id(fctx->cid)) == NULL) {
580 /* no channel for reply */
581 error("%s: unknown channel", __func__);
585 if (fctx->fid >= options.num_remote_forwards) {
586 xasprintf(&failmsg, "unknown forwarding id %d", fctx->fid);
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);
605 buffer_put_int(&out, MUX_S_OK);
606 buffer_put_int(&out, fctx->rid);
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);
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);
622 buffer_put_string(&c->output, buffer_ptr(&out), buffer_len(&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 */
630 process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
633 char *fwd_desc = NULL;
636 int i, ret = 0, freefwd = 1;
638 memset(&fwd, 0, sizeof(fwd));
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__);
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;
656 if (*fwd.connect_host == '\0') {
657 free(fwd.connect_host);
658 fwd.connect_host = NULL;
661 debug2("%s: channel %d: request %s", __func__, c->self,
662 (fwd_desc = format_forward(ftype, &fwd)));
664 if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
665 ftype != MUX_FWD_DYNAMIC) {
666 logit("%s: invalid forwarding type %u", __func__, ftype);
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");
675 if (fwd.listen_port >= 65536) {
676 logit("%s: invalid listen port %u", __func__,
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__,
686 if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL) {
687 logit("%s: missing connect host", __func__);
691 /* Skip forwards that have already been requested */
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)) {
699 debug2("%s: found existing forwarding",
701 buffer_put_int(r, MUX_S_OK);
702 buffer_put_int(r, rid);
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)
713 debug2("%s: found allocated port",
715 buffer_put_int(r, MUX_S_REMOTE_PORT);
716 buffer_put_int(r, rid);
718 options.remote_forwards[i].allocated_port);
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");
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)) {
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");
747 add_local_forward(&options, &fwd);
750 struct mux_channel_confirm_ctx *fctx;
752 fwd.handle = channel_request_remote_forwarding(fwd.listen_host,
753 fwd.listen_port, fwd.connect_host, fwd.connect_port);
756 add_remote_forward(&options, &fwd);
757 fctx = xcalloc(1, sizeof(*fctx));
760 fctx->fid = options.num_remote_forwards - 1;
761 client_register_global_confirm(mux_confirm_remote_forward,
764 c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
765 /* delayed reply in mux_confirm_remote_forward */
768 buffer_put_int(r, MUX_S_OK);
769 buffer_put_int(r, rid);
773 free(fwd.listen_host);
774 free(fwd.connect_host);
780 process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
782 Forward fwd, *found_fwd;
783 char *fwd_desc = NULL;
784 const char *error_reason = NULL;
786 int i, listen_port, ret = 0;
789 memset(&fwd, 0, sizeof(fwd));
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__);
801 fwd.listen_port = lport;
802 fwd.connect_port = cport;
804 if (*fwd.listen_host == '\0') {
805 free(fwd.listen_host);
806 fwd.listen_host = NULL;
808 if (*fwd.connect_host == '\0') {
809 free(fwd.connect_host);
810 fwd.connect_host = NULL;
813 debug2("%s: channel %d: request cancel %s", __func__, c->self,
814 (fwd_desc = format_forward(ftype, &fwd)));
816 /* make sure this has been requested */
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;
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;
840 if (found_fwd == NULL)
841 error_reason = "port not forwarded";
842 else if (ftype == MUX_FWD_REMOTE) {
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.
849 listen_port = (fwd.listen_port == 0) ?
850 found_fwd->allocated_port : fwd.listen_port;
851 if (channel_request_rforward_cancel(fwd.listen_host,
853 error_reason = "port not in permitted opens";
854 } else { /* local and dynamic forwards */
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";
862 if (error_reason == NULL) {
863 buffer_put_int(r, MUX_S_OK);
864 buffer_put_int(r, rid);
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;
871 buffer_put_int(r, MUX_S_FAILURE);
872 buffer_put_int(r, rid);
873 buffer_put_cstring(r, error_reason);
877 free(fwd.listen_host);
878 free(fwd.connect_host);
884 process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
887 char *reserved, *chost;
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) {
897 error("%s: malformed message", __func__);
902 debug2("%s: channel %d: request stdio fwd to %s:%u",
903 __func__, c->self, chost, cport);
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",
910 for (j = 0; j < i; j++)
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");
923 debug3("%s: got fds stdin %d, stdout %d", __func__,
924 new_fd[0], new_fd[1]);
926 /* XXX support multiple child sessions in future */
927 if (c->remote_id != -1) {
928 debug2("%s: session already open", __func__);
930 buffer_put_int(r, MUX_S_FAILURE);
931 buffer_put_int(r, rid);
932 buffer_put_cstring(r, "Multiple sessions not supported");
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? ",
944 debug2("%s: stdio fwd refused by user", __func__);
946 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
947 buffer_put_int(r, rid);
948 buffer_put_cstring(r, "Permission denied");
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]);
959 nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
961 nc->ctl_chan = c->self; /* link session -> control channel */
962 c->remote_id = nc->self; /* link control -> session channel */
964 debug2("%s: channel_new: %d linked to control channel %d",
965 __func__, nc->self, nc->ctl_chan);
967 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
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);
979 process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
981 debug("%s: channel %d: stop listening", __func__, c->self);
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");
995 if (mux_listener_channel != NULL) {
996 channel_free(mux_listener_channel);
998 free(options.control_path);
999 options.control_path = NULL;
1000 mux_listener_channel = NULL;
1001 muxserver_sock = -1;
1005 buffer_put_int(r, MUX_S_OK);
1006 buffer_put_int(r, rid);
1011 /* Channel callbacks fired on read/write from mux slave fd */
1013 mux_master_read_cb(Channel *c)
1015 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
1018 u_int type, rid, have, i;
1022 if (c->mux_ctx == NULL) {
1023 state = xcalloc(1, sizeof(*state));
1025 channel_register_cleanup(c->self,
1026 mux_master_control_cleanup_cb, 0);
1030 buffer_put_int(&out, MUX_MSG_HELLO);
1031 buffer_put_int(&out, SSHMUX_VER);
1033 buffer_put_string(&c->output, buffer_ptr(&out),
1036 debug3("%s: channel %d: hello sent", __func__, c->self);
1043 /* Channel code ensures that we receive whole packets */
1044 if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
1046 error("%s: malformed message", __func__);
1049 buffer_append(&in, ptr, have);
1051 if (buffer_get_int_ret(&type, &in) != 0)
1053 debug3("%s: channel %d packet type 0x%08x len %u",
1054 __func__, c->self, type, buffer_len(&in));
1056 if (type == MUX_MSG_HELLO)
1059 if (!state->hello_rcvd) {
1060 error("%s: expected MUX_MSG_HELLO(0x%08x), "
1061 "received 0x%08x", __func__, MUX_MSG_HELLO, type);
1064 if (buffer_get_int_ret(&rid, &in) != 0)
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);
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");
1081 /* Enqueue reply packet */
1082 if (buffer_len(&out) != 0) {
1083 buffer_put_string(&c->output, buffer_ptr(&out),
1093 mux_exit_message(Channel *c, int exitval)
1098 debug3("%s: channel %d: exit message, exitval %d", __func__, c->self,
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);
1105 /* Append exit message packet to control socket output queue */
1107 buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
1108 buffer_put_int(&m, c->self);
1109 buffer_put_int(&m, exitval);
1111 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1116 mux_tty_alloc_failed(Channel *c)
1121 debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
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);
1127 /* Append exit message packet to control socket output queue */
1129 buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
1130 buffer_put_int(&m, c->self);
1132 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1136 /* Prepare a mux master to listen on a Unix domain socket. */
1138 muxserver_listen(void)
1140 struct sockaddr_un addr;
1143 char *orig_control_path = options.control_path;
1147 if (options.control_path == NULL ||
1148 options.control_master == SSHCTL_MASTER_NO)
1151 debug("setting up multiplex master socket");
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.
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 :
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);
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;
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;
1182 if ((muxserver_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1183 fatal("%s socket(): %s", __func__, strerror(errno));
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);
1191 if (muxserver_sock != -1) {
1192 close(muxserver_sock);
1193 muxserver_sock = -1;
1195 free(orig_control_path);
1196 free(options.control_path);
1197 options.control_path = NULL;
1198 options.control_master = SSHCTL_MASTER_NO;
1201 fatal("%s bind(): %s", __func__, strerror(errno));
1205 if (listen(muxserver_sock, 64) == -1)
1206 fatal("%s listen(): %s", __func__, strerror(errno));
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,
1215 error("ControlSocket %s already exists, disabling multiplexing",
1217 unlink(options.control_path);
1218 goto disable_mux_master;
1220 unlink(options.control_path);
1221 free(options.control_path);
1222 options.control_path = orig_control_path;
1224 set_nonblock(muxserver_sock);
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);
1235 /* Callback on open confirmation in mux master for a mux client session. */
1237 mux_session_confirm(int id, int success, void *arg)
1239 struct mux_session_confirm_ctx *cctx = arg;
1240 const char *display;
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__,
1254 debug3("%s: sending failure reply", __func__);
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");
1263 display = getenv("DISPLAY");
1264 if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1267 /* Get reasonable local authentication information. */
1268 client_x11_get_proto(display, options.xauth_location,
1269 options.forward_x11_trusted, options.forward_x11_timeout,
1271 /* Request forwarding with authentication spoofing. */
1272 debug("Requesting X11 forwarding with authentication "
1274 x11_request_forwarding_with_spoofing(id, display, proto,
1276 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1277 /* XXX exit_on_forward_failure */
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);
1286 client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1287 cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1289 debug3("%s: sending success reply", __func__);
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);
1298 buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1299 buffer_free(&reply);
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);
1307 if (cctx->env != NULL) {
1308 for (i = 0; cctx->env[i] != NULL; i++)
1315 /* ** Multiplexing client support */
1317 /* Exit signal handler */
1319 control_client_sighandler(int signo)
1321 muxclient_terminate = signo;
1325 * Relay signal handler - used to pass some signals from mux client to
1329 control_client_sigrelay(int signo)
1331 int save_errno = errno;
1333 if (muxserver_pid > 1)
1334 kill(muxserver_pid, signo);
1340 mux_client_read(int fd, Buffer *b, u_int need)
1348 pfd.events = POLLIN;
1349 p = buffer_append_space(b, need);
1350 for (have = 0; have < need; ) {
1351 if (muxclient_terminate) {
1355 len = read(fd, p + have, need - have);
1358 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1362 (void)poll(&pfd, 1, -1);
1380 mux_client_write_packet(int fd, Buffer *m)
1389 pfd.events = POLLOUT;
1390 buffer_init(&queue);
1391 buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1393 need = buffer_len(&queue);
1394 ptr = buffer_ptr(&queue);
1396 for (have = 0; have < need; ) {
1397 if (muxclient_terminate) {
1398 buffer_free(&queue);
1402 len = write(fd, ptr + have, need - have);
1405 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1409 (void)poll(&pfd, 1, -1);
1415 buffer_free(&queue);
1421 buffer_free(&queue);
1427 buffer_free(&queue);
1432 mux_client_read_packet(int fd, Buffer *m)
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__,
1444 buffer_free(&queue);
1448 need = get_u32(buffer_ptr(&queue));
1449 if (mux_client_read(fd, &queue, need) != 0) {
1451 debug3("%s: read body failed: %s", __func__, strerror(errno));
1452 buffer_free(&queue);
1456 ptr = buffer_get_string_ptr(&queue, &have);
1457 buffer_append(m, ptr, have);
1458 buffer_free(&queue);
1463 mux_client_hello_exchange(int fd)
1469 buffer_put_int(&m, MUX_MSG_HELLO);
1470 buffer_put_int(&m, SSHMUX_VER);
1473 if (mux_client_write_packet(fd, &m) != 0)
1474 fatal("%s: write packet: %s", __func__, strerror(errno));
1478 /* Read their HELLO */
1479 if (mux_client_read_packet(fd, &m) != 0) {
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);
1498 debug2("Unrecognised master extension \"%s\"", name);
1507 mux_client_request_alive(int fd)
1511 u_int pid, type, rid;
1513 debug3("%s: entering", __func__);
1516 buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1517 buffer_put_int(&m, muxclient_request_id);
1519 if (mux_client_write_packet(fd, &m) != 0)
1520 fatal("%s: write packet: %s", __func__, strerror(errno));
1524 /* Read their reply */
1525 if (mux_client_read_packet(fd, &m) != 0) {
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);
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);
1542 debug3("%s: done pid = %u", __func__, pid);
1544 muxclient_request_id++;
1550 mux_client_request_terminate(int fd)
1556 debug3("%s: entering", __func__);
1559 buffer_put_int(&m, MUX_C_TERMINATE);
1560 buffer_put_int(&m, muxclient_request_id);
1562 if (mux_client_write_packet(fd, &m) != 0)
1563 fatal("%s: write packet: %s", __func__, strerror(errno));
1567 /* Read their reply */
1568 if (mux_client_read_packet(fd, &m) != 0) {
1569 /* Remote end exited already */
1570 if (errno == EPIPE) {
1574 fatal("%s: read from master failed: %s",
1575 __func__, strerror(errno));
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);
1585 case MUX_S_PERMISSION_DENIED:
1586 e = buffer_get_string(&m, NULL);
1587 fatal("Master refused termination request: %s", e);
1589 e = buffer_get_string(&m, NULL);
1590 fatal("%s: termination request failed: %s", __func__, e);
1592 fatal("%s: unexpected response from master 0x%08x",
1596 muxclient_request_id++;
1600 mux_client_forward(int fd, int cancel_flag, u_int ftype, Forward *fwd)
1606 fwd_desc = format_forward(ftype, fwd);
1607 debug("Requesting %s %s",
1608 cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
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);
1622 if (mux_client_write_packet(fd, &m) != 0)
1623 fatal("%s: write packet: %s", __func__, strerror(errno));
1627 /* Read their reply */
1628 if (mux_client_read_packet(fd, &m) != 0) {
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);
1640 case MUX_S_REMOTE_PORT:
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 : "",
1648 if (muxclient_command == SSHMUX_COMMAND_FORWARD)
1649 fprintf(stdout, "%u\n", fwd->allocated_port);
1651 case MUX_S_PERMISSION_DENIED:
1652 e = buffer_get_string(&m, NULL);
1654 error("Master refused forwarding request: %s", e);
1657 e = buffer_get_string(&m, NULL);
1659 error("%s: forwarding request failed: %s", __func__, e);
1662 fatal("%s: unexpected response from master 0x%08x",
1667 muxclient_request_id++;
1672 mux_client_forwards(int fd, int cancel_flag)
1676 debug3("%s: %s forwardings: %d local, %d remote", __func__,
1677 cancel_flag ? "cancel" : "request",
1678 options.num_local_forwards, options.num_remote_forwards);
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)
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)
1697 mux_client_request_session(int fd)
1701 u_int i, rid, sid, esid, exitval, type, exitval_seen;
1702 extern char **environ;
1703 int devnull, rawmode;
1705 debug3("%s: entering", __func__);
1707 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1708 error("%s: master alive request failed", __func__);
1712 signal(SIGPIPE, SIG_IGN);
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)
1723 term = getenv("TERM");
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));
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]);
1747 if (mux_client_write_packet(fd, &m) != 0)
1748 fatal("%s: write packet: %s", __func__, strerror(errno));
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__);
1756 debug3("%s: session request sent", __func__);
1758 /* Read their reply */
1760 if (mux_client_read_packet(fd, &m) != 0) {
1761 error("%s: read from master failed: %s",
1762 __func__, strerror(errno));
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);
1772 case MUX_S_SESSION_OPENED:
1773 sid = buffer_get_int(&m);
1774 debug("%s: master session id: %u", __func__, sid);
1776 case MUX_S_PERMISSION_DENIED:
1777 e = buffer_get_string(&m, NULL);
1779 error("Master refused session request: %s", e);
1782 e = buffer_get_string(&m, NULL);
1784 error("%s: session request failed: %s", __func__, e);
1788 error("%s: unexpected response from master 0x%08x",
1792 muxclient_request_id++;
1794 signal(SIGHUP, control_client_sighandler);
1795 signal(SIGINT, control_client_sighandler);
1796 signal(SIGTERM, control_client_sighandler);
1797 signal(SIGWINCH, control_client_sigrelay);
1801 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
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).
1810 for (exitval = 255, exitval_seen = 0;;) {
1812 if (mux_client_read_packet(fd, &m) != 0)
1814 type = buffer_get_int(&m);
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 ==
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);
1831 fatal("%s: exitval sent twice", __func__);
1832 exitval = buffer_get_int(&m);
1836 e = buffer_get_string(&m, NULL);
1837 fatal("%s: master returned error: %s", __func__, e);
1843 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1845 if (muxclient_terminate) {
1846 debug2("Exiting on signal %ld", (long)muxclient_terminate);
1848 } else if (!exitval_seen) {
1849 debug2("Control master terminated unexpectedly");
1852 debug2("Received exit status from master %d", exitval);
1854 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1855 fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1861 mux_client_request_stdio_fwd(int fd)
1865 u_int type, rid, sid;
1868 debug3("%s: entering", __func__);
1870 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1871 error("%s: master alive request failed", __func__);
1875 signal(SIGPIPE, SIG_IGN);
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)
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);
1893 if (mux_client_write_packet(fd, &m) != 0)
1894 fatal("%s: write packet: %s", __func__, strerror(errno));
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__);
1901 debug3("%s: stdio forward request sent", __func__);
1903 /* Read their reply */
1906 if (mux_client_read_packet(fd, &m) != 0) {
1907 error("%s: read from master failed: %s",
1908 __func__, strerror(errno));
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);
1918 case MUX_S_SESSION_OPENED:
1919 sid = buffer_get_int(&m);
1920 debug("%s: master session id: %u", __func__, sid);
1922 case MUX_S_PERMISSION_DENIED:
1923 e = buffer_get_string(&m, NULL);
1925 fatal("Master refused stdio forwarding request: %s", e);
1927 e = buffer_get_string(&m, NULL);
1929 fatal("%s: stdio forwarding request failed: %s", __func__, e);
1932 error("%s: unexpected response from master 0x%08x",
1936 muxclient_request_id++;
1938 signal(SIGHUP, control_client_sighandler);
1939 signal(SIGINT, control_client_sighandler);
1940 signal(SIGTERM, control_client_sighandler);
1941 signal(SIGWINCH, control_client_sigrelay);
1944 * Stick around until the controlee closes the client_fd.
1947 if (mux_client_read_packet(fd, &m) != 0) {
1948 if (errno == EPIPE ||
1949 (errno == EINTR && muxclient_terminate != 0))
1951 fatal("%s: mux_client_read_packet: %s",
1952 __func__, strerror(errno));
1954 fatal("%s: master returned unexpected message %u", __func__, type);
1958 mux_client_request_stop_listening(int fd)
1964 debug3("%s: entering", __func__);
1967 buffer_put_int(&m, MUX_C_STOP_LISTENING);
1968 buffer_put_int(&m, muxclient_request_id);
1970 if (mux_client_write_packet(fd, &m) != 0)
1971 fatal("%s: write packet: %s", __func__, strerror(errno));
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));
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);
1987 case MUX_S_PERMISSION_DENIED:
1988 e = buffer_get_string(&m, NULL);
1989 fatal("Master refused stop listening request: %s", e);
1991 e = buffer_get_string(&m, NULL);
1992 fatal("%s: stop listening request failed: %s", __func__, e);
1994 fatal("%s: unexpected response from master 0x%08x",
1998 muxclient_request_id++;
2001 /* Multiplex client main loop. */
2003 muxclient(const char *path)
2005 struct sockaddr_un addr;
2010 if (muxclient_command == 0) {
2011 if (stdio_forward_host != NULL)
2012 muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
2014 muxclient_command = SSHMUX_COMMAND_OPEN;
2017 switch (options.control_master) {
2018 case SSHCTL_MASTER_AUTO:
2019 case SSHCTL_MASTER_AUTO_ASK:
2020 debug("auto-mux: Trying existing master");
2022 case SSHCTL_MASTER_NO:
2028 memset(&addr, '\0', sizeof(addr));
2029 addr.sun_family = AF_UNIX;
2030 sun_len = offsetof(struct sockaddr_un, sun_path) +
2033 if (strlcpy(addr.sun_path, path,
2034 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
2035 fatal("ControlPath too long");
2037 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
2038 fatal("%s socket(): %s", __func__, strerror(errno));
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:
2046 fatal("Control socket connect(%.100s): %s", path,
2049 if (errno == ECONNREFUSED &&
2050 options.control_master != SSHCTL_MASTER_NO) {
2051 debug("Stale control socket %.100s, unlinking", path);
2053 } else if (errno == ENOENT) {
2054 debug("Control socket \"%.100s\" does not exist", path);
2056 error("Control socket connect(%.100s): %s", path,
2064 if (mux_client_hello_exchange(sock) != 0) {
2065 error("%s: master hello exchange failed", __func__);
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);
2076 case SSHMUX_COMMAND_TERMINATE:
2077 mux_client_request_terminate(sock);
2078 fprintf(stderr, "Exit request sent.\r\n");
2080 case SSHMUX_COMMAND_FORWARD:
2081 if (mux_client_forwards(sock, 0) != 0)
2082 fatal("%s: master forward request failed", __func__);
2084 case SSHMUX_COMMAND_OPEN:
2085 if (mux_client_forwards(sock, 0) != 0) {
2086 error("%s: master forward request failed", __func__);
2089 mux_client_request_session(sock);
2091 case SSHMUX_COMMAND_STDIO_FWD:
2092 mux_client_request_stdio_fwd(sock);
2094 case SSHMUX_COMMAND_STOP:
2095 mux_client_request_stop_listening(sock);
2096 fprintf(stderr, "Stop listening request sent.\r\n");
2098 case SSHMUX_COMMAND_CANCEL_FWD:
2099 if (mux_client_forwards(sock, 1) != 0)
2100 error("%s: master cancel forward request failed",
2104 fatal("unrecognised muxclient_command %d", muxclient_command);