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

1.144   ! nicm        1: /* $OpenBSD: client.c,v 1.143 2020/04/27 08:35:09 nicm Exp $ */
1.1       nicm        2:
                      3: /*
1.113     nicm        4:  * Copyright (c) 2007 Nicholas Marriott <nicholas.marriott@gmail.com>
1.1       nicm        5:  *
                      6:  * Permission to use, copy, modify, and distribute this software for any
                      7:  * purpose with or without fee is hereby granted, provided that the above
                      8:  * copyright notice and this permission notice appear in all copies.
                      9:  *
                     10:  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
                     11:  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
                     12:  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
                     13:  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
                     14:  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
                     15:  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
                     16:  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
                     17:  */
                     18:
                     19: #include <sys/types.h>
                     20: #include <sys/socket.h>
1.144   ! nicm       21: #include <sys/uio.h>
1.1       nicm       22: #include <sys/un.h>
                     23: #include <sys/wait.h>
                     24:
                     25: #include <errno.h>
1.30      nicm       26: #include <event.h>
1.80      nicm       27: #include <fcntl.h>
1.99      nicm       28: #include <imsg.h>
1.85      nicm       29: #include <signal.h>
1.1       nicm       30: #include <stdlib.h>
                     31: #include <string.h>
                     32: #include <unistd.h>
                     33:
                     34: #include "tmux.h"
                     35:
1.114     nicm       36: static struct tmuxproc *client_proc;
                     37: static struct tmuxpeer *client_peer;
                     38: static int              client_flags;
                     39: static enum {
1.52      nicm       40:        CLIENT_EXIT_NONE,
                     41:        CLIENT_EXIT_DETACHED,
                     42:        CLIENT_EXIT_DETACHED_HUP,
                     43:        CLIENT_EXIT_LOST_TTY,
                     44:        CLIENT_EXIT_TERMINATED,
                     45:        CLIENT_EXIT_LOST_SERVER,
                     46:        CLIENT_EXIT_EXITED,
                     47:        CLIENT_EXIT_SERVER_EXITED,
                     48: } client_exitreason = CLIENT_EXIT_NONE;
1.133     nicm       49: static int              client_exitflag;
1.114     nicm       50: static int              client_exitval;
                     51: static enum msgtype     client_exittype;
                     52: static const char      *client_exitsession;
1.115     nicm       53: static const char      *client_execshell;
                     54: static const char      *client_execcmd;
1.114     nicm       55: static int              client_attached;
1.132     nicm       56: static struct client_files client_files = RB_INITIALIZER(&client_files);
1.114     nicm       57:
                     58: static __dead void      client_exec(const char *,const char *);
                     59: static int              client_get_lock(char *);
                     60: static int              client_connect(struct event_base *, const char *, int);
1.142     nicm       61: static void             client_send_identify(const char *, const char *, int);
1.114     nicm       62: static void             client_signal(int);
                     63: static void             client_dispatch(struct imsg *, void *);
                     64: static void             client_dispatch_attached(struct imsg *);
1.121     nicm       65: static void             client_dispatch_wait(struct imsg *);
1.114     nicm       66: static const char      *client_exit_message(void);
1.25      nicm       67:
1.49      nicm       68: /*
                     69:  * Get server create lock. If already held then server start is happening in
1.110     nicm       70:  * another client, so block until the lock is released and return -2 to
                     71:  * retry. Return -1 on failure to continue and start the server anyway.
1.49      nicm       72:  */
1.114     nicm       73: static int
1.49      nicm       74: client_get_lock(char *lockfile)
                     75: {
                     76:        int lockfd;
                     77:
1.110     nicm       78:        log_debug("lock file is %s", lockfile);
                     79:
1.109     nicm       80:        if ((lockfd = open(lockfile, O_WRONLY|O_CREAT, 0600)) == -1) {
1.110     nicm       81:                log_debug("open failed: %s", strerror(errno));
                     82:                return (-1);
1.109     nicm       83:        }
1.49      nicm       84:
1.82      nicm       85:        if (flock(lockfd, LOCK_EX|LOCK_NB) == -1) {
                     86:                log_debug("flock failed: %s", strerror(errno));
                     87:                if (errno != EAGAIN)
                     88:                        return (lockfd);
                     89:                while (flock(lockfd, LOCK_EX) == -1 && errno == EINTR)
1.49      nicm       90:                        /* nothing */;
                     91:                close(lockfd);
1.110     nicm       92:                return (-2);
1.49      nicm       93:        }
1.82      nicm       94:        log_debug("flock succeeded");
1.49      nicm       95:
                     96:        return (lockfd);
                     97: }
                     98:
1.46      nicm       99: /* Connect client to server. */
1.114     nicm      100: static int
1.138     nicm      101: client_connect(struct event_base *base, const char *path, int flags)
1.1       nicm      102: {
1.26      nicm      103:        struct sockaddr_un      sa;
                    104:        size_t                  size;
1.82      nicm      105:        int                     fd, lockfd = -1, locked = 0;
                    106:        char                   *lockfile = NULL;
1.1       nicm      107:
                    108:        memset(&sa, 0, sizeof sa);
                    109:        sa.sun_family = AF_UNIX;
                    110:        size = strlcpy(sa.sun_path, path, sizeof sa.sun_path);
                    111:        if (size >= sizeof sa.sun_path) {
                    112:                errno = ENAMETOOLONG;
1.46      nicm      113:                return (-1);
1.1       nicm      114:        }
1.82      nicm      115:        log_debug("socket is %s", path);
1.1       nicm      116:
1.49      nicm      117: retry:
1.10      nicm      118:        if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
1.109     nicm      119:                return (-1);
1.1       nicm      120:
1.82      nicm      121:        log_debug("trying connect");
1.109     nicm      122:        if (connect(fd, (struct sockaddr *)&sa, sizeof sa) == -1) {
1.82      nicm      123:                log_debug("connect failed: %s", strerror(errno));
1.49      nicm      124:                if (errno != ECONNREFUSED && errno != ENOENT)
                    125:                        goto failed;
1.138     nicm      126:                if (~flags & CLIENT_STARTSERVER)
1.46      nicm      127:                        goto failed;
1.49      nicm      128:                close(fd);
                    129:
1.82      nicm      130:                if (!locked) {
                    131:                        xasprintf(&lockfile, "%s.lock", path);
1.110     nicm      132:                        if ((lockfd = client_get_lock(lockfile)) < 0) {
                    133:                                log_debug("didn't get lock (%d)", lockfd);
                    134:
1.82      nicm      135:                                free(lockfile);
1.110     nicm      136:                                lockfile = NULL;
                    137:
                    138:                                if (lockfd == -2)
                    139:                                        goto retry;
1.82      nicm      140:                        }
1.110     nicm      141:                        log_debug("got lock (%d)", lockfd);
1.82      nicm      142:
                    143:                        /*
                    144:                         * Always retry at least once, even if we got the lock,
                    145:                         * because another client could have taken the lock,
                    146:                         * started the server and released the lock between our
                    147:                         * connect() and flock().
                    148:                         */
                    149:                        locked = 1;
1.49      nicm      150:                        goto retry;
1.78      nicm      151:                }
1.82      nicm      152:
1.110     nicm      153:                if (lockfd >= 0 && unlink(path) != 0 && errno != ENOENT) {
1.78      nicm      154:                        free(lockfile);
                    155:                        close(lockfd);
1.49      nicm      156:                        return (-1);
1.78      nicm      157:                }
1.138     nicm      158:                fd = server_start(client_proc, flags, base, lockfd, lockfile);
1.82      nicm      159:        }
1.95      nicm      160:
1.110     nicm      161:        if (locked && lockfd >= 0) {
1.58      nicm      162:                free(lockfile);
1.49      nicm      163:                close(lockfd);
1.1       nicm      164:        }
1.47      nicm      165:        setblocking(fd, 0);
1.46      nicm      166:        return (fd);
                    167:
                    168: failed:
1.95      nicm      169:        if (locked) {
                    170:                free(lockfile);
                    171:                close(lockfd);
                    172:        }
1.46      nicm      173:        close(fd);
                    174:        return (-1);
                    175: }
                    176:
1.52      nicm      177: /* Get exit string from reason number. */
                    178: const char *
                    179: client_exit_message(void)
                    180: {
1.73      nicm      181:        static char msg[256];
                    182:
1.52      nicm      183:        switch (client_exitreason) {
                    184:        case CLIENT_EXIT_NONE:
                    185:                break;
                    186:        case CLIENT_EXIT_DETACHED:
1.73      nicm      187:                if (client_exitsession != NULL) {
                    188:                        xsnprintf(msg, sizeof msg, "detached "
                    189:                            "(from session %s)", client_exitsession);
                    190:                        return (msg);
                    191:                }
1.52      nicm      192:                return ("detached");
                    193:        case CLIENT_EXIT_DETACHED_HUP:
1.73      nicm      194:                if (client_exitsession != NULL) {
                    195:                        xsnprintf(msg, sizeof msg, "detached and SIGHUP "
                    196:                            "(from session %s)", client_exitsession);
                    197:                        return (msg);
                    198:                }
1.52      nicm      199:                return ("detached and SIGHUP");
                    200:        case CLIENT_EXIT_LOST_TTY:
                    201:                return ("lost tty");
                    202:        case CLIENT_EXIT_TERMINATED:
                    203:                return ("terminated");
                    204:        case CLIENT_EXIT_LOST_SERVER:
1.131     nicm      205:                return ("server exited unexpectedly");
1.52      nicm      206:        case CLIENT_EXIT_EXITED:
                    207:                return ("exited");
                    208:        case CLIENT_EXIT_SERVER_EXITED:
                    209:                return ("server exited");
                    210:        }
                    211:        return ("unknown reason");
                    212: }
                    213:
1.133     nicm      214: /* Exit if all streams flushed. */
                    215: static void
                    216: client_exit(void)
                    217: {
                    218:        struct client_file      *cf;
                    219:        size_t                   left;
                    220:        int                      waiting = 0;
                    221:
                    222:        RB_FOREACH (cf, client_files, &client_files) {
                    223:                if (cf->event == NULL)
                    224:                        continue;
                    225:                left = EVBUFFER_LENGTH(cf->event->output);
                    226:                if (left != 0) {
                    227:                        waiting++;
                    228:                        log_debug("file %u %zu bytes left", cf->stream, left);
                    229:                }
                    230:        }
                    231:        if (waiting == 0)
                    232:                proc_exit(client_proc);
                    233: }
                    234:
1.46      nicm      235: /* Client main loop. */
                    236: int
1.142     nicm      237: client_main(struct event_base *base, int argc, char **argv, int flags, int feat)
1.46      nicm      238: {
1.129     nicm      239:        struct cmd_parse_result *pr;
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) {
1.141     nicm      268:                        if (cmd_list_any_have(pr->cmdlist, CMD_STARTSERVER))
                    269:                                flags |= CLIENT_STARTSERVER;
1.129     nicm      270:                        cmd_list_free(pr->cmdlist);
                    271:                } else
                    272:                        free(pr->error);
1.46      nicm      273:        }
                    274:
1.138     nicm      275:        /* Save the flags. */
                    276:        client_flags = flags;
                    277:
1.109     nicm      278:        /* Create client process structure (starts logging). */
1.122     nicm      279:        client_proc = proc_start("client");
                    280:        proc_set_signals(client_proc, client_signal);
1.109     nicm      281:
1.82      nicm      282:        /* Initialize the client socket and start the server. */
1.138     nicm      283:        fd = client_connect(base, socket_path, client_flags);
1.46      nicm      284:        if (fd == -1) {
1.87      nicm      285:                if (errno == ECONNREFUSED) {
                    286:                        fprintf(stderr, "no server running on %s\n",
                    287:                            socket_path);
                    288:                } else {
                    289:                        fprintf(stderr, "error connecting to %s (%s)\n",
                    290:                            socket_path, strerror(errno));
                    291:                }
1.46      nicm      292:                return (1);
                    293:        }
1.121     nicm      294:        client_peer = proc_add_peer(client_proc, fd, client_dispatch, NULL);
1.99      nicm      295:
1.97      nicm      296:        /* Save these before pledge(). */
1.128     nicm      297:        if ((cwd = find_cwd()) == NULL && (cwd = find_home()) == NULL)
1.126     nicm      298:                cwd = "/";
1.97      nicm      299:        if ((ttynam = ttyname(STDIN_FILENO)) == NULL)
                    300:                ttynam = "";
                    301:
                    302:        /*
                    303:         * Drop privileges for client. "proc exec" is needed for -c and for
                    304:         * locking (which uses system(3)).
                    305:         *
                    306:         * "tty" is needed to restore termios(4) and also for some reason -CC
                    307:         * does not work properly without it (input is not recognised).
                    308:         *
                    309:         * "sendfd" is dropped later in client_dispatch_wait().
                    310:         */
1.132     nicm      311:        if (pledge(
                    312:            "stdio rpath wpath cpath unix sendfd proc exec tty",
                    313:            NULL) != 0)
1.97      nicm      314:                fatal("pledge failed");
                    315:
                    316:        /* Free stuff that is not used in the client. */
1.119     nicm      317:        if (ptm_fd != -1)
                    318:                close(ptm_fd);
1.100     nicm      319:        options_free(global_options);
                    320:        options_free(global_s_options);
                    321:        options_free(global_w_options);
1.101     nicm      322:        environ_free(global_environ);
1.46      nicm      323:
1.132     nicm      324:        /* Set up control mode. */
1.93      nicm      325:        if (client_flags & CLIENT_CONTROLCONTROL) {
1.118     nicm      326:                if (tcgetattr(STDIN_FILENO, &saved_tio) != 0) {
                    327:                        fprintf(stderr, "tcgetattr failed: %s\n",
                    328:                            strerror(errno));
                    329:                        return (1);
                    330:                }
1.56      nicm      331:                cfmakeraw(&tio);
                    332:                tio.c_iflag = ICRNL|IXANY;
                    333:                tio.c_oflag = OPOST|ONLCR;
                    334:                tio.c_lflag = NOKERNINFO;
                    335:                tio.c_cflag = CREAD|CS8|HUPCL;
                    336:                tio.c_cc[VMIN] = 1;
                    337:                tio.c_cc[VTIME] = 0;
                    338:                cfsetispeed(&tio, cfgetispeed(&saved_tio));
                    339:                cfsetospeed(&tio, cfgetospeed(&saved_tio));
                    340:                tcsetattr(STDIN_FILENO, TCSANOW, &tio);
                    341:        }
1.1       nicm      342:
1.71      nicm      343:        /* Send identify messages. */
1.142     nicm      344:        client_send_identify(ttynam, cwd, feat);
1.1       nicm      345:
1.46      nicm      346:        /* Send first command. */
                    347:        if (msg == MSG_COMMAND) {
1.70      nicm      348:                /* How big is the command? */
                    349:                size = 0;
                    350:                for (i = 0; i < argc; i++)
                    351:                        size += strlen(argv[i]) + 1;
1.124     nicm      352:                if (size > MAX_IMSGSIZE - (sizeof *data)) {
                    353:                        fprintf(stderr, "command too long\n");
                    354:                        return (1);
                    355:                }
1.70      nicm      356:                data = xmalloc((sizeof *data) + size);
1.46      nicm      357:
                    358:                /* Prepare command for server. */
1.70      nicm      359:                data->argc = argc;
1.83      nicm      360:                if (cmd_pack_argv(argc, argv, (char *)(data + 1), size) != 0) {
1.55      nicm      361:                        fprintf(stderr, "command too long\n");
1.70      nicm      362:                        free(data);
1.46      nicm      363:                        return (1);
                    364:                }
1.70      nicm      365:                size += sizeof *data;
1.46      nicm      366:
1.70      nicm      367:                /* Send the command. */
1.99      nicm      368:                if (proc_send(client_peer, msg, -1, data, size) != 0) {
1.70      nicm      369:                        fprintf(stderr, "failed to send command\n");
                    370:                        free(data);
                    371:                        return (1);
                    372:                }
                    373:                free(data);
1.46      nicm      374:        } else if (msg == MSG_SHELL)
1.99      nicm      375:                proc_send(client_peer, msg, -1, NULL, 0);
1.1       nicm      376:
1.99      nicm      377:        /* Start main loop. */
                    378:        proc_loop(client_proc, NULL);
1.46      nicm      379:
1.115     nicm      380:        /* Run command if user requested exec, instead of exiting. */
                    381:        if (client_exittype == MSG_EXEC) {
                    382:                if (client_flags & CLIENT_CONTROLCONTROL)
                    383:                        tcsetattr(STDOUT_FILENO, TCSAFLUSH, &saved_tio);
                    384:                client_exec(client_execshell, client_execcmd);
                    385:        }
                    386:
1.46      nicm      387:        /* Print the exit message, if any, and exit. */
1.48      nicm      388:        if (client_attached) {
1.93      nicm      389:                if (client_exitreason != CLIENT_EXIT_NONE)
1.52      nicm      390:                        printf("[%s]\n", client_exit_message());
1.48      nicm      391:
                    392:                ppid = getppid();
                    393:                if (client_exittype == MSG_DETACHKILL && ppid > 1)
                    394:                        kill(ppid, SIGHUP);
1.93      nicm      395:        } else if (client_flags & CLIENT_CONTROLCONTROL) {
1.68      nicm      396:                if (client_exitreason != CLIENT_EXIT_NONE)
                    397:                        printf("%%exit %s\n", client_exit_message());
                    398:                else
                    399:                        printf("%%exit\n");
                    400:                printf("\033\\");
1.56      nicm      401:                tcsetattr(STDOUT_FILENO, TCSAFLUSH, &saved_tio);
1.112     nicm      402:        } else if (client_exitreason != CLIENT_EXIT_NONE)
1.109     nicm      403:                fprintf(stderr, "%s\n", client_exit_message());
1.54      nicm      404:        setblocking(STDIN_FILENO, 1);
1.46      nicm      405:        return (client_exitval);
1.1       nicm      406: }
                    407:
1.71      nicm      408: /* Send identify messages to server. */
1.114     nicm      409: static void
1.142     nicm      410: client_send_identify(const char *ttynam, const char *cwd, int feat)
1.26      nicm      411: {
1.90      nicm      412:        const char       *s;
1.71      nicm      413:        char            **ss;
1.91      nicm      414:        size_t            sslen;
1.93      nicm      415:        int               fd, flags = client_flags;
1.90      nicm      416:        pid_t             pid;
1.71      nicm      417:
1.99      nicm      418:        proc_send(client_peer, MSG_IDENTIFY_FLAGS, -1, &flags, sizeof flags);
1.71      nicm      419:
                    420:        if ((s = getenv("TERM")) == NULL)
                    421:                s = "";
1.99      nicm      422:        proc_send(client_peer, MSG_IDENTIFY_TERM, -1, s, strlen(s) + 1);
1.142     nicm      423:        proc_send(client_peer, MSG_IDENTIFY_FEATURES, -1, &feat, sizeof feat);
1.71      nicm      424:
1.107     nicm      425:        proc_send(client_peer, MSG_IDENTIFY_TTYNAME, -1, ttynam,
                    426:            strlen(ttynam) + 1);
1.99      nicm      427:        proc_send(client_peer, MSG_IDENTIFY_CWD, -1, cwd, strlen(cwd) + 1);
1.26      nicm      428:
1.50      nicm      429:        if ((fd = dup(STDIN_FILENO)) == -1)
                    430:                fatal("dup failed");
1.99      nicm      431:        proc_send(client_peer, MSG_IDENTIFY_STDIN, fd, NULL, 0);
1.90      nicm      432:
                    433:        pid = getpid();
1.99      nicm      434:        proc_send(client_peer, MSG_IDENTIFY_CLIENTPID, -1, &pid, sizeof pid);
1.26      nicm      435:
1.91      nicm      436:        for (ss = environ; *ss != NULL; ss++) {
                    437:                sslen = strlen(*ss) + 1;
1.107     nicm      438:                if (sslen > MAX_IMSGSIZE - IMSG_HEADER_SIZE)
                    439:                        continue;
                    440:                proc_send(client_peer, MSG_IDENTIFY_ENVIRON, -1, *ss, sslen);
1.91      nicm      441:        }
1.75      nicm      442:
1.99      nicm      443:        proc_send(client_peer, MSG_IDENTIFY_DONE, -1, NULL, 0);
1.30      nicm      444: }
                    445:
1.132     nicm      446: /* File write error callback. */
1.114     nicm      447: static void
1.132     nicm      448: client_write_error_callback(__unused struct bufferevent *bev,
                    449:     __unused short what, void *arg)
1.54      nicm      450: {
1.132     nicm      451:        struct client_file      *cf = arg;
1.54      nicm      452:
1.132     nicm      453:        log_debug("write error file %d", cf->stream);
                    454:
                    455:        bufferevent_free(cf->event);
                    456:        cf->event = NULL;
                    457:
                    458:        close(cf->fd);
                    459:        cf->fd = -1;
1.134     nicm      460:
                    461:        if (client_exitflag)
                    462:                client_exit();
1.132     nicm      463: }
                    464:
                    465: /* File write callback. */
                    466: static void
                    467: client_write_callback(__unused struct bufferevent *bev, void *arg)
                    468: {
                    469:        struct client_file      *cf = arg;
                    470:
                    471:        if (cf->closed && EVBUFFER_LENGTH(cf->event->output) == 0) {
                    472:                bufferevent_free(cf->event);
                    473:                close(cf->fd);
                    474:                RB_REMOVE(client_files, &client_files, cf);
                    475:                file_free(cf);
                    476:        }
1.133     nicm      477:
                    478:        if (client_exitflag)
                    479:                client_exit();
1.132     nicm      480: }
                    481:
                    482: /* Open write file. */
                    483: static void
                    484: client_write_open(void *data, size_t datalen)
                    485: {
                    486:        struct msg_write_open   *msg = data;
1.135     nicm      487:        const char              *path;
1.132     nicm      488:        struct msg_write_ready   reply;
                    489:        struct client_file       find, *cf;
                    490:        const int                flags = O_NONBLOCK|O_WRONLY|O_CREAT;
                    491:        int                      error = 0;
                    492:
1.135     nicm      493:        if (datalen < sizeof *msg)
1.132     nicm      494:                fatalx("bad MSG_WRITE_OPEN size");
1.135     nicm      495:        if (datalen == sizeof *msg)
                    496:                path = "-";
                    497:        else
                    498:                path = (const char *)(msg + 1);
                    499:        log_debug("open write file %d %s", msg->stream, path);
1.132     nicm      500:
                    501:        find.stream = msg->stream;
                    502:        if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL) {
                    503:                cf = file_create(NULL, msg->stream, NULL, NULL);
                    504:                RB_INSERT(client_files, &client_files, cf);
                    505:        } else {
                    506:                error = EBADF;
                    507:                goto reply;
                    508:        }
                    509:        if (cf->closed) {
                    510:                error = EBADF;
                    511:                goto reply;
                    512:        }
                    513:
                    514:        cf->fd = -1;
                    515:        if (msg->fd == -1)
1.135     nicm      516:                cf->fd = open(path, msg->flags|flags, 0644);
1.132     nicm      517:        else {
                    518:                if (msg->fd != STDOUT_FILENO && msg->fd != STDERR_FILENO)
                    519:                        errno = EBADF;
                    520:                else {
                    521:                        cf->fd = dup(msg->fd);
1.143     nicm      522:                        if (~client_flags & CLIENT_CONTROL)
1.132     nicm      523:                                close(msg->fd); /* can only be used once */
                    524:                }
                    525:        }
                    526:        if (cf->fd == -1) {
                    527:                error = errno;
                    528:                goto reply;
                    529:        }
                    530:
                    531:        cf->event = bufferevent_new(cf->fd, NULL, client_write_callback,
                    532:            client_write_error_callback, cf);
                    533:        bufferevent_enable(cf->event, EV_WRITE);
                    534:        goto reply;
                    535:
                    536: reply:
                    537:        reply.stream = msg->stream;
                    538:        reply.error = error;
                    539:        proc_send(client_peer, MSG_WRITE_READY, -1, &reply, sizeof reply);
                    540: }
                    541:
                    542: /* Write to client file. */
                    543: static void
                    544: client_write_data(void *data, size_t datalen)
                    545: {
                    546:        struct msg_write_data   *msg = data;
                    547:        struct client_file       find, *cf;
1.135     nicm      548:        size_t                   size = datalen - sizeof *msg;
1.132     nicm      549:
1.135     nicm      550:        if (datalen < sizeof *msg)
1.132     nicm      551:                fatalx("bad MSG_WRITE size");
                    552:        find.stream = msg->stream;
                    553:        if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL)
                    554:                fatalx("unknown stream number");
1.135     nicm      555:        log_debug("write %zu to file %d", size, cf->stream);
1.132     nicm      556:
                    557:        if (cf->event != NULL)
1.135     nicm      558:                bufferevent_write(cf->event, msg + 1, size);
1.132     nicm      559: }
                    560:
                    561: /* Close client file. */
                    562: static void
                    563: client_write_close(void *data, size_t datalen)
                    564: {
                    565:        struct msg_write_close  *msg = data;
                    566:        struct client_file       find, *cf;
1.54      nicm      567:
1.132     nicm      568:        if (datalen != sizeof *msg)
                    569:                fatalx("bad MSG_WRITE_CLOSE size");
                    570:        find.stream = msg->stream;
                    571:        if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL)
                    572:                fatalx("unknown stream number");
                    573:        log_debug("close file %d", cf->stream);
                    574:
                    575:        if (cf->event == NULL || EVBUFFER_LENGTH(cf->event->output) == 0) {
                    576:                if (cf->event != NULL)
                    577:                        bufferevent_free(cf->event);
                    578:                if (cf->fd != -1)
                    579:                        close(cf->fd);
                    580:                RB_REMOVE(client_files, &client_files, cf);
                    581:                file_free(cf);
                    582:        }
1.54      nicm      583: }
                    584:
1.132     nicm      585: /* File read callback. */
1.114     nicm      586: static void
1.132     nicm      587: client_read_callback(__unused struct bufferevent *bev, void *arg)
1.57      nicm      588: {
1.132     nicm      589:        struct client_file      *cf = arg;
                    590:        void                    *bdata;
                    591:        size_t                   bsize;
1.135     nicm      592:        struct msg_read_data    *msg;
                    593:        size_t                   msglen;
1.132     nicm      594:
1.135     nicm      595:        msg = xmalloc(sizeof *msg);
1.132     nicm      596:        for (;;) {
                    597:                bdata = EVBUFFER_DATA(cf->event->input);
                    598:                bsize = EVBUFFER_LENGTH(cf->event->input);
1.57      nicm      599:
1.132     nicm      600:                if (bsize == 0)
1.57      nicm      601:                        break;
1.136     nicm      602:                if (bsize > MAX_IMSGSIZE - IMSG_HEADER_SIZE - sizeof *msg)
                    603:                        bsize = MAX_IMSGSIZE - IMSG_HEADER_SIZE - sizeof *msg;
1.132     nicm      604:                log_debug("read %zu from file %d", bsize, cf->stream);
                    605:
1.135     nicm      606:                msglen = (sizeof *msg) + bsize;
                    607:                msg = xrealloc(msg, msglen);
                    608:                msg->stream = cf->stream;
                    609:                memcpy(msg + 1, bdata, bsize);
                    610:                proc_send(client_peer, MSG_READ, -1, msg, msglen);
1.132     nicm      611:
                    612:                evbuffer_drain(cf->event->input, bsize);
                    613:        }
1.135     nicm      614:        free(msg);
1.132     nicm      615: }
                    616:
                    617: /* File read error callback. */
                    618: static void
                    619: client_read_error_callback(__unused struct bufferevent *bev,
                    620:     __unused short what, void *arg)
                    621: {
                    622:        struct client_file      *cf = arg;
                    623:        struct msg_read_done     msg;
                    624:
                    625:        log_debug("read error file %d", cf->stream);
                    626:
                    627:        msg.stream = cf->stream;
                    628:        msg.error = 0;
                    629:        proc_send(client_peer, MSG_READ_DONE, -1, &msg, sizeof msg);
                    630:
                    631:        bufferevent_free(cf->event);
                    632:        close(cf->fd);
                    633:        RB_REMOVE(client_files, &client_files, cf);
                    634:        file_free(cf);
                    635: }
                    636:
                    637: /* Open read file. */
                    638: static void
                    639: client_read_open(void *data, size_t datalen)
                    640: {
                    641:        struct msg_read_open    *msg = data;
1.135     nicm      642:        const char              *path;
1.132     nicm      643:        struct msg_read_done     reply;
                    644:        struct client_file       find, *cf;
                    645:        const int                flags = O_NONBLOCK|O_RDONLY;
1.140     nicm      646:        int                      error;
1.132     nicm      647:
1.135     nicm      648:        if (datalen < sizeof *msg)
1.132     nicm      649:                fatalx("bad MSG_READ_OPEN size");
1.135     nicm      650:        if (datalen == sizeof *msg)
                    651:                path = "-";
                    652:        else
                    653:                path = (const char *)(msg + 1);
                    654:        log_debug("open read file %d %s", msg->stream, path);
1.132     nicm      655:
                    656:        find.stream = msg->stream;
                    657:        if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL) {
                    658:                cf = file_create(NULL, msg->stream, NULL, NULL);
                    659:                RB_INSERT(client_files, &client_files, cf);
                    660:        } else {
                    661:                error = EBADF;
                    662:                goto reply;
1.57      nicm      663:        }
1.132     nicm      664:        if (cf->closed) {
                    665:                error = EBADF;
                    666:                goto reply;
                    667:        }
                    668:
                    669:        cf->fd = -1;
                    670:        if (msg->fd == -1)
1.135     nicm      671:                cf->fd = open(path, flags);
1.132     nicm      672:        else {
                    673:                if (msg->fd != STDIN_FILENO)
                    674:                        errno = EBADF;
                    675:                else {
                    676:                        cf->fd = dup(msg->fd);
1.143     nicm      677:                        if (~client_flags & CLIENT_CONTROL)
                    678:                                close(msg->fd); /* can only be used once */
1.132     nicm      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: }