Line data Source code
1 : /* SPDX-License-Identifier: GPL-2.0+ */
2 : /*
3 : * Copyright © 2004 Chris Friesen <chris_friesen@sympatico.ca>
4 : * Copyright © 2009 Canonical Ltd.
5 : * Copyright © 2009 Scott James Remnant <scott@netsplit.com>
6 : */
7 :
8 : #include <errno.h>
9 : #include <fcntl.h>
10 : #include <getopt.h>
11 : #include <signal.h>
12 : #include <stdbool.h>
13 : #include <stddef.h>
14 : #include <stdio.h>
15 : #include <stdlib.h>
16 : #include <string.h>
17 : #include <sys/epoll.h>
18 : #include <sys/file.h>
19 : #include <sys/inotify.h>
20 : #include <sys/ioctl.h>
21 : #include <sys/mount.h>
22 : #include <sys/prctl.h>
23 : #include <sys/signalfd.h>
24 : #include <sys/socket.h>
25 : #include <sys/stat.h>
26 : #include <sys/time.h>
27 : #include <sys/wait.h>
28 : #include <unistd.h>
29 :
30 : #include "sd-daemon.h"
31 : #include "sd-event.h"
32 :
33 : #include "alloc-util.h"
34 : #include "build.h"
35 : #include "cgroup-util.h"
36 : #include "cpu-set-util.h"
37 : #include "dev-setup.h"
38 : #include "device-monitor-private.h"
39 : #include "device-private.h"
40 : #include "device-util.h"
41 : #include "event-util.h"
42 : #include "fd-util.h"
43 : #include "fileio.h"
44 : #include "format-util.h"
45 : #include "fs-util.h"
46 : #include "hashmap.h"
47 : #include "io-util.h"
48 : #include "libudev-device-internal.h"
49 : #include "limits-util.h"
50 : #include "list.h"
51 : #include "main-func.h"
52 : #include "mkdir.h"
53 : #include "netlink-util.h"
54 : #include "parse-util.h"
55 : #include "pretty-print.h"
56 : #include "proc-cmdline.h"
57 : #include "process-util.h"
58 : #include "selinux-util.h"
59 : #include "signal-util.h"
60 : #include "socket-util.h"
61 : #include "string-util.h"
62 : #include "strv.h"
63 : #include "strxcpyx.h"
64 : #include "syslog-util.h"
65 : #include "udev-builtin.h"
66 : #include "udev-ctrl.h"
67 : #include "udev-event.h"
68 : #include "udev-util.h"
69 : #include "udev-watch.h"
70 : #include "user-util.h"
71 :
72 : #define WORKER_NUM_MAX 2048U
73 :
74 : static bool arg_debug = false;
75 : static int arg_daemonize = false;
76 : static ResolveNameTiming arg_resolve_name_timing = RESOLVE_NAME_EARLY;
77 : static unsigned arg_children_max = 0;
78 : static usec_t arg_exec_delay_usec = 0;
79 : static usec_t arg_event_timeout_usec = 180 * USEC_PER_SEC;
80 :
81 : typedef struct Manager {
82 : sd_event *event;
83 : Hashmap *workers;
84 : LIST_HEAD(struct event, events);
85 : const char *cgroup;
86 : pid_t pid; /* the process that originally allocated the manager object */
87 :
88 : UdevRules *rules;
89 : Hashmap *properties;
90 :
91 : sd_netlink *rtnl;
92 :
93 : sd_device_monitor *monitor;
94 : struct udev_ctrl *ctrl;
95 : int fd_inotify;
96 : int worker_watch[2];
97 :
98 : sd_event_source *inotify_event;
99 : sd_event_source *kill_workers_event;
100 :
101 : usec_t last_usec;
102 :
103 : bool stop_exec_queue:1;
104 : bool exit:1;
105 : } Manager;
106 :
107 : enum event_state {
108 : EVENT_UNDEF,
109 : EVENT_QUEUED,
110 : EVENT_RUNNING,
111 : };
112 :
113 : struct event {
114 : Manager *manager;
115 : struct worker *worker;
116 : enum event_state state;
117 :
118 : sd_device *dev;
119 : sd_device *dev_kernel; /* clone of originally received device */
120 :
121 : uint64_t seqnum;
122 : uint64_t delaying_seqnum;
123 :
124 : sd_event_source *timeout_warning_event;
125 : sd_event_source *timeout_event;
126 :
127 : LIST_FIELDS(struct event, event);
128 : };
129 :
130 : static void event_queue_cleanup(Manager *manager, enum event_state type);
131 :
132 : enum worker_state {
133 : WORKER_UNDEF,
134 : WORKER_RUNNING,
135 : WORKER_IDLE,
136 : WORKER_KILLED,
137 : };
138 :
139 : struct worker {
140 : Manager *manager;
141 : pid_t pid;
142 : sd_device_monitor *monitor;
143 : enum worker_state state;
144 : struct event *event;
145 : };
146 :
147 : /* passed from worker to main process */
148 : struct worker_message {
149 : };
150 :
151 0 : static void event_free(struct event *event) {
152 0 : if (!event)
153 0 : return;
154 :
155 0 : assert(event->manager);
156 :
157 0 : LIST_REMOVE(event, event->manager->events, event);
158 0 : sd_device_unref(event->dev);
159 0 : sd_device_unref(event->dev_kernel);
160 :
161 0 : sd_event_source_unref(event->timeout_warning_event);
162 0 : sd_event_source_unref(event->timeout_event);
163 :
164 0 : if (event->worker)
165 0 : event->worker->event = NULL;
166 :
167 : /* only clean up the queue from the process that created it */
168 0 : if (LIST_IS_EMPTY(event->manager->events) &&
169 0 : event->manager->pid == getpid_cached())
170 0 : if (unlink("/run/udev/queue") < 0)
171 0 : log_warning_errno(errno, "Failed to unlink /run/udev/queue: %m");
172 :
173 0 : free(event);
174 : }
175 :
176 0 : static void worker_free(struct worker *worker) {
177 0 : if (!worker)
178 0 : return;
179 :
180 0 : assert(worker->manager);
181 :
182 0 : hashmap_remove(worker->manager->workers, PID_TO_PTR(worker->pid));
183 0 : sd_device_monitor_unref(worker->monitor);
184 0 : event_free(worker->event);
185 :
186 0 : free(worker);
187 : }
188 :
189 0 : DEFINE_TRIVIAL_CLEANUP_FUNC(struct worker *, worker_free);
190 0 : DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(worker_hash_op, void, trivial_hash_func, trivial_compare_func, struct worker, worker_free);
191 :
192 0 : static int worker_new(struct worker **ret, Manager *manager, sd_device_monitor *worker_monitor, pid_t pid) {
193 0 : _cleanup_(worker_freep) struct worker *worker = NULL;
194 : int r;
195 :
196 0 : assert(ret);
197 0 : assert(manager);
198 0 : assert(worker_monitor);
199 0 : assert(pid > 1);
200 :
201 : /* close monitor, but keep address around */
202 0 : device_monitor_disconnect(worker_monitor);
203 :
204 0 : worker = new(struct worker, 1);
205 0 : if (!worker)
206 0 : return -ENOMEM;
207 :
208 0 : *worker = (struct worker) {
209 : .manager = manager,
210 0 : .monitor = sd_device_monitor_ref(worker_monitor),
211 : .pid = pid,
212 : };
213 :
214 0 : r = hashmap_ensure_allocated(&manager->workers, &worker_hash_op);
215 0 : if (r < 0)
216 0 : return r;
217 :
218 0 : r = hashmap_put(manager->workers, PID_TO_PTR(pid), worker);
219 0 : if (r < 0)
220 0 : return r;
221 :
222 0 : *ret = TAKE_PTR(worker);
223 :
224 0 : return 0;
225 : }
226 :
227 0 : static int on_event_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
228 0 : struct event *event = userdata;
229 :
230 0 : assert(event);
231 0 : assert(event->worker);
232 :
233 0 : kill_and_sigcont(event->worker->pid, SIGKILL);
234 0 : event->worker->state = WORKER_KILLED;
235 :
236 0 : log_device_error(event->dev, "Worker ["PID_FMT"] processing SEQNUM=%"PRIu64" killed", event->worker->pid, event->seqnum);
237 :
238 0 : return 1;
239 : }
240 :
241 0 : static int on_event_timeout_warning(sd_event_source *s, uint64_t usec, void *userdata) {
242 0 : struct event *event = userdata;
243 :
244 0 : assert(event);
245 0 : assert(event->worker);
246 :
247 0 : log_device_warning(event->dev, "Worker ["PID_FMT"] processing SEQNUM=%"PRIu64" is taking a long time", event->worker->pid, event->seqnum);
248 :
249 0 : return 1;
250 : }
251 :
252 0 : static void worker_attach_event(struct worker *worker, struct event *event) {
253 : sd_event *e;
254 : uint64_t usec;
255 :
256 0 : assert(worker);
257 0 : assert(worker->manager);
258 0 : assert(event);
259 0 : assert(!event->worker);
260 0 : assert(!worker->event);
261 :
262 0 : worker->state = WORKER_RUNNING;
263 0 : worker->event = event;
264 0 : event->state = EVENT_RUNNING;
265 0 : event->worker = worker;
266 :
267 0 : e = worker->manager->event;
268 :
269 0 : assert_se(sd_event_now(e, CLOCK_MONOTONIC, &usec) >= 0);
270 :
271 0 : (void) sd_event_add_time(e, &event->timeout_warning_event, CLOCK_MONOTONIC,
272 0 : usec + udev_warn_timeout(arg_event_timeout_usec), USEC_PER_SEC, on_event_timeout_warning, event);
273 :
274 0 : (void) sd_event_add_time(e, &event->timeout_event, CLOCK_MONOTONIC,
275 : usec + arg_event_timeout_usec, USEC_PER_SEC, on_event_timeout, event);
276 0 : }
277 :
278 0 : static void manager_clear_for_worker(Manager *manager) {
279 0 : assert(manager);
280 :
281 0 : manager->inotify_event = sd_event_source_unref(manager->inotify_event);
282 0 : manager->kill_workers_event = sd_event_source_unref(manager->kill_workers_event);
283 :
284 0 : manager->event = sd_event_unref(manager->event);
285 :
286 0 : manager->workers = hashmap_free(manager->workers);
287 0 : event_queue_cleanup(manager, EVENT_UNDEF);
288 :
289 0 : manager->monitor = sd_device_monitor_unref(manager->monitor);
290 0 : manager->ctrl = udev_ctrl_unref(manager->ctrl);
291 :
292 0 : manager->worker_watch[READ_END] = safe_close(manager->worker_watch[READ_END]);
293 0 : }
294 :
295 0 : static void manager_free(Manager *manager) {
296 0 : if (!manager)
297 0 : return;
298 :
299 0 : udev_builtin_exit();
300 :
301 0 : if (manager->pid == getpid_cached())
302 0 : udev_ctrl_cleanup(manager->ctrl);
303 :
304 0 : manager_clear_for_worker(manager);
305 :
306 0 : sd_netlink_unref(manager->rtnl);
307 :
308 0 : hashmap_free_free_free(manager->properties);
309 0 : udev_rules_free(manager->rules);
310 :
311 0 : safe_close(manager->fd_inotify);
312 0 : safe_close_pair(manager->worker_watch);
313 :
314 0 : free(manager);
315 : }
316 :
317 4 : DEFINE_TRIVIAL_CLEANUP_FUNC(Manager*, manager_free);
318 :
319 0 : static int worker_send_message(int fd) {
320 0 : struct worker_message message = {};
321 :
322 0 : return loop_write(fd, &message, sizeof(message), false);
323 : }
324 :
325 0 : static int worker_lock_block_device(sd_device *dev, int *ret_fd) {
326 0 : _cleanup_close_ int fd = -1;
327 : const char *val;
328 : int r;
329 :
330 0 : assert(dev);
331 0 : assert(ret_fd);
332 :
333 : /*
334 : * Take a shared lock on the device node; this establishes
335 : * a concept of device "ownership" to serialize device
336 : * access. External processes holding an exclusive lock will
337 : * cause udev to skip the event handling; in the case udev
338 : * acquired the lock, the external process can block until
339 : * udev has finished its event handling.
340 : */
341 :
342 0 : if (device_for_action(dev, DEVICE_ACTION_REMOVE))
343 0 : return 0;
344 :
345 0 : r = sd_device_get_subsystem(dev, &val);
346 0 : if (r < 0)
347 0 : return log_device_debug_errno(dev, r, "Failed to get subsystem: %m");
348 :
349 0 : if (!streq(val, "block"))
350 0 : return 0;
351 :
352 0 : r = sd_device_get_sysname(dev, &val);
353 0 : if (r < 0)
354 0 : return log_device_debug_errno(dev, r, "Failed to get sysname: %m");
355 :
356 0 : if (STARTSWITH_SET(val, "dm-", "md", "drbd"))
357 0 : return 0;
358 :
359 0 : r = sd_device_get_devtype(dev, &val);
360 0 : if (r < 0 && r != -ENOENT)
361 0 : return log_device_debug_errno(dev, r, "Failed to get devtype: %m");
362 0 : if (r >= 0 && streq(val, "partition")) {
363 0 : r = sd_device_get_parent(dev, &dev);
364 0 : if (r < 0)
365 0 : return log_device_debug_errno(dev, r, "Failed to get parent device: %m");
366 : }
367 :
368 0 : r = sd_device_get_devname(dev, &val);
369 0 : if (r == -ENOENT)
370 0 : return 0;
371 0 : if (r < 0)
372 0 : return log_device_debug_errno(dev, r, "Failed to get devname: %m");
373 :
374 0 : fd = open(val, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
375 0 : if (fd < 0) {
376 0 : log_device_debug_errno(dev, errno, "Failed to open '%s', ignoring: %m", val);
377 0 : return 0;
378 : }
379 :
380 0 : if (flock(fd, LOCK_SH|LOCK_NB) < 0)
381 0 : return log_device_debug_errno(dev, errno, "Failed to flock(%s): %m", val);
382 :
383 0 : *ret_fd = TAKE_FD(fd);
384 0 : return 1;
385 : }
386 :
387 0 : static int worker_process_device(Manager *manager, sd_device *dev) {
388 0 : _cleanup_(udev_event_freep) UdevEvent *udev_event = NULL;
389 0 : _cleanup_close_ int fd_lock = -1;
390 : DeviceAction action;
391 : uint64_t seqnum;
392 : int r;
393 :
394 0 : assert(manager);
395 0 : assert(dev);
396 :
397 0 : r = device_get_seqnum(dev, &seqnum);
398 0 : if (r < 0)
399 0 : return log_device_debug_errno(dev, r, "Failed to get SEQNUM: %m");
400 :
401 0 : r = device_get_action(dev, &action);
402 0 : if (r < 0)
403 0 : return log_device_debug_errno(dev, r, "Failed to get ACTION: %m");
404 :
405 0 : log_device_debug(dev, "Processing device (SEQNUM=%"PRIu64", ACTION=%s)",
406 : seqnum, device_action_to_string(action));
407 :
408 0 : udev_event = udev_event_new(dev, arg_exec_delay_usec, manager->rtnl);
409 0 : if (!udev_event)
410 0 : return -ENOMEM;
411 :
412 0 : r = worker_lock_block_device(dev, &fd_lock);
413 0 : if (r < 0)
414 0 : return r;
415 :
416 : /* apply rules, create node, symlinks */
417 0 : r = udev_event_execute_rules(udev_event, arg_event_timeout_usec, manager->properties, manager->rules);
418 0 : if (r < 0)
419 0 : return r;
420 :
421 0 : udev_event_execute_run(udev_event, arg_event_timeout_usec);
422 :
423 0 : if (!manager->rtnl)
424 : /* in case rtnl was initialized */
425 0 : manager->rtnl = sd_netlink_ref(udev_event->rtnl);
426 :
427 : /* apply/restore inotify watch */
428 0 : if (udev_event->inotify_watch) {
429 0 : (void) udev_watch_begin(dev);
430 0 : r = device_update_db(dev);
431 0 : if (r < 0)
432 0 : return log_device_debug_errno(dev, r, "Failed to update database under /run/udev/data/: %m");
433 : }
434 :
435 0 : log_device_debug(dev, "Device (SEQNUM=%"PRIu64", ACTION=%s) processed",
436 : seqnum, device_action_to_string(action));
437 :
438 0 : return 0;
439 : }
440 :
441 0 : static int worker_device_monitor_handler(sd_device_monitor *monitor, sd_device *dev, void *userdata) {
442 0 : Manager *manager = userdata;
443 : int r;
444 :
445 0 : assert(dev);
446 0 : assert(manager);
447 :
448 0 : r = worker_process_device(manager, dev);
449 0 : if (r < 0)
450 0 : log_device_warning_errno(dev, r, "Failed to process device, ignoring: %m");
451 :
452 : /* send processed event back to libudev listeners */
453 0 : r = device_monitor_send_device(monitor, NULL, dev);
454 0 : if (r < 0)
455 0 : log_device_warning_errno(dev, r, "Failed to send device, ignoring: %m");
456 :
457 : /* send udevd the result of the event execution */
458 0 : r = worker_send_message(manager->worker_watch[WRITE_END]);
459 0 : if (r < 0)
460 0 : log_device_warning_errno(dev, r, "Failed to send signal to main daemon, ignoring: %m");
461 :
462 0 : return 1;
463 : }
464 :
465 0 : static int worker_main(Manager *_manager, sd_device_monitor *monitor, sd_device *first_device) {
466 0 : _cleanup_(sd_device_unrefp) sd_device *dev = first_device;
467 0 : _cleanup_(manager_freep) Manager *manager = _manager;
468 : int r;
469 :
470 0 : assert(manager);
471 0 : assert(monitor);
472 0 : assert(dev);
473 :
474 0 : unsetenv("NOTIFY_SOCKET");
475 :
476 0 : assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, -1) >= 0);
477 :
478 : /* Reset OOM score, we only protect the main daemon. */
479 0 : r = set_oom_score_adjust(0);
480 0 : if (r < 0)
481 0 : log_debug_errno(r, "Failed to reset OOM score, ignoring: %m");
482 :
483 : /* Clear unnecessary data in Manager object.*/
484 0 : manager_clear_for_worker(manager);
485 :
486 0 : r = sd_event_new(&manager->event);
487 0 : if (r < 0)
488 0 : return log_error_errno(r, "Failed to allocate event loop: %m");
489 :
490 0 : r = sd_event_add_signal(manager->event, NULL, SIGTERM, NULL, NULL);
491 0 : if (r < 0)
492 0 : return log_error_errno(r, "Failed to set SIGTERM event: %m");
493 :
494 0 : r = sd_device_monitor_attach_event(monitor, manager->event);
495 0 : if (r < 0)
496 0 : return log_error_errno(r, "Failed to attach event loop to device monitor: %m");
497 :
498 0 : r = sd_device_monitor_start(monitor, worker_device_monitor_handler, manager);
499 0 : if (r < 0)
500 0 : return log_error_errno(r, "Failed to start device monitor: %m");
501 :
502 0 : (void) sd_event_source_set_description(sd_device_monitor_get_event_source(monitor), "worker-device-monitor");
503 :
504 : /* Process first device */
505 0 : (void) worker_device_monitor_handler(monitor, dev, manager);
506 :
507 0 : r = sd_event_loop(manager->event);
508 0 : if (r < 0)
509 0 : return log_error_errno(r, "Event loop failed: %m");
510 :
511 0 : return 0;
512 : }
513 :
514 0 : static int worker_spawn(Manager *manager, struct event *event) {
515 0 : _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *worker_monitor = NULL;
516 : struct worker *worker;
517 : pid_t pid;
518 : int r;
519 :
520 : /* listen for new events */
521 0 : r = device_monitor_new_full(&worker_monitor, MONITOR_GROUP_NONE, -1);
522 0 : if (r < 0)
523 0 : return r;
524 :
525 : /* allow the main daemon netlink address to send devices to the worker */
526 0 : r = device_monitor_allow_unicast_sender(worker_monitor, manager->monitor);
527 0 : if (r < 0)
528 0 : return log_error_errno(r, "Worker: Failed to set unicast sender: %m");
529 :
530 0 : r = device_monitor_enable_receiving(worker_monitor);
531 0 : if (r < 0)
532 0 : return log_error_errno(r, "Worker: Failed to enable receiving of device: %m");
533 :
534 0 : r = safe_fork(NULL, FORK_DEATHSIG, &pid);
535 0 : if (r < 0) {
536 0 : event->state = EVENT_QUEUED;
537 0 : return log_error_errno(r, "Failed to fork() worker: %m");
538 : }
539 0 : if (r == 0) {
540 : /* Worker process */
541 0 : r = worker_main(manager, worker_monitor, sd_device_ref(event->dev));
542 0 : log_close();
543 0 : _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
544 : }
545 :
546 0 : r = worker_new(&worker, manager, worker_monitor, pid);
547 0 : if (r < 0)
548 0 : return log_error_errno(r, "Failed to create worker object: %m");
549 :
550 0 : worker_attach_event(worker, event);
551 :
552 0 : log_device_debug(event->dev, "Worker ["PID_FMT"] is forked for processing SEQNUM=%"PRIu64".", pid, event->seqnum);
553 0 : return 0;
554 : }
555 :
556 0 : static void event_run(Manager *manager, struct event *event) {
557 : static bool log_children_max_reached = true;
558 : struct worker *worker;
559 : Iterator i;
560 : int r;
561 :
562 0 : assert(manager);
563 0 : assert(event);
564 :
565 0 : HASHMAP_FOREACH(worker, manager->workers, i) {
566 0 : if (worker->state != WORKER_IDLE)
567 0 : continue;
568 :
569 0 : r = device_monitor_send_device(manager->monitor, worker->monitor, event->dev);
570 0 : if (r < 0) {
571 0 : log_device_error_errno(event->dev, r, "Worker ["PID_FMT"] did not accept message, killing the worker: %m",
572 : worker->pid);
573 0 : (void) kill(worker->pid, SIGKILL);
574 0 : worker->state = WORKER_KILLED;
575 0 : continue;
576 : }
577 0 : worker_attach_event(worker, event);
578 0 : return;
579 : }
580 :
581 0 : if (hashmap_size(manager->workers) >= arg_children_max) {
582 :
583 : /* Avoid spamming the debug logs if the limit is already reached and
584 : * many events still need to be processed */
585 0 : if (log_children_max_reached && arg_children_max > 1) {
586 0 : log_debug("Maximum number (%u) of children reached.", hashmap_size(manager->workers));
587 0 : log_children_max_reached = false;
588 : }
589 0 : return;
590 : }
591 :
592 : /* Re-enable the debug message for the next batch of events */
593 0 : log_children_max_reached = true;
594 :
595 : /* start new worker and pass initial device */
596 0 : worker_spawn(manager, event);
597 : }
598 :
599 0 : static int event_queue_insert(Manager *manager, sd_device *dev) {
600 0 : _cleanup_(sd_device_unrefp) sd_device *clone = NULL;
601 : struct event *event;
602 : DeviceAction action;
603 : uint64_t seqnum;
604 : int r;
605 :
606 0 : assert(manager);
607 0 : assert(dev);
608 :
609 : /* only one process can add events to the queue */
610 0 : assert(manager->pid == getpid_cached());
611 :
612 : /* We only accepts devices received by device monitor. */
613 0 : r = device_get_seqnum(dev, &seqnum);
614 0 : if (r < 0)
615 0 : return r;
616 :
617 : /* Refuse devices do not have ACTION property. */
618 0 : r = device_get_action(dev, &action);
619 0 : if (r < 0)
620 0 : return r;
621 :
622 : /* Save original device to restore the state on failures. */
623 0 : r = device_shallow_clone(dev, &clone);
624 0 : if (r < 0)
625 0 : return r;
626 :
627 0 : r = device_copy_properties(clone, dev);
628 0 : if (r < 0)
629 0 : return r;
630 :
631 0 : event = new(struct event, 1);
632 0 : if (!event)
633 0 : return -ENOMEM;
634 :
635 0 : *event = (struct event) {
636 : .manager = manager,
637 0 : .dev = sd_device_ref(dev),
638 0 : .dev_kernel = TAKE_PTR(clone),
639 : .seqnum = seqnum,
640 : .state = EVENT_QUEUED,
641 : };
642 :
643 0 : if (LIST_IS_EMPTY(manager->events)) {
644 0 : r = touch("/run/udev/queue");
645 0 : if (r < 0)
646 0 : log_warning_errno(r, "Failed to touch /run/udev/queue: %m");
647 : }
648 :
649 0 : LIST_APPEND(event, manager->events, event);
650 :
651 0 : log_device_debug(dev, "Device (SEQNUM=%"PRIu64", ACTION=%s) is queued",
652 : seqnum, device_action_to_string(action));
653 :
654 0 : return 0;
655 : }
656 :
657 0 : static void manager_kill_workers(Manager *manager) {
658 : struct worker *worker;
659 : Iterator i;
660 :
661 0 : assert(manager);
662 :
663 0 : HASHMAP_FOREACH(worker, manager->workers, i) {
664 0 : if (worker->state == WORKER_KILLED)
665 0 : continue;
666 :
667 0 : worker->state = WORKER_KILLED;
668 0 : (void) kill(worker->pid, SIGTERM);
669 : }
670 0 : }
671 :
672 : /* lookup event for identical, parent, child device */
673 0 : static int is_device_busy(Manager *manager, struct event *event) {
674 0 : const char *subsystem, *devpath, *devpath_old = NULL;
675 0 : dev_t devnum = makedev(0, 0);
676 : struct event *loop_event;
677 : size_t devpath_len;
678 0 : int r, ifindex = 0;
679 : bool is_block;
680 :
681 0 : r = sd_device_get_subsystem(event->dev, &subsystem);
682 0 : if (r < 0)
683 0 : return r;
684 :
685 0 : is_block = streq(subsystem, "block");
686 :
687 0 : r = sd_device_get_devpath(event->dev, &devpath);
688 0 : if (r < 0)
689 0 : return r;
690 :
691 0 : devpath_len = strlen(devpath);
692 :
693 0 : r = sd_device_get_property_value(event->dev, "DEVPATH_OLD", &devpath_old);
694 0 : if (r < 0 && r != -ENOENT)
695 0 : return r;
696 :
697 0 : r = sd_device_get_devnum(event->dev, &devnum);
698 0 : if (r < 0 && r != -ENOENT)
699 0 : return r;
700 :
701 0 : r = sd_device_get_ifindex(event->dev, &ifindex);
702 0 : if (r < 0 && r != -ENOENT)
703 0 : return r;
704 :
705 : /* check if queue contains events we depend on */
706 0 : LIST_FOREACH(event, loop_event, manager->events) {
707 : size_t loop_devpath_len, common;
708 : const char *loop_devpath;
709 :
710 : /* we already found a later event, earlier cannot block us, no need to check again */
711 0 : if (loop_event->seqnum < event->delaying_seqnum)
712 0 : continue;
713 :
714 : /* event we checked earlier still exists, no need to check again */
715 0 : if (loop_event->seqnum == event->delaying_seqnum)
716 0 : return true;
717 :
718 : /* found ourself, no later event can block us */
719 0 : if (loop_event->seqnum >= event->seqnum)
720 0 : break;
721 :
722 : /* check major/minor */
723 0 : if (major(devnum) != 0) {
724 : const char *s;
725 : dev_t d;
726 :
727 0 : if (sd_device_get_subsystem(loop_event->dev, &s) < 0)
728 0 : continue;
729 :
730 0 : if (sd_device_get_devnum(loop_event->dev, &d) >= 0 &&
731 0 : devnum == d && is_block == streq(s, "block"))
732 0 : goto set_delaying_seqnum;
733 : }
734 :
735 : /* check network device ifindex */
736 0 : if (ifindex > 0) {
737 : int i;
738 :
739 0 : if (sd_device_get_ifindex(loop_event->dev, &i) >= 0 &&
740 0 : ifindex == i)
741 0 : goto set_delaying_seqnum;
742 : }
743 :
744 0 : if (sd_device_get_devpath(loop_event->dev, &loop_devpath) < 0)
745 0 : continue;
746 :
747 : /* check our old name */
748 0 : if (devpath_old && streq(devpath_old, loop_devpath))
749 0 : goto set_delaying_seqnum;
750 :
751 0 : loop_devpath_len = strlen(loop_devpath);
752 :
753 : /* compare devpath */
754 0 : common = MIN(devpath_len, loop_devpath_len);
755 :
756 : /* one devpath is contained in the other? */
757 0 : if (!strneq(devpath, loop_devpath, common))
758 0 : continue;
759 :
760 : /* identical device event found */
761 0 : if (devpath_len == loop_devpath_len)
762 0 : goto set_delaying_seqnum;
763 :
764 : /* parent device event found */
765 0 : if (devpath[common] == '/')
766 0 : goto set_delaying_seqnum;
767 :
768 : /* child device event found */
769 0 : if (loop_devpath[common] == '/')
770 0 : goto set_delaying_seqnum;
771 : }
772 :
773 0 : return false;
774 :
775 0 : set_delaying_seqnum:
776 0 : event->delaying_seqnum = loop_event->seqnum;
777 0 : return true;
778 : }
779 :
780 0 : static int on_exit_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
781 0 : Manager *manager = userdata;
782 :
783 0 : assert(manager);
784 :
785 0 : log_error("Giving up waiting for workers to finish.");
786 0 : sd_event_exit(manager->event, -ETIMEDOUT);
787 :
788 0 : return 1;
789 : }
790 :
791 0 : static void manager_exit(Manager *manager) {
792 : uint64_t usec;
793 : int r;
794 :
795 0 : assert(manager);
796 :
797 0 : manager->exit = true;
798 :
799 0 : sd_notify(false,
800 : "STOPPING=1\n"
801 : "STATUS=Starting shutdown...");
802 :
803 : /* close sources of new events and discard buffered events */
804 0 : manager->ctrl = udev_ctrl_unref(manager->ctrl);
805 :
806 0 : manager->inotify_event = sd_event_source_unref(manager->inotify_event);
807 0 : manager->fd_inotify = safe_close(manager->fd_inotify);
808 :
809 0 : manager->monitor = sd_device_monitor_unref(manager->monitor);
810 :
811 : /* discard queued events and kill workers */
812 0 : event_queue_cleanup(manager, EVENT_QUEUED);
813 0 : manager_kill_workers(manager);
814 :
815 0 : assert_se(sd_event_now(manager->event, CLOCK_MONOTONIC, &usec) >= 0);
816 :
817 0 : r = sd_event_add_time(manager->event, NULL, CLOCK_MONOTONIC,
818 : usec + 30 * USEC_PER_SEC, USEC_PER_SEC, on_exit_timeout, manager);
819 0 : if (r < 0)
820 0 : return;
821 : }
822 :
823 : /* reload requested, HUP signal received, rules changed, builtin changed */
824 0 : static void manager_reload(Manager *manager) {
825 :
826 0 : assert(manager);
827 :
828 0 : sd_notify(false,
829 : "RELOADING=1\n"
830 : "STATUS=Flushing configuration...");
831 :
832 0 : manager_kill_workers(manager);
833 0 : manager->rules = udev_rules_free(manager->rules);
834 0 : udev_builtin_exit();
835 :
836 0 : sd_notifyf(false,
837 : "READY=1\n"
838 : "STATUS=Processing with %u children at max", arg_children_max);
839 0 : }
840 :
841 0 : static int on_kill_workers_event(sd_event_source *s, uint64_t usec, void *userdata) {
842 0 : Manager *manager = userdata;
843 :
844 0 : assert(manager);
845 :
846 0 : log_debug("Cleanup idle workers");
847 0 : manager_kill_workers(manager);
848 :
849 0 : return 1;
850 : }
851 :
852 0 : static void event_queue_start(Manager *manager) {
853 : struct event *event;
854 : usec_t usec;
855 : int r;
856 :
857 0 : assert(manager);
858 :
859 0 : if (LIST_IS_EMPTY(manager->events) ||
860 0 : manager->exit || manager->stop_exec_queue)
861 0 : return;
862 :
863 0 : assert_se(sd_event_now(manager->event, CLOCK_MONOTONIC, &usec) >= 0);
864 : /* check for changed config, every 3 seconds at most */
865 0 : if (manager->last_usec == 0 ||
866 0 : usec - manager->last_usec > 3 * USEC_PER_SEC) {
867 0 : if (udev_rules_check_timestamp(manager->rules) ||
868 0 : udev_builtin_validate())
869 0 : manager_reload(manager);
870 :
871 0 : manager->last_usec = usec;
872 : }
873 :
874 0 : r = event_source_disable(manager->kill_workers_event);
875 0 : if (r < 0)
876 0 : log_warning_errno(r, "Failed to disable event source for cleaning up idle workers, ignoring: %m");
877 :
878 0 : udev_builtin_init();
879 :
880 0 : if (!manager->rules) {
881 0 : r = udev_rules_new(&manager->rules, arg_resolve_name_timing);
882 0 : if (r < 0) {
883 0 : log_warning_errno(r, "Failed to read udev rules: %m");
884 0 : return;
885 : }
886 : }
887 :
888 0 : LIST_FOREACH(event, event, manager->events) {
889 0 : if (event->state != EVENT_QUEUED)
890 0 : continue;
891 :
892 : /* do not start event if parent or child event is still running */
893 0 : if (is_device_busy(manager, event) != 0)
894 0 : continue;
895 :
896 0 : event_run(manager, event);
897 : }
898 : }
899 :
900 0 : static void event_queue_cleanup(Manager *manager, enum event_state match_type) {
901 : struct event *event, *tmp;
902 :
903 0 : LIST_FOREACH_SAFE(event, event, tmp, manager->events) {
904 0 : if (match_type != EVENT_UNDEF && match_type != event->state)
905 0 : continue;
906 :
907 0 : event_free(event);
908 : }
909 0 : }
910 :
911 0 : static int on_worker(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
912 0 : Manager *manager = userdata;
913 :
914 0 : assert(manager);
915 :
916 0 : for (;;) {
917 : struct worker_message msg;
918 0 : struct iovec iovec = {
919 : .iov_base = &msg,
920 : .iov_len = sizeof(msg),
921 : };
922 : union {
923 : struct cmsghdr cmsghdr;
924 : uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
925 0 : } control = {};
926 0 : struct msghdr msghdr = {
927 : .msg_iov = &iovec,
928 : .msg_iovlen = 1,
929 : .msg_control = &control,
930 : .msg_controllen = sizeof(control),
931 : };
932 : struct cmsghdr *cmsg;
933 : ssize_t size;
934 0 : struct ucred *ucred = NULL;
935 : struct worker *worker;
936 :
937 0 : size = recvmsg(fd, &msghdr, MSG_DONTWAIT);
938 0 : if (size < 0) {
939 0 : if (errno == EINTR)
940 0 : continue;
941 0 : else if (errno == EAGAIN)
942 : /* nothing more to read */
943 0 : break;
944 :
945 0 : return log_error_errno(errno, "Failed to receive message: %m");
946 0 : } else if (size != sizeof(struct worker_message)) {
947 0 : log_warning("Ignoring worker message with invalid size %zi bytes", size);
948 0 : continue;
949 : }
950 :
951 0 : CMSG_FOREACH(cmsg, &msghdr)
952 0 : if (cmsg->cmsg_level == SOL_SOCKET &&
953 0 : cmsg->cmsg_type == SCM_CREDENTIALS &&
954 0 : cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
955 0 : ucred = (struct ucred*) CMSG_DATA(cmsg);
956 :
957 0 : if (!ucred || ucred->pid <= 0) {
958 0 : log_warning("Ignoring worker message without valid PID");
959 0 : continue;
960 : }
961 :
962 : /* lookup worker who sent the signal */
963 0 : worker = hashmap_get(manager->workers, PID_TO_PTR(ucred->pid));
964 0 : if (!worker) {
965 0 : log_debug("Worker ["PID_FMT"] returned, but is no longer tracked", ucred->pid);
966 0 : continue;
967 : }
968 :
969 0 : if (worker->state != WORKER_KILLED)
970 0 : worker->state = WORKER_IDLE;
971 :
972 : /* worker returned */
973 0 : event_free(worker->event);
974 : }
975 :
976 : /* we have free workers, try to schedule events */
977 0 : event_queue_start(manager);
978 :
979 0 : return 1;
980 : }
981 :
982 0 : static int on_uevent(sd_device_monitor *monitor, sd_device *dev, void *userdata) {
983 0 : Manager *manager = userdata;
984 : int r;
985 :
986 0 : assert(manager);
987 :
988 0 : device_ensure_usec_initialized(dev, NULL);
989 :
990 0 : r = event_queue_insert(manager, dev);
991 0 : if (r < 0) {
992 0 : log_device_error_errno(dev, r, "Failed to insert device into event queue: %m");
993 0 : return 1;
994 : }
995 :
996 : /* we have fresh events, try to schedule them */
997 0 : event_queue_start(manager);
998 :
999 0 : return 1;
1000 : }
1001 :
1002 : /* receive the udevd message from userspace */
1003 0 : static int on_ctrl_msg(struct udev_ctrl *uctrl, enum udev_ctrl_msg_type type, const union udev_ctrl_msg_value *value, void *userdata) {
1004 0 : Manager *manager = userdata;
1005 : int r;
1006 :
1007 0 : assert(value);
1008 0 : assert(manager);
1009 :
1010 0 : switch (type) {
1011 0 : case UDEV_CTRL_SET_LOG_LEVEL:
1012 0 : log_debug("Received udev control message (SET_LOG_LEVEL), setting log_priority=%i", value->intval);
1013 0 : log_set_max_level_realm(LOG_REALM_UDEV, value->intval);
1014 0 : log_set_max_level_realm(LOG_REALM_SYSTEMD, value->intval);
1015 0 : manager_kill_workers(manager);
1016 0 : break;
1017 0 : case UDEV_CTRL_STOP_EXEC_QUEUE:
1018 0 : log_debug("Received udev control message (STOP_EXEC_QUEUE)");
1019 0 : manager->stop_exec_queue = true;
1020 0 : break;
1021 0 : case UDEV_CTRL_START_EXEC_QUEUE:
1022 0 : log_debug("Received udev control message (START_EXEC_QUEUE)");
1023 0 : manager->stop_exec_queue = false;
1024 0 : event_queue_start(manager);
1025 0 : break;
1026 0 : case UDEV_CTRL_RELOAD:
1027 0 : log_debug("Received udev control message (RELOAD)");
1028 0 : manager_reload(manager);
1029 0 : break;
1030 0 : case UDEV_CTRL_SET_ENV: {
1031 0 : _cleanup_free_ char *key = NULL, *val = NULL, *old_key = NULL, *old_val = NULL;
1032 : const char *eq;
1033 :
1034 0 : eq = strchr(value->buf, '=');
1035 0 : if (!eq) {
1036 0 : log_error("Invalid key format '%s'", value->buf);
1037 0 : return 1;
1038 : }
1039 :
1040 0 : key = strndup(value->buf, eq - value->buf);
1041 0 : if (!key) {
1042 0 : log_oom();
1043 0 : return 1;
1044 : }
1045 :
1046 0 : old_val = hashmap_remove2(manager->properties, key, (void **) &old_key);
1047 :
1048 0 : r = hashmap_ensure_allocated(&manager->properties, &string_hash_ops);
1049 0 : if (r < 0) {
1050 0 : log_oom();
1051 0 : return 1;
1052 : }
1053 :
1054 0 : eq++;
1055 0 : if (isempty(eq)) {
1056 0 : log_debug("Received udev control message (ENV), unsetting '%s'", key);
1057 :
1058 0 : r = hashmap_put(manager->properties, key, NULL);
1059 0 : if (r < 0) {
1060 0 : log_oom();
1061 0 : return 1;
1062 : }
1063 : } else {
1064 0 : val = strdup(eq);
1065 0 : if (!val) {
1066 0 : log_oom();
1067 0 : return 1;
1068 : }
1069 :
1070 0 : log_debug("Received udev control message (ENV), setting '%s=%s'", key, val);
1071 :
1072 0 : r = hashmap_put(manager->properties, key, val);
1073 0 : if (r < 0) {
1074 0 : log_oom();
1075 0 : return 1;
1076 : }
1077 : }
1078 :
1079 0 : key = val = NULL;
1080 0 : manager_kill_workers(manager);
1081 0 : break;
1082 : }
1083 0 : case UDEV_CTRL_SET_CHILDREN_MAX:
1084 0 : if (value->intval <= 0) {
1085 0 : log_debug("Received invalid udev control message (SET_MAX_CHILDREN, %i), ignoring.", value->intval);
1086 0 : return 0;
1087 : }
1088 :
1089 0 : log_debug("Received udev control message (SET_MAX_CHILDREN), setting children_max=%i", value->intval);
1090 0 : arg_children_max = value->intval;
1091 :
1092 0 : (void) sd_notifyf(false,
1093 : "READY=1\n"
1094 : "STATUS=Processing with %u children at max", arg_children_max);
1095 0 : break;
1096 0 : case UDEV_CTRL_PING:
1097 0 : log_debug("Received udev control message (PING)");
1098 0 : break;
1099 0 : case UDEV_CTRL_EXIT:
1100 0 : log_debug("Received udev control message (EXIT)");
1101 0 : manager_exit(manager);
1102 0 : break;
1103 0 : default:
1104 0 : log_debug("Received unknown udev control message, ignoring");
1105 : }
1106 :
1107 0 : return 1;
1108 : }
1109 :
1110 0 : static int synthesize_change_one(sd_device *dev, const char *syspath) {
1111 : const char *filename;
1112 : int r;
1113 :
1114 0 : filename = strjoina(syspath, "/uevent");
1115 0 : log_device_debug(dev, "device is closed, synthesising 'change' on %s", syspath);
1116 0 : r = write_string_file(filename, "change", WRITE_STRING_FILE_DISABLE_BUFFER);
1117 0 : if (r < 0)
1118 0 : return log_device_debug_errno(dev, r, "Failed to write 'change' to %s: %m", filename);
1119 0 : return 0;
1120 : }
1121 :
1122 0 : static int synthesize_change(sd_device *dev) {
1123 : const char *subsystem, *sysname, *devname, *syspath, *devtype;
1124 : int r;
1125 :
1126 0 : r = sd_device_get_subsystem(dev, &subsystem);
1127 0 : if (r < 0)
1128 0 : return r;
1129 :
1130 0 : r = sd_device_get_sysname(dev, &sysname);
1131 0 : if (r < 0)
1132 0 : return r;
1133 :
1134 0 : r = sd_device_get_devname(dev, &devname);
1135 0 : if (r < 0)
1136 0 : return r;
1137 :
1138 0 : r = sd_device_get_syspath(dev, &syspath);
1139 0 : if (r < 0)
1140 0 : return r;
1141 :
1142 0 : r = sd_device_get_devtype(dev, &devtype);
1143 0 : if (r < 0)
1144 0 : return r;
1145 :
1146 0 : if (streq_ptr("block", subsystem) &&
1147 0 : streq_ptr("disk", devtype) &&
1148 0 : !startswith(sysname, "dm-")) {
1149 0 : _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
1150 0 : bool part_table_read = false, has_partitions = false;
1151 : sd_device *d;
1152 : int fd;
1153 :
1154 : /*
1155 : * Try to re-read the partition table. This only succeeds if
1156 : * none of the devices is busy. The kernel returns 0 if no
1157 : * partition table is found, and we will not get an event for
1158 : * the disk.
1159 : */
1160 0 : fd = open(devname, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
1161 0 : if (fd >= 0) {
1162 0 : r = flock(fd, LOCK_EX|LOCK_NB);
1163 0 : if (r >= 0)
1164 0 : r = ioctl(fd, BLKRRPART, 0);
1165 :
1166 0 : close(fd);
1167 0 : if (r >= 0)
1168 0 : part_table_read = true;
1169 : }
1170 :
1171 : /* search for partitions */
1172 0 : r = sd_device_enumerator_new(&e);
1173 0 : if (r < 0)
1174 0 : return r;
1175 :
1176 0 : r = sd_device_enumerator_allow_uninitialized(e);
1177 0 : if (r < 0)
1178 0 : return r;
1179 :
1180 0 : r = sd_device_enumerator_add_match_parent(e, dev);
1181 0 : if (r < 0)
1182 0 : return r;
1183 :
1184 0 : r = sd_device_enumerator_add_match_subsystem(e, "block", true);
1185 0 : if (r < 0)
1186 0 : return r;
1187 :
1188 0 : FOREACH_DEVICE(e, d) {
1189 : const char *t;
1190 :
1191 0 : if (sd_device_get_devtype(d, &t) < 0 ||
1192 0 : !streq("partition", t))
1193 0 : continue;
1194 :
1195 0 : has_partitions = true;
1196 0 : break;
1197 : }
1198 :
1199 : /*
1200 : * We have partitions and re-read the table, the kernel already sent
1201 : * out a "change" event for the disk, and "remove/add" for all
1202 : * partitions.
1203 : */
1204 0 : if (part_table_read && has_partitions)
1205 0 : return 0;
1206 :
1207 : /*
1208 : * We have partitions but re-reading the partition table did not
1209 : * work, synthesize "change" for the disk and all partitions.
1210 : */
1211 0 : (void) synthesize_change_one(dev, syspath);
1212 :
1213 0 : FOREACH_DEVICE(e, d) {
1214 : const char *t, *n, *s;
1215 :
1216 0 : if (sd_device_get_devtype(d, &t) < 0 ||
1217 0 : !streq("partition", t))
1218 0 : continue;
1219 :
1220 0 : if (sd_device_get_devname(d, &n) < 0 ||
1221 0 : sd_device_get_syspath(d, &s) < 0)
1222 0 : continue;
1223 :
1224 0 : (void) synthesize_change_one(dev, s);
1225 : }
1226 :
1227 : } else
1228 0 : (void) synthesize_change_one(dev, syspath);
1229 :
1230 0 : return 0;
1231 : }
1232 :
1233 0 : static int on_inotify(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1234 0 : Manager *manager = userdata;
1235 : union inotify_event_buffer buffer;
1236 : struct inotify_event *e;
1237 : ssize_t l;
1238 : int r;
1239 :
1240 0 : assert(manager);
1241 :
1242 0 : r = event_source_disable(manager->kill_workers_event);
1243 0 : if (r < 0)
1244 0 : log_warning_errno(r, "Failed to disable event source for cleaning up idle workers, ignoring: %m");
1245 :
1246 0 : l = read(fd, &buffer, sizeof(buffer));
1247 0 : if (l < 0) {
1248 0 : if (IN_SET(errno, EAGAIN, EINTR))
1249 0 : return 1;
1250 :
1251 0 : return log_error_errno(errno, "Failed to read inotify fd: %m");
1252 : }
1253 :
1254 0 : FOREACH_INOTIFY_EVENT(e, buffer, l) {
1255 0 : _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
1256 : const char *devnode;
1257 :
1258 0 : if (udev_watch_lookup(e->wd, &dev) <= 0)
1259 0 : continue;
1260 :
1261 0 : if (sd_device_get_devname(dev, &devnode) < 0)
1262 0 : continue;
1263 :
1264 0 : log_device_debug(dev, "Inotify event: %x for %s", e->mask, devnode);
1265 0 : if (e->mask & IN_CLOSE_WRITE)
1266 0 : synthesize_change(dev);
1267 0 : else if (e->mask & IN_IGNORED)
1268 0 : udev_watch_end(dev);
1269 : }
1270 :
1271 0 : return 1;
1272 : }
1273 :
1274 0 : static int on_sigterm(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
1275 0 : Manager *manager = userdata;
1276 :
1277 0 : assert(manager);
1278 :
1279 0 : manager_exit(manager);
1280 :
1281 0 : return 1;
1282 : }
1283 :
1284 0 : static int on_sighup(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
1285 0 : Manager *manager = userdata;
1286 :
1287 0 : assert(manager);
1288 :
1289 0 : manager_reload(manager);
1290 :
1291 0 : return 1;
1292 : }
1293 :
1294 0 : static int on_sigchld(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
1295 0 : Manager *manager = userdata;
1296 : int r;
1297 :
1298 0 : assert(manager);
1299 :
1300 0 : for (;;) {
1301 : pid_t pid;
1302 : int status;
1303 : struct worker *worker;
1304 :
1305 0 : pid = waitpid(-1, &status, WNOHANG);
1306 0 : if (pid <= 0)
1307 0 : break;
1308 :
1309 0 : worker = hashmap_get(manager->workers, PID_TO_PTR(pid));
1310 0 : if (!worker) {
1311 0 : log_warning("Worker ["PID_FMT"] is unknown, ignoring", pid);
1312 0 : continue;
1313 : }
1314 :
1315 0 : if (WIFEXITED(status)) {
1316 0 : if (WEXITSTATUS(status) == 0)
1317 0 : log_debug("Worker ["PID_FMT"] exited", pid);
1318 : else
1319 0 : log_warning("Worker ["PID_FMT"] exited with return code %i", pid, WEXITSTATUS(status));
1320 0 : } else if (WIFSIGNALED(status))
1321 0 : log_warning("Worker ["PID_FMT"] terminated by signal %i (%s)", pid, WTERMSIG(status), signal_to_string(WTERMSIG(status)));
1322 0 : else if (WIFSTOPPED(status)) {
1323 0 : log_info("Worker ["PID_FMT"] stopped", pid);
1324 0 : continue;
1325 0 : } else if (WIFCONTINUED(status)) {
1326 0 : log_info("Worker ["PID_FMT"] continued", pid);
1327 0 : continue;
1328 : } else
1329 0 : log_warning("Worker ["PID_FMT"] exit with status 0x%04x", pid, status);
1330 :
1331 0 : if ((!WIFEXITED(status) || WEXITSTATUS(status) != 0) && worker->event) {
1332 0 : log_device_error(worker->event->dev, "Worker ["PID_FMT"] failed", pid);
1333 :
1334 : /* delete state from disk */
1335 0 : device_delete_db(worker->event->dev);
1336 0 : device_tag_index(worker->event->dev, NULL, false);
1337 :
1338 : /* forward kernel event without amending it */
1339 0 : r = device_monitor_send_device(manager->monitor, NULL, worker->event->dev_kernel);
1340 0 : if (r < 0)
1341 0 : log_device_error_errno(worker->event->dev_kernel, r, "Failed to send back device to kernel: %m");
1342 : }
1343 :
1344 0 : worker_free(worker);
1345 : }
1346 :
1347 : /* we can start new workers, try to schedule events */
1348 0 : event_queue_start(manager);
1349 :
1350 : /* Disable unnecessary cleanup event */
1351 0 : if (hashmap_isempty(manager->workers)) {
1352 0 : r = event_source_disable(manager->kill_workers_event);
1353 0 : if (r < 0)
1354 0 : log_warning_errno(r, "Failed to disable event source for cleaning up idle workers, ignoring: %m");
1355 : }
1356 :
1357 0 : return 1;
1358 : }
1359 :
1360 0 : static int on_post(sd_event_source *s, void *userdata) {
1361 0 : Manager *manager = userdata;
1362 :
1363 0 : assert(manager);
1364 :
1365 0 : if (!LIST_IS_EMPTY(manager->events))
1366 0 : return 1;
1367 :
1368 : /* There are no pending events. Let's cleanup idle process. */
1369 :
1370 0 : if (!hashmap_isempty(manager->workers)) {
1371 : /* There are idle workers */
1372 0 : (void) event_reset_time(manager->event, &manager->kill_workers_event, CLOCK_MONOTONIC,
1373 0 : now(CLOCK_MONOTONIC) + 3 * USEC_PER_SEC, USEC_PER_SEC,
1374 : on_kill_workers_event, manager, 0, "kill-workers-event", false);
1375 0 : return 1;
1376 : }
1377 :
1378 : /* There are no idle workers. */
1379 :
1380 0 : if (manager->exit)
1381 0 : return sd_event_exit(manager->event, 0);
1382 :
1383 0 : if (manager->cgroup)
1384 : /* cleanup possible left-over processes in our cgroup */
1385 0 : (void) cg_kill(SYSTEMD_CGROUP_CONTROLLER, manager->cgroup, SIGKILL, CGROUP_IGNORE_SELF, NULL, NULL, NULL);
1386 :
1387 0 : return 1;
1388 : }
1389 :
1390 0 : static int listen_fds(int *ret_ctrl, int *ret_netlink) {
1391 0 : int ctrl_fd = -1, netlink_fd = -1;
1392 : int fd, n;
1393 :
1394 0 : assert(ret_ctrl);
1395 0 : assert(ret_netlink);
1396 :
1397 0 : n = sd_listen_fds(true);
1398 0 : if (n < 0)
1399 0 : return n;
1400 :
1401 0 : for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
1402 0 : if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1) > 0) {
1403 0 : if (ctrl_fd >= 0)
1404 0 : return -EINVAL;
1405 0 : ctrl_fd = fd;
1406 0 : continue;
1407 : }
1408 :
1409 0 : if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1) > 0) {
1410 0 : if (netlink_fd >= 0)
1411 0 : return -EINVAL;
1412 0 : netlink_fd = fd;
1413 0 : continue;
1414 : }
1415 :
1416 0 : return -EINVAL;
1417 : }
1418 :
1419 0 : *ret_ctrl = ctrl_fd;
1420 0 : *ret_netlink = netlink_fd;
1421 :
1422 0 : return 0;
1423 : }
1424 :
1425 : /*
1426 : * read the kernel command line, in case we need to get into debug mode
1427 : * udev.log_priority=<level> syslog priority
1428 : * udev.children_max=<number of workers> events are fully serialized if set to 1
1429 : * udev.exec_delay=<number of seconds> delay execution of every executed program
1430 : * udev.event_timeout=<number of seconds> seconds to wait before terminating an event
1431 : */
1432 0 : static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
1433 0 : int r = 0;
1434 :
1435 0 : assert(key);
1436 :
1437 0 : if (!value)
1438 0 : return 0;
1439 :
1440 0 : if (proc_cmdline_key_streq(key, "udev.log_priority")) {
1441 :
1442 0 : if (proc_cmdline_value_missing(key, value))
1443 0 : return 0;
1444 :
1445 0 : r = log_level_from_string(value);
1446 0 : if (r >= 0)
1447 0 : log_set_max_level(r);
1448 :
1449 0 : } else if (proc_cmdline_key_streq(key, "udev.event_timeout")) {
1450 :
1451 0 : if (proc_cmdline_value_missing(key, value))
1452 0 : return 0;
1453 :
1454 0 : r = parse_sec(value, &arg_event_timeout_usec);
1455 :
1456 0 : } else if (proc_cmdline_key_streq(key, "udev.children_max")) {
1457 :
1458 0 : if (proc_cmdline_value_missing(key, value))
1459 0 : return 0;
1460 :
1461 0 : r = safe_atou(value, &arg_children_max);
1462 :
1463 0 : } else if (proc_cmdline_key_streq(key, "udev.exec_delay")) {
1464 :
1465 0 : if (proc_cmdline_value_missing(key, value))
1466 0 : return 0;
1467 :
1468 0 : r = parse_sec(value, &arg_exec_delay_usec);
1469 :
1470 0 : } else if (startswith(key, "udev."))
1471 0 : log_warning("Unknown udev kernel command line option \"%s\", ignoring", key);
1472 :
1473 0 : if (r < 0)
1474 0 : log_warning_errno(r, "Failed to parse \"%s=%s\", ignoring: %m", key, value);
1475 :
1476 0 : return 0;
1477 : }
1478 :
1479 3 : static int help(void) {
1480 3 : _cleanup_free_ char *link = NULL;
1481 : int r;
1482 :
1483 3 : r = terminal_urlify_man("systemd-udevd.service", "8", &link);
1484 3 : if (r < 0)
1485 0 : return log_oom();
1486 :
1487 3 : printf("%s [OPTIONS...]\n\n"
1488 : "Manages devices.\n\n"
1489 : " -h --help Print this message\n"
1490 : " -V --version Print version of the program\n"
1491 : " -d --daemon Detach and run in the background\n"
1492 : " -D --debug Enable debug output\n"
1493 : " -c --children-max=INT Set maximum number of workers\n"
1494 : " -e --exec-delay=SECONDS Seconds to wait before executing RUN=\n"
1495 : " -t --event-timeout=SECONDS Seconds to wait before terminating an event\n"
1496 : " -N --resolve-names=early|late|never\n"
1497 : " When to resolve users and groups\n"
1498 : "\nSee the %s for details.\n"
1499 : , program_invocation_short_name
1500 : , link
1501 : );
1502 :
1503 3 : return 0;
1504 : }
1505 :
1506 4 : static int parse_argv(int argc, char *argv[]) {
1507 : static const struct option options[] = {
1508 : { "daemon", no_argument, NULL, 'd' },
1509 : { "debug", no_argument, NULL, 'D' },
1510 : { "children-max", required_argument, NULL, 'c' },
1511 : { "exec-delay", required_argument, NULL, 'e' },
1512 : { "event-timeout", required_argument, NULL, 't' },
1513 : { "resolve-names", required_argument, NULL, 'N' },
1514 : { "help", no_argument, NULL, 'h' },
1515 : { "version", no_argument, NULL, 'V' },
1516 : {}
1517 : };
1518 :
1519 : int c, r;
1520 :
1521 4 : assert(argc >= 0);
1522 4 : assert(argv);
1523 :
1524 4 : while ((c = getopt_long(argc, argv, "c:de:Dt:N:hV", options, NULL)) >= 0) {
1525 4 : switch (c) {
1526 :
1527 0 : case 'd':
1528 0 : arg_daemonize = true;
1529 0 : break;
1530 0 : case 'c':
1531 0 : r = safe_atou(optarg, &arg_children_max);
1532 0 : if (r < 0)
1533 0 : log_warning_errno(r, "Failed to parse --children-max= value '%s', ignoring: %m", optarg);
1534 0 : break;
1535 0 : case 'e':
1536 0 : r = parse_sec(optarg, &arg_exec_delay_usec);
1537 0 : if (r < 0)
1538 0 : log_warning_errno(r, "Failed to parse --exec-delay= value '%s', ignoring: %m", optarg);
1539 0 : break;
1540 0 : case 't':
1541 0 : r = parse_sec(optarg, &arg_event_timeout_usec);
1542 0 : if (r < 0)
1543 0 : log_warning_errno(r, "Failed to parse --event-timeout= value '%s', ignoring: %m", optarg);
1544 0 : break;
1545 0 : case 'D':
1546 0 : arg_debug = true;
1547 0 : break;
1548 0 : case 'N': {
1549 : ResolveNameTiming t;
1550 :
1551 0 : t = resolve_name_timing_from_string(optarg);
1552 0 : if (t < 0)
1553 0 : log_warning("Invalid --resolve-names= value '%s', ignoring.", optarg);
1554 : else
1555 0 : arg_resolve_name_timing = t;
1556 0 : break;
1557 : }
1558 3 : case 'h':
1559 3 : return help();
1560 0 : case 'V':
1561 0 : printf("%s\n", GIT_VERSION);
1562 0 : return 0;
1563 1 : case '?':
1564 1 : return -EINVAL;
1565 0 : default:
1566 0 : assert_not_reached("Unhandled option");
1567 :
1568 : }
1569 : }
1570 :
1571 0 : return 1;
1572 : }
1573 :
1574 0 : static int manager_new(Manager **ret, int fd_ctrl, int fd_uevent, const char *cgroup) {
1575 0 : _cleanup_(manager_freep) Manager *manager = NULL;
1576 : int r;
1577 :
1578 0 : assert(ret);
1579 :
1580 0 : manager = new(Manager, 1);
1581 0 : if (!manager)
1582 0 : return log_oom();
1583 :
1584 0 : *manager = (Manager) {
1585 : .fd_inotify = -1,
1586 : .worker_watch = { -1, -1 },
1587 : .cgroup = cgroup,
1588 : };
1589 :
1590 0 : r = udev_ctrl_new_from_fd(&manager->ctrl, fd_ctrl);
1591 0 : if (r < 0)
1592 0 : return log_error_errno(r, "Failed to initialize udev control socket: %m");
1593 :
1594 0 : r = udev_ctrl_enable_receiving(manager->ctrl);
1595 0 : if (r < 0)
1596 0 : return log_error_errno(r, "Failed to bind udev control socket: %m");
1597 :
1598 0 : r = device_monitor_new_full(&manager->monitor, MONITOR_GROUP_KERNEL, fd_uevent);
1599 0 : if (r < 0)
1600 0 : return log_error_errno(r, "Failed to initialize device monitor: %m");
1601 :
1602 0 : (void) sd_device_monitor_set_receive_buffer_size(manager->monitor, 128 * 1024 * 1024);
1603 :
1604 0 : r = device_monitor_enable_receiving(manager->monitor);
1605 0 : if (r < 0)
1606 0 : return log_error_errno(r, "Failed to bind netlink socket: %m");
1607 :
1608 0 : *ret = TAKE_PTR(manager);
1609 :
1610 0 : return 0;
1611 : }
1612 :
1613 0 : static int main_loop(Manager *manager) {
1614 : int fd_worker, r;
1615 :
1616 0 : manager->pid = getpid_cached();
1617 :
1618 : /* unnamed socket from workers to the main daemon */
1619 0 : r = socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, manager->worker_watch);
1620 0 : if (r < 0)
1621 0 : return log_error_errno(errno, "Failed to create socketpair for communicating with workers: %m");
1622 :
1623 0 : fd_worker = manager->worker_watch[READ_END];
1624 :
1625 0 : r = setsockopt_int(fd_worker, SOL_SOCKET, SO_PASSCRED, true);
1626 0 : if (r < 0)
1627 0 : return log_error_errno(r, "Failed to enable SO_PASSCRED: %m");
1628 :
1629 0 : r = udev_watch_init();
1630 0 : if (r < 0)
1631 0 : return log_error_errno(r, "Failed to create inotify descriptor: %m");
1632 0 : manager->fd_inotify = r;
1633 :
1634 0 : udev_watch_restore();
1635 :
1636 : /* block and listen to all signals on signalfd */
1637 0 : assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, SIGHUP, SIGCHLD, -1) >= 0);
1638 :
1639 0 : r = sd_event_default(&manager->event);
1640 0 : if (r < 0)
1641 0 : return log_error_errno(r, "Failed to allocate event loop: %m");
1642 :
1643 0 : r = sd_event_add_signal(manager->event, NULL, SIGINT, on_sigterm, manager);
1644 0 : if (r < 0)
1645 0 : return log_error_errno(r, "Failed to create SIGINT event source: %m");
1646 :
1647 0 : r = sd_event_add_signal(manager->event, NULL, SIGTERM, on_sigterm, manager);
1648 0 : if (r < 0)
1649 0 : return log_error_errno(r, "Failed to create SIGTERM event source: %m");
1650 :
1651 0 : r = sd_event_add_signal(manager->event, NULL, SIGHUP, on_sighup, manager);
1652 0 : if (r < 0)
1653 0 : return log_error_errno(r, "Failed to create SIGHUP event source: %m");
1654 :
1655 0 : r = sd_event_add_signal(manager->event, NULL, SIGCHLD, on_sigchld, manager);
1656 0 : if (r < 0)
1657 0 : return log_error_errno(r, "Failed to create SIGCHLD event source: %m");
1658 :
1659 0 : r = sd_event_set_watchdog(manager->event, true);
1660 0 : if (r < 0)
1661 0 : return log_error_errno(r, "Failed to create watchdog event source: %m");
1662 :
1663 0 : r = udev_ctrl_attach_event(manager->ctrl, manager->event);
1664 0 : if (r < 0)
1665 0 : return log_error_errno(r, "Failed to attach event to udev control: %m");
1666 :
1667 0 : r = udev_ctrl_start(manager->ctrl, on_ctrl_msg, manager);
1668 0 : if (r < 0)
1669 0 : return log_error_errno(r, "Failed to start device monitor: %m");
1670 :
1671 : /* This needs to be after the inotify and uevent handling, to make sure
1672 : * that the ping is send back after fully processing the pending uevents
1673 : * (including the synthetic ones we may create due to inotify events).
1674 : */
1675 0 : r = sd_event_source_set_priority(udev_ctrl_get_event_source(manager->ctrl), SD_EVENT_PRIORITY_IDLE);
1676 0 : if (r < 0)
1677 0 : return log_error_errno(r, "Failed to set IDLE event priority for udev control event source: %m");
1678 :
1679 0 : r = sd_event_add_io(manager->event, &manager->inotify_event, manager->fd_inotify, EPOLLIN, on_inotify, manager);
1680 0 : if (r < 0)
1681 0 : return log_error_errno(r, "Failed to create inotify event source: %m");
1682 :
1683 0 : r = sd_device_monitor_attach_event(manager->monitor, manager->event);
1684 0 : if (r < 0)
1685 0 : return log_error_errno(r, "Failed to attach event to device monitor: %m");
1686 :
1687 0 : r = sd_device_monitor_start(manager->monitor, on_uevent, manager);
1688 0 : if (r < 0)
1689 0 : return log_error_errno(r, "Failed to start device monitor: %m");
1690 :
1691 0 : (void) sd_event_source_set_description(sd_device_monitor_get_event_source(manager->monitor), "device-monitor");
1692 :
1693 0 : r = sd_event_add_io(manager->event, NULL, fd_worker, EPOLLIN, on_worker, manager);
1694 0 : if (r < 0)
1695 0 : return log_error_errno(r, "Failed to create worker event source: %m");
1696 :
1697 0 : r = sd_event_add_post(manager->event, NULL, on_post, manager);
1698 0 : if (r < 0)
1699 0 : return log_error_errno(r, "Failed to create post event source: %m");
1700 :
1701 0 : udev_builtin_init();
1702 :
1703 0 : r = udev_rules_new(&manager->rules, arg_resolve_name_timing);
1704 0 : if (!manager->rules)
1705 0 : return log_error_errno(r, "Failed to read udev rules: %m");
1706 :
1707 0 : r = udev_rules_apply_static_dev_perms(manager->rules);
1708 0 : if (r < 0)
1709 0 : log_error_errno(r, "Failed to apply permissions on static device nodes: %m");
1710 :
1711 0 : (void) sd_notifyf(false,
1712 : "READY=1\n"
1713 : "STATUS=Processing with %u children at max", arg_children_max);
1714 :
1715 0 : r = sd_event_loop(manager->event);
1716 0 : if (r < 0)
1717 0 : log_error_errno(r, "Event loop failed: %m");
1718 :
1719 0 : sd_notify(false,
1720 : "STOPPING=1\n"
1721 : "STATUS=Shutting down...");
1722 0 : return r;
1723 : }
1724 :
1725 4 : static int run(int argc, char *argv[]) {
1726 4 : _cleanup_free_ char *cgroup = NULL;
1727 4 : _cleanup_(manager_freep) Manager *manager = NULL;
1728 4 : int fd_ctrl = -1, fd_uevent = -1;
1729 : int r;
1730 :
1731 4 : log_set_target(LOG_TARGET_AUTO);
1732 4 : log_open();
1733 4 : udev_parse_config_full(&arg_children_max, &arg_exec_delay_usec, &arg_event_timeout_usec, &arg_resolve_name_timing);
1734 4 : log_parse_environment();
1735 4 : log_open(); /* Done again to update after reading configuration. */
1736 :
1737 4 : r = parse_argv(argc, argv);
1738 4 : if (r <= 0)
1739 4 : return r;
1740 :
1741 0 : r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, PROC_CMDLINE_STRIP_RD_PREFIX);
1742 0 : if (r < 0)
1743 0 : log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
1744 :
1745 0 : if (arg_debug) {
1746 0 : log_set_target(LOG_TARGET_CONSOLE);
1747 0 : log_set_max_level(LOG_DEBUG);
1748 : }
1749 :
1750 0 : log_set_max_level_realm(LOG_REALM_SYSTEMD, log_get_max_level());
1751 :
1752 0 : r = must_be_root();
1753 0 : if (r < 0)
1754 0 : return r;
1755 :
1756 0 : if (arg_children_max == 0) {
1757 : unsigned long cpu_limit, mem_limit;
1758 0 : unsigned long cpu_count = 1;
1759 : cpu_set_t cpu_set;
1760 :
1761 0 : if (sched_getaffinity(0, sizeof(cpu_set), &cpu_set) == 0)
1762 0 : cpu_count = CPU_COUNT(&cpu_set);
1763 :
1764 0 : cpu_limit = cpu_count * 2 + 16;
1765 0 : mem_limit = MAX(physical_memory() / (128UL*1024*1024), 10U);
1766 :
1767 0 : arg_children_max = MIN(cpu_limit, mem_limit);
1768 0 : arg_children_max = MIN(WORKER_NUM_MAX, arg_children_max);
1769 :
1770 0 : log_debug("Set children_max to %u", arg_children_max);
1771 : }
1772 :
1773 : /* set umask before creating any file/directory */
1774 0 : r = chdir("/");
1775 0 : if (r < 0)
1776 0 : return log_error_errno(errno, "Failed to change dir to '/': %m");
1777 :
1778 0 : umask(022);
1779 :
1780 0 : r = mac_selinux_init();
1781 0 : if (r < 0)
1782 0 : return log_error_errno(r, "Could not initialize labelling: %m");
1783 :
1784 0 : r = mkdir_errno_wrapper("/run/udev", 0755);
1785 0 : if (r < 0 && r != -EEXIST)
1786 0 : return log_error_errno(r, "Failed to create /run/udev: %m");
1787 :
1788 0 : dev_setup(NULL, UID_INVALID, GID_INVALID);
1789 :
1790 0 : if (getppid() == 1 && sd_booted() > 0) {
1791 : /* Get our own cgroup, we regularly kill everything udev has left behind.
1792 : * We only do this on systemd systems, and only if we are directly spawned
1793 : * by PID1. Otherwise we are not guaranteed to have a dedicated cgroup. */
1794 0 : r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &cgroup);
1795 0 : if (r < 0) {
1796 0 : if (IN_SET(r, -ENOENT, -ENOMEDIUM))
1797 0 : log_debug_errno(r, "Dedicated cgroup not found: %m");
1798 : else
1799 0 : log_warning_errno(r, "Failed to get cgroup: %m");
1800 : }
1801 : }
1802 :
1803 0 : r = listen_fds(&fd_ctrl, &fd_uevent);
1804 0 : if (r < 0)
1805 0 : return log_error_errno(r, "Failed to listen on fds: %m");
1806 :
1807 0 : r = manager_new(&manager, fd_ctrl, fd_uevent, cgroup);
1808 0 : if (r < 0)
1809 0 : return log_error_errno(r, "Failed to create manager: %m");
1810 :
1811 0 : if (arg_daemonize) {
1812 : pid_t pid;
1813 :
1814 0 : log_info("Starting version " GIT_VERSION);
1815 :
1816 : /* connect /dev/null to stdin, stdout, stderr */
1817 0 : if (log_get_max_level() < LOG_DEBUG) {
1818 0 : r = make_null_stdio();
1819 0 : if (r < 0)
1820 0 : log_warning_errno(r, "Failed to redirect standard streams to /dev/null: %m");
1821 : }
1822 :
1823 0 : pid = fork();
1824 0 : if (pid < 0)
1825 0 : return log_error_errno(errno, "Failed to fork daemon: %m");
1826 0 : if (pid > 0)
1827 : /* parent */
1828 0 : return 0;
1829 :
1830 : /* child */
1831 0 : (void) setsid();
1832 :
1833 0 : r = set_oom_score_adjust(-1000);
1834 0 : if (r < 0)
1835 0 : log_debug_errno(r, "Failed to adjust OOM score, ignoring: %m");
1836 : }
1837 :
1838 0 : return main_loop(manager);
1839 : }
1840 :
1841 4 : DEFINE_MAIN_FUNCTION(run);
|