[BACK]Return to mux.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/mux.c, Revision 1.50

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