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 if (msg->devpath == NULL)
319 list_for_each_entry(loop_msg, &running_list, node) {
320 if (limit && childs_count++ > limit) {
321 dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
324 if (loop_msg->devpath == NULL)
327 /* return running parent/child device event */
328 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
329 dbg("%llu, child device event still running %llu (%s)",
330 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
334 /* return running physical device event */
335 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
336 if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
337 dbg("%llu, physical device event still running %llu (%s)",
338 msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
346 /* exec queue management routine executes the events and serializes events in the same sequence */
347 static void msg_queue_manager(void)
349 struct uevent_msg *loop_msg;
350 struct uevent_msg *tmp_msg;
353 if (list_empty(&exec_list))
356 running = running_processes();
357 dbg("%d processes runnning on system", running);
359 running = max_childs_running;
361 list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
362 /* check running processes in our session and possibly throttle */
363 if (running >= max_childs_running) {
364 running = running_processes_in_session(sid, max_childs_running+10);
365 dbg("at least %d processes running in session", running);
366 if (running >= max_childs_running) {
367 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
372 /* don't run two processes for the same devpath and wait for the parent*/
373 if (running_with_devpath(loop_msg, max_childs)) {
374 dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
378 /* move event to run list */
379 list_move_tail(&loop_msg->node, &running_list);
380 udev_event_run(loop_msg);
382 dbg("moved seq %llu to running list", loop_msg->seqnum);
386 static struct uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
390 struct uevent_msg *msg;
394 msg = malloc(sizeof(struct uevent_msg) + buf_size);
397 memset(msg, 0x00, sizeof(struct uevent_msg) + buf_size);
399 /* copy environment buffer and reconstruct envp */
400 memcpy(msg->envbuf, buf, buf_size);
402 for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
406 key = &msg->envbuf[bufpos];
407 keylen = strlen(key);
409 bufpos += keylen + 1;
410 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
412 /* remember some keys for further processing */
413 if (strncmp(key, "ACTION=", 7) == 0)
414 msg->action = &key[7];
415 else if (strncmp(key, "DEVPATH=", 8) == 0)
416 msg->devpath = &key[8];
417 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
418 msg->subsystem = &key[10];
419 else if (strncmp(key, "SEQNUM=", 7) == 0)
420 msg->seqnum = strtoull(&key[7], NULL, 10);
421 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
422 msg->physdevpath = &key[12];
423 else if (strncmp(key, "MAJOR=", 6) == 0)
424 major = strtoull(&key[6], NULL, 10);
425 else if (strncmp(key, "MINOR=", 6) == 0)
426 minor = strtoull(&key[6], NULL, 10);
427 else if (strncmp(key, "TIMEOUT=", 8) == 0)
428 msg->timeout = strtoull(&key[8], NULL, 10);
430 msg->devt = makedev(major, minor);
431 msg->envp[i++] = "UDEVD_EVENT=1";
437 /* receive the udevd message from userspace */
438 static struct uevent_msg *get_udevd_msg(void)
440 static struct udevd_msg usend_msg;
441 struct uevent_msg *msg;
444 struct cmsghdr *cmsg;
447 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
451 memset(&usend_msg, 0x00, sizeof(struct udevd_msg));
452 iov.iov_base = &usend_msg;
453 iov.iov_len = sizeof(struct udevd_msg);
455 memset(&smsg, 0x00, sizeof(struct msghdr));
458 smsg.msg_control = cred_msg;
459 smsg.msg_controllen = sizeof(cred_msg);
461 size = recvmsg(udevd_sock, &smsg, 0);
464 err("unable to receive udevd message: %s", strerror(errno));
467 cmsg = CMSG_FIRSTHDR(&smsg);
468 cred = (struct ucred *) CMSG_DATA(cmsg);
470 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
471 err("no sender credentials received, message ignored");
475 if (cred->uid != 0) {
476 err("sender uid=%i, message ignored", cred->uid);
480 if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
481 err("message magic '%s' doesn't match, ignore it", usend_msg.magic);
485 switch (usend_msg.type) {
486 case UDEVD_UEVENT_UDEVSEND:
487 case UDEVD_UEVENT_INITSEND:
488 info("udevd event message received");
489 envbuf_size = size - offsetof(struct udevd_msg, envbuf);
490 dbg("envbuf_size=%i", envbuf_size);
491 msg = get_msg_from_envbuf(usend_msg.envbuf, envbuf_size);
494 msg->type = usend_msg.type;
496 case UDEVD_STOP_EXEC_QUEUE:
497 info("udevd message (STOP_EXEC_QUEUE) received");
500 case UDEVD_START_EXEC_QUEUE:
501 info("udevd message (START_EXEC_QUEUE) received");
505 case UDEVD_SET_LOG_LEVEL:
506 intval = (int *) usend_msg.envbuf;
507 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
508 udev_log_priority = *intval;
509 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
512 case UDEVD_SET_MAX_CHILDS:
513 intval = (int *) usend_msg.envbuf;
514 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
515 max_childs = *intval;
517 case UDEVD_RELOAD_RULES:
518 info("udevd message (RELOAD_RULES) received");
522 dbg("unknown message type");
527 /* receive the kernel user event message and do some sanity checks */
528 static struct uevent_msg *get_netlink_msg(void)
530 struct uevent_msg *msg;
533 static char buffer[UEVENT_BUFFER_SIZE + 512];
536 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
539 err("unable to receive udevd message: %s", strerror(errno));
543 if ((size_t)size > sizeof(buffer)-1)
544 size = sizeof(buffer)-1;
546 dbg("uevent_size=%zi", size);
548 /* start of event payload */
549 bufpos = strlen(buffer)+1;
550 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
553 msg->type = UDEVD_UEVENT_NETLINK;
555 /* validate message */
556 pos = strchr(buffer, '@');
558 err("invalid uevent '%s'", buffer);
564 if (msg->action == NULL) {
565 info("no ACTION in payload found, skip event '%s'", buffer);
570 if (strcmp(msg->action, buffer) != 0) {
571 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
579 static void asmlinkage sig_handler(int signum)
587 /* set flag, then write to pipe if needed */
588 sigchilds_waiting = 1;
595 /* write to pipe, which will wakeup select() in our mainloop */
596 write(signal_pipe[WRITE_END], "", 1);
599 static void udev_done(int pid)
601 /* find msg associated with pid and delete it */
602 struct uevent_msg *msg;
604 list_for_each_entry(msg, &running_list, node) {
605 if (msg->pid == pid) {
606 info("seq %llu, pid [%d] exit, %ld seconds old", msg->seqnum, msg->pid, time(NULL) - msg->queue_time);
607 msg_queue_delete(msg);
609 /* there may be events waiting with the same devpath */
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: %s", strerror(errno));
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 err("another udevd running, exit");
750 err("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: %s", strerror(errno));
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: %s", strerror(errno));
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 err("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;
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);