summary refs log tree commit diff
path: root/.bin/pbd.c
blob: 9e716d6d59e0e10881c6353181e27849aef31c0b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#if 0
exec clang -Weverything $@ -o $(dirname $0)/pbd $0
#endif

#include <err.h>
#include <netinet/in.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sysexits.h>
#include <unistd.h>

static void spawn(const char *cmd, int child_fd, int parent_fd) {
    pid_t pid = fork();
    if (pid < 0) err(EX_OSERR, "fork");

    if (pid) {
        int status;
        pid_t wait = waitpid(pid, &status, 0);
        if (wait < 0) err(EX_OSERR, "waitpid");

        if (status)
            warnx("child %s status %d", cmd, status);
    } else {
        int fd = dup2(parent_fd, child_fd);
        if (fd < 0) err(EX_OSERR, "dup2");

        int error = execlp(cmd, cmd);
        if (error) err(EX_OSERR, "execlp");
    }
}

int main() {
    int error;

    int server = socket(PF_INET, SOCK_STREAM, 0);
    if (server < 0) err(EX_OSERR, "socket");

    struct sockaddr_in addr = {
        .sin_family = AF_INET,
        .sin_port = htons(7062),
        .sin_addr = { .s_addr = htonl(0x7f000001) },
    };

    error = bind(server, (struct sockaddr *) &addr, sizeof(addr));
    if (error) err(EX_OSERR, "bind");

    error = listen(server, 1);
    if (error) err(EX_OSERR, "listen");

    for (;;) {
        int client = accept(server, NULL, NULL);
        if (client < 0) err(EX_OSERR, "accept");

        spawn("pbpaste", STDOUT_FILENO, client);

        uint8_t p;
        ssize_t peek = recv(client, &p, 1, MSG_PEEK);
        if (peek < 0) err(EX_IOERR, "recv");

        if (peek) spawn("pbcopy", STDIN_FILENO, client);

        error = close(client);
        if (error) err(EX_IOERR, "close");
    }
}
r EOFJune McEnroe 2022-06-02Set TABSIZE=4June McEnroe Absolutely indiscriminately. 2022-06-02Do basic match highlightingJune McEnroe 2022-06-02Clean up parsing a littleJune McEnroe 2022-06-02Don't duplicate path stringJune McEnroe 2022-06-02Use stderr instead of /dev/tty, realloc buffer if lines too longJune McEnroe For some reason I haven't been able to figure out, trying to poll /dev/tty returns POLLNVAL (and this was using 100% CPU looping), but using stderr instead works fine. 2022-06-02Add initial working version of qfJune McEnroe 2022-05-29Set prompt for okshJune McEnroe