[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.141

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