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 if (run_program(name_loop->name, udev.subsystem, NULL, 0, NULL,
126 (udev_log_priority >= LOG_INFO)))
131 udev_cleanup_device(&udev);
136 static void msg_queue_delete(struct uevent_msg *msg)
138 list_del(&msg->node);
142 static void udev_event_run(struct uevent_msg *msg)
151 close(uevent_netlink_sock);
155 close(signal_pipe[READ_END]);
156 close(signal_pipe[WRITE_END]);
159 logging_init("udevd-event");
160 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
161 retval = udev_event_process(msg);
162 info("seq %llu finished", msg->seqnum);
169 err("fork of child failed: %s", strerror(errno));
170 msg_queue_delete(msg);
173 /* get SIGCHLD in main loop */
174 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
175 msg->seqnum, pid, msg->action, msg->subsystem, time(NULL) - msg->queue_time);
180 static void msg_queue_insert(struct uevent_msg *msg)
182 msg->queue_time = time(NULL);
184 /* run all events with a timeout set immediately */
185 if (msg->timeout != 0) {
186 list_add_tail(&msg->node, &running_list);
191 list_add_tail(&msg->node, &exec_list);
195 /* runs event and removes event from run queue when finished */
196 static int running_processes(void)
199 static char buf[4096];
204 f = open("/proc/stat", O_RDONLY);
208 len = read(f, buf, sizeof(buf)-1);
216 pos = strstr(buf, "procs_running ");
220 if (sscanf(pos, "procs_running %u", &running) != 1)
226 /* return the number of process es in our session, count only until limit */
227 static int running_processes_in_session(pid_t session, int limit)
233 dir = opendir("/proc");
237 /* read process info from /proc */
238 for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
244 pid_t ppid, pgrp, sess;
247 if (!isdigit(dent->d_name[0]))
250 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
251 procdir[sizeof(procdir)-1] = '\0';
253 f = open(procdir, O_RDONLY);
257 len = read(f, line, sizeof(line)-1);
265 /* skip ugly program name */
266 pos = strrchr(line, ')') + 2;
270 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
273 /* count only processes in our session */
277 /* count only running, no sleeping processes */
282 if (limit > 0 && running >= limit)
290 static int compare_devpath(const char *running, const char *waiting)
294 for (i = 0; i < PATH_SIZE; i++) {
295 /* identical device event found */
296 if (running[i] == '\0' && waiting[i] == '\0')
299 /* parent device event found */
300 if (running[i] == '\0' && waiting[i] == '/')
303 /* child device event found */
304 if (running[i] == '/' && waiting[i] == '\0')
307 /* no matching event */
308 if (running[i] != waiting[i])
315 /* returns still running task for the same device, its parent or its physical device */
316 static int running_with_devpath(struct uevent_msg *msg, int limit)
318 struct uevent_msg *loop_msg;
319 int childs_count = 0;
321 list_for_each_entry(loop_msg, &running_list, node) {
322 if (limit && childs_count++ > limit) {
323 dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
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";
435 info("DEVPATH missing, ignore message");
443 /* receive the udevd message from userspace */
444 static struct uevent_msg *get_udevd_msg(void)
446 static struct udevd_msg usend_msg;
447 struct uevent_msg *msg;
450 struct cmsghdr *cmsg;
453 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
457 memset(&usend_msg, 0x00, sizeof(struct udevd_msg));
458 iov.iov_base = &usend_msg;
459 iov.iov_len = sizeof(struct udevd_msg);
461 memset(&smsg, 0x00, sizeof(struct msghdr));
464 smsg.msg_control = cred_msg;
465 smsg.msg_controllen = sizeof(cred_msg);
467 size = recvmsg(udevd_sock, &smsg, 0);
470 err("unable to receive udevd message: %s", strerror(errno));
473 cmsg = CMSG_FIRSTHDR(&smsg);
474 cred = (struct ucred *) CMSG_DATA(cmsg);
476 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
477 err("no sender credentials received, message ignored");
481 if (cred->uid != 0) {
482 err("sender uid=%i, message ignored", cred->uid);
486 if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
487 err("message magic '%s' doesn't match, ignore it", usend_msg.magic);
491 switch (usend_msg.type) {
492 case UDEVD_UEVENT_UDEVSEND:
493 case UDEVD_UEVENT_INITSEND:
494 info("udevd event message received");
495 envbuf_size = size - offsetof(struct udevd_msg, envbuf);
496 dbg("envbuf_size=%i", envbuf_size);
497 msg = get_msg_from_envbuf(usend_msg.envbuf, envbuf_size);
500 msg->type = usend_msg.type;
502 case UDEVD_STOP_EXEC_QUEUE:
503 info("udevd message (STOP_EXEC_QUEUE) received");
506 case UDEVD_START_EXEC_QUEUE:
507 info("udevd message (START_EXEC_QUEUE) received");
511 case UDEVD_SET_LOG_LEVEL:
512 intval = (int *) usend_msg.envbuf;
513 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
514 udev_log_priority = *intval;
515 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
518 case UDEVD_SET_MAX_CHILDS:
519 intval = (int *) usend_msg.envbuf;
520 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
521 max_childs = *intval;
523 case UDEVD_RELOAD_RULES:
524 info("udevd message (RELOAD_RULES) received");
528 dbg("unknown message type");
533 /* receive the kernel user event message and do some sanity checks */
534 static struct uevent_msg *get_netlink_msg(void)
536 struct uevent_msg *msg;
539 static char buffer[UEVENT_BUFFER_SIZE + 512];
542 size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
545 err("unable to receive udevd message: %s", strerror(errno));
549 if ((size_t)size > sizeof(buffer)-1)
550 size = sizeof(buffer)-1;
552 dbg("uevent_size=%zi", size);
554 /* start of event payload */
555 bufpos = strlen(buffer)+1;
556 msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
559 msg->type = UDEVD_UEVENT_NETLINK;
561 /* validate message */
562 pos = strchr(buffer, '@');
564 err("invalid uevent '%s'", buffer);
570 if (msg->action == NULL) {
571 info("no ACTION in payload found, skip event '%s'", buffer);
576 if (strcmp(msg->action, buffer) != 0) {
577 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
585 static void asmlinkage sig_handler(int signum)
593 /* set flag, then write to pipe if needed */
594 sigchilds_waiting = 1;
601 /* write to pipe, which will wakeup select() in our mainloop */
602 write(signal_pipe[WRITE_END], "", 1);
605 static void udev_done(int pid, int exitstatus)
607 /* find msg associated with pid and delete it */
608 struct uevent_msg *msg;
610 list_for_each_entry(msg, &running_list, node) {
611 if (msg->pid == pid) {
612 info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
613 exitstatus, time(NULL) - msg->queue_time);
614 msg->exitstatus = exitstatus;
615 msg_queue_delete(msg);
617 /* there may be events waiting with the same devpath */
624 static void reap_sigchilds(void)
630 pid = waitpid(-1, &status, WNOHANG);
633 if (WIFEXITED(status))
634 status = WEXITSTATUS(status);
637 udev_done(pid, status);
641 static int init_udevd_socket(void)
643 struct sockaddr_un saddr;
644 const int buffersize = 16 * 1024 * 1024;
646 const int feature_on = 1;
649 memset(&saddr, 0x00, sizeof(saddr));
650 saddr.sun_family = AF_LOCAL;
651 /* use abstract namespace for socket path */
652 strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
653 addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
655 udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
656 if (udevd_sock == -1) {
657 err("error getting socket: %s", strerror(errno));
661 /* set receive buffersize */
662 setsockopt(udevd_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
664 /* the bind takes care of ensuring only one copy running */
665 retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
667 err("bind failed: %s", strerror(errno));
671 /* enable receiving of the sender credentials */
672 setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
677 static int init_uevent_netlink_sock(void)
679 struct sockaddr_nl snl;
680 const int buffersize = 16 * 1024 * 1024;
683 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
684 snl.nl_family = AF_NETLINK;
685 snl.nl_pid = getpid();
686 snl.nl_groups = 0xffffffff;
688 uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
689 if (uevent_netlink_sock == -1) {
690 err("error getting socket: %s", strerror(errno));
694 /* set receive buffersize */
695 setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
697 retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
699 err("bind failed: %s", strerror(errno));
700 close(uevent_netlink_sock);
701 uevent_netlink_sock = -1;
707 int main(int argc, char *argv[], char *envp[])
711 struct sigaction act;
719 /* redirect std fd's, if the kernel forks us, we don't have them at all */
720 fd = open("/dev/null", O_RDWR);
722 if (fd != STDIN_FILENO)
723 dup2(fd, STDIN_FILENO);
724 if (fd != STDOUT_FILENO)
725 dup2(fd, STDOUT_FILENO);
726 if (fd != STDERR_FILENO)
727 dup2(fd, STDERR_FILENO);
728 if (fd > STDERR_FILENO)
732 logging_init("udevd");
734 err("fatal, could not open /dev/null: %s", strerror(errno));
737 dbg("version %s", UDEV_VERSION);
740 err("need to be root, exit");
744 /* parse commandline options */
745 for (i = 1 ; i < argc; i++) {
747 if (strcmp(arg, "--daemon") == 0 || strcmp(arg, "-d") == 0) {
748 info("will daemonize");
751 if (strcmp(arg, "--stop-exec-queue") == 0) {
752 info("will not execute events until START_EXEC_QUEUE is received");
757 /* init sockets to receive events */
758 if (init_udevd_socket() < 0) {
759 if (errno == EADDRINUSE) {
760 err("another udevd running, exit");
763 err("error initializing udevd socket: %s", strerror(errno));
769 if (init_uevent_netlink_sock() < 0) {
770 err("uevent socket not available");
775 /* parse the rules and keep it in memory */
776 udev_rules_init(&rules, 1);
784 dbg("daemonized fork running");
787 err("fork of daemon failed: %s", strerror(errno));
791 dbg("child [%u] running, parent exits", pid);
796 /* set scheduling priority for the daemon */
797 setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
802 /* become session leader */
804 dbg("our session is %d", sid);
806 /* OOM_DISABLE == -17 */
807 fd = open("/proc/self/oom_adj", O_RDWR);
809 err("error disabling OOM: %s", strerror(errno));
815 /* setup signal handler pipe */
816 retval = pipe(signal_pipe);
818 err("error getting pipes: %s", strerror(errno));
821 retval = fcntl(signal_pipe[READ_END], F_SETFL, O_NONBLOCK);
823 err("error fcntl on read pipe: %s", strerror(errno));
826 retval = fcntl(signal_pipe[WRITE_END], F_SETFL, O_NONBLOCK);
828 err("error fcntl on write pipe: %s", strerror(errno));
832 /* set signal handlers */
833 memset(&act, 0x00, sizeof(struct sigaction));
834 act.sa_handler = (void (*)(int)) sig_handler;
835 sigemptyset(&act.sa_mask);
836 act.sa_flags = SA_RESTART;
837 sigaction(SIGINT, &act, NULL);
838 sigaction(SIGTERM, &act, NULL);
839 sigaction(SIGCHLD, &act, NULL);
840 sigaction(SIGHUP, &act, NULL);
842 /* watch rules directory */
843 inotify_fd = inotify_init();
845 inotify_add_watch(inotify_fd, udev_rules_filename, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
847 /* maximum limit of forked childs */
848 value = getenv("UDEVD_MAX_CHILDS");
850 max_childs = strtoul(value, NULL, 10);
852 max_childs = UDEVD_MAX_CHILDS;
853 info("initialize max_childs to %u", max_childs);
855 /* start to throttle forking if maximum number of _running_ childs is reached */
856 value = getenv("UDEVD_MAX_CHILDS_RUNNING");
858 max_childs_running = strtoull(value, NULL, 10);
860 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
861 info("initialize max_childs_running to %u", max_childs_running);
863 /* clear environment for forked event processes */
866 /* export log_priority , as called programs may want to follow that setting */
867 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
871 maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
872 maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
873 maxfd = UDEV_MAX(maxfd, inotify_fd);
876 struct uevent_msg *msg;
880 FD_SET(signal_pipe[READ_END], &readfds);
881 FD_SET(udevd_sock, &readfds);
882 FD_SET(uevent_netlink_sock, &readfds);
884 FD_SET(inotify_fd, &readfds);
886 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
889 err("error in select: %s", strerror(errno));
893 /* get user socket message */
894 if (FD_ISSET(udevd_sock, &readfds)) {
895 msg = get_udevd_msg();
897 if (msg->type == UDEVD_UEVENT_UDEVSEND && msg->seqnum != 0) {
898 info("skip non-kernel message with SEQNUM");
901 msg_queue_insert(msg);
905 /* get kernel netlink message */
906 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
907 msg = get_netlink_msg();
909 msg_queue_insert(msg);
912 /* received a signal, clear our notification pipe */
913 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
916 read(signal_pipe[READ_END], &buf, sizeof(buf));
919 /* rules directory inotify watch */
920 if ((inotify_fd > 0) && FD_ISSET(inotify_fd, &readfds)) {
923 /* discard all possible events, we can just reload the config */
924 if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes) {
928 buf = malloc(nbytes);
930 err("error getting buffer for inotify, disable watching");
934 read(inotify_fd, buf, nbytes);
939 /* rules changed, set by inotify or a signal*/
942 udev_rules_close(&rules);
943 udev_rules_init(&rules, 1);
946 /* forked child has returned */
947 if (sigchilds_waiting) {
948 sigchilds_waiting = 0;
960 udev_rules_close(&rules);
962 if (signal_pipe[READ_END] > 0)
963 close(signal_pipe[READ_END]);
964 if (signal_pipe[WRITE_END] > 0)
965 close(signal_pipe[WRITE_END]);
971 if (uevent_netlink_sock > 0)
972 close(uevent_netlink_sock);