2 * Copyright (C) 2004-2011 Kay Sievers <kay.sievers@vrfy.org>
3 * Copyright (C) 2004 Chris Friesen <chris_friesen@sympatico.ca>
4 * Copyright (C) 2009 Canonical Ltd.
5 * Copyright (C) 2009 Scott James Remnant <scott@netsplit.com>
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
35 #include <sys/prctl.h>
36 #include <sys/socket.h>
38 #include <sys/signalfd.h>
39 #include <sys/epoll.h>
43 #include <sys/ioctl.h>
44 #include <sys/inotify.h>
45 #include <sys/utsname.h>
48 #include "sd-daemon.h"
52 static void log_fn(struct udev *udev, int priority,
53 const char *file, int line, const char *fn,
54 const char *format, va_list args)
61 vsnprintf(buf, sizeof(buf), format, args);
62 gettimeofday(&tv, &tz);
63 fprintf(stderr, "%llu.%06u [%u] %s: %s",
64 (unsigned long long) tv.tv_sec, (unsigned int) tv.tv_usec,
65 (int) getpid(), fn, buf);
67 vsyslog(priority, format, args);
71 static struct udev_rules *rules;
72 static struct udev_queue_export *udev_queue_export;
73 static struct udev_ctrl *udev_ctrl;
74 static struct udev_monitor *monitor;
75 static int worker_watch[2] = { -1, -1 };
76 static int fd_signal = -1;
77 static int fd_ep = -1;
78 static int fd_inotify = -1;
79 static bool stop_exec_queue;
80 static bool reload_config;
82 static int children_max;
83 static int exec_delay;
84 static sigset_t sigmask_orig;
85 static UDEV_LIST(event_list);
86 static UDEV_LIST(worker_list);
87 static bool udev_exit;
96 struct udev_list_node node;
98 struct udev_device *dev;
99 enum event_state state;
101 unsigned long long int delaying_seqnum;
102 unsigned long long int seqnum;
105 const char *devpath_old;
111 static struct event *node_to_event(struct udev_list_node *node)
115 event = (char *)node;
116 event -= offsetof(struct event, node);
117 return (struct event *)event;
120 static void event_queue_cleanup(struct udev *udev, enum event_state type);
130 struct udev_list_node node;
134 struct udev_monitor *monitor;
135 enum worker_state state;
139 /* passed from worker to main process */
140 struct worker_message {
145 static struct worker *node_to_worker(struct udev_list_node *node)
149 worker = (char *)node;
150 worker -= offsetof(struct worker, node);
151 return (struct worker *)worker;
154 static void event_queue_delete(struct event *event, bool export)
156 udev_list_node_remove(&event->node);
159 /* mark as failed, if "add" event returns non-zero */
160 if (event->exitcode != 0 && strcmp(udev_device_get_action(event->dev), "remove") != 0)
161 udev_queue_export_device_failed(udev_queue_export, event->dev);
163 udev_queue_export_device_finished(udev_queue_export, event->dev);
164 info(event->udev, "seq %llu done with %i\n", udev_device_get_seqnum(event->dev), event->exitcode);
166 udev_device_unref(event->dev);
170 static struct worker *worker_ref(struct worker *worker)
176 static void worker_cleanup(struct worker *worker)
178 udev_list_node_remove(&worker->node);
179 udev_monitor_unref(worker->monitor);
184 static void worker_unref(struct worker *worker)
187 if (worker->refcount > 0)
189 info(worker->udev, "worker [%u] cleaned up\n", worker->pid);
190 worker_cleanup(worker);
193 static void worker_list_cleanup(struct udev *udev)
195 struct udev_list_node *loop, *tmp;
197 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
198 struct worker *worker = node_to_worker(loop);
200 worker_cleanup(worker);
204 static void worker_new(struct event *event)
206 struct udev *udev = event->udev;
207 struct worker *worker;
208 struct udev_monitor *worker_monitor;
211 /* listen for new events */
212 worker_monitor = udev_monitor_new_from_netlink(udev, NULL);
213 if (worker_monitor == NULL)
215 /* allow the main daemon netlink address to send devices to the worker */
216 udev_monitor_allow_unicast_sender(worker_monitor, monitor);
217 udev_monitor_enable_receiving(worker_monitor);
219 worker = calloc(1, sizeof(struct worker));
220 if (worker == NULL) {
221 udev_monitor_unref(worker_monitor);
224 /* worker + event reference */
225 worker->refcount = 2;
231 struct udev_device *dev = NULL;
233 struct epoll_event ep_signal, ep_monitor;
235 int rc = EXIT_SUCCESS;
237 /* move initial device from queue */
242 worker_list_cleanup(udev);
243 event_queue_cleanup(udev, EVENT_UNDEF);
244 udev_queue_export_unref(udev_queue_export);
245 udev_monitor_unref(monitor);
246 udev_ctrl_unref(udev_ctrl);
249 close(worker_watch[READ_END]);
252 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
254 err(udev, "error creating signalfd %m\n");
259 fd_ep = epoll_create1(EPOLL_CLOEXEC);
261 err(udev, "error creating epoll fd: %m\n");
266 memset(&ep_signal, 0, sizeof(struct epoll_event));
267 ep_signal.events = EPOLLIN;
268 ep_signal.data.fd = fd_signal;
270 fd_monitor = udev_monitor_get_fd(worker_monitor);
271 memset(&ep_monitor, 0, sizeof(struct epoll_event));
272 ep_monitor.events = EPOLLIN;
273 ep_monitor.data.fd = fd_monitor;
275 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
276 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_monitor, &ep_monitor) < 0) {
277 err(udev, "fail to add fds to epoll: %m\n");
282 /* request TERM signal if parent exits */
283 prctl(PR_SET_PDEATHSIG, SIGTERM);
286 struct udev_event *udev_event;
287 struct worker_message msg;
291 info(udev, "seq %llu running\n", udev_device_get_seqnum(dev));
292 udev_event = udev_event_new(dev);
293 if (udev_event == NULL) {
298 /* needed for SIGCHLD/SIGTERM in spawn() */
299 udev_event->fd_signal = fd_signal;
302 udev_event->exec_delay = exec_delay;
304 /* apply rules, create node, symlinks */
305 err = udev_event_execute_rules(udev_event, rules, &sigmask_orig);
308 failed = udev_event_execute_run(udev_event, &sigmask_orig);
310 /* apply/restore inotify watch */
311 if (err == 0 && udev_event->inotify_watch) {
312 udev_watch_begin(udev, dev);
313 udev_device_update_db(dev);
316 /* send processed event back to libudev listeners */
317 udev_monitor_send_device(worker_monitor, NULL, dev);
319 /* send udevd the result of the event execution */
320 memset(&msg, 0, sizeof(struct worker_message));
323 else if (failed != 0)
324 msg.exitcode = failed;
326 send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
328 info(udev, "seq %llu processed with %i\n", udev_device_get_seqnum(dev), err);
330 udev_device_unref(dev);
333 if (udev_event->sigterm) {
334 udev_event_unref(udev_event);
338 udev_event_unref(udev_event);
340 /* wait for more device messages from main udevd, or term signal */
341 while (dev == NULL) {
342 struct epoll_event ev[4];
346 fdcount = epoll_wait(fd_ep, ev, ARRAY_SIZE(ev), -1);
351 err(udev, "failed to poll: %m\n");
355 for (i = 0; i < fdcount; i++) {
356 if (ev[i].data.fd == fd_monitor && ev[i].events & EPOLLIN) {
357 dev = udev_monitor_receive_device(worker_monitor);
358 } else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN) {
359 struct signalfd_siginfo fdsi;
362 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
363 if (size != sizeof(struct signalfd_siginfo))
365 switch (fdsi.ssi_signo) {
377 udev_device_unref(dev);
383 close(worker_watch[WRITE_END]);
384 udev_rules_unref(rules);
385 udev_monitor_unref(worker_monitor);
391 udev_monitor_unref(worker_monitor);
392 event->state = EVENT_QUEUED;
394 err(udev, "fork of child failed: %m\n");
397 /* close monitor, but keep address around */
398 udev_monitor_disconnect(worker_monitor);
399 worker->monitor = worker_monitor;
401 worker->state = WORKER_RUNNING;
402 worker->event = event;
403 event->state = EVENT_RUNNING;
404 udev_list_node_append(&worker->node, &worker_list);
406 info(udev, "seq %llu forked new worker [%u]\n", udev_device_get_seqnum(event->dev), pid);
411 static void event_run(struct event *event, bool force)
413 struct udev_list_node *loop;
415 udev_list_node_foreach(loop, &worker_list) {
416 struct worker *worker = node_to_worker(loop);
419 if (worker->state != WORKER_IDLE)
422 count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
424 err(event->udev, "worker [%u] did not accept message %zi (%m), kill it\n", worker->pid, count);
425 kill(worker->pid, SIGKILL);
426 worker->state = WORKER_KILLED;
430 worker->event = event;
431 worker->state = WORKER_RUNNING;
432 event->state = EVENT_RUNNING;
436 if (!force && children >= children_max) {
437 if (children_max > 1)
438 info(event->udev, "maximum number (%i) of children reached\n", children);
442 /* start new worker and pass initial device */
446 static int event_queue_insert(struct udev_device *dev)
450 event = calloc(1, sizeof(struct event));
454 event->udev = udev_device_get_udev(dev);
456 event->seqnum = udev_device_get_seqnum(dev);
457 event->devpath = udev_device_get_devpath(dev);
458 event->devpath_len = strlen(event->devpath);
459 event->devpath_old = udev_device_get_devpath_old(dev);
460 event->devnum = udev_device_get_devnum(dev);
461 event->is_block = (strcmp("block", udev_device_get_subsystem(dev)) == 0);
462 event->ifindex = udev_device_get_ifindex(dev);
464 udev_queue_export_device_queued(udev_queue_export, dev);
465 info(event->udev, "seq %llu queued, '%s' '%s'\n", udev_device_get_seqnum(dev),
466 udev_device_get_action(dev), udev_device_get_subsystem(dev));
468 event->state = EVENT_QUEUED;
469 udev_list_node_append(&event->node, &event_list);
471 /* run all events with a timeout set immediately */
472 if (udev_device_get_timeout(dev) > 0) {
473 event_run(event, true);
480 static void worker_kill(struct udev *udev, int retain)
482 struct udev_list_node *loop;
485 if (children <= retain)
488 max = children - retain;
490 udev_list_node_foreach(loop, &worker_list) {
491 struct worker *worker = node_to_worker(loop);
496 if (worker->state == WORKER_KILLED)
499 worker->state = WORKER_KILLED;
500 kill(worker->pid, SIGTERM);
504 /* lookup event for identical, parent, child device */
505 static bool is_devpath_busy(struct event *event)
507 struct udev_list_node *loop;
510 /* check if queue contains events we depend on */
511 udev_list_node_foreach(loop, &event_list) {
512 struct event *loop_event = node_to_event(loop);
514 /* we already found a later event, earlier can not block us, no need to check again */
515 if (loop_event->seqnum < event->delaying_seqnum)
518 /* event we checked earlier still exists, no need to check again */
519 if (loop_event->seqnum == event->delaying_seqnum)
522 /* found ourself, no later event can block us */
523 if (loop_event->seqnum >= event->seqnum)
526 /* check major/minor */
527 if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
530 /* check network device ifindex */
531 if (event->ifindex != 0 && event->ifindex == loop_event->ifindex)
534 /* check our old name */
535 if (event->devpath_old != NULL && strcmp(loop_event->devpath, event->devpath_old) == 0) {
536 event->delaying_seqnum = loop_event->seqnum;
540 /* compare devpath */
541 common = MIN(loop_event->devpath_len, event->devpath_len);
543 /* one devpath is contained in the other? */
544 if (memcmp(loop_event->devpath, event->devpath, common) != 0)
547 /* identical device event found */
548 if (loop_event->devpath_len == event->devpath_len) {
549 /* devices names might have changed/swapped in the meantime */
550 if (major(event->devnum) != 0 && (event->devnum != loop_event->devnum || event->is_block != loop_event->is_block))
552 if (event->ifindex != 0 && event->ifindex != loop_event->ifindex)
554 event->delaying_seqnum = loop_event->seqnum;
558 /* parent device event found */
559 if (event->devpath[common] == '/') {
560 event->delaying_seqnum = loop_event->seqnum;
564 /* child device event found */
565 if (loop_event->devpath[common] == '/') {
566 event->delaying_seqnum = loop_event->seqnum;
570 /* no matching device */
577 static void event_queue_start(struct udev *udev)
579 struct udev_list_node *loop;
581 udev_list_node_foreach(loop, &event_list) {
582 struct event *event = node_to_event(loop);
584 if (event->state != EVENT_QUEUED)
587 /* do not start event if parent or child event is still running */
588 if (is_devpath_busy(event)) {
589 dbg(udev, "delay seq %llu (%s)\n", event->seqnum, event->devpath);
593 event_run(event, false);
597 static void event_queue_cleanup(struct udev *udev, enum event_state match_type)
599 struct udev_list_node *loop, *tmp;
601 udev_list_node_foreach_safe(loop, tmp, &event_list) {
602 struct event *event = node_to_event(loop);
604 if (match_type != EVENT_UNDEF && match_type != event->state)
607 event_queue_delete(event, false);
611 static void worker_returned(int fd_worker)
614 struct worker_message msg;
616 struct udev_list_node *loop;
618 size = recv(fd_worker, &msg, sizeof(struct worker_message), MSG_DONTWAIT);
619 if (size != sizeof(struct worker_message))
622 /* lookup worker who sent the signal */
623 udev_list_node_foreach(loop, &worker_list) {
624 struct worker *worker = node_to_worker(loop);
626 if (worker->pid != msg.pid)
629 /* worker returned */
630 worker->event->exitcode = msg.exitcode;
631 event_queue_delete(worker->event, true);
632 worker->event = NULL;
633 if (worker->state != WORKER_KILLED)
634 worker->state = WORKER_IDLE;
635 worker_unref(worker);
641 /* receive the udevd message from userspace */
642 static struct udev_ctrl_connection *handle_ctrl_msg(struct udev_ctrl *uctrl)
644 struct udev *udev = udev_ctrl_get_udev(uctrl);
645 struct udev_ctrl_connection *ctrl_conn;
646 struct udev_ctrl_msg *ctrl_msg = NULL;
650 ctrl_conn = udev_ctrl_get_connection(uctrl);
651 if (ctrl_conn == NULL)
654 ctrl_msg = udev_ctrl_receive_msg(ctrl_conn);
655 if (ctrl_msg == NULL)
658 i = udev_ctrl_get_set_log_level(ctrl_msg);
660 info(udev, "udevd message (SET_LOG_PRIORITY) received, log_priority=%i\n", i);
661 udev_set_log_priority(udev, i);
662 worker_kill(udev, 0);
665 if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
666 info(udev, "udevd message (STOP_EXEC_QUEUE) received\n");
667 stop_exec_queue = true;
670 if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
671 info(udev, "udevd message (START_EXEC_QUEUE) received\n");
672 stop_exec_queue = false;
675 if (udev_ctrl_get_reload_rules(ctrl_msg) > 0) {
676 info(udev, "udevd message (RELOAD_RULES) received\n");
677 reload_config = true;
680 str = udev_ctrl_get_set_env(ctrl_msg);
688 val = strchr(key, '=');
692 if (val[0] == '\0') {
693 info(udev, "udevd message (ENV) received, unset '%s'\n", key);
694 udev_add_property(udev, key, NULL);
696 info(udev, "udevd message (ENV) received, set '%s=%s'\n", key, val);
697 udev_add_property(udev, key, val);
700 err(udev, "wrong key format '%s'\n", key);
704 worker_kill(udev, 0);
707 i = udev_ctrl_get_set_children_max(ctrl_msg);
709 info(udev, "udevd message (SET_MAX_CHILDREN) received, children_max=%i\n", i);
713 if (udev_ctrl_get_ping(ctrl_msg) > 0)
714 info(udev, "udevd message (SYNC) received\n");
716 if (udev_ctrl_get_exit(ctrl_msg) > 0) {
717 info(udev, "udevd message (EXIT) received\n");
719 /* keep reference to block the client until we exit */
720 udev_ctrl_connection_ref(ctrl_conn);
723 udev_ctrl_msg_unref(ctrl_msg);
724 return udev_ctrl_connection_unref(ctrl_conn);
727 /* read inotify messages */
728 static int handle_inotify(struct udev *udev)
732 struct inotify_event *ev;
734 if ((ioctl(fd_inotify, FIONREAD, &nbytes) < 0) || (nbytes <= 0))
737 buf = malloc(nbytes);
739 err(udev, "error getting buffer for inotify\n");
743 nbytes = read(fd_inotify, buf, nbytes);
745 for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
746 struct udev_device *dev;
748 ev = (struct inotify_event *)(buf + pos);
752 info(udev, "inotify event: %x for %s\n", ev->mask, ev->name);
753 s = strstr(ev->name, ".rules");
756 if (strlen(s) != strlen(".rules"))
758 reload_config = true;
762 dev = udev_watch_lookup(udev, ev->wd);
764 info(udev, "inotify event: %x for %s\n", ev->mask, udev_device_get_devnode(dev));
765 if (ev->mask & IN_CLOSE_WRITE) {
766 char filename[UTIL_PATH_SIZE];
769 info(udev, "device %s closed, synthesising 'change'\n", udev_device_get_devnode(dev));
770 util_strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
771 fd = open(filename, O_WRONLY);
773 if (write(fd, "change", 6) < 0)
774 info(udev, "error writing uevent: %m\n");
778 if (ev->mask & IN_IGNORED)
779 udev_watch_end(udev, dev);
781 udev_device_unref(dev);
790 static void handle_signal(struct udev *udev, int signo)
801 struct udev_list_node *loop, *tmp;
803 pid = waitpid(-1, &status, WNOHANG);
807 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
808 struct worker *worker = node_to_worker(loop);
810 if (worker->pid != pid)
813 info(udev, "worker [%u] exit\n", pid);
814 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
815 if (WEXITSTATUS(status))
816 err(udev, "worker [%u] unexpectedly returned with status %d\n", pid, WEXITSTATUS(status));
817 else if (WIFSIGNALED(status))
818 err(udev, "worker [%u] killed by signal %d (%s)\n", pid,
819 WTERMSIG(status), strsignal(WTERMSIG(status)));
820 else if (WIFSTOPPED(status))
821 err(udev, "worker [%u] unexpectedly stopped\n", pid);
822 else if (WIFCONTINUED(status))
823 err(udev, "worker [%u] continued\n", pid);
825 if (worker->event != NULL) {
826 err(udev, "worker [%u] failed while handling '%s'\n", pid, worker->event->devpath);
827 worker->event->exitcode = -32;
828 event_queue_delete(worker->event, true);
829 /* drop reference from running event */
830 worker_unref(worker);
833 worker_unref(worker);
839 reload_config = true;
844 static void static_dev_create_from_modules(struct udev *udev)
846 struct utsname kernel;
847 char modules[UTIL_PATH_SIZE];
852 util_strscpyl(modules, sizeof(modules), "/lib/modules/", kernel.release, "/modules.devname", NULL);
853 f = fopen(modules, "r");
857 while (fgets(buf, sizeof(buf), f) != NULL) {
865 char filename[UTIL_PATH_SIZE];
871 s = strchr(modname, ' ');
877 s = strchr(devname, ' ');
883 s = strchr(devno, ' ');
885 s = strchr(devno, '\n');
888 if (sscanf(devno, "%c%u:%u", &type, &maj, &min) != 3)
892 mode = 0600 | S_IFCHR;
893 else if (type == 'b')
894 mode = 0600 | S_IFBLK;
898 util_strscpyl(filename, sizeof(filename), udev_get_dev_path(udev), "/", devname, NULL);
899 util_create_path_selinux(udev, filename);
900 udev_selinux_setfscreatecon(udev, filename, mode);
901 info(udev, "mknod '%s' %c%u:%u\n", filename, type, maj, min);
902 if (mknod(filename, mode, makedev(maj, min)) < 0 && errno == EEXIST)
903 utimensat(AT_FDCWD, filename, NULL, 0);
904 udev_selinux_resetfscreatecon(udev);
910 static int copy_dev_dir(struct udev *udev, DIR *dir_from, DIR *dir_to, int maxdepth)
914 for (dent = readdir(dir_from); dent != NULL; dent = readdir(dir_from)) {
917 if (dent->d_name[0] == '.')
919 if (fstatat(dirfd(dir_from), dent->d_name, &stats, AT_SYMLINK_NOFOLLOW) != 0)
922 if (S_ISBLK(stats.st_mode) || S_ISCHR(stats.st_mode)) {
923 udev_selinux_setfscreateconat(udev, dirfd(dir_to), dent->d_name, stats.st_mode & 0777);
924 if (mknodat(dirfd(dir_to), dent->d_name, stats.st_mode, stats.st_rdev) == 0) {
925 fchmodat(dirfd(dir_to), dent->d_name, stats.st_mode & 0777, 0);
926 fchownat(dirfd(dir_to), dent->d_name, stats.st_uid, stats.st_gid, 0);
928 utimensat(dirfd(dir_to), dent->d_name, NULL, 0);
930 udev_selinux_resetfscreatecon(udev);
931 } else if (S_ISLNK(stats.st_mode)) {
932 char target[UTIL_PATH_SIZE];
935 len = readlinkat(dirfd(dir_from), dent->d_name, target, sizeof(target));
936 if (len <= 0 || len == (ssize_t)sizeof(target))
939 udev_selinux_setfscreateconat(udev, dirfd(dir_to), dent->d_name, S_IFLNK);
940 if (symlinkat(target, dirfd(dir_to), dent->d_name) < 0 && errno == EEXIST)
941 utimensat(dirfd(dir_to), dent->d_name, NULL, AT_SYMLINK_NOFOLLOW);
942 udev_selinux_resetfscreatecon(udev);
943 } else if (S_ISDIR(stats.st_mode)) {
944 DIR *dir2_from, *dir2_to;
949 udev_selinux_setfscreateconat(udev, dirfd(dir_to), dent->d_name, S_IFDIR|0755);
950 mkdirat(dirfd(dir_to), dent->d_name, 0755);
951 udev_selinux_resetfscreatecon(udev);
953 dir2_to = fdopendir(openat(dirfd(dir_to), dent->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC));
957 dir2_from = fdopendir(openat(dirfd(dir_from), dent->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC));
958 if (dir2_from == NULL) {
963 copy_dev_dir(udev, dir2_from, dir2_to, maxdepth-1);
973 static void static_dev_create_links(struct udev *udev, DIR *dir)
979 static const struct stdlinks stdlinks[] = {
980 { "core", "/proc/kcore" },
981 { "fd", "/proc/self/fd" },
982 { "stdin", "/proc/self/fd/0" },
983 { "stdout", "/proc/self/fd/1" },
984 { "stderr", "/proc/self/fd/2" },
988 for (i = 0; i < ARRAY_SIZE(stdlinks); i++) {
991 if (stat(stdlinks[i].target, &sb) == 0) {
992 udev_selinux_setfscreateconat(udev, dirfd(dir), stdlinks[i].link, S_IFLNK);
993 if (symlinkat(stdlinks[i].target, dirfd(dir), stdlinks[i].link) < 0 && errno == EEXIST)
994 utimensat(dirfd(dir), stdlinks[i].link, NULL, AT_SYMLINK_NOFOLLOW);
995 udev_selinux_resetfscreatecon(udev);
1000 static void static_dev_create_from_devices(struct udev *udev, DIR *dir)
1004 dir_from = opendir(LIBEXECDIR "/devices");
1005 if (dir_from == NULL)
1007 copy_dev_dir(udev, dir_from, dir, 8);
1011 static void static_dev_create(struct udev *udev)
1015 dir = opendir(udev_get_dev_path(udev));
1019 static_dev_create_links(udev, dir);
1020 static_dev_create_from_devices(udev, dir);
1025 static int mem_size_mb(void)
1029 long int memsize = -1;
1031 f = fopen("/proc/meminfo", "r");
1035 while (fgets(buf, sizeof(buf), f) != NULL) {
1038 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
1039 memsize = value / 1024;
1048 static int convert_db(struct udev *udev)
1050 char filename[UTIL_PATH_SIZE];
1052 struct udev_enumerate *udev_enumerate;
1053 struct udev_list_entry *list_entry;
1055 /* current database */
1056 util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/data", NULL);
1057 if (access(filename, F_OK) >= 0)
1060 /* make sure we do not get here again */
1061 util_create_path(udev, filename);
1062 mkdir(filename, 0755);
1065 util_strscpyl(filename, sizeof(filename), udev_get_dev_path(udev), "/.udev/db", NULL);
1066 if (access(filename, F_OK) < 0)
1069 f = fopen("/dev/kmsg", "w");
1071 fprintf(f, "<30>udevd[%u]: converting old udev database\n", getpid());
1075 udev_enumerate = udev_enumerate_new(udev);
1076 if (udev_enumerate == NULL)
1078 udev_enumerate_scan_devices(udev_enumerate);
1079 udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(udev_enumerate)) {
1080 struct udev_device *device;
1082 device = udev_device_new_from_syspath(udev, udev_list_entry_get_name(list_entry));
1086 /* try to find the old database for devices without a current one */
1087 if (udev_device_read_db(device, NULL) < 0) {
1091 char devpath[UTIL_PATH_SIZE];
1092 char from[UTIL_PATH_SIZE];
1096 /* find database in old location */
1097 id = udev_device_get_id_filename(device);
1098 util_strscpyl(from, sizeof(from), udev_get_dev_path(udev), "/.udev/db/", id, NULL);
1099 if (lstat(from, &stats) == 0) {
1101 udev_device_read_db(device, from);
1107 /* find old database with $subsys:$sysname name */
1108 util_strscpyl(from, sizeof(from), udev_get_dev_path(udev),
1109 "/.udev/db/", udev_device_get_subsystem(device), ":",
1110 udev_device_get_sysname(device), NULL);
1111 if (lstat(from, &stats) == 0) {
1113 udev_device_read_db(device, from);
1119 /* find old database with the encoded devpath name */
1120 util_path_encode(udev_device_get_devpath(device), devpath, sizeof(devpath));
1121 util_strscpyl(from, sizeof(from), udev_get_dev_path(udev), "/.udev/db/", devpath, NULL);
1122 if (lstat(from, &stats) == 0) {
1124 udev_device_read_db(device, from);
1130 /* write out new database */
1132 udev_device_update_db(device);
1134 udev_device_unref(device);
1136 udev_enumerate_unref(udev_enumerate);
1140 static int systemd_fds(struct udev *udev, int *rctrl, int *rnetlink)
1142 int ctrl = -1, netlink = -1;
1145 n = sd_listen_fds(true);
1149 for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
1150 if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1)) {
1157 if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1)) {
1167 if (ctrl < 0 || netlink < 0)
1170 info(udev, "ctrl=%i netlink=%i\n", ctrl, netlink);
1172 *rnetlink = netlink;
1176 int main(int argc, char *argv[])
1181 int daemonize = false;
1182 int resolve_names = 1;
1183 static const struct option options[] = {
1184 { "daemon", no_argument, NULL, 'd' },
1185 { "debug", no_argument, NULL, 'D' },
1186 { "children-max", required_argument, NULL, 'c' },
1187 { "exec-delay", required_argument, NULL, 'e' },
1188 { "resolve-names", required_argument, NULL, 'N' },
1189 { "help", no_argument, NULL, 'h' },
1190 { "version", no_argument, NULL, 'V' },
1194 int fd_netlink = -1;
1196 struct epoll_event ep_ctrl, ep_inotify, ep_signal, ep_netlink, ep_worker;
1197 struct udev_ctrl_connection *ctrl_conn = NULL;
1204 udev_log_init("udevd");
1205 udev_set_log_fn(udev, log_fn);
1206 info(udev, "version %s\n", VERSION);
1207 udev_selinux_init(udev);
1209 /* make sure, that our runtime dir exists and is writable */
1210 if (utimensat(AT_FDCWD, udev_get_run_config_path(udev), NULL, 0) < 0) {
1211 /* try to create our own subdirectory, do not create parent directories */
1212 mkdir(udev_get_run_config_path(udev), 0755);
1214 if (utimensat(AT_FDCWD, udev_get_run_config_path(udev), NULL, 0) >= 0) {
1215 /* directory seems writable now */
1216 udev_set_run_path(udev, udev_get_run_config_path(udev));
1218 /* fall back to /dev/.udev */
1219 char filename[UTIL_PATH_SIZE];
1221 util_strscpyl(filename, sizeof(filename), udev_get_dev_path(udev), "/.udev", NULL);
1222 if (udev_set_run_path(udev, filename) == NULL)
1224 mkdir(udev_get_run_path(udev), 0755);
1225 err(udev, "error: runtime directory '%s' not writable, for now falling back to '%s'",
1226 udev_get_run_config_path(udev), udev_get_run_path(udev));
1229 /* relabel runtime dir only if it resides below /dev */
1230 if (strncmp(udev_get_run_path(udev), udev_get_dev_path(udev), strlen(udev_get_dev_path(udev))) == 0)
1231 udev_selinux_lsetfilecon(udev, udev_get_run_path(udev), 0755);
1232 info(udev, "runtime dir '%s'\n", udev_get_run_path(udev));
1237 option = getopt_long(argc, argv, "c:deDtN:hV", options, NULL);
1246 children_max = strtoul(optarg, NULL, 0);
1249 exec_delay = strtoul(optarg, NULL, 0);
1253 if (udev_get_log_priority(udev) < LOG_INFO)
1254 udev_set_log_priority(udev, LOG_INFO);
1257 if (strcmp (optarg, "early") == 0) {
1259 } else if (strcmp (optarg, "late") == 0) {
1261 } else if (strcmp (optarg, "never") == 0) {
1264 fprintf(stderr, "resolve-names must be early, late or never\n");
1265 err(udev, "resolve-names must be early, late or never\n");
1270 printf("Usage: udevd OPTIONS\n"
1273 " --children-max=<maximum number of workers>\n"
1274 " --exec-delay=<seconds to wait before executing RUN=>\n"
1275 " --resolve-names=early|late|never\n"
1281 printf("%s\n", VERSION);
1289 * read the kernel commandline, in case we need to get into debug mode
1290 * udev.log-priority=<level> syslog priority
1291 * udev.children-max=<number of workers> events are fully serialized if set to 1
1294 f = fopen("/proc/cmdline", "r");
1298 if (fgets(cmdline, sizeof(cmdline), f) != NULL) {
1301 pos = strstr(cmdline, "udev.log-priority=");
1303 pos += strlen("udev.log-priority=");
1304 udev_set_log_priority(udev, util_log_priority(pos));
1307 pos = strstr(cmdline, "udev.children-max=");
1309 pos += strlen("udev.children-max=");
1310 children_max = strtoul(pos, NULL, 0);
1313 pos = strstr(cmdline, "udev.exec-delay=");
1315 pos += strlen("udev.exec-delay=");
1316 exec_delay = strtoul(pos, NULL, 0);
1322 if (getuid() != 0) {
1323 fprintf(stderr, "root privileges required\n");
1324 err(udev, "root privileges required\n");
1328 /* set umask before creating any file/directory */
1332 /* create standard links, copy static nodes, create nodes from modules */
1333 static_dev_create(udev);
1334 static_dev_create_from_modules(udev);
1336 /* before opening new files, make sure std{in,out,err} fds are in a sane state */
1340 fd = open("/dev/null", O_RDWR);
1342 if (write(STDOUT_FILENO, 0, 0) < 0)
1343 dup2(fd, STDOUT_FILENO);
1344 if (write(STDERR_FILENO, 0, 0) < 0)
1345 dup2(fd, STDERR_FILENO);
1346 if (fd > STDERR_FILENO)
1349 fprintf(stderr, "cannot open /dev/null\n");
1350 err(udev, "cannot open /dev/null\n");
1354 if (systemd_fds(udev, &fd_ctrl, &fd_netlink) >= 0) {
1355 /* get control and netlink socket from from systemd */
1356 udev_ctrl = udev_ctrl_new_from_socket_fd(udev, UDEV_CTRL_SOCK_PATH, fd_ctrl);
1357 if (udev_ctrl == NULL) {
1358 err(udev, "error taking over udev control socket");
1363 monitor = udev_monitor_new_from_netlink_fd(udev, "kernel", fd_netlink);
1364 if (monitor == NULL) {
1365 err(udev, "error taking over netlink socket\n");
1370 /* open control and netlink socket */
1371 udev_ctrl = udev_ctrl_new_from_socket(udev, UDEV_CTRL_SOCK_PATH);
1372 if (udev_ctrl == NULL) {
1373 fprintf(stderr, "error initializing udev control socket");
1374 err(udev, "error initializing udev control socket");
1378 fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
1380 monitor = udev_monitor_new_from_netlink(udev, "kernel");
1381 if (monitor == NULL) {
1382 fprintf(stderr, "error initializing netlink socket\n");
1383 err(udev, "error initializing netlink socket\n");
1387 fd_netlink = udev_monitor_get_fd(monitor);
1390 if (udev_monitor_enable_receiving(monitor) < 0) {
1391 fprintf(stderr, "error binding netlink socket\n");
1392 err(udev, "error binding netlink socket\n");
1397 if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
1398 fprintf(stderr, "error binding udev control socket\n");
1399 err(udev, "error binding udev control socket\n");
1404 udev_monitor_set_receive_buffer_size(monitor, 128*1024*1024);
1415 err(udev, "fork of daemon failed: %m\n");
1425 fd = open("/proc/self/oom_score_adj", O_RDWR);
1427 /* Fallback to old interface */
1428 fd = open("/proc/self/oom_adj", O_RDWR);
1430 err(udev, "error disabling OOM: %m\n");
1432 /* OOM_DISABLE == -17 */
1433 write(fd, "-17", 3);
1437 write(fd, "-1000", 5);
1441 sd_notify(1, "READY=1");
1444 f = fopen("/dev/kmsg", "w");
1446 fprintf(f, "<30>udevd[%u]: starting version " VERSION "\n", getpid());
1453 fd = open("/dev/null", O_RDWR);
1455 dup2(fd, STDIN_FILENO);
1456 dup2(fd, STDOUT_FILENO);
1457 dup2(fd, STDERR_FILENO);
1462 fd_inotify = udev_watch_init(udev);
1463 if (fd_inotify < 0) {
1464 fprintf(stderr, "error initializing inotify\n");
1465 err(udev, "error initializing inotify\n");
1470 if (udev_get_rules_path(udev) != NULL) {
1471 inotify_add_watch(fd_inotify, udev_get_rules_path(udev),
1472 IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1474 char filename[UTIL_PATH_SIZE];
1475 struct stat statbuf;
1477 inotify_add_watch(fd_inotify, LIBEXECDIR "/rules.d",
1478 IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1479 inotify_add_watch(fd_inotify, SYSCONFDIR "/udev/rules.d",
1480 IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1482 /* watch dynamic rules directory */
1483 util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/rules.d", NULL);
1484 if (stat(filename, &statbuf) != 0) {
1485 util_create_path(udev, filename);
1486 mkdir(filename, 0755);
1488 inotify_add_watch(fd_inotify, filename,
1489 IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1491 udev_watch_restore(udev);
1493 /* block and listen to all signals on signalfd */
1495 sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
1496 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
1497 if (fd_signal < 0) {
1498 fprintf(stderr, "error creating signalfd\n");
1499 err(udev, "error creating signalfd\n");
1504 /* unnamed socket from workers to the main daemon */
1505 if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
1506 fprintf(stderr, "error creating socketpair\n");
1507 err(udev, "error creating socketpair\n");
1511 fd_worker = worker_watch[READ_END];
1513 rules = udev_rules_new(udev, resolve_names);
1514 if (rules == NULL) {
1515 err(udev, "error reading rules\n");
1519 udev_queue_export = udev_queue_export_new(udev);
1520 if (udev_queue_export == NULL) {
1521 err(udev, "error creating queue file\n");
1525 memset(&ep_ctrl, 0, sizeof(struct epoll_event));
1526 ep_ctrl.events = EPOLLIN;
1527 ep_ctrl.data.fd = fd_ctrl;
1529 memset(&ep_inotify, 0, sizeof(struct epoll_event));
1530 ep_inotify.events = EPOLLIN;
1531 ep_inotify.data.fd = fd_inotify;
1533 memset(&ep_signal, 0, sizeof(struct epoll_event));
1534 ep_signal.events = EPOLLIN;
1535 ep_signal.data.fd = fd_signal;
1537 memset(&ep_netlink, 0, sizeof(struct epoll_event));
1538 ep_netlink.events = EPOLLIN;
1539 ep_netlink.data.fd = fd_netlink;
1541 memset(&ep_worker, 0, sizeof(struct epoll_event));
1542 ep_worker.events = EPOLLIN;
1543 ep_worker.data.fd = fd_worker;
1545 fd_ep = epoll_create1(EPOLL_CLOEXEC);
1547 err(udev, "error creating epoll fd: %m\n");
1550 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_ctrl, &ep_ctrl) < 0 ||
1551 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_inotify, &ep_inotify) < 0 ||
1552 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
1553 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_netlink, &ep_netlink) < 0 ||
1554 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_worker, &ep_worker) < 0) {
1555 err(udev, "fail to add fds to epoll: %m\n");
1559 /* if needed, convert old database from earlier udev version */
1562 if (children_max <= 0) {
1563 int memsize = mem_size_mb();
1565 /* set value depending on the amount of RAM */
1567 children_max = 128 + (memsize / 8);
1571 info(udev, "set children_max to %u\n", children_max);
1573 udev_rules_apply_static_dev_perms(rules);
1575 udev_list_init(&event_list);
1576 udev_list_init(&worker_list);
1579 struct epoll_event ev[8];
1582 bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
1586 /* close sources of new events and discard buffered events */
1588 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
1591 if (monitor != NULL) {
1592 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
1593 udev_monitor_unref(monitor);
1596 if (fd_inotify >= 0) {
1597 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
1602 /* discard queued events and kill workers */
1603 event_queue_cleanup(udev, EVENT_QUEUED);
1604 worker_kill(udev, 0);
1606 /* exit after all has cleaned up */
1607 if (udev_list_is_empty(&event_list) && udev_list_is_empty(&worker_list))
1610 /* timeout at exit for workers to finish */
1611 timeout = 60 * 1000;
1612 } else if (udev_list_is_empty(&event_list) && children > 2) {
1613 /* set timeout to kill idle workers */
1618 fdcount = epoll_wait(fd_ep, ev, ARRAY_SIZE(ev), timeout);
1624 info(udev, "timeout, giving up waiting for workers to finish\n");
1628 /* timeout - kill idle workers */
1629 worker_kill(udev, 2);
1632 is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
1633 for (i = 0; i < fdcount; i++) {
1634 if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
1636 else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
1638 else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
1640 else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
1642 else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
1646 /* event has finished */
1648 worker_returned(fd_worker);
1651 struct udev_device *dev;
1653 dev = udev_monitor_receive_device(monitor);
1655 if (event_queue_insert(dev) < 0)
1656 udev_device_unref(dev);
1659 /* start new events */
1660 if (!udev_list_is_empty(&event_list) && !udev_exit && !stop_exec_queue)
1661 event_queue_start(udev);
1664 struct signalfd_siginfo fdsi;
1667 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
1668 if (size == sizeof(struct signalfd_siginfo))
1669 handle_signal(udev, fdsi.ssi_signo);
1672 /* we are shutting down, the events below are not handled anymore */
1676 /* device node and rules directory inotify watch */
1678 handle_inotify(udev);
1681 * This needs to be after the inotify handling, to make sure,
1682 * that the ping is send back after the possibly generated
1683 * "change" events by the inotify device node watch.
1685 * A single time we may receive a client connection which we need to
1686 * keep open to block the client. It will be closed right before we
1690 ctrl_conn = handle_ctrl_msg(udev_ctrl);
1692 /* rules changed, set by inotify or a HUP signal */
1693 if (reload_config) {
1694 struct udev_rules *rules_new;
1696 worker_kill(udev, 0);
1697 rules_new = udev_rules_new(udev, resolve_names);
1698 if (rules_new != NULL) {
1699 udev_rules_unref(rules);
1706 udev_queue_export_cleanup(udev_queue_export);
1711 worker_list_cleanup(udev);
1712 event_queue_cleanup(udev, EVENT_UNDEF);
1713 udev_rules_unref(rules);
1716 if (worker_watch[READ_END] >= 0)
1717 close(worker_watch[READ_END]);
1718 if (worker_watch[WRITE_END] >= 0)
1719 close(worker_watch[WRITE_END]);
1720 udev_monitor_unref(monitor);
1721 udev_queue_export_unref(udev_queue_export);
1722 udev_ctrl_connection_unref(ctrl_conn);
1723 udev_ctrl_unref(udev_ctrl);
1724 udev_selinux_exit(udev);