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

1.140   ! nicm        1: /* $OpenBSD: client.c,v 1.139 2020/03/30 15:49:23 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.46      nicm      239:        struct cmd              *cmd;
1.132     nicm      240:        struct msg_command      *data;
1.138     nicm      241:        int                      fd, i;
1.98      nicm      242:        const char              *ttynam, *cwd;
1.48      nicm      243:        pid_t                    ppid;
1.46      nicm      244:        enum msgtype             msg;
1.56      nicm      245:        struct termios           tio, saved_tio;
1.70      nicm      246:        size_t                   size;
1.46      nicm      247:
1.99      nicm      248:        /* Ignore SIGCHLD now or daemon() in the server will leave a zombie. */
                    249:        signal(SIGCHLD, SIG_IGN);
                    250:
1.46      nicm      251:        /* Set up the initial command. */
1.121     nicm      252:        if (shell_command != NULL) {
1.46      nicm      253:                msg = MSG_SHELL;
1.139     nicm      254:                flags |= CLIENT_STARTSERVER;
1.46      nicm      255:        } else if (argc == 0) {
                    256:                msg = MSG_COMMAND;
1.138     nicm      257:                flags |= CLIENT_STARTSERVER;
1.46      nicm      258:        } else {
                    259:                msg = MSG_COMMAND;
                    260:
                    261:                /*
                    262:                 * It sucks parsing the command string twice (in client and
                    263:                 * later in server) but it is necessary to get the start server
                    264:                 * flag.
                    265:                 */
1.129     nicm      266:                pr = cmd_parse_from_arguments(argc, argv, NULL);
                    267:                if (pr->status == CMD_PARSE_SUCCESS) {
                    268:                        TAILQ_FOREACH(cmd, &pr->cmdlist->list, qentry) {
1.120     nicm      269:                                if (cmd->entry->flags & CMD_STARTSERVER)
1.138     nicm      270:                                        flags |= CLIENT_STARTSERVER;
1.120     nicm      271:                        }
1.129     nicm      272:                        cmd_list_free(pr->cmdlist);
                    273:                } else
                    274:                        free(pr->error);
1.46      nicm      275:        }
                    276:
1.138     nicm      277:        /* Save the flags. */
                    278:        client_flags = flags;
                    279:
1.109     nicm      280:        /* Create client process structure (starts logging). */
1.122     nicm      281:        client_proc = proc_start("client");
                    282:        proc_set_signals(client_proc, client_signal);
1.109     nicm      283:
1.82      nicm      284:        /* Initialize the client socket and start the server. */
1.138     nicm      285:        fd = client_connect(base, socket_path, client_flags);
1.46      nicm      286:        if (fd == -1) {
1.87      nicm      287:                if (errno == ECONNREFUSED) {
                    288:                        fprintf(stderr, "no server running on %s\n",
                    289:                            socket_path);
                    290:                } else {
                    291:                        fprintf(stderr, "error connecting to %s (%s)\n",
                    292:                            socket_path, strerror(errno));
                    293:                }
1.46      nicm      294:                return (1);
                    295:        }
1.121     nicm      296:        client_peer = proc_add_peer(client_proc, fd, client_dispatch, NULL);
1.99      nicm      297:
1.97      nicm      298:        /* Save these before pledge(). */
1.128     nicm      299:        if ((cwd = find_cwd()) == NULL && (cwd = find_home()) == NULL)
1.126     nicm      300:                cwd = "/";
1.97      nicm      301:        if ((ttynam = ttyname(STDIN_FILENO)) == NULL)
                    302:                ttynam = "";
                    303:
                    304:        /*
                    305:         * Drop privileges for client. "proc exec" is needed for -c and for
                    306:         * locking (which uses system(3)).
                    307:         *
                    308:         * "tty" is needed to restore termios(4) and also for some reason -CC
                    309:         * does not work properly without it (input is not recognised).
                    310:         *
                    311:         * "sendfd" is dropped later in client_dispatch_wait().
                    312:         */
1.132     nicm      313:        if (pledge(
                    314:            "stdio rpath wpath cpath unix sendfd proc exec tty",
                    315:            NULL) != 0)
1.97      nicm      316:                fatal("pledge failed");
                    317:
                    318:        /* Free stuff that is not used in the client. */
1.119     nicm      319:        if (ptm_fd != -1)
                    320:                close(ptm_fd);
1.100     nicm      321:        options_free(global_options);
                    322:        options_free(global_s_options);
                    323:        options_free(global_w_options);
1.101     nicm      324:        environ_free(global_environ);
1.46      nicm      325:
1.132     nicm      326:        /* Set up control mode. */
1.93      nicm      327:        if (client_flags & CLIENT_CONTROLCONTROL) {
1.118     nicm      328:                if (tcgetattr(STDIN_FILENO, &saved_tio) != 0) {
                    329:                        fprintf(stderr, "tcgetattr failed: %s\n",
                    330:                            strerror(errno));
                    331:                        return (1);
                    332:                }
1.56      nicm      333:                cfmakeraw(&tio);
                    334:                tio.c_iflag = ICRNL|IXANY;
                    335:                tio.c_oflag = OPOST|ONLCR;
                    336:                tio.c_lflag = NOKERNINFO;
                    337:                tio.c_cflag = CREAD|CS8|HUPCL;
                    338:                tio.c_cc[VMIN] = 1;
                    339:                tio.c_cc[VTIME] = 0;
                    340:                cfsetispeed(&tio, cfgetispeed(&saved_tio));
                    341:                cfsetospeed(&tio, cfgetospeed(&saved_tio));
                    342:                tcsetattr(STDIN_FILENO, TCSANOW, &tio);
                    343:        }
1.1       nicm      344:
1.71      nicm      345:        /* Send identify messages. */
1.98      nicm      346:        client_send_identify(ttynam, cwd);
1.1       nicm      347:
1.46      nicm      348:        /* Send first command. */
                    349:        if (msg == MSG_COMMAND) {
1.70      nicm      350:                /* How big is the command? */
                    351:                size = 0;
                    352:                for (i = 0; i < argc; i++)
                    353:                        size += strlen(argv[i]) + 1;
1.124     nicm      354:                if (size > MAX_IMSGSIZE - (sizeof *data)) {
                    355:                        fprintf(stderr, "command too long\n");
                    356:                        return (1);
                    357:                }
1.70      nicm      358:                data = xmalloc((sizeof *data) + size);
1.46      nicm      359:
                    360:                /* Prepare command for server. */
1.70      nicm      361:                data->argc = argc;
1.83      nicm      362:                if (cmd_pack_argv(argc, argv, (char *)(data + 1), size) != 0) {
1.55      nicm      363:                        fprintf(stderr, "command too long\n");
1.70      nicm      364:                        free(data);
1.46      nicm      365:                        return (1);
                    366:                }
1.70      nicm      367:                size += sizeof *data;
1.46      nicm      368:
1.70      nicm      369:                /* Send the command. */
1.99      nicm      370:                if (proc_send(client_peer, msg, -1, data, size) != 0) {
1.70      nicm      371:                        fprintf(stderr, "failed to send command\n");
                    372:                        free(data);
                    373:                        return (1);
                    374:                }
                    375:                free(data);
1.46      nicm      376:        } else if (msg == MSG_SHELL)
1.99      nicm      377:                proc_send(client_peer, msg, -1, NULL, 0);
1.1       nicm      378:
1.99      nicm      379:        /* Start main loop. */
                    380:        proc_loop(client_proc, NULL);
1.46      nicm      381:
1.115     nicm      382:        /* Run command if user requested exec, instead of exiting. */
                    383:        if (client_exittype == MSG_EXEC) {
                    384:                if (client_flags & CLIENT_CONTROLCONTROL)
                    385:                        tcsetattr(STDOUT_FILENO, TCSAFLUSH, &saved_tio);
                    386:                client_exec(client_execshell, client_execcmd);
                    387:        }
                    388:
1.46      nicm      389:        /* Print the exit message, if any, and exit. */
1.48      nicm      390:        if (client_attached) {
1.93      nicm      391:                if (client_exitreason != CLIENT_EXIT_NONE)
1.52      nicm      392:                        printf("[%s]\n", client_exit_message());
1.48      nicm      393:
                    394:                ppid = getppid();
                    395:                if (client_exittype == MSG_DETACHKILL && ppid > 1)
                    396:                        kill(ppid, SIGHUP);
1.93      nicm      397:        } else if (client_flags & CLIENT_CONTROLCONTROL) {
1.68      nicm      398:                if (client_exitreason != CLIENT_EXIT_NONE)
                    399:                        printf("%%exit %s\n", client_exit_message());
                    400:                else
                    401:                        printf("%%exit\n");
                    402:                printf("\033\\");
1.56      nicm      403:                tcsetattr(STDOUT_FILENO, TCSAFLUSH, &saved_tio);
1.112     nicm      404:        } else if (client_exitreason != CLIENT_EXIT_NONE)
1.109     nicm      405:                fprintf(stderr, "%s\n", client_exit_message());
1.54      nicm      406:        setblocking(STDIN_FILENO, 1);
1.46      nicm      407:        return (client_exitval);
1.1       nicm      408: }
                    409:
1.71      nicm      410: /* Send identify messages to server. */
1.114     nicm      411: static void
1.98      nicm      412: client_send_identify(const char *ttynam, const char *cwd)
1.26      nicm      413: {
1.90      nicm      414:        const char       *s;
1.71      nicm      415:        char            **ss;
1.91      nicm      416:        size_t            sslen;
1.93      nicm      417:        int               fd, flags = client_flags;
1.90      nicm      418:        pid_t             pid;
1.71      nicm      419:
1.99      nicm      420:        proc_send(client_peer, MSG_IDENTIFY_FLAGS, -1, &flags, sizeof flags);
1.71      nicm      421:
                    422:        if ((s = getenv("TERM")) == NULL)
                    423:                s = "";
1.99      nicm      424:        proc_send(client_peer, MSG_IDENTIFY_TERM, -1, s, strlen(s) + 1);
1.71      nicm      425:
1.107     nicm      426:        proc_send(client_peer, MSG_IDENTIFY_TTYNAME, -1, ttynam,
                    427:            strlen(ttynam) + 1);
1.99      nicm      428:        proc_send(client_peer, MSG_IDENTIFY_CWD, -1, cwd, strlen(cwd) + 1);
1.26      nicm      429:
1.50      nicm      430:        if ((fd = dup(STDIN_FILENO)) == -1)
                    431:                fatal("dup failed");
1.99      nicm      432:        proc_send(client_peer, MSG_IDENTIFY_STDIN, fd, NULL, 0);
1.90      nicm      433:
                    434:        pid = getpid();
1.99      nicm      435:        proc_send(client_peer, MSG_IDENTIFY_CLIENTPID, -1, &pid, sizeof pid);
1.26      nicm      436:
1.91      nicm      437:        for (ss = environ; *ss != NULL; ss++) {
                    438:                sslen = strlen(*ss) + 1;
1.107     nicm      439:                if (sslen > MAX_IMSGSIZE - IMSG_HEADER_SIZE)
                    440:                        continue;
                    441:                proc_send(client_peer, MSG_IDENTIFY_ENVIRON, -1, *ss, sslen);
1.91      nicm      442:        }
1.75      nicm      443:
1.99      nicm      444:        proc_send(client_peer, MSG_IDENTIFY_DONE, -1, NULL, 0);
1.30      nicm      445: }
                    446:
1.132     nicm      447: /* File write error callback. */
1.114     nicm      448: static void
1.132     nicm      449: client_write_error_callback(__unused struct bufferevent *bev,
                    450:     __unused short what, void *arg)
1.54      nicm      451: {
1.132     nicm      452:        struct client_file      *cf = arg;
1.54      nicm      453:
1.132     nicm      454:        log_debug("write error file %d", cf->stream);
                    455:
                    456:        bufferevent_free(cf->event);
                    457:        cf->event = NULL;
                    458:
                    459:        close(cf->fd);
                    460:        cf->fd = -1;
1.134     nicm      461:
                    462:        if (client_exitflag)
                    463:                client_exit();
1.132     nicm      464: }
                    465:
                    466: /* File write callback. */
                    467: static void
                    468: client_write_callback(__unused struct bufferevent *bev, void *arg)
                    469: {
                    470:        struct client_file      *cf = arg;
                    471:
                    472:        if (cf->closed && EVBUFFER_LENGTH(cf->event->output) == 0) {
                    473:                bufferevent_free(cf->event);
                    474:                close(cf->fd);
                    475:                RB_REMOVE(client_files, &client_files, cf);
                    476:                file_free(cf);
                    477:        }
1.133     nicm      478:
                    479:        if (client_exitflag)
                    480:                client_exit();
1.132     nicm      481: }
                    482:
                    483: /* Open write file. */
                    484: static void
                    485: client_write_open(void *data, size_t datalen)
                    486: {
                    487:        struct msg_write_open   *msg = data;
1.135     nicm      488:        const char              *path;
1.132     nicm      489:        struct msg_write_ready   reply;
                    490:        struct client_file       find, *cf;
                    491:        const int                flags = O_NONBLOCK|O_WRONLY|O_CREAT;
                    492:        int                      error = 0;
                    493:
1.135     nicm      494:        if (datalen < sizeof *msg)
1.132     nicm      495:                fatalx("bad MSG_WRITE_OPEN size");
1.135     nicm      496:        if (datalen == sizeof *msg)
                    497:                path = "-";
                    498:        else
                    499:                path = (const char *)(msg + 1);
                    500:        log_debug("open write file %d %s", msg->stream, path);
1.132     nicm      501:
                    502:        find.stream = msg->stream;
                    503:        if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL) {
                    504:                cf = file_create(NULL, msg->stream, NULL, NULL);
                    505:                RB_INSERT(client_files, &client_files, cf);
                    506:        } else {
                    507:                error = EBADF;
                    508:                goto reply;
                    509:        }
                    510:        if (cf->closed) {
                    511:                error = EBADF;
                    512:                goto reply;
                    513:        }
                    514:
                    515:        cf->fd = -1;
                    516:        if (msg->fd == -1)
1.135     nicm      517:                cf->fd = open(path, msg->flags|flags, 0644);
1.132     nicm      518:        else {
                    519:                if (msg->fd != STDOUT_FILENO && msg->fd != STDERR_FILENO)
                    520:                        errno = EBADF;
                    521:                else {
                    522:                        cf->fd = dup(msg->fd);
                    523:                        if (client_flags & CLIENT_CONTROL)
                    524:                                close(msg->fd); /* can only be used once */
                    525:                }
                    526:        }
                    527:        if (cf->fd == -1) {
                    528:                error = errno;
                    529:                goto reply;
                    530:        }
                    531:
                    532:        cf->event = bufferevent_new(cf->fd, NULL, client_write_callback,
                    533:            client_write_error_callback, cf);
                    534:        bufferevent_enable(cf->event, EV_WRITE);
                    535:        goto reply;
                    536:
                    537: reply:
                    538:        reply.stream = msg->stream;
                    539:        reply.error = error;
                    540:        proc_send(client_peer, MSG_WRITE_READY, -1, &reply, sizeof reply);
                    541: }
                    542:
                    543: /* Write to client file. */
                    544: static void
                    545: client_write_data(void *data, size_t datalen)
                    546: {
                    547:        struct msg_write_data   *msg = data;
                    548:        struct client_file       find, *cf;
1.135     nicm      549:        size_t                   size = datalen - sizeof *msg;
1.132     nicm      550:
1.135     nicm      551:        if (datalen < sizeof *msg)
1.132     nicm      552:                fatalx("bad MSG_WRITE size");
                    553:        find.stream = msg->stream;
                    554:        if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL)
                    555:                fatalx("unknown stream number");
1.135     nicm      556:        log_debug("write %zu to file %d", size, cf->stream);
1.132     nicm      557:
                    558:        if (cf->event != NULL)
1.135     nicm      559:                bufferevent_write(cf->event, msg + 1, size);
1.132     nicm      560: }
                    561:
                    562: /* Close client file. */
                    563: static void
                    564: client_write_close(void *data, size_t datalen)
                    565: {
                    566:        struct msg_write_close  *msg = data;
                    567:        struct client_file       find, *cf;
1.54      nicm      568:
1.132     nicm      569:        if (datalen != sizeof *msg)
                    570:                fatalx("bad MSG_WRITE_CLOSE size");
                    571:        find.stream = msg->stream;
                    572:        if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL)
                    573:                fatalx("unknown stream number");
                    574:        log_debug("close file %d", cf->stream);
                    575:
                    576:        if (cf->event == NULL || EVBUFFER_LENGTH(cf->event->output) == 0) {
                    577:                if (cf->event != NULL)
                    578:                        bufferevent_free(cf->event);
                    579:                if (cf->fd != -1)
                    580:                        close(cf->fd);
                    581:                RB_REMOVE(client_files, &client_files, cf);
                    582:                file_free(cf);
                    583:        }
1.54      nicm      584: }
                    585:
1.132     nicm      586: /* File read callback. */
1.114     nicm      587: static void
1.132     nicm      588: client_read_callback(__unused struct bufferevent *bev, void *arg)
1.57      nicm      589: {
1.132     nicm      590:        struct client_file      *cf = arg;
                    591:        void                    *bdata;
                    592:        size_t                   bsize;
1.135     nicm      593:        struct msg_read_data    *msg;
                    594:        size_t                   msglen;
1.132     nicm      595:
1.135     nicm      596:        msg = xmalloc(sizeof *msg);
1.132     nicm      597:        for (;;) {
                    598:                bdata = EVBUFFER_DATA(cf->event->input);
                    599:                bsize = EVBUFFER_LENGTH(cf->event->input);
1.57      nicm      600:
1.132     nicm      601:                if (bsize == 0)
1.57      nicm      602:                        break;
1.136     nicm      603:                if (bsize > MAX_IMSGSIZE - IMSG_HEADER_SIZE - sizeof *msg)
                    604:                        bsize = MAX_IMSGSIZE - IMSG_HEADER_SIZE - sizeof *msg;
1.132     nicm      605:                log_debug("read %zu from file %d", bsize, cf->stream);
                    606:
1.135     nicm      607:                msglen = (sizeof *msg) + bsize;
                    608:                msg = xrealloc(msg, msglen);
                    609:                msg->stream = cf->stream;
                    610:                memcpy(msg + 1, bdata, bsize);
                    611:                proc_send(client_peer, MSG_READ, -1, msg, msglen);
1.132     nicm      612:
                    613:                evbuffer_drain(cf->event->input, bsize);
                    614:        }
1.135     nicm      615:        free(msg);
1.132     nicm      616: }
                    617:
                    618: /* File read error callback. */
                    619: static void
                    620: client_read_error_callback(__unused struct bufferevent *bev,
                    621:     __unused short what, void *arg)
                    622: {
                    623:        struct client_file      *cf = arg;
                    624:        struct msg_read_done     msg;
                    625:
                    626:        log_debug("read error file %d", cf->stream);
                    627:
                    628:        msg.stream = cf->stream;
                    629:        msg.error = 0;
                    630:        proc_send(client_peer, MSG_READ_DONE, -1, &msg, sizeof msg);
                    631:
                    632:        bufferevent_free(cf->event);
                    633:        close(cf->fd);
                    634:        RB_REMOVE(client_files, &client_files, cf);
                    635:        file_free(cf);
                    636: }
                    637:
                    638: /* Open read file. */
                    639: static void
                    640: client_read_open(void *data, size_t datalen)
                    641: {
                    642:        struct msg_read_open    *msg = data;
1.135     nicm      643:        const char              *path;
1.132     nicm      644:        struct msg_read_done     reply;
                    645:        struct client_file       find, *cf;
                    646:        const int                flags = O_NONBLOCK|O_RDONLY;
1.140   ! nicm      647:        int                      error;
1.132     nicm      648:
1.135     nicm      649:        if (datalen < sizeof *msg)
1.132     nicm      650:                fatalx("bad MSG_READ_OPEN size");
1.135     nicm      651:        if (datalen == sizeof *msg)
                    652:                path = "-";
                    653:        else
                    654:                path = (const char *)(msg + 1);
                    655:        log_debug("open read file %d %s", msg->stream, path);
1.132     nicm      656:
                    657:        find.stream = msg->stream;
                    658:        if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL) {
                    659:                cf = file_create(NULL, msg->stream, NULL, NULL);
                    660:                RB_INSERT(client_files, &client_files, cf);
                    661:        } else {
                    662:                error = EBADF;
                    663:                goto reply;
1.57      nicm      664:        }
1.132     nicm      665:        if (cf->closed) {
                    666:                error = EBADF;
                    667:                goto reply;
                    668:        }
                    669:
                    670:        cf->fd = -1;
                    671:        if (msg->fd == -1)
1.135     nicm      672:                cf->fd = open(path, flags);
1.132     nicm      673:        else {
                    674:                if (msg->fd != STDIN_FILENO)
                    675:                        errno = EBADF;
                    676:                else {
                    677:                        cf->fd = dup(msg->fd);
                    678:                        close(msg->fd); /* can only be used once */
                    679:                }
                    680:        }
                    681:        if (cf->fd == -1) {
                    682:                error = errno;
                    683:                goto reply;
                    684:        }
                    685:
                    686:        cf->event = bufferevent_new(cf->fd, client_read_callback, NULL,
                    687:            client_read_error_callback, cf);
                    688:        bufferevent_enable(cf->event, EV_READ);
                    689:        return;
                    690:
                    691: reply:
                    692:        reply.stream = msg->stream;
                    693:        reply.error = error;
                    694:        proc_send(client_peer, MSG_READ_DONE, -1, &reply, sizeof reply);
1.57      nicm      695: }
                    696:
1.93      nicm      697: /* Run command in shell; used for -c. */
1.114     nicm      698: static __dead void
1.111     nicm      699: client_exec(const char *shell, const char *shellcmd)
1.93      nicm      700: {
                    701:        const char      *name, *ptr;
                    702:        char            *argv0;
                    703:
1.111     nicm      704:        log_debug("shell %s, command %s", shell, shellcmd);
1.93      nicm      705:
                    706:        ptr = strrchr(shell, '/');
                    707:        if (ptr != NULL && *(ptr + 1) != '\0')
                    708:                name = ptr + 1;
                    709:        else
                    710:                name = shell;
                    711:        if (client_flags & CLIENT_LOGIN)
                    712:                xasprintf(&argv0, "-%s", name);
                    713:        else
                    714:                xasprintf(&argv0, "%s", name);
                    715:        setenv("SHELL", shell, 1);
                    716:
1.123     nicm      717:        proc_clear_signals(client_proc, 1);
                    718:
1.93      nicm      719:        setblocking(STDIN_FILENO, 1);
                    720:        setblocking(STDOUT_FILENO, 1);
                    721:        setblocking(STDERR_FILENO, 1);
                    722:        closefrom(STDERR_FILENO + 1);
                    723:
1.111     nicm      724:        execl(shell, argv0, "-c", shellcmd, (char *) NULL);
1.93      nicm      725:        fatal("execl failed");
                    726: }
                    727:
1.99      nicm      728: /* Callback to handle signals in the client. */
1.114     nicm      729: static void
1.99      nicm      730: client_signal(int sig)
                    731: {
                    732:        struct sigaction sigact;
                    733:        int              status;
                    734:
                    735:        if (sig == SIGCHLD)
                    736:                waitpid(WAIT_ANY, &status, WNOHANG);
                    737:        else if (!client_attached) {
                    738:                if (sig == SIGTERM)
                    739:                        proc_exit(client_proc);
                    740:        } else {
                    741:                switch (sig) {
                    742:                case SIGHUP:
                    743:                        client_exitreason = CLIENT_EXIT_LOST_TTY;
                    744:                        client_exitval = 1;
                    745:                        proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    746:                        break;
                    747:                case SIGTERM:
                    748:                        client_exitreason = CLIENT_EXIT_TERMINATED;
                    749:                        client_exitval = 1;
                    750:                        proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    751:                        break;
                    752:                case SIGWINCH:
                    753:                        proc_send(client_peer, MSG_RESIZE, -1, NULL, 0);
                    754:                        break;
                    755:                case SIGCONT:
                    756:                        memset(&sigact, 0, sizeof sigact);
                    757:                        sigemptyset(&sigact.sa_mask);
                    758:                        sigact.sa_flags = SA_RESTART;
                    759:                        sigact.sa_handler = SIG_IGN;
                    760:                        if (sigaction(SIGTSTP, &sigact, NULL) != 0)
                    761:                                fatal("sigaction failed");
                    762:                        proc_send(client_peer, MSG_WAKEUP, -1, NULL, 0);
                    763:                        break;
                    764:                }
                    765:        }
                    766: }
                    767:
                    768: /* Callback for client read events. */
1.114     nicm      769: static void
1.121     nicm      770: client_dispatch(struct imsg *imsg, __unused void *arg)
1.99      nicm      771: {
                    772:        if (imsg == NULL) {
                    773:                client_exitreason = CLIENT_EXIT_LOST_SERVER;
                    774:                client_exitval = 1;
1.109     nicm      775:                proc_exit(client_proc);
                    776:                return;
                    777:        }
                    778:
                    779:        if (client_attached)
1.99      nicm      780:                client_dispatch_attached(imsg);
                    781:        else
1.121     nicm      782:                client_dispatch_wait(imsg);
1.99      nicm      783: }
                    784:
1.46      nicm      785: /* Dispatch imsgs when in wait state (before MSG_READY). */
1.114     nicm      786: static void
1.121     nicm      787: client_dispatch_wait(struct imsg *imsg)
1.46      nicm      788: {
1.132     nicm      789:        char            *data;
                    790:        ssize_t          datalen;
                    791:        int              retval;
                    792:        static int       pledge_applied;
1.97      nicm      793:
                    794:        /*
                    795:         * "sendfd" is no longer required once all of the identify messages
                    796:         * have been sent. We know the server won't send us anything until that
                    797:         * point (because we don't ask it to), so we can drop "sendfd" once we
                    798:         * get the first message from the server.
                    799:         */
                    800:        if (!pledge_applied) {
1.132     nicm      801:                if (pledge(
                    802:                    "stdio rpath wpath cpath unix proc exec tty",
                    803:                    NULL) != 0)
1.97      nicm      804:                        fatal("pledge failed");
                    805:                pledge_applied = 1;
1.132     nicm      806:        }
1.46      nicm      807:
1.99      nicm      808:        data = imsg->data;
                    809:        datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
1.60      nicm      810:
1.99      nicm      811:        switch (imsg->hdr.type) {
                    812:        case MSG_EXIT:
                    813:        case MSG_SHUTDOWN:
                    814:                if (datalen != sizeof retval && datalen != 0)
                    815:                        fatalx("bad MSG_EXIT size");
                    816:                if (datalen == sizeof retval) {
                    817:                        memcpy(&retval, data, sizeof retval);
                    818:                        client_exitval = retval;
                    819:                }
1.133     nicm      820:                client_exitflag = 1;
                    821:                client_exit();
1.99      nicm      822:                break;
                    823:        case MSG_READY:
                    824:                if (datalen != 0)
                    825:                        fatalx("bad MSG_READY size");
1.54      nicm      826:
1.99      nicm      827:                client_attached = 1;
                    828:                proc_send(client_peer, MSG_RESIZE, -1, NULL, 0);
                    829:                break;
                    830:        case MSG_VERSION:
                    831:                if (datalen != 0)
                    832:                        fatalx("bad MSG_VERSION size");
                    833:
                    834:                fprintf(stderr, "protocol version mismatch "
                    835:                    "(client %d, server %u)\n", PROTOCOL_VERSION,
1.103     nicm      836:                    imsg->hdr.peerid & 0xff);
1.99      nicm      837:                client_exitval = 1;
                    838:                proc_exit(client_proc);
                    839:                break;
                    840:        case MSG_SHELL:
                    841:                if (datalen == 0 || data[datalen - 1] != '\0')
                    842:                        fatalx("bad MSG_SHELL string");
                    843:
1.121     nicm      844:                client_exec(data, shell_command);
1.99      nicm      845:                /* NOTREACHED */
                    846:        case MSG_DETACH:
                    847:        case MSG_DETACHKILL:
                    848:                proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    849:                break;
                    850:        case MSG_EXITED:
                    851:                proc_exit(client_proc);
1.132     nicm      852:                break;
                    853:        case MSG_READ_OPEN:
                    854:                client_read_open(data, datalen);
                    855:                break;
                    856:        case MSG_WRITE_OPEN:
                    857:                client_write_open(data, datalen);
                    858:                break;
                    859:        case MSG_WRITE:
                    860:                client_write_data(data, datalen);
                    861:                break;
                    862:        case MSG_WRITE_CLOSE:
                    863:                client_write_close(data, datalen);
1.137     nicm      864:                break;
                    865:        case MSG_OLDSTDERR:
                    866:        case MSG_OLDSTDIN:
                    867:        case MSG_OLDSTDOUT:
                    868:                fprintf(stderr, "server version is too old for client\n");
                    869:                proc_exit(client_proc);
1.99      nicm      870:                break;
1.46      nicm      871:        }
                    872: }
                    873:
                    874: /* Dispatch imsgs in attached state (after MSG_READY). */
1.114     nicm      875: static void
1.99      nicm      876: client_dispatch_attached(struct imsg *imsg)
1.9       nicm      877: {
1.69      nicm      878:        struct sigaction         sigact;
                    879:        char                    *data;
1.99      nicm      880:        ssize_t                  datalen;
1.9       nicm      881:
1.99      nicm      882:        data = imsg->data;
                    883:        datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
1.12      nicm      884:
1.99      nicm      885:        switch (imsg->hdr.type) {
                    886:        case MSG_DETACH:
                    887:        case MSG_DETACHKILL:
                    888:                if (datalen == 0 || data[datalen - 1] != '\0')
                    889:                        fatalx("bad MSG_DETACH string");
                    890:
                    891:                client_exitsession = xstrdup(data);
                    892:                client_exittype = imsg->hdr.type;
                    893:                if (imsg->hdr.type == MSG_DETACHKILL)
                    894:                        client_exitreason = CLIENT_EXIT_DETACHED_HUP;
                    895:                else
                    896:                        client_exitreason = CLIENT_EXIT_DETACHED;
1.115     nicm      897:                proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    898:                break;
                    899:        case MSG_EXEC:
                    900:                if (datalen == 0 || data[datalen - 1] != '\0' ||
                    901:                    strlen(data) + 1 == (size_t)datalen)
                    902:                        fatalx("bad MSG_EXEC string");
                    903:                client_execcmd = xstrdup(data);
                    904:                client_execshell = xstrdup(data + strlen(data) + 1);
                    905:
                    906:                client_exittype = imsg->hdr.type;
1.99      nicm      907:                proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    908:                break;
                    909:        case MSG_EXIT:
                    910:                if (datalen != 0 && datalen != sizeof (int))
                    911:                        fatalx("bad MSG_EXIT size");
1.9       nicm      912:
1.99      nicm      913:                proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    914:                client_exitreason = CLIENT_EXIT_EXITED;
                    915:                break;
                    916:        case MSG_EXITED:
                    917:                if (datalen != 0)
                    918:                        fatalx("bad MSG_EXITED size");
1.9       nicm      919:
1.99      nicm      920:                proc_exit(client_proc);
                    921:                break;
                    922:        case MSG_SHUTDOWN:
                    923:                if (datalen != 0)
                    924:                        fatalx("bad MSG_SHUTDOWN size");
                    925:
                    926:                proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    927:                client_exitreason = CLIENT_EXIT_SERVER_EXITED;
                    928:                client_exitval = 1;
                    929:                break;
                    930:        case MSG_SUSPEND:
                    931:                if (datalen != 0)
                    932:                        fatalx("bad MSG_SUSPEND size");
                    933:
                    934:                memset(&sigact, 0, sizeof sigact);
                    935:                sigemptyset(&sigact.sa_mask);
                    936:                sigact.sa_flags = SA_RESTART;
                    937:                sigact.sa_handler = SIG_DFL;
                    938:                if (sigaction(SIGTSTP, &sigact, NULL) != 0)
                    939:                        fatal("sigaction failed");
                    940:                kill(getpid(), SIGTSTP);
                    941:                break;
                    942:        case MSG_LOCK:
                    943:                if (datalen == 0 || data[datalen - 1] != '\0')
                    944:                        fatalx("bad MSG_LOCK string");
1.9       nicm      945:
1.99      nicm      946:                system(data);
                    947:                proc_send(client_peer, MSG_UNLOCK, -1, NULL, 0);
                    948:                break;
1.9       nicm      949:        }
1.1       nicm      950: }