diff options
Diffstat (limited to 'nldev-handler.c')
-rw-r--r-- | nldev-handler.c | 128 |
1 files changed, 128 insertions, 0 deletions
diff --git a/nldev-handler.c b/nldev-handler.c new file mode 100644 index 0000000..4fa6e2a --- /dev/null +++ b/nldev-handler.c @@ -0,0 +1,128 @@ + +#include <fcntl.h> +#include <poll.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <sys/types.h> +#include <sys/wait.h> + +#include "log.h" + +#define EVENT_TIMEOUT 2000 + +void +child(char *runpath) +{ + pid_t pid; + + if (!(pid = fork())) { + dbg("running %s", runpath); + if (execlp(runpath, basename(runpath), NULL) < 0) + edie("execvp"); + exit(0); + } + if (pid < 0) + edie("fork"); + + waitpid(pid, NULL, 0); +} + + +void +usage(void) +{ + die("usage: %s [-d] [-r run]\n", argv0); +} + +int main(int argc, char *argv[]) +{ + struct pollfd fds; + int r; + static char buf[16384]; + char *runpath = "/bin/mdev"; + char *subsystem = NULL; + + ARGBEGIN { + case 'd': + dodebug = 1; + break; + case 'r': + runpath = EARGF(usage()); + break; + case 'f': + subsystem = EARGF(usage()); + break; + default: + usage(); + } ARGEND; + + dbg("runpath=%s\n", runpath); + + fds.fd = 0; /* stdin */ + fds.events = POLLIN; + while ((r = poll(&fds, 1, EVENT_TIMEOUT)) > 0) { + size_t len; + int i, slen; + char *key, *value; + + clearenv(); + setenv("PATH", "/sbin:/bin", 1); + + if (!(fds.revents & POLLIN)) + continue; + + len = read(fds.fd, buf, sizeof(buf)-1); + buf[len] = 0; + dbg("Got %u bytes", len); + + slen = 0; + for (i = 0; i < len; i += slen + 1) { + key = buf + i; + value = strchr(key, '='); + slen = strlen(buf+i); + + if (!slen || value == NULL) + continue; + if (subsystem && !strncmp(key, "SUBSYSTEM=", 10) + && !strstr(key+10, subsystem)) { + dbg("subsystem filter '%s' applied.", + subsystem); + break; + } + + value[0] = '\0'; + value++; + + /* + * We generally trust the kernel. But there + * might be some udev flaw. (It's >20k sloc!) + */ + if (strcmp(key, "PATH")) { + setenv(key, value, 1); + dbg("%s = \"%s\"", key, value); + } + } + if (getenv("ACTION") != NULL && + getenv("DEVPATH") != NULL && + getenv("SUBSYSTEM") != NULL && + getenv("SEQNUM") != NULL) { + child(runpath); + } + + if (fds.revents & POLLHUP) { + dbg("parent hung up\n"); + return 0; + } + } + if (r == -1) + edie("poll"); + + if (r == 0) + dbg("exit due to timeout"); + + return 0; +} + + |