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