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

1.145   ! nicm        1: /* $OpenBSD: client.c,v 1.144 2020/05/08 14:15:11 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.145   ! nicm      405:        setblocking(STDOUT_FILENO, 1);
        !           406:        setblocking(STDERR_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.142     nicm      412: client_send_identify(const char *ttynam, const char *cwd, int feat)
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.142     nicm      425:        proc_send(client_peer, MSG_IDENTIFY_FEATURES, -1, &feat, sizeof feat);
1.71      nicm      426:
1.107     nicm      427:        proc_send(client_peer, MSG_IDENTIFY_TTYNAME, -1, ttynam,
                    428:            strlen(ttynam) + 1);
1.99      nicm      429:        proc_send(client_peer, MSG_IDENTIFY_CWD, -1, cwd, strlen(cwd) + 1);
1.26      nicm      430:
1.50      nicm      431:        if ((fd = dup(STDIN_FILENO)) == -1)
                    432:                fatal("dup failed");
1.99      nicm      433:        proc_send(client_peer, MSG_IDENTIFY_STDIN, fd, NULL, 0);
1.145   ! nicm      434:        if ((fd = dup(STDOUT_FILENO)) == -1)
        !           435:                fatal("dup failed");
        !           436:        proc_send(client_peer, MSG_IDENTIFY_STDOUT, fd, NULL, 0);
1.90      nicm      437:
                    438:        pid = getpid();
1.99      nicm      439:        proc_send(client_peer, MSG_IDENTIFY_CLIENTPID, -1, &pid, sizeof pid);
1.26      nicm      440:
1.91      nicm      441:        for (ss = environ; *ss != NULL; ss++) {
                    442:                sslen = strlen(*ss) + 1;
1.107     nicm      443:                if (sslen > MAX_IMSGSIZE - IMSG_HEADER_SIZE)
                    444:                        continue;
                    445:                proc_send(client_peer, MSG_IDENTIFY_ENVIRON, -1, *ss, sslen);
1.91      nicm      446:        }
1.75      nicm      447:
1.99      nicm      448:        proc_send(client_peer, MSG_IDENTIFY_DONE, -1, NULL, 0);
1.30      nicm      449: }
                    450:
1.132     nicm      451: /* File write error callback. */
1.114     nicm      452: static void
1.132     nicm      453: client_write_error_callback(__unused struct bufferevent *bev,
                    454:     __unused short what, void *arg)
1.54      nicm      455: {
1.132     nicm      456:        struct client_file      *cf = arg;
1.54      nicm      457:
1.132     nicm      458:        log_debug("write error file %d", cf->stream);
                    459:
                    460:        bufferevent_free(cf->event);
                    461:        cf->event = NULL;
                    462:
                    463:        close(cf->fd);
                    464:        cf->fd = -1;
1.134     nicm      465:
                    466:        if (client_exitflag)
                    467:                client_exit();
1.132     nicm      468: }
                    469:
                    470: /* File write callback. */
                    471: static void
                    472: client_write_callback(__unused struct bufferevent *bev, void *arg)
                    473: {
                    474:        struct client_file      *cf = arg;
                    475:
                    476:        if (cf->closed && EVBUFFER_LENGTH(cf->event->output) == 0) {
                    477:                bufferevent_free(cf->event);
                    478:                close(cf->fd);
                    479:                RB_REMOVE(client_files, &client_files, cf);
                    480:                file_free(cf);
                    481:        }
1.133     nicm      482:
                    483:        if (client_exitflag)
                    484:                client_exit();
1.132     nicm      485: }
                    486:
                    487: /* Open write file. */
                    488: static void
                    489: client_write_open(void *data, size_t datalen)
                    490: {
                    491:        struct msg_write_open   *msg = data;
1.135     nicm      492:        const char              *path;
1.132     nicm      493:        struct msg_write_ready   reply;
                    494:        struct client_file       find, *cf;
                    495:        const int                flags = O_NONBLOCK|O_WRONLY|O_CREAT;
                    496:        int                      error = 0;
                    497:
1.135     nicm      498:        if (datalen < sizeof *msg)
1.132     nicm      499:                fatalx("bad MSG_WRITE_OPEN size");
1.135     nicm      500:        if (datalen == sizeof *msg)
                    501:                path = "-";
                    502:        else
                    503:                path = (const char *)(msg + 1);
                    504:        log_debug("open write file %d %s", msg->stream, path);
1.132     nicm      505:
                    506:        find.stream = msg->stream;
                    507:        if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL) {
                    508:                cf = file_create(NULL, msg->stream, NULL, NULL);
                    509:                RB_INSERT(client_files, &client_files, cf);
                    510:        } else {
                    511:                error = EBADF;
                    512:                goto reply;
                    513:        }
                    514:        if (cf->closed) {
                    515:                error = EBADF;
                    516:                goto reply;
                    517:        }
                    518:
                    519:        cf->fd = -1;
                    520:        if (msg->fd == -1)
1.135     nicm      521:                cf->fd = open(path, msg->flags|flags, 0644);
1.132     nicm      522:        else {
                    523:                if (msg->fd != STDOUT_FILENO && msg->fd != STDERR_FILENO)
                    524:                        errno = EBADF;
                    525:                else {
                    526:                        cf->fd = dup(msg->fd);
1.143     nicm      527:                        if (~client_flags & CLIENT_CONTROL)
1.132     nicm      528:                                close(msg->fd); /* can only be used once */
                    529:                }
                    530:        }
                    531:        if (cf->fd == -1) {
                    532:                error = errno;
                    533:                goto reply;
                    534:        }
                    535:
                    536:        cf->event = bufferevent_new(cf->fd, NULL, client_write_callback,
                    537:            client_write_error_callback, cf);
                    538:        bufferevent_enable(cf->event, EV_WRITE);
                    539:        goto reply;
                    540:
                    541: reply:
                    542:        reply.stream = msg->stream;
                    543:        reply.error = error;
                    544:        proc_send(client_peer, MSG_WRITE_READY, -1, &reply, sizeof reply);
                    545: }
                    546:
                    547: /* Write to client file. */
                    548: static void
                    549: client_write_data(void *data, size_t datalen)
                    550: {
                    551:        struct msg_write_data   *msg = data;
                    552:        struct client_file       find, *cf;
1.135     nicm      553:        size_t                   size = datalen - sizeof *msg;
1.132     nicm      554:
1.135     nicm      555:        if (datalen < sizeof *msg)
1.132     nicm      556:                fatalx("bad MSG_WRITE size");
                    557:        find.stream = msg->stream;
                    558:        if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL)
                    559:                fatalx("unknown stream number");
1.135     nicm      560:        log_debug("write %zu to file %d", size, cf->stream);
1.132     nicm      561:
                    562:        if (cf->event != NULL)
1.135     nicm      563:                bufferevent_write(cf->event, msg + 1, size);
1.132     nicm      564: }
                    565:
                    566: /* Close client file. */
                    567: static void
                    568: client_write_close(void *data, size_t datalen)
                    569: {
                    570:        struct msg_write_close  *msg = data;
                    571:        struct client_file       find, *cf;
1.54      nicm      572:
1.132     nicm      573:        if (datalen != sizeof *msg)
                    574:                fatalx("bad MSG_WRITE_CLOSE size");
                    575:        find.stream = msg->stream;
                    576:        if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL)
                    577:                fatalx("unknown stream number");
                    578:        log_debug("close file %d", cf->stream);
                    579:
                    580:        if (cf->event == NULL || EVBUFFER_LENGTH(cf->event->output) == 0) {
                    581:                if (cf->event != NULL)
                    582:                        bufferevent_free(cf->event);
                    583:                if (cf->fd != -1)
                    584:                        close(cf->fd);
                    585:                RB_REMOVE(client_files, &client_files, cf);
                    586:                file_free(cf);
                    587:        }
1.54      nicm      588: }
                    589:
1.132     nicm      590: /* File read callback. */
1.114     nicm      591: static void
1.132     nicm      592: client_read_callback(__unused struct bufferevent *bev, void *arg)
1.57      nicm      593: {
1.132     nicm      594:        struct client_file      *cf = arg;
                    595:        void                    *bdata;
                    596:        size_t                   bsize;
1.135     nicm      597:        struct msg_read_data    *msg;
                    598:        size_t                   msglen;
1.132     nicm      599:
1.135     nicm      600:        msg = xmalloc(sizeof *msg);
1.132     nicm      601:        for (;;) {
                    602:                bdata = EVBUFFER_DATA(cf->event->input);
                    603:                bsize = EVBUFFER_LENGTH(cf->event->input);
1.57      nicm      604:
1.132     nicm      605:                if (bsize == 0)
1.57      nicm      606:                        break;
1.136     nicm      607:                if (bsize > MAX_IMSGSIZE - IMSG_HEADER_SIZE - sizeof *msg)
                    608:                        bsize = MAX_IMSGSIZE - IMSG_HEADER_SIZE - sizeof *msg;
1.132     nicm      609:                log_debug("read %zu from file %d", bsize, cf->stream);
                    610:
1.135     nicm      611:                msglen = (sizeof *msg) + bsize;
                    612:                msg = xrealloc(msg, msglen);
                    613:                msg->stream = cf->stream;
                    614:                memcpy(msg + 1, bdata, bsize);
                    615:                proc_send(client_peer, MSG_READ, -1, msg, msglen);
1.132     nicm      616:
                    617:                evbuffer_drain(cf->event->input, bsize);
                    618:        }
1.135     nicm      619:        free(msg);
1.132     nicm      620: }
                    621:
                    622: /* File read error callback. */
                    623: static void
                    624: client_read_error_callback(__unused struct bufferevent *bev,
                    625:     __unused short what, void *arg)
                    626: {
                    627:        struct client_file      *cf = arg;
                    628:        struct msg_read_done     msg;
                    629:
                    630:        log_debug("read error file %d", cf->stream);
                    631:
                    632:        msg.stream = cf->stream;
                    633:        msg.error = 0;
                    634:        proc_send(client_peer, MSG_READ_DONE, -1, &msg, sizeof msg);
                    635:
                    636:        bufferevent_free(cf->event);
                    637:        close(cf->fd);
                    638:        RB_REMOVE(client_files, &client_files, cf);
                    639:        file_free(cf);
                    640: }
                    641:
                    642: /* Open read file. */
                    643: static void
                    644: client_read_open(void *data, size_t datalen)
                    645: {
                    646:        struct msg_read_open    *msg = data;
1.135     nicm      647:        const char              *path;
1.132     nicm      648:        struct msg_read_done     reply;
                    649:        struct client_file       find, *cf;
                    650:        const int                flags = O_NONBLOCK|O_RDONLY;
1.140     nicm      651:        int                      error;
1.132     nicm      652:
1.135     nicm      653:        if (datalen < sizeof *msg)
1.132     nicm      654:                fatalx("bad MSG_READ_OPEN size");
1.135     nicm      655:        if (datalen == sizeof *msg)
                    656:                path = "-";
                    657:        else
                    658:                path = (const char *)(msg + 1);
                    659:        log_debug("open read file %d %s", msg->stream, path);
1.132     nicm      660:
                    661:        find.stream = msg->stream;
                    662:        if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL) {
                    663:                cf = file_create(NULL, msg->stream, NULL, NULL);
                    664:                RB_INSERT(client_files, &client_files, cf);
                    665:        } else {
                    666:                error = EBADF;
                    667:                goto reply;
1.57      nicm      668:        }
1.132     nicm      669:        if (cf->closed) {
                    670:                error = EBADF;
                    671:                goto reply;
                    672:        }
                    673:
                    674:        cf->fd = -1;
                    675:        if (msg->fd == -1)
1.135     nicm      676:                cf->fd = open(path, flags);
1.132     nicm      677:        else {
                    678:                if (msg->fd != STDIN_FILENO)
                    679:                        errno = EBADF;
                    680:                else {
                    681:                        cf->fd = dup(msg->fd);
1.143     nicm      682:                        if (~client_flags & CLIENT_CONTROL)
                    683:                                close(msg->fd); /* can only be used once */
1.132     nicm      684:                }
                    685:        }
                    686:        if (cf->fd == -1) {
                    687:                error = errno;
                    688:                goto reply;
                    689:        }
                    690:
                    691:        cf->event = bufferevent_new(cf->fd, client_read_callback, NULL,
                    692:            client_read_error_callback, cf);
                    693:        bufferevent_enable(cf->event, EV_READ);
                    694:        return;
                    695:
                    696: reply:
                    697:        reply.stream = msg->stream;
                    698:        reply.error = error;
                    699:        proc_send(client_peer, MSG_READ_DONE, -1, &reply, sizeof reply);
1.57      nicm      700: }
                    701:
1.93      nicm      702: /* Run command in shell; used for -c. */
1.114     nicm      703: static __dead void
1.111     nicm      704: client_exec(const char *shell, const char *shellcmd)
1.93      nicm      705: {
                    706:        const char      *name, *ptr;
                    707:        char            *argv0;
                    708:
1.111     nicm      709:        log_debug("shell %s, command %s", shell, shellcmd);
1.93      nicm      710:
                    711:        ptr = strrchr(shell, '/');
                    712:        if (ptr != NULL && *(ptr + 1) != '\0')
                    713:                name = ptr + 1;
                    714:        else
                    715:                name = shell;
                    716:        if (client_flags & CLIENT_LOGIN)
                    717:                xasprintf(&argv0, "-%s", name);
                    718:        else
                    719:                xasprintf(&argv0, "%s", name);
                    720:        setenv("SHELL", shell, 1);
                    721:
1.123     nicm      722:        proc_clear_signals(client_proc, 1);
                    723:
1.93      nicm      724:        setblocking(STDIN_FILENO, 1);
                    725:        setblocking(STDOUT_FILENO, 1);
                    726:        setblocking(STDERR_FILENO, 1);
                    727:        closefrom(STDERR_FILENO + 1);
                    728:
1.111     nicm      729:        execl(shell, argv0, "-c", shellcmd, (char *) NULL);
1.93      nicm      730:        fatal("execl failed");
                    731: }
                    732:
1.99      nicm      733: /* Callback to handle signals in the client. */
1.114     nicm      734: static void
1.99      nicm      735: client_signal(int sig)
                    736: {
                    737:        struct sigaction sigact;
                    738:        int              status;
                    739:
                    740:        if (sig == SIGCHLD)
                    741:                waitpid(WAIT_ANY, &status, WNOHANG);
                    742:        else if (!client_attached) {
                    743:                if (sig == SIGTERM)
                    744:                        proc_exit(client_proc);
                    745:        } else {
                    746:                switch (sig) {
                    747:                case SIGHUP:
                    748:                        client_exitreason = CLIENT_EXIT_LOST_TTY;
                    749:                        client_exitval = 1;
                    750:                        proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    751:                        break;
                    752:                case SIGTERM:
                    753:                        client_exitreason = CLIENT_EXIT_TERMINATED;
                    754:                        client_exitval = 1;
                    755:                        proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    756:                        break;
                    757:                case SIGWINCH:
                    758:                        proc_send(client_peer, MSG_RESIZE, -1, NULL, 0);
                    759:                        break;
                    760:                case SIGCONT:
                    761:                        memset(&sigact, 0, sizeof sigact);
                    762:                        sigemptyset(&sigact.sa_mask);
                    763:                        sigact.sa_flags = SA_RESTART;
                    764:                        sigact.sa_handler = SIG_IGN;
                    765:                        if (sigaction(SIGTSTP, &sigact, NULL) != 0)
                    766:                                fatal("sigaction failed");
                    767:                        proc_send(client_peer, MSG_WAKEUP, -1, NULL, 0);
                    768:                        break;
                    769:                }
                    770:        }
                    771: }
                    772:
                    773: /* Callback for client read events. */
1.114     nicm      774: static void
1.121     nicm      775: client_dispatch(struct imsg *imsg, __unused void *arg)
1.99      nicm      776: {
                    777:        if (imsg == NULL) {
                    778:                client_exitreason = CLIENT_EXIT_LOST_SERVER;
                    779:                client_exitval = 1;
1.109     nicm      780:                proc_exit(client_proc);
                    781:                return;
                    782:        }
                    783:
                    784:        if (client_attached)
1.99      nicm      785:                client_dispatch_attached(imsg);
                    786:        else
1.121     nicm      787:                client_dispatch_wait(imsg);
1.99      nicm      788: }
                    789:
1.46      nicm      790: /* Dispatch imsgs when in wait state (before MSG_READY). */
1.114     nicm      791: static void
1.121     nicm      792: client_dispatch_wait(struct imsg *imsg)
1.46      nicm      793: {
1.132     nicm      794:        char            *data;
                    795:        ssize_t          datalen;
                    796:        int              retval;
                    797:        static int       pledge_applied;
1.97      nicm      798:
                    799:        /*
                    800:         * "sendfd" is no longer required once all of the identify messages
                    801:         * have been sent. We know the server won't send us anything until that
                    802:         * point (because we don't ask it to), so we can drop "sendfd" once we
                    803:         * get the first message from the server.
                    804:         */
                    805:        if (!pledge_applied) {
1.132     nicm      806:                if (pledge(
                    807:                    "stdio rpath wpath cpath unix proc exec tty",
                    808:                    NULL) != 0)
1.97      nicm      809:                        fatal("pledge failed");
                    810:                pledge_applied = 1;
1.132     nicm      811:        }
1.46      nicm      812:
1.99      nicm      813:        data = imsg->data;
                    814:        datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
1.60      nicm      815:
1.99      nicm      816:        switch (imsg->hdr.type) {
                    817:        case MSG_EXIT:
                    818:        case MSG_SHUTDOWN:
                    819:                if (datalen != sizeof retval && datalen != 0)
                    820:                        fatalx("bad MSG_EXIT size");
                    821:                if (datalen == sizeof retval) {
                    822:                        memcpy(&retval, data, sizeof retval);
                    823:                        client_exitval = retval;
                    824:                }
1.133     nicm      825:                client_exitflag = 1;
                    826:                client_exit();
1.99      nicm      827:                break;
                    828:        case MSG_READY:
                    829:                if (datalen != 0)
                    830:                        fatalx("bad MSG_READY size");
1.54      nicm      831:
1.99      nicm      832:                client_attached = 1;
                    833:                proc_send(client_peer, MSG_RESIZE, -1, NULL, 0);
                    834:                break;
                    835:        case MSG_VERSION:
                    836:                if (datalen != 0)
                    837:                        fatalx("bad MSG_VERSION size");
                    838:
                    839:                fprintf(stderr, "protocol version mismatch "
                    840:                    "(client %d, server %u)\n", PROTOCOL_VERSION,
1.103     nicm      841:                    imsg->hdr.peerid & 0xff);
1.99      nicm      842:                client_exitval = 1;
                    843:                proc_exit(client_proc);
                    844:                break;
                    845:        case MSG_SHELL:
                    846:                if (datalen == 0 || data[datalen - 1] != '\0')
                    847:                        fatalx("bad MSG_SHELL string");
                    848:
1.121     nicm      849:                client_exec(data, shell_command);
1.99      nicm      850:                /* NOTREACHED */
                    851:        case MSG_DETACH:
                    852:        case MSG_DETACHKILL:
                    853:                proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    854:                break;
                    855:        case MSG_EXITED:
                    856:                proc_exit(client_proc);
1.132     nicm      857:                break;
                    858:        case MSG_READ_OPEN:
                    859:                client_read_open(data, datalen);
                    860:                break;
                    861:        case MSG_WRITE_OPEN:
                    862:                client_write_open(data, datalen);
                    863:                break;
                    864:        case MSG_WRITE:
                    865:                client_write_data(data, datalen);
                    866:                break;
                    867:        case MSG_WRITE_CLOSE:
                    868:                client_write_close(data, datalen);
1.137     nicm      869:                break;
                    870:        case MSG_OLDSTDERR:
                    871:        case MSG_OLDSTDIN:
                    872:        case MSG_OLDSTDOUT:
                    873:                fprintf(stderr, "server version is too old for client\n");
                    874:                proc_exit(client_proc);
1.99      nicm      875:                break;
1.46      nicm      876:        }
                    877: }
                    878:
                    879: /* Dispatch imsgs in attached state (after MSG_READY). */
1.114     nicm      880: static void
1.99      nicm      881: client_dispatch_attached(struct imsg *imsg)
1.9       nicm      882: {
1.69      nicm      883:        struct sigaction         sigact;
                    884:        char                    *data;
1.99      nicm      885:        ssize_t                  datalen;
1.9       nicm      886:
1.99      nicm      887:        data = imsg->data;
                    888:        datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
1.12      nicm      889:
1.99      nicm      890:        switch (imsg->hdr.type) {
                    891:        case MSG_DETACH:
                    892:        case MSG_DETACHKILL:
                    893:                if (datalen == 0 || data[datalen - 1] != '\0')
                    894:                        fatalx("bad MSG_DETACH string");
                    895:
                    896:                client_exitsession = xstrdup(data);
                    897:                client_exittype = imsg->hdr.type;
                    898:                if (imsg->hdr.type == MSG_DETACHKILL)
                    899:                        client_exitreason = CLIENT_EXIT_DETACHED_HUP;
                    900:                else
                    901:                        client_exitreason = CLIENT_EXIT_DETACHED;
1.115     nicm      902:                proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    903:                break;
                    904:        case MSG_EXEC:
                    905:                if (datalen == 0 || data[datalen - 1] != '\0' ||
                    906:                    strlen(data) + 1 == (size_t)datalen)
                    907:                        fatalx("bad MSG_EXEC string");
                    908:                client_execcmd = xstrdup(data);
                    909:                client_execshell = xstrdup(data + strlen(data) + 1);
                    910:
                    911:                client_exittype = imsg->hdr.type;
1.99      nicm      912:                proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    913:                break;
                    914:        case MSG_EXIT:
                    915:                if (datalen != 0 && datalen != sizeof (int))
                    916:                        fatalx("bad MSG_EXIT size");
1.9       nicm      917:
1.99      nicm      918:                proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    919:                client_exitreason = CLIENT_EXIT_EXITED;
                    920:                break;
                    921:        case MSG_EXITED:
                    922:                if (datalen != 0)
                    923:                        fatalx("bad MSG_EXITED size");
1.9       nicm      924:
1.99      nicm      925:                proc_exit(client_proc);
                    926:                break;
                    927:        case MSG_SHUTDOWN:
                    928:                if (datalen != 0)
                    929:                        fatalx("bad MSG_SHUTDOWN size");
                    930:
                    931:                proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
                    932:                client_exitreason = CLIENT_EXIT_SERVER_EXITED;
                    933:                client_exitval = 1;
                    934:                break;
                    935:        case MSG_SUSPEND:
                    936:                if (datalen != 0)
                    937:                        fatalx("bad MSG_SUSPEND size");
                    938:
                    939:                memset(&sigact, 0, sizeof sigact);
                    940:                sigemptyset(&sigact.sa_mask);
                    941:                sigact.sa_flags = SA_RESTART;
                    942:                sigact.sa_handler = SIG_DFL;
                    943:                if (sigaction(SIGTSTP, &sigact, NULL) != 0)
                    944:                        fatal("sigaction failed");
                    945:                kill(getpid(), SIGTSTP);
                    946:                break;
                    947:        case MSG_LOCK:
                    948:                if (datalen == 0 || data[datalen - 1] != '\0')
                    949:                        fatalx("bad MSG_LOCK string");
1.9       nicm      950:
1.99      nicm      951:                system(data);
                    952:                proc_send(client_peer, MSG_UNLOCK, -1, NULL, 0);
                    953:                break;
1.9       nicm      954:        }
1.1       nicm      955: }