1 /* $OpenBSD: mux.c,v 1.36 2012/07/06 01:37:21 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
35 #include <sys/types.h>
36 #include <sys/param.h>
38 #include <sys/socket.h>
57 # ifdef HAVE_SYS_POLL_H
58 # include <sys/poll.h>
70 #include "openbsd-compat/sys-queue.h"
75 #include "pathnames.h"
82 #include "monitor_fdpass.h"
86 #include "clientloop.h"
90 extern Options options;
91 extern int stdin_null_flag;
93 extern int subsystem_flag;
94 extern Buffer command;
95 extern volatile sig_atomic_t quit_pending;
96 extern char *stdio_forward_host;
97 extern int stdio_forward_port;
99 /* Context for session open confirmation callback */
100 struct mux_session_confirm_ctx {
104 u_int want_agent_fwd;
112 /* Context for global channel callback */
113 struct mux_channel_confirm_ctx {
114 u_int cid; /* channel id */
115 u_int rid; /* request id */
116 int fid; /* forward id */
119 /* fd to control socket */
120 int muxserver_sock = -1;
122 /* client request id */
123 u_int muxclient_request_id = 0;
125 /* Multiplexing control command */
126 u_int muxclient_command = 0;
128 /* Set when signalled. */
129 static volatile sig_atomic_t muxclient_terminate = 0;
131 /* PID of multiplex server */
132 static u_int muxserver_pid = 0;
134 static Channel *mux_listener_channel = NULL;
136 struct mux_master_state {
140 /* mux protocol messages */
141 #define MUX_MSG_HELLO 0x00000001
142 #define MUX_C_NEW_SESSION 0x10000002
143 #define MUX_C_ALIVE_CHECK 0x10000004
144 #define MUX_C_TERMINATE 0x10000005
145 #define MUX_C_OPEN_FWD 0x10000006
146 #define MUX_C_CLOSE_FWD 0x10000007
147 #define MUX_C_NEW_STDIO_FWD 0x10000008
148 #define MUX_C_STOP_LISTENING 0x10000009
149 #define MUX_S_OK 0x80000001
150 #define MUX_S_PERMISSION_DENIED 0x80000002
151 #define MUX_S_FAILURE 0x80000003
152 #define MUX_S_EXIT_MESSAGE 0x80000004
153 #define MUX_S_ALIVE 0x80000005
154 #define MUX_S_SESSION_OPENED 0x80000006
155 #define MUX_S_REMOTE_PORT 0x80000007
156 #define MUX_S_TTY_ALLOC_FAIL 0x80000008
158 /* type codes for MUX_C_OPEN_FWD and MUX_C_CLOSE_FWD */
159 #define MUX_FWD_LOCAL 1
160 #define MUX_FWD_REMOTE 2
161 #define MUX_FWD_DYNAMIC 3
163 static void mux_session_confirm(int, int, void *);
165 static int process_mux_master_hello(u_int, Channel *, Buffer *, Buffer *);
166 static int process_mux_new_session(u_int, Channel *, Buffer *, Buffer *);
167 static int process_mux_alive_check(u_int, Channel *, Buffer *, Buffer *);
168 static int process_mux_terminate(u_int, Channel *, Buffer *, Buffer *);
169 static int process_mux_open_fwd(u_int, Channel *, Buffer *, Buffer *);
170 static int process_mux_close_fwd(u_int, Channel *, Buffer *, Buffer *);
171 static int process_mux_stdio_fwd(u_int, Channel *, Buffer *, Buffer *);
172 static int process_mux_stop_listening(u_int, Channel *, Buffer *, Buffer *);
174 static const struct {
176 int (*handler)(u_int, Channel *, Buffer *, Buffer *);
177 } mux_master_handlers[] = {
178 { MUX_MSG_HELLO, process_mux_master_hello },
179 { MUX_C_NEW_SESSION, process_mux_new_session },
180 { MUX_C_ALIVE_CHECK, process_mux_alive_check },
181 { MUX_C_TERMINATE, process_mux_terminate },
182 { MUX_C_OPEN_FWD, process_mux_open_fwd },
183 { MUX_C_CLOSE_FWD, process_mux_close_fwd },
184 { MUX_C_NEW_STDIO_FWD, process_mux_stdio_fwd },
185 { MUX_C_STOP_LISTENING, process_mux_stop_listening },
189 /* Cleanup callback fired on closure of mux slave _session_ channel */
192 mux_master_session_cleanup_cb(int cid, void *unused)
194 Channel *cc, *c = channel_by_id(cid);
196 debug3("%s: entering for channel %d", __func__, cid);
198 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
199 if (c->ctl_chan != -1) {
200 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
201 fatal("%s: channel %d missing control channel %d",
202 __func__, c->self, c->ctl_chan);
205 chan_rcvd_oclose(cc);
207 channel_cancel_cleanup(c->self);
210 /* Cleanup callback fired on closure of mux slave _control_ channel */
213 mux_master_control_cleanup_cb(int cid, void *unused)
215 Channel *sc, *c = channel_by_id(cid);
217 debug3("%s: entering for channel %d", __func__, cid);
219 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
220 if (c->remote_id != -1) {
221 if ((sc = channel_by_id(c->remote_id)) == NULL)
222 fatal("%s: channel %d missing session channel %d",
223 __func__, c->self, c->remote_id);
226 if (sc->type != SSH_CHANNEL_OPEN) {
227 debug2("%s: channel %d: not open", __func__, sc->self);
230 if (sc->istate == CHAN_INPUT_OPEN)
231 chan_read_failed(sc);
232 if (sc->ostate == CHAN_OUTPUT_OPEN)
233 chan_write_failed(sc);
236 channel_cancel_cleanup(c->self);
239 /* Check mux client environment variables before passing them to mux master. */
241 env_permitted(char *env)
244 char name[1024], *cp;
246 if ((cp = strchr(env, '=')) == NULL || cp == env)
248 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
249 if (ret <= 0 || (size_t)ret >= sizeof(name)) {
250 error("env_permitted: name '%.100s...' too long", env);
254 for (i = 0; i < options.num_send_env; i++)
255 if (match_pattern(name, options.send_env[i]))
261 /* Mux master protocol message handlers */
264 process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
267 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
270 fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
271 if (state->hello_rcvd) {
272 error("%s: HELLO received twice", __func__);
275 if (buffer_get_int_ret(&ver, m) != 0) {
277 error("%s: malformed message", __func__);
280 if (ver != SSHMUX_VER) {
281 error("Unsupported multiplexing protocol version %d "
282 "(expected %d)", ver, SSHMUX_VER);
285 debug2("%s: channel %d slave version %u", __func__, c->self, ver);
287 /* No extensions are presently defined */
288 while (buffer_len(m) > 0) {
289 char *name = buffer_get_string_ret(m, NULL);
290 char *value = buffer_get_string_ret(m, NULL);
292 if (name == NULL || value == NULL) {
297 debug2("Unrecognised slave extension \"%s\"", name);
301 state->hello_rcvd = 1;
306 process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
309 struct mux_session_confirm_ctx *cctx;
310 char *reserved, *cmd, *cp;
311 u_int i, j, len, env_len, escape_char, window, packetmax;
314 /* Reply for SSHMUX_COMMAND_OPEN */
315 cctx = xcalloc(1, sizeof(*cctx));
318 cmd = reserved = NULL;
321 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
322 buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
323 buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
324 buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
325 buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
326 buffer_get_int_ret(&escape_char, m) != 0 ||
327 (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
328 (cmd = buffer_get_string_ret(m, &len)) == NULL) {
332 if (reserved != NULL)
334 for (j = 0; j < env_len; j++)
338 if (cctx->term != NULL)
341 error("%s: malformed message", __func__);
347 while (buffer_len(m) > 0) {
348 #define MUX_MAX_ENV_VARS 4096
349 if ((cp = buffer_get_string_ret(m, &len)) == NULL)
351 if (!env_permitted(cp)) {
355 cctx->env = xrealloc(cctx->env, env_len + 2,
357 cctx->env[env_len++] = cp;
358 cctx->env[env_len] = NULL;
359 if (env_len > MUX_MAX_ENV_VARS) {
360 error(">%d environment variables received, ignoring "
361 "additional", MUX_MAX_ENV_VARS);
366 debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
367 "term \"%s\", cmd \"%s\", env %u", __func__, c->self,
368 cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
369 cctx->want_subsys, cctx->term, cmd, env_len);
371 buffer_init(&cctx->cmd);
372 buffer_append(&cctx->cmd, cmd, strlen(cmd));
376 /* Gather fds from client */
377 for(i = 0; i < 3; i++) {
378 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
379 error("%s: failed to receive fd %d from slave",
381 for (j = 0; j < i; j++)
383 for (j = 0; j < env_len; j++)
388 buffer_free(&cctx->cmd);
392 buffer_put_int(r, MUX_S_FAILURE);
393 buffer_put_int(r, rid);
394 buffer_put_cstring(r,
395 "did not receive file descriptors");
400 debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
401 new_fd[0], new_fd[1], new_fd[2]);
403 /* XXX support multiple child sessions in future */
404 if (c->remote_id != -1) {
405 debug2("%s: session already open", __func__);
407 buffer_put_int(r, MUX_S_FAILURE);
408 buffer_put_int(r, rid);
409 buffer_put_cstring(r, "Multiple sessions not supported");
416 for (i = 0; i < env_len; i++)
420 buffer_free(&cctx->cmd);
425 if (options.control_master == SSHCTL_MASTER_ASK ||
426 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
427 if (!ask_permission("Allow shared connection to %s? ", host)) {
428 debug2("%s: session refused by user", __func__);
430 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
431 buffer_put_int(r, rid);
432 buffer_put_cstring(r, "Permission denied");
437 /* Try to pick up ttymodes from client before it goes raw */
438 if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
439 error("%s: tcgetattr: %s", __func__, strerror(errno));
441 /* enable nonblocking unless tty */
442 if (!isatty(new_fd[0]))
443 set_nonblock(new_fd[0]);
444 if (!isatty(new_fd[1]))
445 set_nonblock(new_fd[1]);
446 if (!isatty(new_fd[2]))
447 set_nonblock(new_fd[2]);
449 window = CHAN_SES_WINDOW_DEFAULT;
450 packetmax = CHAN_SES_PACKET_DEFAULT;
451 if (cctx->want_tty) {
456 nc = channel_new("session", SSH_CHANNEL_OPENING,
457 new_fd[0], new_fd[1], new_fd[2], window, packetmax,
458 CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
460 nc->ctl_chan = c->self; /* link session -> control channel */
461 c->remote_id = nc->self; /* link control -> session channel */
463 if (cctx->want_tty && escape_char != 0xffffffff) {
464 channel_register_filter(nc->self,
465 client_simple_escape_filter, NULL,
466 client_filter_cleanup,
467 client_new_escape_filter_ctx((int)escape_char));
470 debug2("%s: channel_new: %d linked to control channel %d",
471 __func__, nc->self, nc->ctl_chan);
473 channel_send_open(nc->self);
474 channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
475 c->mux_pause = 1; /* stop handling messages until open_confirm done */
476 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
478 /* reply is deferred, sent by mux_session_confirm */
483 process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
485 debug2("%s: channel %d: alive check", __func__, c->self);
488 buffer_put_int(r, MUX_S_ALIVE);
489 buffer_put_int(r, rid);
490 buffer_put_int(r, (u_int)getpid());
496 process_mux_terminate(u_int rid, Channel *c, Buffer *m, Buffer *r)
498 debug2("%s: channel %d: terminate request", __func__, c->self);
500 if (options.control_master == SSHCTL_MASTER_ASK ||
501 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
502 if (!ask_permission("Terminate shared connection to %s? ",
504 debug2("%s: termination refused by user", __func__);
505 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
506 buffer_put_int(r, rid);
507 buffer_put_cstring(r, "Permission denied");
513 buffer_put_int(r, MUX_S_OK);
514 buffer_put_int(r, rid);
515 /* XXX exit happens too soon - message never makes it to client */
520 format_forward(u_int ftype, Forward *fwd)
526 xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
527 (fwd->listen_host == NULL) ?
528 (options.gateway_ports ? "*" : "LOCALHOST") :
529 fwd->listen_host, fwd->listen_port,
530 fwd->connect_host, fwd->connect_port);
532 case MUX_FWD_DYNAMIC:
533 xasprintf(&ret, "dynamic forward %.200s:%d -> *",
534 (fwd->listen_host == NULL) ?
535 (options.gateway_ports ? "*" : "LOCALHOST") :
536 fwd->listen_host, fwd->listen_port);
539 xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
540 (fwd->listen_host == NULL) ?
541 "LOCALHOST" : fwd->listen_host,
543 fwd->connect_host, fwd->connect_port);
546 fatal("%s: unknown forward type %u", __func__, ftype);
552 compare_host(const char *a, const char *b)
554 if (a == NULL && b == NULL)
556 if (a == NULL || b == NULL)
558 return strcmp(a, b) == 0;
562 compare_forward(Forward *a, Forward *b)
564 if (!compare_host(a->listen_host, b->listen_host))
566 if (a->listen_port != b->listen_port)
568 if (!compare_host(a->connect_host, b->connect_host))
570 if (a->connect_port != b->connect_port)
577 mux_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
579 struct mux_channel_confirm_ctx *fctx = ctxt;
580 char *failmsg = NULL;
585 if ((c = channel_by_id(fctx->cid)) == NULL) {
586 /* no channel for reply */
587 error("%s: unknown channel", __func__);
591 if (fctx->fid >= options.num_remote_forwards) {
592 xasprintf(&failmsg, "unknown forwarding id %d", fctx->fid);
595 rfwd = &options.remote_forwards[fctx->fid];
596 debug("%s: %s for: listen %d, connect %s:%d", __func__,
597 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
598 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
599 if (type == SSH2_MSG_REQUEST_SUCCESS) {
600 if (rfwd->listen_port == 0) {
601 rfwd->allocated_port = packet_get_int();
602 logit("Allocated port %u for mux remote forward"
603 " to %s:%d", rfwd->allocated_port,
604 rfwd->connect_host, rfwd->connect_port);
605 buffer_put_int(&out, MUX_S_REMOTE_PORT);
606 buffer_put_int(&out, fctx->rid);
607 buffer_put_int(&out, rfwd->allocated_port);
608 channel_update_permitted_opens(rfwd->handle,
609 rfwd->allocated_port);
611 buffer_put_int(&out, MUX_S_OK);
612 buffer_put_int(&out, fctx->rid);
616 if (rfwd->listen_port == 0)
617 channel_update_permitted_opens(rfwd->handle, -1);
618 xasprintf(&failmsg, "remote port forwarding failed for "
619 "listen port %d", rfwd->listen_port);
622 error("%s: %s", __func__, failmsg);
623 buffer_put_int(&out, MUX_S_FAILURE);
624 buffer_put_int(&out, fctx->rid);
625 buffer_put_cstring(&out, failmsg);
628 buffer_put_string(&c->output, buffer_ptr(&out), buffer_len(&out));
630 if (c->mux_pause <= 0)
631 fatal("%s: mux_pause %d", __func__, c->mux_pause);
632 c->mux_pause = 0; /* start processing messages again */
636 process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
639 char *fwd_desc = NULL;
641 int i, ret = 0, freefwd = 1;
643 fwd.listen_host = fwd.connect_host = NULL;
644 if (buffer_get_int_ret(&ftype, m) != 0 ||
645 (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
646 buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
647 (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
648 buffer_get_int_ret(&fwd.connect_port, m) != 0) {
649 error("%s: malformed message", __func__);
654 if (*fwd.listen_host == '\0') {
655 xfree(fwd.listen_host);
656 fwd.listen_host = NULL;
658 if (*fwd.connect_host == '\0') {
659 xfree(fwd.connect_host);
660 fwd.connect_host = NULL;
663 debug2("%s: channel %d: request %s", __func__, c->self,
664 (fwd_desc = format_forward(ftype, &fwd)));
666 if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
667 ftype != MUX_FWD_DYNAMIC) {
668 logit("%s: invalid forwarding type %u", __func__, ftype);
671 xfree(fwd.listen_host);
672 if (fwd.connect_host)
673 xfree(fwd.connect_host);
674 buffer_put_int(r, MUX_S_FAILURE);
675 buffer_put_int(r, rid);
676 buffer_put_cstring(r, "Invalid forwarding request");
679 if (fwd.listen_port >= 65536) {
680 logit("%s: invalid listen port %u", __func__,
684 if (fwd.connect_port >= 65536 || (ftype != MUX_FWD_DYNAMIC &&
685 ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
686 logit("%s: invalid connect port %u", __func__,
690 if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL) {
691 logit("%s: missing connect host", __func__);
695 /* Skip forwards that have already been requested */
698 case MUX_FWD_DYNAMIC:
699 for (i = 0; i < options.num_local_forwards; i++) {
700 if (compare_forward(&fwd,
701 options.local_forwards + i)) {
703 debug2("%s: found existing forwarding",
705 buffer_put_int(r, MUX_S_OK);
706 buffer_put_int(r, rid);
712 for (i = 0; i < options.num_remote_forwards; i++) {
713 if (compare_forward(&fwd,
714 options.remote_forwards + i)) {
715 if (fwd.listen_port != 0)
717 debug2("%s: found allocated port",
719 buffer_put_int(r, MUX_S_REMOTE_PORT);
720 buffer_put_int(r, rid);
722 options.remote_forwards[i].allocated_port);
729 if (options.control_master == SSHCTL_MASTER_ASK ||
730 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
731 if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
732 debug2("%s: forwarding refused by user", __func__);
733 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
734 buffer_put_int(r, rid);
735 buffer_put_cstring(r, "Permission denied");
740 if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
741 if (channel_setup_local_fwd_listener(fwd.listen_host,
742 fwd.listen_port, fwd.connect_host, fwd.connect_port,
743 options.gateway_ports) < 0) {
745 logit("slave-requested %s failed", fwd_desc);
746 buffer_put_int(r, MUX_S_FAILURE);
747 buffer_put_int(r, rid);
748 buffer_put_cstring(r, "Port forwarding failed");
751 add_local_forward(&options, &fwd);
754 struct mux_channel_confirm_ctx *fctx;
756 fwd.handle = channel_request_remote_forwarding(fwd.listen_host,
757 fwd.listen_port, fwd.connect_host, fwd.connect_port);
760 add_remote_forward(&options, &fwd);
761 fctx = xcalloc(1, sizeof(*fctx));
764 fctx->fid = options.num_remote_forwards - 1;
765 client_register_global_confirm(mux_confirm_remote_forward,
768 c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
769 /* delayed reply in mux_confirm_remote_forward */
772 buffer_put_int(r, MUX_S_OK);
773 buffer_put_int(r, rid);
775 if (fwd_desc != NULL)
778 if (fwd.listen_host != NULL)
779 xfree(fwd.listen_host);
780 if (fwd.connect_host != NULL)
781 xfree(fwd.connect_host);
787 process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
789 Forward fwd, *found_fwd;
790 char *fwd_desc = NULL;
791 const char *error_reason = NULL;
793 int i, listen_port, ret = 0;
795 fwd.listen_host = fwd.connect_host = NULL;
796 if (buffer_get_int_ret(&ftype, m) != 0 ||
797 (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
798 buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
799 (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
800 buffer_get_int_ret(&fwd.connect_port, m) != 0) {
801 error("%s: malformed message", __func__);
806 if (*fwd.listen_host == '\0') {
807 xfree(fwd.listen_host);
808 fwd.listen_host = NULL;
810 if (*fwd.connect_host == '\0') {
811 xfree(fwd.connect_host);
812 fwd.connect_host = NULL;
815 debug2("%s: channel %d: request cancel %s", __func__, c->self,
816 (fwd_desc = format_forward(ftype, &fwd)));
818 /* make sure this has been requested */
822 case MUX_FWD_DYNAMIC:
823 for (i = 0; i < options.num_local_forwards; i++) {
824 if (compare_forward(&fwd,
825 options.local_forwards + i)) {
826 found_fwd = options.local_forwards + i;
832 for (i = 0; i < options.num_remote_forwards; i++) {
833 if (compare_forward(&fwd,
834 options.remote_forwards + i)) {
835 found_fwd = options.remote_forwards + i;
842 if (found_fwd == NULL)
843 error_reason = "port not forwarded";
844 else if (ftype == MUX_FWD_REMOTE) {
846 * This shouldn't fail unless we confused the host/port
847 * between options.remote_forwards and permitted_opens.
848 * However, for dynamic allocated listen ports we need
849 * to lookup the actual listen port.
851 listen_port = (fwd.listen_port == 0) ?
852 found_fwd->allocated_port : fwd.listen_port;
853 if (channel_request_rforward_cancel(fwd.listen_host,
855 error_reason = "port not in permitted opens";
856 } else { /* local and dynamic forwards */
858 if (channel_cancel_lport_listener(fwd.listen_host,
859 fwd.listen_port, fwd.connect_port,
860 options.gateway_ports) == -1)
861 error_reason = "port not found";
864 if (error_reason == NULL) {
865 buffer_put_int(r, MUX_S_OK);
866 buffer_put_int(r, rid);
868 if (found_fwd->listen_host != NULL)
869 xfree(found_fwd->listen_host);
870 if (found_fwd->connect_host != NULL)
871 xfree(found_fwd->connect_host);
872 found_fwd->listen_host = found_fwd->connect_host = NULL;
873 found_fwd->listen_port = found_fwd->connect_port = 0;
875 buffer_put_int(r, MUX_S_FAILURE);
876 buffer_put_int(r, rid);
877 buffer_put_cstring(r, error_reason);
880 if (fwd_desc != NULL)
882 if (fwd.listen_host != NULL)
883 xfree(fwd.listen_host);
884 if (fwd.connect_host != NULL)
885 xfree(fwd.connect_host);
891 process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
894 char *reserved, *chost;
898 chost = reserved = NULL;
899 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
900 (chost = buffer_get_string_ret(m, NULL)) == NULL ||
901 buffer_get_int_ret(&cport, m) != 0) {
902 if (reserved != NULL)
906 error("%s: malformed message", __func__);
911 debug2("%s: channel %d: request stdio fwd to %s:%u",
912 __func__, c->self, chost, cport);
914 /* Gather fds from client */
915 for(i = 0; i < 2; i++) {
916 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
917 error("%s: failed to receive fd %d from slave",
919 for (j = 0; j < i; j++)
924 buffer_put_int(r, MUX_S_FAILURE);
925 buffer_put_int(r, rid);
926 buffer_put_cstring(r,
927 "did not receive file descriptors");
932 debug3("%s: got fds stdin %d, stdout %d", __func__,
933 new_fd[0], new_fd[1]);
935 /* XXX support multiple child sessions in future */
936 if (c->remote_id != -1) {
937 debug2("%s: session already open", __func__);
939 buffer_put_int(r, MUX_S_FAILURE);
940 buffer_put_int(r, rid);
941 buffer_put_cstring(r, "Multiple sessions not supported");
949 if (options.control_master == SSHCTL_MASTER_ASK ||
950 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
951 if (!ask_permission("Allow forward to %s:%u? ",
953 debug2("%s: stdio fwd refused by user", __func__);
955 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
956 buffer_put_int(r, rid);
957 buffer_put_cstring(r, "Permission denied");
962 /* enable nonblocking unless tty */
963 if (!isatty(new_fd[0]))
964 set_nonblock(new_fd[0]);
965 if (!isatty(new_fd[1]))
966 set_nonblock(new_fd[1]);
968 nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
970 nc->ctl_chan = c->self; /* link session -> control channel */
971 c->remote_id = nc->self; /* link control -> session channel */
973 debug2("%s: channel_new: %d linked to control channel %d",
974 __func__, nc->self, nc->ctl_chan);
976 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
979 /* XXX defer until channel confirmed */
980 buffer_put_int(r, MUX_S_SESSION_OPENED);
981 buffer_put_int(r, rid);
982 buffer_put_int(r, nc->self);
988 process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
990 debug("%s: channel %d: stop listening", __func__, c->self);
992 if (options.control_master == SSHCTL_MASTER_ASK ||
993 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
994 if (!ask_permission("Disable further multiplexing on shared "
995 "connection to %s? ", host)) {
996 debug2("%s: stop listen refused by user", __func__);
997 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
998 buffer_put_int(r, rid);
999 buffer_put_cstring(r, "Permission denied");
1004 if (mux_listener_channel != NULL) {
1005 channel_free(mux_listener_channel);
1007 xfree(options.control_path);
1008 options.control_path = NULL;
1009 mux_listener_channel = NULL;
1010 muxserver_sock = -1;
1014 buffer_put_int(r, MUX_S_OK);
1015 buffer_put_int(r, rid);
1020 /* Channel callbacks fired on read/write from mux slave fd */
1022 mux_master_read_cb(Channel *c)
1024 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
1027 u_int type, rid, have, i;
1031 if (c->mux_ctx == NULL) {
1032 state = xcalloc(1, sizeof(*state));
1034 channel_register_cleanup(c->self,
1035 mux_master_control_cleanup_cb, 0);
1039 buffer_put_int(&out, MUX_MSG_HELLO);
1040 buffer_put_int(&out, SSHMUX_VER);
1042 buffer_put_string(&c->output, buffer_ptr(&out),
1045 debug3("%s: channel %d: hello sent", __func__, c->self);
1052 /* Channel code ensures that we receive whole packets */
1053 if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
1055 error("%s: malformed message", __func__);
1058 buffer_append(&in, ptr, have);
1060 if (buffer_get_int_ret(&type, &in) != 0)
1062 debug3("%s: channel %d packet type 0x%08x len %u",
1063 __func__, c->self, type, buffer_len(&in));
1065 if (type == MUX_MSG_HELLO)
1068 if (!state->hello_rcvd) {
1069 error("%s: expected MUX_MSG_HELLO(0x%08x), "
1070 "received 0x%08x", __func__, MUX_MSG_HELLO, type);
1073 if (buffer_get_int_ret(&rid, &in) != 0)
1077 for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
1078 if (type == mux_master_handlers[i].type) {
1079 ret = mux_master_handlers[i].handler(rid, c, &in, &out);
1083 if (mux_master_handlers[i].handler == NULL) {
1084 error("%s: unsupported mux message 0x%08x", __func__, type);
1085 buffer_put_int(&out, MUX_S_FAILURE);
1086 buffer_put_int(&out, rid);
1087 buffer_put_cstring(&out, "unsupported request");
1090 /* Enqueue reply packet */
1091 if (buffer_len(&out) != 0) {
1092 buffer_put_string(&c->output, buffer_ptr(&out),
1102 mux_exit_message(Channel *c, int exitval)
1107 debug3("%s: channel %d: exit message, evitval %d", __func__, c->self,
1110 if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1111 fatal("%s: channel %d missing mux channel %d",
1112 __func__, c->self, c->ctl_chan);
1114 /* Append exit message packet to control socket output queue */
1116 buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
1117 buffer_put_int(&m, c->self);
1118 buffer_put_int(&m, exitval);
1120 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1125 mux_tty_alloc_failed(Channel *c)
1130 debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
1132 if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1133 fatal("%s: channel %d missing mux channel %d",
1134 __func__, c->self, c->ctl_chan);
1136 /* Append exit message packet to control socket output queue */
1138 buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
1139 buffer_put_int(&m, c->self);
1141 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1145 /* Prepare a mux master to listen on a Unix domain socket. */
1147 muxserver_listen(void)
1149 struct sockaddr_un addr;
1152 char *orig_control_path = options.control_path;
1156 if (options.control_path == NULL ||
1157 options.control_master == SSHCTL_MASTER_NO)
1160 debug("setting up multiplex master socket");
1163 * Use a temporary path before listen so we can pseudo-atomically
1164 * establish the listening socket in its final location to avoid
1165 * other processes racing in between bind() and listen() and hitting
1166 * an unready socket.
1168 for (i = 0; i < sizeof(rbuf) - 1; i++) {
1169 r = arc4random_uniform(26+26+10);
1170 rbuf[i] = (r < 26) ? 'a' + r :
1171 (r < 26*2) ? 'A' + r - 26 :
1174 rbuf[sizeof(rbuf) - 1] = '\0';
1175 options.control_path = NULL;
1176 xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
1177 debug3("%s: temporary control path %s", __func__, options.control_path);
1179 memset(&addr, '\0', sizeof(addr));
1180 addr.sun_family = AF_UNIX;
1181 sun_len = offsetof(struct sockaddr_un, sun_path) +
1182 strlen(options.control_path) + 1;
1184 if (strlcpy(addr.sun_path, options.control_path,
1185 sizeof(addr.sun_path)) >= sizeof(addr.sun_path)) {
1186 error("ControlPath \"%s\" too long for Unix domain socket",
1187 options.control_path);
1188 goto disable_mux_master;
1191 if ((muxserver_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1192 fatal("%s socket(): %s", __func__, strerror(errno));
1194 old_umask = umask(0177);
1195 if (bind(muxserver_sock, (struct sockaddr *)&addr, sun_len) == -1) {
1196 if (errno == EINVAL || errno == EADDRINUSE) {
1197 error("ControlSocket %s already exists, "
1198 "disabling multiplexing", options.control_path);
1200 if (muxserver_sock != -1) {
1201 close(muxserver_sock);
1202 muxserver_sock = -1;
1204 xfree(orig_control_path);
1205 xfree(options.control_path);
1206 options.control_path = NULL;
1207 options.control_master = SSHCTL_MASTER_NO;
1210 fatal("%s bind(): %s", __func__, strerror(errno));
1214 if (listen(muxserver_sock, 64) == -1)
1215 fatal("%s listen(): %s", __func__, strerror(errno));
1217 /* Now atomically "move" the mux socket into position */
1218 if (link(options.control_path, orig_control_path) != 0) {
1219 if (errno != EEXIST) {
1220 fatal("%s: link mux listener %s => %s: %s", __func__,
1221 options.control_path, orig_control_path,
1224 error("ControlSocket %s already exists, disabling multiplexing",
1226 unlink(options.control_path);
1227 goto disable_mux_master;
1229 unlink(options.control_path);
1230 xfree(options.control_path);
1231 options.control_path = orig_control_path;
1233 set_nonblock(muxserver_sock);
1235 mux_listener_channel = channel_new("mux listener",
1236 SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
1237 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1238 0, options.control_path, 1);
1239 mux_listener_channel->mux_rcb = mux_master_read_cb;
1240 debug3("%s: mux listener channel %d fd %d", __func__,
1241 mux_listener_channel->self, mux_listener_channel->sock);
1244 /* Callback on open confirmation in mux master for a mux client session. */
1246 mux_session_confirm(int id, int success, void *arg)
1248 struct mux_session_confirm_ctx *cctx = arg;
1249 const char *display;
1255 fatal("%s: cctx == NULL", __func__);
1256 if ((c = channel_by_id(id)) == NULL)
1257 fatal("%s: no channel for id %d", __func__, id);
1258 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1259 fatal("%s: channel %d lacks control channel %d", __func__,
1263 debug3("%s: sending failure reply", __func__);
1265 buffer_init(&reply);
1266 buffer_put_int(&reply, MUX_S_FAILURE);
1267 buffer_put_int(&reply, cctx->rid);
1268 buffer_put_cstring(&reply, "Session open refused by peer");
1272 display = getenv("DISPLAY");
1273 if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1276 /* Get reasonable local authentication information. */
1277 client_x11_get_proto(display, options.xauth_location,
1278 options.forward_x11_trusted, options.forward_x11_timeout,
1280 /* Request forwarding with authentication spoofing. */
1281 debug("Requesting X11 forwarding with authentication "
1283 x11_request_forwarding_with_spoofing(id, display, proto,
1285 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1286 /* XXX exit_on_forward_failure */
1289 if (cctx->want_agent_fwd && options.forward_agent) {
1290 debug("Requesting authentication agent forwarding.");
1291 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1295 client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1296 cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1298 debug3("%s: sending success reply", __func__);
1300 buffer_init(&reply);
1301 buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1302 buffer_put_int(&reply, cctx->rid);
1303 buffer_put_int(&reply, c->self);
1307 buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1308 buffer_free(&reply);
1310 if (cc->mux_pause <= 0)
1311 fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1312 cc->mux_pause = 0; /* start processing messages again */
1313 c->open_confirm_ctx = NULL;
1314 buffer_free(&cctx->cmd);
1316 if (cctx->env != NULL) {
1317 for (i = 0; cctx->env[i] != NULL; i++)
1318 xfree(cctx->env[i]);
1324 /* ** Multiplexing client support */
1326 /* Exit signal handler */
1328 control_client_sighandler(int signo)
1330 muxclient_terminate = signo;
1334 * Relay signal handler - used to pass some signals from mux client to
1338 control_client_sigrelay(int signo)
1340 int save_errno = errno;
1342 if (muxserver_pid > 1)
1343 kill(muxserver_pid, signo);
1349 mux_client_read(int fd, Buffer *b, u_int need)
1357 pfd.events = POLLIN;
1358 p = buffer_append_space(b, need);
1359 for (have = 0; have < need; ) {
1360 if (muxclient_terminate) {
1364 len = read(fd, p + have, need - have);
1367 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1371 (void)poll(&pfd, 1, -1);
1389 mux_client_write_packet(int fd, Buffer *m)
1398 pfd.events = POLLOUT;
1399 buffer_init(&queue);
1400 buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1402 need = buffer_len(&queue);
1403 ptr = buffer_ptr(&queue);
1405 for (have = 0; have < need; ) {
1406 if (muxclient_terminate) {
1407 buffer_free(&queue);
1411 len = write(fd, ptr + have, need - have);
1414 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1418 (void)poll(&pfd, 1, -1);
1424 buffer_free(&queue);
1430 buffer_free(&queue);
1436 buffer_free(&queue);
1441 mux_client_read_packet(int fd, Buffer *m)
1448 buffer_init(&queue);
1449 if (mux_client_read(fd, &queue, 4) != 0) {
1450 if ((oerrno = errno) == EPIPE)
1451 debug3("%s: read header failed: %s", __func__, strerror(errno));
1455 need = get_u32(buffer_ptr(&queue));
1456 if (mux_client_read(fd, &queue, need) != 0) {
1458 debug3("%s: read body failed: %s", __func__, strerror(errno));
1462 ptr = buffer_get_string_ptr(&queue, &have);
1463 buffer_append(m, ptr, have);
1464 buffer_free(&queue);
1469 mux_client_hello_exchange(int fd)
1475 buffer_put_int(&m, MUX_MSG_HELLO);
1476 buffer_put_int(&m, SSHMUX_VER);
1479 if (mux_client_write_packet(fd, &m) != 0)
1480 fatal("%s: write packet: %s", __func__, strerror(errno));
1484 /* Read their HELLO */
1485 if (mux_client_read_packet(fd, &m) != 0) {
1490 type = buffer_get_int(&m);
1491 if (type != MUX_MSG_HELLO)
1492 fatal("%s: expected HELLO (%u) received %u",
1493 __func__, MUX_MSG_HELLO, type);
1494 ver = buffer_get_int(&m);
1495 if (ver != SSHMUX_VER)
1496 fatal("Unsupported multiplexing protocol version %d "
1497 "(expected %d)", ver, SSHMUX_VER);
1498 debug2("%s: master version %u", __func__, ver);
1499 /* No extensions are presently defined */
1500 while (buffer_len(&m) > 0) {
1501 char *name = buffer_get_string(&m, NULL);
1502 char *value = buffer_get_string(&m, NULL);
1504 debug2("Unrecognised master extension \"%s\"", name);
1513 mux_client_request_alive(int fd)
1517 u_int pid, type, rid;
1519 debug3("%s: entering", __func__);
1522 buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1523 buffer_put_int(&m, muxclient_request_id);
1525 if (mux_client_write_packet(fd, &m) != 0)
1526 fatal("%s: write packet: %s", __func__, strerror(errno));
1530 /* Read their reply */
1531 if (mux_client_read_packet(fd, &m) != 0) {
1536 type = buffer_get_int(&m);
1537 if (type != MUX_S_ALIVE) {
1538 e = buffer_get_string(&m, NULL);
1539 fatal("%s: master returned error: %s", __func__, e);
1542 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1543 fatal("%s: out of sequence reply: my id %u theirs %u",
1544 __func__, muxclient_request_id, rid);
1545 pid = buffer_get_int(&m);
1548 debug3("%s: done pid = %u", __func__, pid);
1550 muxclient_request_id++;
1556 mux_client_request_terminate(int fd)
1562 debug3("%s: entering", __func__);
1565 buffer_put_int(&m, MUX_C_TERMINATE);
1566 buffer_put_int(&m, muxclient_request_id);
1568 if (mux_client_write_packet(fd, &m) != 0)
1569 fatal("%s: write packet: %s", __func__, strerror(errno));
1573 /* Read their reply */
1574 if (mux_client_read_packet(fd, &m) != 0) {
1575 /* Remote end exited already */
1576 if (errno == EPIPE) {
1580 fatal("%s: read from master failed: %s",
1581 __func__, strerror(errno));
1584 type = buffer_get_int(&m);
1585 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1586 fatal("%s: out of sequence reply: my id %u theirs %u",
1587 __func__, muxclient_request_id, rid);
1591 case MUX_S_PERMISSION_DENIED:
1592 e = buffer_get_string(&m, NULL);
1593 fatal("Master refused termination request: %s", e);
1595 e = buffer_get_string(&m, NULL);
1596 fatal("%s: termination request failed: %s", __func__, e);
1598 fatal("%s: unexpected response from master 0x%08x",
1602 muxclient_request_id++;
1606 mux_client_forward(int fd, int cancel_flag, u_int ftype, Forward *fwd)
1612 fwd_desc = format_forward(ftype, fwd);
1613 debug("Requesting %s %s",
1614 cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
1618 buffer_put_int(&m, cancel_flag ? MUX_C_CLOSE_FWD : MUX_C_OPEN_FWD);
1619 buffer_put_int(&m, muxclient_request_id);
1620 buffer_put_int(&m, ftype);
1621 buffer_put_cstring(&m,
1622 fwd->listen_host == NULL ? "" : fwd->listen_host);
1623 buffer_put_int(&m, fwd->listen_port);
1624 buffer_put_cstring(&m,
1625 fwd->connect_host == NULL ? "" : fwd->connect_host);
1626 buffer_put_int(&m, fwd->connect_port);
1628 if (mux_client_write_packet(fd, &m) != 0)
1629 fatal("%s: write packet: %s", __func__, strerror(errno));
1633 /* Read their reply */
1634 if (mux_client_read_packet(fd, &m) != 0) {
1639 type = buffer_get_int(&m);
1640 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1641 fatal("%s: out of sequence reply: my id %u theirs %u",
1642 __func__, muxclient_request_id, rid);
1646 case MUX_S_REMOTE_PORT:
1648 fatal("%s: got MUX_S_REMOTE_PORT for cancel", __func__);
1649 fwd->allocated_port = buffer_get_int(&m);
1650 logit("Allocated port %u for remote forward to %s:%d",
1651 fwd->allocated_port,
1652 fwd->connect_host ? fwd->connect_host : "",
1654 if (muxclient_command == SSHMUX_COMMAND_FORWARD)
1655 fprintf(stdout, "%u\n", fwd->allocated_port);
1657 case MUX_S_PERMISSION_DENIED:
1658 e = buffer_get_string(&m, NULL);
1660 error("Master refused forwarding request: %s", e);
1663 e = buffer_get_string(&m, NULL);
1665 error("%s: forwarding request failed: %s", __func__, e);
1668 fatal("%s: unexpected response from master 0x%08x",
1673 muxclient_request_id++;
1678 mux_client_forwards(int fd, int cancel_flag)
1682 debug3("%s: %s forwardings: %d local, %d remote", __func__,
1683 cancel_flag ? "cancel" : "request",
1684 options.num_local_forwards, options.num_remote_forwards);
1686 /* XXX ExitOnForwardingFailure */
1687 for (i = 0; i < options.num_local_forwards; i++) {
1688 if (mux_client_forward(fd, cancel_flag,
1689 options.local_forwards[i].connect_port == 0 ?
1690 MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1691 options.local_forwards + i) != 0)
1694 for (i = 0; i < options.num_remote_forwards; i++) {
1695 if (mux_client_forward(fd, cancel_flag, MUX_FWD_REMOTE,
1696 options.remote_forwards + i) != 0)
1703 mux_client_request_session(int fd)
1707 u_int i, rid, sid, esid, exitval, type, exitval_seen;
1708 extern char **environ;
1709 int devnull, rawmode;
1711 debug3("%s: entering", __func__);
1713 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1714 error("%s: master alive request failed", __func__);
1718 signal(SIGPIPE, SIG_IGN);
1720 if (stdin_null_flag) {
1721 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1722 fatal("open(/dev/null): %s", strerror(errno));
1723 if (dup2(devnull, STDIN_FILENO) == -1)
1724 fatal("dup2: %s", strerror(errno));
1725 if (devnull > STDERR_FILENO)
1729 term = getenv("TERM");
1732 buffer_put_int(&m, MUX_C_NEW_SESSION);
1733 buffer_put_int(&m, muxclient_request_id);
1734 buffer_put_cstring(&m, ""); /* reserved */
1735 buffer_put_int(&m, tty_flag);
1736 buffer_put_int(&m, options.forward_x11);
1737 buffer_put_int(&m, options.forward_agent);
1738 buffer_put_int(&m, subsystem_flag);
1739 buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1740 0xffffffff : (u_int)options.escape_char);
1741 buffer_put_cstring(&m, term == NULL ? "" : term);
1742 buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1744 if (options.num_send_env > 0 && environ != NULL) {
1745 /* Pass environment */
1746 for (i = 0; environ[i] != NULL; i++) {
1747 if (env_permitted(environ[i])) {
1748 buffer_put_cstring(&m, environ[i]);
1753 if (mux_client_write_packet(fd, &m) != 0)
1754 fatal("%s: write packet: %s", __func__, strerror(errno));
1756 /* Send the stdio file descriptors */
1757 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1758 mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1759 mm_send_fd(fd, STDERR_FILENO) == -1)
1760 fatal("%s: send fds failed", __func__);
1762 debug3("%s: session request sent", __func__);
1764 /* Read their reply */
1766 if (mux_client_read_packet(fd, &m) != 0) {
1767 error("%s: read from master failed: %s",
1768 __func__, strerror(errno));
1773 type = buffer_get_int(&m);
1774 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1775 fatal("%s: out of sequence reply: my id %u theirs %u",
1776 __func__, muxclient_request_id, rid);
1778 case MUX_S_SESSION_OPENED:
1779 sid = buffer_get_int(&m);
1780 debug("%s: master session id: %u", __func__, sid);
1782 case MUX_S_PERMISSION_DENIED:
1783 e = buffer_get_string(&m, NULL);
1785 error("Master refused session request: %s", e);
1788 e = buffer_get_string(&m, NULL);
1790 error("%s: session request failed: %s", __func__, e);
1794 error("%s: unexpected response from master 0x%08x",
1798 muxclient_request_id++;
1800 signal(SIGHUP, control_client_sighandler);
1801 signal(SIGINT, control_client_sighandler);
1802 signal(SIGTERM, control_client_sighandler);
1803 signal(SIGWINCH, control_client_sigrelay);
1807 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1810 * Stick around until the controlee closes the client_fd.
1811 * Before it does, it is expected to write an exit message.
1812 * This process must read the value and wait for the closure of
1813 * the client_fd; if this one closes early, the multiplex master will
1814 * terminate early too (possibly losing data).
1816 for (exitval = 255, exitval_seen = 0;;) {
1818 if (mux_client_read_packet(fd, &m) != 0)
1820 type = buffer_get_int(&m);
1822 case MUX_S_TTY_ALLOC_FAIL:
1823 if ((esid = buffer_get_int(&m)) != sid)
1824 fatal("%s: tty alloc fail on unknown session: "
1825 "my id %u theirs %u",
1826 __func__, sid, esid);
1827 leave_raw_mode(options.request_tty ==
1831 case MUX_S_EXIT_MESSAGE:
1832 if ((esid = buffer_get_int(&m)) != sid)
1833 fatal("%s: exit on unknown session: "
1834 "my id %u theirs %u",
1835 __func__, sid, esid);
1837 fatal("%s: exitval sent twice", __func__);
1838 exitval = buffer_get_int(&m);
1842 e = buffer_get_string(&m, NULL);
1843 fatal("%s: master returned error: %s", __func__, e);
1849 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1851 if (muxclient_terminate) {
1852 debug2("Exiting on signal %d", muxclient_terminate);
1854 } else if (!exitval_seen) {
1855 debug2("Control master terminated unexpectedly");
1858 debug2("Received exit status from master %d", exitval);
1860 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1861 fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1867 mux_client_request_stdio_fwd(int fd)
1871 u_int type, rid, sid;
1874 debug3("%s: entering", __func__);
1876 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1877 error("%s: master alive request failed", __func__);
1881 signal(SIGPIPE, SIG_IGN);
1883 if (stdin_null_flag) {
1884 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1885 fatal("open(/dev/null): %s", strerror(errno));
1886 if (dup2(devnull, STDIN_FILENO) == -1)
1887 fatal("dup2: %s", strerror(errno));
1888 if (devnull > STDERR_FILENO)
1893 buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
1894 buffer_put_int(&m, muxclient_request_id);
1895 buffer_put_cstring(&m, ""); /* reserved */
1896 buffer_put_cstring(&m, stdio_forward_host);
1897 buffer_put_int(&m, stdio_forward_port);
1899 if (mux_client_write_packet(fd, &m) != 0)
1900 fatal("%s: write packet: %s", __func__, strerror(errno));
1902 /* Send the stdio file descriptors */
1903 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1904 mm_send_fd(fd, STDOUT_FILENO) == -1)
1905 fatal("%s: send fds failed", __func__);
1907 debug3("%s: stdio forward request sent", __func__);
1909 /* Read their reply */
1912 if (mux_client_read_packet(fd, &m) != 0) {
1913 error("%s: read from master failed: %s",
1914 __func__, strerror(errno));
1919 type = buffer_get_int(&m);
1920 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1921 fatal("%s: out of sequence reply: my id %u theirs %u",
1922 __func__, muxclient_request_id, rid);
1924 case MUX_S_SESSION_OPENED:
1925 sid = buffer_get_int(&m);
1926 debug("%s: master session id: %u", __func__, sid);
1928 case MUX_S_PERMISSION_DENIED:
1929 e = buffer_get_string(&m, NULL);
1931 fatal("Master refused stdio forwarding request: %s", e);
1933 e = buffer_get_string(&m, NULL);
1935 fatal("%s: stdio forwarding request failed: %s", __func__, e);
1938 error("%s: unexpected response from master 0x%08x",
1942 muxclient_request_id++;
1944 signal(SIGHUP, control_client_sighandler);
1945 signal(SIGINT, control_client_sighandler);
1946 signal(SIGTERM, control_client_sighandler);
1947 signal(SIGWINCH, control_client_sigrelay);
1950 * Stick around until the controlee closes the client_fd.
1953 if (mux_client_read_packet(fd, &m) != 0) {
1954 if (errno == EPIPE ||
1955 (errno == EINTR && muxclient_terminate != 0))
1957 fatal("%s: mux_client_read_packet: %s",
1958 __func__, strerror(errno));
1960 fatal("%s: master returned unexpected message %u", __func__, type);
1964 mux_client_request_stop_listening(int fd)
1970 debug3("%s: entering", __func__);
1973 buffer_put_int(&m, MUX_C_STOP_LISTENING);
1974 buffer_put_int(&m, muxclient_request_id);
1976 if (mux_client_write_packet(fd, &m) != 0)
1977 fatal("%s: write packet: %s", __func__, strerror(errno));
1981 /* Read their reply */
1982 if (mux_client_read_packet(fd, &m) != 0)
1983 fatal("%s: read from master failed: %s",
1984 __func__, strerror(errno));
1986 type = buffer_get_int(&m);
1987 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1988 fatal("%s: out of sequence reply: my id %u theirs %u",
1989 __func__, muxclient_request_id, rid);
1993 case MUX_S_PERMISSION_DENIED:
1994 e = buffer_get_string(&m, NULL);
1995 fatal("Master refused stop listening request: %s", e);
1997 e = buffer_get_string(&m, NULL);
1998 fatal("%s: stop listening request failed: %s", __func__, e);
2000 fatal("%s: unexpected response from master 0x%08x",
2004 muxclient_request_id++;
2007 /* Multiplex client main loop. */
2009 muxclient(const char *path)
2011 struct sockaddr_un addr;
2016 if (muxclient_command == 0) {
2017 if (stdio_forward_host != NULL)
2018 muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
2020 muxclient_command = SSHMUX_COMMAND_OPEN;
2023 switch (options.control_master) {
2024 case SSHCTL_MASTER_AUTO:
2025 case SSHCTL_MASTER_AUTO_ASK:
2026 debug("auto-mux: Trying existing master");
2028 case SSHCTL_MASTER_NO:
2034 memset(&addr, '\0', sizeof(addr));
2035 addr.sun_family = AF_UNIX;
2036 sun_len = offsetof(struct sockaddr_un, sun_path) +
2039 if (strlcpy(addr.sun_path, path,
2040 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
2041 fatal("ControlPath too long");
2043 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
2044 fatal("%s socket(): %s", __func__, strerror(errno));
2046 if (connect(sock, (struct sockaddr *)&addr, sun_len) == -1) {
2047 switch (muxclient_command) {
2048 case SSHMUX_COMMAND_OPEN:
2049 case SSHMUX_COMMAND_STDIO_FWD:
2052 fatal("Control socket connect(%.100s): %s", path,
2055 if (errno == ECONNREFUSED &&
2056 options.control_master != SSHCTL_MASTER_NO) {
2057 debug("Stale control socket %.100s, unlinking", path);
2059 } else if (errno == ENOENT) {
2060 debug("Control socket \"%.100s\" does not exist", path);
2062 error("Control socket connect(%.100s): %s", path,
2070 if (mux_client_hello_exchange(sock) != 0) {
2071 error("%s: master hello exchange failed", __func__);
2076 switch (muxclient_command) {
2077 case SSHMUX_COMMAND_ALIVE_CHECK:
2078 if ((pid = mux_client_request_alive(sock)) == 0)
2079 fatal("%s: master alive check failed", __func__);
2080 fprintf(stderr, "Master running (pid=%d)\r\n", pid);
2082 case SSHMUX_COMMAND_TERMINATE:
2083 mux_client_request_terminate(sock);
2084 fprintf(stderr, "Exit request sent.\r\n");
2086 case SSHMUX_COMMAND_FORWARD:
2087 if (mux_client_forwards(sock, 0) != 0)
2088 fatal("%s: master forward request failed", __func__);
2090 case SSHMUX_COMMAND_OPEN:
2091 if (mux_client_forwards(sock, 0) != 0) {
2092 error("%s: master forward request failed", __func__);
2095 mux_client_request_session(sock);
2097 case SSHMUX_COMMAND_STDIO_FWD:
2098 mux_client_request_stdio_fwd(sock);
2100 case SSHMUX_COMMAND_STOP:
2101 mux_client_request_stop_listening(sock);
2102 fprintf(stderr, "Stop listening request sent.\r\n");
2104 case SSHMUX_COMMAND_CANCEL_FWD:
2105 if (mux_client_forwards(sock, 1) != 0)
2106 error("%s: master cancel forward request failed",
2110 fatal("unrecognised muxclient_command %d", muxclient_command);