2 * udevd.c - event listener and serializer
4 * Copyright (C) 2004-2005 Kay Sievers <kay.sievers@vrfy.org>
5 * Copyright (C) 2004 Chris Friesen <chris_friesen@sympatico.ca>
8 * This program is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the
10 * Free Software Foundation version 2 of the License.
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 675 Mass Ave, Cambridge, MA 02139, USA.
35 #include <sys/select.h>
37 #include <sys/types.h>
38 #include <sys/socket.h>
41 #include <sys/ioctl.h>
42 #include <linux/types.h>
43 #include <linux/netlink.h>
46 #include "udev_libc_wrapper.h"
48 #include "udev_version.h"
49 #include "udev_rules.h"
50 #include "udev_utils.h"
54 struct udev_rules rules;
55 static int udevd_sock;
56 static int uevent_netlink_sock;
57 static int inotify_fd;
60 static int signal_pipe[2] = {-1, -1};
61 static volatile int sigchilds_waiting;
62 static volatile int udev_exit;
63 static volatile int reload_config;
64 static int run_exec_q;
65 static int stop_exec_q;
66 static int max_childs;
67 static int max_childs_running;
68 static char udev_log[32];
70 static LIST_HEAD(exec_list);
71 static LIST_HEAD(running_list);
75 void log_message(int priority, const char *format, ...)
79 if (priority > udev_log_priority)
82 va_start(args, format);
83 vsyslog(priority, format, args);
88 static void asmlinkage udev_event_sig_handler(int signum)
90 if (signum == SIGALRM)
94 static int udev_event_process(struct uevent_msg *msg)
98 struct name_entry *name_loop;
102 /* set signal handlers */
103 memset(&act, 0x00, sizeof(act));
104 act.sa_handler = (void (*)(int)) udev_event_sig_handler;
105 sigemptyset (&act.sa_mask);
107 sigaction(SIGALRM, &act, NULL);
109 /* trigger timeout to prevent hanging processes */
110 alarm(UDEV_ALARM_TIMEOUT);
112 /* reconstruct env from message */
113 for (i = 0; msg->envp[i]; i++)
114 putenv(msg->envp[i]);
116 udev_init_device(&udev, msg->devpath, msg->subsystem, msg->action);
117 retval = udev_process_event(&rules, &udev);
119 /* run programs collected by RUN-key*/
121 list_for_each_entry(name_loop, &udev.run_list, node) {
122 if (strncmp(name_loop->name, "socket:", strlen("socket:")) == 0)
123 pass_env_to_socket(&name_loop->name[strlen("socket:")], msg->devpath, msg->action);
125 run_program(name_loop->name, udev.subsystem, NULL, 0, NULL, (udev_log_priority >= LOG_INFO));
129 udev_cleanup_device(&udev);
134 static void msg_queue_delete(struct uevent_msg *msg)
136 list_del(&msg->node);
140 static void udev_event_run(struct uevent_msg *msg)
148 close(uevent_netlink_sock);
152 close(signal_pipe[READ_END]);
153 close(signal_pipe[WRITE_END]);
156 logging_init("udevd-event");
157 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
158 udev_event_process(msg);
159 info("seq %llu finished", msg->seqnum);
164 err("fork of child failed: %s", strerror(errno));
165 msg_queue_delete(msg);
168 /* get SIGCHLD in main loop */
169 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
170 msg->seqnum, pid, msg->action, msg->subsystem, time(NULL) - msg->queue_time);
175 static void msg_queue_insert(struct uevent_msg *msg)
177 msg->queue_time = time(NULL);
179 /* run all events with a timeout set immediately */
180 if (msg->timeout != 0) {
181 list_add_tail(&msg->node, &running_list);
186 list_add_tail(&msg->node, &exec_list);
190 /* runs event and removes event from run queue when finished */
191 static int running_processes(void)
194 static char buf[4096];
199 f = open("/proc/stat", O_RDONLY);
203 len = read(f, buf, sizeof(buf)-1);
211 pos = strstr(buf, "procs_running ");
215 if (sscanf(pos, "procs_running %u", &running) != 1)
221 /* return the number of process es in our session, count only until limit */
222 static int running_processes_in_session(pid_t session, int limit)
228 dir = opendir("/proc");
232 /* read process info from /proc */
233 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
239 pid_t ppid, pgrp, sess;
242 if (!isdigit(dent->d_name[0]))
245 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
246 procdir[sizeof(procdir)-1] = '\0';
248 f = open(procdir, O_RDONLY);
252 len = read(f, line, sizeof(line)-1);
260 /* skip ugly program name */
261 pos = strrchr(line, ')') + 2;
265 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
268 /* count only processes in our session */
272 /* count only running, no sleeping processes */
277 if (limit > 0 && running >= limit)
285 static int compare_devpath(const char *running, const char *waiting)
289 for (i = 0; i < PATH_SIZE; i++) {
290 /* identical device event found */
291 if (running[i] == '\0' && waiting[i] == '\0')
294 /* parent device event found */
295 if (running[i] == '\0' && waiting[i] == '/')
298 /* child device event found */
299 if (running[i] == '/' && waiting[i] == '\0')
302 /* no matching event */
303 if (running[i] != waiting[i])
310 /* returns still running task for the same device, its parent or its physical device */
311 static int running_with_devpath(struct uevent_msg *msg, int limit)
313 struct uevent_msg *loop_msg;
314 int childs_count = 0;
316 list_for_each_entry(loop_msg, &running_list, node) {
317 if (limit && childs_count++ > limit) {
318 dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
322 /* return running parent/child device event */
323 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
324 dbg("%llu, child device event still running %llu (%s)",
325 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
329 /* return running physical device event */
330 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
331 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
332 dbg("%llu, physical device event still running %llu (%s)",
333 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
341 /* exec queue management routine executes the events and serializes events in the same sequence */
342 static void msg_queue_manager(void)
344 struct uevent_msg *loop_msg;
345 struct uevent_msg *tmp_msg;
348 if (list_empty(&exec_list))
351 running = running_processes();
352 dbg("%d processes runnning on system", running);
354 running = max_childs_running;
356 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
357 /* check running processes in our session and possibly throttle */
358 if (running >= max_childs_running) {
359 running = running_processes_in_session(sid, max_childs_running+10);
360 dbg("at least %d processes running in session", running);
361 if (running >= max_childs_running) {
362 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
367 /* don't run two processes for the same devpath and wait for the parent*/
368 if (running_with_devpath(loop_msg, max_childs)) {
369 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
373 /* move event to run list */
374 list_move_tail(&loop_msg->node, &running_list);
375 udev_event_run(loop_msg);
377 dbg("moved seq %llu to running list", loop_msg->seqnum);
381 static struct uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
385 struct uevent_msg *msg;
389 msg = malloc(sizeof(struct uevent_msg) + buf_size);
392 memset(msg, 0x00, sizeof(struct uevent_msg) + buf_size);
394 /* copy environment buffer and reconstruct envp */
395 memcpy(msg->envbuf, buf, buf_size);
397 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
401 key = &msg->envbuf[bufpos];
402 keylen = strlen(key);
404 bufpos += keylen + 1;
405 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
407 /* remember some keys for further processing */
408 if (strncmp(key, "ACTION=", 7) == 0)
409 msg->action = &key[7];
410 else if (strncmp(key, "DEVPATH=", 8) == 0)
411 msg->devpath = &key[8];
412 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
413 msg->subsystem = &key[10];
414 else if (strncmp(key, "SEQNUM=", 7) == 0)
415 msg->seqnum = strtoull(&key[7], NULL, 10);
416 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
417 msg->physdevpath = &key[12];
418 else if (strncmp(key, "MAJOR=", 6) == 0)
419 major = strtoull(&key[6], NULL, 10);
420 else if (strncmp(key, "MINOR=", 6) == 0)
421 minor = strtoull(&key[6], NULL, 10);
422 else if (strncmp(key, "TIMEOUT=", 8) == 0)
423 msg->timeout = strtoull(&key[8], NULL, 10);
425 msg->devt = makedev(major, minor);
426 msg->envp[i++] = "UDEVD_EVENT=1";
430 info("DEVPATH missing, ingnore message");
438 /* receive the udevd message from userspace */
439 static struct uevent_msg *get_udevd_msg(void)
441 static struct udevd_msg usend_msg;
442 struct uevent_msg *msg;
445 struct cmsghdr *cmsg;
448 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
452 memset(&usend_msg, 0x00, sizeof(struct udevd_msg));
453 iov.iov_base = &usend_msg;
454 iov.iov_len = sizeof(struct udevd_msg);
456 memset(&smsg, 0x00, sizeof(struct msghdr));
459 smsg.msg_control = cred_msg;
460 smsg.msg_controllen = sizeof(cred_msg);
462 size = recvmsg(udevd_sock, &smsg, 0);
465 err("unable to receive udevd message: %s", strerror(errno));
468 cmsg = CMSG_FIRSTHDR(&smsg);
469 cred = (struct ucred *) CMSG_DATA(cmsg);
471 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
472 err("no sender credentials received, message ignored");
476 if (cred->uid != 0) {
477 err("sender uid=%i, message ignored", cred->uid);
481 if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
482 err("message magic '%s' doesn't match, ignore it", usend_msg.magic);
486 switch (usend_msg.type) {
487 case UDEVD_UEVENT_UDEVSEND:
488 case UDEVD_UEVENT_INITSEND:
489 info("udevd event message received");
490 envbuf_size = size - offsetof(struct udevd_msg, envbuf);
491 dbg("envbuf_size=%i", envbuf_size);
492 msg = get_msg_from_envbuf(usend_msg.envbuf, envbuf_size);
495 msg->type = usend_msg.type;
497 case UDEVD_STOP_EXEC_QUEUE:
498 info("udevd message (STOP_EXEC_QUEUE) received");
501 case UDEVD_START_EXEC_QUEUE:
502 info("udevd message (START_EXEC_QUEUE) received");
506 case UDEVD_SET_LOG_LEVEL:
507 intval = (int *) usend_msg.envbuf;
508 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
509 udev_log_priority = *intval;
510 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
513 case UDEVD_SET_MAX_CHILDS:
514 intval = (int *) usend_msg.envbuf;
515 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
516 max_childs = *intval;
518 case UDEVD_RELOAD_RULES:
519 info("udevd message (RELOAD_RULES) received");
523 dbg("unknown message type");
528 /* receive the kernel user event message and do some sanity checks */
529 static struct uevent_msg *get_netlink_msg(void)
531 struct uevent_msg *msg;
534 static char buffer[UEVENT_BUFFER_SIZE + 512];
537 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
540 err("unable to receive udevd message: %s", strerror(errno));
544 if ((size_t)size > sizeof(buffer)-1)
545 size = sizeof(buffer)-1;
547 dbg("uevent_size=%zi", size);
549 /* start of event payload */
550 bufpos = strlen(buffer)+1;
551 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
554 msg->type = UDEVD_UEVENT_NETLINK;
556 /* validate message */
557 pos = strchr(buffer, '@');
559 err("invalid uevent '%s'", buffer);
565 if (msg->action == NULL) {
566 info("no ACTION in payload found, skip event '%s'", buffer);
571 if (strcmp(msg->action, buffer) != 0) {
572 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
580 static void asmlinkage sig_handler(int signum)
588 /* set flag, then write to pipe if needed */
589 sigchilds_waiting = 1;
596 /* write to pipe, which will wakeup select() in our mainloop */
597 write(signal_pipe[WRITE_END], "", 1);
600 static void udev_done(int pid)
602 /* find msg associated with pid and delete it */
603 struct uevent_msg *msg;
605 list_for_each_entry(msg, &running_list, node) {
606 if (msg->pid == pid) {
607 info("seq %llu, pid [%d] exit, %ld seconds old", msg->seqnum, msg->pid, time(NULL) - msg->queue_time);
608 msg_queue_delete(msg);
610 /* there may be events waiting with the same devpath */
617 static void reap_sigchilds(void)
622 pid = waitpid(-1, NULL, WNOHANG);
629 static int init_udevd_socket(void)
631 struct sockaddr_un saddr;
632 const int buffersize = 16 * 1024 * 1024;
634 const int feature_on = 1;
637 memset(&saddr, 0x00, sizeof(saddr));
638 saddr.sun_family = AF_LOCAL;
639 /* use abstract namespace for socket path */
640 strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
641 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
643 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
644 if (udevd_sock == -1) {
645 err("error getting socket: %s", strerror(errno));
649 /* set receive buffersize */
650 setsockopt(udevd_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
652 /* the bind takes care of ensuring only one copy running */
653 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
655 err("bind failed: %s", strerror(errno));
659 /* enable receiving of the sender credentials */
660 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
665 static int init_uevent_netlink_sock(void)
667 struct sockaddr_nl snl;
668 const int buffersize = 16 * 1024 * 1024;
671 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
672 snl.nl_family = AF_NETLINK;
673 snl.nl_pid = getpid();
674 snl.nl_groups = 0xffffffff;
676 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
677 if (uevent_netlink_sock == -1) {
678 err("error getting socket: %s", strerror(errno));
682 /* set receive buffersize */
683 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
685 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
687 err("bind failed: %s", strerror(errno));
688 close(uevent_netlink_sock);
689 uevent_netlink_sock = -1;
695 int main(int argc, char *argv[], char *envp[])
699 struct sigaction act;
707 /* redirect std fd's, if the kernel forks us, we don't have them at all */
708 fd = open("/dev/null", O_RDWR);
710 if (fd != STDIN_FILENO)
711 dup2(fd, STDIN_FILENO);
712 if (fd != STDOUT_FILENO)
713 dup2(fd, STDOUT_FILENO);
714 if (fd != STDERR_FILENO)
715 dup2(fd, STDERR_FILENO);
716 if (fd > STDERR_FILENO)
720 logging_init("udevd");
722 err("fatal, could not open /dev/null: %s", strerror(errno));
725 dbg("version %s", UDEV_VERSION);
728 err("need to be root, exit");
732 /* parse commandline options */
733 for (i = 1 ; i < argc; i++) {
735 if (strcmp(arg, "--daemon") == 0 || strcmp(arg, "-d") == 0) {
736 info("will daemonize");
739 if (strcmp(arg, "--stop-exec-queue") == 0) {
740 info("will not execute events until START_EXEC_QUEUE is received");
745 /* init sockets to receive events */
746 if (init_udevd_socket() < 0) {
747 if (errno == EADDRINUSE) {
748 err("another udevd running, exit");
751 err("error initializing udevd socket: %s", strerror(errno));
757 if (init_uevent_netlink_sock() < 0) {
758 err("uevent socket not available");
763 /* parse the rules and keep it in memory */
764 udev_rules_init(&rules, 1);
772 dbg("daemonized fork running");
775 err("fork of daemon failed: %s", strerror(errno));
779 dbg("child [%u] running, parent exits", pid);
784 /* set scheduling priority for the daemon */
785 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
790 /* become session leader */
792 dbg("our session is %d", sid);
794 /* OOM_DISABLE == -17 */
795 fd = open("/proc/self/oom_adj", O_RDWR);
797 err("error disabling OOM: %s", strerror(errno));
803 /* setup signal handler pipe */
804 retval = pipe(signal_pipe);
806 err("error getting pipes: %s", strerror(errno));
809 retval = fcntl(signal_pipe[READ_END], F_SETFL, O_NONBLOCK);
811 err("error fcntl on read pipe: %s", strerror(errno));
814 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, O_NONBLOCK);
816 err("error fcntl on write pipe: %s", strerror(errno));
820 /* set signal handlers */
821 memset(&act, 0x00, sizeof(struct sigaction));
822 act.sa_handler = (void (*)(int)) sig_handler;
823 sigemptyset(&act.sa_mask);
824 act.sa_flags = SA_RESTART;
825 sigaction(SIGINT, &act, NULL);
826 sigaction(SIGTERM, &act, NULL);
827 sigaction(SIGCHLD, &act, NULL);
828 sigaction(SIGHUP, &act, NULL);
830 /* watch rules directory */
831 inotify_fd = inotify_init();
833 inotify_add_watch(inotify_fd, udev_rules_filename, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
835 /* maximum limit of forked childs */
836 value = getenv("UDEVD_MAX_CHILDS");
838 max_childs = strtoul(value, NULL, 10);
840 max_childs = UDEVD_MAX_CHILDS;
841 info("initialize max_childs to %u", max_childs);
843 /* start to throttle forking if maximum number of _running_ childs is reached */
844 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
846 max_childs_running = strtoull(value, NULL, 10);
848 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
849 info("initialize max_childs_running to %u", max_childs_running);
851 /* clear environment for forked event processes */
854 /* export log_priority , as called programs may want to follow that setting */
855 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
859 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
860 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
861 maxfd = UDEV_MAX(maxfd, inotify_fd);
864 struct uevent_msg *msg;
868 FD_SET(signal_pipe[READ_END], &readfds);
869 FD_SET(udevd_sock, &readfds);
870 FD_SET(uevent_netlink_sock, &readfds);
872 FD_SET(inotify_fd, &readfds);
874 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
877 err("error in select: %s", strerror(errno));
881 /* get user socket message */
882 if (FD_ISSET(udevd_sock, &readfds)) {
883 msg = get_udevd_msg();
885 if (msg->type == UDEVD_UEVENT_UDEVSEND && msg->seqnum != 0) {
886 info("skip non-kernel message with SEQNUM");
889 msg_queue_insert(msg);
893 /* get kernel netlink message */
894 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
895 msg = get_netlink_msg();
897 msg_queue_insert(msg);
900 /* received a signal, clear our notification pipe */
901 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
904 read(signal_pipe[READ_END], &buf, sizeof(buf));
907 /* rules directory inotify watch */
908 if ((inotify_fd > 0) && FD_ISSET(inotify_fd, &readfds)) {
911 /* discard all possible events, we can just reload the config */
912 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes) {
916 buf = malloc(nbytes);
918 err("error getting buffer for inotify, disable watching");
922 read(inotify_fd, buf, nbytes);
927 /* rules changed, set by inotify or a signal*/
930 udev_rules_close(&rules);
931 udev_rules_init(&rules, 1);
934 /* forked child has returned */
935 if (sigchilds_waiting) {
936 sigchilds_waiting = 0;
948 udev_rules_close(&rules);
950 if (signal_pipe[READ_END] > 0)
951 close(signal_pipe[READ_END]);
952 if (signal_pipe[WRITE_END] > 0)
953 close(signal_pipe[WRITE_END]);
959 if (uevent_netlink_sock > 0)
960 close(uevent_netlink_sock);