1 /* $OpenBSD: mux.c,v 1.38 2013/01/02 00:32:07 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>
66 #include "openbsd-compat/sys-queue.h"
71 #include "pathnames.h"
78 #include "monitor_fdpass.h"
82 #include "clientloop.h"
86 extern Options options;
87 extern int stdin_null_flag;
89 extern int subsystem_flag;
90 extern Buffer command;
91 extern volatile sig_atomic_t quit_pending;
92 extern char *stdio_forward_host;
93 extern int stdio_forward_port;
95 /* Context for session open confirmation callback */
96 struct mux_session_confirm_ctx {
100 u_int want_agent_fwd;
108 /* Context for global channel callback */
109 struct mux_channel_confirm_ctx {
110 u_int cid; /* channel id */
111 u_int rid; /* request id */
112 int fid; /* forward id */
115 /* fd to control socket */
116 int muxserver_sock = -1;
118 /* client request id */
119 u_int muxclient_request_id = 0;
121 /* Multiplexing control command */
122 u_int muxclient_command = 0;
124 /* Set when signalled. */
125 static volatile sig_atomic_t muxclient_terminate = 0;
127 /* PID of multiplex server */
128 static u_int muxserver_pid = 0;
130 static Channel *mux_listener_channel = NULL;
132 struct mux_master_state {
136 /* mux protocol messages */
137 #define MUX_MSG_HELLO 0x00000001
138 #define MUX_C_NEW_SESSION 0x10000002
139 #define MUX_C_ALIVE_CHECK 0x10000004
140 #define MUX_C_TERMINATE 0x10000005
141 #define MUX_C_OPEN_FWD 0x10000006
142 #define MUX_C_CLOSE_FWD 0x10000007
143 #define MUX_C_NEW_STDIO_FWD 0x10000008
144 #define MUX_C_STOP_LISTENING 0x10000009
145 #define MUX_S_OK 0x80000001
146 #define MUX_S_PERMISSION_DENIED 0x80000002
147 #define MUX_S_FAILURE 0x80000003
148 #define MUX_S_EXIT_MESSAGE 0x80000004
149 #define MUX_S_ALIVE 0x80000005
150 #define MUX_S_SESSION_OPENED 0x80000006
151 #define MUX_S_REMOTE_PORT 0x80000007
152 #define MUX_S_TTY_ALLOC_FAIL 0x80000008
154 /* type codes for MUX_C_OPEN_FWD and MUX_C_CLOSE_FWD */
155 #define MUX_FWD_LOCAL 1
156 #define MUX_FWD_REMOTE 2
157 #define MUX_FWD_DYNAMIC 3
159 static void mux_session_confirm(int, int, void *);
161 static int process_mux_master_hello(u_int, Channel *, Buffer *, Buffer *);
162 static int process_mux_new_session(u_int, Channel *, Buffer *, Buffer *);
163 static int process_mux_alive_check(u_int, Channel *, Buffer *, Buffer *);
164 static int process_mux_terminate(u_int, Channel *, Buffer *, Buffer *);
165 static int process_mux_open_fwd(u_int, Channel *, Buffer *, Buffer *);
166 static int process_mux_close_fwd(u_int, Channel *, Buffer *, Buffer *);
167 static int process_mux_stdio_fwd(u_int, Channel *, Buffer *, Buffer *);
168 static int process_mux_stop_listening(u_int, Channel *, Buffer *, Buffer *);
170 static const struct {
172 int (*handler)(u_int, Channel *, Buffer *, Buffer *);
173 } mux_master_handlers[] = {
174 { MUX_MSG_HELLO, process_mux_master_hello },
175 { MUX_C_NEW_SESSION, process_mux_new_session },
176 { MUX_C_ALIVE_CHECK, process_mux_alive_check },
177 { MUX_C_TERMINATE, process_mux_terminate },
178 { MUX_C_OPEN_FWD, process_mux_open_fwd },
179 { MUX_C_CLOSE_FWD, process_mux_close_fwd },
180 { MUX_C_NEW_STDIO_FWD, process_mux_stdio_fwd },
181 { MUX_C_STOP_LISTENING, process_mux_stop_listening },
185 /* Cleanup callback fired on closure of mux slave _session_ channel */
188 mux_master_session_cleanup_cb(int cid, void *unused)
190 Channel *cc, *c = channel_by_id(cid);
192 debug3("%s: entering for channel %d", __func__, cid);
194 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
195 if (c->ctl_chan != -1) {
196 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
197 fatal("%s: channel %d missing control channel %d",
198 __func__, c->self, c->ctl_chan);
201 chan_rcvd_oclose(cc);
203 channel_cancel_cleanup(c->self);
206 /* Cleanup callback fired on closure of mux slave _control_ channel */
209 mux_master_control_cleanup_cb(int cid, void *unused)
211 Channel *sc, *c = channel_by_id(cid);
213 debug3("%s: entering for channel %d", __func__, cid);
215 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
216 if (c->remote_id != -1) {
217 if ((sc = channel_by_id(c->remote_id)) == NULL)
218 fatal("%s: channel %d missing session channel %d",
219 __func__, c->self, c->remote_id);
222 if (sc->type != SSH_CHANNEL_OPEN) {
223 debug2("%s: channel %d: not open", __func__, sc->self);
226 if (sc->istate == CHAN_INPUT_OPEN)
227 chan_read_failed(sc);
228 if (sc->ostate == CHAN_OUTPUT_OPEN)
229 chan_write_failed(sc);
232 channel_cancel_cleanup(c->self);
235 /* Check mux client environment variables before passing them to mux master. */
237 env_permitted(char *env)
240 char name[1024], *cp;
242 if ((cp = strchr(env, '=')) == NULL || cp == env)
244 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
245 if (ret <= 0 || (size_t)ret >= sizeof(name)) {
246 error("env_permitted: name '%.100s...' too long", env);
250 for (i = 0; i < options.num_send_env; i++)
251 if (match_pattern(name, options.send_env[i]))
257 /* Mux master protocol message handlers */
260 process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
263 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
266 fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
267 if (state->hello_rcvd) {
268 error("%s: HELLO received twice", __func__);
271 if (buffer_get_int_ret(&ver, m) != 0) {
273 error("%s: malformed message", __func__);
276 if (ver != SSHMUX_VER) {
277 error("Unsupported multiplexing protocol version %d "
278 "(expected %d)", ver, SSHMUX_VER);
281 debug2("%s: channel %d slave version %u", __func__, c->self, ver);
283 /* No extensions are presently defined */
284 while (buffer_len(m) > 0) {
285 char *name = buffer_get_string_ret(m, NULL);
286 char *value = buffer_get_string_ret(m, NULL);
288 if (name == NULL || value == NULL) {
293 debug2("Unrecognised slave extension \"%s\"", name);
297 state->hello_rcvd = 1;
302 process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
305 struct mux_session_confirm_ctx *cctx;
306 char *reserved, *cmd, *cp;
307 u_int i, j, len, env_len, escape_char, window, packetmax;
310 /* Reply for SSHMUX_COMMAND_OPEN */
311 cctx = xcalloc(1, sizeof(*cctx));
314 cmd = reserved = NULL;
317 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
318 buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
319 buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
320 buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
321 buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
322 buffer_get_int_ret(&escape_char, m) != 0 ||
323 (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
324 (cmd = buffer_get_string_ret(m, &len)) == NULL) {
328 if (reserved != NULL)
330 for (j = 0; j < env_len; j++)
334 if (cctx->term != NULL)
337 error("%s: malformed message", __func__);
343 while (buffer_len(m) > 0) {
344 #define MUX_MAX_ENV_VARS 4096
345 if ((cp = buffer_get_string_ret(m, &len)) == NULL)
347 if (!env_permitted(cp)) {
351 cctx->env = xrealloc(cctx->env, env_len + 2,
353 cctx->env[env_len++] = cp;
354 cctx->env[env_len] = NULL;
355 if (env_len > MUX_MAX_ENV_VARS) {
356 error(">%d environment variables received, ignoring "
357 "additional", MUX_MAX_ENV_VARS);
362 debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
363 "term \"%s\", cmd \"%s\", env %u", __func__, c->self,
364 cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
365 cctx->want_subsys, cctx->term, cmd, env_len);
367 buffer_init(&cctx->cmd);
368 buffer_append(&cctx->cmd, cmd, strlen(cmd));
372 /* Gather fds from client */
373 for(i = 0; i < 3; i++) {
374 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
375 error("%s: failed to receive fd %d from slave",
377 for (j = 0; j < i; j++)
379 for (j = 0; j < env_len; j++)
384 buffer_free(&cctx->cmd);
388 buffer_put_int(r, MUX_S_FAILURE);
389 buffer_put_int(r, rid);
390 buffer_put_cstring(r,
391 "did not receive file descriptors");
396 debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
397 new_fd[0], new_fd[1], new_fd[2]);
399 /* XXX support multiple child sessions in future */
400 if (c->remote_id != -1) {
401 debug2("%s: session already open", __func__);
403 buffer_put_int(r, MUX_S_FAILURE);
404 buffer_put_int(r, rid);
405 buffer_put_cstring(r, "Multiple sessions not supported");
412 for (i = 0; i < env_len; i++)
416 buffer_free(&cctx->cmd);
421 if (options.control_master == SSHCTL_MASTER_ASK ||
422 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
423 if (!ask_permission("Allow shared connection to %s? ", host)) {
424 debug2("%s: session refused by user", __func__);
426 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
427 buffer_put_int(r, rid);
428 buffer_put_cstring(r, "Permission denied");
433 /* Try to pick up ttymodes from client before it goes raw */
434 if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
435 error("%s: tcgetattr: %s", __func__, strerror(errno));
437 /* enable nonblocking unless tty */
438 if (!isatty(new_fd[0]))
439 set_nonblock(new_fd[0]);
440 if (!isatty(new_fd[1]))
441 set_nonblock(new_fd[1]);
442 if (!isatty(new_fd[2]))
443 set_nonblock(new_fd[2]);
445 window = CHAN_SES_WINDOW_DEFAULT;
446 packetmax = CHAN_SES_PACKET_DEFAULT;
447 if (cctx->want_tty) {
452 nc = channel_new("session", SSH_CHANNEL_OPENING,
453 new_fd[0], new_fd[1], new_fd[2], window, packetmax,
454 CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
456 nc->ctl_chan = c->self; /* link session -> control channel */
457 c->remote_id = nc->self; /* link control -> session channel */
459 if (cctx->want_tty && escape_char != 0xffffffff) {
460 channel_register_filter(nc->self,
461 client_simple_escape_filter, NULL,
462 client_filter_cleanup,
463 client_new_escape_filter_ctx((int)escape_char));
466 debug2("%s: channel_new: %d linked to control channel %d",
467 __func__, nc->self, nc->ctl_chan);
469 channel_send_open(nc->self);
470 channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
471 c->mux_pause = 1; /* stop handling messages until open_confirm done */
472 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
474 /* reply is deferred, sent by mux_session_confirm */
479 process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
481 debug2("%s: channel %d: alive check", __func__, c->self);
484 buffer_put_int(r, MUX_S_ALIVE);
485 buffer_put_int(r, rid);
486 buffer_put_int(r, (u_int)getpid());
492 process_mux_terminate(u_int rid, Channel *c, Buffer *m, Buffer *r)
494 debug2("%s: channel %d: terminate request", __func__, c->self);
496 if (options.control_master == SSHCTL_MASTER_ASK ||
497 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
498 if (!ask_permission("Terminate shared connection to %s? ",
500 debug2("%s: termination refused by user", __func__);
501 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
502 buffer_put_int(r, rid);
503 buffer_put_cstring(r, "Permission denied");
509 buffer_put_int(r, MUX_S_OK);
510 buffer_put_int(r, rid);
511 /* XXX exit happens too soon - message never makes it to client */
516 format_forward(u_int ftype, Forward *fwd)
522 xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
523 (fwd->listen_host == NULL) ?
524 (options.gateway_ports ? "*" : "LOCALHOST") :
525 fwd->listen_host, fwd->listen_port,
526 fwd->connect_host, fwd->connect_port);
528 case MUX_FWD_DYNAMIC:
529 xasprintf(&ret, "dynamic forward %.200s:%d -> *",
530 (fwd->listen_host == NULL) ?
531 (options.gateway_ports ? "*" : "LOCALHOST") :
532 fwd->listen_host, fwd->listen_port);
535 xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
536 (fwd->listen_host == NULL) ?
537 "LOCALHOST" : fwd->listen_host,
539 fwd->connect_host, fwd->connect_port);
542 fatal("%s: unknown forward type %u", __func__, ftype);
548 compare_host(const char *a, const char *b)
550 if (a == NULL && b == NULL)
552 if (a == NULL || b == NULL)
554 return strcmp(a, b) == 0;
558 compare_forward(Forward *a, Forward *b)
560 if (!compare_host(a->listen_host, b->listen_host))
562 if (a->listen_port != b->listen_port)
564 if (!compare_host(a->connect_host, b->connect_host))
566 if (a->connect_port != b->connect_port)
573 mux_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
575 struct mux_channel_confirm_ctx *fctx = ctxt;
576 char *failmsg = NULL;
581 if ((c = channel_by_id(fctx->cid)) == NULL) {
582 /* no channel for reply */
583 error("%s: unknown channel", __func__);
587 if (fctx->fid >= options.num_remote_forwards) {
588 xasprintf(&failmsg, "unknown forwarding id %d", fctx->fid);
591 rfwd = &options.remote_forwards[fctx->fid];
592 debug("%s: %s for: listen %d, connect %s:%d", __func__,
593 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
594 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
595 if (type == SSH2_MSG_REQUEST_SUCCESS) {
596 if (rfwd->listen_port == 0) {
597 rfwd->allocated_port = packet_get_int();
598 logit("Allocated port %u for mux remote forward"
599 " to %s:%d", rfwd->allocated_port,
600 rfwd->connect_host, rfwd->connect_port);
601 buffer_put_int(&out, MUX_S_REMOTE_PORT);
602 buffer_put_int(&out, fctx->rid);
603 buffer_put_int(&out, rfwd->allocated_port);
604 channel_update_permitted_opens(rfwd->handle,
605 rfwd->allocated_port);
607 buffer_put_int(&out, MUX_S_OK);
608 buffer_put_int(&out, fctx->rid);
612 if (rfwd->listen_port == 0)
613 channel_update_permitted_opens(rfwd->handle, -1);
614 xasprintf(&failmsg, "remote port forwarding failed for "
615 "listen port %d", rfwd->listen_port);
618 error("%s: %s", __func__, failmsg);
619 buffer_put_int(&out, MUX_S_FAILURE);
620 buffer_put_int(&out, fctx->rid);
621 buffer_put_cstring(&out, failmsg);
624 buffer_put_string(&c->output, buffer_ptr(&out), buffer_len(&out));
626 if (c->mux_pause <= 0)
627 fatal("%s: mux_pause %d", __func__, c->mux_pause);
628 c->mux_pause = 0; /* start processing messages again */
632 process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
635 char *fwd_desc = NULL;
637 int i, ret = 0, freefwd = 1;
639 fwd.listen_host = fwd.connect_host = NULL;
640 if (buffer_get_int_ret(&ftype, m) != 0 ||
641 (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
642 buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
643 (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
644 buffer_get_int_ret(&fwd.connect_port, m) != 0) {
645 error("%s: malformed message", __func__);
650 if (*fwd.listen_host == '\0') {
651 xfree(fwd.listen_host);
652 fwd.listen_host = NULL;
654 if (*fwd.connect_host == '\0') {
655 xfree(fwd.connect_host);
656 fwd.connect_host = NULL;
659 debug2("%s: channel %d: request %s", __func__, c->self,
660 (fwd_desc = format_forward(ftype, &fwd)));
662 if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
663 ftype != MUX_FWD_DYNAMIC) {
664 logit("%s: invalid forwarding type %u", __func__, ftype);
667 xfree(fwd.listen_host);
668 if (fwd.connect_host)
669 xfree(fwd.connect_host);
670 buffer_put_int(r, MUX_S_FAILURE);
671 buffer_put_int(r, rid);
672 buffer_put_cstring(r, "Invalid forwarding request");
675 if (fwd.listen_port >= 65536) {
676 logit("%s: invalid listen port %u", __func__,
680 if (fwd.connect_port >= 65536 || (ftype != MUX_FWD_DYNAMIC &&
681 ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
682 logit("%s: invalid connect port %u", __func__,
686 if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL) {
687 logit("%s: missing connect host", __func__);
691 /* Skip forwards that have already been requested */
694 case MUX_FWD_DYNAMIC:
695 for (i = 0; i < options.num_local_forwards; i++) {
696 if (compare_forward(&fwd,
697 options.local_forwards + i)) {
699 debug2("%s: found existing forwarding",
701 buffer_put_int(r, MUX_S_OK);
702 buffer_put_int(r, rid);
708 for (i = 0; i < options.num_remote_forwards; i++) {
709 if (compare_forward(&fwd,
710 options.remote_forwards + i)) {
711 if (fwd.listen_port != 0)
713 debug2("%s: found allocated port",
715 buffer_put_int(r, MUX_S_REMOTE_PORT);
716 buffer_put_int(r, rid);
718 options.remote_forwards[i].allocated_port);
725 if (options.control_master == SSHCTL_MASTER_ASK ||
726 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
727 if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
728 debug2("%s: forwarding refused by user", __func__);
729 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
730 buffer_put_int(r, rid);
731 buffer_put_cstring(r, "Permission denied");
736 if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
737 if (!channel_setup_local_fwd_listener(fwd.listen_host,
738 fwd.listen_port, fwd.connect_host, fwd.connect_port,
739 options.gateway_ports)) {
741 logit("slave-requested %s failed", fwd_desc);
742 buffer_put_int(r, MUX_S_FAILURE);
743 buffer_put_int(r, rid);
744 buffer_put_cstring(r, "Port forwarding failed");
747 add_local_forward(&options, &fwd);
750 struct mux_channel_confirm_ctx *fctx;
752 fwd.handle = channel_request_remote_forwarding(fwd.listen_host,
753 fwd.listen_port, fwd.connect_host, fwd.connect_port);
756 add_remote_forward(&options, &fwd);
757 fctx = xcalloc(1, sizeof(*fctx));
760 fctx->fid = options.num_remote_forwards - 1;
761 client_register_global_confirm(mux_confirm_remote_forward,
764 c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
765 /* delayed reply in mux_confirm_remote_forward */
768 buffer_put_int(r, MUX_S_OK);
769 buffer_put_int(r, rid);
771 if (fwd_desc != NULL)
774 if (fwd.listen_host != NULL)
775 xfree(fwd.listen_host);
776 if (fwd.connect_host != NULL)
777 xfree(fwd.connect_host);
783 process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
785 Forward fwd, *found_fwd;
786 char *fwd_desc = NULL;
787 const char *error_reason = NULL;
789 int i, listen_port, ret = 0;
791 fwd.listen_host = fwd.connect_host = NULL;
792 if (buffer_get_int_ret(&ftype, m) != 0 ||
793 (fwd.listen_host = buffer_get_string_ret(m, NULL)) == NULL ||
794 buffer_get_int_ret(&fwd.listen_port, m) != 0 ||
795 (fwd.connect_host = buffer_get_string_ret(m, NULL)) == NULL ||
796 buffer_get_int_ret(&fwd.connect_port, m) != 0) {
797 error("%s: malformed message", __func__);
802 if (*fwd.listen_host == '\0') {
803 xfree(fwd.listen_host);
804 fwd.listen_host = NULL;
806 if (*fwd.connect_host == '\0') {
807 xfree(fwd.connect_host);
808 fwd.connect_host = NULL;
811 debug2("%s: channel %d: request cancel %s", __func__, c->self,
812 (fwd_desc = format_forward(ftype, &fwd)));
814 /* make sure this has been requested */
818 case MUX_FWD_DYNAMIC:
819 for (i = 0; i < options.num_local_forwards; i++) {
820 if (compare_forward(&fwd,
821 options.local_forwards + i)) {
822 found_fwd = options.local_forwards + i;
828 for (i = 0; i < options.num_remote_forwards; i++) {
829 if (compare_forward(&fwd,
830 options.remote_forwards + i)) {
831 found_fwd = options.remote_forwards + i;
838 if (found_fwd == NULL)
839 error_reason = "port not forwarded";
840 else if (ftype == MUX_FWD_REMOTE) {
842 * This shouldn't fail unless we confused the host/port
843 * between options.remote_forwards and permitted_opens.
844 * However, for dynamic allocated listen ports we need
845 * to lookup the actual listen port.
847 listen_port = (fwd.listen_port == 0) ?
848 found_fwd->allocated_port : fwd.listen_port;
849 if (channel_request_rforward_cancel(fwd.listen_host,
851 error_reason = "port not in permitted opens";
852 } else { /* local and dynamic forwards */
854 if (channel_cancel_lport_listener(fwd.listen_host,
855 fwd.listen_port, fwd.connect_port,
856 options.gateway_ports) == -1)
857 error_reason = "port not found";
860 if (error_reason == NULL) {
861 buffer_put_int(r, MUX_S_OK);
862 buffer_put_int(r, rid);
864 if (found_fwd->listen_host != NULL)
865 xfree(found_fwd->listen_host);
866 if (found_fwd->connect_host != NULL)
867 xfree(found_fwd->connect_host);
868 found_fwd->listen_host = found_fwd->connect_host = NULL;
869 found_fwd->listen_port = found_fwd->connect_port = 0;
871 buffer_put_int(r, MUX_S_FAILURE);
872 buffer_put_int(r, rid);
873 buffer_put_cstring(r, error_reason);
876 if (fwd_desc != NULL)
878 if (fwd.listen_host != NULL)
879 xfree(fwd.listen_host);
880 if (fwd.connect_host != NULL)
881 xfree(fwd.connect_host);
887 process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
890 char *reserved, *chost;
894 chost = reserved = NULL;
895 if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
896 (chost = buffer_get_string_ret(m, NULL)) == NULL ||
897 buffer_get_int_ret(&cport, m) != 0) {
898 if (reserved != NULL)
902 error("%s: malformed message", __func__);
907 debug2("%s: channel %d: request stdio fwd to %s:%u",
908 __func__, c->self, chost, cport);
910 /* Gather fds from client */
911 for(i = 0; i < 2; i++) {
912 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
913 error("%s: failed to receive fd %d from slave",
915 for (j = 0; j < i; j++)
920 buffer_put_int(r, MUX_S_FAILURE);
921 buffer_put_int(r, rid);
922 buffer_put_cstring(r,
923 "did not receive file descriptors");
928 debug3("%s: got fds stdin %d, stdout %d", __func__,
929 new_fd[0], new_fd[1]);
931 /* XXX support multiple child sessions in future */
932 if (c->remote_id != -1) {
933 debug2("%s: session already open", __func__);
935 buffer_put_int(r, MUX_S_FAILURE);
936 buffer_put_int(r, rid);
937 buffer_put_cstring(r, "Multiple sessions not supported");
945 if (options.control_master == SSHCTL_MASTER_ASK ||
946 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
947 if (!ask_permission("Allow forward to %s:%u? ",
949 debug2("%s: stdio fwd refused by user", __func__);
951 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
952 buffer_put_int(r, rid);
953 buffer_put_cstring(r, "Permission denied");
958 /* enable nonblocking unless tty */
959 if (!isatty(new_fd[0]))
960 set_nonblock(new_fd[0]);
961 if (!isatty(new_fd[1]))
962 set_nonblock(new_fd[1]);
964 nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
966 nc->ctl_chan = c->self; /* link session -> control channel */
967 c->remote_id = nc->self; /* link control -> session channel */
969 debug2("%s: channel_new: %d linked to control channel %d",
970 __func__, nc->self, nc->ctl_chan);
972 channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
975 /* XXX defer until channel confirmed */
976 buffer_put_int(r, MUX_S_SESSION_OPENED);
977 buffer_put_int(r, rid);
978 buffer_put_int(r, nc->self);
984 process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
986 debug("%s: channel %d: stop listening", __func__, c->self);
988 if (options.control_master == SSHCTL_MASTER_ASK ||
989 options.control_master == SSHCTL_MASTER_AUTO_ASK) {
990 if (!ask_permission("Disable further multiplexing on shared "
991 "connection to %s? ", host)) {
992 debug2("%s: stop listen refused by user", __func__);
993 buffer_put_int(r, MUX_S_PERMISSION_DENIED);
994 buffer_put_int(r, rid);
995 buffer_put_cstring(r, "Permission denied");
1000 if (mux_listener_channel != NULL) {
1001 channel_free(mux_listener_channel);
1003 xfree(options.control_path);
1004 options.control_path = NULL;
1005 mux_listener_channel = NULL;
1006 muxserver_sock = -1;
1010 buffer_put_int(r, MUX_S_OK);
1011 buffer_put_int(r, rid);
1016 /* Channel callbacks fired on read/write from mux slave fd */
1018 mux_master_read_cb(Channel *c)
1020 struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
1023 u_int type, rid, have, i;
1027 if (c->mux_ctx == NULL) {
1028 state = xcalloc(1, sizeof(*state));
1030 channel_register_cleanup(c->self,
1031 mux_master_control_cleanup_cb, 0);
1035 buffer_put_int(&out, MUX_MSG_HELLO);
1036 buffer_put_int(&out, SSHMUX_VER);
1038 buffer_put_string(&c->output, buffer_ptr(&out),
1041 debug3("%s: channel %d: hello sent", __func__, c->self);
1048 /* Channel code ensures that we receive whole packets */
1049 if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
1051 error("%s: malformed message", __func__);
1054 buffer_append(&in, ptr, have);
1056 if (buffer_get_int_ret(&type, &in) != 0)
1058 debug3("%s: channel %d packet type 0x%08x len %u",
1059 __func__, c->self, type, buffer_len(&in));
1061 if (type == MUX_MSG_HELLO)
1064 if (!state->hello_rcvd) {
1065 error("%s: expected MUX_MSG_HELLO(0x%08x), "
1066 "received 0x%08x", __func__, MUX_MSG_HELLO, type);
1069 if (buffer_get_int_ret(&rid, &in) != 0)
1073 for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
1074 if (type == mux_master_handlers[i].type) {
1075 ret = mux_master_handlers[i].handler(rid, c, &in, &out);
1079 if (mux_master_handlers[i].handler == NULL) {
1080 error("%s: unsupported mux message 0x%08x", __func__, type);
1081 buffer_put_int(&out, MUX_S_FAILURE);
1082 buffer_put_int(&out, rid);
1083 buffer_put_cstring(&out, "unsupported request");
1086 /* Enqueue reply packet */
1087 if (buffer_len(&out) != 0) {
1088 buffer_put_string(&c->output, buffer_ptr(&out),
1098 mux_exit_message(Channel *c, int exitval)
1103 debug3("%s: channel %d: exit message, evitval %d", __func__, c->self,
1106 if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1107 fatal("%s: channel %d missing mux channel %d",
1108 __func__, c->self, c->ctl_chan);
1110 /* Append exit message packet to control socket output queue */
1112 buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
1113 buffer_put_int(&m, c->self);
1114 buffer_put_int(&m, exitval);
1116 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1121 mux_tty_alloc_failed(Channel *c)
1126 debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
1128 if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1129 fatal("%s: channel %d missing mux channel %d",
1130 __func__, c->self, c->ctl_chan);
1132 /* Append exit message packet to control socket output queue */
1134 buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
1135 buffer_put_int(&m, c->self);
1137 buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1141 /* Prepare a mux master to listen on a Unix domain socket. */
1143 muxserver_listen(void)
1145 struct sockaddr_un addr;
1148 char *orig_control_path = options.control_path;
1152 if (options.control_path == NULL ||
1153 options.control_master == SSHCTL_MASTER_NO)
1156 debug("setting up multiplex master socket");
1159 * Use a temporary path before listen so we can pseudo-atomically
1160 * establish the listening socket in its final location to avoid
1161 * other processes racing in between bind() and listen() and hitting
1162 * an unready socket.
1164 for (i = 0; i < sizeof(rbuf) - 1; i++) {
1165 r = arc4random_uniform(26+26+10);
1166 rbuf[i] = (r < 26) ? 'a' + r :
1167 (r < 26*2) ? 'A' + r - 26 :
1170 rbuf[sizeof(rbuf) - 1] = '\0';
1171 options.control_path = NULL;
1172 xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
1173 debug3("%s: temporary control path %s", __func__, options.control_path);
1175 memset(&addr, '\0', sizeof(addr));
1176 addr.sun_family = AF_UNIX;
1177 sun_len = offsetof(struct sockaddr_un, sun_path) +
1178 strlen(options.control_path) + 1;
1180 if (strlcpy(addr.sun_path, options.control_path,
1181 sizeof(addr.sun_path)) >= sizeof(addr.sun_path)) {
1182 error("ControlPath \"%s\" too long for Unix domain socket",
1183 options.control_path);
1184 goto disable_mux_master;
1187 if ((muxserver_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1188 fatal("%s socket(): %s", __func__, strerror(errno));
1190 old_umask = umask(0177);
1191 if (bind(muxserver_sock, (struct sockaddr *)&addr, sun_len) == -1) {
1192 if (errno == EINVAL || errno == EADDRINUSE) {
1193 error("ControlSocket %s already exists, "
1194 "disabling multiplexing", options.control_path);
1196 if (muxserver_sock != -1) {
1197 close(muxserver_sock);
1198 muxserver_sock = -1;
1200 xfree(orig_control_path);
1201 xfree(options.control_path);
1202 options.control_path = NULL;
1203 options.control_master = SSHCTL_MASTER_NO;
1206 fatal("%s bind(): %s", __func__, strerror(errno));
1210 if (listen(muxserver_sock, 64) == -1)
1211 fatal("%s listen(): %s", __func__, strerror(errno));
1213 /* Now atomically "move" the mux socket into position */
1214 if (link(options.control_path, orig_control_path) != 0) {
1215 if (errno != EEXIST) {
1216 fatal("%s: link mux listener %s => %s: %s", __func__,
1217 options.control_path, orig_control_path,
1220 error("ControlSocket %s already exists, disabling multiplexing",
1222 unlink(options.control_path);
1223 goto disable_mux_master;
1225 unlink(options.control_path);
1226 xfree(options.control_path);
1227 options.control_path = orig_control_path;
1229 set_nonblock(muxserver_sock);
1231 mux_listener_channel = channel_new("mux listener",
1232 SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
1233 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1234 0, options.control_path, 1);
1235 mux_listener_channel->mux_rcb = mux_master_read_cb;
1236 debug3("%s: mux listener channel %d fd %d", __func__,
1237 mux_listener_channel->self, mux_listener_channel->sock);
1240 /* Callback on open confirmation in mux master for a mux client session. */
1242 mux_session_confirm(int id, int success, void *arg)
1244 struct mux_session_confirm_ctx *cctx = arg;
1245 const char *display;
1251 fatal("%s: cctx == NULL", __func__);
1252 if ((c = channel_by_id(id)) == NULL)
1253 fatal("%s: no channel for id %d", __func__, id);
1254 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1255 fatal("%s: channel %d lacks control channel %d", __func__,
1259 debug3("%s: sending failure reply", __func__);
1261 buffer_init(&reply);
1262 buffer_put_int(&reply, MUX_S_FAILURE);
1263 buffer_put_int(&reply, cctx->rid);
1264 buffer_put_cstring(&reply, "Session open refused by peer");
1268 display = getenv("DISPLAY");
1269 if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1272 /* Get reasonable local authentication information. */
1273 client_x11_get_proto(display, options.xauth_location,
1274 options.forward_x11_trusted, options.forward_x11_timeout,
1276 /* Request forwarding with authentication spoofing. */
1277 debug("Requesting X11 forwarding with authentication "
1279 x11_request_forwarding_with_spoofing(id, display, proto,
1281 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1282 /* XXX exit_on_forward_failure */
1285 if (cctx->want_agent_fwd && options.forward_agent) {
1286 debug("Requesting authentication agent forwarding.");
1287 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1291 client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1292 cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1294 debug3("%s: sending success reply", __func__);
1296 buffer_init(&reply);
1297 buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1298 buffer_put_int(&reply, cctx->rid);
1299 buffer_put_int(&reply, c->self);
1303 buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1304 buffer_free(&reply);
1306 if (cc->mux_pause <= 0)
1307 fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1308 cc->mux_pause = 0; /* start processing messages again */
1309 c->open_confirm_ctx = NULL;
1310 buffer_free(&cctx->cmd);
1312 if (cctx->env != NULL) {
1313 for (i = 0; cctx->env[i] != NULL; i++)
1314 xfree(cctx->env[i]);
1320 /* ** Multiplexing client support */
1322 /* Exit signal handler */
1324 control_client_sighandler(int signo)
1326 muxclient_terminate = signo;
1330 * Relay signal handler - used to pass some signals from mux client to
1334 control_client_sigrelay(int signo)
1336 int save_errno = errno;
1338 if (muxserver_pid > 1)
1339 kill(muxserver_pid, signo);
1345 mux_client_read(int fd, Buffer *b, u_int need)
1353 pfd.events = POLLIN;
1354 p = buffer_append_space(b, need);
1355 for (have = 0; have < need; ) {
1356 if (muxclient_terminate) {
1360 len = read(fd, p + have, need - have);
1363 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1367 (void)poll(&pfd, 1, -1);
1385 mux_client_write_packet(int fd, Buffer *m)
1394 pfd.events = POLLOUT;
1395 buffer_init(&queue);
1396 buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1398 need = buffer_len(&queue);
1399 ptr = buffer_ptr(&queue);
1401 for (have = 0; have < need; ) {
1402 if (muxclient_terminate) {
1403 buffer_free(&queue);
1407 len = write(fd, ptr + have, need - have);
1410 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1414 (void)poll(&pfd, 1, -1);
1420 buffer_free(&queue);
1426 buffer_free(&queue);
1432 buffer_free(&queue);
1437 mux_client_read_packet(int fd, Buffer *m)
1444 buffer_init(&queue);
1445 if (mux_client_read(fd, &queue, 4) != 0) {
1446 if ((oerrno = errno) == EPIPE)
1447 debug3("%s: read header failed: %s", __func__, strerror(errno));
1451 need = get_u32(buffer_ptr(&queue));
1452 if (mux_client_read(fd, &queue, need) != 0) {
1454 debug3("%s: read body failed: %s", __func__, strerror(errno));
1458 ptr = buffer_get_string_ptr(&queue, &have);
1459 buffer_append(m, ptr, have);
1460 buffer_free(&queue);
1465 mux_client_hello_exchange(int fd)
1471 buffer_put_int(&m, MUX_MSG_HELLO);
1472 buffer_put_int(&m, SSHMUX_VER);
1475 if (mux_client_write_packet(fd, &m) != 0)
1476 fatal("%s: write packet: %s", __func__, strerror(errno));
1480 /* Read their HELLO */
1481 if (mux_client_read_packet(fd, &m) != 0) {
1486 type = buffer_get_int(&m);
1487 if (type != MUX_MSG_HELLO)
1488 fatal("%s: expected HELLO (%u) received %u",
1489 __func__, MUX_MSG_HELLO, type);
1490 ver = buffer_get_int(&m);
1491 if (ver != SSHMUX_VER)
1492 fatal("Unsupported multiplexing protocol version %d "
1493 "(expected %d)", ver, SSHMUX_VER);
1494 debug2("%s: master version %u", __func__, ver);
1495 /* No extensions are presently defined */
1496 while (buffer_len(&m) > 0) {
1497 char *name = buffer_get_string(&m, NULL);
1498 char *value = buffer_get_string(&m, NULL);
1500 debug2("Unrecognised master extension \"%s\"", name);
1509 mux_client_request_alive(int fd)
1513 u_int pid, type, rid;
1515 debug3("%s: entering", __func__);
1518 buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1519 buffer_put_int(&m, muxclient_request_id);
1521 if (mux_client_write_packet(fd, &m) != 0)
1522 fatal("%s: write packet: %s", __func__, strerror(errno));
1526 /* Read their reply */
1527 if (mux_client_read_packet(fd, &m) != 0) {
1532 type = buffer_get_int(&m);
1533 if (type != MUX_S_ALIVE) {
1534 e = buffer_get_string(&m, NULL);
1535 fatal("%s: master returned error: %s", __func__, e);
1538 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1539 fatal("%s: out of sequence reply: my id %u theirs %u",
1540 __func__, muxclient_request_id, rid);
1541 pid = buffer_get_int(&m);
1544 debug3("%s: done pid = %u", __func__, pid);
1546 muxclient_request_id++;
1552 mux_client_request_terminate(int fd)
1558 debug3("%s: entering", __func__);
1561 buffer_put_int(&m, MUX_C_TERMINATE);
1562 buffer_put_int(&m, muxclient_request_id);
1564 if (mux_client_write_packet(fd, &m) != 0)
1565 fatal("%s: write packet: %s", __func__, strerror(errno));
1569 /* Read their reply */
1570 if (mux_client_read_packet(fd, &m) != 0) {
1571 /* Remote end exited already */
1572 if (errno == EPIPE) {
1576 fatal("%s: read from master failed: %s",
1577 __func__, strerror(errno));
1580 type = buffer_get_int(&m);
1581 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1582 fatal("%s: out of sequence reply: my id %u theirs %u",
1583 __func__, muxclient_request_id, rid);
1587 case MUX_S_PERMISSION_DENIED:
1588 e = buffer_get_string(&m, NULL);
1589 fatal("Master refused termination request: %s", e);
1591 e = buffer_get_string(&m, NULL);
1592 fatal("%s: termination request failed: %s", __func__, e);
1594 fatal("%s: unexpected response from master 0x%08x",
1598 muxclient_request_id++;
1602 mux_client_forward(int fd, int cancel_flag, u_int ftype, Forward *fwd)
1608 fwd_desc = format_forward(ftype, fwd);
1609 debug("Requesting %s %s",
1610 cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
1614 buffer_put_int(&m, cancel_flag ? MUX_C_CLOSE_FWD : MUX_C_OPEN_FWD);
1615 buffer_put_int(&m, muxclient_request_id);
1616 buffer_put_int(&m, ftype);
1617 buffer_put_cstring(&m,
1618 fwd->listen_host == NULL ? "" : fwd->listen_host);
1619 buffer_put_int(&m, fwd->listen_port);
1620 buffer_put_cstring(&m,
1621 fwd->connect_host == NULL ? "" : fwd->connect_host);
1622 buffer_put_int(&m, fwd->connect_port);
1624 if (mux_client_write_packet(fd, &m) != 0)
1625 fatal("%s: write packet: %s", __func__, strerror(errno));
1629 /* Read their reply */
1630 if (mux_client_read_packet(fd, &m) != 0) {
1635 type = buffer_get_int(&m);
1636 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1637 fatal("%s: out of sequence reply: my id %u theirs %u",
1638 __func__, muxclient_request_id, rid);
1642 case MUX_S_REMOTE_PORT:
1644 fatal("%s: got MUX_S_REMOTE_PORT for cancel", __func__);
1645 fwd->allocated_port = buffer_get_int(&m);
1646 logit("Allocated port %u for remote forward to %s:%d",
1647 fwd->allocated_port,
1648 fwd->connect_host ? fwd->connect_host : "",
1650 if (muxclient_command == SSHMUX_COMMAND_FORWARD)
1651 fprintf(stdout, "%u\n", fwd->allocated_port);
1653 case MUX_S_PERMISSION_DENIED:
1654 e = buffer_get_string(&m, NULL);
1656 error("Master refused forwarding request: %s", e);
1659 e = buffer_get_string(&m, NULL);
1661 error("%s: forwarding request failed: %s", __func__, e);
1664 fatal("%s: unexpected response from master 0x%08x",
1669 muxclient_request_id++;
1674 mux_client_forwards(int fd, int cancel_flag)
1678 debug3("%s: %s forwardings: %d local, %d remote", __func__,
1679 cancel_flag ? "cancel" : "request",
1680 options.num_local_forwards, options.num_remote_forwards);
1682 /* XXX ExitOnForwardingFailure */
1683 for (i = 0; i < options.num_local_forwards; i++) {
1684 if (mux_client_forward(fd, cancel_flag,
1685 options.local_forwards[i].connect_port == 0 ?
1686 MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1687 options.local_forwards + i) != 0)
1690 for (i = 0; i < options.num_remote_forwards; i++) {
1691 if (mux_client_forward(fd, cancel_flag, MUX_FWD_REMOTE,
1692 options.remote_forwards + i) != 0)
1699 mux_client_request_session(int fd)
1703 u_int i, rid, sid, esid, exitval, type, exitval_seen;
1704 extern char **environ;
1705 int devnull, rawmode;
1707 debug3("%s: entering", __func__);
1709 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1710 error("%s: master alive request failed", __func__);
1714 signal(SIGPIPE, SIG_IGN);
1716 if (stdin_null_flag) {
1717 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1718 fatal("open(/dev/null): %s", strerror(errno));
1719 if (dup2(devnull, STDIN_FILENO) == -1)
1720 fatal("dup2: %s", strerror(errno));
1721 if (devnull > STDERR_FILENO)
1725 term = getenv("TERM");
1728 buffer_put_int(&m, MUX_C_NEW_SESSION);
1729 buffer_put_int(&m, muxclient_request_id);
1730 buffer_put_cstring(&m, ""); /* reserved */
1731 buffer_put_int(&m, tty_flag);
1732 buffer_put_int(&m, options.forward_x11);
1733 buffer_put_int(&m, options.forward_agent);
1734 buffer_put_int(&m, subsystem_flag);
1735 buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1736 0xffffffff : (u_int)options.escape_char);
1737 buffer_put_cstring(&m, term == NULL ? "" : term);
1738 buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1740 if (options.num_send_env > 0 && environ != NULL) {
1741 /* Pass environment */
1742 for (i = 0; environ[i] != NULL; i++) {
1743 if (env_permitted(environ[i])) {
1744 buffer_put_cstring(&m, environ[i]);
1749 if (mux_client_write_packet(fd, &m) != 0)
1750 fatal("%s: write packet: %s", __func__, strerror(errno));
1752 /* Send the stdio file descriptors */
1753 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1754 mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1755 mm_send_fd(fd, STDERR_FILENO) == -1)
1756 fatal("%s: send fds failed", __func__);
1758 debug3("%s: session request sent", __func__);
1760 /* Read their reply */
1762 if (mux_client_read_packet(fd, &m) != 0) {
1763 error("%s: read from master failed: %s",
1764 __func__, strerror(errno));
1769 type = buffer_get_int(&m);
1770 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1771 fatal("%s: out of sequence reply: my id %u theirs %u",
1772 __func__, muxclient_request_id, rid);
1774 case MUX_S_SESSION_OPENED:
1775 sid = buffer_get_int(&m);
1776 debug("%s: master session id: %u", __func__, sid);
1778 case MUX_S_PERMISSION_DENIED:
1779 e = buffer_get_string(&m, NULL);
1781 error("Master refused session request: %s", e);
1784 e = buffer_get_string(&m, NULL);
1786 error("%s: session request failed: %s", __func__, e);
1790 error("%s: unexpected response from master 0x%08x",
1794 muxclient_request_id++;
1796 signal(SIGHUP, control_client_sighandler);
1797 signal(SIGINT, control_client_sighandler);
1798 signal(SIGTERM, control_client_sighandler);
1799 signal(SIGWINCH, control_client_sigrelay);
1803 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1806 * Stick around until the controlee closes the client_fd.
1807 * Before it does, it is expected to write an exit message.
1808 * This process must read the value and wait for the closure of
1809 * the client_fd; if this one closes early, the multiplex master will
1810 * terminate early too (possibly losing data).
1812 for (exitval = 255, exitval_seen = 0;;) {
1814 if (mux_client_read_packet(fd, &m) != 0)
1816 type = buffer_get_int(&m);
1818 case MUX_S_TTY_ALLOC_FAIL:
1819 if ((esid = buffer_get_int(&m)) != sid)
1820 fatal("%s: tty alloc fail on unknown session: "
1821 "my id %u theirs %u",
1822 __func__, sid, esid);
1823 leave_raw_mode(options.request_tty ==
1827 case MUX_S_EXIT_MESSAGE:
1828 if ((esid = buffer_get_int(&m)) != sid)
1829 fatal("%s: exit on unknown session: "
1830 "my id %u theirs %u",
1831 __func__, sid, esid);
1833 fatal("%s: exitval sent twice", __func__);
1834 exitval = buffer_get_int(&m);
1838 e = buffer_get_string(&m, NULL);
1839 fatal("%s: master returned error: %s", __func__, e);
1845 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1847 if (muxclient_terminate) {
1848 debug2("Exiting on signal %d", muxclient_terminate);
1850 } else if (!exitval_seen) {
1851 debug2("Control master terminated unexpectedly");
1854 debug2("Received exit status from master %d", exitval);
1856 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1857 fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1863 mux_client_request_stdio_fwd(int fd)
1867 u_int type, rid, sid;
1870 debug3("%s: entering", __func__);
1872 if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1873 error("%s: master alive request failed", __func__);
1877 signal(SIGPIPE, SIG_IGN);
1879 if (stdin_null_flag) {
1880 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1881 fatal("open(/dev/null): %s", strerror(errno));
1882 if (dup2(devnull, STDIN_FILENO) == -1)
1883 fatal("dup2: %s", strerror(errno));
1884 if (devnull > STDERR_FILENO)
1889 buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
1890 buffer_put_int(&m, muxclient_request_id);
1891 buffer_put_cstring(&m, ""); /* reserved */
1892 buffer_put_cstring(&m, stdio_forward_host);
1893 buffer_put_int(&m, stdio_forward_port);
1895 if (mux_client_write_packet(fd, &m) != 0)
1896 fatal("%s: write packet: %s", __func__, strerror(errno));
1898 /* Send the stdio file descriptors */
1899 if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1900 mm_send_fd(fd, STDOUT_FILENO) == -1)
1901 fatal("%s: send fds failed", __func__);
1903 debug3("%s: stdio forward request sent", __func__);
1905 /* Read their reply */
1908 if (mux_client_read_packet(fd, &m) != 0) {
1909 error("%s: read from master failed: %s",
1910 __func__, strerror(errno));
1915 type = buffer_get_int(&m);
1916 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1917 fatal("%s: out of sequence reply: my id %u theirs %u",
1918 __func__, muxclient_request_id, rid);
1920 case MUX_S_SESSION_OPENED:
1921 sid = buffer_get_int(&m);
1922 debug("%s: master session id: %u", __func__, sid);
1924 case MUX_S_PERMISSION_DENIED:
1925 e = buffer_get_string(&m, NULL);
1927 fatal("Master refused stdio forwarding request: %s", e);
1929 e = buffer_get_string(&m, NULL);
1931 fatal("%s: stdio forwarding request failed: %s", __func__, e);
1934 error("%s: unexpected response from master 0x%08x",
1938 muxclient_request_id++;
1940 signal(SIGHUP, control_client_sighandler);
1941 signal(SIGINT, control_client_sighandler);
1942 signal(SIGTERM, control_client_sighandler);
1943 signal(SIGWINCH, control_client_sigrelay);
1946 * Stick around until the controlee closes the client_fd.
1949 if (mux_client_read_packet(fd, &m) != 0) {
1950 if (errno == EPIPE ||
1951 (errno == EINTR && muxclient_terminate != 0))
1953 fatal("%s: mux_client_read_packet: %s",
1954 __func__, strerror(errno));
1956 fatal("%s: master returned unexpected message %u", __func__, type);
1960 mux_client_request_stop_listening(int fd)
1966 debug3("%s: entering", __func__);
1969 buffer_put_int(&m, MUX_C_STOP_LISTENING);
1970 buffer_put_int(&m, muxclient_request_id);
1972 if (mux_client_write_packet(fd, &m) != 0)
1973 fatal("%s: write packet: %s", __func__, strerror(errno));
1977 /* Read their reply */
1978 if (mux_client_read_packet(fd, &m) != 0)
1979 fatal("%s: read from master failed: %s",
1980 __func__, strerror(errno));
1982 type = buffer_get_int(&m);
1983 if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1984 fatal("%s: out of sequence reply: my id %u theirs %u",
1985 __func__, muxclient_request_id, rid);
1989 case MUX_S_PERMISSION_DENIED:
1990 e = buffer_get_string(&m, NULL);
1991 fatal("Master refused stop listening request: %s", e);
1993 e = buffer_get_string(&m, NULL);
1994 fatal("%s: stop listening request failed: %s", __func__, e);
1996 fatal("%s: unexpected response from master 0x%08x",
2000 muxclient_request_id++;
2003 /* Multiplex client main loop. */
2005 muxclient(const char *path)
2007 struct sockaddr_un addr;
2012 if (muxclient_command == 0) {
2013 if (stdio_forward_host != NULL)
2014 muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
2016 muxclient_command = SSHMUX_COMMAND_OPEN;
2019 switch (options.control_master) {
2020 case SSHCTL_MASTER_AUTO:
2021 case SSHCTL_MASTER_AUTO_ASK:
2022 debug("auto-mux: Trying existing master");
2024 case SSHCTL_MASTER_NO:
2030 memset(&addr, '\0', sizeof(addr));
2031 addr.sun_family = AF_UNIX;
2032 sun_len = offsetof(struct sockaddr_un, sun_path) +
2035 if (strlcpy(addr.sun_path, path,
2036 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
2037 fatal("ControlPath too long");
2039 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
2040 fatal("%s socket(): %s", __func__, strerror(errno));
2042 if (connect(sock, (struct sockaddr *)&addr, sun_len) == -1) {
2043 switch (muxclient_command) {
2044 case SSHMUX_COMMAND_OPEN:
2045 case SSHMUX_COMMAND_STDIO_FWD:
2048 fatal("Control socket connect(%.100s): %s", path,
2051 if (errno == ECONNREFUSED &&
2052 options.control_master != SSHCTL_MASTER_NO) {
2053 debug("Stale control socket %.100s, unlinking", path);
2055 } else if (errno == ENOENT) {
2056 debug("Control socket \"%.100s\" does not exist", path);
2058 error("Control socket connect(%.100s): %s", path,
2066 if (mux_client_hello_exchange(sock) != 0) {
2067 error("%s: master hello exchange failed", __func__);
2072 switch (muxclient_command) {
2073 case SSHMUX_COMMAND_ALIVE_CHECK:
2074 if ((pid = mux_client_request_alive(sock)) == 0)
2075 fatal("%s: master alive check failed", __func__);
2076 fprintf(stderr, "Master running (pid=%d)\r\n", pid);
2078 case SSHMUX_COMMAND_TERMINATE:
2079 mux_client_request_terminate(sock);
2080 fprintf(stderr, "Exit request sent.\r\n");
2082 case SSHMUX_COMMAND_FORWARD:
2083 if (mux_client_forwards(sock, 0) != 0)
2084 fatal("%s: master forward request failed", __func__);
2086 case SSHMUX_COMMAND_OPEN:
2087 if (mux_client_forwards(sock, 0) != 0) {
2088 error("%s: master forward request failed", __func__);
2091 mux_client_request_session(sock);
2093 case SSHMUX_COMMAND_STDIO_FWD:
2094 mux_client_request_stdio_fwd(sock);
2096 case SSHMUX_COMMAND_STOP:
2097 mux_client_request_stop_listening(sock);
2098 fprintf(stderr, "Stop listening request sent.\r\n");
2100 case SSHMUX_COMMAND_CANCEL_FWD:
2101 if (mux_client_forwards(sock, 1) != 0)
2102 error("%s: master cancel forward request failed",
2106 fatal("unrecognised muxclient_command %d", muxclient_command);