udevd.c revision 39c19cf13a5d32887977f06cb34e4c95e6da3f56
0N/A/*
0N/A * Copyright (C) 2004-2012 Kay Sievers <kay@vrfy.org>
0N/A * Copyright (C) 2004 Chris Friesen <chris_friesen@sympatico.ca>
0N/A * Copyright (C) 2009 Canonical Ltd.
0N/A * Copyright (C) 2009 Scott James Remnant <scott@netsplit.com>
0N/A *
0N/A * This program is free software: you can redistribute it and/or modify
0N/A * it under the terms of the GNU General Public License as published by
0N/A * the Free Software Foundation, either version 2 of the License, or
0N/A * (at your option) any later version.
0N/A *
0N/A * This program is distributed in the hope that it will be useful,
0N/A * but WITHOUT ANY WARRANTY; without even the implied warranty of
0N/A * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
0N/A * GNU General Public License for more details.
0N/A *
0N/A * You should have received a copy of the GNU General Public License
0N/A * along with this program. If not, see <http://www.gnu.org/licenses/>.
873N/A */
0N/A
0N/A#include <stddef.h>
0N/A#include <signal.h>
0N/A#include <unistd.h>
0N/A#include <errno.h>
868N/A#include <stdio.h>
0N/A#include <stdlib.h>
0N/A#include <stdbool.h>
0N/A#include <string.h>
0N/A#include <fcntl.h>
0N/A#include <getopt.h>
0N/A#include <sys/file.h>
0N/A#include <sys/time.h>
0N/A#include <sys/prctl.h>
0N/A#include <sys/socket.h>
0N/A#include <sys/signalfd.h>
0N/A#include <sys/epoll.h>
0N/A#include <sys/mount.h>
0N/A#include <sys/wait.h>
0N/A#include <sys/stat.h>
0N/A#include <sys/ioctl.h>
0N/A#include <sys/inotify.h>
0N/A
0N/A#include "sd-daemon.h"
0N/A#include "rtnl-util.h"
0N/A#include "cgroup-util.h"
868N/A#include "dev-setup.h"
0N/A#include "fileio.h"
0N/A#include "selinux-util.h"
879N/A#include "udev.h"
868N/A#include "udev-util.h"
0N/A#include "formats-util.h"
0N/A
0N/Astatic struct udev_rules *rules;
0N/Astatic struct udev_ctrl *udev_ctrl;
0N/Astatic struct udev_monitor *monitor;
0N/Astatic int worker_watch[2] = { -1, -1 };
0N/Astatic int fd_signal = -1;
0N/Astatic int fd_ep = -1;
0N/Astatic int fd_inotify = -1;
0N/Astatic bool stop_exec_queue;
0N/Astatic bool reload;
0N/Astatic int children;
0N/Astatic bool arg_debug = false;
0N/Astatic int arg_daemonize = false;
0N/Astatic int arg_resolve_names = 1;
0N/Astatic int arg_children_max;
0N/Astatic int arg_exec_delay;
0N/Astatic usec_t arg_event_timeout_usec = 180 * USEC_PER_SEC;
0N/Astatic usec_t arg_event_timeout_warn_usec = 180 * USEC_PER_SEC / 3;
0N/Astatic sigset_t sigmask_orig;
0N/Astatic UDEV_LIST(event_list);
0N/Astatic UDEV_LIST(worker_list);
0N/Astatic char *udev_cgroup;
0N/Astatic struct udev_list properties_list;
0N/Astatic bool udev_exit;
0N/A
0N/Aenum event_state {
0N/A EVENT_UNDEF,
0N/A EVENT_QUEUED,
0N/A EVENT_RUNNING,
0N/A};
0N/A
0N/Astruct event {
0N/A struct udev_list_node node;
0N/A struct udev *udev;
0N/A struct udev_device *dev;
0N/A struct udev_device *dev_kernel;
0N/A enum event_state state;
0N/A unsigned long long int delaying_seqnum;
0N/A unsigned long long int seqnum;
0N/A const char *devpath;
0N/A size_t devpath_len;
0N/A const char *devpath_old;
0N/A dev_t devnum;
0N/A int ifindex;
0N/A bool is_block;
0N/A};
0N/A
0N/Astatic inline struct event *node_to_event(struct udev_list_node *node) {
0N/A return container_of(node, struct event, node);
0N/A}
0N/A
0N/Astatic void event_queue_cleanup(struct udev *udev, enum event_state type);
0N/A
0N/Aenum worker_state {
0N/A WORKER_UNDEF,
0N/A WORKER_RUNNING,
0N/A WORKER_IDLE,
0N/A WORKER_KILLED,
0N/A};
0N/A
0N/Astruct worker {
0N/A struct udev_list_node node;
0N/A struct udev *udev;
0N/A int refcount;
0N/A pid_t pid;
0N/A struct udev_monitor *monitor;
0N/A enum worker_state state;
0N/A struct event *event;
0N/A usec_t event_start_usec;
0N/A bool event_warned;
0N/A};
0N/A
0N/A/* passed from worker to main process */
0N/Astruct worker_message {
0N/A};
0N/A
0N/Astatic inline struct worker *node_to_worker(struct udev_list_node *node) {
0N/A return container_of(node, struct worker, node);
0N/A}
0N/A
0N/Astatic void event_queue_delete(struct event *event) {
0N/A udev_list_node_remove(&event->node);
0N/A udev_device_unref(event->dev);
0N/A udev_device_unref(event->dev_kernel);
0N/A free(event);
0N/A}
0N/A
0N/Astatic struct worker *worker_ref(struct worker *worker) {
0N/A worker->refcount++;
0N/A return worker;
0N/A}
0N/A
0N/Astatic void worker_cleanup(struct worker *worker) {
0N/A udev_list_node_remove(&worker->node);
0N/A udev_monitor_unref(worker->monitor);
0N/A udev_unref(worker->udev);
0N/A children--;
0N/A free(worker);
0N/A}
0N/A
0N/Astatic void worker_unref(struct worker *worker) {
0N/A worker->refcount--;
0N/A if (worker->refcount > 0)
0N/A return;
0N/A log_debug("worker ["PID_FMT"] cleaned up", worker->pid);
0N/A worker_cleanup(worker);
0N/A}
0N/A
0N/Astatic void worker_list_cleanup(struct udev *udev) {
0N/A struct udev_list_node *loop, *tmp;
0N/A
0N/A udev_list_node_foreach_safe(loop, tmp, &worker_list) {
0N/A struct worker *worker = node_to_worker(loop);
0N/A
0N/A worker_cleanup(worker);
0N/A }
0N/A}
0N/A
0N/Astatic int worker_new(struct worker **ret, struct udev *udev, struct udev_monitor *worker_monitor, pid_t pid) {
0N/A struct worker *worker;
0N/A
0N/A assert(ret);
0N/A assert(udev);
0N/A assert(worker_monitor);
0N/A assert(pid > 1);
0N/A
0N/A worker = new0(struct worker, 1);
0N/A if (!worker)
0N/A return -ENOMEM;
0N/A
0N/A worker->refcount = 1;
0N/A worker->udev = udev_ref(udev);
0N/A /* close monitor, but keep address around */
0N/A udev_monitor_disconnect(worker_monitor);
0N/A worker->monitor = udev_monitor_ref(worker_monitor);
0N/A worker->pid = pid;
0N/A udev_list_node_append(&worker->node, &worker_list);
0N/A children++;
0N/A
0N/A *ret = worker;
0N/A
0N/A return 0;
0N/A}
0N/A
0N/Astatic void worker_attach_event(struct worker *worker, struct event *event) {
0N/A worker->state = WORKER_RUNNING;
0N/A worker->event_start_usec = now(CLOCK_MONOTONIC);
0N/A worker->event_warned = false;
0N/A worker->event = event;
0N/A event->state = EVENT_RUNNING;
0N/A worker_ref(worker);
0N/A}
0N/A
0N/Astatic void worker_spawn(struct event *event) {
0N/A struct udev *udev = event->udev;
0N/A _cleanup_udev_monitor_unref_ struct udev_monitor *worker_monitor = NULL;
0N/A pid_t pid;
0N/A
0N/A /* listen for new events */
0N/A worker_monitor = udev_monitor_new_from_netlink(udev, NULL);
0N/A if (worker_monitor == NULL)
0N/A return;
0N/A /* allow the main daemon netlink address to send devices to the worker */
0N/A udev_monitor_allow_unicast_sender(worker_monitor, monitor);
0N/A udev_monitor_enable_receiving(worker_monitor);
0N/A
0N/A pid = fork();
0N/A switch (pid) {
0N/A case 0: {
0N/A struct udev_device *dev = NULL;
0N/A int fd_monitor;
0N/A _cleanup_rtnl_unref_ sd_rtnl *rtnl = NULL;
0N/A struct epoll_event ep_signal, ep_monitor;
0N/A sigset_t mask;
0N/A int rc = EXIT_SUCCESS;
0N/A
0N/A /* take initial device from queue */
0N/A dev = event->dev;
0N/A event->dev = NULL;
0N/A
0N/A worker_list_cleanup(udev);
0N/A event_queue_cleanup(udev, EVENT_UNDEF);
0N/A udev_monitor_unref(monitor);
0N/A udev_ctrl_unref(udev_ctrl);
0N/A close(fd_signal);
0N/A close(fd_ep);
0N/A close(worker_watch[READ_END]);
0N/A
0N/A sigfillset(&mask);
0N/A fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
0N/A if (fd_signal < 0) {
0N/A log_error_errno(errno, "error creating signalfd %m");
0N/A rc = 2;
0N/A goto out;
0N/A }
0N/A
0N/A fd_ep = epoll_create1(EPOLL_CLOEXEC);
0N/A if (fd_ep < 0) {
0N/A log_error_errno(errno, "error creating epoll fd: %m");
0N/A rc = 3;
0N/A goto out;
0N/A }
0N/A
0N/A memzero(&ep_signal, sizeof(struct epoll_event));
0N/A ep_signal.events = EPOLLIN;
0N/A ep_signal.data.fd = fd_signal;
0N/A
0N/A fd_monitor = udev_monitor_get_fd(worker_monitor);
0N/A memzero(&ep_monitor, sizeof(struct epoll_event));
0N/A ep_monitor.events = EPOLLIN;
0N/A ep_monitor.data.fd = fd_monitor;
0N/A
0N/A if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
0N/A epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_monitor, &ep_monitor) < 0) {
0N/A log_error_errno(errno, "fail to add fds to epoll: %m");
0N/A rc = 4;
0N/A goto out;
0N/A }
0N/A
0N/A /* request TERM signal if parent exits */
0N/A prctl(PR_SET_PDEATHSIG, SIGTERM);
0N/A
0N/A /* reset OOM score, we only protect the main daemon */
0N/A write_string_file("/proc/self/oom_score_adj", "0");
0N/A
0N/A for (;;) {
0N/A struct udev_event *udev_event;
0N/A struct worker_message msg;
0N/A int fd_lock = -1, r;
0N/A
0N/A log_debug("seq %llu running", udev_device_get_seqnum(dev));
0N/A udev_event = udev_event_new(dev);
0N/A if (udev_event == NULL) {
0N/A rc = 5;
0N/A goto out;
0N/A }
0N/A
0N/A /* needed for SIGCHLD/SIGTERM in spawn() */
0N/A udev_event->fd_signal = fd_signal;
0N/A
0N/A if (arg_exec_delay > 0)
0N/A udev_event->exec_delay = arg_exec_delay;
0N/A
0N/A /*
0N/A * Take a shared lock on the device node; this establishes
0N/A * a concept of device "ownership" to serialize device
0N/A * access. External processes holding an exclusive lock will
0N/A * cause udev to skip the event handling; in the case udev
0N/A * acquired the lock, the external process can block until
0N/A * udev has finished its event handling.
0N/A */
0N/A if (!streq_ptr(udev_device_get_action(dev), "remove") &&
0N/A streq_ptr("block", udev_device_get_subsystem(dev)) &&
0N/A !startswith(udev_device_get_sysname(dev), "dm-") &&
0N/A !startswith(udev_device_get_sysname(dev), "md")) {
0N/A struct udev_device *d = dev;
0N/A
0N/A if (streq_ptr("partition", udev_device_get_devtype(d)))
0N/A d = udev_device_get_parent(d);
0N/A
0N/A if (d) {
0N/A fd_lock = open(udev_device_get_devnode(d), O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
0N/A if (fd_lock >= 0 && flock(fd_lock, LOCK_SH|LOCK_NB) < 0) {
0N/A log_debug_errno(errno, "Unable to flock(%s), skipping event handling: %m", udev_device_get_devnode(d));
0N/A fd_lock = safe_close(fd_lock);
0N/A goto skip;
0N/A }
0N/A }
0N/A }
0N/A
0N/A /* needed for renaming netifs */
0N/A udev_event->rtnl = rtnl;
0N/A
0N/A /* apply rules, create node, symlinks */
0N/A udev_event_execute_rules(udev_event,
0N/A arg_event_timeout_usec, arg_event_timeout_warn_usec,
0N/A &properties_list,
0N/A rules,
0N/A &sigmask_orig);
0N/A
0N/A udev_event_execute_run(udev_event,
0N/A arg_event_timeout_usec, arg_event_timeout_warn_usec,
0N/A &sigmask_orig);
0N/A
0N/A if (udev_event->rtnl)
0N/A /* in case rtnl was initialized */
0N/A rtnl = sd_rtnl_ref(udev_event->rtnl);
0N/A
0N/A /* apply/restore inotify watch */
0N/A if (udev_event->inotify_watch) {
0N/A udev_watch_begin(udev, dev);
0N/A udev_device_update_db(dev);
0N/A }
0N/A
0N/A safe_close(fd_lock);
0N/A
0N/A /* send processed event back to libudev listeners */
0N/A udev_monitor_send_device(worker_monitor, NULL, dev);
0N/A
0N/Askip:
0N/A log_debug("seq %llu processed", udev_device_get_seqnum(dev));
0N/A
0N/A /* send udevd the result of the event execution */
0N/A memzero(&msg, sizeof(struct worker_message));
0N/A r = send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
0N/A if (r < 0)
0N/A log_error_errno(errno, "failed to send result of seq %llu to main daemon: %m",
0N/A udev_device_get_seqnum(dev));
0N/A
0N/A udev_device_unref(dev);
0N/A dev = NULL;
0N/A
0N/A if (udev_event->sigterm) {
0N/A udev_event_unref(udev_event);
0N/A goto out;
0N/A }
0N/A
0N/A udev_event_unref(udev_event);
0N/A
0N/A /* wait for more device messages from main udevd, or term signal */
0N/A while (dev == NULL) {
0N/A struct epoll_event ev[4];
0N/A int fdcount;
0N/A int i;
0N/A
0N/A fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), -1);
0N/A if (fdcount < 0) {
0N/A if (errno == EINTR)
0N/A continue;
0N/A log_error_errno(errno, "failed to poll: %m");
0N/A goto out;
0N/A }
0N/A
0N/A for (i = 0; i < fdcount; i++) {
0N/A if (ev[i].data.fd == fd_monitor && ev[i].events & EPOLLIN) {
0N/A dev = udev_monitor_receive_device(worker_monitor);
0N/A break;
0N/A } else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN) {
0N/A struct signalfd_siginfo fdsi;
0N/A ssize_t size;
0N/A
0N/A size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
0N/A if (size != sizeof(struct signalfd_siginfo))
0N/A continue;
0N/A switch (fdsi.ssi_signo) {
0N/A case SIGTERM:
0N/A goto out;
0N/A }
0N/A }
0N/A }
0N/A }
0N/A }
0N/Aout:
0N/A udev_device_unref(dev);
0N/A safe_close(fd_signal);
0N/A safe_close(fd_ep);
0N/A close(fd_inotify);
0N/A close(worker_watch[WRITE_END]);
0N/A udev_rules_unref(rules);
0N/A udev_builtin_exit(udev);
0N/A udev_unref(udev);
0N/A log_close();
0N/A exit(rc);
0N/A }
0N/A case -1:
0N/A event->state = EVENT_QUEUED;
0N/A log_error_errno(errno, "fork of child failed: %m");
0N/A break;
0N/A default:
0N/A {
0N/A struct worker *worker;
0N/A int r;
0N/A
0N/A r = worker_new(&worker, udev, worker_monitor, pid);
0N/A if (r < 0)
0N/A return;
0N/A
0N/A worker_attach_event(worker, event);
0N/A
0N/A log_debug("seq %llu forked new worker ["PID_FMT"]", udev_device_get_seqnum(event->dev), pid);
0N/A break;
0N/A }
0N/A }
0N/A}
0N/A
0N/Astatic void event_run(struct event *event) {
0N/A struct udev_list_node *loop;
0N/A
0N/A udev_list_node_foreach(loop, &worker_list) {
0N/A struct worker *worker = node_to_worker(loop);
0N/A ssize_t count;
0N/A
0N/A if (worker->state != WORKER_IDLE)
0N/A continue;
0N/A
0N/A count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
0N/A if (count < 0) {
0N/A log_error_errno(errno, "worker ["PID_FMT"] did not accept message %zi (%m), kill it",
0N/A worker->pid, count);
0N/A kill(worker->pid, SIGKILL);
0N/A worker->state = WORKER_KILLED;
0N/A continue;
0N/A }
0N/A worker_attach_event(worker, event);
0N/A return;
0N/A }
0N/A
0N/A if (children >= arg_children_max) {
0N/A if (arg_children_max > 1)
0N/A log_debug("maximum number (%i) of children reached", children);
0N/A return;
0N/A }
0N/A
0N/A /* start new worker and pass initial device */
0N/A worker_spawn(event);
0N/A}
0N/A
0N/Astatic int event_queue_insert(struct udev_device *dev) {
0N/A struct event *event;
0N/A
0N/A event = new0(struct event, 1);
0N/A if (event == NULL)
0N/A return -1;
0N/A
0N/A event->udev = udev_device_get_udev(dev);
0N/A event->dev = dev;
0N/A event->dev_kernel = udev_device_shallow_clone(dev);
0N/A udev_device_copy_properties(event->dev_kernel, dev);
0N/A event->seqnum = udev_device_get_seqnum(dev);
0N/A event->devpath = udev_device_get_devpath(dev);
0N/A event->devpath_len = strlen(event->devpath);
0N/A event->devpath_old = udev_device_get_devpath_old(dev);
0N/A event->devnum = udev_device_get_devnum(dev);
0N/A event->is_block = streq("block", udev_device_get_subsystem(dev));
0N/A event->ifindex = udev_device_get_ifindex(dev);
0N/A
0N/A log_debug("seq %llu queued, '%s' '%s'", udev_device_get_seqnum(dev),
0N/A udev_device_get_action(dev), udev_device_get_subsystem(dev));
0N/A
0N/A event->state = EVENT_QUEUED;
0N/A udev_list_node_append(&event->node, &event_list);
0N/A return 0;
0N/A}
0N/A
0N/Astatic void worker_kill(struct udev *udev) {
0N/A struct udev_list_node *loop;
0N/A
0N/A udev_list_node_foreach(loop, &worker_list) {
0N/A struct worker *worker = node_to_worker(loop);
0N/A
0N/A if (worker->state == WORKER_KILLED)
0N/A continue;
0N/A
0N/A worker->state = WORKER_KILLED;
0N/A kill(worker->pid, SIGTERM);
0N/A }
0N/A}
0N/A
0N/A/* lookup event for identical, parent, child device */
0N/Astatic bool is_devpath_busy(struct event *event) {
0N/A struct udev_list_node *loop;
0N/A size_t common;
0N/A
0N/A /* check if queue contains events we depend on */
0N/A udev_list_node_foreach(loop, &event_list) {
0N/A struct event *loop_event = node_to_event(loop);
0N/A
0N/A /* we already found a later event, earlier can not block us, no need to check again */
0N/A if (loop_event->seqnum < event->delaying_seqnum)
0N/A continue;
0N/A
0N/A /* event we checked earlier still exists, no need to check again */
0N/A if (loop_event->seqnum == event->delaying_seqnum)
0N/A return true;
0N/A
0N/A /* found ourself, no later event can block us */
0N/A if (loop_event->seqnum >= event->seqnum)
0N/A break;
0N/A
0N/A /* check major/minor */
0N/A if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
0N/A return true;
0N/A
0N/A /* check network device ifindex */
0N/A if (event->ifindex != 0 && event->ifindex == loop_event->ifindex)
0N/A return true;
0N/A
0N/A /* check our old name */
0N/A if (event->devpath_old != NULL && streq(loop_event->devpath, event->devpath_old)) {
0N/A event->delaying_seqnum = loop_event->seqnum;
0N/A return true;
0N/A }
0N/A
0N/A /* compare devpath */
0N/A common = MIN(loop_event->devpath_len, event->devpath_len);
0N/A
0N/A /* one devpath is contained in the other? */
0N/A if (memcmp(loop_event->devpath, event->devpath, common) != 0)
0N/A continue;
0N/A
0N/A /* identical device event found */
0N/A if (loop_event->devpath_len == event->devpath_len) {
0N/A /* devices names might have changed/swapped in the meantime */
0N/A if (major(event->devnum) != 0 && (event->devnum != loop_event->devnum || event->is_block != loop_event->is_block))
0N/A continue;
0N/A if (event->ifindex != 0 && event->ifindex != loop_event->ifindex)
0N/A continue;
0N/A event->delaying_seqnum = loop_event->seqnum;
0N/A return true;
0N/A }
0N/A
0N/A /* parent device event found */
0N/A if (event->devpath[common] == '/') {
0N/A event->delaying_seqnum = loop_event->seqnum;
0N/A return true;
0N/A }
0N/A
0N/A /* child device event found */
0N/A if (loop_event->devpath[common] == '/') {
0N/A event->delaying_seqnum = loop_event->seqnum;
0N/A return true;
0N/A }
0N/A
0N/A /* no matching device */
0N/A continue;
0N/A }
0N/A
0N/A return false;
0N/A}
0N/A
0N/Astatic void event_queue_start(struct udev *udev) {
0N/A struct udev_list_node *loop;
0N/A
0N/A udev_list_node_foreach(loop, &event_list) {
0N/A struct event *event = node_to_event(loop);
0N/A
0N/A if (event->state != EVENT_QUEUED)
0N/A continue;
0N/A
0N/A /* do not start event if parent or child event is still running */
0N/A if (is_devpath_busy(event))
0N/A continue;
0N/A
0N/A event_run(event);
0N/A }
0N/A}
0N/A
0N/Astatic void event_queue_cleanup(struct udev *udev, enum event_state match_type) {
0N/A struct udev_list_node *loop, *tmp;
0N/A
0N/A udev_list_node_foreach_safe(loop, tmp, &event_list) {
0N/A struct event *event = node_to_event(loop);
0N/A
0N/A if (match_type != EVENT_UNDEF && match_type != event->state)
0N/A continue;
0N/A
0N/A event_queue_delete(event);
0N/A }
0N/A}
0N/A
0N/Astatic void worker_returned(int fd_worker) {
0N/A for (;;) {
0N/A struct worker_message msg;
0N/A struct iovec iovec = {
0N/A .iov_base = &msg,
0N/A .iov_len = sizeof(msg),
0N/A };
0N/A union {
0N/A struct cmsghdr cmsghdr;
0N/A uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
0N/A } control = {};
0N/A struct msghdr msghdr = {
0N/A .msg_iov = &iovec,
0N/A .msg_iovlen = 1,
0N/A .msg_control = &control,
0N/A .msg_controllen = sizeof(control),
0N/A };
0N/A struct cmsghdr *cmsg;
0N/A ssize_t size;
0N/A struct ucred *ucred = NULL;
0N/A struct udev_list_node *loop;
0N/A bool found = false;
0N/A
0N/A size = recvmsg(fd_worker, &msghdr, MSG_DONTWAIT);
0N/A if (size < 0) {
0N/A if (errno == EAGAIN || errno == EINTR)
0N/A return;
0N/A
0N/A log_error_errno(errno, "failed to receive message: %m");
0N/A return;
0N/A } else if (size != sizeof(struct worker_message)) {
0N/A log_warning_errno(EIO, "ignoring worker message with invalid size %zi bytes", size);
0N/A return;
0N/A }
0N/A
0N/A for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
0N/A if (cmsg->cmsg_level == SOL_SOCKET &&
0N/A cmsg->cmsg_type == SCM_CREDENTIALS &&
0N/A cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
0N/A ucred = (struct ucred*) CMSG_DATA(cmsg);
0N/A }
0N/A
0N/A if (!ucred || ucred->pid <= 0) {
0N/A log_warning_errno(EIO, "ignoring worker message without valid PID");
0N/A continue;
0N/A }
0N/A
0N/A /* lookup worker who sent the signal */
0N/A udev_list_node_foreach(loop, &worker_list) {
0N/A struct worker *worker = node_to_worker(loop);
0N/A
0N/A if (worker->pid != ucred->pid)
0N/A continue;
0N/A else
0N/A found = true;
0N/A
0N/A /* worker returned */
0N/A if (worker->event) {
0N/A event_queue_delete(worker->event);
0N/A worker->event = NULL;
0N/A }
0N/A if (worker->state != WORKER_KILLED)
0N/A worker->state = WORKER_IDLE;
0N/A worker_unref(worker);
0N/A break;
0N/A }
0N/A
0N/A if (!found)
0N/A log_warning("unknown worker ["PID_FMT"] returned", ucred->pid);
0N/A }
0N/A}
0N/A
0N/A/* receive the udevd message from userspace */
0N/Astatic struct udev_ctrl_connection *handle_ctrl_msg(struct udev_ctrl *uctrl) {
0N/A struct udev *udev = udev_ctrl_get_udev(uctrl);
0N/A struct udev_ctrl_connection *ctrl_conn;
0N/A struct udev_ctrl_msg *ctrl_msg = NULL;
0N/A const char *str;
0N/A int i;
0N/A
0N/A ctrl_conn = udev_ctrl_get_connection(uctrl);
0N/A if (ctrl_conn == NULL)
0N/A goto out;
0N/A
0N/A ctrl_msg = udev_ctrl_receive_msg(ctrl_conn);
0N/A if (ctrl_msg == NULL)
0N/A goto out;
0N/A
0N/A i = udev_ctrl_get_set_log_level(ctrl_msg);
0N/A if (i >= 0) {
0N/A log_debug("udevd message (SET_LOG_LEVEL) received, log_priority=%i", i);
0N/A log_set_max_level(i);
0N/A worker_kill(udev);
0N/A }
0N/A
0N/A if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
0N/A log_debug("udevd message (STOP_EXEC_QUEUE) received");
0N/A stop_exec_queue = true;
0N/A }
0N/A
0N/A if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
0N/A log_debug("udevd message (START_EXEC_QUEUE) received");
0N/A stop_exec_queue = false;
0N/A }
0N/A
0N/A if (udev_ctrl_get_reload(ctrl_msg) > 0) {
0N/A log_debug("udevd message (RELOAD) received");
0N/A reload = true;
0N/A }
0N/A
0N/A str = udev_ctrl_get_set_env(ctrl_msg);
0N/A if (str != NULL) {
0N/A char *key;
0N/A
0N/A key = strdup(str);
0N/A if (key != NULL) {
0N/A char *val;
0N/A
0N/A val = strchr(key, '=');
0N/A if (val != NULL) {
0N/A val[0] = '\0';
0N/A val = &val[1];
0N/A if (val[0] == '\0') {
0N/A log_debug("udevd message (ENV) received, unset '%s'", key);
0N/A udev_list_entry_add(&properties_list, key, NULL);
0N/A } else {
0N/A log_debug("udevd message (ENV) received, set '%s=%s'", key, val);
0N/A udev_list_entry_add(&properties_list, key, val);
0N/A }
0N/A } else {
0N/A log_error("wrong key format '%s'", key);
0N/A }
0N/A free(key);
0N/A }
0N/A worker_kill(udev);
0N/A }
0N/A
0N/A i = udev_ctrl_get_set_children_max(ctrl_msg);
0N/A if (i >= 0) {
0N/A log_debug("udevd message (SET_MAX_CHILDREN) received, children_max=%i", i);
0N/A arg_children_max = i;
0N/A }
0N/A
0N/A if (udev_ctrl_get_ping(ctrl_msg) > 0)
0N/A log_debug("udevd message (SYNC) received");
0N/A
0N/A if (udev_ctrl_get_exit(ctrl_msg) > 0) {
0N/A log_debug("udevd message (EXIT) received");
0N/A udev_exit = true;
0N/A /* keep reference to block the client until we exit */
0N/A udev_ctrl_connection_ref(ctrl_conn);
0N/A }
0N/Aout:
0N/A udev_ctrl_msg_unref(ctrl_msg);
0N/A return udev_ctrl_connection_unref(ctrl_conn);
0N/A}
0N/A
0N/Astatic int synthesize_change(struct udev_device *dev) {
0N/A char filename[UTIL_PATH_SIZE];
0N/A int r;
0N/A
0N/A if (streq_ptr("block", udev_device_get_subsystem(dev)) &&
0N/A streq_ptr("disk", udev_device_get_devtype(dev)) &&
0N/A !startswith(udev_device_get_sysname(dev), "dm-")) {
0N/A bool part_table_read = false;
0N/A bool has_partitions = false;
0N/A int fd;
0N/A struct udev *udev = udev_device_get_udev(dev);
0N/A _cleanup_udev_enumerate_unref_ struct udev_enumerate *e = NULL;
0N/A struct udev_list_entry *item;
0N/A
0N/A /*
0N/A * Try to re-read the partition table. This only succeeds if
0N/A * none of the devices is busy. The kernel returns 0 if no
0N/A * partition table is found, and we will not get an event for
0N/A * the disk.
0N/A */
0N/A fd = open(udev_device_get_devnode(dev), O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
0N/A if (fd >= 0) {
0N/A r = flock(fd, LOCK_EX|LOCK_NB);
0N/A if (r >= 0)
0N/A r = ioctl(fd, BLKRRPART, 0);
0N/A
0N/A close(fd);
0N/A if (r >= 0)
0N/A part_table_read = true;
0N/A }
0N/A
0N/A /* search for partitions */
0N/A e = udev_enumerate_new(udev);
0N/A if (!e)
0N/A return -ENOMEM;
0N/A
0N/A r = udev_enumerate_add_match_parent(e, dev);
0N/A if (r < 0)
0N/A return r;
0N/A
0N/A r = udev_enumerate_add_match_subsystem(e, "block");
0N/A if (r < 0)
0N/A return r;
0N/A
0N/A r = udev_enumerate_scan_devices(e);
0N/A if (r < 0)
0N/A return r;
0N/A
0N/A udev_list_entry_foreach(item, udev_enumerate_get_list_entry(e)) {
0N/A _cleanup_udev_device_unref_ struct udev_device *d = NULL;
0N/A
0N/A d = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item));
0N/A if (!d)
0N/A continue;
0N/A
0N/A if (!streq_ptr("partition", udev_device_get_devtype(d)))
0N/A continue;
0N/A
0N/A has_partitions = true;
0N/A break;
0N/A }
0N/A
0N/A /*
0N/A * We have partitions and re-read the table, the kernel already sent
0N/A * out a "change" event for the disk, and "remove/add" for all
0N/A * partitions.
0N/A */
0N/A if (part_table_read && has_partitions)
0N/A return 0;
0N/A
0N/A /*
0N/A * We have partitions but re-reading the partition table did not
0N/A * work, synthesize "change" for the disk and all partitions.
0N/A */
0N/A log_debug("device %s closed, synthesising 'change'", udev_device_get_devnode(dev));
0N/A strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
0N/A write_string_file(filename, "change");
0N/A
0N/A udev_list_entry_foreach(item, udev_enumerate_get_list_entry(e)) {
0N/A _cleanup_udev_device_unref_ struct udev_device *d = NULL;
0N/A
0N/A d = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item));
0N/A if (!d)
0N/A continue;
0N/A
0N/A if (!streq_ptr("partition", udev_device_get_devtype(d)))
0N/A continue;
0N/A
0N/A log_debug("device %s closed, synthesising partition '%s' 'change'",
0N/A udev_device_get_devnode(dev), udev_device_get_devnode(d));
0N/A strscpyl(filename, sizeof(filename), udev_device_get_syspath(d), "/uevent", NULL);
0N/A write_string_file(filename, "change");
0N/A }
0N/A
0N/A return 0;
0N/A }
0N/A
0N/A log_debug("device %s closed, synthesising 'change'", udev_device_get_devnode(dev));
0N/A strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
0N/A write_string_file(filename, "change");
0N/A
0N/A return 0;
0N/A}
0N/A
0N/Astatic int handle_inotify(struct udev *udev) {
0N/A union inotify_event_buffer buffer;
0N/A struct inotify_event *e;
0N/A ssize_t l;
0N/A
0N/A l = read(fd_inotify, &buffer, sizeof(buffer));
0N/A if (l < 0) {
0N/A if (errno == EAGAIN || errno == EINTR)
0N/A return 0;
0N/A
0N/A return log_error_errno(errno, "Failed to read inotify fd: %m");
0N/A }
0N/A
0N/A FOREACH_INOTIFY_EVENT(e, buffer, l) {
0N/A struct udev_device *dev;
0N/A
0N/A dev = udev_watch_lookup(udev, e->wd);
0N/A if (!dev)
0N/A continue;
0N/A
0N/A log_debug("inotify event: %x for %s", e->mask, udev_device_get_devnode(dev));
0N/A if (e->mask & IN_CLOSE_WRITE)
0N/A synthesize_change(dev);
0N/A else if (e->mask & IN_IGNORED)
0N/A udev_watch_end(udev, dev);
0N/A
0N/A udev_device_unref(dev);
0N/A }
0N/A
0N/A return 0;
0N/A}
0N/A
0N/Astatic void handle_signal(struct udev *udev, int signo) {
0N/A switch (signo) {
0N/A case SIGINT:
0N/A case SIGTERM:
0N/A udev_exit = true;
0N/A break;
0N/A case SIGCHLD:
0N/A for (;;) {
0N/A pid_t pid;
0N/A int status;
0N/A struct udev_list_node *loop, *tmp;
0N/A bool found = false;
0N/A
0N/A pid = waitpid(-1, &status, WNOHANG);
0N/A if (pid <= 0)
0N/A break;
0N/A
0N/A udev_list_node_foreach_safe(loop, tmp, &worker_list) {
0N/A struct worker *worker = node_to_worker(loop);
0N/A
0N/A if (worker->pid != pid)
0N/A continue;
0N/A else
0N/A found = true;
0N/A
0N/A if (WIFEXITED(status)) {
0N/A if (WEXITSTATUS(status) == 0)
0N/A log_debug("worker ["PID_FMT"] exited", pid);
0N/A else
0N/A log_warning("worker ["PID_FMT"] exited with return code %i", pid, WEXITSTATUS(status));
0N/A } else if (WIFSIGNALED(status)) {
0N/A log_warning("worker ["PID_FMT"] terminated by signal %i (%s)",
0N/A pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
0N/A } else if (WIFSTOPPED(status)) {
0N/A log_info("worker ["PID_FMT"] stopped", pid);
0N/A break;
0N/A } else if (WIFCONTINUED(status)) {
0N/A log_info("worker ["PID_FMT"] continued", pid);
0N/A break;
0N/A } else {
0N/A log_warning("worker ["PID_FMT"] exit with status 0x%04x", pid, status);
0N/A }
0N/A
0N/A if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
0N/A if (worker->event) {
0N/A log_error("worker ["PID_FMT"] failed while handling '%s'",
0N/A pid, worker->event->devpath);
0N/A /* delete state from disk */
0N/A udev_device_delete_db(worker->event->dev);
0N/A udev_device_tag_index(worker->event->dev, NULL, false);
0N/A /* forward kernel event without amending it */
0N/A udev_monitor_send_device(monitor, NULL, worker->event->dev_kernel);
0N/A event_queue_delete(worker->event);
0N/A
0N/A /* drop reference taken for state 'running' */
0N/A worker_unref(worker);
0N/A }
0N/A }
0N/A worker_unref(worker);
0N/A break;
0N/A }
0N/A
0N/A if (!found)
0N/A log_warning("worker ["PID_FMT"] is unknown, ignoring", pid);
0N/A }
0N/A break;
0N/A case SIGHUP:
0N/A reload = true;
0N/A break;
0N/A }
0N/A}
0N/A
0N/Astatic void event_queue_update(void) {
0N/A int r;
0N/A
0N/A if (!udev_list_node_is_empty(&event_list)) {
0N/A r = touch("/run/udev/queue");
0N/A if (r < 0)
0N/A log_warning_errno(r, "could not touch /run/udev/queue: %m");
0N/A } else {
0N/A r = unlink("/run/udev/queue");
0N/A if (r < 0 && errno != ENOENT)
0N/A log_warning("could not unlink /run/udev/queue: %m");
0N/A }
0N/A}
0N/A
0N/Astatic int systemd_fds(struct udev *udev, int *rctrl, int *rnetlink) {
0N/A int ctrl = -1, netlink = -1;
0N/A int fd, n;
0N/A
0N/A n = sd_listen_fds(true);
0N/A if (n <= 0)
0N/A return -1;
0N/A
0N/A for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
0N/A if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1)) {
0N/A if (ctrl >= 0)
0N/A return -1;
0N/A ctrl = fd;
0N/A continue;
0N/A }
0N/A
0N/A if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1)) {
0N/A if (netlink >= 0)
0N/A return -1;
0N/A netlink = fd;
0N/A continue;
0N/A }
0N/A
0N/A return -1;
0N/A }
0N/A
0N/A if (ctrl < 0 || netlink < 0)
0N/A return -1;
0N/A
0N/A log_debug("ctrl=%i netlink=%i", ctrl, netlink);
0N/A *rctrl = ctrl;
0N/A *rnetlink = netlink;
0N/A return 0;
0N/A}
0N/A
0N/A/*
0N/A * read the kernel command line, in case we need to get into debug mode
0N/A * udev.log-priority=<level> syslog priority
0N/A * udev.children-max=<number of workers> events are fully serialized if set to 1
0N/A * udev.exec-delay=<number of seconds> delay execution of every executed program
0N/A */
0N/Astatic void kernel_cmdline_options(struct udev *udev) {
0N/A _cleanup_free_ char *line = NULL;
0N/A const char *word, *state;
0N/A size_t l;
0N/A int r;
0N/A
0N/A r = proc_cmdline(&line);
0N/A if (r < 0) {
0N/A log_warning_errno(r, "Failed to read /proc/cmdline, ignoring: %m");
0N/A return;
0N/A }
0N/A
0N/A FOREACH_WORD_QUOTED(word, l, line, state) {
0N/A char *s, *opt, *value;
0N/A
0N/A s = strndup(word, l);
0N/A if (!s)
0N/A break;
0N/A
0N/A /* accept the same options for the initrd, prefixed with "rd." */
0N/A if (in_initrd() && startswith(s, "rd."))
0N/A opt = s + 3;
0N/A else
0N/A opt = s;
0N/A
0N/A if ((value = startswith(opt, "udev.log-priority="))) {
0N/A int prio;
0N/A
0N/A prio = util_log_priority(value);
0N/A log_set_max_level(prio);
0N/A } else if ((value = startswith(opt, "udev.children-max="))) {
0N/A r = safe_atoi(value, &arg_children_max);
0N/A if (r < 0)
0N/A log_warning("Invalid udev.children-max ignored: %s", value);
0N/A } else if ((value = startswith(opt, "udev.exec-delay="))) {
0N/A r = safe_atoi(value, &arg_exec_delay);
0N/A if (r < 0)
0N/A log_warning("Invalid udev.exec-delay ignored: %s", value);
0N/A } else if ((value = startswith(opt, "udev.event-timeout="))) {
0N/A r = safe_atou64(value, &arg_event_timeout_usec);
0N/A if (r < 0) {
0N/A log_warning("Invalid udev.event-timeout ignored: %s", value);
0N/A break;
0N/A }
0N/A arg_event_timeout_usec *= USEC_PER_SEC;
0N/A arg_event_timeout_warn_usec = (arg_event_timeout_usec / 3) ? : 1;
0N/A }
0N/A
0N/A free(s);
0N/A }
0N/A}
0N/A
0N/Astatic void help(void) {
0N/A printf("%s [OPTIONS...]\n\n"
0N/A "Manages devices.\n\n"
0N/A " -h --help Print this message\n"
0N/A " --version Print version of the program\n"
0N/A " --daemon Detach and run in the background\n"
0N/A " --debug Enable debug output\n"
0N/A " --children-max=INT Set maximum number of workers\n"
0N/A " --exec-delay=SECONDS Seconds to wait before executing RUN=\n"
0N/A " --event-timeout=SECONDS Seconds to wait before terminating an event\n"
0N/A " --resolve-names=early|late|never\n"
0N/A " When to resolve users and groups\n"
0N/A , program_invocation_short_name);
0N/A}
0N/A
0N/Astatic int parse_argv(int argc, char *argv[]) {
0N/A static const struct option options[] = {
0N/A { "daemon", no_argument, NULL, 'd' },
0N/A { "debug", no_argument, NULL, 'D' },
0N/A { "children-max", required_argument, NULL, 'c' },
0N/A { "exec-delay", required_argument, NULL, 'e' },
0N/A { "event-timeout", required_argument, NULL, 't' },
0N/A { "resolve-names", required_argument, NULL, 'N' },
0N/A { "help", no_argument, NULL, 'h' },
0N/A { "version", no_argument, NULL, 'V' },
0N/A {}
0N/A };
0N/A
0N/A int c;
0N/A
0N/A assert(argc >= 0);
0N/A assert(argv);
0N/A
0N/A while ((c = getopt_long(argc, argv, "c:de:DtN:hV", options, NULL)) >= 0) {
868N/A int r;
868N/A
879N/A switch (c) {
868N/A
0N/A case 'd':
0N/A arg_daemonize = true;
0N/A break;
0N/A case 'c':
0N/A r = safe_atoi(optarg, &arg_children_max);
868N/A if (r < 0)
868N/A log_warning("Invalid --children-max ignored: %s", optarg);
879N/A break;
868N/A case 'e':
0N/A r = safe_atoi(optarg, &arg_exec_delay);
0N/A if (r < 0)
0N/A log_warning("Invalid --exec-delay ignored: %s", optarg);
0N/A break;
0N/A case 't':
0N/A r = safe_atou64(optarg, &arg_event_timeout_usec);
0N/A if (r < 0)
0N/A log_warning("Invalid --event-timeout ignored: %s", optarg);
0N/A else {
0N/A arg_event_timeout_usec *= USEC_PER_SEC;
0N/A arg_event_timeout_warn_usec = (arg_event_timeout_usec / 3) ? : 1;
0N/A }
0N/A break;
0N/A case 'D':
0N/A arg_debug = true;
0N/A break;
0N/A case 'N':
0N/A if (streq(optarg, "early")) {
0N/A arg_resolve_names = 1;
0N/A } else if (streq(optarg, "late")) {
0N/A arg_resolve_names = 0;
0N/A } else if (streq(optarg, "never")) {
0N/A arg_resolve_names = -1;
0N/A } else {
0N/A log_error("resolve-names must be early, late or never");
0N/A return 0;
0N/A }
0N/A break;
0N/A case 'h':
0N/A help();
0N/A return 0;
0N/A case 'V':
0N/A printf("%s\n", VERSION);
0N/A return 0;
0N/A case '?':
0N/A return -EINVAL;
0N/A default:
0N/A assert_not_reached("Unhandled option");
}
}
return 1;
}
int main(int argc, char *argv[]) {
struct udev *udev;
sigset_t mask;
int fd_ctrl = -1;
int fd_netlink = -1;
int fd_worker = -1;
struct epoll_event ep_ctrl = { .events = EPOLLIN };
struct epoll_event ep_inotify = { .events = EPOLLIN };
struct epoll_event ep_signal = { .events = EPOLLIN };
struct epoll_event ep_netlink = { .events = EPOLLIN };
struct epoll_event ep_worker = { .events = EPOLLIN };
struct udev_ctrl_connection *ctrl_conn = NULL;
int rc = 1, r, one = 1;
udev = udev_new();
if (udev == NULL)
goto exit;
log_set_target(LOG_TARGET_AUTO);
log_parse_environment();
log_open();
r = parse_argv(argc, argv);
if (r <= 0)
goto exit;
kernel_cmdline_options(udev);
if (arg_debug)
log_set_max_level(LOG_DEBUG);
if (getuid() != 0) {
log_error("root privileges required");
goto exit;
}
r = mac_selinux_init("/dev");
if (r < 0) {
log_error_errno(r, "could not initialize labelling: %m");
goto exit;
}
/* set umask before creating any file/directory */
r = chdir("/");
if (r < 0) {
log_error_errno(errno, "could not change dir to /: %m");
goto exit;
}
umask(022);
udev_list_init(udev, &properties_list, true);
r = mkdir("/run/udev", 0755);
if (r < 0 && errno != EEXIST) {
log_error_errno(errno, "could not create /run/udev: %m");
goto exit;
}
dev_setup(NULL);
/* before opening new files, make sure std{in,out,err} fds are in a sane state */
if (arg_daemonize) {
int fd;
fd = open("/dev/null", O_RDWR);
if (fd >= 0) {
if (write(STDOUT_FILENO, 0, 0) < 0)
dup2(fd, STDOUT_FILENO);
if (write(STDERR_FILENO, 0, 0) < 0)
dup2(fd, STDERR_FILENO);
if (fd > STDERR_FILENO)
close(fd);
} else {
log_error("cannot open /dev/null");
}
}
if (systemd_fds(udev, &fd_ctrl, &fd_netlink) >= 0) {
/* get control and netlink socket from systemd */
udev_ctrl = udev_ctrl_new_from_fd(udev, fd_ctrl);
if (udev_ctrl == NULL) {
log_error("error taking over udev control socket");
rc = 1;
goto exit;
}
monitor = udev_monitor_new_from_netlink_fd(udev, "kernel", fd_netlink);
if (monitor == NULL) {
log_error("error taking over netlink socket");
rc = 3;
goto exit;
}
/* get our own cgroup, we regularly kill everything udev has left behind */
if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &udev_cgroup) < 0)
udev_cgroup = NULL;
} else {
/* open control and netlink socket */
udev_ctrl = udev_ctrl_new(udev);
if (udev_ctrl == NULL) {
log_error("error initializing udev control socket");
rc = 1;
goto exit;
}
fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
monitor = udev_monitor_new_from_netlink(udev, "kernel");
if (monitor == NULL) {
log_error("error initializing netlink socket");
rc = 3;
goto exit;
}
fd_netlink = udev_monitor_get_fd(monitor);
udev_monitor_set_receive_buffer_size(monitor, 128 * 1024 * 1024);
}
if (udev_monitor_enable_receiving(monitor) < 0) {
log_error("error binding netlink socket");
rc = 3;
goto exit;
}
if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
log_error("error binding udev control socket");
rc = 1;
goto exit;
}
log_info("starting version " VERSION);
udev_builtin_init(udev);
rules = udev_rules_new(udev, arg_resolve_names);
if (rules == NULL) {
log_error("error reading rules");
goto exit;
}
rc = udev_rules_apply_static_dev_perms(rules);
if (rc < 0)
log_error_errno(rc, "failed to apply permissions on static device nodes - %m");
if (arg_daemonize) {
pid_t pid;
pid = fork();
switch (pid) {
case 0:
break;
case -1:
log_error_errno(errno, "fork of daemon failed: %m");
rc = 4;
goto exit;
default:
rc = EXIT_SUCCESS;
goto exit_daemonize;
}
setsid();
write_string_file("/proc/self/oom_score_adj", "-1000");
} else {
sd_notify(1, "READY=1");
}
if (arg_children_max <= 0) {
cpu_set_t cpu_set;
arg_children_max = 8;
if (sched_getaffinity(0, sizeof (cpu_set), &cpu_set) == 0) {
arg_children_max += CPU_COUNT(&cpu_set) * 2;
}
}
log_debug("set children_max to %u", arg_children_max);
udev_list_node_init(&event_list);
udev_list_node_init(&worker_list);
fd_inotify = udev_watch_init(udev);
if (fd_inotify < 0) {
log_error("error initializing inotify");
rc = 4;
goto exit;
}
udev_watch_restore(udev);
/* block and listen to all signals on signalfd */
sigfillset(&mask);
sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
if (fd_signal < 0) {
log_error("error creating signalfd");
rc = 5;
goto exit;
}
/* unnamed socket from workers to the main daemon */
if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
log_error("error creating socketpair");
rc = 6;
goto exit;
}
fd_worker = worker_watch[READ_END];
r = setsockopt(fd_worker, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
if (r < 0)
return log_error_errno(errno, "could not enable SO_PASSCRED: %m");
ep_ctrl.data.fd = fd_ctrl;
ep_inotify.data.fd = fd_inotify;
ep_signal.data.fd = fd_signal;
ep_netlink.data.fd = fd_netlink;
ep_worker.data.fd = fd_worker;
fd_ep = epoll_create1(EPOLL_CLOEXEC);
if (fd_ep < 0) {
log_error_errno(errno, "error creating epoll fd: %m");
goto exit;
}
if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_ctrl, &ep_ctrl) < 0 ||
epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_inotify, &ep_inotify) < 0 ||
epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_netlink, &ep_netlink) < 0 ||
epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_worker, &ep_worker) < 0) {
log_error_errno(errno, "fail to add fds to epoll: %m");
goto exit;
}
for (;;) {
static usec_t last_usec;
struct epoll_event ev[8];
int fdcount;
int timeout;
bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
int i;
if (udev_exit) {
/* close sources of new events and discard buffered events */
if (fd_ctrl >= 0) {
epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
fd_ctrl = -1;
}
if (monitor != NULL) {
epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
udev_monitor_unref(monitor);
monitor = NULL;
}
if (fd_inotify >= 0) {
epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
close(fd_inotify);
fd_inotify = -1;
}
/* discard queued events and kill workers */
event_queue_cleanup(udev, EVENT_QUEUED);
worker_kill(udev);
/* exit after all has cleaned up */
if (udev_list_node_is_empty(&event_list) && children == 0)
break;
/* timeout at exit for workers to finish */
timeout = 30 * MSEC_PER_SEC;
} else if (udev_list_node_is_empty(&event_list) && children == 0) {
/* we are idle */
timeout = -1;
/* cleanup possible left-over processes in our cgroup */
if (udev_cgroup)
cg_kill(SYSTEMD_CGROUP_CONTROLLER, udev_cgroup, SIGKILL, false, true, NULL);
} else {
/* kill idle or hanging workers */
timeout = 3 * MSEC_PER_SEC;
}
/* tell settle that we are busy or idle */
event_queue_update();
fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
if (fdcount < 0)
continue;
if (fdcount == 0) {
struct udev_list_node *loop;
/* timeout */
if (udev_exit) {
log_error("timeout, giving up waiting for workers to finish");
break;
}
/* kill idle workers */
if (udev_list_node_is_empty(&event_list)) {
log_debug("cleanup idle workers");
worker_kill(udev);
}
/* check for hanging events */
udev_list_node_foreach(loop, &worker_list) {
struct worker *worker = node_to_worker(loop);
usec_t ts;
if (worker->state != WORKER_RUNNING)
continue;
ts = now(CLOCK_MONOTONIC);
if ((ts - worker->event_start_usec) > arg_event_timeout_warn_usec) {
if ((ts - worker->event_start_usec) > arg_event_timeout_usec) {
log_error("worker ["PID_FMT"] %s timeout; kill it", worker->pid, worker->event->devpath);
kill(worker->pid, SIGKILL);
worker->state = WORKER_KILLED;
log_error("seq %llu '%s' killed", udev_device_get_seqnum(worker->event->dev), worker->event->devpath);
} else if (!worker->event_warned) {
log_warning("worker ["PID_FMT"] %s is taking a long time", worker->pid, worker->event->devpath);
worker->event_warned = true;
}
}
}
}
is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
for (i = 0; i < fdcount; i++) {
if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
is_worker = true;
else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
is_netlink = true;
else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
is_signal = true;
else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
is_inotify = true;
else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
is_ctrl = true;
}
/* check for changed config, every 3 seconds at most */
if ((now(CLOCK_MONOTONIC) - last_usec) > 3 * USEC_PER_SEC) {
if (udev_rules_check_timestamp(rules))
reload = true;
if (udev_builtin_validate(udev))
reload = true;
last_usec = now(CLOCK_MONOTONIC);
}
/* reload requested, HUP signal received, rules changed, builtin changed */
if (reload) {
worker_kill(udev);
rules = udev_rules_unref(rules);
udev_builtin_exit(udev);
reload = false;
}
/* event has finished */
if (is_worker)
worker_returned(fd_worker);
if (is_netlink) {
struct udev_device *dev;
dev = udev_monitor_receive_device(monitor);
if (dev) {
udev_device_ensure_usec_initialized(dev, NULL);
if (event_queue_insert(dev) < 0)
udev_device_unref(dev);
}
}
/* start new events */
if (!udev_list_node_is_empty(&event_list) && !udev_exit && !stop_exec_queue) {
udev_builtin_init(udev);
if (rules == NULL)
rules = udev_rules_new(udev, arg_resolve_names);
if (rules != NULL)
event_queue_start(udev);
}
if (is_signal) {
struct signalfd_siginfo fdsi;
ssize_t size;
size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
if (size == sizeof(struct signalfd_siginfo))
handle_signal(udev, fdsi.ssi_signo);
}
/* we are shutting down, the events below are not handled anymore */
if (udev_exit)
continue;
/* device node watch */
if (is_inotify) {
handle_inotify(udev);
/*
* settle might be waiting on us to determine the queue
* state. If we just handled an inotify event, we might have
* generated a "change" event, but we won't have queued up
* the resultant uevent yet.
*
* Before we go ahead and potentially tell settle that the
* queue is empty, lets loop one more time to update the
* queue state again before deciding.
*/
continue;
}
/* tell settle that we are busy or idle, this needs to be before the
* PING handling
*/
event_queue_update();
/*
* This needs to be after the inotify handling, to make sure,
* that the ping is send back after the possibly generated
* "change" events by the inotify device node watch.
*
* A single time we may receive a client connection which we need to
* keep open to block the client. It will be closed right before we
* exit.
*/
if (is_ctrl)
ctrl_conn = handle_ctrl_msg(udev_ctrl);
}
rc = EXIT_SUCCESS;
exit:
udev_ctrl_cleanup(udev_ctrl);
unlink("/run/udev/queue");
exit_daemonize:
if (fd_ep >= 0)
close(fd_ep);
worker_list_cleanup(udev);
event_queue_cleanup(udev, EVENT_UNDEF);
udev_rules_unref(rules);
udev_builtin_exit(udev);
if (fd_signal >= 0)
close(fd_signal);
if (worker_watch[READ_END] >= 0)
close(worker_watch[READ_END]);
if (worker_watch[WRITE_END] >= 0)
close(worker_watch[WRITE_END]);
udev_monitor_unref(monitor);
udev_ctrl_connection_unref(ctrl_conn);
udev_ctrl_unref(udev_ctrl);
udev_list_cleanup(&properties_list);
mac_selinux_finish();
udev_unref(udev);
log_close();
return rc;
}