aruu

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

commit cfb210c650a79e83f5994a5a7d2a8a3c120b800f
parent 94aff3fa42ac476238674520f7c7ed576c85fe94
Author: xplshn <anto@xplshn.com.ar>
Date:   Thu, 26 Nov 2026 04:09:08 -0300

ld and cpp fixed so programs that call libc run, partplan edits plans, mdev

Diffstat:
Mcmd/dev/cc/pp.c | 4++--
Mcmd/dev/cc/scan.c | 6+++++-
Mcmd/dev/ld/ld.c | 7++++++-
Mcmd/extra/partplan.c | 282++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Acmd/linux/mdev.c | 523+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5 files changed, 802 insertions(+), 20 deletions(-)

diff --git a/cmd/dev/cc/pp.c b/cmd/dev/cc/pp.c @@ -132,9 +132,9 @@ include(void) /* freestanding headers (stddef.h etc) the libc may not ship: an include/ dir next to the compiler in a source tree, lib/aruu/include in a - system whose binaries are all in bin/ */ + system whose binaries are in bin/, or beside a lib/aruu/bin they sit in */ if (!f) { - static const char *const rel[] = {"include", "../lib/aruu/include"}; + static const char *const rel[] = {"include", "../lib/aruu/include", "../include"}; char self[FILENAME_MAX]; ssize_t n = proc_selfexe(self, sizeof(self) - 1); if (n == -1) { diff --git a/cmd/dev/cc/scan.c b/cmd/dev/cc/scan.c @@ -510,13 +510,17 @@ scanclose(void) void scan(struct token *t) { + struct scanner *next; + scanner->sawspace = false; for (;;) { t->kind = scankind(scanner, &t->loc); if (t->kind != TEOF || !scanner->next) break; + /* the file that ended is freed: where to go on is taken first */ + next = scanner->next; scanclose(); - scanner = scanner->next; + scanner = next; scanopen(); } if (scanner->usebuf) { diff --git a/cmd/dev/ld/ld.c b/cmd/dev/ld/ld.c @@ -516,7 +516,12 @@ outelf_write(struct outelf *oe, int fd) write(fd, pad, gap); free(pad); } - code_end = sec->faddr + len; + /* an empty section can share its address with one that has code (musl's + * empty .text beside .text.strlen), and the order of equal addresses is + * qsort's: the end only moves forward, or the next gap fill writes over + * the code */ + if ((long)(sec->faddr + len) > code_end) + code_end = sec->faddr + len; lseek(fd, sec->faddr, SEEK_SET); write(fd, buf, len); } diff --git a/cmd/extra/partplan.c b/cmd/extra/partplan.c @@ -3,6 +3,7 @@ #include "arg.h" #include "util.h" +#include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -14,8 +15,10 @@ static void __attribute__((noreturn)) usage(void) { - eprintf("usage: %s guided [-s swap_mib] [-f root_fs] disk | disks | layout | show plan | check [-rb] plan | write plan |\n" - " mkfs plan | mounts plan | fstab plan | get plan esp|root|swap|bios|rootfs\n", + eprintf("usage: %s guided [-s swap_mib] [-f root_fs] disk | disks | layout | read disk | new [-m] disk |\n" + " show plan | gaps plan | changes plan | check [-rb] plan | write plan | mkfs plan | mounts plan |\n" + " fstab plan | get plan esp|root|swap|bios|rootfs |\n" + " add [-t type] [-l label] plan size fs [mount] | delete plan n | set [-k] [-l label] plan n fs [mount]\n", argv0); } @@ -26,9 +29,9 @@ load(struct plan *p, const char *path) FILE *f = path && strcmp(path, "-") ? fopen(path, "r") : stdin; if (!f) - eprintf("%s: %s:", argv0, path); + eprintf("%s:", path); if (plan_load(p, f, why, sizeof why) < 0) - eprintf("%s: %s: %s\n", argv0, path, why); + eprintf("%s: %s\n", path, why); if (f != stdin) fclose(f); return 0; @@ -84,7 +87,7 @@ do_guided(int argc, char *argv[]) if (argc != 1) usage(); if (plan_guided(&p, argv[0], swap, fs) < 0) - eprintf("%s: %s cannot hold the guided layout\n", argv0, argv[0]); + eprintf("%s cannot hold the guided layout\n", argv[0]); return plan_save(&p, stdout); } @@ -154,19 +157,19 @@ do_write(struct plan *p) int rc; if (blockdev_open(&dev, p->disk, 1) < 0) - eprintf("%s: %s:", argv0, p->disk); + eprintf("%s:", p->disk); /* what was there is read again as a signature of something: a filesystem, an old table */ rc = blockdev_write(&dev, 0, zero, SECTORS_ZEROED * 512 / dev.sec_size); free(zero); if (rc < 0) - weprintf("%s: could not clear the start of %s\n", argv0, p->disk); + weprintf("could not clear the start of %s\n", p->disk); rc = label_write(&dev, &p->label); blockdev_close(&dev); if (rc < 0) - eprintf("%s: could not write the partition table of %s\n", argv0, p->disk); + eprintf("could not write the partition table of %s\n", p->disk); /* a disk that is an image has no devices to wait for */ if (access(p->disk, F_OK) == 0 && plan_wait_nodes(p, 100) < 0) - eprintf("%s: the partition devices of %s did not appear\n", argv0, p->disk); + eprintf("the partition devices of %s did not appear\n", p->disk); return 0; } @@ -187,11 +190,11 @@ do_mkfs(struct plan *p) printf("formatting %s as %s...\n", dev, p->attr[i].fs); fflush(stdout); if (plan_mkfs_argv(p, i, argv, 16, store, sizeof store) < 0) - eprintf("%s: no way to make a %s filesystem\n", argv0, p->attr[i].fs); + eprintf("no way to make a %s filesystem\n", p->attr[i].fs); /* swap is a warning when its maker is missing: the system works without it */ switch ((pid = fork())) { case -1: - eprintf("%s: fork:", argv0); + eprintf("fork:"); break; case 0: freopen("/dev/null", "w", stdout); @@ -200,9 +203,9 @@ do_mkfs(struct plan *p) default: if (waitpid(pid, &st, 0) < 0 || !WIFEXITED(st) || WEXITSTATUS(st) != 0) { if (strcmp(p->attr[i].fs, "swap") == 0) { - weprintf("%s: %s did not make swap on %s, going on without it\n", argv0, argv[0], dev); + weprintf("%s did not make swap on %s, going on without it\n", argv[0], dev); } else { - weprintf("%s: %s failed on %s\n", argv0, argv[0], dev); + weprintf("%s failed on %s\n", argv[0], dev); status = 1; } } @@ -258,8 +261,235 @@ do_fstab(struct plan *p) return 0; } +/* the plan written back over its file, whole or not at all */ +static void +save(const struct plan *p, const char *path) +{ + char tmp[PATH_MAX]; + FILE *f; + + if (snprintf(tmp, sizeof tmp, "%s.new", path) >= (int)sizeof tmp) + eprintf("%s: name too long\n", path); + if (!(f = fopen(tmp, "w"))) + eprintf("%s:", tmp); + if (plan_save(p, f) < 0 || fclose(f) == EOF) + eprintf("%s: could not write\n", tmp); + if (rename(tmp, path) < 0) + eprintf("%s:", path); +} + +/* a partition named as a person does, by the number its device ends in */ +static int +slot_of(const struct plan *p, const char *n) +{ + long slot = estrtol(n, 10) - 1; + + if (slot < 0 || slot >= p->label.slots || !p->label.part[slot].used) + eprintf("%s: no such partition\n", n); + return (int)slot; +} + +/* "512M", "20G", "1T", plain MiB, or "rest": sectors, 0 for what is left */ +static uint64_t +sectors_of(const struct plan *p, const char *size) +{ + char *end; + uint64_t n, mul = 1048576; + + if (strcmp(size, "rest") == 0 || strcmp(size, "0") == 0) + return 0; + n = strtoull(size, &end, 10); + switch (*end) { + case 'k': case 'K': mul = 1024; end++; break; + case 'm': case 'M': end++; break; + case 'g': case 'G': mul = 1048576ULL * 1024; end++; break; + case 't': case 'T': mul = 1048576ULL * 1024 * 1024; end++; break; + } + if (*end == 'i' || *end == 'I') + end++; + if (*end == 'b' || *end == 'B') + end++; + if (end == size || *end || !n) + eprintf("%s: not a size (512M, 20G, rest)\n", size); + return (n * mul + p->label.sec_size - 1) / p->label.sec_size; +} + +/* the type a filesystem is given when none is said: what a firmware, limine and a reader of the table expect */ +static const char * +type_of(const char *fs, const char *mount) +{ + if (strcmp(fs, "swap") == 0) + return "8200"; + if (strcmp(fs, "vfat") == 0 && mount && strcmp(mount, "/boot/efi") == 0) + return "ef00"; + if (strcmp(fs, "bios") == 0) + return "ef02"; + if (strcmp(fs, "vfat") == 0) + return "0700"; + return "8300"; +} + +static int +do_read(int argc, char *argv[]) +{ + struct plan p; + + if (argc != 2) + usage(); + if (plan_read_disk(&p, argv[1]) < 0) + eprintf("%s: could not read its partitions\n", argv[1]); + return plan_save(&p, stdout); +} + +static int +do_new(int argc, char *argv[]) +{ + struct plan p; + struct BlockDev dev; + enum label_kind kind = LABEL_GPT; + + ARGBEGIN + { + case 'm': + kind = LABEL_MBR; + break; + default: + usage(); + } + ARGEND + if (argc != 1) + usage(); + memset(&p, 0, sizeof p); + snprintf(p.disk, sizeof p.disk, "%s", argv[0]); + if (blockdev_open(&dev, argv[0], 0) < 0) + eprintf("%s:", argv[0]); + if (label_init(&p.label, &dev, kind) < 0) + eprintf("%s is too small for a partition table\n", argv[0]); + blockdev_close(&dev); + return plan_save(&p, stdout); +} + +static int +do_gaps(struct plan *p) +{ + struct label_gap gaps[LABEL_SLOTS + 1]; + int n = label_gaps(&p->label, gaps, LABEL_SLOTS + 1), i; + char size[32]; + + for (i = 0; i < n; i++) { + plan_size((gaps[i].end - gaps[i].start + 1) * p->label.sec_size, size, sizeof size); + printf("free %9s sectors %llu-%llu\n", size, (unsigned long long)gaps[i].start, (unsigned long long)gaps[i].end); + } + return 0; +} + +static int +do_changes(struct plan *p) +{ + struct plan before; + + if (plan_read_disk(&before, p->disk) < 0) + memset(&before, 0, sizeof before); + plan_changes(&before, p, show_line, NULL); + return 0; +} + +static int +do_add(int argc, char *argv[]) +{ + struct plan *p; + const char *type = NULL, *label = "", *fs, *mount; + char name[16]; + int slot; + + ARGBEGIN + { + case 't': + type = EARGF(usage()); + break; + case 'l': + label = EARGF(usage()); + break; + default: + usage(); + } + ARGEND + if (argc < 3 || argc > 4) + usage(); + p = ecalloc(1, sizeof *p); + load(p, argv[0]); + if (p->label.kind == LABEL_NONE) + eprintf("%s has no partition table: start from partplan new\n", p->disk); + fs = argv[2]; + mount = argc == 4 ? argv[3] : ""; + if (!type) + type = type_of(fs, mount); + /* the BIOS boot partition holds no filesystem, it is only its type */ + if (strcmp(fs, "bios") == 0 || strcmp(fs, "none") == 0) + fs = ""; + snprintf(name, sizeof name, "%s", strcmp(type, "ef00") == 0 ? "ESP" : strcmp(type, "ef02") == 0 ? "BIOS" + : strcmp(type, "8200") == 0 ? "SWAP" : strcmp(mount, "/") == 0 ? "ROOT" : "DATA"); + slot = plan_add(p, 0, sectors_of(p, argv[1]), type, name, fs, mount, label); + if (slot < 0) + eprintf("no room for %s, or %s %s is not a partition (gaps shows the room)\n", argv[1], argv[2], mount); + save(p, argv[0]); + printf("%d\n", slot + 1); + free(p); + return 0; +} + +static int +do_delete(int argc, char *argv[]) +{ + struct plan *p; + + if (argc != 3) + usage(); + p = ecalloc(1, sizeof *p); + load(p, argv[1]); + if (plan_delete(p, slot_of(p, argv[2])) < 0) + eprintf("could not delete %s\n", argv[2]); + save(p, argv[1]); + free(p); + return 0; +} + +/* a partition's filesystem and place: -k keeps what is on it instead of making it anew */ +static int +do_set(int argc, char *argv[]) +{ + struct plan *p; + const char *label = NULL; + int keep = 0, slot; + + ARGBEGIN + { + case 'k': + keep = 1; + break; + case 'l': + label = EARGF(usage()); + break; + default: + usage(); + } + ARGEND + if (argc < 3 || argc > 4) + usage(); + p = ecalloc(1, sizeof *p); + load(p, argv[0]); + slot = slot_of(p, argv[1]); + if (strcmp(argv[2], "none") == 0) + argv[2] = ""; + if (plan_set(p, slot, argv[2], argc == 4 ? argv[3] : "", label ? label : p->attr[slot].label, !keep) < 0) + eprintf("%s is not a filesystem partplan makes, or its label is too long\n", argv[2]); + save(p, argv[0]); + free(p); + return 0; +} + // ?man partplan: a disk's layout as a plan, made, checked and applied -// ?man arguments: guided [-s swap_mib] [-f root_fs] disk | disks | layout | show plan | check [-rb] plan | write plan | mkfs plan | mounts plan | fstab plan | get plan role +// ?man arguments: guided [-s swap_mib] [-f root_fs] disk | disks | layout | read disk | new [-m] disk | show plan | gaps plan | changes plan | check [-rb] plan | write plan | mkfs plan | mounts plan | fstab plan | get plan role | add [-t type] [-l label] plan size fs [mount] | delete plan n | set [-k] [-l label] plan n fs [mount] // ?man partplan works on a plan, the text a partitioner and an installer // ?man share: the disk, its partition table, and for each partition the // ?man filesystem it holds, where it is mounted and whether it is made @@ -270,8 +500,14 @@ do_fstab(struct plan *p) // ?man write clears the start of the disk and writes the table, mkfs makes // ?man the filesystems, mounts and fstab say where each goes, and get tells // ?man the device of the esp, root or swap, the number of the bios boot partition, -// ?man or the root filesystem. a plan is read from the file named, or from the -// ?man standard input when it is - +// ?man or the root filesystem. read makes a plan of a disk as it is, new one of +// ?man an empty GPT table (-m an MBR one), and add, delete and set edit a plan +// ?man file in place: add puts a partition of size (512M, 20G, rest) holding fs +// ?man (ext4, f2fs, vfat, swap, bios, none) in the first room that fits it, set +// ?man gives partition n its filesystem and mount point, made anew unless -k +// ?man keeps what is on it. gaps lists the free room, changes what writing the +// ?man plan would do to the disk. a plan is read from the file named, or from +// ?man the standard input when it is - int main(int argc, char *argv[]) { @@ -287,6 +523,16 @@ main(int argc, char *argv[]) return do_check(argc - 1, argv + 1); if (strcmp(argv[1], "disks") == 0) return do_disks(); + if (strcmp(argv[1], "read") == 0) + return do_read(argc - 1, argv + 1); + if (strcmp(argv[1], "new") == 0) + return do_new(argc - 1, argv + 1); + if (strcmp(argv[1], "add") == 0) + return do_add(argc - 1, argv + 1); + if (strcmp(argv[1], "delete") == 0) + return do_delete(argc - 1, argv + 1); + if (strcmp(argv[1], "set") == 0) + return do_set(argc - 1, argv + 1); /* what the guided layout puts ahead of the root, for a question to show */ if (strcmp(argv[1], "layout") == 0) { printf("BIOS boot|%d MiB\nEFI system|%d MiB\n", PLAN_BIOS_MIB, PLAN_ESP_MIB); @@ -298,6 +544,10 @@ main(int argc, char *argv[]) load(p, argv[2]); if (strcmp(argv[1], "show") == 0) rc = do_show(p); + else if (strcmp(argv[1], "gaps") == 0) + rc = do_gaps(p); + else if (strcmp(argv[1], "changes") == 0) + rc = do_changes(p); else if (strcmp(argv[1], "write") == 0) rc = do_write(p); else if (strcmp(argv[1], "mkfs") == 0) diff --git a/cmd/linux/mdev.c b/cmd/linux/mdev.c @@ -0,0 +1,523 @@ +/* see LICENSE file for copyright and license details */ + +#define _DEFAULT_SOURCE /* clearenv, putenv */ + +#include <sys/socket.h> +#include <sys/stat.h> +#include <sys/sysmacros.h> +#include <sys/types.h> +#include <sys/uio.h> +#include <sys/wait.h> + +#include <linux/netlink.h> + +#include <dirent.h> +#include <errno.h> +#include <fcntl.h> +#include <grp.h> +#include <limits.h> +#include <pwd.h> +#include <regex.h> +#include <signal.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +#include "paths.h" +#include "util.h" + +#define CONF "/etc/mdev.conf" +#define EVENT_MAX 8192 +#define ENV_MAX 64 +#define RCVBUF (4 << 20) /* the burst of a dock or a hub, or of the replay at start */ + +/* a line of mdev.conf: + * + * [-][$VAR=]regex user:group mode [=path | >path | !] [@cmd | $cmd | *cmd] + * [-]@maj,min[-min2] ... + * + * the regex is matched against the device's name under /dev, or with $VAR= + * against the event's VAR. the first line that matches is taken, a line + * starting with - is taken and the matching goes on */ +struct rule { + int cont; + char env[64]; /* "" for the device's name */ + int bymaj, maj, min0, min1; + regex_t re; + uid_t uid; + gid_t gid; + mode_t mode; + char place; /* 0, '=' to move the node, '>' to move it and link it back, '!' for none */ + char path[PATH_MAX]; + char when; /* 0, '@' after it is added, '$' before it goes, '*' both */ + char cmd[512]; +}; + +/* an event: the kernel's KEY=value fields */ +struct event { + char *kv[ENV_MAX]; + int n; +}; + +static struct rule *rules; +static int nrules; +static int vflag; + +static void +usage(void) +{ + eprintf("usage: %s [-s | -d [-f]] [-v]\n", argv0); +} + +static int +owner(const char *spec, uid_t *uid, gid_t *gid) +{ + char u[64], g[64], *end; + struct passwd *pw; + struct group *gr; + + if (sscanf(spec, "%63[^:]:%63s", u, g) != 2) + return -1; + *uid = (uid_t)strtoul(u, &end, 10); + if (*end) { + if (!(pw = getpwnam(u))) + return -1; + *uid = pw->pw_uid; + } + *gid = (gid_t)strtoul(g, &end, 10); + if (*end) { + if (!(gr = getgrnam(g))) + return -1; + *gid = gr->gr_gid; + } + return 0; +} + +static void +load(const char *path) +{ + FILE *f; + char line[1024]; + int n = 0; + + if (!(f = fopen(path, "r"))) { + if (errno != ENOENT) + weprintf("%s:", path); + return; + } + while (fgets(line, sizeof line, f)) { + struct rule r; + char pat[256], own[128], mode[16], *p = line, *rest, re[300]; + int used = 0; + + n++; + line[strcspn(line, "\n")] = '\0'; + p += strspn(p, " \t"); + if (*p == '#' || *p == '\0') + continue; + memset(&r, 0, sizeof r); + if (*p == '-') { + r.cont = 1; + p++; + } + if (sscanf(p, "%255s %127s %15s %n", pat, own, mode, &used) < 3) { + weprintf("%s:%d: not \"device user:group mode\"\n", path, n); + continue; + } + rest = p + used; + if (owner(own, &r.uid, &r.gid) < 0) { + weprintf("%s:%d: no such user or group: %s\n", path, n, own); + continue; + } + r.mode = (mode_t)strtoul(mode, NULL, 8) & 07777; + if (pat[0] == '@') { + r.bymaj = 1; + r.min1 = -1; + if (sscanf(pat + 1, "%d,%d-%d", &r.maj, &r.min0, &r.min1) < 2) { + weprintf("%s:%d: not @major,minor[-minor]\n", path, n); + continue; + } + if (r.min1 < 0) + r.min1 = r.min0; + } else { + const char *rx = pat; + char *eq; + + if (pat[0] == '$' && (eq = strchr(pat, '='))) { + *eq = '\0'; + estrlcpy(r.env, pat + 1, sizeof r.env); + rx = eq + 1; + } + /* the whole name, as mdev has it */ + snprintf(re, sizeof re, "^(%s)$", rx); + if (regcomp(&r.re, re, REG_EXTENDED | REG_NOSUB) != 0) { + weprintf("%s:%d: bad expression %s\n", path, n, rx); + continue; + } + } + rest += strspn(rest, " \t"); + if (*rest == '=' || *rest == '>' || *rest == '!') { + r.place = *rest++; + if (r.place != '!') { + int k = (int)strcspn(rest, " \t"); + + snprintf(r.path, sizeof r.path, "%.*s", k, rest); + rest += k; + } + rest += strspn(rest, " \t"); + } + if (*rest == '@' || *rest == '$' || *rest == '*') { + r.when = *rest++; + estrlcpy(r.cmd, rest, sizeof r.cmd); + } + rules = ereallocarray(rules, (size_t)nrules + 1, sizeof *rules); + rules[nrules++] = r; + } + fclose(f); +} + +static const char * +get(const struct event *e, const char *key) +{ + size_t k = strlen(key); + int i; + + for (i = 0; i < e->n; i++) + if (strncmp(e->kv[i], key, k) == 0 && e->kv[i][k] == '=') + return e->kv[i] + k + 1; + return NULL; +} + +static int +matches(const struct rule *r, const struct event *e, const char *name) +{ + const char *v; + + if (r->bymaj) { + const char *ma = get(e, "MAJOR"), *mi = get(e, "MINOR"); + int m; + + if (!ma || !mi || atoi(ma) != r->maj) + return 0; + m = atoi(mi); + return m >= r->min0 && m <= r->min1; + } + v = r->env[0] ? get(e, r->env) : name; + return v && regexec(&r->re, v, 0, NULL, 0) == 0; +} + +/* a directory for path, as mkdir -p */ +static void +parents(const char *path) +{ + char d[PATH_MAX], *s; + + estrlcpy(d, path, sizeof d); + for (s = d + 1; (s = strchr(s, '/')); s++) { + *s = '\0'; + mkdir(d, 0755); + *s = '/'; + } +} + +static void +command(const struct rule *r, const struct event *e, const char *name) +{ + pid_t pid; + int i; + + if ((pid = fork()) < 0) { + weprintf("fork:"); + return; + } + if (pid == 0) { + signal(SIGCHLD, SIG_DFL); + clearenv(); + setenv("PATH", "/bin", 1); + for (i = 0; i < e->n; i++) + putenv(e->kv[i]); + if (name) + setenv("MDEV", name, 1); + execl("/bin/sh", "sh", "-c", r->cmd, (char *)NULL); + _exit(127); + } + while (waitpid(pid, NULL, 0) < 0 && errno == EINTR) + ; +} + +/* the node the kernel made, given its owner and mode, and put where the + * line says */ +static void +node(const struct rule *r, const char *name, int adding) +{ + char dev[PATH_MAX], to[PATH_MAX]; + + snprintf(dev, sizeof dev, "/dev/%s", name); + if (!r->place || r->path[0] == '\0') { + if (r->place == '!' && adding) + unlink(dev); + } else { + /* a path ending in / keeps the name under it */ + if (r->path[strlen(r->path) - 1] == '/') + snprintf(to, sizeof to, "/dev/%s%s", r->path, strrchr(name, '/') ? strrchr(name, '/') + 1 : name); + else + snprintf(to, sizeof to, "/dev/%s", r->path); + if (adding) { + parents(to); + if (rename(dev, to) == 0 && r->place == '>') + symlink(to + 5, dev); + estrlcpy(dev, to, sizeof dev); + } else { + unlink(to); + if (r->place == '>') + unlink(dev); + return; + } + } + if (!adding || r->place == '!') + return; + if (chown(dev, r->uid, r->gid) < 0 || chmod(dev, r->mode) < 0) { + if (errno != ENOENT) + weprintf("%s:", dev); + return; + } + if (vflag) + printf("%s %u:%u %04o\n", dev, (unsigned)r->uid, (unsigned)r->gid, (unsigned)r->mode); +} + +static void +handle(const struct event *e) +{ + const char *action = get(e, "ACTION"), *name = get(e, "DEVNAME"); + int adding, removing, i; + + if (!action) + return; + adding = !strcmp(action, "add") || !strcmp(action, "change"); + removing = !strcmp(action, "remove"); + for (i = 0; i < nrules; i++) { + const struct rule *r = &rules[i]; + + if (!matches(r, e, name)) + continue; + if (name) + node(r, name, adding); + if ((r->when == '@' && !strcmp(action, "add")) || (r->when == '$' && removing) || + (r->when == '*' && (!strcmp(action, "add") || removing))) + command(r, e, name); + if (!r->cont) + break; + } +} + +/* the fields of a netlink message: "action@devpath" then KEY=value, each + * ended by a NUL */ +static void +from_buffer(struct event *e, char *buf, size_t n) +{ + char *p; + + e->n = 0; + for (p = buf; p < buf + n && e->n < ENV_MAX; p += strlen(p) + 1) + if (strchr(p, '=') && !strchr(p, '@')) + e->kv[e->n++] = p; +} + +/* every device of the sysfs tree asked to say again that it was added, so + * what was there before mdev listened comes through the same way: drivers, + * nodes, lines with commands */ +static void +replay(const char *dir) +{ + DIR *d; + struct dirent *ent; + char path[PATH_MAX]; + int fd; + + snprintf(path, sizeof path, "%s/uevent", dir); + if ((fd = open(path, O_WRONLY | O_CLOEXEC)) >= 0) { + if (write(fd, "add", 3) < 0) { + /* a device that cannot be replayed is left as it is */ + } + close(fd); + } + if (!(d = opendir(dir))) + return; + while ((ent = readdir(d))) { + struct stat st; + + if (ent->d_name[0] == '.') + continue; + snprintf(path, sizeof path, "%s/%s", dir, ent->d_name); + /* the tree's links lead back into it */ + if (lstat(path, &st) == 0 && S_ISDIR(st.st_mode)) + replay(path); + } + closedir(d); +} + +/* -s: the nodes there now, from /sys/dev, each as if it had just been added */ +static void +scan(const char *dir) +{ + DIR *d; + struct dirent *ent; + + if (!(d = opendir(dir))) + return; + while ((ent = readdir(d))) { + char path[PATH_MAX], buf[EVENT_MAX], link[PATH_MAX], sub[80]; + struct event e; + ssize_t n, k; + int fd; + char *p; + + if (ent->d_name[0] == '.') + continue; + snprintf(path, sizeof path, "%s/%s/uevent", dir, ent->d_name); + if ((fd = open(path, O_RDONLY | O_CLOEXEC)) < 0) + continue; + n = read(fd, buf, sizeof buf - 64); + close(fd); + if (n <= 0) + continue; + buf[n] = '\0'; + for (p = buf; (p = strchr(p, '\n')); p++) + *p = '\0'; + /* what the kernel would have said besides: the action and the subsystem */ + memcpy(buf + n + 1, "ACTION=add", 11); + from_buffer(&e, buf, (size_t)n + 12); + snprintf(path, sizeof path, "%s/%s/subsystem", dir, ent->d_name); + if ((k = readlink(path, link, sizeof link - 1)) > 0 && e.n < ENV_MAX) { + link[k] = '\0'; + snprintf(sub, sizeof sub, "SUBSYSTEM=%s", strrchr(link, '/') ? strrchr(link, '/') + 1 : link); + e.kv[e.n++] = sub; + } + handle(&e); + } + closedir(d); +} + +static int +listen_kernel(void) +{ + struct sockaddr_nl sa; + int fd, size = RCVBUF; + + if ((fd = socket(AF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT)) < 0) + eprintf("socket:"); + memset(&sa, 0, sizeof sa); + sa.nl_family = AF_NETLINK; + sa.nl_groups = 1; + if (bind(fd, (struct sockaddr *)&sa, sizeof sa) < 0) + eprintf("bind:"); + if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &size, sizeof size) < 0) + setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof size); + return fd; +} + +// ?man mdev: gives the kernel's devices their owner, mode and place, and runs what mdev.conf says for them +// ?man arguments: [-s | -d [-f]] [-v] +// ?man mdev reads /etc/mdev.conf, BusyBox mdev's table, a line each: +// ?man "[-][$VAR=]regex user:group mode [=path|>path|!] [@cmd|$cmd|*cmd]", or +// ?man "@major,minor[-minor] ..." for a device by its numbers. the regex is +// ?man matched against the device's name under /dev, or with $VAR= against the +// ?man event's VAR (SUBSYSTEM, MODALIAS, DEVPATH...). the first line that +// ?man matches is taken, and one starting with - is taken and the matching goes +// ?man on. =path moves the node there, >path moves it and leaves a link, ! +// ?man takes it away. @cmd runs once the device is added, $cmd before it goes, +// ?man *cmd both, through sh with the event's fields and MDEV, the device's +// ?man name, in the environment. the kernel's devtmpfs makes and removes the +// ?man nodes, mdev gives them what the table says. run with no option, it is a +// ?man hotplug helper and takes the one event in its environment +int +main(int argc, char *argv[]) +{ + int sflag = 0, dflag = 0; + char buf[EVENT_MAX + 1]; + + ARGBEGIN + { + // ?man -s: set every node there is now, and stop + case 's': + sflag = 1; + break; + // ?man -d: listen to the kernel's events and stay, having had every device + // ?man there already say again that it was added + case 'd': + dflag = 1; + break; + // ?man -f: in the foreground, which mdev always is: for BusyBox's command lines + case 'f': + break; + // ?man -v: say each node it sets + case 'v': + vflag = 1; + break; + default: + usage(); + } + ARGEND; + if (argc || (sflag && dflag)) + usage(); + + load(CONF); + signal(SIGCHLD, SIG_DFL); + + if (sflag) { + scan(ARUU_LINUX_PATH_SYS "/dev/char"); + scan(ARUU_LINUX_PATH_SYS "/dev/block"); + return 0; + } + + if (!dflag) { + extern char **environ; + struct event e; + char **p; + + e.n = 0; + for (p = environ; *p && e.n < ENV_MAX; p++) + e.kv[e.n++] = *p; + handle(&e); + return 0; + } + + { + int fd = listen_kernel(); + + /* listening first: nothing added between the replay and the loop is lost */ + replay(ARUU_LINUX_PATH_SYS "/devices"); + for (;;) { + struct sockaddr_nl from; + struct iovec iov = {buf, EVENT_MAX}; + struct msghdr msg; + struct event e; + ssize_t n; + + memset(&msg, 0, sizeof msg); + msg.msg_name = &from; + msg.msg_namelen = sizeof from; + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + if ((n = recvmsg(fd, &msg, 0)) < 0) { + /* events were lost in a burst: the nodes are set over again */ + if (errno == ENOBUFS) { + weprintf("events were lost, setting the nodes again\n"); + scan(ARUU_LINUX_PATH_SYS "/dev/char"); + scan(ARUU_LINUX_PATH_SYS "/dev/block"); + continue; + } + if (errno == EINTR) + continue; + eprintf("recv:"); + } + /* the kernel's own, port 0: udev's rebroadcasts and anyone else's are not believed */ + if (from.nl_pid != 0 || n == 0 || !memchr(buf, '@', (size_t)n < 64 ? (size_t)n : 64)) + continue; + buf[n] = '\0'; + from_buffer(&e, buf, (size_t)n); + handle(&e); + } + } +}