reach

ssh by name on the local network
git clone https://github.com/tortr-rs/reach
Log | Files | Refs | README | LICENSE

reach.c (7918B)


      1 /* reach: ssh by name on the local network. "reach start" answers to its name, "reach NAME" finds it, puts your
      2  * key there the first time (ssh asks the password once) and logs in. ssh does the connecting, reach only finds. */
      3 #if (defined(__x86_64__) || defined(__i386__)) && !defined(LIBC)
      4 #include "c.h"
      5 #else
      6 #define _GNU_SOURCE
      7 #include <arpa/inet.h>
      8 #include <errno.h>
      9 #include <fcntl.h>
     10 #include <netinet/in.h>
     11 #include <poll.h>
     12 #include <pwd.h>
     13 #include <signal.h>
     14 #include <stdio.h>
     15 #include <stdlib.h>
     16 #include <string.h>
     17 #include <strings.h>
     18 #include <sys/socket.h>
     19 #include <sys/stat.h>
     20 #include <sys/wait.h>
     21 #include <unistd.h>
     22 #endif
     23 
     24 #define PORT 7177
     25 #define ASK "reach?"
     26 
     27 static void die(const char *m)
     28 {
     29     fprintf(stderr, "reach: %s\n", m);
     30     exit(1);
     31 }
     32 
     33 static const char *home(void)
     34 {
     35     const char *h = getenv("HOME");
     36     struct passwd *p;
     37     if (h && *h) return h;
     38     p = getpwuid(getuid());
     39     return p ? p->pw_dir : "/";
     40 }
     41 
     42 static const char *me(void)
     43 {
     44     struct passwd *p = getpwuid(getuid());
     45     const char *u = getenv("USER");
     46     return p ? p->pw_name : u ? u : "root";
     47 }
     48 
     49 static int run(char *const av[], int in)
     50 {
     51     int st;
     52     pid_t p = fork();
     53     if (p < 0) return -1;
     54     if (!p) {
     55         if (in >= 0) { dup2(in, 0); close(in); }
     56         execvp(av[0], av);
     57         _exit(127);
     58     }
     59     while (waitpid(p, &st, 0) < 0) if (errno != EINTR) return -1;
     60     return WIFEXITED(st) ? WEXITSTATUS(st) : -1;
     61 }
     62 
     63 static int udp(int port)
     64 {
     65     int fd = socket(AF_INET, SOCK_DGRAM, 0), on = 1;
     66     struct sockaddr_in a;
     67     if (fd < 0) die("no socket");
     68     setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &on, sizeof on);
     69     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof on);
     70     memset(&a, 0, sizeof a);
     71     a.sin_family = AF_INET;
     72     a.sin_port = htons(port);
     73     if (bind(fd, (struct sockaddr *)&a, sizeof a) < 0) return -1;
     74     return fd;
     75 }
     76 
     77 /* sshd: up already if something takes a connection on 22, else started through doas */
     78 static int listening(void)
     79 {
     80     int fd = socket(AF_INET, SOCK_STREAM, 0), r;
     81     struct sockaddr_in a;
     82     memset(&a, 0, sizeof a);
     83     a.sin_family = AF_INET;
     84     a.sin_port = htons(22);
     85     a.sin_addr.s_addr = htonl(0x7f000001);
     86     r = connect(fd, (struct sockaddr *)&a, sizeof a);
     87     close(fd);
     88     return r == 0;
     89 }
     90 
     91 static void sshd(void)
     92 {
     93     char *root[] = { "sh", "-c", "ssh-keygen -A >/dev/null && /usr/sbin/sshd", NULL };
     94     char *doas[] = { "doas", "sh", "-c", "ssh-keygen -A >/dev/null && /usr/sbin/sshd", NULL };
     95     if (listening()) return;
     96     if (access("/usr/sbin/sshd", X_OK)) die("there is no sshd: install openssh-server");
     97     if (run(getuid() ? doas : root, -1)) die("sshd did not start");
     98 }
     99 
    100 static char *pidfile(void)
    101 {
    102     static char f[512];
    103     snprintf(f, sizeof f, "%s/.cache/reach.pid", home());
    104     return f;
    105 }
    106 
    107 static void start(const char *name)
    108 {
    109     char host[256], reply[600], buf[64];
    110     struct sockaddr_in from;
    111     socklen_t fl;
    112     FILE *f;
    113     int fd;
    114     pid_t p;
    115     if (!name) {
    116         if (gethostname(host, sizeof host)) die("no host name");
    117         name = host;
    118     }
    119     sshd();
    120     if ((fd = udp(PORT)) < 0) die("port 7177 is taken: is reach running already? (reach stop)");
    121     snprintf(reply, sizeof reply, "reach %s %s", name, me());
    122     if ((p = fork()) < 0) die("fork failed");
    123     if (p) {
    124         snprintf(buf, sizeof buf, "%s/.cache", home());
    125         mkdir(buf, 0755);
    126         if ((f = fopen(pidfile(), "w"))) { fprintf(f, "%d\n", (int)p); fclose(f); }
    127         printf("reach: answering as %s\n", name);
    128         return;
    129     }
    130     setsid();
    131     if ((p = open("/dev/null", O_RDWR)) >= 0) { dup2(p, 0); dup2(p, 1); dup2(p, 2); if (p > 2) close(p); }
    132     for (;;) {
    133         ssize_t n;
    134         fl = sizeof from;
    135         n = recvfrom(fd, buf, sizeof buf - 1, 0, (struct sockaddr *)&from, &fl);
    136         if (n < 0) continue;
    137         buf[n] = 0;
    138         if (!strcmp(buf, ASK)) sendto(fd, reply, strlen(reply), 0, (struct sockaddr *)&from, fl);
    139     }
    140 }
    141 
    142 static void stop(void)
    143 {
    144     FILE *f = fopen(pidfile(), "r");
    145     int p = 0;
    146     if (!f || fscanf(f, "%d", &p) != 1 || p <= 0) die("reach is not running here");
    147     fclose(f);
    148     if (kill(p, SIGTERM)) die("reach is not running here");
    149     unlink(pidfile());
    150     puts("reach: stopped");
    151 }
    152 
    153 struct peer { char name[256], user[64], ip[16]; };
    154 
    155 /* asks the network, gives what answered within a second */
    156 static int ask(struct peer *pe, int max)
    157 {
    158     int fd = udp(0), n = 0;
    159     struct sockaddr_in a, from;
    160     socklen_t fl;
    161     struct pollfd pf;
    162     char buf[600];
    163     if (fd < 0) die("no socket");
    164     memset(&a, 0, sizeof a);
    165     a.sin_family = AF_INET;
    166     a.sin_port = htons(PORT);
    167     a.sin_addr.s_addr = htonl(0xffffffff);
    168     sendto(fd, ASK, strlen(ASK), 0, (struct sockaddr *)&a, sizeof a);
    169     pf.fd = fd;
    170     pf.events = POLLIN;
    171     while (n < max && poll(&pf, 1, 1000) > 0) {
    172         ssize_t r;
    173         fl = sizeof from;
    174         r = recvfrom(fd, buf, sizeof buf - 1, 0, (struct sockaddr *)&from, &fl);
    175         if (r <= 0) continue;
    176         buf[r] = 0;
    177         if (sscanf(buf, "reach %255s %63s", pe[n].name, pe[n].user) != 2) continue;
    178         snprintf(pe[n].ip, sizeof pe[n].ip, "%s", inet_ntoa(from.sin_addr));
    179         n++;
    180     }
    181     close(fd);
    182     return n;
    183 }
    184 
    185 static void list(void)
    186 {
    187     struct peer pe[64];
    188     int i, n = ask(pe, 64);
    189     if (!n) die("nothing answered: run reach start on the other machine");
    190     for (i = 0; i < n; i++) printf("%-20s %-15s %s\n", pe[i].name, pe[i].ip, pe[i].user);
    191 }
    192 
    193 static void go(const char *name, int argc, char **argv)
    194 {
    195     struct peer pe[64];
    196     char key[512], pub[520], to[340], *av[64];
    197     int i, n = ask(pe, 64), k, fd;
    198     for (i = 0; i < n && strcasecmp(pe[i].name, name); i++) {}
    199     if (i == n) {
    200         fprintf(stderr, "reach: %s did not answer%s\n", name, n ? ", these did:" : "");
    201         for (k = 0; k < n; k++) fprintf(stderr, "  %s\n", pe[k].name);
    202         exit(1);
    203     }
    204     snprintf(to, sizeof to, "%s@%s", pe[i].user, pe[i].ip);
    205     snprintf(key, sizeof key, "%s/.ssh/id_ed25519", home());
    206     snprintf(pub, sizeof pub, "%s.pub", key);
    207     if (access(pub, R_OK)) {
    208         char *gen[] = { "ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", key, NULL };
    209         snprintf(to, sizeof to, "%s/.ssh", home());
    210         mkdir(to, 0700);
    211         snprintf(to, sizeof to, "%s@%s", pe[i].user, pe[i].ip);
    212         if (run(gen, -1)) die("ssh-keygen failed");
    213     }
    214     {
    215         char *test[] = { "ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "-o", "StrictHostKeyChecking=accept-new", to, "true", NULL };
    216         char *copy[] = { "ssh", "-o", "StrictHostKeyChecking=accept-new", to,
    217             "umask 077; mkdir -p .ssh && cat >> .ssh/authorized_keys", NULL };
    218         if (run(test, -1)) {
    219             printf("reach: first time on %s, its password puts your key there\n", pe[i].name);
    220             if ((fd = open(pub, O_RDONLY)) < 0) die("cannot read the key");
    221             if (run(copy, fd)) die("the key did not get there");
    222             close(fd);
    223         }
    224     }
    225     k = 0;
    226     av[k++] = "ssh";
    227     av[k++] = to;
    228     for (i = 0; i < argc && k < 63; i++) av[k++] = argv[i];
    229     av[k] = NULL;
    230     execvp("ssh", av);
    231     die("there is no ssh: install openssh-client");
    232 }
    233 
    234 static void usage(void)
    235 {
    236     fputs("usage: reach start [NAME]   answer to NAME (the host name) on this network, sshd started if needed\n"
    237           "       reach stop           stop answering\n"
    238           "       reach list           what answers on this network\n"
    239           "       reach NAME [CMD]     log in to NAME, or run CMD there\n", stderr);
    240     exit(2);
    241 }
    242 
    243 int main(int argc, char **argv)
    244 {
    245     if (argc < 2) usage();
    246     if (!strcmp(argv[1], "start")) start(argc > 2 ? argv[2] : NULL);
    247     else if (!strcmp(argv[1], "stop")) stop();
    248     else if (!strcmp(argv[1], "list")) list();
    249     else if (argv[1][0] == '-') usage();
    250     else go(argv[1], argc - 2, argv + 2);
    251     return 0;
    252 }