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