aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

mdev.c (13933B)


      1 /* see LICENSE file for copyright and license details */
      2 
      3 #define _DEFAULT_SOURCE /* clearenv, putenv */
      4 
      5 #include <sys/socket.h>
      6 #include <sys/stat.h>
      7 #include <sys/sysmacros.h>
      8 #include <sys/types.h>
      9 #include <sys/uio.h>
     10 #include <sys/wait.h>
     11 
     12 #include <linux/netlink.h>
     13 
     14 #include <dirent.h>
     15 #include <errno.h>
     16 #include <fcntl.h>
     17 #include <grp.h>
     18 #include <limits.h>
     19 #include <pwd.h>
     20 #include <regex.h>
     21 #include <signal.h>
     22 #include <stdio.h>
     23 #include <stdlib.h>
     24 #include <string.h>
     25 #include <unistd.h>
     26 
     27 #include "paths.h"
     28 #include "util.h"
     29 
     30 #define CONF      "/etc/mdev.conf"
     31 #define EVENT_MAX 8192
     32 #define ENV_MAX   64
     33 #define RCVBUF    (4 << 20) /* the burst of a dock or a hub, or of the replay at start */
     34 
     35 /* a line of mdev.conf:
     36  *
     37  *   [-][$VAR=]regex  user:group mode [=path | >path | !] [@cmd | $cmd | *cmd]
     38  *   [-]@maj,min[-min2] ...
     39  *
     40  * the regex is matched against the device's name under /dev, or with $VAR=
     41  * against the event's VAR. the first line that matches is taken, a line
     42  * starting with - is taken and the matching goes on */
     43 struct rule {
     44   int     cont;
     45   char    env[64]; /* "" for the device's name */
     46   int     bymaj, maj, min0, min1;
     47   regex_t re;
     48   uid_t   uid;
     49   gid_t   gid;
     50   mode_t  mode;
     51   char    place; /* 0, '=' to move the node, '>' to move it and link it back, '!' for none */
     52   char    path[PATH_MAX];
     53   char    when; /* 0, '@' after it is added, '$' before it goes, '*' both */
     54   char    cmd[512];
     55 };
     56 
     57 /* an event: the kernel's KEY=value fields */
     58 struct event {
     59   char *kv[ENV_MAX];
     60   int   n;
     61 };
     62 
     63 static struct rule *rules;
     64 static int          nrules;
     65 static int          vflag;
     66 
     67 static void
     68 usage(void)
     69 {
     70   eprintf("usage: %s [-s | -d [-f]] [-v]\n", argv0);
     71 }
     72 
     73 static int
     74 owner(const char *spec, uid_t *uid, gid_t *gid)
     75 {
     76   char           u[64], g[64], *end;
     77   struct passwd *pw;
     78   struct group  *gr;
     79 
     80   if (sscanf(spec, "%63[^:]:%63s", u, g) != 2)
     81     return -1;
     82   *uid = (uid_t)strtoul(u, &end, 10);
     83   if (*end) {
     84     if (!(pw = getpwnam(u)))
     85       return -1;
     86     *uid = pw->pw_uid;
     87   }
     88   *gid = (gid_t)strtoul(g, &end, 10);
     89   if (*end) {
     90     if (!(gr = getgrnam(g)))
     91       return -1;
     92     *gid = gr->gr_gid;
     93   }
     94   return 0;
     95 }
     96 
     97 static void
     98 load(const char *path)
     99 {
    100   FILE *f;
    101   char  line[1024];
    102   int   n = 0;
    103 
    104   if (!(f = fopen(path, "r"))) {
    105     if (errno != ENOENT)
    106       weprintf("%s:", path);
    107     return;
    108   }
    109   while (fgets(line, sizeof line, f)) {
    110     struct rule r;
    111     char        pat[256], own[128], mode[16], *p = line, *rest, re[300];
    112     int         used = 0;
    113 
    114     n++;
    115     line[strcspn(line, "\n")] = '\0';
    116     p += strspn(p, " \t");
    117     if (*p == '#' || *p == '\0')
    118       continue;
    119     memset(&r, 0, sizeof r);
    120     if (*p == '-') {
    121       r.cont = 1;
    122       p++;
    123     }
    124     if (sscanf(p, "%255s %127s %15s %n", pat, own, mode, &used) < 3) {
    125       weprintf("%s:%d: not \"device user:group mode\"\n", path, n);
    126       continue;
    127     }
    128     rest = p + used;
    129     if (owner(own, &r.uid, &r.gid) < 0) {
    130       weprintf("%s:%d: no such user or group: %s\n", path, n, own);
    131       continue;
    132     }
    133     r.mode = (mode_t)strtoul(mode, NULL, 8) & 07777;
    134     if (pat[0] == '@') {
    135       r.bymaj = 1;
    136       r.min1  = -1;
    137       if (sscanf(pat + 1, "%d,%d-%d", &r.maj, &r.min0, &r.min1) < 2) {
    138         weprintf("%s:%d: not @major,minor[-minor]\n", path, n);
    139         continue;
    140       }
    141       if (r.min1 < 0)
    142         r.min1 = r.min0;
    143     } else {
    144       const char *rx = pat;
    145       char       *eq;
    146 
    147       if (pat[0] == '$' && (eq = strchr(pat, '='))) {
    148         *eq = '\0';
    149         estrlcpy(r.env, pat + 1, sizeof r.env);
    150         rx = eq + 1;
    151       }
    152       /* the whole name, as mdev has it */
    153       snprintf(re, sizeof re, "^(%s)$", rx);
    154       if (regcomp(&r.re, re, REG_EXTENDED | REG_NOSUB) != 0) {
    155         weprintf("%s:%d: bad expression %s\n", path, n, rx);
    156         continue;
    157       }
    158     }
    159     rest += strspn(rest, " \t");
    160     if (*rest == '=' || *rest == '>' || *rest == '!') {
    161       r.place = *rest++;
    162       if (r.place != '!') {
    163         int k = (int)strcspn(rest, " \t");
    164 
    165         snprintf(r.path, sizeof r.path, "%.*s", k, rest);
    166         rest += k;
    167       }
    168       rest += strspn(rest, " \t");
    169     }
    170     if (*rest == '@' || *rest == '$' || *rest == '*') {
    171       r.when = *rest++;
    172       estrlcpy(r.cmd, rest, sizeof r.cmd);
    173     }
    174     rules           = ereallocarray(rules, (size_t)nrules + 1, sizeof *rules);
    175     rules[nrules++] = r;
    176   }
    177   fclose(f);
    178 }
    179 
    180 static const char *
    181 get(const struct event *e, const char *key)
    182 {
    183   size_t k = strlen(key);
    184   int    i;
    185 
    186   for (i = 0; i < e->n; i++)
    187     if (strncmp(e->kv[i], key, k) == 0 && e->kv[i][k] == '=')
    188       return e->kv[i] + k + 1;
    189   return NULL;
    190 }
    191 
    192 static int
    193 matches(const struct rule *r, const struct event *e, const char *name)
    194 {
    195   const char *v;
    196 
    197   if (r->bymaj) {
    198     const char *ma = get(e, "MAJOR"), *mi = get(e, "MINOR");
    199     int         m;
    200 
    201     if (!ma || !mi || atoi(ma) != r->maj)
    202       return 0;
    203     m = atoi(mi);
    204     return m >= r->min0 && m <= r->min1;
    205   }
    206   v = r->env[0] ? get(e, r->env) : name;
    207   return v && regexec(&r->re, v, 0, NULL, 0) == 0;
    208 }
    209 
    210 /* a directory for path, as mkdir -p */
    211 static void
    212 parents(const char *path)
    213 {
    214   char d[PATH_MAX], *s;
    215 
    216   estrlcpy(d, path, sizeof d);
    217   for (s = d + 1; (s = strchr(s, '/')); s++) {
    218     *s = '\0';
    219     mkdir(d, 0755);
    220     *s = '/';
    221   }
    222 }
    223 
    224 static void
    225 command(const struct rule *r, const struct event *e, const char *name)
    226 {
    227   pid_t pid;
    228   int   i;
    229 
    230   if ((pid = fork()) < 0) {
    231     weprintf("fork:");
    232     return;
    233   }
    234   if (pid == 0) {
    235     signal(SIGCHLD, SIG_DFL);
    236     clearenv();
    237     setenv("PATH", "/bin", 1);
    238     for (i = 0; i < e->n; i++)
    239       putenv(e->kv[i]);
    240     if (name)
    241       setenv("MDEV", name, 1);
    242     execl("/bin/sh", "sh", "-c", r->cmd, (char *)NULL);
    243     _exit(127);
    244   }
    245   while (waitpid(pid, NULL, 0) < 0 && errno == EINTR)
    246     ;
    247 }
    248 
    249 /* the node the kernel made, given its owner and mode, and put where the
    250  * line says */
    251 static void
    252 node(const struct rule *r, const char *name, int adding)
    253 {
    254   char dev[PATH_MAX], to[PATH_MAX];
    255 
    256   snprintf(dev, sizeof dev, "/dev/%s", name);
    257   if (!r->place || r->path[0] == '\0') {
    258     if (r->place == '!' && adding)
    259       unlink(dev);
    260   } else {
    261     /* a path ending in / keeps the name under it */
    262     if (r->path[strlen(r->path) - 1] == '/')
    263       snprintf(
    264           to, sizeof to, "/dev/%s%s", r->path, strrchr(name, '/') ? strrchr(name, '/') + 1 : name
    265       );
    266     else
    267       snprintf(to, sizeof to, "/dev/%s", r->path);
    268     if (adding) {
    269       parents(to);
    270       if (rename(dev, to) == 0 && r->place == '>')
    271         symlink(to + 5, dev);
    272       estrlcpy(dev, to, sizeof dev);
    273     } else {
    274       unlink(to);
    275       if (r->place == '>')
    276         unlink(dev);
    277       return;
    278     }
    279   }
    280   if (!adding || r->place == '!')
    281     return;
    282   if (chown(dev, r->uid, r->gid) < 0 || chmod(dev, r->mode) < 0) {
    283     if (errno != ENOENT)
    284       weprintf("%s:", dev);
    285     return;
    286   }
    287   if (vflag)
    288     printf("%s %u:%u %04o\n", dev, (unsigned)r->uid, (unsigned)r->gid, (unsigned)r->mode);
    289 }
    290 
    291 static void
    292 handle(const struct event *e)
    293 {
    294   const char *action = get(e, "ACTION"), *name = get(e, "DEVNAME");
    295   int         adding, removing, i;
    296 
    297   if (!action)
    298     return;
    299   adding   = !strcmp(action, "add") || !strcmp(action, "change");
    300   removing = !strcmp(action, "remove");
    301   for (i = 0; i < nrules; i++) {
    302     const struct rule *r = &rules[i];
    303 
    304     if (!matches(r, e, name))
    305       continue;
    306     if (name)
    307       node(r, name, adding);
    308     if ((r->when == '@' && !strcmp(action, "add")) || (r->when == '$' && removing)
    309         || (r->when == '*' && (!strcmp(action, "add") || removing)))
    310       command(r, e, name);
    311     if (!r->cont)
    312       break;
    313   }
    314 }
    315 
    316 /* the fields of a netlink message: "action@devpath" then KEY=value, each
    317  * ended by a NUL */
    318 static void
    319 from_buffer(struct event *e, char *buf, size_t n)
    320 {
    321   char *p;
    322 
    323   e->n = 0;
    324   for (p = buf; p < buf + n && e->n < ENV_MAX; p += strlen(p) + 1)
    325     if (strchr(p, '=') && !strchr(p, '@'))
    326       e->kv[e->n++] = p;
    327 }
    328 
    329 /* every device of the sysfs tree asked to say again that it was added, so
    330  * what was there before mdev listened comes through the same way: drivers,
    331  * nodes, lines with commands */
    332 static void
    333 replay(const char *dir)
    334 {
    335   DIR           *d;
    336   struct dirent *ent;
    337   char           path[PATH_MAX];
    338   int            fd;
    339 
    340   snprintf(path, sizeof path, "%s/uevent", dir);
    341   if ((fd = open(path, O_WRONLY | O_CLOEXEC)) >= 0) {
    342     if (write(fd, "add", 3) < 0) {
    343       /* a device that cannot be replayed is left as it is */
    344     }
    345     close(fd);
    346   }
    347   if (!(d = opendir(dir)))
    348     return;
    349   while ((ent = readdir(d))) {
    350     struct stat st;
    351 
    352     if (ent->d_name[0] == '.')
    353       continue;
    354     snprintf(path, sizeof path, "%s/%s", dir, ent->d_name);
    355     /* the tree's links lead back into it */
    356     if (lstat(path, &st) == 0 && S_ISDIR(st.st_mode))
    357       replay(path);
    358   }
    359   closedir(d);
    360 }
    361 
    362 /* -s: the nodes there now, from /sys/dev, each as if it had just been added */
    363 static void
    364 scan(const char *dir)
    365 {
    366   DIR           *d;
    367   struct dirent *ent;
    368 
    369   if (!(d = opendir(dir)))
    370     return;
    371   while ((ent = readdir(d))) {
    372     char         path[PATH_MAX], buf[EVENT_MAX], link[PATH_MAX], sub[80];
    373     struct event e;
    374     ssize_t      n, k;
    375     int          fd;
    376     char        *p;
    377 
    378     if (ent->d_name[0] == '.')
    379       continue;
    380     snprintf(path, sizeof path, "%s/%s/uevent", dir, ent->d_name);
    381     if ((fd = open(path, O_RDONLY | O_CLOEXEC)) < 0)
    382       continue;
    383     n = read(fd, buf, sizeof buf - 64);
    384     close(fd);
    385     if (n <= 0)
    386       continue;
    387     buf[n] = '\0';
    388     for (p = buf; (p = strchr(p, '\n')); p++)
    389       *p = '\0';
    390     /* what the kernel would have said besides: the action and the subsystem */
    391     memcpy(buf + n + 1, "ACTION=add", 11);
    392     from_buffer(&e, buf, (size_t)n + 12);
    393     snprintf(path, sizeof path, "%s/%s/subsystem", dir, ent->d_name);
    394     if ((k = readlink(path, link, sizeof link - 1)) > 0 && e.n < ENV_MAX) {
    395       link[k] = '\0';
    396       snprintf(sub, sizeof sub, "SUBSYSTEM=%s", strrchr(link, '/') ? strrchr(link, '/') + 1 : link);
    397       e.kv[e.n++] = sub;
    398     }
    399     handle(&e);
    400   }
    401   closedir(d);
    402 }
    403 
    404 static int
    405 listen_kernel(void)
    406 {
    407   struct sockaddr_nl sa;
    408   int                fd, size = RCVBUF;
    409 
    410   if ((fd = socket(AF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT)) < 0)
    411     eprintf("socket:");
    412   memset(&sa, 0, sizeof sa);
    413   sa.nl_family = AF_NETLINK;
    414   sa.nl_groups = 1;
    415   if (bind(fd, (struct sockaddr *)&sa, sizeof sa) < 0)
    416     eprintf("bind:");
    417   if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &size, sizeof size) < 0)
    418     setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof size);
    419   return fd;
    420 }
    421 
    422 // ?man mdev: gives the kernel's devices their owner, mode and place, and runs what mdev.conf says for them
    423 // ?man arguments: [-s | -d [-f]] [-v]
    424 // ?man mdev reads /etc/mdev.conf, BusyBox mdev's table, a line each:
    425 // ?man "[-][$VAR=]regex user:group mode [=path|>path|!] [@cmd|$cmd|*cmd]", or
    426 // ?man "@major,minor[-minor] ..." for a device by its numbers. the regex is
    427 // ?man matched against the device's name under /dev, or with $VAR= against the
    428 // ?man event's VAR (SUBSYSTEM, MODALIAS, DEVPATH...). the first line that
    429 // ?man matches is taken, and one starting with - is taken and the matching goes
    430 // ?man on. =path moves the node there, >path moves it and leaves a link, !
    431 // ?man takes it away. @cmd runs once the device is added, $cmd before it goes,
    432 // ?man *cmd both, through sh with the event's fields and MDEV, the device's
    433 // ?man name, in the environment. the kernel's devtmpfs makes and removes the
    434 // ?man nodes, mdev gives them what the table says. run with no option, it is a
    435 // ?man hotplug helper and takes the one event in its environment
    436 int
    437 main(int argc, char *argv[])
    438 {
    439   int  sflag = 0, dflag = 0;
    440   char buf[EVENT_MAX + 1];
    441 
    442   ARGBEGIN
    443   {
    444     // ?man -s: set every node there is now, and stop
    445     case 's':
    446       sflag = 1;
    447       break;
    448     // ?man -d: listen to the kernel's events and stay, having had every device
    449     // ?man there already say again that it was added
    450     case 'd':
    451       dflag = 1;
    452       break;
    453     // ?man -f: in the foreground, which mdev always is: for BusyBox's command lines
    454     case 'f':
    455       break;
    456     // ?man -v: say each node it sets
    457     case 'v':
    458       vflag = 1;
    459       break;
    460     default:
    461       usage();
    462   }
    463   ARGEND;
    464   if (argc || (sflag && dflag))
    465     usage();
    466 
    467   load(CONF);
    468   signal(SIGCHLD, SIG_DFL);
    469 
    470   if (sflag) {
    471     scan(ARUU_LINUX_PATH_SYS "/dev/char");
    472     scan(ARUU_LINUX_PATH_SYS "/dev/block");
    473     return 0;
    474   }
    475 
    476   if (!dflag) {
    477     extern char **environ;
    478     struct event  e;
    479     char        **p;
    480 
    481     e.n = 0;
    482     for (p = environ; *p && e.n < ENV_MAX; p++)
    483       e.kv[e.n++] = *p;
    484     handle(&e);
    485     return 0;
    486   }
    487 
    488   {
    489     int fd = listen_kernel();
    490 
    491     /* listening first: nothing added between the replay and the loop is lost */
    492     replay(ARUU_LINUX_PATH_SYS "/devices");
    493     for (;;) {
    494       struct sockaddr_nl from;
    495       struct iovec       iov = {buf, EVENT_MAX};
    496       struct msghdr      msg;
    497       struct event       e;
    498       ssize_t            n;
    499 
    500       memset(&msg, 0, sizeof msg);
    501       msg.msg_name    = &from;
    502       msg.msg_namelen = sizeof from;
    503       msg.msg_iov     = &iov;
    504       msg.msg_iovlen  = 1;
    505       if ((n = recvmsg(fd, &msg, 0)) < 0) {
    506         /* events were lost in a burst: the nodes are set over again */
    507         if (errno == ENOBUFS) {
    508           weprintf("events were lost, setting the nodes again\n");
    509           scan(ARUU_LINUX_PATH_SYS "/dev/char");
    510           scan(ARUU_LINUX_PATH_SYS "/dev/block");
    511           continue;
    512         }
    513         if (errno == EINTR)
    514           continue;
    515         eprintf("recv:");
    516       }
    517       /* the kernel's own, port 0: udev's rebroadcasts and anyone else's are not believed */
    518       if (from.nl_pid != 0 || n == 0 || !memchr(buf, '@', (size_t)n < 64 ? (size_t)n : 64))
    519         continue;
    520       buf[n] = '\0';
    521       from_buffer(&e, buf, (size_t)n);
    522       handle(&e);
    523     }
    524   }
    525 }