1 /* $OpenBSD: mux.c,v 1.54 2015/08/19 23:18:26 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>
37 #include <sys/socket.h>
56 # ifdef HAVE_SYS_POLL_H
57 # include <sys/poll.h>
65 #include "openbsd-compat/sys-queue.h"
70 #include "pathnames.h"
77 #include "monitor_fdpass.h"
81 #include "clientloop.h"
85 extern Options options;
86 extern int stdin_null_flag;
88 extern int subsystem_flag;
89 extern Buffer command;
90 extern volatile sig_atomic_t quit_pending;
91 extern char *stdio_forward_host;
92 extern int stdio_forward_port;
94 /* Context for session open confirmation callback */
95 struct mux_session_confirm_ctx {
107 /* Context for stdio fwd open confirmation callback */
108 struct mux_stdio_confirm_ctx {
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 *);
164 static void mux_stdio_confirm(int, int, void *);
166 static int process_mux_master_hello(u_int, Channel *, Buffer *, Buffer *);
167 static int process_mux_new_session(u_int, Channel *, Buffer *, Buffer *);
168 static int process_mux_alive_check(u_int, Channel *, Buffer *, Buffer *);
169 static int process_mux_terminate(u_int, Channel *, Buffer *, Buffer *);
170 static int process_mux_open_fwd(u_int, Channel *, Buffer *, Buffer *);
171 static int process_mux_close_fwd(u_int, Channel *, Buffer *, Buffer *);
172 static int process_mux_stdio_fwd(u_int, Channel *, Buffer *, Buffer *);
173 static int process_mux_stop_listening(u_int, Channel *, Buffer *, Buffer *);
175 static const struct {
177 int (*handler)(u_int, Channel *, Buffer *, Buffer *);
178 } mux_master_handlers[] = {
179 { MUX_MSG_HELLO, process_mux_master_hello },
180 { MUX_C_NEW_SESSION, process_mux_new_session },
181 { MUX_C_ALIVE_CHECK, process_mux_alive_check },
182 { MUX_C_TERMINATE, process_mux_terminate },
183 { MUX_C_OPEN_FWD, process_mux_open_fwd },
184 { MUX_C_CLOSE_FWD, process_mux_close_fwd },
185 { MUX_C_NEW_STDIO_FWD, process_mux_stdio_fwd },
186 { MUX_C_STOP_LISTENING, process_mux_stop_listening },
190 /* Cleanup callback fired on closure of mux slave _session_ channel */
193 mux_master_session_cleanup_cb(int cid, void *unused)
195 Channel *cc, *c = channel_by_id(cid);
197 debug3("%s: entering for channel %d", __func__, cid);
199 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
200 if (c->ctl_chan != -1) {
201 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
202 fatal("%s: channel %d missing control channel %d",
203 __func__, c->self, c->ctl_chan);
206 chan_rcvd_oclose(cc);
208 channel_cancel_cleanup(c->self);
211 /* Cleanup callback fired on closure of mux slave _control_ channel */
214 mux_master_control_cleanup_cb(int cid, void *unused)
216 Channel *sc, *c = channel_by_id(cid);
218 debug3("%s: entering for channel %d", __func__, cid);
220 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
221 if (c->remote_id != -1) {
222 if ((sc = channel_by_id(c->remote_id)) == NULL)
223 fatal("%s: channel %d missing session channel %d",
224 __func__, c->self, c->remote_id);
227 if (sc->type != SSH_CHANNEL_OPEN &&
228 sc->type != SSH_CHANNEL_OPENING) {
229 debug2("%s: channel %d: not open", __func__, sc->self);
232 if (sc->istate == CHAN_INPUT_OPEN)
233 chan_read_failed(sc);
234 if (sc->ostate == CHAN_OUTPUT_OPEN)
235 chan_write_failed(sc);
238 channel_cancel_cleanup(c->self);
241 /* Check mux client environment variables before passing them to mux master. */
243 env_permitted(char *env)
246 char name[1024], *cp;
248 if ((cp = strchr(env, '=')) == NULL || cp == env)
250 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
251 if (ret <= 0 || (size_t)ret >= sizeof(name)) {
252 error("env_permitted: name '%.100s...' too long", env);
256 for (i = 0; i < options.num_send_env; i++)
257 if (match_pattern(name, options.send_env[i]))
263 /* Mux master protocol message handlers */
266 process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
269 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
272 fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
273 if (state->hello_rcvd) {
274 error("%s: HELLO received twice", __func__);
277 if (buffer_get_int_ret(&ver, m) != 0) {
279 error("%s: malformed message", __func__);
282 if (ver != SSHMUX_VER) {
283 error("Unsupported multiplexing protocol version %d "
284 "(expected %d)", ver, SSHMUX_VER);
287 debug2("%s: channel %d slave version %u", __func__, c->self, ver);
289 /* No extensions are presently defined */
290 while (buffer_len(m) > 0) {
291 char *name = buffer_get_string_ret(m, NULL);
292 char *value = buffer_get_string_ret(m, NULL);
294 if (name == NULL || value == NULL) {
299 debug2("Unrecognised slave extension \"%s\"", name);
303 state->hello_rcvd = 1;
308 process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
311 struct mux_session_confirm_ctx *cctx;
312 char *reserved, *cmd, *cp;
313 u_int i, j, len, env_len, escape_char, window, packetmax;
316 /* Reply for SSHMUX_COMMAND_OPEN */
317 cctx = xcalloc(1, sizeof(*cctx));
320 cmd = reserved = NULL;
323 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
324 buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
325 buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
326 buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
327 buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
328 buffer_get_int_ret(&escape_char, m) != 0 ||
329 (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
330 (cmd = buffer_get_string_ret(m, &len)) == NULL) {
334 for (j = 0; j < env_len; j++)
339 error("%s: malformed message", __func__);
345 while (buffer_len(m) > 0) {
346 #define MUX_MAX_ENV_VARS 4096
347 if ((cp = buffer_get_string_ret(m, &len)) == NULL)
349 if (!env_permitted(cp)) {
353 cctx->env = xreallocarray(cctx->env, env_len + 2,
355 cctx->env[env_len++] = cp;
356 cctx->env[env_len] = NULL;
357 if (env_len > MUX_MAX_ENV_VARS) {
358 error(">%d environment variables received, ignoring "
359 "additional", MUX_MAX_ENV_VARS);
364 debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
365 "term \"%s\", cmd \"%s\", env %u", __func__, c->self,
366 cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
367 cctx->want_subsys, cctx->term, cmd, env_len);
369 buffer_init(&cctx->cmd);
370 buffer_append(&cctx->cmd, cmd, strlen(cmd));
374 /* Gather fds from client */
375 for(i = 0; i < 3; i++) {
376 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
377 error("%s: failed to receive fd %d from slave",
379 for (j = 0; j < i; j++)
381 for (j = 0; j < env_len; j++)
385 buffer_free(&cctx->cmd);
389 buffer_put_int(r, MUX_S_FAILURE);
390 buffer_put_int(r, rid);
391 buffer_put_cstring(r,
392 "did not receive file descriptors");
397 debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
398 new_fd[0], new_fd[1], new_fd[2]);
400 /* XXX support multiple child sessions in future */
401 if (c->remote_id != -1) {
402 debug2("%s: session already open", __func__);
404 buffer_put_int(r, MUX_S_FAILURE);
405 buffer_put_int(r, rid);
406 buffer_put_cstring(r, "Multiple sessions not supported");
413 for (i = 0; i < env_len; i++)
417 buffer_free(&cctx->cmd);
422 if (options.control_master == SSHCTL_MASTER_ASK ||
423 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
424 if (!ask_permission("Allow shared connection to %s? ", host)) {
425 debug2("%s: session refused by user", __func__);
427 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
428 buffer_put_int(r, rid);
429 buffer_put_cstring(r, "Permission denied");
434 /* Try to pick up ttymodes from client before it goes raw */
435 if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
436 error("%s: tcgetattr: %s", __func__, strerror(errno));
438 /* enable nonblocking unless tty */
439 if (!isatty(new_fd[0]))
440 set_nonblock(new_fd[0]);
441 if (!isatty(new_fd[1]))
442 set_nonblock(new_fd[1]);
443 if (!isatty(new_fd[2]))
444 set_nonblock(new_fd[2]);
446 window = CHAN_SES_WINDOW_DEFAULT;
447 packetmax = CHAN_SES_PACKET_DEFAULT;
448 if (cctx->want_tty) {
453 nc = channel_new("session", SSH_CHANNEL_OPENING,
454 new_fd[0], new_fd[1], new_fd[2], window, packetmax,
455 CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
457 nc->ctl_chan = c->self; /* link session -> control channel */
458 c->remote_id = nc->self; /* link control -> session channel */
460 if (cctx->want_tty && escape_char != 0xffffffff) {
461 channel_register_filter(nc->self,
462 client_simple_escape_filter, NULL,
463 client_filter_cleanup,
464 client_new_escape_filter_ctx((int)escape_char));
467 debug2("%s: channel_new: %d linked to control channel %d",
468 __func__, nc->self, nc->ctl_chan);
470 channel_send_open(nc->self);
471 channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
472 c->mux_pause = 1; /* stop handling messages until open_confirm done */
473 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
475 /* reply is deferred, sent by mux_session_confirm */
480 process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
482 debug2("%s: channel %d: alive check", __func__, c->self);
485 buffer_put_int(r, MUX_S_ALIVE);
486 buffer_put_int(r, rid);
487 buffer_put_int(r, (u_int)getpid());
493 process_mux_terminate(u_int rid, Channel *c, Buffer *m, Buffer *r)
495 debug2("%s: channel %d: terminate request", __func__, c->self);
497 if (options.control_master == SSHCTL_MASTER_ASK ||
498 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
499 if (!ask_permission("Terminate shared connection to %s? ",
501 debug2("%s: termination refused by user", __func__);
502 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
503 buffer_put_int(r, rid);
504 buffer_put_cstring(r, "Permission denied");
510 buffer_put_int(r, MUX_S_OK);
511 buffer_put_int(r, rid);
512 /* XXX exit happens too soon - message never makes it to client */
517 format_forward(u_int ftype, struct Forward *fwd)
523 xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
524 (fwd->listen_path != NULL) ? fwd->listen_path :
525 (fwd->listen_host == NULL) ?
526 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
527 fwd->listen_host, fwd->listen_port,
528 (fwd->connect_path != NULL) ? fwd->connect_path :
529 fwd->connect_host, fwd->connect_port);
531 case MUX_FWD_DYNAMIC:
532 xasprintf(&ret, "dynamic forward %.200s:%d -> *",
533 (fwd->listen_host == NULL) ?
534 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
535 fwd->listen_host, fwd->listen_port);
538 xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
539 (fwd->listen_path != NULL) ? fwd->listen_path :
540 (fwd->listen_host == NULL) ?
541 "LOCALHOST" : fwd->listen_host,
543 (fwd->connect_path != NULL) ? fwd->connect_path :
544 fwd->connect_host, fwd->connect_port);
547 fatal("%s: unknown forward type %u", __func__, ftype);
553 compare_host(const char *a, const char *b)
555 if (a == NULL && b == NULL)
557 if (a == NULL || b == NULL)
559 return strcmp(a, b) == 0;
563 compare_forward(struct Forward *a, struct Forward *b)
565 if (!compare_host(a->listen_host, b->listen_host))
567 if (!compare_host(a->listen_path, b->listen_path))
569 if (a->listen_port != b->listen_port)
571 if (!compare_host(a->connect_host, b->connect_host))
573 if (!compare_host(a->connect_path, b->connect_path))
575 if (a->connect_port != b->connect_port)
582 mux_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
584 struct mux_channel_confirm_ctx *fctx = ctxt;
585 char *failmsg = NULL;
586 struct Forward *rfwd;
590 if ((c = channel_by_id(fctx->cid)) == NULL) {
591 /* no channel for reply */
592 error("%s: unknown channel", __func__);
596 if (fctx->fid >= options.num_remote_forwards ||
597 (options.remote_forwards[fctx->fid].connect_path == NULL &&
598 options.remote_forwards[fctx->fid].connect_host == NULL)) {
599 xasprintf(&failmsg, "unknown forwarding id %d", fctx->fid);
602 rfwd = &options.remote_forwards[fctx->fid];
603 debug("%s: %s for: listen %d, connect %s:%d", __func__,
604 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
605 rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
606 rfwd->connect_host, rfwd->connect_port);
607 if (type == SSH2_MSG_REQUEST_SUCCESS) {
608 if (rfwd->listen_port == 0) {
609 rfwd->allocated_port = packet_get_int();
610 debug("Allocated port %u for mux remote forward"
611 " to %s:%d", rfwd->allocated_port,
612 rfwd->connect_host, rfwd->connect_port);
613 buffer_put_int(&out, MUX_S_REMOTE_PORT);
614 buffer_put_int(&out, fctx->rid);
615 buffer_put_int(&out, rfwd->allocated_port);
616 channel_update_permitted_opens(rfwd->handle,
617 rfwd->allocated_port);
619 buffer_put_int(&out, MUX_S_OK);
620 buffer_put_int(&out, fctx->rid);
624 if (rfwd->listen_port == 0)
625 channel_update_permitted_opens(rfwd->handle, -1);
626 if (rfwd->listen_path != NULL)
627 xasprintf(&failmsg, "remote port forwarding failed for "
628 "listen path %s", rfwd->listen_path);
630 xasprintf(&failmsg, "remote port forwarding failed for "
631 "listen port %d", rfwd->listen_port);
633 debug2("%s: clearing registered forwarding for listen %d, "
634 "connect %s:%d", __func__, rfwd->listen_port,
635 rfwd->connect_path ? rfwd->connect_path :
636 rfwd->connect_host, rfwd->connect_port);
638 free(rfwd->listen_host);
639 free(rfwd->listen_path);
640 free(rfwd->connect_host);
641 free(rfwd->connect_path);
642 memset(rfwd, 0, sizeof(*rfwd));
645 error("%s: %s", __func__, failmsg);
646 buffer_put_int(&out, MUX_S_FAILURE);
647 buffer_put_int(&out, fctx->rid);
648 buffer_put_cstring(&out, failmsg);
651 buffer_put_string(&c->output, buffer_ptr(&out), buffer_len(&out));
653 if (c->mux_pause <= 0)
654 fatal("%s: mux_pause %d", __func__, c->mux_pause);
655 c->mux_pause = 0; /* start processing messages again */
659 process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
662 char *fwd_desc = NULL;
663 char *listen_addr, *connect_addr;
666 int i, ret = 0, freefwd = 1;
668 memset(&fwd, 0, sizeof(fwd));
670 /* XXX - lport/cport check redundant */
671 if (buffer_get_int_ret(&ftype, m) != 0 ||
672 (listen_addr = buffer_get_string_ret(m, NULL)) == NULL ||
673 buffer_get_int_ret(&lport, m) != 0 ||
674 (connect_addr = buffer_get_string_ret(m, NULL)) == NULL ||
675 buffer_get_int_ret(&cport, m) != 0 ||
676 (lport != (u_int)PORT_STREAMLOCAL && lport > 65535) ||
677 (cport != (u_int)PORT_STREAMLOCAL && cport > 65535)) {
678 error("%s: malformed message", __func__);
682 if (*listen_addr == '\0') {
686 if (*connect_addr == '\0') {
691 memset(&fwd, 0, sizeof(fwd));
692 fwd.listen_port = lport;
693 if (fwd.listen_port == PORT_STREAMLOCAL)
694 fwd.listen_path = listen_addr;
696 fwd.listen_host = listen_addr;
697 fwd.connect_port = cport;
698 if (fwd.connect_port == PORT_STREAMLOCAL)
699 fwd.connect_path = connect_addr;
701 fwd.connect_host = connect_addr;
703 debug2("%s: channel %d: request %s", __func__, c->self,
704 (fwd_desc = format_forward(ftype, &fwd)));
706 if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
707 ftype != MUX_FWD_DYNAMIC) {
708 logit("%s: invalid forwarding type %u", __func__, ftype);
712 buffer_put_int(r, MUX_S_FAILURE);
713 buffer_put_int(r, rid);
714 buffer_put_cstring(r, "Invalid forwarding request");
717 if (ftype == MUX_FWD_DYNAMIC && fwd.listen_path) {
718 logit("%s: streamlocal and dynamic forwards "
719 "are mutually exclusive", __func__);
722 if (fwd.listen_port != PORT_STREAMLOCAL && fwd.listen_port >= 65536) {
723 logit("%s: invalid listen port %u", __func__,
727 if ((fwd.connect_port != PORT_STREAMLOCAL && fwd.connect_port >= 65536)
728 || (ftype != MUX_FWD_DYNAMIC && ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
729 logit("%s: invalid connect port %u", __func__,
733 if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL && fwd.connect_path == NULL) {
734 logit("%s: missing connect host", __func__);
738 /* Skip forwards that have already been requested */
741 case MUX_FWD_DYNAMIC:
742 for (i = 0; i < options.num_local_forwards; i++) {
743 if (compare_forward(&fwd,
744 options.local_forwards + i)) {
746 debug2("%s: found existing forwarding",
748 buffer_put_int(r, MUX_S_OK);
749 buffer_put_int(r, rid);
755 for (i = 0; i < options.num_remote_forwards; i++) {
756 if (compare_forward(&fwd,
757 options.remote_forwards + i)) {
758 if (fwd.listen_port != 0)
760 debug2("%s: found allocated port",
762 buffer_put_int(r, MUX_S_REMOTE_PORT);
763 buffer_put_int(r, rid);
765 options.remote_forwards[i].allocated_port);
772 if (options.control_master == SSHCTL_MASTER_ASK ||
773 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
774 if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
775 debug2("%s: forwarding refused by user", __func__);
776 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
777 buffer_put_int(r, rid);
778 buffer_put_cstring(r, "Permission denied");
783 if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
784 if (!channel_setup_local_fwd_listener(&fwd,
785 &options.fwd_opts)) {
787 logit("slave-requested %s failed", fwd_desc);
788 buffer_put_int(r, MUX_S_FAILURE);
789 buffer_put_int(r, rid);
790 buffer_put_cstring(r, "Port forwarding failed");
793 add_local_forward(&options, &fwd);
796 struct mux_channel_confirm_ctx *fctx;
798 fwd.handle = channel_request_remote_forwarding(&fwd);
801 add_remote_forward(&options, &fwd);
802 fctx = xcalloc(1, sizeof(*fctx));
805 fctx->fid = options.num_remote_forwards - 1;
806 client_register_global_confirm(mux_confirm_remote_forward,
809 c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
810 /* delayed reply in mux_confirm_remote_forward */
813 buffer_put_int(r, MUX_S_OK);
814 buffer_put_int(r, rid);
818 free(fwd.listen_host);
819 free(fwd.listen_path);
820 free(fwd.connect_host);
821 free(fwd.connect_path);
827 process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
829 struct Forward fwd, *found_fwd;
830 char *fwd_desc = NULL;
831 const char *error_reason = NULL;
832 char *listen_addr = NULL, *connect_addr = NULL;
837 memset(&fwd, 0, sizeof(fwd));
839 if (buffer_get_int_ret(&ftype, m) != 0 ||
840 (listen_addr = buffer_get_string_ret(m, NULL)) == NULL ||
841 buffer_get_int_ret(&lport, m) != 0 ||
842 (connect_addr = buffer_get_string_ret(m, NULL)) == NULL ||
843 buffer_get_int_ret(&cport, m) != 0 ||
844 (lport != (u_int)PORT_STREAMLOCAL && lport > 65535) ||
845 (cport != (u_int)PORT_STREAMLOCAL && cport > 65535)) {
846 error("%s: malformed message", __func__);
851 if (*listen_addr == '\0') {
855 if (*connect_addr == '\0') {
860 memset(&fwd, 0, sizeof(fwd));
861 fwd.listen_port = lport;
862 if (fwd.listen_port == PORT_STREAMLOCAL)
863 fwd.listen_path = listen_addr;
865 fwd.listen_host = listen_addr;
866 fwd.connect_port = cport;
867 if (fwd.connect_port == PORT_STREAMLOCAL)
868 fwd.connect_path = connect_addr;
870 fwd.connect_host = connect_addr;
872 debug2("%s: channel %d: request cancel %s", __func__, c->self,
873 (fwd_desc = format_forward(ftype, &fwd)));
875 /* make sure this has been requested */
879 case MUX_FWD_DYNAMIC:
880 for (i = 0; i < options.num_local_forwards; i++) {
881 if (compare_forward(&fwd,
882 options.local_forwards + i)) {
883 found_fwd = options.local_forwards + i;
889 for (i = 0; i < options.num_remote_forwards; i++) {
890 if (compare_forward(&fwd,
891 options.remote_forwards + i)) {
892 found_fwd = options.remote_forwards + i;
899 if (found_fwd == NULL)
900 error_reason = "port not forwarded";
901 else if (ftype == MUX_FWD_REMOTE) {
903 * This shouldn't fail unless we confused the host/port
904 * between options.remote_forwards and permitted_opens.
905 * However, for dynamic allocated listen ports we need
906 * to use the actual listen port.
908 if (channel_request_rforward_cancel(found_fwd) == -1)
909 error_reason = "port not in permitted opens";
910 } else { /* local and dynamic forwards */
912 if (channel_cancel_lport_listener(&fwd, fwd.connect_port,
913 &options.fwd_opts) == -1)
914 error_reason = "port not found";
917 if (error_reason == NULL) {
918 buffer_put_int(r, MUX_S_OK);
919 buffer_put_int(r, rid);
921 free(found_fwd->listen_host);
922 free(found_fwd->listen_path);
923 free(found_fwd->connect_host);
924 free(found_fwd->connect_path);
925 found_fwd->listen_host = found_fwd->connect_host = NULL;
926 found_fwd->listen_path = found_fwd->connect_path = NULL;
927 found_fwd->listen_port = found_fwd->connect_port = 0;
929 buffer_put_int(r, MUX_S_FAILURE);
930 buffer_put_int(r, rid);
931 buffer_put_cstring(r, error_reason);
942 process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
945 char *reserved, *chost;
948 struct mux_stdio_confirm_ctx *cctx;
950 chost = reserved = NULL;
951 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
952 (chost = buffer_get_string_ret(m, NULL)) == NULL ||
953 buffer_get_int_ret(&cport, m) != 0) {
956 error("%s: malformed message", __func__);
961 debug2("%s: channel %d: request stdio fwd to %s:%u",
962 __func__, c->self, chost, cport);
964 /* Gather fds from client */
965 for(i = 0; i < 2; i++) {
966 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
967 error("%s: failed to receive fd %d from slave",
969 for (j = 0; j < i; j++)
974 buffer_put_int(r, MUX_S_FAILURE);
975 buffer_put_int(r, rid);
976 buffer_put_cstring(r,
977 "did not receive file descriptors");
982 debug3("%s: got fds stdin %d, stdout %d", __func__,
983 new_fd[0], new_fd[1]);
985 /* XXX support multiple child sessions in future */
986 if (c->remote_id != -1) {
987 debug2("%s: session already open", __func__);
989 buffer_put_int(r, MUX_S_FAILURE);
990 buffer_put_int(r, rid);
991 buffer_put_cstring(r, "Multiple sessions not supported");
999 if (options.control_master == SSHCTL_MASTER_ASK ||
1000 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
1001 if (!ask_permission("Allow forward to %s:%u? ",
1003 debug2("%s: stdio fwd refused by user", __func__);
1005 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
1006 buffer_put_int(r, rid);
1007 buffer_put_cstring(r, "Permission denied");
1012 /* enable nonblocking unless tty */
1013 if (!isatty(new_fd[0]))
1014 set_nonblock(new_fd[0]);
1015 if (!isatty(new_fd[1]))
1016 set_nonblock(new_fd[1]);
1018 nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
1020 nc->ctl_chan = c->self; /* link session -> control channel */
1021 c->remote_id = nc->self; /* link control -> session channel */
1023 debug2("%s: channel_new: %d linked to control channel %d",
1024 __func__, nc->self, nc->ctl_chan);
1026 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
1028 cctx = xcalloc(1, sizeof(*cctx));
1030 channel_register_open_confirm(nc->self, mux_stdio_confirm, cctx);
1031 c->mux_pause = 1; /* stop handling messages until open_confirm done */
1033 /* reply is deferred, sent by mux_session_confirm */
1037 /* Callback on open confirmation in mux master for a mux stdio fwd session. */
1039 mux_stdio_confirm(int id, int success, void *arg)
1041 struct mux_stdio_confirm_ctx *cctx = arg;
1046 fatal("%s: cctx == NULL", __func__);
1047 if ((c = channel_by_id(id)) == NULL)
1048 fatal("%s: no channel for id %d", __func__, id);
1049 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1050 fatal("%s: channel %d lacks control channel %d", __func__,
1054 debug3("%s: sending failure reply", __func__);
1056 buffer_init(&reply);
1057 buffer_put_int(&reply, MUX_S_FAILURE);
1058 buffer_put_int(&reply, cctx->rid);
1059 buffer_put_cstring(&reply, "Session open refused by peer");
1063 debug3("%s: sending success reply", __func__);
1065 buffer_init(&reply);
1066 buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1067 buffer_put_int(&reply, cctx->rid);
1068 buffer_put_int(&reply, c->self);
1072 buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1073 buffer_free(&reply);
1075 if (cc->mux_pause <= 0)
1076 fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1077 cc->mux_pause = 0; /* start processing messages again */
1078 c->open_confirm_ctx = NULL;
1083 process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
1085 debug("%s: channel %d: stop listening", __func__, c->self);
1087 if (options.control_master == SSHCTL_MASTER_ASK ||
1088 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
1089 if (!ask_permission("Disable further multiplexing on shared "
1090 "connection to %s? ", host)) {
1091 debug2("%s: stop listen refused by user", __func__);
1092 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
1093 buffer_put_int(r, rid);
1094 buffer_put_cstring(r, "Permission denied");
1099 if (mux_listener_channel != NULL) {
1100 channel_free(mux_listener_channel);
1102 free(options.control_path);
1103 options.control_path = NULL;
1104 mux_listener_channel = NULL;
1105 muxserver_sock = -1;
1109 buffer_put_int(r, MUX_S_OK);
1110 buffer_put_int(r, rid);
1115 /* Channel callbacks fired on read/write from mux slave fd */
1117 mux_master_read_cb(Channel *c)
1119 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
1122 u_int type, rid, have, i;
1126 if (c->mux_ctx == NULL) {
1127 state = xcalloc(1, sizeof(*state));
1129 channel_register_cleanup(c->self,
1130 mux_master_control_cleanup_cb, 0);
1134 buffer_put_int(&out, MUX_MSG_HELLO);
1135 buffer_put_int(&out, SSHMUX_VER);
1137 buffer_put_string(&c->output, buffer_ptr(&out),
1140 debug3("%s: channel %d: hello sent", __func__, c->self);
1147 /* Channel code ensures that we receive whole packets */
1148 if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
1150 error("%s: malformed message", __func__);
1153 buffer_append(&in, ptr, have);
1155 if (buffer_get_int_ret(&type, &in) != 0)
1157 debug3("%s: channel %d packet type 0x%08x len %u",
1158 __func__, c->self, type, buffer_len(&in));
1160 if (type == MUX_MSG_HELLO)
1163 if (!state->hello_rcvd) {
1164 error("%s: expected MUX_MSG_HELLO(0x%08x), "
1165 "received 0x%08x", __func__, MUX_MSG_HELLO, type);
1168 if (buffer_get_int_ret(&rid, &in) != 0)
1172 for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
1173 if (type == mux_master_handlers[i].type) {
1174 ret = mux_master_handlers[i].handler(rid, c, &in, &out);
1178 if (mux_master_handlers[i].handler == NULL) {
1179 error("%s: unsupported mux message 0x%08x", __func__, type);
1180 buffer_put_int(&out, MUX_S_FAILURE);
1181 buffer_put_int(&out, rid);
1182 buffer_put_cstring(&out, "unsupported request");
1185 /* Enqueue reply packet */
1186 if (buffer_len(&out) != 0) {
1187 buffer_put_string(&c->output, buffer_ptr(&out),
1197 mux_exit_message(Channel *c, int exitval)
1202 debug3("%s: channel %d: exit message, exitval %d", __func__, c->self,
1205 if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1206 fatal("%s: channel %d missing mux channel %d",
1207 __func__, c->self, c->ctl_chan);
1209 /* Append exit message packet to control socket output queue */
1211 buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
1212 buffer_put_int(&m, c->self);
1213 buffer_put_int(&m, exitval);
1215 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1220 mux_tty_alloc_failed(Channel *c)
1225 debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
1227 if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1228 fatal("%s: channel %d missing mux channel %d",
1229 __func__, c->self, c->ctl_chan);
1231 /* Append exit message packet to control socket output queue */
1233 buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
1234 buffer_put_int(&m, c->self);
1236 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1240 /* Prepare a mux master to listen on a Unix domain socket. */
1242 muxserver_listen(void)
1245 char *orig_control_path = options.control_path;
1250 if (options.control_path == NULL ||
1251 options.control_master == SSHCTL_MASTER_NO)
1254 debug("setting up multiplex master socket");
1257 * Use a temporary path before listen so we can pseudo-atomically
1258 * establish the listening socket in its final location to avoid
1259 * other processes racing in between bind() and listen() and hitting
1260 * an unready socket.
1262 for (i = 0; i < sizeof(rbuf) - 1; i++) {
1263 r = arc4random_uniform(26+26+10);
1264 rbuf[i] = (r < 26) ? 'a' + r :
1265 (r < 26*2) ? 'A' + r - 26 :
1268 rbuf[sizeof(rbuf) - 1] = '\0';
1269 options.control_path = NULL;
1270 xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
1271 debug3("%s: temporary control path %s", __func__, options.control_path);
1273 old_umask = umask(0177);
1274 muxserver_sock = unix_listener(options.control_path, 64, 0);
1277 if (muxserver_sock < 0) {
1278 if (oerrno == EINVAL || oerrno == EADDRINUSE) {
1279 error("ControlSocket %s already exists, "
1280 "disabling multiplexing", options.control_path);
1282 if (muxserver_sock != -1) {
1283 close(muxserver_sock);
1284 muxserver_sock = -1;
1286 free(orig_control_path);
1287 free(options.control_path);
1288 options.control_path = NULL;
1289 options.control_master = SSHCTL_MASTER_NO;
1292 /* unix_listener() logs the error */
1297 /* Now atomically "move" the mux socket into position */
1298 if (link(options.control_path, orig_control_path) != 0) {
1299 if (errno != EEXIST) {
1300 fatal("%s: link mux listener %s => %s: %s", __func__,
1301 options.control_path, orig_control_path,
1304 error("ControlSocket %s already exists, disabling multiplexing",
1306 unlink(options.control_path);
1307 goto disable_mux_master;
1309 unlink(options.control_path);
1310 free(options.control_path);
1311 options.control_path = orig_control_path;
1313 set_nonblock(muxserver_sock);
1315 mux_listener_channel = channel_new("mux listener",
1316 SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
1317 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1318 0, options.control_path, 1);
1319 mux_listener_channel->mux_rcb = mux_master_read_cb;
1320 debug3("%s: mux listener channel %d fd %d", __func__,
1321 mux_listener_channel->self, mux_listener_channel->sock);
1324 /* Callback on open confirmation in mux master for a mux client session. */
1326 mux_session_confirm(int id, int success, void *arg)
1328 struct mux_session_confirm_ctx *cctx = arg;
1329 const char *display;
1335 fatal("%s: cctx == NULL", __func__);
1336 if ((c = channel_by_id(id)) == NULL)
1337 fatal("%s: no channel for id %d", __func__, id);
1338 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1339 fatal("%s: channel %d lacks control channel %d", __func__,
1343 debug3("%s: sending failure reply", __func__);
1345 buffer_init(&reply);
1346 buffer_put_int(&reply, MUX_S_FAILURE);
1347 buffer_put_int(&reply, cctx->rid);
1348 buffer_put_cstring(&reply, "Session open refused by peer");
1352 display = getenv("DISPLAY");
1353 if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1356 /* Get reasonable local authentication information. */
1357 client_x11_get_proto(display, options.xauth_location,
1358 options.forward_x11_trusted, options.forward_x11_timeout,
1360 /* Request forwarding with authentication spoofing. */
1361 debug("Requesting X11 forwarding with authentication "
1363 x11_request_forwarding_with_spoofing(id, display, proto,
1365 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1366 /* XXX exit_on_forward_failure */
1369 if (cctx->want_agent_fwd && options.forward_agent) {
1370 debug("Requesting authentication agent forwarding.");
1371 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1375 client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1376 cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1378 debug3("%s: sending success reply", __func__);
1380 buffer_init(&reply);
1381 buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1382 buffer_put_int(&reply, cctx->rid);
1383 buffer_put_int(&reply, c->self);
1387 buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1388 buffer_free(&reply);
1390 if (cc->mux_pause <= 0)
1391 fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1392 cc->mux_pause = 0; /* start processing messages again */
1393 c->open_confirm_ctx = NULL;
1394 buffer_free(&cctx->cmd);
1396 if (cctx->env != NULL) {
1397 for (i = 0; cctx->env[i] != NULL; i++)
1404 /* ** Multiplexing client support */
1406 /* Exit signal handler */
1408 control_client_sighandler(int signo)
1410 muxclient_terminate = signo;
1414 * Relay signal handler - used to pass some signals from mux client to
1418 control_client_sigrelay(int signo)
1420 int save_errno = errno;
1422 if (muxserver_pid > 1)
1423 kill(muxserver_pid, signo);
1429 mux_client_read(int fd, Buffer *b, u_int need)
1437 pfd.events = POLLIN;
1438 p = buffer_append_space(b, need);
1439 for (have = 0; have < need; ) {
1440 if (muxclient_terminate) {
1444 len = read(fd, p + have, need - have);
1447 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1451 (void)poll(&pfd, 1, -1);
1469 mux_client_write_packet(int fd, Buffer *m)
1478 pfd.events = POLLOUT;
1479 buffer_init(&queue);
1480 buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1482 need = buffer_len(&queue);
1483 ptr = buffer_ptr(&queue);
1485 for (have = 0; have < need; ) {
1486 if (muxclient_terminate) {
1487 buffer_free(&queue);
1491 len = write(fd, ptr + have, need - have);
1494 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1498 (void)poll(&pfd, 1, -1);
1504 buffer_free(&queue);
1510 buffer_free(&queue);
1516 buffer_free(&queue);
1521 mux_client_read_packet(int fd, Buffer *m)
1528 buffer_init(&queue);
1529 if (mux_client_read(fd, &queue, 4) != 0) {
1530 if ((oerrno = errno) == EPIPE)
1531 debug3("%s: read header failed: %s", __func__,
1533 buffer_free(&queue);
1537 need = get_u32(buffer_ptr(&queue));
1538 if (mux_client_read(fd, &queue, need) != 0) {
1540 debug3("%s: read body failed: %s", __func__, strerror(errno));
1541 buffer_free(&queue);
1545 ptr = buffer_get_string_ptr(&queue, &have);
1546 buffer_append(m, ptr, have);
1547 buffer_free(&queue);
1552 mux_client_hello_exchange(int fd)
1558 buffer_put_int(&m, MUX_MSG_HELLO);
1559 buffer_put_int(&m, SSHMUX_VER);
1562 if (mux_client_write_packet(fd, &m) != 0)
1563 fatal("%s: write packet: %s", __func__, strerror(errno));
1567 /* Read their HELLO */
1568 if (mux_client_read_packet(fd, &m) != 0) {
1573 type = buffer_get_int(&m);
1574 if (type != MUX_MSG_HELLO)
1575 fatal("%s: expected HELLO (%u) received %u",
1576 __func__, MUX_MSG_HELLO, type);
1577 ver = buffer_get_int(&m);
1578 if (ver != SSHMUX_VER)
1579 fatal("Unsupported multiplexing protocol version %d "
1580 "(expected %d)", ver, SSHMUX_VER);
1581 debug2("%s: master version %u", __func__, ver);
1582 /* No extensions are presently defined */
1583 while (buffer_len(&m) > 0) {
1584 char *name = buffer_get_string(&m, NULL);
1585 char *value = buffer_get_string(&m, NULL);
1587 debug2("Unrecognised master extension \"%s\"", name);
1596 mux_client_request_alive(int fd)
1600 u_int pid, type, rid;
1602 debug3("%s: entering", __func__);
1605 buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1606 buffer_put_int(&m, muxclient_request_id);
1608 if (mux_client_write_packet(fd, &m) != 0)
1609 fatal("%s: write packet: %s", __func__, strerror(errno));
1613 /* Read their reply */
1614 if (mux_client_read_packet(fd, &m) != 0) {
1619 type = buffer_get_int(&m);
1620 if (type != MUX_S_ALIVE) {
1621 e = buffer_get_string(&m, NULL);
1622 fatal("%s: master returned error: %s", __func__, e);
1625 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1626 fatal("%s: out of sequence reply: my id %u theirs %u",
1627 __func__, muxclient_request_id, rid);
1628 pid = buffer_get_int(&m);
1631 debug3("%s: done pid = %u", __func__, pid);
1633 muxclient_request_id++;
1639 mux_client_request_terminate(int fd)
1645 debug3("%s: entering", __func__);
1648 buffer_put_int(&m, MUX_C_TERMINATE);
1649 buffer_put_int(&m, muxclient_request_id);
1651 if (mux_client_write_packet(fd, &m) != 0)
1652 fatal("%s: write packet: %s", __func__, strerror(errno));
1656 /* Read their reply */
1657 if (mux_client_read_packet(fd, &m) != 0) {
1658 /* Remote end exited already */
1659 if (errno == EPIPE) {
1663 fatal("%s: read from master failed: %s",
1664 __func__, strerror(errno));
1667 type = buffer_get_int(&m);
1668 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1669 fatal("%s: out of sequence reply: my id %u theirs %u",
1670 __func__, muxclient_request_id, rid);
1674 case MUX_S_PERMISSION_DENIED:
1675 e = buffer_get_string(&m, NULL);
1676 fatal("Master refused termination request: %s", e);
1678 e = buffer_get_string(&m, NULL);
1679 fatal("%s: termination request failed: %s", __func__, e);
1681 fatal("%s: unexpected response from master 0x%08x",
1685 muxclient_request_id++;
1689 mux_client_forward(int fd, int cancel_flag, u_int ftype, struct Forward *fwd)
1695 fwd_desc = format_forward(ftype, fwd);
1696 debug("Requesting %s %s",
1697 cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
1701 buffer_put_int(&m, cancel_flag ? MUX_C_CLOSE_FWD : MUX_C_OPEN_FWD);
1702 buffer_put_int(&m, muxclient_request_id);
1703 buffer_put_int(&m, ftype);
1704 if (fwd->listen_path != NULL) {
1705 buffer_put_cstring(&m, fwd->listen_path);
1707 buffer_put_cstring(&m,
1708 fwd->listen_host == NULL ? "" :
1709 (*fwd->listen_host == '\0' ? "*" : fwd->listen_host));
1711 buffer_put_int(&m, fwd->listen_port);
1712 if (fwd->connect_path != NULL) {
1713 buffer_put_cstring(&m, fwd->connect_path);
1715 buffer_put_cstring(&m,
1716 fwd->connect_host == NULL ? "" : fwd->connect_host);
1718 buffer_put_int(&m, fwd->connect_port);
1720 if (mux_client_write_packet(fd, &m) != 0)
1721 fatal("%s: write packet: %s", __func__, strerror(errno));
1725 /* Read their reply */
1726 if (mux_client_read_packet(fd, &m) != 0) {
1731 type = buffer_get_int(&m);
1732 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1733 fatal("%s: out of sequence reply: my id %u theirs %u",
1734 __func__, muxclient_request_id, rid);
1738 case MUX_S_REMOTE_PORT:
1740 fatal("%s: got MUX_S_REMOTE_PORT for cancel", __func__);
1741 fwd->allocated_port = buffer_get_int(&m);
1742 verbose("Allocated port %u for remote forward to %s:%d",
1743 fwd->allocated_port,
1744 fwd->connect_host ? fwd->connect_host : "",
1746 if (muxclient_command == SSHMUX_COMMAND_FORWARD)
1747 fprintf(stdout, "%u\n", fwd->allocated_port);
1749 case MUX_S_PERMISSION_DENIED:
1750 e = buffer_get_string(&m, NULL);
1752 error("Master refused forwarding request: %s", e);
1755 e = buffer_get_string(&m, NULL);
1757 error("%s: forwarding request failed: %s", __func__, e);
1760 fatal("%s: unexpected response from master 0x%08x",
1765 muxclient_request_id++;
1770 mux_client_forwards(int fd, int cancel_flag)
1774 debug3("%s: %s forwardings: %d local, %d remote", __func__,
1775 cancel_flag ? "cancel" : "request",
1776 options.num_local_forwards, options.num_remote_forwards);
1778 /* XXX ExitOnForwardingFailure */
1779 for (i = 0; i < options.num_local_forwards; i++) {
1780 if (mux_client_forward(fd, cancel_flag,
1781 options.local_forwards[i].connect_port == 0 ?
1782 MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1783 options.local_forwards + i) != 0)
1786 for (i = 0; i < options.num_remote_forwards; i++) {
1787 if (mux_client_forward(fd, cancel_flag, MUX_FWD_REMOTE,
1788 options.remote_forwards + i) != 0)
1795 mux_client_request_session(int fd)
1799 u_int i, rid, sid, esid, exitval, type, exitval_seen;
1800 extern char **environ;
1801 int devnull, rawmode;
1803 debug3("%s: entering", __func__);
1805 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1806 error("%s: master alive request failed", __func__);
1810 signal(SIGPIPE, SIG_IGN);
1812 if (stdin_null_flag) {
1813 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1814 fatal("open(/dev/null): %s", strerror(errno));
1815 if (dup2(devnull, STDIN_FILENO) == -1)
1816 fatal("dup2: %s", strerror(errno));
1817 if (devnull > STDERR_FILENO)
1821 term = getenv("TERM");
1824 buffer_put_int(&m, MUX_C_NEW_SESSION);
1825 buffer_put_int(&m, muxclient_request_id);
1826 buffer_put_cstring(&m, ""); /* reserved */
1827 buffer_put_int(&m, tty_flag);
1828 buffer_put_int(&m, options.forward_x11);
1829 buffer_put_int(&m, options.forward_agent);
1830 buffer_put_int(&m, subsystem_flag);
1831 buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1832 0xffffffff : (u_int)options.escape_char);
1833 buffer_put_cstring(&m, term == NULL ? "" : term);
1834 buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1836 if (options.num_send_env > 0 && environ != NULL) {
1837 /* Pass environment */
1838 for (i = 0; environ[i] != NULL; i++) {
1839 if (env_permitted(environ[i])) {
1840 buffer_put_cstring(&m, environ[i]);
1845 if (mux_client_write_packet(fd, &m) != 0)
1846 fatal("%s: write packet: %s", __func__, strerror(errno));
1848 /* Send the stdio file descriptors */
1849 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1850 mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1851 mm_send_fd(fd, STDERR_FILENO) == -1)
1852 fatal("%s: send fds failed", __func__);
1854 debug3("%s: session request sent", __func__);
1856 /* Read their reply */
1858 if (mux_client_read_packet(fd, &m) != 0) {
1859 error("%s: read from master failed: %s",
1860 __func__, strerror(errno));
1865 type = buffer_get_int(&m);
1866 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1867 fatal("%s: out of sequence reply: my id %u theirs %u",
1868 __func__, muxclient_request_id, rid);
1870 case MUX_S_SESSION_OPENED:
1871 sid = buffer_get_int(&m);
1872 debug("%s: master session id: %u", __func__, sid);
1874 case MUX_S_PERMISSION_DENIED:
1875 e = buffer_get_string(&m, NULL);
1877 error("Master refused session request: %s", e);
1880 e = buffer_get_string(&m, NULL);
1882 error("%s: session request failed: %s", __func__, e);
1886 error("%s: unexpected response from master 0x%08x",
1890 muxclient_request_id++;
1892 signal(SIGHUP, control_client_sighandler);
1893 signal(SIGINT, control_client_sighandler);
1894 signal(SIGTERM, control_client_sighandler);
1895 signal(SIGWINCH, control_client_sigrelay);
1899 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1902 * Stick around until the controlee closes the client_fd.
1903 * Before it does, it is expected to write an exit message.
1904 * This process must read the value and wait for the closure of
1905 * the client_fd; if this one closes early, the multiplex master will
1906 * terminate early too (possibly losing data).
1908 for (exitval = 255, exitval_seen = 0;;) {
1910 if (mux_client_read_packet(fd, &m) != 0)
1912 type = buffer_get_int(&m);
1914 case MUX_S_TTY_ALLOC_FAIL:
1915 if ((esid = buffer_get_int(&m)) != sid)
1916 fatal("%s: tty alloc fail on unknown session: "
1917 "my id %u theirs %u",
1918 __func__, sid, esid);
1919 leave_raw_mode(options.request_tty ==
1923 case MUX_S_EXIT_MESSAGE:
1924 if ((esid = buffer_get_int(&m)) != sid)
1925 fatal("%s: exit on unknown session: "
1926 "my id %u theirs %u",
1927 __func__, sid, esid);
1929 fatal("%s: exitval sent twice", __func__);
1930 exitval = buffer_get_int(&m);
1934 e = buffer_get_string(&m, NULL);
1935 fatal("%s: master returned error: %s", __func__, e);
1941 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1943 if (muxclient_terminate) {
1944 debug2("Exiting on signal %d", muxclient_terminate);
1946 } else if (!exitval_seen) {
1947 debug2("Control master terminated unexpectedly");
1950 debug2("Received exit status from master %d", exitval);
1952 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1953 fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1959 mux_client_request_stdio_fwd(int fd)
1963 u_int type, rid, sid;
1966 debug3("%s: entering", __func__);
1968 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1969 error("%s: master alive request failed", __func__);
1973 signal(SIGPIPE, SIG_IGN);
1975 if (stdin_null_flag) {
1976 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1977 fatal("open(/dev/null): %s", strerror(errno));
1978 if (dup2(devnull, STDIN_FILENO) == -1)
1979 fatal("dup2: %s", strerror(errno));
1980 if (devnull > STDERR_FILENO)
1985 buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
1986 buffer_put_int(&m, muxclient_request_id);
1987 buffer_put_cstring(&m, ""); /* reserved */
1988 buffer_put_cstring(&m, stdio_forward_host);
1989 buffer_put_int(&m, stdio_forward_port);
1991 if (mux_client_write_packet(fd, &m) != 0)
1992 fatal("%s: write packet: %s", __func__, strerror(errno));
1994 /* Send the stdio file descriptors */
1995 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1996 mm_send_fd(fd, STDOUT_FILENO) == -1)
1997 fatal("%s: send fds failed", __func__);
1999 debug3("%s: stdio forward request sent", __func__);
2001 /* Read their reply */
2004 if (mux_client_read_packet(fd, &m) != 0) {
2005 error("%s: read from master failed: %s",
2006 __func__, strerror(errno));
2011 type = buffer_get_int(&m);
2012 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
2013 fatal("%s: out of sequence reply: my id %u theirs %u",
2014 __func__, muxclient_request_id, rid);
2016 case MUX_S_SESSION_OPENED:
2017 sid = buffer_get_int(&m);
2018 debug("%s: master session id: %u", __func__, sid);
2020 case MUX_S_PERMISSION_DENIED:
2021 e = buffer_get_string(&m, NULL);
2023 fatal("Master refused stdio forwarding request: %s", e);
2025 e = buffer_get_string(&m, NULL);
2027 fatal("Stdio forwarding request failed: %s", e);
2030 error("%s: unexpected response from master 0x%08x",
2034 muxclient_request_id++;
2036 signal(SIGHUP, control_client_sighandler);
2037 signal(SIGINT, control_client_sighandler);
2038 signal(SIGTERM, control_client_sighandler);
2039 signal(SIGWINCH, control_client_sigrelay);
2042 * Stick around until the controlee closes the client_fd.
2045 if (mux_client_read_packet(fd, &m) != 0) {
2046 if (errno == EPIPE ||
2047 (errno == EINTR && muxclient_terminate != 0))
2049 fatal("%s: mux_client_read_packet: %s",
2050 __func__, strerror(errno));
2052 fatal("%s: master returned unexpected message %u", __func__, type);
2056 mux_client_request_stop_listening(int fd)
2062 debug3("%s: entering", __func__);
2065 buffer_put_int(&m, MUX_C_STOP_LISTENING);
2066 buffer_put_int(&m, muxclient_request_id);
2068 if (mux_client_write_packet(fd, &m) != 0)
2069 fatal("%s: write packet: %s", __func__, strerror(errno));
2073 /* Read their reply */
2074 if (mux_client_read_packet(fd, &m) != 0)
2075 fatal("%s: read from master failed: %s",
2076 __func__, strerror(errno));
2078 type = buffer_get_int(&m);
2079 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
2080 fatal("%s: out of sequence reply: my id %u theirs %u",
2081 __func__, muxclient_request_id, rid);
2085 case MUX_S_PERMISSION_DENIED:
2086 e = buffer_get_string(&m, NULL);
2087 fatal("Master refused stop listening request: %s", e);
2089 e = buffer_get_string(&m, NULL);
2090 fatal("%s: stop listening request failed: %s", __func__, e);
2092 fatal("%s: unexpected response from master 0x%08x",
2096 muxclient_request_id++;
2099 /* Multiplex client main loop. */
2101 muxclient(const char *path)
2103 struct sockaddr_un addr;
2108 if (muxclient_command == 0) {
2109 if (stdio_forward_host != NULL)
2110 muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
2112 muxclient_command = SSHMUX_COMMAND_OPEN;
2115 switch (options.control_master) {
2116 case SSHCTL_MASTER_AUTO:
2117 case SSHCTL_MASTER_AUTO_ASK:
2118 debug("auto-mux: Trying existing master");
2120 case SSHCTL_MASTER_NO:
2126 memset(&addr, '\0', sizeof(addr));
2127 addr.sun_family = AF_UNIX;
2128 sun_len = offsetof(struct sockaddr_un, sun_path) +
2131 if (strlcpy(addr.sun_path, path,
2132 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
2133 fatal("ControlPath too long");
2135 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
2136 fatal("%s socket(): %s", __func__, strerror(errno));
2138 if (connect(sock, (struct sockaddr *)&addr, sun_len) == -1) {
2139 switch (muxclient_command) {
2140 case SSHMUX_COMMAND_OPEN:
2141 case SSHMUX_COMMAND_STDIO_FWD:
2144 fatal("Control socket connect(%.100s): %s", path,
2147 if (errno == ECONNREFUSED &&
2148 options.control_master != SSHCTL_MASTER_NO) {
2149 debug("Stale control socket %.100s, unlinking", path);
2151 } else if (errno == ENOENT) {
2152 debug("Control socket \"%.100s\" does not exist", path);
2154 error("Control socket connect(%.100s): %s", path,
2162 if (mux_client_hello_exchange(sock) != 0) {
2163 error("%s: master hello exchange failed", __func__);
2168 switch (muxclient_command) {
2169 case SSHMUX_COMMAND_ALIVE_CHECK:
2170 if ((pid = mux_client_request_alive(sock)) == 0)
2171 fatal("%s: master alive check failed", __func__);
2172 fprintf(stderr, "Master running (pid=%d)\r\n", pid);
2174 case SSHMUX_COMMAND_TERMINATE:
2175 mux_client_request_terminate(sock);
2176 fprintf(stderr, "Exit request sent.\r\n");
2178 case SSHMUX_COMMAND_FORWARD:
2179 if (mux_client_forwards(sock, 0) != 0)
2180 fatal("%s: master forward request failed", __func__);
2182 case SSHMUX_COMMAND_OPEN:
2183 if (mux_client_forwards(sock, 0) != 0) {
2184 error("%s: master forward request failed", __func__);
2187 mux_client_request_session(sock);
2189 case SSHMUX_COMMAND_STDIO_FWD:
2190 mux_client_request_stdio_fwd(sock);
2192 case SSHMUX_COMMAND_STOP:
2193 mux_client_request_stop_listening(sock);
2194 fprintf(stderr, "Stop listening request sent.\r\n");
2196 case SSHMUX_COMMAND_CANCEL_FWD:
2197 if (mux_client_forwards(sock, 1) != 0)
2198 error("%s: master cancel forward request failed",
2202 fatal("unrecognised muxclient_command %d", muxclient_command);