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"
53 struct udev_rules rules;
54 static int udevd_sock;
55 static int uevent_netlink_sock;
56 static int inotify_fd;
59 static int signal_pipe[2] = {-1, -1};
60 static volatile int sigchilds_waiting;
61 static volatile int udev_exit;
62 static volatile int reload_config;
63 static int run_exec_q;
64 static int stop_exec_q;
65 static int max_childs;
66 static int max_childs_running;
67 static char udev_log[32];
69 static LIST_HEAD(exec_list);
70 static LIST_HEAD(running_list);
74 void log_message(int priority, const char *format, ...)
78 if (priority > udev_log_priority)
81 va_start(args, format);
82 vsyslog(priority, format, args);
87 static void asmlinkage udev_event_sig_handler(int signum)
89 if (signum == SIGALRM)
93 static int udev_event_process(struct uevent_msg *msg)
97 struct name_entry *name_loop;
101 /* set signal handlers */
102 memset(&act, 0x00, sizeof(act));
103 act.sa_handler = (void (*)(int)) udev_event_sig_handler;
104 sigemptyset (&act.sa_mask);
106 sigaction(SIGALRM, &act, NULL);
108 /* trigger timeout to prevent hanging processes */
109 alarm(UDEV_ALARM_TIMEOUT);
111 /* reconstruct env from message */
112 for (i = 0; msg->envp[i]; i++)
113 putenv(msg->envp[i]);
115 udev_init_device(&udev, msg->devpath, msg->subsystem, msg->action);
116 retval = udev_process_event(&rules, &udev);
118 /* run programs collected by RUN-key*/
120 list_for_each_entry(name_loop, &udev.run_list, node) {
121 if (strncmp(name_loop->name, "socket:", strlen("socket:")) == 0)
122 pass_env_to_socket(&name_loop->name[strlen("socket:")], msg->devpath, msg->action);
124 run_program(name_loop->name, udev.subsystem, NULL, 0, NULL, (udev_log_priority >= LOG_INFO));
128 udev_cleanup_device(&udev);
133 static void msg_queue_delete(struct uevent_msg *msg)
135 list_del(&msg->node);
139 static void udev_event_run(struct uevent_msg *msg)
147 close(uevent_netlink_sock);
151 close(signal_pipe[READ_END]);
152 close(signal_pipe[WRITE_END]);
155 logging_init("udevd-event");
156 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
157 udev_event_process(msg);
158 info("seq %llu finished", msg->seqnum);
163 err("fork of child failed");
164 msg_queue_delete(msg);
167 /* get SIGCHLD in main loop */
168 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
169 msg->seqnum, pid, msg->action, msg->subsystem, time(NULL) - msg->queue_time);
174 static void msg_queue_insert(struct uevent_msg *msg)
176 msg->queue_time = time(NULL);
178 /* run all events with a timeout set immediately */
179 if (msg->timeout != 0) {
180 list_add_tail(&msg->node, &running_list);
185 list_add_tail(&msg->node, &exec_list);
189 /* runs event and removes event from run queue when finished */
190 static int running_processes(void)
193 static char buf[4096];
198 f = open("/proc/stat", O_RDONLY);
202 len = read(f, buf, sizeof(buf)-1);
210 pos = strstr(buf, "procs_running ");
214 if (sscanf(pos, "procs_running %u", &running) != 1)
220 /* return the number of process es in our session, count only until limit */
221 static int running_processes_in_session(pid_t session, int limit)
227 dir = opendir("/proc");
231 /* read process info from /proc */
232 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
238 pid_t ppid, pgrp, sess;
241 if (!isdigit(dent->d_name[0]))
244 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
245 procdir[sizeof(procdir)-1] = '\0';
247 f = open(procdir, O_RDONLY);
251 len = read(f, line, sizeof(line)-1);
259 /* skip ugly program name */
260 pos = strrchr(line, ')') + 2;
264 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
267 /* count only processes in our session */
271 /* count only running, no sleeping processes */
276 if (limit > 0 && running >= limit)
284 static int compare_devpath(const char *running, const char *waiting)
288 for (i = 0; i < PATH_SIZE; i++) {
289 /* identical device event found */
290 if (running[i] == '\0' && waiting[i] == '\0')
293 /* parent device event found */
294 if (running[i] == '\0' && waiting[i] == '/')
297 /* child device event found */
298 if (running[i] == '/' && waiting[i] == '\0')
301 /* no matching event */
302 if (running[i] != waiting[i])
309 /* returns still running task for the same device, its parent or its physical device */
310 static int running_with_devpath(struct uevent_msg *msg, int limit)
312 struct uevent_msg *loop_msg;
313 int childs_count = 0;
315 if (msg->devpath == NULL)
318 list_for_each_entry(loop_msg, &running_list, node) {
319 if (limit && childs_count++ > limit) {
320 dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
323 if (loop_msg->devpath == NULL)
326 /* return running parent/child device event */
327 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
328 dbg("%llu, child device event still running %llu (%s)",
329 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
333 /* return running physical device event */
334 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
335 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
336 dbg("%llu, physical device event still running %llu (%s)",
337 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
345 /* exec queue management routine executes the events and serializes events in the same sequence */
346 static void msg_queue_manager(void)
348 struct uevent_msg *loop_msg;
349 struct uevent_msg *tmp_msg;
352 if (list_empty(&exec_list))
355 running = running_processes();
356 dbg("%d processes runnning on system", running);
358 running = max_childs_running;
360 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
361 /* check running processes in our session and possibly throttle */
362 if (running >= max_childs_running) {
363 running = running_processes_in_session(sid, max_childs_running+10);
364 dbg("at least %d processes running in session", running);
365 if (running >= max_childs_running) {
366 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
371 /* don't run two processes for the same devpath and wait for the parent*/
372 if (running_with_devpath(loop_msg, max_childs)) {
373 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
377 /* move event to run list */
378 list_move_tail(&loop_msg->node, &running_list);
379 udev_event_run(loop_msg);
381 dbg("moved seq %llu to running list", loop_msg->seqnum);
385 static struct uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
389 struct uevent_msg *msg;
393 msg = malloc(sizeof(struct uevent_msg) + buf_size);
396 memset(msg, 0x00, sizeof(struct uevent_msg) + buf_size);
398 /* copy environment buffer and reconstruct envp */
399 memcpy(msg->envbuf, buf, buf_size);
401 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
405 key = &msg->envbuf[bufpos];
406 keylen = strlen(key);
408 bufpos += keylen + 1;
409 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
411 /* remember some keys for further processing */
412 if (strncmp(key, "ACTION=", 7) == 0)
413 msg->action = &key[7];
414 else if (strncmp(key, "DEVPATH=", 8) == 0)
415 msg->devpath = &key[8];
416 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
417 msg->subsystem = &key[10];
418 else if (strncmp(key, "SEQNUM=", 7) == 0)
419 msg->seqnum = strtoull(&key[7], NULL, 10);
420 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
421 msg->physdevpath = &key[12];
422 else if (strncmp(key, "MAJOR=", 6) == 0)
423 major = strtoull(&key[6], NULL, 10);
424 else if (strncmp(key, "MINOR=", 6) == 0)
425 minor = strtoull(&key[6], NULL, 10);
426 else if (strncmp(key, "TIMEOUT=", 8) == 0)
427 msg->timeout = strtoull(&key[8], NULL, 10);
429 msg->devt = makedev(major, minor);
430 msg->envp[i++] = "UDEVD_EVENT=1";
436 /* receive the udevd message from userspace */
437 static struct uevent_msg *get_udevd_msg(void)
439 static struct udevd_msg usend_msg;
440 struct uevent_msg *msg;
443 struct cmsghdr *cmsg;
446 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
450 memset(&usend_msg, 0x00, sizeof(struct udevd_msg));
451 iov.iov_base = &usend_msg;
452 iov.iov_len = sizeof(struct udevd_msg);
454 memset(&smsg, 0x00, sizeof(struct msghdr));
457 smsg.msg_control = cred_msg;
458 smsg.msg_controllen = sizeof(cred_msg);
460 size = recvmsg(udevd_sock, &smsg, 0);
463 err("unable to receive udevd message");
466 cmsg = CMSG_FIRSTHDR(&smsg);
467 cred = (struct ucred *) CMSG_DATA(cmsg);
469 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
470 err("no sender credentials received, message ignored");
474 if (cred->uid != 0) {
475 err("sender uid=%i, message ignored", cred->uid);
479 if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
480 err("message magic '%s' doesn't match, ignore it", usend_msg.magic);
484 switch (usend_msg.type) {
485 case UDEVD_UEVENT_UDEVSEND:
486 case UDEVD_UEVENT_INITSEND:
487 info("udevd event message received");
488 envbuf_size = size - offsetof(struct udevd_msg, envbuf);
489 dbg("envbuf_size=%i", envbuf_size);
490 msg = get_msg_from_envbuf(usend_msg.envbuf, envbuf_size);
493 msg->type = usend_msg.type;
495 case UDEVD_STOP_EXEC_QUEUE:
496 info("udevd message (STOP_EXEC_QUEUE) received");
499 case UDEVD_START_EXEC_QUEUE:
500 info("udevd message (START_EXEC_QUEUE) received");
504 case UDEVD_SET_LOG_LEVEL:
505 intval = (int *) usend_msg.envbuf;
506 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
507 udev_log_priority = *intval;
508 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
511 case UDEVD_SET_MAX_CHILDS:
512 intval = (int *) usend_msg.envbuf;
513 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
514 max_childs = *intval;
516 case UDEVD_RELOAD_RULES:
517 info("udevd message (RELOAD_RULES) received");
521 dbg("unknown message type");
526 /* receive the kernel user event message and do some sanity checks */
527 static struct uevent_msg *get_netlink_msg(void)
529 struct uevent_msg *msg;
532 static char buffer[UEVENT_BUFFER_SIZE + 512];
535 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
538 err("unable to receive udevd message");
542 if ((size_t)size > sizeof(buffer)-1)
543 size = sizeof(buffer)-1;
545 dbg("uevent_size=%zi", size);
547 /* start of event payload */
548 bufpos = strlen(buffer)+1;
549 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
552 msg->type = UDEVD_UEVENT_NETLINK;
554 /* validate message */
555 pos = strchr(buffer, '@');
557 err("invalid uevent '%s'", buffer);
563 if (msg->action == NULL) {
564 info("no ACTION in payload found, skip event '%s'", buffer);
569 if (strcmp(msg->action, buffer) != 0) {
570 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
578 static void asmlinkage sig_handler(int signum)
586 /* set flag, then write to pipe if needed */
587 sigchilds_waiting = 1;
594 /* write to pipe, which will wakeup select() in our mainloop */
595 write(signal_pipe[WRITE_END], "", 1);
598 static void udev_done(int pid)
600 /* find msg associated with pid and delete it */
601 struct uevent_msg *msg;
603 list_for_each_entry(msg, &running_list, node) {
604 if (msg->pid == pid) {
605 info("seq %llu, pid [%d] exit, %ld seconds old", msg->seqnum, msg->pid, time(NULL) - msg->queue_time);
606 msg_queue_delete(msg);
608 /* there may be events waiting with the same devpath */
615 static void reap_sigchilds(void)
620 pid = waitpid(-1, NULL, WNOHANG);
627 static int init_udevd_socket(void)
629 struct sockaddr_un saddr;
630 const int buffersize = 16 * 1024 * 1024;
632 const int feature_on = 1;
635 memset(&saddr, 0x00, sizeof(saddr));
636 saddr.sun_family = AF_LOCAL;
637 /* use abstract namespace for socket path */
638 strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
639 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
641 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
642 if (udevd_sock == -1) {
643 err("error getting socket, %s", strerror(errno));
647 /* set receive buffersize */
648 setsockopt(udevd_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
650 /* the bind takes care of ensuring only one copy running */
651 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
653 err("bind failed, %s", strerror(errno));
657 /* enable receiving of the sender credentials */
658 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
663 static int init_uevent_netlink_sock(void)
665 struct sockaddr_nl snl;
666 const int buffersize = 16 * 1024 * 1024;
669 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
670 snl.nl_family = AF_NETLINK;
671 snl.nl_pid = getpid();
672 snl.nl_groups = 0xffffffff;
674 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
675 if (uevent_netlink_sock == -1) {
676 err("error getting socket, %s", strerror(errno));
680 /* set receive buffersize */
681 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
683 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
685 err("bind failed, %s", strerror(errno));
686 close(uevent_netlink_sock);
687 uevent_netlink_sock = -1;
693 int main(int argc, char *argv[], char *envp[])
697 struct sigaction act;
705 /* redirect std fd's, if the kernel forks us, we don't have them at all */
706 fd = open("/dev/null", O_RDWR);
708 if (fd != STDIN_FILENO)
709 dup2(fd, STDIN_FILENO);
710 if (fd != STDOUT_FILENO)
711 dup2(fd, STDOUT_FILENO);
712 if (fd != STDERR_FILENO)
713 dup2(fd, STDERR_FILENO);
714 if (fd > STDERR_FILENO)
718 logging_init("udevd");
720 err("fatal, could not open /dev/null");
723 dbg("version %s", UDEV_VERSION);
726 err("need to be root, exit");
730 /* parse commandline options */
731 for (i = 1 ; i < argc; i++) {
733 if (strcmp(arg, "--daemon") == 0 || strcmp(arg, "-d") == 0) {
734 info("will daemonize");
737 if (strcmp(arg, "--stop-exec-queue") == 0) {
738 info("will not execute events until START_EXEC_QUEUE is received");
743 /* init sockets to receive events */
744 if (init_udevd_socket() < 0) {
745 if (errno == EADDRINUSE) {
746 dbg("another udevd running, exit");
749 dbg("error initializing udevd socket: %s", strerror(errno));
755 if (init_uevent_netlink_sock() < 0) {
756 err("uevent socket not available");
761 /* parse the rules and keep it in memory */
762 udev_rules_init(&rules, 1);
770 dbg("daemonized fork running");
773 err("fork of daemon failed");
777 dbg("child [%u] running, parent exits", pid);
782 /* set scheduling priority for the daemon */
783 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
788 /* become session leader */
790 dbg("our session is %d", sid);
792 /* OOM_DISABLE == -17 */
793 fd = open("/proc/self/oom_adj", O_RDWR);
795 err("error disabling OOM");
801 /* setup signal handler pipe */
802 retval = pipe(signal_pipe);
804 err("error getting pipes: %s", strerror(errno));
807 retval = fcntl(signal_pipe[READ_END], F_SETFL, O_NONBLOCK);
809 err("error fcntl on read pipe: %s", strerror(errno));
812 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, O_NONBLOCK);
814 err("error fcntl on write pipe: %s", strerror(errno));
818 /* set signal handlers */
819 memset(&act, 0x00, sizeof(struct sigaction));
820 act.sa_handler = (void (*)(int)) sig_handler;
821 sigemptyset(&act.sa_mask);
822 act.sa_flags = SA_RESTART;
823 sigaction(SIGINT, &act, NULL);
824 sigaction(SIGTERM, &act, NULL);
825 sigaction(SIGCHLD, &act, NULL);
826 sigaction(SIGHUP, &act, NULL);
828 /* watch rules directory */
829 inotify_fd = inotify_init();
831 inotify_add_watch(inotify_fd, udev_rules_filename, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
833 /* maximum limit of forked childs */
834 value = getenv("UDEVD_MAX_CHILDS");
836 max_childs = strtoul(value, NULL, 10);
838 max_childs = UDEVD_MAX_CHILDS;
839 info("initialize max_childs to %u", max_childs);
841 /* start to throttle forking if maximum number of _running_ childs is reached */
842 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
844 max_childs_running = strtoull(value, NULL, 10);
846 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
847 info("initialize max_childs_running to %u", max_childs_running);
849 /* clear environment for forked event processes */
852 /* export log_priority , as called programs may want to follow that setting */
853 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
857 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
858 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
859 maxfd = UDEV_MAX(maxfd, inotify_fd);
862 struct uevent_msg *msg;
866 FD_SET(signal_pipe[READ_END], &readfds);
867 FD_SET(udevd_sock, &readfds);
868 FD_SET(uevent_netlink_sock, &readfds);
870 FD_SET(inotify_fd, &readfds);
872 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
875 dbg("error in select: %s", strerror(errno));
879 /* get user socket message */
880 if (FD_ISSET(udevd_sock, &readfds)) {
881 msg = get_udevd_msg();
883 if (msg->type == UDEVD_UEVENT_UDEVSEND && msg->seqnum != 0) {
884 info("skip non-kernel message with SEQNUM");
887 msg_queue_insert(msg);
891 /* get kernel netlink message */
892 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
893 msg = get_netlink_msg();
895 msg_queue_insert(msg);
898 /* received a signal, clear our notification pipe */
899 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
902 read(signal_pipe[READ_END], &buf, sizeof(buf));
905 /* rules directory inotify watch */
906 if ((inotify_fd > 0) && FD_ISSET(inotify_fd, &readfds)) {
909 /* discard all possible events, we can just reload the config */
910 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes) {
914 buf = malloc(nbytes);
916 err("error getting buffer for inotify, disable watching");
920 read(inotify_fd, buf, nbytes);
925 /* rules changed, set by inotify or a signal*/
928 udev_rules_close(&rules);
929 udev_rules_init(&rules, 1);
932 /* forked child has returned */
933 if (sigchilds_waiting) {
934 sigchilds_waiting = 0;
946 udev_rules_close(&rules);
948 if (signal_pipe[READ_END] > 0)
949 close(signal_pipe[READ_END]);
950 if (signal_pipe[WRITE_END] > 0)
951 close(signal_pipe[WRITE_END]);
957 if (uevent_netlink_sock > 0)
958 close(uevent_netlink_sock);