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/netlink.h>
45 #include "udev_libc_wrapper.h"
47 #include "udev_version.h"
48 #include "udev_rules.h"
49 #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 msg_queue_insert(struct uevent_msg *msg)
90 list_add(&msg->node, &exec_list);
91 msg->queue_time = time(NULL);
95 static void msg_queue_delete(struct uevent_msg *msg)
101 static void asmlinkage udev_event_sig_handler(int signum)
103 if (signum == SIGALRM)
107 static int udev_event_process(struct uevent_msg *msg)
109 struct sigaction act;
111 struct name_entry *name_loop;
115 /* set signal handlers */
116 memset(&act, 0x00, sizeof(act));
117 act.sa_handler = (void (*)(int)) udev_event_sig_handler;
118 sigemptyset (&act.sa_mask);
120 sigaction(SIGALRM, &act, NULL);
122 /* trigger timeout to prevent hanging processes */
123 alarm(UDEV_ALARM_TIMEOUT);
125 /* reconstruct env from message */
126 for (i = 0; msg->envp[i]; i++)
127 putenv(msg->envp[i]);
129 udev_init_device(&udev, msg->devpath, msg->subsystem, msg->action);
130 retval = udev_process_event(&rules, &udev);
132 /* run programs collected by RUN-key*/
134 list_for_each_entry(name_loop, &udev.run_list, node) {
135 if (strncmp(name_loop->name, "socket:", strlen("socket:")) == 0)
136 pass_env_to_socket(&name_loop->name[strlen("socket:")], msg->devpath, msg->action);
138 run_program(name_loop->name, udev.subsystem, NULL, 0, NULL, (udev_log_priority >= LOG_INFO));
142 udev_cleanup_device(&udev);
147 /* runs event and removes event from run queue when finished */
148 static void udev_event_run(struct uevent_msg *msg)
156 close(uevent_netlink_sock);
160 close(signal_pipe[READ_END]);
161 close(signal_pipe[WRITE_END]);
164 logging_init("udevd-event");
165 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
166 udev_event_process(msg);
167 info("seq %llu finished", msg->seqnum);
172 err("fork of child failed");
173 msg_queue_delete(msg);
176 /* get SIGCHLD in main loop */
177 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
178 msg->seqnum, pid, msg->action, msg->subsystem, time(NULL) - msg->queue_time);
183 static int running_processes(void)
186 static char buf[4096];
191 f = open("/proc/stat", O_RDONLY);
195 len = read(f, buf, sizeof(buf)-1);
203 pos = strstr(buf, "procs_running ");
207 if (sscanf(pos, "procs_running %u", &running) != 1)
213 /* return the number of process es in our session, count only until limit */
214 static int running_processes_in_session(pid_t session, int limit)
220 dir = opendir("/proc");
224 /* read process info from /proc */
225 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
231 pid_t ppid, pgrp, sess;
234 if (!isdigit(dent->d_name[0]))
237 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
238 procdir[sizeof(procdir)-1] = '\0';
240 f = open(procdir, O_RDONLY);
244 len = read(f, line, sizeof(line)-1);
252 /* skip ugly program name */
253 pos = strrchr(line, ')') + 2;
257 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
260 /* count only processes in our session */
264 /* count only running, no sleeping processes */
269 if (limit > 0 && running >= limit)
277 static int compare_devpath(const char *running, const char *waiting)
281 for (i = 0; i < PATH_SIZE; i++) {
282 /* identical device event found */
283 if (running[i] == '\0' && waiting[i] == '\0')
286 /* parent device event found */
287 if (running[i] == '\0' && waiting[i] == '/')
290 /* child device event found */
291 if (running[i] == '/' && waiting[i] == '\0')
294 /* no matching event */
295 if (running[i] != waiting[i])
302 /* returns still running task for the same device, its parent or its physical device */
303 static int running_with_devpath(struct uevent_msg *msg, int limit)
305 struct uevent_msg *loop_msg;
306 int childs_count = 0;
308 if (msg->devpath == NULL)
311 /* skip any events with a timeout set */
312 if (msg->timeout != 0)
315 list_for_each_entry(loop_msg, &running_list, node) {
316 if (limit && childs_count++ > limit) {
317 dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
320 if (loop_msg->devpath == NULL)
323 /* return running parent/child device event */
324 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
325 dbg("%llu, child device event still running %llu (%s)",
326 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
330 /* return running physical device event */
331 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
332 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
333 dbg("%llu, physical device event still running %llu (%s)",
334 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
342 /* exec queue management routine executes the events and serializes events in the same sequence */
343 static void exec_queue_manager(void)
345 struct uevent_msg *loop_msg;
346 struct uevent_msg *tmp_msg;
349 if (list_empty(&exec_list))
352 running = running_processes();
353 dbg("%d processes runnning on system", running);
355 running = max_childs_running;
357 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
358 /* check running processes in our session and possibly throttle */
359 if (running >= max_childs_running) {
360 running = running_processes_in_session(sid, max_childs_running+10);
361 dbg("at least %d processes running in session", running);
362 if (running >= max_childs_running) {
363 dbg("delay seq %llu, cause too many processes already running",
369 if (running_with_devpath(loop_msg, max_childs) == 0) {
370 /* move event to run list */
371 list_move_tail(&loop_msg->node, &running_list);
372 udev_event_run(loop_msg);
374 dbg("moved seq %llu to running list", loop_msg->seqnum);
376 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
380 static struct uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
384 struct uevent_msg *msg;
388 msg = malloc(sizeof(struct uevent_msg) + buf_size);
391 memset(msg, 0x00, sizeof(struct uevent_msg) + buf_size);
393 /* copy environment buffer and reconstruct envp */
394 memcpy(msg->envbuf, buf, buf_size);
396 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
400 key = &msg->envbuf[bufpos];
401 keylen = strlen(key);
403 bufpos += keylen + 1;
404 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
406 /* remember some keys for further processing */
407 if (strncmp(key, "ACTION=", 7) == 0)
408 msg->action = &key[7];
409 else if (strncmp(key, "DEVPATH=", 8) == 0)
410 msg->devpath = &key[8];
411 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
412 msg->subsystem = &key[10];
413 else if (strncmp(key, "SEQNUM=", 7) == 0)
414 msg->seqnum = strtoull(&key[7], NULL, 10);
415 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
416 msg->physdevpath = &key[12];
417 else if (strncmp(key, "MAJOR=", 6) == 0)
418 major = strtoull(&key[6], NULL, 10);
419 else if (strncmp(key, "MINOR=", 6) == 0)
420 minor = strtoull(&key[6], NULL, 10);
421 else if (strncmp(key, "TIMEOUT=", 8) == 0)
422 msg->timeout = strtoull(&key[8], NULL, 10);
424 msg->devt = makedev(major, minor);
425 msg->envp[i++] = "UDEVD_EVENT=1";
431 /* receive the udevd message from userspace */
432 static struct uevent_msg *get_udevd_msg(void)
434 static struct udevd_msg usend_msg;
435 struct uevent_msg *msg;
438 struct cmsghdr *cmsg;
441 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
445 memset(&usend_msg, 0x00, sizeof(struct udevd_msg));
446 iov.iov_base = &usend_msg;
447 iov.iov_len = sizeof(struct udevd_msg);
449 memset(&smsg, 0x00, sizeof(struct msghdr));
452 smsg.msg_control = cred_msg;
453 smsg.msg_controllen = sizeof(cred_msg);
455 size = recvmsg(udevd_sock, &smsg, 0);
458 err("unable to receive udevd message");
461 cmsg = CMSG_FIRSTHDR(&smsg);
462 cred = (struct ucred *) CMSG_DATA(cmsg);
464 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
465 err("no sender credentials received, message ignored");
469 if (cred->uid != 0) {
470 err("sender uid=%i, message ignored", cred->uid);
474 if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
475 err("message magic '%s' doesn't match, ignore it", usend_msg.magic);
479 switch (usend_msg.type) {
480 case UDEVD_UEVENT_UDEVSEND:
481 case UDEVD_UEVENT_INITSEND:
482 info("udevd event message received");
483 envbuf_size = size - offsetof(struct udevd_msg, envbuf);
484 dbg("envbuf_size=%i", envbuf_size);
485 msg = get_msg_from_envbuf(usend_msg.envbuf, envbuf_size);
488 msg->type = usend_msg.type;
490 case UDEVD_STOP_EXEC_QUEUE:
491 info("udevd message (STOP_EXEC_QUEUE) received");
494 case UDEVD_START_EXEC_QUEUE:
495 info("udevd message (START_EXEC_QUEUE) received");
497 exec_queue_manager();
499 case UDEVD_SET_LOG_LEVEL:
500 intval = (int *) usend_msg.envbuf;
501 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
502 udev_log_priority = *intval;
503 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
506 case UDEVD_SET_MAX_CHILDS:
507 intval = (int *) usend_msg.envbuf;
508 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
509 max_childs = *intval;
511 case UDEVD_RELOAD_RULES:
512 info("udevd message (RELOAD_RULES) received");
516 dbg("unknown message type");
521 /* receive the kernel user event message and do some sanity checks */
522 static struct uevent_msg *get_netlink_msg(void)
524 struct uevent_msg *msg;
527 static char buffer[UEVENT_BUFFER_SIZE + 512];
530 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
533 err("unable to receive udevd message");
537 if ((size_t)size > sizeof(buffer)-1)
538 size = sizeof(buffer)-1;
540 dbg("uevent_size=%zi", size);
542 /* start of event payload */
543 bufpos = strlen(buffer)+1;
544 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
547 msg->type = UDEVD_UEVENT_NETLINK;
549 /* validate message */
550 pos = strchr(buffer, '@');
552 err("invalid uevent '%s'", buffer);
558 if (msg->action == NULL) {
559 info("no ACTION in payload found, skip event '%s'", buffer);
564 if (strcmp(msg->action, buffer) != 0) {
565 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
573 static void asmlinkage sig_handler(int signum)
581 /* set flag, then write to pipe if needed */
582 sigchilds_waiting = 1;
589 /* write to pipe, which will wakeup select() in our mainloop */
590 write(signal_pipe[WRITE_END], "", 1);
593 static void udev_done(int pid)
595 /* find msg associated with pid and delete it */
596 struct uevent_msg *msg;
598 list_for_each_entry(msg, &running_list, node) {
599 if (msg->pid == pid) {
601 info("seq %llu, pid [%d] exit, %ld seconds old", msg->seqnum, msg->pid, time(NULL) - msg->queue_time);
603 info("seq 0, pid [%d] exit", msg->pid);
604 msg_queue_delete(msg);
606 /* we want to run the exec queue manager since there may
607 * be events waiting with the devpath of the one that
616 static void reap_sigchilds(void)
621 pid = waitpid(-1, NULL, WNOHANG);
628 static int init_udevd_socket(void)
630 struct sockaddr_un saddr;
631 const int buffersize = 16 * 1024 * 1024;
633 const int feature_on = 1;
636 memset(&saddr, 0x00, sizeof(saddr));
637 saddr.sun_family = AF_LOCAL;
638 /* use abstract namespace for socket path */
639 strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
640 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
642 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
643 if (udevd_sock == -1) {
644 err("error getting socket, %s", strerror(errno));
648 /* set receive buffersize */
649 setsockopt(udevd_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
651 /* the bind takes care of ensuring only one copy running */
652 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
654 err("bind failed, %s", strerror(errno));
658 /* enable receiving of the sender credentials */
659 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
664 static int init_uevent_netlink_sock(void)
666 struct sockaddr_nl snl;
667 const int buffersize = 16 * 1024 * 1024;
670 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
671 snl.nl_family = AF_NETLINK;
672 snl.nl_pid = getpid();
673 snl.nl_groups = 0xffffffff;
675 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
676 if (uevent_netlink_sock == -1) {
677 err("error getting socket, %s", strerror(errno));
681 /* set receive buffersize */
682 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
684 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
686 err("bind failed, %s", strerror(errno));
687 close(uevent_netlink_sock);
688 uevent_netlink_sock = -1;
694 int main(int argc, char *argv[], char *envp[])
698 struct sigaction act;
706 /* redirect std fd's, if the kernel forks us, we don't have them at all */
707 fd = open("/dev/null", O_RDWR);
709 if (fd != STDIN_FILENO)
710 dup2(fd, STDIN_FILENO);
711 if (fd != STDOUT_FILENO)
712 dup2(fd, STDOUT_FILENO);
713 if (fd != STDERR_FILENO)
714 dup2(fd, STDERR_FILENO);
715 if (fd > STDERR_FILENO)
719 logging_init("udevd");
721 err("fatal, could not open /dev/null");
724 dbg("version %s", UDEV_VERSION);
727 err("need to be root, exit");
731 /* parse commandline options */
732 for (i = 1 ; i < argc; i++) {
734 if (strcmp(arg, "--daemon") == 0 || strcmp(arg, "-d") == 0) {
735 info("will daemonize");
738 if (strcmp(arg, "--stop-exec-queue") == 0) {
739 info("will not execute events until START_EXEC_QUEUE is received");
744 /* init sockets to receive events */
745 if (init_udevd_socket() < 0) {
746 if (errno == EADDRINUSE) {
747 dbg("another udevd running, exit");
750 dbg("error initializing udevd socket: %s", strerror(errno));
756 if (init_uevent_netlink_sock() < 0) {
757 err("uevent socket not available");
762 /* parse the rules and keep it in memory */
763 udev_rules_init(&rules, 1);
771 dbg("daemonized fork running");
774 err("fork of daemon failed");
778 dbg("child [%u] running, parent exits", pid);
783 /* set scheduling priority for the daemon */
784 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
789 /* become session leader */
791 dbg("our session is %d", sid);
793 /* OOM_DISABLE == -17 */
794 fd = open("/proc/self/oom_adj", O_RDWR);
796 err("error disabling OOM");
802 /* setup signal handler pipe */
803 retval = pipe(signal_pipe);
805 err("error getting pipes: %s", strerror(errno));
808 retval = fcntl(signal_pipe[READ_END], F_SETFL, O_NONBLOCK);
810 err("error fcntl on read pipe: %s", strerror(errno));
813 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, O_NONBLOCK);
815 err("error fcntl on write pipe: %s", strerror(errno));
819 /* set signal handlers */
820 memset(&act, 0x00, sizeof(struct sigaction));
821 act.sa_handler = (void (*)(int)) sig_handler;
822 sigemptyset(&act.sa_mask);
823 act.sa_flags = SA_RESTART;
824 sigaction(SIGINT, &act, NULL);
825 sigaction(SIGTERM, &act, NULL);
826 sigaction(SIGCHLD, &act, NULL);
827 sigaction(SIGHUP, &act, NULL);
829 /* watch rules directory */
830 inotify_fd = inotify_init();
832 inotify_add_watch(inotify_fd, udev_rules_filename, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
834 /* maximum limit of forked childs */
835 value = getenv("UDEVD_MAX_CHILDS");
837 max_childs = strtoul(value, NULL, 10);
839 max_childs = UDEVD_MAX_CHILDS;
840 info("initialize max_childs to %u", max_childs);
842 /* start to throttle forking if maximum number of _running_ childs is reached */
843 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
845 max_childs_running = strtoull(value, NULL, 10);
847 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
848 info("initialize max_childs_running to %u", max_childs_running);
850 /* clear environment for forked event processes */
853 /* export log_priority , as called programs may want to follow that setting */
854 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
858 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
859 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
860 maxfd = UDEV_MAX(maxfd, inotify_fd);
863 struct uevent_msg *msg;
867 FD_SET(signal_pipe[READ_END], &readfds);
868 FD_SET(udevd_sock, &readfds);
869 FD_SET(uevent_netlink_sock, &readfds);
871 FD_SET(inotify_fd, &readfds);
873 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
876 dbg("error in select: %s", strerror(errno));
880 /* get user socket message */
881 if (FD_ISSET(udevd_sock, &readfds)) {
882 msg = get_udevd_msg();
884 if (msg->type == UDEVD_UEVENT_UDEVSEND && msg->seqnum != 0) {
885 info("skip non-kernel message with SEQNUM");
888 msg_queue_insert(msg);
892 /* get kernel netlink message */
893 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
894 msg = get_netlink_msg();
896 msg_queue_insert(msg);
899 /* received a signal, clear our notification pipe */
900 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
903 read(signal_pipe[READ_END], &buf, sizeof(buf));
906 /* rules directory inotify watch */
907 if ((inotify_fd > 0) && FD_ISSET(inotify_fd, &readfds)) {
910 /* discard all possible events, we can just reload the config */
911 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes) {
915 buf = malloc(nbytes);
917 err("error getting buffer for inotify, disable watching");
921 read(inotify_fd, buf, nbytes);
926 /* rules changed, set by inotify or a signal*/
929 udev_rules_close(&rules);
930 udev_rules_init(&rules, 1);
933 /* forked child has returned */
934 if (sigchilds_waiting) {
935 sigchilds_waiting = 0;
942 exec_queue_manager();
947 udev_rules_close(&rules);
949 if (signal_pipe[READ_END] > 0)
950 close(signal_pipe[READ_END]);
951 if (signal_pipe[WRITE_END] > 0)
952 close(signal_pipe[WRITE_END]);
958 if (uevent_netlink_sock > 0)
959 close(uevent_netlink_sock);