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

Annotation of src/usr.bin/tmux/client.c, Revision 1.147

1.147   ! nicm        1: /* $OpenBSD: client.c,v 1.146 2020/06/01 09:43:00 nicm Exp $ */
1.1       nicm        2:
                      3: /*
1.113     nicm        4:  * Copyright (c) 2007 Nicholas Marriott <nicholas.marriott@gmail.com>
1.1       nicm        5:  *
                      6:  * Permission to use, copy, modify, and distribute this software for any
                      7:  * purpose with or without fee is hereby granted, provided that the above
                      8:  * copyright notice and this permission notice appear in all copies.
                      9:  *
                     10:  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
                     11:  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
                     12:  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
                     13:  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
                     14:  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
                     15:  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
                     16:  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
                     17:  */
                     18:
                     19: #include <sys/types.h>
                     20: #include <sys/socket.h>
1.144     nicm       21: #include <sys/uio.h>
1.1       nicm       22: #include <sys/un.h>
                     23: #include <sys/wait.h>
                     24:
                     25: #include <errno.h>
1.30      nicm       26: #include <event.h>
1.80      nicm       27: #include <fcntl.h>
1.99      nicm       28: #include <imsg.h>
1.85      nicm       29: #include <signal.h>
1.1       nicm       30: #include <stdlib.h>
                     31: #include <string.h>
                     32: #include <unistd.h>
                     33:
                     34: #include "tmux.h"
                     35:
1.114     nicm       36: static struct tmuxproc *client_proc;
                     37: static struct tmuxpeer *client_peer;
                     38: static int              client_flags;
                     39: static enum {
1.52      nicm       40:        CLIENT_EXIT_NONE,
                     41:        CLIENT_EXIT_DETACHED,
                     42:        CLIENT_EXIT_DETACHED_HUP,
                     43:        CLIENT_EXIT_LOST_TTY,
                     44:        CLIENT_EXIT_TERMINATED,
                     45:        CLIENT_EXIT_LOST_SERVER,
                     46:        CLIENT_EXIT_EXITED,
                     47:        CLIENT_EXIT_SERVER_EXITED,
1.147   ! nicm       48:        CLIENT_EXIT_MESSAGE_PROVIDED
1.52      nicm       49: } client_exitreason = CLIENT_EXIT_NONE;
1.133     nicm       50: static int              client_exitflag;
1.114     nicm       51: static int              client_exitval;
                     52: static enum msgtype     client_exittype;
                     53: static const char      *client_exitsession;
1.147   ! nicm       54: static char            *client_exitmessage;
1.115     nicm       55: static const char      *client_execshell;
                     56: static const char      *client_execcmd;
1.114     nicm       57: static int              client_attached;
1.132     nicm       58: static struct client_files client_files = RB_INITIALIZER(&client_files);
1.114     nicm       59:
                     60: static __dead void      client_exec(const char *,const char *);
                     61: static int              client_get_lock(char *);
                     62: static int              client_connect(struct event_base *, const char *, int);
1.142     nicm       63: static void             client_send_identify(const char *, const char *, int);
1.114     nicm       64: static void             client_signal(int);
                     65: static void             client_dispatch(struct imsg *, void *);
                     66: static void             client_dispatch_attached(struct imsg *);
1.121     nicm       67: static void             client_dispatch_wait(struct imsg *);
1.114     nicm       68: static const char      *client_exit_message(void);
1.25      nicm       69:
1.49      nicm       70: /*
                     71:  * Get server create lock. If already held then server start is happening in
1.110     nicm       72:  * another client, so block until the lock is released and return -2 to
                     73:  * retry. Return -1 on failure to continue and start the server anyway.
1.49      nicm       74:  */
1.114     nicm       75: static int
1.49      nicm       76: client_get_lock(char *lockfile)
                     77: {
                     78:        int lockfd;
                     79:
1.110     nicm       80:        log_debug("lock file is %s", lockfile);
                     81:
1.109     nicm       82:        if ((lockfd = open(lockfile, O_WRONLY|O_CREAT, 0600)) == -1) {
1.110     nicm       83:                log_debug("open failed: %s", strerror(errno));
                     84:                return (-1);
1.109     nicm       85:        }
1.49      nicm       86:
1.82      nicm       87:        if (flock(lockfd, LOCK_EX|LOCK_NB) == -1) {
                     88:                log_debug("flock failed: %s", strerror(errno));
                     89:                if (errno != EAGAIN)
                     90:                        return (lockfd);
                     91:                while (flock(lockfd, LOCK_EX) == -1 && errno == EINTR)
1.49      nicm       92:                        /* nothing */;
                     93:                close(lockfd);
1.110     nicm       94:                return (-2);
1.49      nicm       95:        }
1.82      nicm       96:        log_debug("flock succeeded");
1.49      nicm       97:
                     98:        return (lockfd);
                     99: }
                    100:
1.46      nicm      101: /* Connect client to server. */
1.114     nicm      102: static int
1.138     nicm      103: client_connect(struct event_base *base, const char *path, int flags)
1.1       nicm      104: {
1.26      nicm      105:        struct sockaddr_un      sa;
                    106:        size_t                  size;
1.82      nicm      107:        int                     fd, lockfd = -1, locked = 0;
                    108:        char                   *lockfile = NULL;
1.1       nicm      109:
                    110:        memset(&sa, 0, sizeof sa);
                    111:        sa.sun_family = AF_UNIX;
                    112:        size = strlcpy(sa.sun_path, path, sizeof sa.sun_path);
                    113:        if (size >= sizeof sa.sun_path) {
                    114:                errno = ENAMETOOLONG;
1.46      nicm      115:                return (-1);
1.1       nicm      116:        }
1.82      nicm      117:        log_debug("socket is %s", path);
1.1       nicm      118:
1.49      nicm      119: retry:
1.10      nicm      120:        if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
1.109     nicm      121:                return (-1);
1.1       nicm      122:
1.82      nicm      123:        log_debug("trying connect");
1.109     nicm      124:        if (connect(fd, (struct sockaddr *)&sa, sizeof sa) == -1) {
1.82      nicm      125:                log_debug("connect failed: %s", strerror(errno));
1.49      nicm      126:                if (errno != ECONNREFUSED && errno != ENOENT)
                    127:                        goto failed;
1.138     nicm      128:                if (~flags & CLIENT_STARTSERVER)
1.46      nicm      129:                        goto failed;
1.49      nicm      130:                close(fd);
                    131:
1.82      nicm      132:                if (!locked) {
                    133:                        xasprintf(&lockfile, "%s.lock", path);
1.110     nicm      134:                        if ((lockfd = client_get_lock(lockfile)) < 0) {
                    135:                                log_debug("didn't get lock (%d)", lockfd);
                    136:
1.82      nicm      137:                                free(lockfile);
1.110     nicm      138:                                lockfile = NULL;
                    139:
                    140:                                if (lockfd == -2)
                    141:                                        goto retry;
1.82      nicm      142:                        }
1.110     nicm      143:                        log_debug("got lock (%d)", lockfd);
1.82      nicm      144:
                    145:                        /*
                    146:                         * Always retry at least once, even if we got the lock,
                    147:                         * because another client could have taken the lock,
                    148:                         * started the server and released the lock between our
                    149:                         * connect() and flock().
                    150:                         */
                    151:                        locked = 1;
1.49      nicm      152:                        goto retry;
1.78      nicm      153:                }
1.82      nicm      154:
1.110     nicm      155:                if (lockfd >= 0 && unlink(path) != 0 && errno != ENOENT) {
1.78      nicm      156:                        free(lockfile);
                    157:                        close(lockfd);
1.49      nicm      158:                        return (-1);
1.78      nicm      159:                }
1.138     nicm      160:                fd = server_start(client_proc, flags, base, lockfd, lockfile);
1.82      nicm      161:        }
1.95      nicm      162:
1.110     nicm      163:        if (locked && lockfd >= 0) {
1.58      nicm      164:                free(lockfile);
1.49      nicm      165:                close(lockfd);
1.1       nicm      166:        }
1.47      nicm      167:        setblocking(fd, 0);
1.46      nicm      168:        return (fd);
                    169:
                    170: failed:
1.95      nicm      171:        if (locked) {
                    172:                free(lockfile);
                    173:                close(lockfd);
                    174:        }
1.46      nicm      175:        close(fd);
                    176:        return (-1);
                    177: }
                    178:
1.52      nicm      179: /* Get exit string from reason number. */
                    180: const char *
                    181: client_exit_message(void)
                    182: {
1.73      nicm      183:        static char msg[256];
                    184:
1.52      nicm      185:        switch (client_exitreason) {
                    186:        case CLIENT_EXIT_NONE:
                    187:                break;
                    188:        case CLIENT_EXIT_DETACHED:
1.73      nicm      189:                if (client_exitsession != NULL) {
                    190:                        xsnprintf(msg, sizeof msg, "detached "
                    191:                            "(from session %s)", client_exitsession);
                    192:                        return (msg);
                    193:                }
1.52      nicm      194:                return ("detached");
                    195:        case CLIENT_EXIT_DETACHED_HUP:
1.73      nicm      196:                if (client_exitsession != NULL) {
                    197:                        xsnprintf(msg, sizeof msg, "detached and SIGHUP "
                    198:                            "(from session %s)", client_exitsession);
                    199:                        return (msg);
                    200:                }
1.52      nicm      201:                return ("detached and SIGHUP");
                    202:        case CLIENT_EXIT_LOST_TTY:
                    203:                return ("lost tty");
                    204:        case CLIENT_EXIT_TERMINATED:
                    205:                return ("terminated");
                    206:        case CLIENT_EXIT_LOST_SERVER:
1.131     nicm      207:                return ("server exited unexpectedly");
1.52      nicm      208:        case CLIENT_EXIT_EXITED:
                    209:                return ("exited");
                    210:        case CLIENT_EXIT_SERVER_EXITED:
                    211:                return ("server exited");
1.147   ! nicm      212:        case CLIENT_EXIT_MESSAGE_PROVIDED:
        !           213:                return (client_exitmessage);
1.52      nicm      214:        }
                    215:        return ("unknown reason");
                    216: }
                    217:
1.133     nicm      218: /* Exit if all streams flushed. */
                    219: static void
                    220: client_exit(void)
                    221: {
                    222:        struct client_file      *cf;
                    223:        size_t                   left;
                    224:        int                      waiting = 0;
                    225:
                    226:        RB_FOREACH (cf, client_files, &client_files) {
                    227:                if (cf->event == NULL)
                    228:                        continue;
                    229:                left = EVBUFFER_LENGTH(cf->event->output);
                    230:                if (left != 0) {
                    231:                        waiting++;
                    232:                        log_debug("file %u %zu bytes left", cf->stream, left);
                    233:                }
                    234:        }
                    235:        if (waiting == 0)
                    236:                proc_exit(client_proc);
                    237: }
                    238:
1.46      nicm      239: /* Client main loop. */
                    240: int
1.142     nicm      241: client_main(struct event_base *base, int argc, char **argv, int flags, int feat)
1.46      nicm      242: {
1.129     nicm      243:        struct cmd_parse_result *pr;
1.132     nicm      244:        struct msg_command      *data;
1.138     nicm      245:        int                      fd, i;
1.98      nicm      246:        const char              *ttynam, *cwd;
1.48      nicm      247:        pid_t                    ppid;
1.46      nicm      248:        enum msgtype             msg;
1.56      nicm      249:        struct termios           tio, saved_tio;
1.70      nicm      250:        size_t                   size;
1.46      nicm      251:
1.99      nicm      252:        /* Ignore SIGCHLD now or daemon() in the server will leave a zombie. */
                    253:        signal(SIGCHLD, SIG_IGN);
                    254:
1.46      nicm      255:        /* Set up the initial command. */
1.121     nicm      256:        if (shell_command != NULL) {
1.46      nicm      257:                msg = MSG_SHELL;
1.139     nicm      258:                flags |= CLIENT_STARTSERVER;
1.46      nicm      259:        } else if (argc == 0) {
                    260:                msg = MSG_COMMAND;
1.138     nicm      261:                flags |= CLIENT_STARTSERVER;
1.46      nicm      262:        } else {
                    263:                msg = MSG_COMMAND;
                    264:
                    265:                /*
                    266:                 * It sucks parsing the command string twice (in client and
                    267:                 * later in server) but it is necessary to get the start server
                    268:                 * flag.
                    269:                 */
1.129     nicm      270:                pr = cmd_parse_from_arguments(argc, argv, NULL);
                    271:                if (pr->status == CMD_PARSE_SUCCESS) {
1.141     nicm      272:                        if (cmd_list_any_have(pr->cmdlist, CMD_STARTSERVER))
                    273:                                flags |= CLIENT_STARTSERVER;
1.129     nicm      274:                        cmd_list_free(pr->cmdlist);
                    275:                } else
                    276:                        free(pr->error);
1.46      nicm      277:        }
                    278:
1.138     nicm      279:        /* Save the flags. */
                    280:        client_flags = flags;
                    281:
1.109     nicm      282:        /* Create client process structure (starts logging). */
1.122     nicm      283:        client_proc = proc_start("client");
                    284:        proc_set_signals(client_proc, client_signal);
1.109     nicm      285:
1.82      nicm      286:        /* Initialize the client socket and start the server. */
1.138     nicm      287:        fd = client_connect(base, socket_path, client_flags);
1.46      nicm      288:        if (fd == -1) {
1.87      nicm      289:                if (errno == ECONNREFUSED) {
                    290:                        fprintf(stderr, "no server running on %s\n",
                    291:                            socket_path);
                    292:                } else {
                    293:                        fprintf(stderr, "error connecting to %s (%s)\n",
                    294:                            socket_path, strerror(errno));
                    295:                }
1.46      nicm      296:                return (1);
                    297:        }
1.121     nicm      298:        client_peer = proc_add_peer(client_proc, fd, client_dispatch, NULL);
1.99      nicm      299:
1.97      nicm      300:        /* Save these before pledge(). */
1.128     nicm      301:        if ((cwd = find_cwd()) == NULL && (cwd = find_home()) == NULL)
1.126     nicm      302:                cwd = "/";
1.97      nicm      303:        if ((ttynam = ttyname(STDIN_FILENO)) == NULL)
                    304:                ttynam = "";
                    305:
                    306:        /*
                    307:         * Drop privileges for client. "proc exec" is needed for -c and for
                    308:         * locking (which uses system(3)).
                    309:         *
                    310:         * "tty" is needed to restore termios(4) and also for some reason -CC
                    311:         * does not work properly without it (input is not recognised).
                    312:         *
                    313:         * "sendfd" is dropped later in client_dispatch_wait().
                    314:         */
1.132     nicm      315:        if (pledge(
                    316:            "stdio rpath wpath cpath unix sendfd proc exec tty",
                    317:            NULL) != 0)
1.97      nicm      318:                fatal("pledge failed");
                    319:
                    320:        /* Free stuff that is not used in the client. */
1.119     nicm      321:        if (ptm_fd != -1)
                    322:                close(ptm_fd);
1.100     nicm      323:        options_free(global_options);
                    324:        options_free(global_s_options);
                    325:        options_free(global_w_options);
1.101     nicm      326:        environ_free(global_environ);
1.46      nicm      327:
1.132     nicm      328:        /* Set up control mode. */
1.93      nicm      329:        if (client_flags & CLIENT_CONTROLCONTROL) {
1.118     nicm      330:                if (tcgetattr(STDIN_FILENO, &saved_tio) != 0) {
                    331:                        fprintf(stderr, "tcgetattr failed: %s\n",
                    332:                            strerror(errno));
                    333:                        return (1);
                    334:                }
1.56      nicm      335:                cfmakeraw(&tio);
                    336:                tio.c_iflag = ICRNL|IXANY;
                    337:                tio.c_oflag = OPOST|ONLCR;
                    338:                tio.c_lflag = NOKERNINFO;
                    339:                tio.c_cflag = CREAD|CS8|HUPCL;
                    340:                tio.c_cc[VMIN] = 1;
                    341:                tio.c_cc[VTIME] = 0;
                    342:                cfsetispeed(&tio, cfgetispeed(&saved_tio));
                    343:                cfsetospeed(&tio, cfgetospeed(&saved_tio));
                    344:                tcsetattr(STDIN_FILENO, TCSANOW, &tio);
                    345:        }
1.1       nicm      346:
1.71      nicm      347:        /* Send identify messages. */
1.142     nicm      348:        client_send_identify(ttynam, cwd, feat);
1.1       nicm      349:
1.46      nicm      350:        /* Send first command. */
                    351:        if (msg == MSG_COMMAND) {
1.70      nicm      352:                /* How big is the command? */
                    353:                size = 0;
                    354:                for (i = 0; i < argc; i++)
                    355:                        size += strlen(argv[i]) + 1;
1.124     nicm      356:                if (size > MAX_IMSGSIZE - (sizeof *data)) {
                    357:                        fprintf(stderr, "command too long\n");
                    358:                        return (1);
                    359:                }
1.70      nicm      360:                data = xmalloc((sizeof *data) + size);
1.46      nicm      361:
                    362:                /* Prepare command for server. */
1.70      nicm      363:                data->argc = argc;
1.83      nicm      364:                if (cmd_pack_argv(argc, argv, (char *)(data + 1), size) != 0) {
1.55      nicm      365:                        fprintf(stderr, "command too long\n");
1.70      nicm      366:                        free(data);
1.46      nicm      367:                        return (1);
                    368:                }
1.70      nicm      369:                size += sizeof *data;
1.46      nicm      370:
1.70      nicm      371:                /* Send the command. */
1.99      nicm      372:                if (proc_send(client_peer, msg, -1, data, size) != 0) {
1.70      nicm      373:                        fprintf(stderr, "failed to send command\n");
                    374:                        free(data);
                    375:                        return (1);
                    376:                }
                    377:                free(data);
1.46      nicm      378:        } else if (msg == MSG_SHELL)
1.99      nicm      379:                proc_send(client_peer, msg, -1, NULL, 0);
1.1       nicm      380:
1.99      nicm      381:        /* Start main loop. */
                    382:        proc_loop(client_proc, NULL);
1.46      nicm      383:
1.115     nicm      384:        /* Run command if user requested exec, instead of exiting. */
                    385:        if (client_exittype == MSG_EXEC) {
                    386:                if (client_flags & CLIENT_CONTROLCONTROL)
                    387:                        tcsetattr(STDOUT_FILENO, TCSAFLUSH, &saved_tio);
                    388:                client_exec(client_execshell, client_execcmd);
                    389:        }
                    390:
1.146     nicm      391:        /* Restore streams to blocking. */
                    392:        setblocking(STDIN_FILENO, 1);
                    393:        setblocking(STDOUT_FILENO, 1);
                    394:        setblocking(STDERR_FILENO, 1);
                    395:
1.46      nicm      396:        /* Print the exit message, if any, and exit. */
1.48      nicm      397:        if (client_attached) {
1.93      nicm      398:                if (client_exitreason != CLIENT_EXIT_NONE)
1.52      nicm      399:                        printf("[%s]\n", client_exit_message());
1.48      nicm      400:
                    401:                ppid = getppid();
                    402:                if (client_exittype == MSG_DETACHKILL && ppid > 1)
                    403:                        kill(ppid, SIGHUP);
1.146     nicm      404:        } else if (client_flags & CLIENT_CONTROL) {
1.68      nicm      405:                if (client_exitreason != CLIENT_EXIT_NONE)
                    406:                        printf("%%exit %s\n", client_exit_message());
                    407:                else
                    408:                        printf("%%exit\n");
1.146     nicm      409:                if (client_flags & CLIENT_CONTROLCONTROL) {
                    410:                        printf("\033\\");
                    411:                        tcsetattr(STDOUT_FILENO, TCSAFLUSH, &saved_tio);
                    412:                }
1.112     nicm      413:        } else if (client_exitreason != CLIENT_EXIT_NONE)
1.109     nicm      414:                fprintf(stderr, "%s\n", client_exit_message());
1.46      nicm      415:        return (client_exitval);
1.1       nicm      416: }
                    417:
1.71      nicm      418: /* Send identify messages to server. */
1.114     nicm      419: static void
1.142     nicm      420: client_send_identify(const char *ttynam, const char *cwd, int feat)
1.26      nicm      421: {
1.90      nicm      422:        const char       *s;
1.71      nicm      423:        char            **ss;
1.91      nicm      424:        size_t            sslen;
1.93      nicm      425:        int               fd, flags = client_flags;
1.90      nicm      426:        pid_t             pid;
1.71      nicm      427:
1.99      nicm      428:        proc_send(client_peer, MSG_IDENTIFY_FLAGS, -1, &flags, sizeof flags);
1.71      nicm      429:
                    430:        if ((s = getenv("TERM")) == NULL)
                    431:                s = "";
1.99      nicm      432:        proc_send(client_peer, MSG_IDENTIFY_TERM, -1, s, strlen(s) + 1);
1.142     nicm      433:        proc_send(client_peer, MSG_IDENTIFY_FEATURES, -1, &feat, sizeof feat);
1.71      nicm      434:
1.107     nicm      435:        proc_send(client_peer, MSG_IDENTIFY_TTYNAME, -1, ttynam,
                    436:            strlen(ttynam) + 1);
1.99      nicm      437:        proc_send(client_peer, MSG_IDENTIFY_CWD, -1, cwd, strlen(cwd) + 1);
1.26      nicm      438:
1.50      nicm      439:        if ((fd = dup(STDIN_FILENO)) == -1)
                    440:                fatal("dup failed");
1.99      nicm      441:        proc_send(client_peer, MSG_IDENTIFY_STDIN, fd, NULL, 0);
1.145     nicm      442:        if ((fd = dup(STDOUT_FILENO)) == -1)
                    443:                fatal("dup failed");
                    444:        proc_send(client_peer, MSG_IDENTIFY_STDOUT, fd, NULL, 0);
1.90      nicm      445:
                    446:        pid = getpid();
1.99      nicm      447:        proc_send(client_peer, MSG_IDENTIFY_CLIENTPID, -1, &pid, sizeof pid);
1.26      nicm      448:
1.91      nicm      449:        for (ss = environ; *ss != NULL; ss++) {
                    450:                sslen = strlen(*ss) + 1;
1.107     nicm      451:                if (sslen > MAX_IMSGSIZE - IMSG_HEADER_SIZE)
                    452:                        continue;
                    453:                proc_send(client_peer, MSG_IDENTIFY_ENVIRON, -1, *ss, sslen);
1.91      nicm      454:        }
1.75      nicm      455:
1.99      nicm      456:        proc_send(client_peer, MSG_IDENTIFY_DONE, -1, NULL, 0);
1.30      nicm      457: }
                    458:
1.132     nicm      459: /* File write error callback. */
1.114     nicm      460: static void
1.132     nicm      461: client_write_error_callback(__unused struct bufferevent *bev,
                    462:     __unused short what, void *arg)
1.54      nicm      463: {
1.132     nicm      464:        struct client_file      *cf = arg;
1.54      nicm      465:
1.132     nicm      466:        log_debug("write error file %d", cf->stream);
                    467:
                    468:        bufferevent_free(cf->event);
                    469:        cf->event = NULL;
                    470:
                    471:        close(cf->fd);
                    472:        cf->fd = -1;
1.134     nicm      473:
                    474:        if (client_exitflag)
                    475:                client_exit();
1.132     nicm      476: }
                    477:
                    478: /* File write callback. */
                    479: static void
                    480: client_write_callback(__unused struct bufferevent *bev, void *arg)
                    481: {
                    482:        struct client_file      *cf = arg;
                    483:
                    484:        if (cf->closed && EVBUFFER_LENGTH(cf->event->output) == 0) {
                    485:                bufferevent_free(cf->event);
                    486:                close(cf->fd);
                    487:                RB_REMOVE(client_files, &client_files, cf);
                    488:                file_free(cf);
                    489:        }
1.133     nicm      490:
                    491:        if (client_exitflag)
                    492:                client_exit();
1.132     nicm      493: }
                    494:
                    495: /* Open write file. */
                    496: static void
                    497: client_write_open(void *data, size_t datalen)
                    498: {
                    499:        struct msg_write_open   *msg = data;
1.135     nicm      500:        const char              *path;
1.132     nicm      501:        struct msg_write_ready   reply;
                    502:        struct client_file       find, *cf;
                    503:        const int                flags = O_NONBLOCK|O_WRONLY|O_CREAT;
                    504:        int                      error = 0;
                    505:
1.135     nicm      506:        if (datalen < sizeof *msg)
1.132     nicm      507:                fatalx("bad MSG_WRITE_OPEN size");
1.135     nicm      508:        if (datalen == sizeof *msg)
                    509:                path = "-";
                    510:        else
                    511:                path = (const char *)(msg + 1);
                    512:        log_debug("open write file %d %s", msg->stream, path);
1.132     nicm      513:
                    514:        find.stream = msg->stream;
                    515:        if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL) {
                    516:                cf = file_create(NULL, msg->stream, NULL, NULL);
                    517:                RB_INSERT(client_files, &client_files, cf);
                    518:        } else {
                    519:                error = EBADF;
                    520:                goto reply;
                    521:        }
                    522:        if (cf->closed) {
                    523:                error = EBADF;
                    524:                goto reply;
                    525:        }
                    526:
                    527:        cf->fd = -1;
                    528:        if (msg->fd == -1)
1.135     nicm      529:                cf->fd = open(path, msg->flags|flags, 0644);
1.132     nicm      530:        else {
                    531:                if (msg->fd != STDOUT_FILENO && msg->fd != STDERR_FILENO)
                    532:                        errno = EBADF;
                    533:                else {
                    534:                        cf->fd = dup(msg->fd);
1.143     nicm      535:                        if (~client_flags & CLIENT_CONTROL)
1.132     nicm      536:                                close(msg->fd); /* can only be used once */
                    537:                }
                    538:        }
                    539:        if (cf->fd == -1) {
                    540:                error = errno;
                    541:                goto reply;
                    542:        }
                    543:
                    544:        cf->event = bufferevent_new(cf->fd, NULL, client_write_callback,
                    545:            client_write_error_callback, cf);
                    546:        bufferevent_enable(cf->event, EV_WRITE);
                    547:        goto reply;
                    548:
                    549: reply:
                    550:        reply.stream = msg->stream;
                    551:        reply.error = error;
                    552:        proc_send(client_peer, MSG_WRITE_READY, -1, &reply, sizeof reply);
                    553: }
                    554:
                    555: /* Write to client file. */
                    556: static void
                    557: client_write_data(void *data, size_t datalen)
                    558: {
                    559:        struct msg_write_data   *msg = data;
                    560:        struct client_file       find, *cf;
1.135     nicm      561:        size_t                   size = datalen - sizeof *msg;
1.132     nicm      562:
1.135     nicm      563:        if (datalen < sizeof *msg)
1.132     nicm      564:                fatalx("bad MSG_WRITE size");
                    565:        find.stream = msg->stream;
                    566:        if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL)
                    567:                fatalx("unknown stream number");
1.135     nicm      568:        log_debug("write %zu to file %d", size, cf->stream);
1.132     nicm      569:
                    570:        if (cf->event != NULL)
1.135     nicm      571:                bufferevent_write(cf->event, msg + 1, size);
1.132     nicm      572: }
                    573:
                    574: /* Close client file. */
                    575: static void
                    576: client_write_close(void *data, size_t datalen)
                    577: {
                    578:        struct msg_write_close  *msg = data;
                    579:        struct client_file       find, *cf;
1.54      nicm      580:
1.132     nicm      581:        if (datalen != sizeof *msg)
                    582:                fatalx("bad MSG_WRITE_CLOSE size");
                    583:        find.stream = msg->stream;
                    584:        if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL)
                    585:                fatalx("unknown stream number");
                    586:        log_debug("close file %d", cf->stream);
                    587:
                    588:        if (cf->event == NULL || EVBUFFER_LENGTH(cf->event->output) == 0) {
                    589:                if (cf->event != NULL)
                    590:                        bufferevent_free(cf->event);
                    591:                if (cf->fd != -1)
                    592:                        close(cf->fd);
                    593:                RB_REMOVE(client_files, &client_files, cf);
                    594:                file_free(cf);
                    595:        }
1.54      nicm      596: }
                    597:
1.132     nicm      598: /* File read callback. */
1.114     nicm      599: static void
1.132     nicm      600: client_read_callback(__unused struct bufferevent *bev, void *arg)
1.57      nicm      601: {
1.132     nicm      602:        struct client_file      *cf = arg;
                    603:        void                    *bdata;
                    604:        size_t                   bsize;
1.135     nicm      605:        struct msg_read_data    *msg;
                    606:        size_t                   msglen;
1.132     nicm      607:
1.135     nicm      608:        msg = xmalloc(sizeof *msg);
1.132     nicm      609:        for (;;) {
                    610:                bdata = EVBUFFER_DATA(cf->event->input);
                    611:                bsize = EVBUFFER_LENGTH(cf->event->input);
1.57      nicm      612:
1.132     nicm      613:                if (bsize == 0)
1.57      nicm      614:                        break;
1.136     nicm      615:                if (bsize > MAX_IMSGSIZE - IMSG_HEADER_SIZE - sizeof *msg)
                    616:                        bsize = MAX_IMSGSIZE - IMSG_HEADER_SIZE - sizeof *msg;
1.132     nicm      617:                log_debug("read %zu from file %d", bsize, cf->stream);
                    618:
1.135     nicm      619:                msglen = (sizeof *msg) + bsize;
                    620:                msg = xrealloc(msg, msglen);
                    621:                msg->stream = cf->stream;
                    622:                memcpy(msg + 1, bdata, bsize);
                    623:                proc_send(client_peer, MSG_READ, -1, msg, msglen);
1.132     nicm      624:
                    625:                evbuffer_drain(cf->event->input, bsize);
                    626:        }
1.135     nicm      627:        free(msg);
1.132     nicm      628: }
                    629:
                    630: /* File read error callback. */
                    631: static void
                    632: client_read_error_callback(__unused struct bufferevent *bev,
                    633:     __unused short what, void *arg)
                    634: {
                    635:        struct client_file      *cf = arg;
                    636:        struct msg_read_done     msg;
                    637:
                    638:        log_debug("read error file %d", cf->stream);
                    639:
                    640:        msg.stream = cf->stream;
                    641:        msg.error = 0;
                    642:        proc_send(client_peer, MSG_READ_DONE, -1, &msg, sizeof msg);
                    643:
                    644:        bufferevent_free(cf->event);
                    645:        close(cf->fd);
                    646:        RB_REMOVE(client_files, &client_files, cf);
                    647:        file_free(cf);
                    648: }
                    649:
                    650: /* Open read file. */
                    651: static void
                    652: client_read_open(void *data, size_t datalen)
                    653: {
                    654:        struct msg_read_open    *msg = data;
1.135     nicm      655:        const char              *path;
1.132     nicm      656:        struct msg_read_done     reply;
                    657:        struct client_file       find, *cf;
                    658:        const int                flags = O_NONBLOCK|O_RDONLY;
1.140     nicm      659:        int                      error;
1.132     nicm      660:
1.135     nicm      661:        if (datalen < sizeof *msg)
1.132     nicm      662:                fatalx("bad MSG_READ_OPEN size");
1.135     nicm      663:        if (datalen == sizeof *msg)
                    664:                path = "-";
                    665:        else
                    666:                path = (const char *)(msg + 1);
                    667:        log_debug("open read file %d %s", msg->stream, path);
1.132     nicm      668:
                    669:        find.stream = msg->stream;
                    670:        if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL) {
                    671:                cf = file_create(NULL, msg->stream, NULL, NULL);
                    672:                RB_INSERT(client_files, &client_files, cf);
                    673:        } else {
                    674:                error = EBADF;
                    675:                goto reply;
1.57      nicm      676:        }
1.132     nicm      677:        if (cf->closed) {
                    678:                error = EBADF;
                    679:                goto reply;
                    680:        }
                    681:
                    682:        cf->fd = -1;
                    683:        if (msg->fd == -1)
1.135     nicm      684:                cf->fd = open(path, flags);
1.132     nicm      685:        else {
                    686:                if (msg->fd != STDIN_FILENO)
                    687:                        errno = EBADF;
                    688:                else {
                    689:                        cf->fd = dup(msg->fd);
1.143     nicm      690:                        if (~client_flags & CLIENT_CONTROL)
                    691:                                close(msg->fd); /* can only be used once */
1.132     nicm      692:                }
                    693:        }
                    694:        if (cf->fd == -1) {
                    695:                error = errno;
                    696:                goto reply;
                    697:        }
                    698:
                    699:        cf->event = bufferevent_new(cf->fd, client_read_callback, NULL,
                    700:            client_read_error_callback, cf);
                    701:        bufferevent_enable(cf->event, EV_READ);
                    702:        return;
                    703:
                    704: reply:
                    705:        reply.stream = msg->stream;
                    706:        reply.error = error;
                    707:        proc_send(client_peer, MSG_READ_DONE, -1, &reply, sizeof reply);
1.57      nicm      708: }
                    709:
1.93      nicm      710: /* Run command in shell; used for -c. */
1.114     nicm      711: static __dead void
1.111     nicm      712: client_exec(const char *shell, const char *shellcmd)
1.93      nicm      713: {
                    714:        const char      *name, *ptr;
                    715:        char            *argv0;
                    716:
1.111     nicm      717:        log_debug("shell %s, command %s", shell, shellcmd);
1.93      nicm      718:
                    719:        ptr = strrchr(shell, '/');
                    720:        if (ptr != NULL && *(ptr + 1) != '\0')
                    721:                name = ptr + 1;
                    722:        else
                    723:                name = shell;
                    724:        if (client_flags & CLIENT_LOGIN)
                    725:                xasprintf(&argv0, "-%s", name);
                    726:        else
                    727:                xasprintf(&argv0, "%s", name);
                    728:        setenv("SHELL", shell, 1);
                    729:
1.123     nicm      730:        proc_clear_signals(client_proc, 1);
                    731:
1.93      nicm      732:        setblocking(STDIN_FILENO, 1);
                    733:        setblocking(STDOUT_FILENO, 1);
                    734:        setblocking(STDERR_FILENO, 1);
                    735:        closefrom(STDERR_FILENO + 1);
                    736:
1.111     nicm      737:        execl(shell, argv0, "-c", shellcmd, (char *) NULL);
1.93      nicm      738:        fatal("execl failed");
                    739: }
                    740:
1.99      nicm      741: /* Callback to handle signals in the client. */
1.114     nicm      742: static void
1.99      nicm      743: client_signal(int sig)
                    744: {
                    745:        struct sigaction sigact;
                    746:        int              status;
                    747:
                    748:        if (sig == SIGCHLD)
                    749:                waitpid(WAIT_ANY, &status, WNOHANG);
                    750:        else if (!client_attached) {
                    751:                if (sig == SIGTERM)
                    752:                        proc_exit(client_proc);
                    753:        } else {
                    754:                switch (sig) {
                    755:                case SIGHUP:
                    756:                        client_exitreason = CLIENT_EXIT_LOST_TTY;
                    757:                        client_exitval = 1;
                    758:                        proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    759:                        break;
                    760:                case SIGTERM:
                    761:                        client_exitreason = CLIENT_EXIT_TERMINATED;
                    762:                        client_exitval = 1;
                    763:                        proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    764:                        break;
                    765:                case SIGWINCH:
                    766:                        proc_send(client_peer, MSG_RESIZE, -1, NULL, 0);
                    767:                        break;
                    768:                case SIGCONT:
                    769:                        memset(&sigact, 0, sizeof sigact);
                    770:                        sigemptyset(&sigact.sa_mask);
                    771:                        sigact.sa_flags = SA_RESTART;
                    772:                        sigact.sa_handler = SIG_IGN;
                    773:                        if (sigaction(SIGTSTP, &sigact, NULL) != 0)
                    774:                                fatal("sigaction failed");
                    775:                        proc_send(client_peer, MSG_WAKEUP, -1, NULL, 0);
                    776:                        break;
                    777:                }
                    778:        }
                    779: }
                    780:
                    781: /* Callback for client read events. */
1.114     nicm      782: static void
1.121     nicm      783: client_dispatch(struct imsg *imsg, __unused void *arg)
1.99      nicm      784: {
                    785:        if (imsg == NULL) {
                    786:                client_exitreason = CLIENT_EXIT_LOST_SERVER;
                    787:                client_exitval = 1;
1.109     nicm      788:                proc_exit(client_proc);
                    789:                return;
                    790:        }
                    791:
                    792:        if (client_attached)
1.99      nicm      793:                client_dispatch_attached(imsg);
                    794:        else
1.121     nicm      795:                client_dispatch_wait(imsg);
1.99      nicm      796: }
                    797:
1.147   ! nicm      798: /* Process an exit message. */
        !           799: static void
        !           800: client_dispatch_exit_message(char *data, size_t datalen)
        !           801: {
        !           802:        int     retval;
        !           803:
        !           804:        if (datalen < sizeof retval && datalen != 0)
        !           805:                fatalx("bad MSG_EXIT size");
        !           806:
        !           807:        if (datalen >= sizeof retval) {
        !           808:                memcpy(&retval, data, sizeof retval);
        !           809:                client_exitval = retval;
        !           810:        }
        !           811:
        !           812:        if (datalen > sizeof retval) {
        !           813:                datalen -= sizeof retval;
        !           814:                data += sizeof retval;
        !           815:
        !           816:                client_exitmessage = xmalloc(datalen);
        !           817:                memcpy(client_exitmessage, data, datalen);
        !           818:                client_exitmessage[datalen - 1] = '\0';
        !           819:
        !           820:                client_exitreason = CLIENT_EXIT_MESSAGE_PROVIDED;
        !           821:        }
        !           822: }
        !           823:
1.46      nicm      824: /* Dispatch imsgs when in wait state (before MSG_READY). */
1.114     nicm      825: static void
1.121     nicm      826: client_dispatch_wait(struct imsg *imsg)
1.46      nicm      827: {
1.132     nicm      828:        char            *data;
                    829:        ssize_t          datalen;
                    830:        static int       pledge_applied;
1.97      nicm      831:
                    832:        /*
                    833:         * "sendfd" is no longer required once all of the identify messages
                    834:         * have been sent. We know the server won't send us anything until that
                    835:         * point (because we don't ask it to), so we can drop "sendfd" once we
                    836:         * get the first message from the server.
                    837:         */
                    838:        if (!pledge_applied) {
1.132     nicm      839:                if (pledge(
                    840:                    "stdio rpath wpath cpath unix proc exec tty",
                    841:                    NULL) != 0)
1.97      nicm      842:                        fatal("pledge failed");
                    843:                pledge_applied = 1;
1.132     nicm      844:        }
1.46      nicm      845:
1.99      nicm      846:        data = imsg->data;
                    847:        datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
1.60      nicm      848:
1.99      nicm      849:        switch (imsg->hdr.type) {
                    850:        case MSG_EXIT:
                    851:        case MSG_SHUTDOWN:
1.147   ! nicm      852:                client_dispatch_exit_message(data, datalen);
1.133     nicm      853:                client_exitflag = 1;
                    854:                client_exit();
1.99      nicm      855:                break;
                    856:        case MSG_READY:
                    857:                if (datalen != 0)
                    858:                        fatalx("bad MSG_READY size");
1.54      nicm      859:
1.99      nicm      860:                client_attached = 1;
                    861:                proc_send(client_peer, MSG_RESIZE, -1, NULL, 0);
                    862:                break;
                    863:        case MSG_VERSION:
                    864:                if (datalen != 0)
                    865:                        fatalx("bad MSG_VERSION size");
                    866:
                    867:                fprintf(stderr, "protocol version mismatch "
                    868:                    "(client %d, server %u)\n", PROTOCOL_VERSION,
1.103     nicm      869:                    imsg->hdr.peerid & 0xff);
1.99      nicm      870:                client_exitval = 1;
                    871:                proc_exit(client_proc);
                    872:                break;
                    873:        case MSG_SHELL:
                    874:                if (datalen == 0 || data[datalen - 1] != '\0')
                    875:                        fatalx("bad MSG_SHELL string");
                    876:
1.121     nicm      877:                client_exec(data, shell_command);
1.99      nicm      878:                /* NOTREACHED */
                    879:        case MSG_DETACH:
                    880:        case MSG_DETACHKILL:
                    881:                proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    882:                break;
                    883:        case MSG_EXITED:
                    884:                proc_exit(client_proc);
1.132     nicm      885:                break;
                    886:        case MSG_READ_OPEN:
                    887:                client_read_open(data, datalen);
                    888:                break;
                    889:        case MSG_WRITE_OPEN:
                    890:                client_write_open(data, datalen);
                    891:                break;
                    892:        case MSG_WRITE:
                    893:                client_write_data(data, datalen);
                    894:                break;
                    895:        case MSG_WRITE_CLOSE:
                    896:                client_write_close(data, datalen);
1.137     nicm      897:                break;
                    898:        case MSG_OLDSTDERR:
                    899:        case MSG_OLDSTDIN:
                    900:        case MSG_OLDSTDOUT:
                    901:                fprintf(stderr, "server version is too old for client\n");
                    902:                proc_exit(client_proc);
1.99      nicm      903:                break;
1.46      nicm      904:        }
                    905: }
                    906:
                    907: /* Dispatch imsgs in attached state (after MSG_READY). */
1.114     nicm      908: static void
1.99      nicm      909: client_dispatch_attached(struct imsg *imsg)
1.9       nicm      910: {
1.69      nicm      911:        struct sigaction         sigact;
                    912:        char                    *data;
1.99      nicm      913:        ssize_t                  datalen;
1.9       nicm      914:
1.99      nicm      915:        data = imsg->data;
                    916:        datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
1.12      nicm      917:
1.99      nicm      918:        switch (imsg->hdr.type) {
                    919:        case MSG_DETACH:
                    920:        case MSG_DETACHKILL:
                    921:                if (datalen == 0 || data[datalen - 1] != '\0')
                    922:                        fatalx("bad MSG_DETACH string");
                    923:
                    924:                client_exitsession = xstrdup(data);
                    925:                client_exittype = imsg->hdr.type;
                    926:                if (imsg->hdr.type == MSG_DETACHKILL)
                    927:                        client_exitreason = CLIENT_EXIT_DETACHED_HUP;
                    928:                else
                    929:                        client_exitreason = CLIENT_EXIT_DETACHED;
1.115     nicm      930:                proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    931:                break;
                    932:        case MSG_EXEC:
                    933:                if (datalen == 0 || data[datalen - 1] != '\0' ||
                    934:                    strlen(data) + 1 == (size_t)datalen)
                    935:                        fatalx("bad MSG_EXEC string");
                    936:                client_execcmd = xstrdup(data);
                    937:                client_execshell = xstrdup(data + strlen(data) + 1);
                    938:
                    939:                client_exittype = imsg->hdr.type;
1.99      nicm      940:                proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    941:                break;
                    942:        case MSG_EXIT:
1.147   ! nicm      943:                client_dispatch_exit_message(data, datalen);
        !           944:                if (client_exitreason == CLIENT_EXIT_NONE)
        !           945:                        client_exitreason = CLIENT_EXIT_EXITED;
1.99      nicm      946:                proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    947:                break;
                    948:        case MSG_EXITED:
                    949:                if (datalen != 0)
                    950:                        fatalx("bad MSG_EXITED size");
1.9       nicm      951:
1.99      nicm      952:                proc_exit(client_proc);
                    953:                break;
                    954:        case MSG_SHUTDOWN:
                    955:                if (datalen != 0)
                    956:                        fatalx("bad MSG_SHUTDOWN size");
                    957:
                    958:                proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    959:                client_exitreason = CLIENT_EXIT_SERVER_EXITED;
                    960:                client_exitval = 1;
                    961:                break;
                    962:        case MSG_SUSPEND:
                    963:                if (datalen != 0)
                    964:                        fatalx("bad MSG_SUSPEND size");
                    965:
                    966:                memset(&sigact, 0, sizeof sigact);
                    967:                sigemptyset(&sigact.sa_mask);
                    968:                sigact.sa_flags = SA_RESTART;
                    969:                sigact.sa_handler = SIG_DFL;
                    970:                if (sigaction(SIGTSTP, &sigact, NULL) != 0)
                    971:                        fatal("sigaction failed");
                    972:                kill(getpid(), SIGTSTP);
                    973:                break;
                    974:        case MSG_LOCK:
                    975:                if (datalen == 0 || data[datalen - 1] != '\0')
                    976:                        fatalx("bad MSG_LOCK string");
1.9       nicm      977:
1.99      nicm      978:                system(data);
                    979:                proc_send(client_peer, MSG_UNLOCK, -1, NULL, 0);
                    980:                break;
1.9       nicm      981:        }
1.1       nicm      982: }