]> CyberLeo.Net >> Repos - FreeBSD/releng/10.3.git/blob - crypto/openssh/mux.c
MFS (r296781):
[FreeBSD/releng/10.3.git] / crypto / openssh / mux.c
1 /* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
2 /*
3  * Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
4  *
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.
8  *
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.
16  */
17
18 /* ssh session multiplexing support */
19
20 /*
21  * TODO:
22  *   - Better signalling from master to slave, especially passing of
23  *      error messages
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
30  *     sessions in master.
31  */
32
33 #include "includes.h"
34 __RCSID("$FreeBSD$");
35
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <sys/socket.h>
39 #include <sys/un.h>
40
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <signal.h>
44 #include <stdarg.h>
45 #include <stddef.h>
46 #include <stdlib.h>
47 #include <stdio.h>
48 #include <string.h>
49 #include <unistd.h>
50 #ifdef HAVE_PATHS_H
51 #include <paths.h>
52 #endif
53
54 #ifdef HAVE_POLL_H
55 #include <poll.h>
56 #else
57 # ifdef HAVE_SYS_POLL_H
58 #  include <sys/poll.h>
59 # endif
60 #endif
61
62 #ifdef HAVE_UTIL_H
63 # include <util.h>
64 #endif
65
66 #include "openbsd-compat/sys-queue.h"
67 #include "xmalloc.h"
68 #include "log.h"
69 #include "ssh.h"
70 #include "ssh2.h"
71 #include "pathnames.h"
72 #include "misc.h"
73 #include "match.h"
74 #include "buffer.h"
75 #include "channels.h"
76 #include "msg.h"
77 #include "packet.h"
78 #include "monitor_fdpass.h"
79 #include "sshpty.h"
80 #include "key.h"
81 #include "readconf.h"
82 #include "clientloop.h"
83
84 /* from ssh.c */
85 extern int tty_flag;
86 extern Options options;
87 extern int stdin_null_flag;
88 extern char *host;
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;
94
95 /* Context for session open confirmation callback */
96 struct mux_session_confirm_ctx {
97         u_int want_tty;
98         u_int want_subsys;
99         u_int want_x_fwd;
100         u_int want_agent_fwd;
101         Buffer cmd;
102         char *term;
103         struct termios tio;
104         char **env;
105         u_int rid;
106 };
107
108 /* Context for stdio fwd open confirmation callback */
109 struct mux_stdio_confirm_ctx {
110         u_int rid;
111 };
112
113 /* Context for global channel callback */
114 struct mux_channel_confirm_ctx {
115         u_int cid;      /* channel id */
116         u_int rid;      /* request id */
117         int fid;        /* forward id */
118 };
119
120 /* fd to control socket */
121 int muxserver_sock = -1;
122
123 /* client request id */
124 u_int muxclient_request_id = 0;
125
126 /* Multiplexing control command */
127 u_int muxclient_command = 0;
128
129 /* Set when signalled. */
130 static volatile sig_atomic_t muxclient_terminate = 0;
131
132 /* PID of multiplex server */
133 static u_int muxserver_pid = 0;
134
135 static Channel *mux_listener_channel = NULL;
136
137 struct mux_master_state {
138         int hello_rcvd;
139 };
140
141 /* mux protocol messages */
142 #define MUX_MSG_HELLO           0x00000001
143 #define MUX_C_NEW_SESSION       0x10000002
144 #define MUX_C_ALIVE_CHECK       0x10000004
145 #define MUX_C_TERMINATE         0x10000005
146 #define MUX_C_OPEN_FWD          0x10000006
147 #define MUX_C_CLOSE_FWD         0x10000007
148 #define MUX_C_NEW_STDIO_FWD     0x10000008
149 #define MUX_C_STOP_LISTENING    0x10000009
150 #define MUX_S_OK                0x80000001
151 #define MUX_S_PERMISSION_DENIED 0x80000002
152 #define MUX_S_FAILURE           0x80000003
153 #define MUX_S_EXIT_MESSAGE      0x80000004
154 #define MUX_S_ALIVE             0x80000005
155 #define MUX_S_SESSION_OPENED    0x80000006
156 #define MUX_S_REMOTE_PORT       0x80000007
157 #define MUX_S_TTY_ALLOC_FAIL    0x80000008
158
159 /* type codes for MUX_C_OPEN_FWD and MUX_C_CLOSE_FWD */
160 #define MUX_FWD_LOCAL   1
161 #define MUX_FWD_REMOTE  2
162 #define MUX_FWD_DYNAMIC 3
163
164 static void mux_session_confirm(int, int, void *);
165 static void mux_stdio_confirm(int, int, void *);
166
167 static int process_mux_master_hello(u_int, Channel *, Buffer *, Buffer *);
168 static int process_mux_new_session(u_int, Channel *, Buffer *, Buffer *);
169 static int process_mux_alive_check(u_int, Channel *, Buffer *, Buffer *);
170 static int process_mux_terminate(u_int, Channel *, Buffer *, Buffer *);
171 static int process_mux_open_fwd(u_int, Channel *, Buffer *, Buffer *);
172 static int process_mux_close_fwd(u_int, Channel *, Buffer *, Buffer *);
173 static int process_mux_stdio_fwd(u_int, Channel *, Buffer *, Buffer *);
174 static int process_mux_stop_listening(u_int, Channel *, Buffer *, Buffer *);
175
176 static const struct {
177         u_int type;
178         int (*handler)(u_int, Channel *, Buffer *, Buffer *);
179 } mux_master_handlers[] = {
180         { MUX_MSG_HELLO, process_mux_master_hello },
181         { MUX_C_NEW_SESSION, process_mux_new_session },
182         { MUX_C_ALIVE_CHECK, process_mux_alive_check },
183         { MUX_C_TERMINATE, process_mux_terminate },
184         { MUX_C_OPEN_FWD, process_mux_open_fwd },
185         { MUX_C_CLOSE_FWD, process_mux_close_fwd },
186         { MUX_C_NEW_STDIO_FWD, process_mux_stdio_fwd },
187         { MUX_C_STOP_LISTENING, process_mux_stop_listening },
188         { 0, NULL }
189 };
190
191 /* Cleanup callback fired on closure of mux slave _session_ channel */
192 /* ARGSUSED */
193 static void
194 mux_master_session_cleanup_cb(int cid, void *unused)
195 {
196         Channel *cc, *c = channel_by_id(cid);
197
198         debug3("%s: entering for channel %d", __func__, cid);
199         if (c == NULL)
200                 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
201         if (c->ctl_chan != -1) {
202                 if ((cc = channel_by_id(c->ctl_chan)) == NULL)
203                         fatal("%s: channel %d missing control channel %d",
204                             __func__, c->self, c->ctl_chan);
205                 c->ctl_chan = -1;
206                 cc->remote_id = -1;
207                 chan_rcvd_oclose(cc);
208         }
209         channel_cancel_cleanup(c->self);
210 }
211
212 /* Cleanup callback fired on closure of mux slave _control_ channel */
213 /* ARGSUSED */
214 static void
215 mux_master_control_cleanup_cb(int cid, void *unused)
216 {
217         Channel *sc, *c = channel_by_id(cid);
218
219         debug3("%s: entering for channel %d", __func__, cid);
220         if (c == NULL)
221                 fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
222         if (c->remote_id != -1) {
223                 if ((sc = channel_by_id(c->remote_id)) == NULL)
224                         fatal("%s: channel %d missing session channel %d",
225                             __func__, c->self, c->remote_id);
226                 c->remote_id = -1;
227                 sc->ctl_chan = -1;
228                 if (sc->type != SSH_CHANNEL_OPEN &&
229                     sc->type != SSH_CHANNEL_OPENING) {
230                         debug2("%s: channel %d: not open", __func__, sc->self);
231                         chan_mark_dead(sc);
232                 } else {
233                         if (sc->istate == CHAN_INPUT_OPEN)
234                                 chan_read_failed(sc);
235                         if (sc->ostate == CHAN_OUTPUT_OPEN)
236                                 chan_write_failed(sc);
237                 }
238         }
239         channel_cancel_cleanup(c->self);
240 }
241
242 /* Check mux client environment variables before passing them to mux master. */
243 static int
244 env_permitted(char *env)
245 {
246         int i, ret;
247         char name[1024], *cp;
248
249         if ((cp = strchr(env, '=')) == NULL || cp == env)
250                 return 0;
251         ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
252         if (ret <= 0 || (size_t)ret >= sizeof(name)) {
253                 error("env_permitted: name '%.100s...' too long", env);
254                 return 0;
255         }
256
257         for (i = 0; i < options.num_send_env; i++)
258                 if (match_pattern(name, options.send_env[i]))
259                         return 1;
260
261         return 0;
262 }
263
264 /* Mux master protocol message handlers */
265
266 static int
267 process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
268 {
269         u_int ver;
270         struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
271
272         if (state == NULL)
273                 fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
274         if (state->hello_rcvd) {
275                 error("%s: HELLO received twice", __func__);
276                 return -1;
277         }
278         if (buffer_get_int_ret(&ver, m) != 0) {
279  malf:
280                 error("%s: malformed message", __func__);
281                 return -1;
282         }
283         if (ver != SSHMUX_VER) {
284                 error("Unsupported multiplexing protocol version %d "
285                     "(expected %d)", ver, SSHMUX_VER);
286                 return -1;
287         }
288         debug2("%s: channel %d slave version %u", __func__, c->self, ver);
289
290         /* No extensions are presently defined */
291         while (buffer_len(m) > 0) {
292                 char *name = buffer_get_string_ret(m, NULL);
293                 char *value = buffer_get_string_ret(m, NULL);
294
295                 if (name == NULL || value == NULL) {
296                         free(name);
297                         free(value);
298                         goto malf;
299                 }
300                 debug2("Unrecognised slave extension \"%s\"", name);
301                 free(name);
302                 free(value);
303         }
304         state->hello_rcvd = 1;
305         return 0;
306 }
307
308 static int
309 process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
310 {
311         Channel *nc;
312         struct mux_session_confirm_ctx *cctx;
313         char *reserved, *cmd, *cp;
314         u_int i, j, len, env_len, escape_char, window, packetmax;
315         int new_fd[3];
316
317         /* Reply for SSHMUX_COMMAND_OPEN */
318         cctx = xcalloc(1, sizeof(*cctx));
319         cctx->term = NULL;
320         cctx->rid = rid;
321         cmd = reserved = NULL;
322         cctx->env = NULL;
323         env_len = 0;
324         if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
325             buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
326             buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
327             buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
328             buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
329             buffer_get_int_ret(&escape_char, m) != 0 ||
330             (cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
331             (cmd = buffer_get_string_ret(m, &len)) == NULL) {
332  malf:
333                 free(cmd);
334                 free(reserved);
335                 for (j = 0; j < env_len; j++)
336                         free(cctx->env[j]);
337                 free(cctx->env);
338                 free(cctx->term);
339                 free(cctx);
340                 error("%s: malformed message", __func__);
341                 return -1;
342         }
343         free(reserved);
344         reserved = NULL;
345
346         while (buffer_len(m) > 0) {
347 #define MUX_MAX_ENV_VARS        4096
348                 if ((cp = buffer_get_string_ret(m, &len)) == NULL)
349                         goto malf;
350                 if (!env_permitted(cp)) {
351                         free(cp);
352                         continue;
353                 }
354                 cctx->env = xreallocarray(cctx->env, env_len + 2,
355                     sizeof(*cctx->env));
356                 cctx->env[env_len++] = cp;
357                 cctx->env[env_len] = NULL;
358                 if (env_len > MUX_MAX_ENV_VARS) {
359                         error(">%d environment variables received, ignoring "
360                             "additional", MUX_MAX_ENV_VARS);
361                         break;
362                 }
363         }
364
365         debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
366             "term \"%s\", cmd \"%s\", env %u", __func__, c->self,
367             cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
368             cctx->want_subsys, cctx->term, cmd, env_len);
369
370         buffer_init(&cctx->cmd);
371         buffer_append(&cctx->cmd, cmd, strlen(cmd));
372         free(cmd);
373         cmd = NULL;
374
375         /* Gather fds from client */
376         for(i = 0; i < 3; i++) {
377                 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
378                         error("%s: failed to receive fd %d from slave",
379                             __func__, i);
380                         for (j = 0; j < i; j++)
381                                 close(new_fd[j]);
382                         for (j = 0; j < env_len; j++)
383                                 free(cctx->env[j]);
384                         free(cctx->env);
385                         free(cctx->term);
386                         buffer_free(&cctx->cmd);
387                         free(cctx);
388
389                         /* prepare reply */
390                         buffer_put_int(r, MUX_S_FAILURE);
391                         buffer_put_int(r, rid);
392                         buffer_put_cstring(r,
393                             "did not receive file descriptors");
394                         return -1;
395                 }
396         }
397
398         debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
399             new_fd[0], new_fd[1], new_fd[2]);
400
401         /* XXX support multiple child sessions in future */
402         if (c->remote_id != -1) {
403                 debug2("%s: session already open", __func__);
404                 /* prepare reply */
405                 buffer_put_int(r, MUX_S_FAILURE);
406                 buffer_put_int(r, rid);
407                 buffer_put_cstring(r, "Multiple sessions not supported");
408  cleanup:
409                 close(new_fd[0]);
410                 close(new_fd[1]);
411                 close(new_fd[2]);
412                 free(cctx->term);
413                 if (env_len != 0) {
414                         for (i = 0; i < env_len; i++)
415                                 free(cctx->env[i]);
416                         free(cctx->env);
417                 }
418                 buffer_free(&cctx->cmd);
419                 free(cctx);
420                 return 0;
421         }
422
423         if (options.control_master == SSHCTL_MASTER_ASK ||
424             options.control_master == SSHCTL_MASTER_AUTO_ASK) {
425                 if (!ask_permission("Allow shared connection to %s? ", host)) {
426                         debug2("%s: session refused by user", __func__);
427                         /* prepare reply */
428                         buffer_put_int(r, MUX_S_PERMISSION_DENIED);
429                         buffer_put_int(r, rid);
430                         buffer_put_cstring(r, "Permission denied");
431                         goto cleanup;
432                 }
433         }
434
435         /* Try to pick up ttymodes from client before it goes raw */
436         if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
437                 error("%s: tcgetattr: %s", __func__, strerror(errno));
438
439         /* enable nonblocking unless tty */
440         if (!isatty(new_fd[0]))
441                 set_nonblock(new_fd[0]);
442         if (!isatty(new_fd[1]))
443                 set_nonblock(new_fd[1]);
444         if (!isatty(new_fd[2]))
445                 set_nonblock(new_fd[2]);
446
447         window = CHAN_SES_WINDOW_DEFAULT;
448         packetmax = CHAN_SES_PACKET_DEFAULT;
449         if (cctx->want_tty) {
450                 window >>= 1;
451                 packetmax >>= 1;
452         }
453
454         nc = channel_new("session", SSH_CHANNEL_OPENING,
455             new_fd[0], new_fd[1], new_fd[2], window, packetmax,
456             CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
457
458         nc->ctl_chan = c->self;         /* link session -> control channel */
459         c->remote_id = nc->self;        /* link control -> session channel */
460
461         if (cctx->want_tty && escape_char != 0xffffffff) {
462                 channel_register_filter(nc->self,
463                     client_simple_escape_filter, NULL,
464                     client_filter_cleanup,
465                     client_new_escape_filter_ctx((int)escape_char));
466         }
467
468         debug2("%s: channel_new: %d linked to control channel %d",
469             __func__, nc->self, nc->ctl_chan);
470
471         channel_send_open(nc->self);
472         channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
473         c->mux_pause = 1; /* stop handling messages until open_confirm done */
474         channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
475
476         /* reply is deferred, sent by mux_session_confirm */
477         return 0;
478 }
479
480 static int
481 process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
482 {
483         debug2("%s: channel %d: alive check", __func__, c->self);
484
485         /* prepare reply */
486         buffer_put_int(r, MUX_S_ALIVE);
487         buffer_put_int(r, rid);
488         buffer_put_int(r, (u_int)getpid());
489
490         return 0;
491 }
492
493 static int
494 process_mux_terminate(u_int rid, Channel *c, Buffer *m, Buffer *r)
495 {
496         debug2("%s: channel %d: terminate request", __func__, c->self);
497
498         if (options.control_master == SSHCTL_MASTER_ASK ||
499             options.control_master == SSHCTL_MASTER_AUTO_ASK) {
500                 if (!ask_permission("Terminate shared connection to %s? ",
501                     host)) {
502                         debug2("%s: termination refused by user", __func__);
503                         buffer_put_int(r, MUX_S_PERMISSION_DENIED);
504                         buffer_put_int(r, rid);
505                         buffer_put_cstring(r, "Permission denied");
506                         return 0;
507                 }
508         }
509
510         quit_pending = 1;
511         buffer_put_int(r, MUX_S_OK);
512         buffer_put_int(r, rid);
513         /* XXX exit happens too soon - message never makes it to client */
514         return 0;
515 }
516
517 static char *
518 format_forward(u_int ftype, struct Forward *fwd)
519 {
520         char *ret;
521
522         switch (ftype) {
523         case MUX_FWD_LOCAL:
524                 xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
525                     (fwd->listen_path != NULL) ? fwd->listen_path :
526                     (fwd->listen_host == NULL) ?
527                     (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
528                     fwd->listen_host, fwd->listen_port,
529                     (fwd->connect_path != NULL) ? fwd->connect_path :
530                     fwd->connect_host, fwd->connect_port);
531                 break;
532         case MUX_FWD_DYNAMIC:
533                 xasprintf(&ret, "dynamic forward %.200s:%d -> *",
534                     (fwd->listen_host == NULL) ?
535                     (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
536                      fwd->listen_host, fwd->listen_port);
537                 break;
538         case MUX_FWD_REMOTE:
539                 xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
540                     (fwd->listen_path != NULL) ? fwd->listen_path :
541                     (fwd->listen_host == NULL) ?
542                     "LOCALHOST" : fwd->listen_host,
543                     fwd->listen_port,
544                     (fwd->connect_path != NULL) ? fwd->connect_path :
545                     fwd->connect_host, fwd->connect_port);
546                 break;
547         default:
548                 fatal("%s: unknown forward type %u", __func__, ftype);
549         }
550         return ret;
551 }
552
553 static int
554 compare_host(const char *a, const char *b)
555 {
556         if (a == NULL && b == NULL)
557                 return 1;
558         if (a == NULL || b == NULL)
559                 return 0;
560         return strcmp(a, b) == 0;
561 }
562
563 static int
564 compare_forward(struct Forward *a, struct Forward *b)
565 {
566         if (!compare_host(a->listen_host, b->listen_host))
567                 return 0;
568         if (!compare_host(a->listen_path, b->listen_path))
569                 return 0;
570         if (a->listen_port != b->listen_port)
571                 return 0;
572         if (!compare_host(a->connect_host, b->connect_host))
573                 return 0;
574         if (!compare_host(a->connect_path, b->connect_path))
575                 return 0;
576         if (a->connect_port != b->connect_port)
577                 return 0;
578
579         return 1;
580 }
581
582 static void
583 mux_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
584 {
585         struct mux_channel_confirm_ctx *fctx = ctxt;
586         char *failmsg = NULL;
587         struct Forward *rfwd;
588         Channel *c;
589         Buffer out;
590
591         if ((c = channel_by_id(fctx->cid)) == NULL) {
592                 /* no channel for reply */
593                 error("%s: unknown channel", __func__);
594                 return;
595         }
596         buffer_init(&out);
597         if (fctx->fid >= options.num_remote_forwards ||
598             (options.remote_forwards[fctx->fid].connect_path == NULL &&
599             options.remote_forwards[fctx->fid].connect_host == NULL)) {
600                 xasprintf(&failmsg, "unknown forwarding id %d", fctx->fid);
601                 goto fail;
602         }
603         rfwd = &options.remote_forwards[fctx->fid];
604         debug("%s: %s for: listen %d, connect %s:%d", __func__,
605             type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
606             rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
607             rfwd->connect_host, rfwd->connect_port);
608         if (type == SSH2_MSG_REQUEST_SUCCESS) {
609                 if (rfwd->listen_port == 0) {
610                         rfwd->allocated_port = packet_get_int();
611                         debug("Allocated port %u for mux remote forward"
612                             " to %s:%d", rfwd->allocated_port,
613                             rfwd->connect_host, rfwd->connect_port);
614                         buffer_put_int(&out, MUX_S_REMOTE_PORT);
615                         buffer_put_int(&out, fctx->rid);
616                         buffer_put_int(&out, rfwd->allocated_port);
617                         channel_update_permitted_opens(rfwd->handle,
618                            rfwd->allocated_port);
619                 } else {
620                         buffer_put_int(&out, MUX_S_OK);
621                         buffer_put_int(&out, fctx->rid);
622                 }
623                 goto out;
624         } else {
625                 if (rfwd->listen_port == 0)
626                         channel_update_permitted_opens(rfwd->handle, -1);
627                 if (rfwd->listen_path != NULL)
628                         xasprintf(&failmsg, "remote port forwarding failed for "
629                             "listen path %s", rfwd->listen_path);
630                 else
631                         xasprintf(&failmsg, "remote port forwarding failed for "
632                             "listen port %d", rfwd->listen_port);
633
634                 debug2("%s: clearing registered forwarding for listen %d, "
635                     "connect %s:%d", __func__, rfwd->listen_port,
636                     rfwd->connect_path ? rfwd->connect_path :
637                     rfwd->connect_host, rfwd->connect_port);
638
639                 free(rfwd->listen_host);
640                 free(rfwd->listen_path);
641                 free(rfwd->connect_host);
642                 free(rfwd->connect_path);
643                 memset(rfwd, 0, sizeof(*rfwd));
644         }
645  fail:
646         error("%s: %s", __func__, failmsg);
647         buffer_put_int(&out, MUX_S_FAILURE);
648         buffer_put_int(&out, fctx->rid);
649         buffer_put_cstring(&out, failmsg);
650         free(failmsg);
651  out:
652         buffer_put_string(&c->output, buffer_ptr(&out), buffer_len(&out));
653         buffer_free(&out);
654         if (c->mux_pause <= 0)
655                 fatal("%s: mux_pause %d", __func__, c->mux_pause);
656         c->mux_pause = 0; /* start processing messages again */
657 }
658
659 static int
660 process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
661 {
662         struct Forward fwd;
663         char *fwd_desc = NULL;
664         char *listen_addr, *connect_addr;
665         u_int ftype;
666         u_int lport, cport;
667         int i, ret = 0, freefwd = 1;
668
669         memset(&fwd, 0, sizeof(fwd));
670
671         /* XXX - lport/cport check redundant */
672         if (buffer_get_int_ret(&ftype, m) != 0 ||
673             (listen_addr = buffer_get_string_ret(m, NULL)) == NULL ||
674             buffer_get_int_ret(&lport, m) != 0 ||
675             (connect_addr = buffer_get_string_ret(m, NULL)) == NULL ||
676             buffer_get_int_ret(&cport, m) != 0 ||
677             (lport != (u_int)PORT_STREAMLOCAL && lport > 65535) ||
678             (cport != (u_int)PORT_STREAMLOCAL && cport > 65535)) {
679                 error("%s: malformed message", __func__);
680                 ret = -1;
681                 goto out;
682         }
683         if (*listen_addr == '\0') {
684                 free(listen_addr);
685                 listen_addr = NULL;
686         }
687         if (*connect_addr == '\0') {
688                 free(connect_addr);
689                 connect_addr = NULL;
690         }
691
692         memset(&fwd, 0, sizeof(fwd));
693         fwd.listen_port = lport;
694         if (fwd.listen_port == PORT_STREAMLOCAL)
695                 fwd.listen_path = listen_addr;
696         else
697                 fwd.listen_host = listen_addr;
698         fwd.connect_port = cport;
699         if (fwd.connect_port == PORT_STREAMLOCAL)
700                 fwd.connect_path = connect_addr;
701         else
702                 fwd.connect_host = connect_addr;
703
704         debug2("%s: channel %d: request %s", __func__, c->self,
705             (fwd_desc = format_forward(ftype, &fwd)));
706
707         if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
708             ftype != MUX_FWD_DYNAMIC) {
709                 logit("%s: invalid forwarding type %u", __func__, ftype);
710  invalid:
711                 free(listen_addr);
712                 free(connect_addr);
713                 buffer_put_int(r, MUX_S_FAILURE);
714                 buffer_put_int(r, rid);
715                 buffer_put_cstring(r, "Invalid forwarding request");
716                 return 0;
717         }
718         if (ftype == MUX_FWD_DYNAMIC && fwd.listen_path) {
719                 logit("%s: streamlocal and dynamic forwards "
720                     "are mutually exclusive", __func__);
721                 goto invalid;
722         }
723         if (fwd.listen_port != PORT_STREAMLOCAL && fwd.listen_port >= 65536) {
724                 logit("%s: invalid listen port %u", __func__,
725                     fwd.listen_port);
726                 goto invalid;
727         }
728         if ((fwd.connect_port != PORT_STREAMLOCAL && fwd.connect_port >= 65536)
729             || (ftype != MUX_FWD_DYNAMIC && ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
730                 logit("%s: invalid connect port %u", __func__,
731                     fwd.connect_port);
732                 goto invalid;
733         }
734         if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL && fwd.connect_path == NULL) {
735                 logit("%s: missing connect host", __func__);
736                 goto invalid;
737         }
738
739         /* Skip forwards that have already been requested */
740         switch (ftype) {
741         case MUX_FWD_LOCAL:
742         case MUX_FWD_DYNAMIC:
743                 for (i = 0; i < options.num_local_forwards; i++) {
744                         if (compare_forward(&fwd,
745                             options.local_forwards + i)) {
746  exists:
747                                 debug2("%s: found existing forwarding",
748                                     __func__);
749                                 buffer_put_int(r, MUX_S_OK);
750                                 buffer_put_int(r, rid);
751                                 goto out;
752                         }
753                 }
754                 break;
755         case MUX_FWD_REMOTE:
756                 for (i = 0; i < options.num_remote_forwards; i++) {
757                         if (compare_forward(&fwd,
758                             options.remote_forwards + i)) {
759                                 if (fwd.listen_port != 0)
760                                         goto exists;
761                                 debug2("%s: found allocated port",
762                                     __func__);
763                                 buffer_put_int(r, MUX_S_REMOTE_PORT);
764                                 buffer_put_int(r, rid);
765                                 buffer_put_int(r,
766                                     options.remote_forwards[i].allocated_port);
767                                 goto out;
768                         }
769                 }
770                 break;
771         }
772
773         if (options.control_master == SSHCTL_MASTER_ASK ||
774             options.control_master == SSHCTL_MASTER_AUTO_ASK) {
775                 if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
776                         debug2("%s: forwarding refused by user", __func__);
777                         buffer_put_int(r, MUX_S_PERMISSION_DENIED);
778                         buffer_put_int(r, rid);
779                         buffer_put_cstring(r, "Permission denied");
780                         goto out;
781                 }
782         }
783
784         if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
785                 if (!channel_setup_local_fwd_listener(&fwd,
786                     &options.fwd_opts)) {
787  fail:
788                         logit("slave-requested %s failed", fwd_desc);
789                         buffer_put_int(r, MUX_S_FAILURE);
790                         buffer_put_int(r, rid);
791                         buffer_put_cstring(r, "Port forwarding failed");
792                         goto out;
793                 }
794                 add_local_forward(&options, &fwd);
795                 freefwd = 0;
796         } else {
797                 struct mux_channel_confirm_ctx *fctx;
798
799                 fwd.handle = channel_request_remote_forwarding(&fwd);
800                 if (fwd.handle < 0)
801                         goto fail;
802                 add_remote_forward(&options, &fwd);
803                 fctx = xcalloc(1, sizeof(*fctx));
804                 fctx->cid = c->self;
805                 fctx->rid = rid;
806                 fctx->fid = options.num_remote_forwards - 1;
807                 client_register_global_confirm(mux_confirm_remote_forward,
808                     fctx);
809                 freefwd = 0;
810                 c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
811                 /* delayed reply in mux_confirm_remote_forward */
812                 goto out;
813         }
814         buffer_put_int(r, MUX_S_OK);
815         buffer_put_int(r, rid);
816  out:
817         free(fwd_desc);
818         if (freefwd) {
819                 free(fwd.listen_host);
820                 free(fwd.listen_path);
821                 free(fwd.connect_host);
822                 free(fwd.connect_path);
823         }
824         return ret;
825 }
826
827 static int
828 process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
829 {
830         struct Forward fwd, *found_fwd;
831         char *fwd_desc = NULL;
832         const char *error_reason = NULL;
833         char *listen_addr = NULL, *connect_addr = NULL;
834         u_int ftype;
835         int i, ret = 0;
836         u_int lport, cport;
837
838         memset(&fwd, 0, sizeof(fwd));
839
840         if (buffer_get_int_ret(&ftype, m) != 0 ||
841             (listen_addr = buffer_get_string_ret(m, NULL)) == NULL ||
842             buffer_get_int_ret(&lport, m) != 0 ||
843             (connect_addr = buffer_get_string_ret(m, NULL)) == NULL ||
844             buffer_get_int_ret(&cport, m) != 0 ||
845             (lport != (u_int)PORT_STREAMLOCAL && lport > 65535) ||
846             (cport != (u_int)PORT_STREAMLOCAL && cport > 65535)) {
847                 error("%s: malformed message", __func__);
848                 ret = -1;
849                 goto out;
850         }
851
852         if (*listen_addr == '\0') {
853                 free(listen_addr);
854                 listen_addr = NULL;
855         }
856         if (*connect_addr == '\0') {
857                 free(connect_addr);
858                 connect_addr = NULL;
859         }
860
861         memset(&fwd, 0, sizeof(fwd));
862         fwd.listen_port = lport;
863         if (fwd.listen_port == PORT_STREAMLOCAL)
864                 fwd.listen_path = listen_addr;
865         else
866                 fwd.listen_host = listen_addr;
867         fwd.connect_port = cport;
868         if (fwd.connect_port == PORT_STREAMLOCAL)
869                 fwd.connect_path = connect_addr;
870         else
871                 fwd.connect_host = connect_addr;
872
873         debug2("%s: channel %d: request cancel %s", __func__, c->self,
874             (fwd_desc = format_forward(ftype, &fwd)));
875
876         /* make sure this has been requested */
877         found_fwd = NULL;
878         switch (ftype) {
879         case MUX_FWD_LOCAL:
880         case MUX_FWD_DYNAMIC:
881                 for (i = 0; i < options.num_local_forwards; i++) {
882                         if (compare_forward(&fwd,
883                             options.local_forwards + i)) {
884                                 found_fwd = options.local_forwards + i;
885                                 break;
886                         }
887                 }
888                 break;
889         case MUX_FWD_REMOTE:
890                 for (i = 0; i < options.num_remote_forwards; i++) {
891                         if (compare_forward(&fwd,
892                             options.remote_forwards + i)) {
893                                 found_fwd = options.remote_forwards + i;
894                                 break;
895                         }
896                 }
897                 break;
898         }
899
900         if (found_fwd == NULL)
901                 error_reason = "port not forwarded";
902         else if (ftype == MUX_FWD_REMOTE) {
903                 /*
904                  * This shouldn't fail unless we confused the host/port
905                  * between options.remote_forwards and permitted_opens.
906                  * However, for dynamic allocated listen ports we need
907                  * to use the actual listen port.
908                  */
909                 if (channel_request_rforward_cancel(found_fwd) == -1)
910                         error_reason = "port not in permitted opens";
911         } else {        /* local and dynamic forwards */
912                 /* Ditto */
913                 if (channel_cancel_lport_listener(&fwd, fwd.connect_port,
914                     &options.fwd_opts) == -1)
915                         error_reason = "port not found";
916         }
917
918         if (error_reason == NULL) {
919                 buffer_put_int(r, MUX_S_OK);
920                 buffer_put_int(r, rid);
921
922                 free(found_fwd->listen_host);
923                 free(found_fwd->listen_path);
924                 free(found_fwd->connect_host);
925                 free(found_fwd->connect_path);
926                 found_fwd->listen_host = found_fwd->connect_host = NULL;
927                 found_fwd->listen_path = found_fwd->connect_path = NULL;
928                 found_fwd->listen_port = found_fwd->connect_port = 0;
929         } else {
930                 buffer_put_int(r, MUX_S_FAILURE);
931                 buffer_put_int(r, rid);
932                 buffer_put_cstring(r, error_reason);
933         }
934  out:
935         free(fwd_desc);
936         free(listen_addr);
937         free(connect_addr);
938
939         return ret;
940 }
941
942 static int
943 process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
944 {
945         Channel *nc;
946         char *reserved, *chost;
947         u_int cport, i, j;
948         int new_fd[2];
949         struct mux_stdio_confirm_ctx *cctx;
950
951         chost = reserved = NULL;
952         if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
953            (chost = buffer_get_string_ret(m, NULL)) == NULL ||
954             buffer_get_int_ret(&cport, m) != 0) {
955                 free(reserved);
956                 free(chost);
957                 error("%s: malformed message", __func__);
958                 return -1;
959         }
960         free(reserved);
961
962         debug2("%s: channel %d: request stdio fwd to %s:%u",
963             __func__, c->self, chost, cport);
964
965         /* Gather fds from client */
966         for(i = 0; i < 2; i++) {
967                 if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
968                         error("%s: failed to receive fd %d from slave",
969                             __func__, i);
970                         for (j = 0; j < i; j++)
971                                 close(new_fd[j]);
972                         free(chost);
973
974                         /* prepare reply */
975                         buffer_put_int(r, MUX_S_FAILURE);
976                         buffer_put_int(r, rid);
977                         buffer_put_cstring(r,
978                             "did not receive file descriptors");
979                         return -1;
980                 }
981         }
982
983         debug3("%s: got fds stdin %d, stdout %d", __func__,
984             new_fd[0], new_fd[1]);
985
986         /* XXX support multiple child sessions in future */
987         if (c->remote_id != -1) {
988                 debug2("%s: session already open", __func__);
989                 /* prepare reply */
990                 buffer_put_int(r, MUX_S_FAILURE);
991                 buffer_put_int(r, rid);
992                 buffer_put_cstring(r, "Multiple sessions not supported");
993  cleanup:
994                 close(new_fd[0]);
995                 close(new_fd[1]);
996                 free(chost);
997                 return 0;
998         }
999
1000         if (options.control_master == SSHCTL_MASTER_ASK ||
1001             options.control_master == SSHCTL_MASTER_AUTO_ASK) {
1002                 if (!ask_permission("Allow forward to %s:%u? ",
1003                     chost, cport)) {
1004                         debug2("%s: stdio fwd refused by user", __func__);
1005                         /* prepare reply */
1006                         buffer_put_int(r, MUX_S_PERMISSION_DENIED);
1007                         buffer_put_int(r, rid);
1008                         buffer_put_cstring(r, "Permission denied");
1009                         goto cleanup;
1010                 }
1011         }
1012
1013         /* enable nonblocking unless tty */
1014         if (!isatty(new_fd[0]))
1015                 set_nonblock(new_fd[0]);
1016         if (!isatty(new_fd[1]))
1017                 set_nonblock(new_fd[1]);
1018
1019         nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
1020
1021         nc->ctl_chan = c->self;         /* link session -> control channel */
1022         c->remote_id = nc->self;        /* link control -> session channel */
1023
1024         debug2("%s: channel_new: %d linked to control channel %d",
1025             __func__, nc->self, nc->ctl_chan);
1026
1027         channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
1028
1029         cctx = xcalloc(1, sizeof(*cctx));
1030         cctx->rid = rid;
1031         channel_register_open_confirm(nc->self, mux_stdio_confirm, cctx);
1032         c->mux_pause = 1; /* stop handling messages until open_confirm done */
1033
1034         /* reply is deferred, sent by mux_session_confirm */
1035         return 0;
1036 }
1037
1038 /* Callback on open confirmation in mux master for a mux stdio fwd session. */
1039 static void
1040 mux_stdio_confirm(int id, int success, void *arg)
1041 {
1042         struct mux_stdio_confirm_ctx *cctx = arg;
1043         Channel *c, *cc;
1044         Buffer reply;
1045
1046         if (cctx == NULL)
1047                 fatal("%s: cctx == NULL", __func__);
1048         if ((c = channel_by_id(id)) == NULL)
1049                 fatal("%s: no channel for id %d", __func__, id);
1050         if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1051                 fatal("%s: channel %d lacks control channel %d", __func__,
1052                     id, c->ctl_chan);
1053
1054         if (!success) {
1055                 debug3("%s: sending failure reply", __func__);
1056                 /* prepare reply */
1057                 buffer_init(&reply);
1058                 buffer_put_int(&reply, MUX_S_FAILURE);
1059                 buffer_put_int(&reply, cctx->rid);
1060                 buffer_put_cstring(&reply, "Session open refused by peer");
1061                 goto done;
1062         }
1063
1064         debug3("%s: sending success reply", __func__);
1065         /* prepare reply */
1066         buffer_init(&reply);
1067         buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1068         buffer_put_int(&reply, cctx->rid);
1069         buffer_put_int(&reply, c->self);
1070
1071  done:
1072         /* Send reply */
1073         buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1074         buffer_free(&reply);
1075
1076         if (cc->mux_pause <= 0)
1077                 fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1078         cc->mux_pause = 0; /* start processing messages again */
1079         c->open_confirm_ctx = NULL;
1080         free(cctx);
1081 }
1082
1083 static int
1084 process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
1085 {
1086         debug("%s: channel %d: stop listening", __func__, c->self);
1087
1088         if (options.control_master == SSHCTL_MASTER_ASK ||
1089             options.control_master == SSHCTL_MASTER_AUTO_ASK) {
1090                 if (!ask_permission("Disable further multiplexing on shared "
1091                     "connection to %s? ", host)) {
1092                         debug2("%s: stop listen refused by user", __func__);
1093                         buffer_put_int(r, MUX_S_PERMISSION_DENIED);
1094                         buffer_put_int(r, rid);
1095                         buffer_put_cstring(r, "Permission denied");
1096                         return 0;
1097                 }
1098         }
1099
1100         if (mux_listener_channel != NULL) {
1101                 channel_free(mux_listener_channel);
1102                 client_stop_mux();
1103                 free(options.control_path);
1104                 options.control_path = NULL;
1105                 mux_listener_channel = NULL;
1106                 muxserver_sock = -1;
1107         }
1108
1109         /* prepare reply */
1110         buffer_put_int(r, MUX_S_OK);
1111         buffer_put_int(r, rid);
1112
1113         return 0;
1114 }
1115
1116 /* Channel callbacks fired on read/write from mux slave fd */
1117 static int
1118 mux_master_read_cb(Channel *c)
1119 {
1120         struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
1121         Buffer in, out;
1122         const u_char *ptr;
1123         u_int type, rid, have, i;
1124         int ret = -1;
1125
1126         /* Setup ctx and  */
1127         if (c->mux_ctx == NULL) {
1128                 state = xcalloc(1, sizeof(*state));
1129                 c->mux_ctx = state;
1130                 channel_register_cleanup(c->self,
1131                     mux_master_control_cleanup_cb, 0);
1132
1133                 /* Send hello */
1134                 buffer_init(&out);
1135                 buffer_put_int(&out, MUX_MSG_HELLO);
1136                 buffer_put_int(&out, SSHMUX_VER);
1137                 /* no extensions */
1138                 buffer_put_string(&c->output, buffer_ptr(&out),
1139                     buffer_len(&out));
1140                 buffer_free(&out);
1141                 debug3("%s: channel %d: hello sent", __func__, c->self);
1142                 return 0;
1143         }
1144
1145         buffer_init(&in);
1146         buffer_init(&out);
1147
1148         /* Channel code ensures that we receive whole packets */
1149         if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
1150  malf:
1151                 error("%s: malformed message", __func__);
1152                 goto out;
1153         }
1154         buffer_append(&in, ptr, have);
1155
1156         if (buffer_get_int_ret(&type, &in) != 0)
1157                 goto malf;
1158         debug3("%s: channel %d packet type 0x%08x len %u",
1159             __func__, c->self, type, buffer_len(&in));
1160
1161         if (type == MUX_MSG_HELLO)
1162                 rid = 0;
1163         else {
1164                 if (!state->hello_rcvd) {
1165                         error("%s: expected MUX_MSG_HELLO(0x%08x), "
1166                             "received 0x%08x", __func__, MUX_MSG_HELLO, type);
1167                         goto out;
1168                 }
1169                 if (buffer_get_int_ret(&rid, &in) != 0)
1170                         goto malf;
1171         }
1172
1173         for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
1174                 if (type == mux_master_handlers[i].type) {
1175                         ret = mux_master_handlers[i].handler(rid, c, &in, &out);
1176                         break;
1177                 }
1178         }
1179         if (mux_master_handlers[i].handler == NULL) {
1180                 error("%s: unsupported mux message 0x%08x", __func__, type);
1181                 buffer_put_int(&out, MUX_S_FAILURE);
1182                 buffer_put_int(&out, rid);
1183                 buffer_put_cstring(&out, "unsupported request");
1184                 ret = 0;
1185         }
1186         /* Enqueue reply packet */
1187         if (buffer_len(&out) != 0) {
1188                 buffer_put_string(&c->output, buffer_ptr(&out),
1189                     buffer_len(&out));
1190         }
1191  out:
1192         buffer_free(&in);
1193         buffer_free(&out);
1194         return ret;
1195 }
1196
1197 void
1198 mux_exit_message(Channel *c, int exitval)
1199 {
1200         Buffer m;
1201         Channel *mux_chan;
1202
1203         debug3("%s: channel %d: exit message, exitval %d", __func__, c->self,
1204             exitval);
1205
1206         if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1207                 fatal("%s: channel %d missing mux channel %d",
1208                     __func__, c->self, c->ctl_chan);
1209
1210         /* Append exit message packet to control socket output queue */
1211         buffer_init(&m);
1212         buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
1213         buffer_put_int(&m, c->self);
1214         buffer_put_int(&m, exitval);
1215
1216         buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1217         buffer_free(&m);
1218 }
1219
1220 void
1221 mux_tty_alloc_failed(Channel *c)
1222 {
1223         Buffer m;
1224         Channel *mux_chan;
1225
1226         debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
1227
1228         if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
1229                 fatal("%s: channel %d missing mux channel %d",
1230                     __func__, c->self, c->ctl_chan);
1231
1232         /* Append exit message packet to control socket output queue */
1233         buffer_init(&m);
1234         buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
1235         buffer_put_int(&m, c->self);
1236
1237         buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
1238         buffer_free(&m);
1239 }
1240
1241 /* Prepare a mux master to listen on a Unix domain socket. */
1242 void
1243 muxserver_listen(void)
1244 {
1245         mode_t old_umask;
1246         char *orig_control_path = options.control_path;
1247         char rbuf[16+1];
1248         u_int i, r;
1249         int oerrno;
1250
1251         if (options.control_path == NULL ||
1252             options.control_master == SSHCTL_MASTER_NO)
1253                 return;
1254
1255         debug("setting up multiplex master socket");
1256
1257         /*
1258          * Use a temporary path before listen so we can pseudo-atomically
1259          * establish the listening socket in its final location to avoid
1260          * other processes racing in between bind() and listen() and hitting
1261          * an unready socket.
1262          */
1263         for (i = 0; i < sizeof(rbuf) - 1; i++) {
1264                 r = arc4random_uniform(26+26+10);
1265                 rbuf[i] = (r < 26) ? 'a' + r :
1266                     (r < 26*2) ? 'A' + r - 26 :
1267                     '0' + r - 26 - 26;
1268         }
1269         rbuf[sizeof(rbuf) - 1] = '\0';
1270         options.control_path = NULL;
1271         xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
1272         debug3("%s: temporary control path %s", __func__, options.control_path);
1273
1274         old_umask = umask(0177);
1275         muxserver_sock = unix_listener(options.control_path, 64, 0);
1276         oerrno = errno;
1277         umask(old_umask);
1278         if (muxserver_sock < 0) {
1279                 if (oerrno == EINVAL || oerrno == EADDRINUSE) {
1280                         error("ControlSocket %s already exists, "
1281                             "disabling multiplexing", options.control_path);
1282  disable_mux_master:
1283                         if (muxserver_sock != -1) {
1284                                 close(muxserver_sock);
1285                                 muxserver_sock = -1;
1286                         }
1287                         free(orig_control_path);
1288                         free(options.control_path);
1289                         options.control_path = NULL;
1290                         options.control_master = SSHCTL_MASTER_NO;
1291                         return;
1292                 } else {
1293                         /* unix_listener() logs the error */
1294                         cleanup_exit(255);
1295                 }
1296         }
1297
1298         /* Now atomically "move" the mux socket into position */
1299         if (link(options.control_path, orig_control_path) != 0) {
1300                 if (errno != EEXIST) {
1301                         fatal("%s: link mux listener %s => %s: %s", __func__, 
1302                             options.control_path, orig_control_path,
1303                             strerror(errno));
1304                 }
1305                 error("ControlSocket %s already exists, disabling multiplexing",
1306                     orig_control_path);
1307                 unlink(options.control_path);
1308                 goto disable_mux_master;
1309         }
1310         unlink(options.control_path);
1311         free(options.control_path);
1312         options.control_path = orig_control_path;
1313
1314         set_nonblock(muxserver_sock);
1315
1316         mux_listener_channel = channel_new("mux listener",
1317             SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
1318             CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1319             0, options.control_path, 1);
1320         mux_listener_channel->mux_rcb = mux_master_read_cb;
1321         debug3("%s: mux listener channel %d fd %d", __func__,
1322             mux_listener_channel->self, mux_listener_channel->sock);
1323 }
1324
1325 /* Callback on open confirmation in mux master for a mux client session. */
1326 static void
1327 mux_session_confirm(int id, int success, void *arg)
1328 {
1329         struct mux_session_confirm_ctx *cctx = arg;
1330         const char *display;
1331         Channel *c, *cc;
1332         int i;
1333         Buffer reply;
1334
1335         if (cctx == NULL)
1336                 fatal("%s: cctx == NULL", __func__);
1337         if ((c = channel_by_id(id)) == NULL)
1338                 fatal("%s: no channel for id %d", __func__, id);
1339         if ((cc = channel_by_id(c->ctl_chan)) == NULL)
1340                 fatal("%s: channel %d lacks control channel %d", __func__,
1341                     id, c->ctl_chan);
1342
1343         if (!success) {
1344                 debug3("%s: sending failure reply", __func__);
1345                 /* prepare reply */
1346                 buffer_init(&reply);
1347                 buffer_put_int(&reply, MUX_S_FAILURE);
1348                 buffer_put_int(&reply, cctx->rid);
1349                 buffer_put_cstring(&reply, "Session open refused by peer");
1350                 goto done;
1351         }
1352
1353         display = getenv("DISPLAY");
1354         if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
1355                 char *proto, *data;
1356
1357                 /* Get reasonable local authentication information. */
1358                 if (client_x11_get_proto(display, options.xauth_location,
1359                     options.forward_x11_trusted, options.forward_x11_timeout,
1360                     &proto, &data) == 0) {
1361                         /* Request forwarding with authentication spoofing. */
1362                         debug("Requesting X11 forwarding with authentication "
1363                             "spoofing.");
1364                         x11_request_forwarding_with_spoofing(id, display, proto,
1365                             data, 1);
1366                         /* XXX exit_on_forward_failure */
1367                         client_expect_confirm(id, "X11 forwarding",
1368                             CONFIRM_WARN);
1369                 }
1370         }
1371
1372         if (cctx->want_agent_fwd && options.forward_agent) {
1373                 debug("Requesting authentication agent forwarding.");
1374                 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1375                 packet_send();
1376         }
1377
1378         client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
1379             cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
1380
1381         debug3("%s: sending success reply", __func__);
1382         /* prepare reply */
1383         buffer_init(&reply);
1384         buffer_put_int(&reply, MUX_S_SESSION_OPENED);
1385         buffer_put_int(&reply, cctx->rid);
1386         buffer_put_int(&reply, c->self);
1387
1388  done:
1389         /* Send reply */
1390         buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
1391         buffer_free(&reply);
1392
1393         if (cc->mux_pause <= 0)
1394                 fatal("%s: mux_pause %d", __func__, cc->mux_pause);
1395         cc->mux_pause = 0; /* start processing messages again */
1396         c->open_confirm_ctx = NULL;
1397         buffer_free(&cctx->cmd);
1398         free(cctx->term);
1399         if (cctx->env != NULL) {
1400                 for (i = 0; cctx->env[i] != NULL; i++)
1401                         free(cctx->env[i]);
1402                 free(cctx->env);
1403         }
1404         free(cctx);
1405 }
1406
1407 /* ** Multiplexing client support */
1408
1409 /* Exit signal handler */
1410 static void
1411 control_client_sighandler(int signo)
1412 {
1413         muxclient_terminate = signo;
1414 }
1415
1416 /*
1417  * Relay signal handler - used to pass some signals from mux client to
1418  * mux master.
1419  */
1420 static void
1421 control_client_sigrelay(int signo)
1422 {
1423         int save_errno = errno;
1424
1425         if (muxserver_pid > 1)
1426                 kill(muxserver_pid, signo);
1427
1428         errno = save_errno;
1429 }
1430
1431 static int
1432 mux_client_read(int fd, Buffer *b, u_int need)
1433 {
1434         u_int have;
1435         ssize_t len;
1436         u_char *p;
1437         struct pollfd pfd;
1438
1439         pfd.fd = fd;
1440         pfd.events = POLLIN;
1441         p = buffer_append_space(b, need);
1442         for (have = 0; have < need; ) {
1443                 if (muxclient_terminate) {
1444                         errno = EINTR;
1445                         return -1;
1446                 }
1447                 len = read(fd, p + have, need - have);
1448                 if (len < 0) {
1449                         switch (errno) {
1450 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1451                         case EWOULDBLOCK:
1452 #endif
1453                         case EAGAIN:
1454                                 (void)poll(&pfd, 1, -1);
1455                                 /* FALLTHROUGH */
1456                         case EINTR:
1457                                 continue;
1458                         default:
1459                                 return -1;
1460                         }
1461                 }
1462                 if (len == 0) {
1463                         errno = EPIPE;
1464                         return -1;
1465                 }
1466                 have += (u_int)len;
1467         }
1468         return 0;
1469 }
1470
1471 static int
1472 mux_client_write_packet(int fd, Buffer *m)
1473 {
1474         Buffer queue;
1475         u_int have, need;
1476         int oerrno, len;
1477         u_char *ptr;
1478         struct pollfd pfd;
1479
1480         pfd.fd = fd;
1481         pfd.events = POLLOUT;
1482         buffer_init(&queue);
1483         buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
1484
1485         need = buffer_len(&queue);
1486         ptr = buffer_ptr(&queue);
1487
1488         for (have = 0; have < need; ) {
1489                 if (muxclient_terminate) {
1490                         buffer_free(&queue);
1491                         errno = EINTR;
1492                         return -1;
1493                 }
1494                 len = write(fd, ptr + have, need - have);
1495                 if (len < 0) {
1496                         switch (errno) {
1497 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
1498                         case EWOULDBLOCK:
1499 #endif
1500                         case EAGAIN:
1501                                 (void)poll(&pfd, 1, -1);
1502                                 /* FALLTHROUGH */
1503                         case EINTR:
1504                                 continue;
1505                         default:
1506                                 oerrno = errno;
1507                                 buffer_free(&queue);
1508                                 errno = oerrno;
1509                                 return -1;
1510                         }
1511                 }
1512                 if (len == 0) {
1513                         buffer_free(&queue);
1514                         errno = EPIPE;
1515                         return -1;
1516                 }
1517                 have += (u_int)len;
1518         }
1519         buffer_free(&queue);
1520         return 0;
1521 }
1522
1523 static int
1524 mux_client_read_packet(int fd, Buffer *m)
1525 {
1526         Buffer queue;
1527         u_int need, have;
1528         const u_char *ptr;
1529         int oerrno;
1530
1531         buffer_init(&queue);
1532         if (mux_client_read(fd, &queue, 4) != 0) {
1533                 if ((oerrno = errno) == EPIPE)
1534                         debug3("%s: read header failed: %s", __func__,
1535                             strerror(errno));
1536                 buffer_free(&queue);
1537                 errno = oerrno;
1538                 return -1;
1539         }
1540         need = get_u32(buffer_ptr(&queue));
1541         if (mux_client_read(fd, &queue, need) != 0) {
1542                 oerrno = errno;
1543                 debug3("%s: read body failed: %s", __func__, strerror(errno));
1544                 buffer_free(&queue);
1545                 errno = oerrno;
1546                 return -1;
1547         }
1548         ptr = buffer_get_string_ptr(&queue, &have);
1549         buffer_append(m, ptr, have);
1550         buffer_free(&queue);
1551         return 0;
1552 }
1553
1554 static int
1555 mux_client_hello_exchange(int fd)
1556 {
1557         Buffer m;
1558         u_int type, ver;
1559
1560         buffer_init(&m);
1561         buffer_put_int(&m, MUX_MSG_HELLO);
1562         buffer_put_int(&m, SSHMUX_VER);
1563         /* no extensions */
1564
1565         if (mux_client_write_packet(fd, &m) != 0)
1566                 fatal("%s: write packet: %s", __func__, strerror(errno));
1567
1568         buffer_clear(&m);
1569
1570         /* Read their HELLO */
1571         if (mux_client_read_packet(fd, &m) != 0) {
1572                 buffer_free(&m);
1573                 return -1;
1574         }
1575
1576         type = buffer_get_int(&m);
1577         if (type != MUX_MSG_HELLO)
1578                 fatal("%s: expected HELLO (%u) received %u",
1579                     __func__, MUX_MSG_HELLO, type);
1580         ver = buffer_get_int(&m);
1581         if (ver != SSHMUX_VER)
1582                 fatal("Unsupported multiplexing protocol version %d "
1583                     "(expected %d)", ver, SSHMUX_VER);
1584         debug2("%s: master version %u", __func__, ver);
1585         /* No extensions are presently defined */
1586         while (buffer_len(&m) > 0) {
1587                 char *name = buffer_get_string(&m, NULL);
1588                 char *value = buffer_get_string(&m, NULL);
1589
1590                 debug2("Unrecognised master extension \"%s\"", name);
1591                 free(name);
1592                 free(value);
1593         }
1594         buffer_free(&m);
1595         return 0;
1596 }
1597
1598 static u_int
1599 mux_client_request_alive(int fd)
1600 {
1601         Buffer m;
1602         char *e;
1603         u_int pid, type, rid;
1604
1605         debug3("%s: entering", __func__);
1606
1607         buffer_init(&m);
1608         buffer_put_int(&m, MUX_C_ALIVE_CHECK);
1609         buffer_put_int(&m, muxclient_request_id);
1610
1611         if (mux_client_write_packet(fd, &m) != 0)
1612                 fatal("%s: write packet: %s", __func__, strerror(errno));
1613
1614         buffer_clear(&m);
1615
1616         /* Read their reply */
1617         if (mux_client_read_packet(fd, &m) != 0) {
1618                 buffer_free(&m);
1619                 return 0;
1620         }
1621
1622         type = buffer_get_int(&m);
1623         if (type != MUX_S_ALIVE) {
1624                 e = buffer_get_string(&m, NULL);
1625                 fatal("%s: master returned error: %s", __func__, e);
1626         }
1627
1628         if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1629                 fatal("%s: out of sequence reply: my id %u theirs %u",
1630                     __func__, muxclient_request_id, rid);
1631         pid = buffer_get_int(&m);
1632         buffer_free(&m);
1633
1634         debug3("%s: done pid = %u", __func__, pid);
1635
1636         muxclient_request_id++;
1637
1638         return pid;
1639 }
1640
1641 static void
1642 mux_client_request_terminate(int fd)
1643 {
1644         Buffer m;
1645         char *e;
1646         u_int type, rid;
1647
1648         debug3("%s: entering", __func__);
1649
1650         buffer_init(&m);
1651         buffer_put_int(&m, MUX_C_TERMINATE);
1652         buffer_put_int(&m, muxclient_request_id);
1653
1654         if (mux_client_write_packet(fd, &m) != 0)
1655                 fatal("%s: write packet: %s", __func__, strerror(errno));
1656
1657         buffer_clear(&m);
1658
1659         /* Read their reply */
1660         if (mux_client_read_packet(fd, &m) != 0) {
1661                 /* Remote end exited already */
1662                 if (errno == EPIPE) {
1663                         buffer_free(&m);
1664                         return;
1665                 }
1666                 fatal("%s: read from master failed: %s",
1667                     __func__, strerror(errno));
1668         }
1669
1670         type = buffer_get_int(&m);
1671         if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1672                 fatal("%s: out of sequence reply: my id %u theirs %u",
1673                     __func__, muxclient_request_id, rid);
1674         switch (type) {
1675         case MUX_S_OK:
1676                 break;
1677         case MUX_S_PERMISSION_DENIED:
1678                 e = buffer_get_string(&m, NULL);
1679                 fatal("Master refused termination request: %s", e);
1680         case MUX_S_FAILURE:
1681                 e = buffer_get_string(&m, NULL);
1682                 fatal("%s: termination request failed: %s", __func__, e);
1683         default:
1684                 fatal("%s: unexpected response from master 0x%08x",
1685                     __func__, type);
1686         }
1687         buffer_free(&m);
1688         muxclient_request_id++;
1689 }
1690
1691 static int
1692 mux_client_forward(int fd, int cancel_flag, u_int ftype, struct Forward *fwd)
1693 {
1694         Buffer m;
1695         char *e, *fwd_desc;
1696         u_int type, rid;
1697
1698         fwd_desc = format_forward(ftype, fwd);
1699         debug("Requesting %s %s",
1700             cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
1701         free(fwd_desc);
1702
1703         buffer_init(&m);
1704         buffer_put_int(&m, cancel_flag ? MUX_C_CLOSE_FWD : MUX_C_OPEN_FWD);
1705         buffer_put_int(&m, muxclient_request_id);
1706         buffer_put_int(&m, ftype);
1707         if (fwd->listen_path != NULL) {
1708                 buffer_put_cstring(&m, fwd->listen_path);
1709         } else {
1710                 buffer_put_cstring(&m,
1711                     fwd->listen_host == NULL ? "" :
1712                     (*fwd->listen_host == '\0' ? "*" : fwd->listen_host));
1713         }
1714         buffer_put_int(&m, fwd->listen_port);
1715         if (fwd->connect_path != NULL) {
1716                 buffer_put_cstring(&m, fwd->connect_path);
1717         } else {
1718                 buffer_put_cstring(&m,
1719                     fwd->connect_host == NULL ? "" : fwd->connect_host);
1720         }
1721         buffer_put_int(&m, fwd->connect_port);
1722
1723         if (mux_client_write_packet(fd, &m) != 0)
1724                 fatal("%s: write packet: %s", __func__, strerror(errno));
1725
1726         buffer_clear(&m);
1727
1728         /* Read their reply */
1729         if (mux_client_read_packet(fd, &m) != 0) {
1730                 buffer_free(&m);
1731                 return -1;
1732         }
1733
1734         type = buffer_get_int(&m);
1735         if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1736                 fatal("%s: out of sequence reply: my id %u theirs %u",
1737                     __func__, muxclient_request_id, rid);
1738         switch (type) {
1739         case MUX_S_OK:
1740                 break;
1741         case MUX_S_REMOTE_PORT:
1742                 if (cancel_flag)
1743                         fatal("%s: got MUX_S_REMOTE_PORT for cancel", __func__);
1744                 fwd->allocated_port = buffer_get_int(&m);
1745                 verbose("Allocated port %u for remote forward to %s:%d",
1746                     fwd->allocated_port,
1747                     fwd->connect_host ? fwd->connect_host : "",
1748                     fwd->connect_port);
1749                 if (muxclient_command == SSHMUX_COMMAND_FORWARD)
1750                         fprintf(stdout, "%i\n", fwd->allocated_port);
1751                 break;
1752         case MUX_S_PERMISSION_DENIED:
1753                 e = buffer_get_string(&m, NULL);
1754                 buffer_free(&m);
1755                 error("Master refused forwarding request: %s", e);
1756                 return -1;
1757         case MUX_S_FAILURE:
1758                 e = buffer_get_string(&m, NULL);
1759                 buffer_free(&m);
1760                 error("%s: forwarding request failed: %s", __func__, e);
1761                 return -1;
1762         default:
1763                 fatal("%s: unexpected response from master 0x%08x",
1764                     __func__, type);
1765         }
1766         buffer_free(&m);
1767
1768         muxclient_request_id++;
1769         return 0;
1770 }
1771
1772 static int
1773 mux_client_forwards(int fd, int cancel_flag)
1774 {
1775         int i, ret = 0;
1776
1777         debug3("%s: %s forwardings: %d local, %d remote", __func__,
1778             cancel_flag ? "cancel" : "request",
1779             options.num_local_forwards, options.num_remote_forwards);
1780
1781         /* XXX ExitOnForwardingFailure */
1782         for (i = 0; i < options.num_local_forwards; i++) {
1783                 if (mux_client_forward(fd, cancel_flag,
1784                     options.local_forwards[i].connect_port == 0 ?
1785                     MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
1786                     options.local_forwards + i) != 0)
1787                         ret = -1;
1788         }
1789         for (i = 0; i < options.num_remote_forwards; i++) {
1790                 if (mux_client_forward(fd, cancel_flag, MUX_FWD_REMOTE,
1791                     options.remote_forwards + i) != 0)
1792                         ret = -1;
1793         }
1794         return ret;
1795 }
1796
1797 static int
1798 mux_client_request_session(int fd)
1799 {
1800         Buffer m;
1801         char *e, *term;
1802         u_int i, rid, sid, esid, exitval, type, exitval_seen;
1803         extern char **environ;
1804         int devnull, rawmode;
1805
1806         debug3("%s: entering", __func__);
1807
1808         if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1809                 error("%s: master alive request failed", __func__);
1810                 return -1;
1811         }
1812
1813         signal(SIGPIPE, SIG_IGN);
1814
1815         if (stdin_null_flag) {
1816                 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1817                         fatal("open(/dev/null): %s", strerror(errno));
1818                 if (dup2(devnull, STDIN_FILENO) == -1)
1819                         fatal("dup2: %s", strerror(errno));
1820                 if (devnull > STDERR_FILENO)
1821                         close(devnull);
1822         }
1823
1824         term = getenv("TERM");
1825
1826         buffer_init(&m);
1827         buffer_put_int(&m, MUX_C_NEW_SESSION);
1828         buffer_put_int(&m, muxclient_request_id);
1829         buffer_put_cstring(&m, ""); /* reserved */
1830         buffer_put_int(&m, tty_flag);
1831         buffer_put_int(&m, options.forward_x11);
1832         buffer_put_int(&m, options.forward_agent);
1833         buffer_put_int(&m, subsystem_flag);
1834         buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
1835             0xffffffff : (u_int)options.escape_char);
1836         buffer_put_cstring(&m, term == NULL ? "" : term);
1837         buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
1838
1839         if (options.num_send_env > 0 && environ != NULL) {
1840                 /* Pass environment */
1841                 for (i = 0; environ[i] != NULL; i++) {
1842                         if (env_permitted(environ[i])) {
1843                                 buffer_put_cstring(&m, environ[i]);
1844                         }
1845                 }
1846         }
1847
1848         if (mux_client_write_packet(fd, &m) != 0)
1849                 fatal("%s: write packet: %s", __func__, strerror(errno));
1850
1851         /* Send the stdio file descriptors */
1852         if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
1853             mm_send_fd(fd, STDOUT_FILENO) == -1 ||
1854             mm_send_fd(fd, STDERR_FILENO) == -1)
1855                 fatal("%s: send fds failed", __func__);
1856
1857         debug3("%s: session request sent", __func__);
1858
1859         /* Read their reply */
1860         buffer_clear(&m);
1861         if (mux_client_read_packet(fd, &m) != 0) {
1862                 error("%s: read from master failed: %s",
1863                     __func__, strerror(errno));
1864                 buffer_free(&m);
1865                 return -1;
1866         }
1867
1868         type = buffer_get_int(&m);
1869         if ((rid = buffer_get_int(&m)) != muxclient_request_id)
1870                 fatal("%s: out of sequence reply: my id %u theirs %u",
1871                     __func__, muxclient_request_id, rid);
1872         switch (type) {
1873         case MUX_S_SESSION_OPENED:
1874                 sid = buffer_get_int(&m);
1875                 debug("%s: master session id: %u", __func__, sid);
1876                 break;
1877         case MUX_S_PERMISSION_DENIED:
1878                 e = buffer_get_string(&m, NULL);
1879                 buffer_free(&m);
1880                 error("Master refused session request: %s", e);
1881                 return -1;
1882         case MUX_S_FAILURE:
1883                 e = buffer_get_string(&m, NULL);
1884                 buffer_free(&m);
1885                 error("%s: session request failed: %s", __func__, e);
1886                 return -1;
1887         default:
1888                 buffer_free(&m);
1889                 error("%s: unexpected response from master 0x%08x",
1890                     __func__, type);
1891                 return -1;
1892         }
1893         muxclient_request_id++;
1894
1895         if (pledge("stdio proc tty", NULL) == -1)
1896                 fatal("%s pledge(): %s", __func__, strerror(errno));
1897         platform_pledge_mux();
1898
1899         signal(SIGHUP, control_client_sighandler);
1900         signal(SIGINT, control_client_sighandler);
1901         signal(SIGTERM, control_client_sighandler);
1902         signal(SIGWINCH, control_client_sigrelay);
1903
1904         rawmode = tty_flag;
1905         if (tty_flag)
1906                 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1907
1908         /*
1909          * Stick around until the controlee closes the client_fd.
1910          * Before it does, it is expected to write an exit message.
1911          * This process must read the value and wait for the closure of
1912          * the client_fd; if this one closes early, the multiplex master will
1913          * terminate early too (possibly losing data).
1914          */
1915         for (exitval = 255, exitval_seen = 0;;) {
1916                 buffer_clear(&m);
1917                 if (mux_client_read_packet(fd, &m) != 0)
1918                         break;
1919                 type = buffer_get_int(&m);
1920                 switch (type) {
1921                 case MUX_S_TTY_ALLOC_FAIL:
1922                         if ((esid = buffer_get_int(&m)) != sid)
1923                                 fatal("%s: tty alloc fail on unknown session: "
1924                                     "my id %u theirs %u",
1925                                     __func__, sid, esid);
1926                         leave_raw_mode(options.request_tty ==
1927                             REQUEST_TTY_FORCE);
1928                         rawmode = 0;
1929                         continue;
1930                 case MUX_S_EXIT_MESSAGE:
1931                         if ((esid = buffer_get_int(&m)) != sid)
1932                                 fatal("%s: exit on unknown session: "
1933                                     "my id %u theirs %u",
1934                                     __func__, sid, esid);
1935                         if (exitval_seen)
1936                                 fatal("%s: exitval sent twice", __func__);
1937                         exitval = buffer_get_int(&m);
1938                         exitval_seen = 1;
1939                         continue;
1940                 default:
1941                         e = buffer_get_string(&m, NULL);
1942                         fatal("%s: master returned error: %s", __func__, e);
1943                 }
1944         }
1945
1946         close(fd);
1947         if (rawmode)
1948                 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1949
1950         if (muxclient_terminate) {
1951                 debug2("Exiting on signal %ld", (long)muxclient_terminate);
1952                 exitval = 255;
1953         } else if (!exitval_seen) {
1954                 debug2("Control master terminated unexpectedly");
1955                 exitval = 255;
1956         } else
1957                 debug2("Received exit status from master %d", exitval);
1958
1959         if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1960                 fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1961
1962         exit(exitval);
1963 }
1964
1965 static int
1966 mux_client_request_stdio_fwd(int fd)
1967 {
1968         Buffer m;
1969         char *e;
1970         u_int type, rid, sid;
1971         int devnull;
1972
1973         debug3("%s: entering", __func__);
1974
1975         if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
1976                 error("%s: master alive request failed", __func__);
1977                 return -1;
1978         }
1979
1980         signal(SIGPIPE, SIG_IGN);
1981
1982         if (stdin_null_flag) {
1983                 if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1984                         fatal("open(/dev/null): %s", strerror(errno));
1985                 if (dup2(devnull, STDIN_FILENO) == -1)
1986                         fatal("dup2: %s", strerror(errno));
1987                 if (devnull > STDERR_FILENO)
1988                         close(devnull);
1989         }
1990
1991         buffer_init(&m);
1992         buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
1993         buffer_put_int(&m, muxclient_request_id);
1994         buffer_put_cstring(&m, ""); /* reserved */
1995         buffer_put_cstring(&m, stdio_forward_host);
1996         buffer_put_int(&m, stdio_forward_port);
1997
1998         if (mux_client_write_packet(fd, &m) != 0)
1999                 fatal("%s: write packet: %s", __func__, strerror(errno));
2000
2001         /* Send the stdio file descriptors */
2002         if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
2003             mm_send_fd(fd, STDOUT_FILENO) == -1)
2004                 fatal("%s: send fds failed", __func__);
2005
2006         if (pledge("stdio proc tty", NULL) == -1)
2007                 fatal("%s pledge(): %s", __func__, strerror(errno));
2008         platform_pledge_mux();
2009
2010         debug3("%s: stdio forward request sent", __func__);
2011
2012         /* Read their reply */
2013         buffer_clear(&m);
2014
2015         if (mux_client_read_packet(fd, &m) != 0) {
2016                 error("%s: read from master failed: %s",
2017                     __func__, strerror(errno));
2018                 buffer_free(&m);
2019                 return -1;
2020         }
2021
2022         type = buffer_get_int(&m);
2023         if ((rid = buffer_get_int(&m)) != muxclient_request_id)
2024                 fatal("%s: out of sequence reply: my id %u theirs %u",
2025                     __func__, muxclient_request_id, rid);
2026         switch (type) {
2027         case MUX_S_SESSION_OPENED:
2028                 sid = buffer_get_int(&m);
2029                 debug("%s: master session id: %u", __func__, sid);
2030                 break;
2031         case MUX_S_PERMISSION_DENIED:
2032                 e = buffer_get_string(&m, NULL);
2033                 buffer_free(&m);
2034                 fatal("Master refused stdio forwarding request: %s", e);
2035         case MUX_S_FAILURE:
2036                 e = buffer_get_string(&m, NULL);
2037                 buffer_free(&m);
2038                 fatal("Stdio forwarding request failed: %s", e);
2039         default:
2040                 buffer_free(&m);
2041                 error("%s: unexpected response from master 0x%08x",
2042                     __func__, type);
2043                 return -1;
2044         }
2045         muxclient_request_id++;
2046
2047         signal(SIGHUP, control_client_sighandler);
2048         signal(SIGINT, control_client_sighandler);
2049         signal(SIGTERM, control_client_sighandler);
2050         signal(SIGWINCH, control_client_sigrelay);
2051
2052         /*
2053          * Stick around until the controlee closes the client_fd.
2054          */
2055         buffer_clear(&m);
2056         if (mux_client_read_packet(fd, &m) != 0) {
2057                 if (errno == EPIPE ||
2058                     (errno == EINTR && muxclient_terminate != 0))
2059                         return 0;
2060                 fatal("%s: mux_client_read_packet: %s",
2061                     __func__, strerror(errno));
2062         }
2063         fatal("%s: master returned unexpected message %u", __func__, type);
2064 }
2065
2066 static void
2067 mux_client_request_stop_listening(int fd)
2068 {
2069         Buffer m;
2070         char *e;
2071         u_int type, rid;
2072
2073         debug3("%s: entering", __func__);
2074
2075         buffer_init(&m);
2076         buffer_put_int(&m, MUX_C_STOP_LISTENING);
2077         buffer_put_int(&m, muxclient_request_id);
2078
2079         if (mux_client_write_packet(fd, &m) != 0)
2080                 fatal("%s: write packet: %s", __func__, strerror(errno));
2081
2082         buffer_clear(&m);
2083
2084         /* Read their reply */
2085         if (mux_client_read_packet(fd, &m) != 0)
2086                 fatal("%s: read from master failed: %s",
2087                     __func__, strerror(errno));
2088
2089         type = buffer_get_int(&m);
2090         if ((rid = buffer_get_int(&m)) != muxclient_request_id)
2091                 fatal("%s: out of sequence reply: my id %u theirs %u",
2092                     __func__, muxclient_request_id, rid);
2093         switch (type) {
2094         case MUX_S_OK:
2095                 break;
2096         case MUX_S_PERMISSION_DENIED:
2097                 e = buffer_get_string(&m, NULL);
2098                 fatal("Master refused stop listening request: %s", e);
2099         case MUX_S_FAILURE:
2100                 e = buffer_get_string(&m, NULL);
2101                 fatal("%s: stop listening request failed: %s", __func__, e);
2102         default:
2103                 fatal("%s: unexpected response from master 0x%08x",
2104                     __func__, type);
2105         }
2106         buffer_free(&m);
2107         muxclient_request_id++;
2108 }
2109
2110 /* Multiplex client main loop. */
2111 void
2112 muxclient(const char *path)
2113 {
2114         struct sockaddr_un addr;
2115         socklen_t sun_len;
2116         int sock;
2117         u_int pid;
2118
2119         if (muxclient_command == 0) {
2120                 if (stdio_forward_host != NULL)
2121                         muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
2122                 else
2123                         muxclient_command = SSHMUX_COMMAND_OPEN;
2124         }
2125
2126         switch (options.control_master) {
2127         case SSHCTL_MASTER_AUTO:
2128         case SSHCTL_MASTER_AUTO_ASK:
2129                 debug("auto-mux: Trying existing master");
2130                 /* FALLTHROUGH */
2131         case SSHCTL_MASTER_NO:
2132                 break;
2133         default:
2134                 return;
2135         }
2136
2137         memset(&addr, '\0', sizeof(addr));
2138         addr.sun_family = AF_UNIX;
2139         sun_len = offsetof(struct sockaddr_un, sun_path) +
2140             strlen(path) + 1;
2141
2142         if (strlcpy(addr.sun_path, path,
2143             sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
2144                 fatal("ControlPath too long");
2145
2146         if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
2147                 fatal("%s socket(): %s", __func__, strerror(errno));
2148
2149         if (connect(sock, (struct sockaddr *)&addr, sun_len) == -1) {
2150                 switch (muxclient_command) {
2151                 case SSHMUX_COMMAND_OPEN:
2152                 case SSHMUX_COMMAND_STDIO_FWD:
2153                         break;
2154                 default:
2155                         fatal("Control socket connect(%.100s): %s", path,
2156                             strerror(errno));
2157                 }
2158                 if (errno == ECONNREFUSED &&
2159                     options.control_master != SSHCTL_MASTER_NO) {
2160                         debug("Stale control socket %.100s, unlinking", path);
2161                         unlink(path);
2162                 } else if (errno == ENOENT) {
2163                         debug("Control socket \"%.100s\" does not exist", path);
2164                 } else {
2165                         error("Control socket connect(%.100s): %s", path,
2166                             strerror(errno));
2167                 }
2168                 close(sock);
2169                 return;
2170         }
2171         set_nonblock(sock);
2172
2173         if (mux_client_hello_exchange(sock) != 0) {
2174                 error("%s: master hello exchange failed", __func__);
2175                 close(sock);
2176                 return;
2177         }
2178
2179         switch (muxclient_command) {
2180         case SSHMUX_COMMAND_ALIVE_CHECK:
2181                 if ((pid = mux_client_request_alive(sock)) == 0)
2182                         fatal("%s: master alive check failed", __func__);
2183                 fprintf(stderr, "Master running (pid=%u)\r\n", pid);
2184                 exit(0);
2185         case SSHMUX_COMMAND_TERMINATE:
2186                 mux_client_request_terminate(sock);
2187                 fprintf(stderr, "Exit request sent.\r\n");
2188                 exit(0);
2189         case SSHMUX_COMMAND_FORWARD:
2190                 if (mux_client_forwards(sock, 0) != 0)
2191                         fatal("%s: master forward request failed", __func__);
2192                 exit(0);
2193         case SSHMUX_COMMAND_OPEN:
2194                 if (mux_client_forwards(sock, 0) != 0) {
2195                         error("%s: master forward request failed", __func__);
2196                         return;
2197                 }
2198                 mux_client_request_session(sock);
2199                 return;
2200         case SSHMUX_COMMAND_STDIO_FWD:
2201                 mux_client_request_stdio_fwd(sock);
2202                 exit(0);
2203         case SSHMUX_COMMAND_STOP:
2204                 mux_client_request_stop_listening(sock);
2205                 fprintf(stderr, "Stop listening request sent.\r\n");
2206                 exit(0);
2207         case SSHMUX_COMMAND_CANCEL_FWD:
2208                 if (mux_client_forwards(sock, 1) != 0)
2209                         error("%s: master cancel forward request failed",
2210                             __func__);
2211                 exit(0);
2212         default:
2213                 fatal("unrecognised muxclient_command %d", muxclient_command);
2214         }
2215 }