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