1 /* $OpenBSD: mux.c,v 1.44 2013/07/12 00:19:58 djm Exp $ */
3 * Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
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.
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.
18 /* ssh session multiplexing support */
22 * - Better signalling from master to slave, especially passing of
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
36 #include <sys/types.h>
37 #include <sys/param.h>
39 #include <sys/socket.h>
58 # ifdef HAVE_SYS_POLL_H
59 # include <sys/poll.h>
67 #include "openbsd-compat/sys-queue.h"
72 #include "pathnames.h"
79 #include "monitor_fdpass.h"
83 #include "clientloop.h"
87 extern Options options;
88 extern int stdin_null_flag;
90 extern int subsystem_flag;
91 extern Buffer command;
92 extern volatile sig_atomic_t quit_pending;
93 extern char *stdio_forward_host;
94 extern int stdio_forward_port;
96 /* Context for session open confirmation callback */
97 struct mux_session_confirm_ctx {
101 u_int want_agent_fwd;
109 /* Context for global channel callback */
110 struct mux_channel_confirm_ctx {
111 u_int cid; /* channel id */
112 u_int rid; /* request id */
113 int fid; /* forward id */
116 /* fd to control socket */
117 int muxserver_sock = -1;
119 /* client request id */
120 u_int muxclient_request_id = 0;
122 /* Multiplexing control command */
123 u_int muxclient_command = 0;
125 /* Set when signalled. */
126 static volatile sig_atomic_t muxclient_terminate = 0;
128 /* PID of multiplex server */
129 static u_int muxserver_pid = 0;
131 static Channel *mux_listener_channel = NULL;
133 struct mux_master_state {
137 /* mux protocol messages */
138 #define MUX_MSG_HELLO 0x00000001
139 #define MUX_C_NEW_SESSION 0x10000002
140 #define MUX_C_ALIVE_CHECK 0x10000004
141 #define MUX_C_TERMINATE 0x10000005
142 #define MUX_C_OPEN_FWD 0x10000006
143 #define MUX_C_CLOSE_FWD 0x10000007
144 #define MUX_C_NEW_STDIO_FWD 0x10000008
145 #define MUX_C_STOP_LISTENING 0x10000009
146 #define MUX_S_OK 0x80000001
147 #define MUX_S_PERMISSION_DENIED 0x80000002
148 #define MUX_S_FAILURE 0x80000003
149 #define MUX_S_EXIT_MESSAGE 0x80000004
150 #define MUX_S_ALIVE 0x80000005
151 #define MUX_S_SESSION_OPENED 0x80000006
152 #define MUX_S_REMOTE_PORT 0x80000007
153 #define MUX_S_TTY_ALLOC_FAIL 0x80000008
155 /* type codes for MUX_C_OPEN_FWD and MUX_C_CLOSE_FWD */
156 #define MUX_FWD_LOCAL 1
157 #define MUX_FWD_REMOTE 2
158 #define MUX_FWD_DYNAMIC 3
160 static void mux_session_confirm(int, int, void *);
162 static int process_mux_master_hello(u_int, Channel *, Buffer *, Buffer *);
163 static int process_mux_new_session(u_int, Channel *, Buffer *, Buffer *);
164 static int process_mux_alive_check(u_int, Channel *, Buffer *, Buffer *);
165 static int process_mux_terminate(u_int, Channel *, Buffer *, Buffer *);
166 static int process_mux_open_fwd(u_int, Channel *, Buffer *, Buffer *);
167 static int process_mux_close_fwd(u_int, Channel *, Buffer *, Buffer *);
168 static int process_mux_stdio_fwd(u_int, Channel *, Buffer *, Buffer *);
169 static int process_mux_stop_listening(u_int, Channel *, Buffer *, Buffer *);
171 static const struct {
173 int (*handler)(u_int, Channel *, Buffer *, Buffer *);
174 } mux_master_handlers[] = {
175 { MUX_MSG_HELLO, process_mux_master_hello },
176 { MUX_C_NEW_SESSION, process_mux_new_session },
177 { MUX_C_ALIVE_CHECK, process_mux_alive_check },
178 { MUX_C_TERMINATE, process_mux_terminate },
179 { MUX_C_OPEN_FWD, process_mux_open_fwd },
180 { MUX_C_CLOSE_FWD, process_mux_close_fwd },
181 { MUX_C_NEW_STDIO_FWD, process_mux_stdio_fwd },
182 { MUX_C_STOP_LISTENING, process_mux_stop_listening },
186 /* Cleanup callback fired on closure of mux slave _session_ channel */
189 mux_master_session_cleanup_cb(int cid, void *unused)
191 Channel *cc, *c = channel_by_id(cid);
193 debug3("%s: entering for channel %d", __func__, cid);
195 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
196 if (c->ctl_chan != -1) {
197 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
198 fatal("%s: channel %d missing control channel %d",
199 __func__, c->self, c->ctl_chan);
202 chan_rcvd_oclose(cc);
204 channel_cancel_cleanup(c->self);
207 /* Cleanup callback fired on closure of mux slave _control_ channel */
210 mux_master_control_cleanup_cb(int cid, void *unused)
212 Channel *sc, *c = channel_by_id(cid);
214 debug3("%s: entering for channel %d", __func__, cid);
216 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
217 if (c->remote_id != -1) {
218 if ((sc = channel_by_id(c->remote_id)) == NULL)
219 fatal("%s: channel %d missing session channel %d",
220 __func__, c->self, c->remote_id);
223 if (sc->type != SSH_CHANNEL_OPEN &&
224 sc->type != SSH_CHANNEL_OPENING) {
225 debug2("%s: channel %d: not open", __func__, sc->self);
228 if (sc->istate == CHAN_INPUT_OPEN)
229 chan_read_failed(sc);
230 if (sc->ostate == CHAN_OUTPUT_OPEN)
231 chan_write_failed(sc);
234 channel_cancel_cleanup(c->self);
237 /* Check mux client environment variables before passing them to mux master. */
239 env_permitted(char *env)
242 char name[1024], *cp;
244 if ((cp = strchr(env, '=')) == NULL || cp == env)
246 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
247 if (ret <= 0 || (size_t)ret >= sizeof(name)) {
248 error("env_permitted: name '%.100s...' too long", env);
252 for (i = 0; i < options.num_send_env; i++)
253 if (match_pattern(name, options.send_env[i]))
259 /* Mux master protocol message handlers */
262 process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
265 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
268 fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
269 if (state->hello_rcvd) {
270 error("%s: HELLO received twice", __func__);
273 if (buffer_get_int_ret(&ver, m) != 0) {
275 error("%s: malformed message", __func__);
278 if (ver != SSHMUX_VER) {
279 error("Unsupported multiplexing protocol version %d "
280 "(expected %d)", ver, SSHMUX_VER);
283 debug2("%s: channel %d slave version %u", __func__, c->self, ver);
285 /* No extensions are presently defined */
286 while (buffer_len(m) > 0) {
287 char *name = buffer_get_string_ret(m, NULL);
288 char *value = buffer_get_string_ret(m, NULL);
290 if (name == NULL || value == NULL) {
295 debug2("Unrecognised slave extension \"%s\"", name);
299 state->hello_rcvd = 1;
304 process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
307 struct mux_session_confirm_ctx *cctx;
308 char *reserved, *cmd, *cp;
309 u_int i, j, len, env_len, escape_char, window, packetmax;
312 /* Reply for SSHMUX_COMMAND_OPEN */
313 cctx = xcalloc(1, sizeof(*cctx));
316 cmd = reserved = NULL;
319 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
320 buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
321 buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
322 buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
323 buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
324 buffer_get_int_ret(&escape_char, m) != 0 ||
325 (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
326 (cmd = buffer_get_string_ret(m, &len)) == NULL) {
330 for (j = 0; j < env_len; j++)
335 error("%s: malformed message", __func__);
341 while (buffer_len(m) > 0) {
342 #define MUX_MAX_ENV_VARS 4096
343 if ((cp = buffer_get_string_ret(m, &len)) == NULL)
345 if (!env_permitted(cp)) {
349 cctx->env = xrealloc(cctx->env, env_len + 2,
351 cctx->env[env_len++] = cp;
352 cctx->env[env_len] = NULL;
353 if (env_len > MUX_MAX_ENV_VARS) {
354 error(">%d environment variables received, ignoring "
355 "additional", MUX_MAX_ENV_VARS);
360 debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
361 "term \"%s\", cmd \"%s\", env %u", __func__, c->self,
362 cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
363 cctx->want_subsys, cctx->term, cmd, env_len);
365 buffer_init(&cctx->cmd);
366 buffer_append(&cctx->cmd, cmd, strlen(cmd));
370 /* Gather fds from client */
371 for(i = 0; i < 3; i++) {
372 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
373 error("%s: failed to receive fd %d from slave",
375 for (j = 0; j < i; j++)
377 for (j = 0; j < env_len; j++)
381 buffer_free(&cctx->cmd);
385 buffer_put_int(r, MUX_S_FAILURE);
386 buffer_put_int(r, rid);
387 buffer_put_cstring(r,
388 "did not receive file descriptors");
393 debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
394 new_fd[0], new_fd[1], new_fd[2]);
396 /* XXX support multiple child sessions in future */
397 if (c->remote_id != -1) {
398 debug2("%s: session already open", __func__);
400 buffer_put_int(r, MUX_S_FAILURE);
401 buffer_put_int(r, rid);
402 buffer_put_cstring(r, "Multiple sessions not supported");
409 for (i = 0; i < env_len; i++)
413 buffer_free(&cctx->cmd);
418 if (options.control_master == SSHCTL_MASTER_ASK ||
419 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
420 if (!ask_permission("Allow shared connection to %s? ", host)) {
421 debug2("%s: session refused by user", __func__);
423 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
424 buffer_put_int(r, rid);
425 buffer_put_cstring(r, "Permission denied");
430 /* Try to pick up ttymodes from client before it goes raw */
431 if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
432 error("%s: tcgetattr: %s", __func__, strerror(errno));
434 /* enable nonblocking unless tty */
435 if (!isatty(new_fd[0]))
436 set_nonblock(new_fd[0]);
437 if (!isatty(new_fd[1]))
438 set_nonblock(new_fd[1]);
439 if (!isatty(new_fd[2]))
440 set_nonblock(new_fd[2]);
442 window = CHAN_SES_WINDOW_DEFAULT;
443 packetmax = CHAN_SES_PACKET_DEFAULT;
444 if (cctx->want_tty) {
449 nc = channel_new("session", SSH_CHANNEL_OPENING,
450 new_fd[0], new_fd[1], new_fd[2], window, packetmax,
451 CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
453 nc->ctl_chan = c->self; /* link session -> control channel */
454 c->remote_id = nc->self; /* link control -> session channel */
456 if (cctx->want_tty && escape_char != 0xffffffff) {
457 channel_register_filter(nc->self,
458 client_simple_escape_filter, NULL,
459 client_filter_cleanup,
460 client_new_escape_filter_ctx((int)escape_char));
463 debug2("%s: channel_new: %d linked to control channel %d",
464 __func__, nc->self, nc->ctl_chan);
466 channel_send_open(nc->self);
467 channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
468 c->mux_pause = 1; /* stop handling messages until open_confirm done */
469 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
471 /* reply is deferred, sent by mux_session_confirm */
476 process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
478 debug2("%s: channel %d: alive check", __func__, c->self);
481 buffer_put_int(r, MUX_S_ALIVE);
482 buffer_put_int(r, rid);
483 buffer_put_int(r, (u_int)getpid());
489 process_mux_terminate(u_int rid, Channel *c, Buffer *m, Buffer *r)
491 debug2("%s: channel %d: terminate request", __func__, c->self);
493 if (options.control_master == SSHCTL_MASTER_ASK ||
494 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
495 if (!ask_permission("Terminate shared connection to %s? ",
497 debug2("%s: termination refused by user", __func__);
498 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
499 buffer_put_int(r, rid);
500 buffer_put_cstring(r, "Permission denied");
506 buffer_put_int(r, MUX_S_OK);
507 buffer_put_int(r, rid);
508 /* XXX exit happens too soon - message never makes it to client */
513 format_forward(u_int ftype, Forward *fwd)
519 xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
520 (fwd->listen_host == NULL) ?
521 (options.gateway_ports ? "*" : "LOCALHOST") :
522 fwd->listen_host, fwd->listen_port,
523 fwd->connect_host, fwd->connect_port);
525 case MUX_FWD_DYNAMIC:
526 xasprintf(&ret, "dynamic forward %.200s:%d -> *",
527 (fwd->listen_host == NULL) ?
528 (options.gateway_ports ? "*" : "LOCALHOST") :
529 fwd->listen_host, fwd->listen_port);
532 xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
533 (fwd->listen_host == NULL) ?
534 "LOCALHOST" : fwd->listen_host,
536 fwd->connect_host, fwd->connect_port);
539 fatal("%s: unknown forward type %u", __func__, ftype);
545 compare_host(const char *a, const char *b)
547 if (a == NULL && b == NULL)
549 if (a == NULL || b == NULL)
551 return strcmp(a, b) == 0;
555 compare_forward(Forward *a, Forward *b)
557 if (!compare_host(a->listen_host, b->listen_host))
559 if (a->listen_port != b->listen_port)
561 if (!compare_host(a->connect_host, b->connect_host))
563 if (a->connect_port != b->connect_port)
570 mux_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
572 struct mux_channel_confirm_ctx *fctx = ctxt;
573 char *failmsg = NULL;
578 if ((c = channel_by_id(fctx->cid)) == NULL) {
579 /* no channel for reply */
580 error("%s: unknown channel", __func__);
584 if (fctx->fid >= options.num_remote_forwards) {
585 xasprintf(&failmsg, "unknown forwarding id %d", fctx->fid);
588 rfwd = &options.remote_forwards[fctx->fid];
589 debug("%s: %s for: listen %d, connect %s:%d", __func__,
590 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
591 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
592 if (type == SSH2_MSG_REQUEST_SUCCESS) {
593 if (rfwd->listen_port == 0) {
594 rfwd->allocated_port = packet_get_int();
595 logit("Allocated port %u for mux remote forward"
596 " to %s:%d", rfwd->allocated_port,
597 rfwd->connect_host, rfwd->connect_port);
598 buffer_put_int(&out, MUX_S_REMOTE_PORT);
599 buffer_put_int(&out, fctx->rid);
600 buffer_put_int(&out, rfwd->allocated_port);
601 channel_update_permitted_opens(rfwd->handle,
602 rfwd->allocated_port);
604 buffer_put_int(&out, MUX_S_OK);
605 buffer_put_int(&out, fctx->rid);
609 if (rfwd->listen_port == 0)
610 channel_update_permitted_opens(rfwd->handle, -1);
611 xasprintf(&failmsg, "remote port forwarding failed for "
612 "listen port %d", rfwd->listen_port);
615 error("%s: %s", __func__, failmsg);
616 buffer_put_int(&out, MUX_S_FAILURE);
617 buffer_put_int(&out, fctx->rid);
618 buffer_put_cstring(&out, failmsg);
621 buffer_put_string(&c->output, buffer_ptr(&out), buffer_len(&out));
623 if (c->mux_pause <= 0)
624 fatal("%s: mux_pause %d", __func__, c->mux_pause);
625 c->mux_pause = 0; /* start processing messages again */
629 process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
632 char *fwd_desc = NULL;
635 int i, ret = 0, freefwd = 1;
637 memset(&fwd, 0, sizeof(fwd));
639 if (buffer_get_int_ret(&ftype, m) != 0 ||
640 (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
641 buffer_get_int_ret(&lport, m) != 0 ||
642 (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
643 buffer_get_int_ret(&cport, m) != 0 ||
644 lport > 65535 || cport > 65535) {
645 error("%s: malformed message", __func__);
649 fwd.listen_port = lport;
650 fwd.connect_port = cport;
651 if (*fwd.listen_host == '\0') {
652 free(fwd.listen_host);
653 fwd.listen_host = NULL;
655 if (*fwd.connect_host == '\0') {
656 free(fwd.connect_host);
657 fwd.connect_host = NULL;
660 debug2("%s: channel %d: request %s", __func__, c->self,
661 (fwd_desc = format_forward(ftype, &fwd)));
663 if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
664 ftype != MUX_FWD_DYNAMIC) {
665 logit("%s: invalid forwarding type %u", __func__, ftype);
667 free(fwd.listen_host);
668 free(fwd.connect_host);
669 buffer_put_int(r, MUX_S_FAILURE);
670 buffer_put_int(r, rid);
671 buffer_put_cstring(r, "Invalid forwarding request");
674 if (fwd.listen_port >= 65536) {
675 logit("%s: invalid listen port %u", __func__,
679 if (fwd.connect_port >= 65536 || (ftype != MUX_FWD_DYNAMIC &&
680 ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
681 logit("%s: invalid connect port %u", __func__,
685 if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL) {
686 logit("%s: missing connect host", __func__);
690 /* Skip forwards that have already been requested */
693 case MUX_FWD_DYNAMIC:
694 for (i = 0; i < options.num_local_forwards; i++) {
695 if (compare_forward(&fwd,
696 options.local_forwards + i)) {
698 debug2("%s: found existing forwarding",
700 buffer_put_int(r, MUX_S_OK);
701 buffer_put_int(r, rid);
707 for (i = 0; i < options.num_remote_forwards; i++) {
708 if (compare_forward(&fwd,
709 options.remote_forwards + i)) {
710 if (fwd.listen_port != 0)
712 debug2("%s: found allocated port",
714 buffer_put_int(r, MUX_S_REMOTE_PORT);
715 buffer_put_int(r, rid);
717 options.remote_forwards[i].allocated_port);
724 if (options.control_master == SSHCTL_MASTER_ASK ||
725 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
726 if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
727 debug2("%s: forwarding refused by user", __func__);
728 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
729 buffer_put_int(r, rid);
730 buffer_put_cstring(r, "Permission denied");
735 if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
736 if (!channel_setup_local_fwd_listener(fwd.listen_host,
737 fwd.listen_port, fwd.connect_host, fwd.connect_port,
738 options.gateway_ports)) {
740 logit("slave-requested %s failed", fwd_desc);
741 buffer_put_int(r, MUX_S_FAILURE);
742 buffer_put_int(r, rid);
743 buffer_put_cstring(r, "Port forwarding failed");
746 add_local_forward(&options, &fwd);
749 struct mux_channel_confirm_ctx *fctx;
751 fwd.handle = channel_request_remote_forwarding(fwd.listen_host,
752 fwd.listen_port, fwd.connect_host, fwd.connect_port);
755 add_remote_forward(&options, &fwd);
756 fctx = xcalloc(1, sizeof(*fctx));
759 fctx->fid = options.num_remote_forwards - 1;
760 client_register_global_confirm(mux_confirm_remote_forward,
763 c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
764 /* delayed reply in mux_confirm_remote_forward */
767 buffer_put_int(r, MUX_S_OK);
768 buffer_put_int(r, rid);
772 free(fwd.listen_host);
773 free(fwd.connect_host);
779 process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
781 Forward fwd, *found_fwd;
782 char *fwd_desc = NULL;
783 const char *error_reason = NULL;
785 int i, listen_port, ret = 0;
788 memset(&fwd, 0, sizeof(fwd));
790 if (buffer_get_int_ret(&ftype, m) != 0 ||
791 (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
792 buffer_get_int_ret(&lport, m) != 0 ||
793 (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
794 buffer_get_int_ret(&cport, m) != 0 ||
795 lport > 65535 || cport > 65535) {
796 error("%s: malformed message", __func__);
800 fwd.listen_port = lport;
801 fwd.connect_port = cport;
803 if (*fwd.listen_host == '\0') {
804 free(fwd.listen_host);
805 fwd.listen_host = NULL;
807 if (*fwd.connect_host == '\0') {
808 free(fwd.connect_host);
809 fwd.connect_host = NULL;
812 debug2("%s: channel %d: request cancel %s", __func__, c->self,
813 (fwd_desc = format_forward(ftype, &fwd)));
815 /* make sure this has been requested */
819 case MUX_FWD_DYNAMIC:
820 for (i = 0; i < options.num_local_forwards; i++) {
821 if (compare_forward(&fwd,
822 options.local_forwards + i)) {
823 found_fwd = options.local_forwards + i;
829 for (i = 0; i < options.num_remote_forwards; i++) {
830 if (compare_forward(&fwd,
831 options.remote_forwards + i)) {
832 found_fwd = options.remote_forwards + i;
839 if (found_fwd == NULL)
840 error_reason = "port not forwarded";
841 else if (ftype == MUX_FWD_REMOTE) {
843 * This shouldn't fail unless we confused the host/port
844 * between options.remote_forwards and permitted_opens.
845 * However, for dynamic allocated listen ports we need
846 * to lookup the actual listen port.
848 listen_port = (fwd.listen_port == 0) ?
849 found_fwd->allocated_port : fwd.listen_port;
850 if (channel_request_rforward_cancel(fwd.listen_host,
852 error_reason = "port not in permitted opens";
853 } else { /* local and dynamic forwards */
855 if (channel_cancel_lport_listener(fwd.listen_host,
856 fwd.listen_port, fwd.connect_port,
857 options.gateway_ports) == -1)
858 error_reason = "port not found";
861 if (error_reason == NULL) {
862 buffer_put_int(r, MUX_S_OK);
863 buffer_put_int(r, rid);
865 free(found_fwd->listen_host);
866 free(found_fwd->connect_host);
867 found_fwd->listen_host = found_fwd->connect_host = NULL;
868 found_fwd->listen_port = found_fwd->connect_port = 0;
870 buffer_put_int(r, MUX_S_FAILURE);
871 buffer_put_int(r, rid);
872 buffer_put_cstring(r, error_reason);
876 free(fwd.listen_host);
877 free(fwd.connect_host);
883 process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
886 char *reserved, *chost;
890 chost = reserved = NULL;
891 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
892 (chost = buffer_get_string_ret(m, NULL)) == NULL ||
893 buffer_get_int_ret(&cport, m) != 0) {
896 error("%s: malformed message", __func__);
901 debug2("%s: channel %d: request stdio fwd to %s:%u",
902 __func__, c->self, chost, cport);
904 /* Gather fds from client */
905 for(i = 0; i < 2; i++) {
906 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
907 error("%s: failed to receive fd %d from slave",
909 for (j = 0; j < i; j++)
914 buffer_put_int(r, MUX_S_FAILURE);
915 buffer_put_int(r, rid);
916 buffer_put_cstring(r,
917 "did not receive file descriptors");
922 debug3("%s: got fds stdin %d, stdout %d", __func__,
923 new_fd[0], new_fd[1]);
925 /* XXX support multiple child sessions in future */
926 if (c->remote_id != -1) {
927 debug2("%s: session already open", __func__);
929 buffer_put_int(r, MUX_S_FAILURE);
930 buffer_put_int(r, rid);
931 buffer_put_cstring(r, "Multiple sessions not supported");
939 if (options.control_master == SSHCTL_MASTER_ASK ||
940 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
941 if (!ask_permission("Allow forward to %s:%u? ",
943 debug2("%s: stdio fwd refused by user", __func__);
945 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
946 buffer_put_int(r, rid);
947 buffer_put_cstring(r, "Permission denied");
952 /* enable nonblocking unless tty */
953 if (!isatty(new_fd[0]))
954 set_nonblock(new_fd[0]);
955 if (!isatty(new_fd[1]))
956 set_nonblock(new_fd[1]);
958 nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
960 nc->ctl_chan = c->self; /* link session -> control channel */
961 c->remote_id = nc->self; /* link control -> session channel */
963 debug2("%s: channel_new: %d linked to control channel %d",
964 __func__, nc->self, nc->ctl_chan);
966 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
969 /* XXX defer until channel confirmed */
970 buffer_put_int(r, MUX_S_SESSION_OPENED);
971 buffer_put_int(r, rid);
972 buffer_put_int(r, nc->self);
978 process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
980 debug("%s: channel %d: stop listening", __func__, c->self);
982 if (options.control_master == SSHCTL_MASTER_ASK ||
983 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
984 if (!ask_permission("Disable further multiplexing on shared "
985 "connection to %s? ", host)) {
986 debug2("%s: stop listen refused by user", __func__);
987 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
988 buffer_put_int(r, rid);
989 buffer_put_cstring(r, "Permission denied");
994 if (mux_listener_channel != NULL) {
995 channel_free(mux_listener_channel);
997 free(options.control_path);
998 options.control_path = NULL;
999 mux_listener_channel = NULL;
1000 muxserver_sock = -1;
1004 buffer_put_int(r, MUX_S_OK);
1005 buffer_put_int(r, rid);
1010 /* Channel callbacks fired on read/write from mux slave fd */
1012 mux_master_read_cb(Channel *c)
1014 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
1017 u_int type, rid, have, i;
1021 if (c->mux_ctx == NULL) {
1022 state = xcalloc(1, sizeof(*state));
1024 channel_register_cleanup(c->self,
1025 mux_master_control_cleanup_cb, 0);
1029 buffer_put_int(&out, MUX_MSG_HELLO);
1030 buffer_put_int(&out, SSHMUX_VER);
1032 buffer_put_string(&c->output, buffer_ptr(&out),
1035 debug3("%s: channel %d: hello sent", __func__, c->self);
1042 /* Channel code ensures that we receive whole packets */
1043 if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
1045 error("%s: malformed message", __func__);
1048 buffer_append(&in, ptr, have);
1050 if (buffer_get_int_ret(&type, &in) != 0)
1052 debug3("%s: channel %d packet type 0x%08x len %u",
1053 __func__, c->self, type, buffer_len(&in));
1055 if (type == MUX_MSG_HELLO)
1058 if (!state->hello_rcvd) {
1059 error("%s: expected MUX_MSG_HELLO(0x%08x), "
1060 "received 0x%08x", __func__, MUX_MSG_HELLO, type);
1063 if (buffer_get_int_ret(&rid, &in) != 0)
1067 for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
1068 if (type == mux_master_handlers[i].type) {
1069 ret = mux_master_handlers[i].handler(rid, c, &in, &out);
1073 if (mux_master_handlers[i].handler == NULL) {
1074 error("%s: unsupported mux message 0x%08x", __func__, type);
1075 buffer_put_int(&out, MUX_S_FAILURE);
1076 buffer_put_int(&out, rid);
1077 buffer_put_cstring(&out, "unsupported request");
1080 /* Enqueue reply packet */
1081 if (buffer_len(&out) != 0) {
1082 buffer_put_string(&c->output, buffer_ptr(&out),
1092 mux_exit_message(Channel *c, int exitval)
1097 debug3("%s: channel %d: exit message, exitval %d", __func__, c->self,
1100 if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1101 fatal("%s: channel %d missing mux channel %d",
1102 __func__, c->self, c->ctl_chan);
1104 /* Append exit message packet to control socket output queue */
1106 buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
1107 buffer_put_int(&m, c->self);
1108 buffer_put_int(&m, exitval);
1110 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1115 mux_tty_alloc_failed(Channel *c)
1120 debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
1122 if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1123 fatal("%s: channel %d missing mux channel %d",
1124 __func__, c->self, c->ctl_chan);
1126 /* Append exit message packet to control socket output queue */
1128 buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
1129 buffer_put_int(&m, c->self);
1131 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1135 /* Prepare a mux master to listen on a Unix domain socket. */
1137 muxserver_listen(void)
1139 struct sockaddr_un addr;
1142 char *orig_control_path = options.control_path;
1146 if (options.control_path == NULL ||
1147 options.control_master == SSHCTL_MASTER_NO)
1150 debug("setting up multiplex master socket");
1153 * Use a temporary path before listen so we can pseudo-atomically
1154 * establish the listening socket in its final location to avoid
1155 * other processes racing in between bind() and listen() and hitting
1156 * an unready socket.
1158 for (i = 0; i < sizeof(rbuf) - 1; i++) {
1159 r = arc4random_uniform(26+26+10);
1160 rbuf[i] = (r < 26) ? 'a' + r :
1161 (r < 26*2) ? 'A' + r - 26 :
1164 rbuf[sizeof(rbuf) - 1] = '\0';
1165 options.control_path = NULL;
1166 xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
1167 debug3("%s: temporary control path %s", __func__, options.control_path);
1169 memset(&addr, '\0', sizeof(addr));
1170 addr.sun_family = AF_UNIX;
1171 sun_len = offsetof(struct sockaddr_un, sun_path) +
1172 strlen(options.control_path) + 1;
1174 if (strlcpy(addr.sun_path, options.control_path,
1175 sizeof(addr.sun_path)) >= sizeof(addr.sun_path)) {
1176 error("ControlPath \"%s\" too long for Unix domain socket",
1177 options.control_path);
1178 goto disable_mux_master;
1181 if ((muxserver_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1182 fatal("%s socket(): %s", __func__, strerror(errno));
1184 old_umask = umask(0177);
1185 if (bind(muxserver_sock, (struct sockaddr *)&addr, sun_len) == -1) {
1186 if (errno == EINVAL || errno == EADDRINUSE) {
1187 error("ControlSocket %s already exists, "
1188 "disabling multiplexing", options.control_path);
1190 if (muxserver_sock != -1) {
1191 close(muxserver_sock);
1192 muxserver_sock = -1;
1194 free(orig_control_path);
1195 free(options.control_path);
1196 options.control_path = NULL;
1197 options.control_master = SSHCTL_MASTER_NO;
1200 fatal("%s bind(): %s", __func__, strerror(errno));
1204 if (listen(muxserver_sock, 64) == -1)
1205 fatal("%s listen(): %s", __func__, strerror(errno));
1207 /* Now atomically "move" the mux socket into position */
1208 if (link(options.control_path, orig_control_path) != 0) {
1209 if (errno != EEXIST) {
1210 fatal("%s: link mux listener %s => %s: %s", __func__,
1211 options.control_path, orig_control_path,
1214 error("ControlSocket %s already exists, disabling multiplexing",
1216 unlink(options.control_path);
1217 goto disable_mux_master;
1219 unlink(options.control_path);
1220 free(options.control_path);
1221 options.control_path = orig_control_path;
1223 set_nonblock(muxserver_sock);
1225 mux_listener_channel = channel_new("mux listener",
1226 SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
1227 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1228 0, options.control_path, 1);
1229 mux_listener_channel->mux_rcb = mux_master_read_cb;
1230 debug3("%s: mux listener channel %d fd %d", __func__,
1231 mux_listener_channel->self, mux_listener_channel->sock);
1234 /* Callback on open confirmation in mux master for a mux client session. */
1236 mux_session_confirm(int id, int success, void *arg)
1238 struct mux_session_confirm_ctx *cctx = arg;
1239 const char *display;
1245 fatal("%s: cctx == NULL", __func__);
1246 if ((c = channel_by_id(id)) == NULL)
1247 fatal("%s: no channel for id %d", __func__, id);
1248 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1249 fatal("%s: channel %d lacks control channel %d", __func__,
1253 debug3("%s: sending failure reply", __func__);
1255 buffer_init(&reply);
1256 buffer_put_int(&reply, MUX_S_FAILURE);
1257 buffer_put_int(&reply, cctx->rid);
1258 buffer_put_cstring(&reply, "Session open refused by peer");
1262 display = getenv("DISPLAY");
1263 if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1266 /* Get reasonable local authentication information. */
1267 client_x11_get_proto(display, options.xauth_location,
1268 options.forward_x11_trusted, options.forward_x11_timeout,
1270 /* Request forwarding with authentication spoofing. */
1271 debug("Requesting X11 forwarding with authentication "
1273 x11_request_forwarding_with_spoofing(id, display, proto,
1275 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1276 /* XXX exit_on_forward_failure */
1279 if (cctx->want_agent_fwd && options.forward_agent) {
1280 debug("Requesting authentication agent forwarding.");
1281 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1285 client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1286 cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1288 debug3("%s: sending success reply", __func__);
1290 buffer_init(&reply);
1291 buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1292 buffer_put_int(&reply, cctx->rid);
1293 buffer_put_int(&reply, c->self);
1297 buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1298 buffer_free(&reply);
1300 if (cc->mux_pause <= 0)
1301 fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1302 cc->mux_pause = 0; /* start processing messages again */
1303 c->open_confirm_ctx = NULL;
1304 buffer_free(&cctx->cmd);
1306 if (cctx->env != NULL) {
1307 for (i = 0; cctx->env[i] != NULL; i++)
1314 /* ** Multiplexing client support */
1316 /* Exit signal handler */
1318 control_client_sighandler(int signo)
1320 muxclient_terminate = signo;
1324 * Relay signal handler - used to pass some signals from mux client to
1328 control_client_sigrelay(int signo)
1330 int save_errno = errno;
1332 if (muxserver_pid > 1)
1333 kill(muxserver_pid, signo);
1339 mux_client_read(int fd, Buffer *b, u_int need)
1347 pfd.events = POLLIN;
1348 p = buffer_append_space(b, need);
1349 for (have = 0; have < need; ) {
1350 if (muxclient_terminate) {
1354 len = read(fd, p + have, need - have);
1357 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1361 (void)poll(&pfd, 1, -1);
1379 mux_client_write_packet(int fd, Buffer *m)
1388 pfd.events = POLLOUT;
1389 buffer_init(&queue);
1390 buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1392 need = buffer_len(&queue);
1393 ptr = buffer_ptr(&queue);
1395 for (have = 0; have < need; ) {
1396 if (muxclient_terminate) {
1397 buffer_free(&queue);
1401 len = write(fd, ptr + have, need - have);
1404 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1408 (void)poll(&pfd, 1, -1);
1414 buffer_free(&queue);
1420 buffer_free(&queue);
1426 buffer_free(&queue);
1431 mux_client_read_packet(int fd, Buffer *m)
1438 buffer_init(&queue);
1439 if (mux_client_read(fd, &queue, 4) != 0) {
1440 if ((oerrno = errno) == EPIPE)
1441 debug3("%s: read header failed: %s", __func__,
1443 buffer_free(&queue);
1447 need = get_u32(buffer_ptr(&queue));
1448 if (mux_client_read(fd, &queue, need) != 0) {
1450 debug3("%s: read body failed: %s", __func__, strerror(errno));
1451 buffer_free(&queue);
1455 ptr = buffer_get_string_ptr(&queue, &have);
1456 buffer_append(m, ptr, have);
1457 buffer_free(&queue);
1462 mux_client_hello_exchange(int fd)
1468 buffer_put_int(&m, MUX_MSG_HELLO);
1469 buffer_put_int(&m, SSHMUX_VER);
1472 if (mux_client_write_packet(fd, &m) != 0)
1473 fatal("%s: write packet: %s", __func__, strerror(errno));
1477 /* Read their HELLO */
1478 if (mux_client_read_packet(fd, &m) != 0) {
1483 type = buffer_get_int(&m);
1484 if (type != MUX_MSG_HELLO)
1485 fatal("%s: expected HELLO (%u) received %u",
1486 __func__, MUX_MSG_HELLO, type);
1487 ver = buffer_get_int(&m);
1488 if (ver != SSHMUX_VER)
1489 fatal("Unsupported multiplexing protocol version %d "
1490 "(expected %d)", ver, SSHMUX_VER);
1491 debug2("%s: master version %u", __func__, ver);
1492 /* No extensions are presently defined */
1493 while (buffer_len(&m) > 0) {
1494 char *name = buffer_get_string(&m, NULL);
1495 char *value = buffer_get_string(&m, NULL);
1497 debug2("Unrecognised master extension \"%s\"", name);
1506 mux_client_request_alive(int fd)
1510 u_int pid, type, rid;
1512 debug3("%s: entering", __func__);
1515 buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1516 buffer_put_int(&m, muxclient_request_id);
1518 if (mux_client_write_packet(fd, &m) != 0)
1519 fatal("%s: write packet: %s", __func__, strerror(errno));
1523 /* Read their reply */
1524 if (mux_client_read_packet(fd, &m) != 0) {
1529 type = buffer_get_int(&m);
1530 if (type != MUX_S_ALIVE) {
1531 e = buffer_get_string(&m, NULL);
1532 fatal("%s: master returned error: %s", __func__, e);
1535 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1536 fatal("%s: out of sequence reply: my id %u theirs %u",
1537 __func__, muxclient_request_id, rid);
1538 pid = buffer_get_int(&m);
1541 debug3("%s: done pid = %u", __func__, pid);
1543 muxclient_request_id++;
1549 mux_client_request_terminate(int fd)
1555 debug3("%s: entering", __func__);
1558 buffer_put_int(&m, MUX_C_TERMINATE);
1559 buffer_put_int(&m, muxclient_request_id);
1561 if (mux_client_write_packet(fd, &m) != 0)
1562 fatal("%s: write packet: %s", __func__, strerror(errno));
1566 /* Read their reply */
1567 if (mux_client_read_packet(fd, &m) != 0) {
1568 /* Remote end exited already */
1569 if (errno == EPIPE) {
1573 fatal("%s: read from master failed: %s",
1574 __func__, strerror(errno));
1577 type = buffer_get_int(&m);
1578 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1579 fatal("%s: out of sequence reply: my id %u theirs %u",
1580 __func__, muxclient_request_id, rid);
1584 case MUX_S_PERMISSION_DENIED:
1585 e = buffer_get_string(&m, NULL);
1586 fatal("Master refused termination request: %s", e);
1588 e = buffer_get_string(&m, NULL);
1589 fatal("%s: termination request failed: %s", __func__, e);
1591 fatal("%s: unexpected response from master 0x%08x",
1595 muxclient_request_id++;
1599 mux_client_forward(int fd, int cancel_flag, u_int ftype, Forward *fwd)
1605 fwd_desc = format_forward(ftype, fwd);
1606 debug("Requesting %s %s",
1607 cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
1611 buffer_put_int(&m, cancel_flag ? MUX_C_CLOSE_FWD : MUX_C_OPEN_FWD);
1612 buffer_put_int(&m, muxclient_request_id);
1613 buffer_put_int(&m, ftype);
1614 buffer_put_cstring(&m,
1615 fwd->listen_host == NULL ? "" : fwd->listen_host);
1616 buffer_put_int(&m, fwd->listen_port);
1617 buffer_put_cstring(&m,
1618 fwd->connect_host == NULL ? "" : fwd->connect_host);
1619 buffer_put_int(&m, fwd->connect_port);
1621 if (mux_client_write_packet(fd, &m) != 0)
1622 fatal("%s: write packet: %s", __func__, strerror(errno));
1626 /* Read their reply */
1627 if (mux_client_read_packet(fd, &m) != 0) {
1632 type = buffer_get_int(&m);
1633 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1634 fatal("%s: out of sequence reply: my id %u theirs %u",
1635 __func__, muxclient_request_id, rid);
1639 case MUX_S_REMOTE_PORT:
1641 fatal("%s: got MUX_S_REMOTE_PORT for cancel", __func__);
1642 fwd->allocated_port = buffer_get_int(&m);
1643 logit("Allocated port %u for remote forward to %s:%d",
1644 fwd->allocated_port,
1645 fwd->connect_host ? fwd->connect_host : "",
1647 if (muxclient_command == SSHMUX_COMMAND_FORWARD)
1648 fprintf(stdout, "%u\n", fwd->allocated_port);
1650 case MUX_S_PERMISSION_DENIED:
1651 e = buffer_get_string(&m, NULL);
1653 error("Master refused forwarding request: %s", e);
1656 e = buffer_get_string(&m, NULL);
1658 error("%s: forwarding request failed: %s", __func__, e);
1661 fatal("%s: unexpected response from master 0x%08x",
1666 muxclient_request_id++;
1671 mux_client_forwards(int fd, int cancel_flag)
1675 debug3("%s: %s forwardings: %d local, %d remote", __func__,
1676 cancel_flag ? "cancel" : "request",
1677 options.num_local_forwards, options.num_remote_forwards);
1679 /* XXX ExitOnForwardingFailure */
1680 for (i = 0; i < options.num_local_forwards; i++) {
1681 if (mux_client_forward(fd, cancel_flag,
1682 options.local_forwards[i].connect_port == 0 ?
1683 MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1684 options.local_forwards + i) != 0)
1687 for (i = 0; i < options.num_remote_forwards; i++) {
1688 if (mux_client_forward(fd, cancel_flag, MUX_FWD_REMOTE,
1689 options.remote_forwards + i) != 0)
1696 mux_client_request_session(int fd)
1700 u_int i, rid, sid, esid, exitval, type, exitval_seen;
1701 extern char **environ;
1702 int devnull, rawmode;
1704 debug3("%s: entering", __func__);
1706 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1707 error("%s: master alive request failed", __func__);
1711 signal(SIGPIPE, SIG_IGN);
1713 if (stdin_null_flag) {
1714 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1715 fatal("open(/dev/null): %s", strerror(errno));
1716 if (dup2(devnull, STDIN_FILENO) == -1)
1717 fatal("dup2: %s", strerror(errno));
1718 if (devnull > STDERR_FILENO)
1722 term = getenv("TERM");
1725 buffer_put_int(&m, MUX_C_NEW_SESSION);
1726 buffer_put_int(&m, muxclient_request_id);
1727 buffer_put_cstring(&m, ""); /* reserved */
1728 buffer_put_int(&m, tty_flag);
1729 buffer_put_int(&m, options.forward_x11);
1730 buffer_put_int(&m, options.forward_agent);
1731 buffer_put_int(&m, subsystem_flag);
1732 buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1733 0xffffffff : (u_int)options.escape_char);
1734 buffer_put_cstring(&m, term == NULL ? "" : term);
1735 buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1737 if (options.num_send_env > 0 && environ != NULL) {
1738 /* Pass environment */
1739 for (i = 0; environ[i] != NULL; i++) {
1740 if (env_permitted(environ[i])) {
1741 buffer_put_cstring(&m, environ[i]);
1746 if (mux_client_write_packet(fd, &m) != 0)
1747 fatal("%s: write packet: %s", __func__, strerror(errno));
1749 /* Send the stdio file descriptors */
1750 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1751 mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1752 mm_send_fd(fd, STDERR_FILENO) == -1)
1753 fatal("%s: send fds failed", __func__);
1755 debug3("%s: session request sent", __func__);
1757 /* Read their reply */
1759 if (mux_client_read_packet(fd, &m) != 0) {
1760 error("%s: read from master failed: %s",
1761 __func__, strerror(errno));
1766 type = buffer_get_int(&m);
1767 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1768 fatal("%s: out of sequence reply: my id %u theirs %u",
1769 __func__, muxclient_request_id, rid);
1771 case MUX_S_SESSION_OPENED:
1772 sid = buffer_get_int(&m);
1773 debug("%s: master session id: %u", __func__, sid);
1775 case MUX_S_PERMISSION_DENIED:
1776 e = buffer_get_string(&m, NULL);
1778 error("Master refused session request: %s", e);
1781 e = buffer_get_string(&m, NULL);
1783 error("%s: session request failed: %s", __func__, e);
1787 error("%s: unexpected response from master 0x%08x",
1791 muxclient_request_id++;
1793 signal(SIGHUP, control_client_sighandler);
1794 signal(SIGINT, control_client_sighandler);
1795 signal(SIGTERM, control_client_sighandler);
1796 signal(SIGWINCH, control_client_sigrelay);
1800 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1803 * Stick around until the controlee closes the client_fd.
1804 * Before it does, it is expected to write an exit message.
1805 * This process must read the value and wait for the closure of
1806 * the client_fd; if this one closes early, the multiplex master will
1807 * terminate early too (possibly losing data).
1809 for (exitval = 255, exitval_seen = 0;;) {
1811 if (mux_client_read_packet(fd, &m) != 0)
1813 type = buffer_get_int(&m);
1815 case MUX_S_TTY_ALLOC_FAIL:
1816 if ((esid = buffer_get_int(&m)) != sid)
1817 fatal("%s: tty alloc fail on unknown session: "
1818 "my id %u theirs %u",
1819 __func__, sid, esid);
1820 leave_raw_mode(options.request_tty ==
1824 case MUX_S_EXIT_MESSAGE:
1825 if ((esid = buffer_get_int(&m)) != sid)
1826 fatal("%s: exit on unknown session: "
1827 "my id %u theirs %u",
1828 __func__, sid, esid);
1830 fatal("%s: exitval sent twice", __func__);
1831 exitval = buffer_get_int(&m);
1835 e = buffer_get_string(&m, NULL);
1836 fatal("%s: master returned error: %s", __func__, e);
1842 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1844 if (muxclient_terminate) {
1845 debug2("Exiting on signal %ld", (long)muxclient_terminate);
1847 } else if (!exitval_seen) {
1848 debug2("Control master terminated unexpectedly");
1851 debug2("Received exit status from master %d", exitval);
1853 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1854 fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1860 mux_client_request_stdio_fwd(int fd)
1864 u_int type, rid, sid;
1867 debug3("%s: entering", __func__);
1869 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1870 error("%s: master alive request failed", __func__);
1874 signal(SIGPIPE, SIG_IGN);
1876 if (stdin_null_flag) {
1877 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1878 fatal("open(/dev/null): %s", strerror(errno));
1879 if (dup2(devnull, STDIN_FILENO) == -1)
1880 fatal("dup2: %s", strerror(errno));
1881 if (devnull > STDERR_FILENO)
1886 buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
1887 buffer_put_int(&m, muxclient_request_id);
1888 buffer_put_cstring(&m, ""); /* reserved */
1889 buffer_put_cstring(&m, stdio_forward_host);
1890 buffer_put_int(&m, stdio_forward_port);
1892 if (mux_client_write_packet(fd, &m) != 0)
1893 fatal("%s: write packet: %s", __func__, strerror(errno));
1895 /* Send the stdio file descriptors */
1896 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1897 mm_send_fd(fd, STDOUT_FILENO) == -1)
1898 fatal("%s: send fds failed", __func__);
1900 debug3("%s: stdio forward request sent", __func__);
1902 /* Read their reply */
1905 if (mux_client_read_packet(fd, &m) != 0) {
1906 error("%s: read from master failed: %s",
1907 __func__, strerror(errno));
1912 type = buffer_get_int(&m);
1913 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1914 fatal("%s: out of sequence reply: my id %u theirs %u",
1915 __func__, muxclient_request_id, rid);
1917 case MUX_S_SESSION_OPENED:
1918 sid = buffer_get_int(&m);
1919 debug("%s: master session id: %u", __func__, sid);
1921 case MUX_S_PERMISSION_DENIED:
1922 e = buffer_get_string(&m, NULL);
1924 fatal("Master refused stdio forwarding request: %s", e);
1926 e = buffer_get_string(&m, NULL);
1928 fatal("%s: stdio forwarding request failed: %s", __func__, e);
1931 error("%s: unexpected response from master 0x%08x",
1935 muxclient_request_id++;
1937 signal(SIGHUP, control_client_sighandler);
1938 signal(SIGINT, control_client_sighandler);
1939 signal(SIGTERM, control_client_sighandler);
1940 signal(SIGWINCH, control_client_sigrelay);
1943 * Stick around until the controlee closes the client_fd.
1946 if (mux_client_read_packet(fd, &m) != 0) {
1947 if (errno == EPIPE ||
1948 (errno == EINTR && muxclient_terminate != 0))
1950 fatal("%s: mux_client_read_packet: %s",
1951 __func__, strerror(errno));
1953 fatal("%s: master returned unexpected message %u", __func__, type);
1957 mux_client_request_stop_listening(int fd)
1963 debug3("%s: entering", __func__);
1966 buffer_put_int(&m, MUX_C_STOP_LISTENING);
1967 buffer_put_int(&m, muxclient_request_id);
1969 if (mux_client_write_packet(fd, &m) != 0)
1970 fatal("%s: write packet: %s", __func__, strerror(errno));
1974 /* Read their reply */
1975 if (mux_client_read_packet(fd, &m) != 0)
1976 fatal("%s: read from master failed: %s",
1977 __func__, strerror(errno));
1979 type = buffer_get_int(&m);
1980 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1981 fatal("%s: out of sequence reply: my id %u theirs %u",
1982 __func__, muxclient_request_id, rid);
1986 case MUX_S_PERMISSION_DENIED:
1987 e = buffer_get_string(&m, NULL);
1988 fatal("Master refused stop listening request: %s", e);
1990 e = buffer_get_string(&m, NULL);
1991 fatal("%s: stop listening request failed: %s", __func__, e);
1993 fatal("%s: unexpected response from master 0x%08x",
1997 muxclient_request_id++;
2000 /* Multiplex client main loop. */
2002 muxclient(const char *path)
2004 struct sockaddr_un addr;
2009 if (muxclient_command == 0) {
2010 if (stdio_forward_host != NULL)
2011 muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
2013 muxclient_command = SSHMUX_COMMAND_OPEN;
2016 switch (options.control_master) {
2017 case SSHCTL_MASTER_AUTO:
2018 case SSHCTL_MASTER_AUTO_ASK:
2019 debug("auto-mux: Trying existing master");
2021 case SSHCTL_MASTER_NO:
2027 memset(&addr, '\0', sizeof(addr));
2028 addr.sun_family = AF_UNIX;
2029 sun_len = offsetof(struct sockaddr_un, sun_path) +
2032 if (strlcpy(addr.sun_path, path,
2033 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
2034 fatal("ControlPath too long");
2036 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
2037 fatal("%s socket(): %s", __func__, strerror(errno));
2039 if (connect(sock, (struct sockaddr *)&addr, sun_len) == -1) {
2040 switch (muxclient_command) {
2041 case SSHMUX_COMMAND_OPEN:
2042 case SSHMUX_COMMAND_STDIO_FWD:
2045 fatal("Control socket connect(%.100s): %s", path,
2048 if (errno == ECONNREFUSED &&
2049 options.control_master != SSHCTL_MASTER_NO) {
2050 debug("Stale control socket %.100s, unlinking", path);
2052 } else if (errno == ENOENT) {
2053 debug("Control socket \"%.100s\" does not exist", path);
2055 error("Control socket connect(%.100s): %s", path,
2063 if (mux_client_hello_exchange(sock) != 0) {
2064 error("%s: master hello exchange failed", __func__);
2069 switch (muxclient_command) {
2070 case SSHMUX_COMMAND_ALIVE_CHECK:
2071 if ((pid = mux_client_request_alive(sock)) == 0)
2072 fatal("%s: master alive check failed", __func__);
2073 fprintf(stderr, "Master running (pid=%d)\r\n", pid);
2075 case SSHMUX_COMMAND_TERMINATE:
2076 mux_client_request_terminate(sock);
2077 fprintf(stderr, "Exit request sent.\r\n");
2079 case SSHMUX_COMMAND_FORWARD:
2080 if (mux_client_forwards(sock, 0) != 0)
2081 fatal("%s: master forward request failed", __func__);
2083 case SSHMUX_COMMAND_OPEN:
2084 if (mux_client_forwards(sock, 0) != 0) {
2085 error("%s: master forward request failed", __func__);
2088 mux_client_request_session(sock);
2090 case SSHMUX_COMMAND_STDIO_FWD:
2091 mux_client_request_stdio_fwd(sock);
2093 case SSHMUX_COMMAND_STOP:
2094 mux_client_request_stop_listening(sock);
2095 fprintf(stderr, "Stop listening request sent.\r\n");
2097 case SSHMUX_COMMAND_CANCEL_FWD:
2098 if (mux_client_forwards(sock, 1) != 0)
2099 error("%s: master cancel forward request failed",
2103 fatal("unrecognised muxclient_command %d", muxclient_command);