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