1 /*
2 * Copyright (C) 2004-2012 Kay Sievers <kay@vrfy.org>
3 * Copyright (C) 2004 Chris Friesen <chris_friesen@sympatico.ca>
4 * Copyright (C) 2009 Canonical Ltd.
5 * Copyright (C) 2009 Scott James Remnant <scott@netsplit.com>
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <stddef.h>
22 #include <signal.h>
23 #include <unistd.h>
24 #include <errno.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <stdbool.h>
28 #include <string.h>
29 #include <ctype.h>
30 #include <fcntl.h>
31 #include <time.h>
32 #include <getopt.h>
33 #include <dirent.h>
34 #include <sys/file.h>
35 #include <sys/time.h>
36 #include <sys/prctl.h>
37 #include <sys/socket.h>
38 #include <sys/un.h>
39 #include <sys/signalfd.h>
40 #include <sys/epoll.h>
41 #include <sys/mount.h>
42 #include <poll.h>
43 #include <sys/wait.h>
44 #include <sys/stat.h>
45 #include <sys/ioctl.h>
46 #include <sys/inotify.h>
47 #include <sys/utsname.h>
48 #include <sys/sysmacros.h>
49
50 #include "udev.h"
51 #include "udev-util.h"
52 #include "def.h"
53 #include "dev-setup.h"
54 #include "fileio.h"
55 #include "hashmap.h"
56
57 static struct udev_rules *rules;
58 static struct udev_ctrl *udev_ctrl;
59 static struct udev_ctrl_connection *udev_ctrl_conn;
60 static struct udev_monitor *monitor;
61 static int worker_watch[2] = { -1, -1 };
62 static int fd_signal = -1;
63 static int fd_ep = -1;
64 static int fd_inotify = -1;
65 static bool stop_exec_queue;
66 static bool reload;
67 static bool arg_debug = false;
68 static int arg_daemonize = false;
69 static int arg_resolve_names = 1;
70 static unsigned arg_children_max;
71 static int arg_exec_delay;
72 static usec_t arg_event_timeout_usec = 180 * USEC_PER_SEC;
73 static usec_t arg_event_timeout_warn_usec = 180 * USEC_PER_SEC / 3;
74 static sigset_t sigmask_orig;
75 static UDEV_LIST(event_list);
76 Hashmap *workers;
77 static struct udev_list properties_list;
78 static bool udev_exit;
79
80 enum event_state {
81 EVENT_UNDEF,
82 EVENT_QUEUED,
83 EVENT_RUNNING,
84 };
85
86 struct event {
87 struct udev_list_node node;
88 struct udev *udev;
89 struct udev_device *dev;
90 struct udev_device *dev_kernel;
91 struct worker *worker;
92 enum event_state state;
93 unsigned long long int delaying_seqnum;
94 unsigned long long int seqnum;
95 const char *devpath;
96 size_t devpath_len;
97 const char *devpath_old;
98 dev_t devnum;
99 int ifindex;
100 bool is_block;
101 usec_t start_usec;
102 bool warned;
103 };
104
node_to_event(struct udev_list_node * node)105 static inline struct event *node_to_event(struct udev_list_node *node) {
106 return container_of(node, struct event, node);
107 }
108
109 static void event_queue_cleanup(struct udev *udev, enum event_state type);
110
111 enum worker_state {
112 WORKER_UNDEF,
113 WORKER_RUNNING,
114 WORKER_IDLE,
115 WORKER_KILLED,
116 };
117
118 struct worker {
119 struct udev_list_node node;
120 struct udev *udev;
121 int refcount;
122 pid_t pid;
123 struct udev_monitor *monitor;
124 enum worker_state state;
125 struct event *event;
126 };
127
128 /* passed from worker to main process */
129 struct worker_message {
130 };
131
event_free(struct event * event)132 static void event_free(struct event *event) {
133 if (!event)
134 return;
135
136 udev_list_node_remove(&event->node);
137 udev_device_unref(event->dev);
138 udev_device_unref(event->dev_kernel);
139
140 if (event->worker)
141 event->worker->event = NULL;
142
143 free(event);
144 }
145
worker_free(struct worker * worker)146 static void worker_free(struct worker *worker) {
147 if (!worker)
148 return;
149
150 hashmap_remove(workers, UINT_TO_PTR(worker->pid));
151 udev_monitor_unref(worker->monitor);
152 udev_unref(worker->udev);
153 event_free(worker->event);
154
155 free(worker);
156 }
157
workers_free(void)158 static void workers_free(void) {
159 struct worker *worker;
160 Iterator i;
161
162 HASHMAP_FOREACH(worker, workers, i)
163 worker_free(worker);
164
165 hashmap_free(workers);
166 workers = NULL;
167 }
168
worker_new(struct worker ** ret,struct udev * udev,struct udev_monitor * worker_monitor,pid_t pid)169 static int worker_new(struct worker **ret, struct udev *udev, struct udev_monitor *worker_monitor, pid_t pid) {
170 _cleanup_free_ struct worker *worker = NULL;
171 int r;
172
173 assert(ret);
174 assert(udev);
175 assert(worker_monitor);
176 assert(pid > 1);
177
178 worker = new0(struct worker, 1);
179 if (!worker)
180 return -ENOMEM;
181
182 worker->refcount = 1;
183 worker->udev = udev_ref(udev);
184 /* close monitor, but keep address around */
185 udev_monitor_disconnect(worker_monitor);
186 worker->monitor = udev_monitor_ref(worker_monitor);
187 worker->pid = pid;
188
189 r = hashmap_ensure_allocated(&workers, NULL);
190 if (r < 0)
191 return r;
192
193 r = hashmap_put(workers, UINT_TO_PTR(pid), worker);
194 if (r < 0)
195 return r;
196
197 *ret = worker;
198 worker = NULL;
199
200 return 0;
201 }
202
worker_attach_event(struct worker * worker,struct event * event)203 static void worker_attach_event(struct worker *worker, struct event *event) {
204 assert(worker);
205 assert(event);
206 assert(!event->worker);
207 assert(!worker->event);
208
209 worker->state = WORKER_RUNNING;
210 worker->event = event;
211 event->state = EVENT_RUNNING;
212 event->start_usec = now(CLOCK_MONOTONIC);
213 event->warned = false;
214 event->worker = worker;
215 }
216
worker_send_message(int fd)217 static int worker_send_message(int fd) {
218 struct worker_message message = {};
219
220 return loop_write(fd, &message, sizeof(message), false);
221 }
222
worker_spawn(struct event * event)223 static void worker_spawn(struct event *event) {
224 struct udev *udev = event->udev;
225 _cleanup_udev_monitor_unref_ struct udev_monitor *worker_monitor = NULL;
226 pid_t pid;
227
228 /* listen for new events */
229 worker_monitor = udev_monitor_new_from_netlink(udev, NULL);
230 if (worker_monitor == NULL)
231 return;
232 /* allow the main daemon netlink address to send devices to the worker */
233 udev_monitor_allow_unicast_sender(worker_monitor, monitor);
234 udev_monitor_enable_receiving(worker_monitor);
235
236 pid = fork();
237 switch (pid) {
238 case 0: {
239 struct udev_device *dev = NULL;
240 int fd_monitor;
241 struct epoll_event ep_signal, ep_monitor;
242 sigset_t mask;
243 int r = 0;
244
245 /* take initial device from queue */
246 dev = event->dev;
247 event->dev = NULL;
248
249 workers_free();
250 event_queue_cleanup(udev, EVENT_UNDEF);
251 udev_monitor_unref(monitor);
252 udev_ctrl_unref(udev_ctrl);
253 close(fd_signal);
254 close(fd_ep);
255 close(worker_watch[READ_END]);
256
257 sigfillset(&mask);
258 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
259 if (fd_signal < 0) {
260 r = log_error_errno(errno, "error creating signalfd %m");
261 goto out;
262 }
263
264 fd_ep = epoll_create1(EPOLL_CLOEXEC);
265 if (fd_ep < 0) {
266 r = log_error_errno(errno, "error creating epoll fd: %m");
267 goto out;
268 }
269
270 memzero(&ep_signal, sizeof(struct epoll_event));
271 ep_signal.events = EPOLLIN;
272 ep_signal.data.fd = fd_signal;
273
274 fd_monitor = udev_monitor_get_fd(worker_monitor);
275 memzero(&ep_monitor, sizeof(struct epoll_event));
276 ep_monitor.events = EPOLLIN;
277 ep_monitor.data.fd = fd_monitor;
278
279 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
280 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_monitor, &ep_monitor) < 0) {
281 r = log_error_errno(errno, "fail to add fds to epoll: %m");
282 goto out;
283 }
284
285 /* request TERM signal if parent exits */
286 prctl(PR_SET_PDEATHSIG, SIGTERM);
287
288 /* reset OOM score, we only protect the main daemon */
289 write_string_file("/proc/self/oom_score_adj", "0");
290
291 for (;;) {
292 struct udev_event *udev_event;
293 int fd_lock = -1;
294
295 log_debug("seq %llu running", udev_device_get_seqnum(dev));
296 udev_event = udev_event_new(dev);
297 if (udev_event == NULL) {
298 r = -ENOMEM;
299 goto out;
300 }
301
302 /* needed for SIGCHLD/SIGTERM in spawn() */
303 udev_event->fd_signal = fd_signal;
304
305 if (arg_exec_delay > 0)
306 udev_event->exec_delay = arg_exec_delay;
307
308 /*
309 * Take a shared lock on the device node; this establishes
310 * a concept of device "ownership" to serialize device
311 * access. External processes holding an exclusive lock will
312 * cause udev to skip the event handling; in the case udev
313 * acquired the lock, the external process can block until
314 * udev has finished its event handling.
315 */
316 if (!streq_ptr(udev_device_get_action(dev), "remove") &&
317 streq_ptr("block", udev_device_get_subsystem(dev)) &&
318 !startswith(udev_device_get_sysname(dev), "dm-") &&
319 !startswith(udev_device_get_sysname(dev), "md")) {
320 struct udev_device *d = dev;
321
322 if (streq_ptr("partition", udev_device_get_devtype(d)))
323 d = udev_device_get_parent(d);
324
325 if (d) {
326 fd_lock = open(udev_device_get_devnode(d), O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
327 if (fd_lock >= 0 && flock(fd_lock, LOCK_SH|LOCK_NB) < 0) {
328 log_debug_errno(errno, "Unable to flock(%s), skipping event handling: %m", udev_device_get_devnode(d));
329 fd_lock = safe_close(fd_lock);
330 r = -EAGAIN;
331 goto skip;
332 }
333 }
334 }
335
336 /* apply rules, create node, symlinks */
337 udev_event_execute_rules(udev_event,
338 arg_event_timeout_usec, arg_event_timeout_warn_usec,
339 &properties_list,
340 rules,
341 &sigmask_orig);
342
343 udev_event_execute_run(udev_event,
344 arg_event_timeout_usec, arg_event_timeout_warn_usec,
345 &sigmask_orig);
346
347 /* apply/restore inotify watch */
348 if (udev_event->inotify_watch) {
349 udev_watch_begin(udev, dev);
350 udev_device_update_db(dev);
351 }
352
353 safe_close(fd_lock);
354
355 /* send processed event back to libudev listeners */
356 udev_monitor_send_device(worker_monitor, NULL, dev);
357
358 skip:
359 log_debug("seq %llu processed", udev_device_get_seqnum(dev));
360
361 /* send udevd the result of the event execution */
362 r = worker_send_message(worker_watch[WRITE_END]);
363 if (r < 0)
364 log_error_errno(r, "failed to send result of seq %llu to main daemon: %m",
365 udev_device_get_seqnum(dev));
366
367 udev_device_unref(dev);
368 dev = NULL;
369
370 if (udev_event->sigterm) {
371 udev_event_unref(udev_event);
372 goto out;
373 }
374
375 udev_event_unref(udev_event);
376
377 /* wait for more device messages from main udevd, or term signal */
378 while (dev == NULL) {
379 struct epoll_event ev[4];
380 int fdcount;
381 int i;
382
383 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), -1);
384 if (fdcount < 0) {
385 if (errno == EINTR)
386 continue;
387 r = log_error_errno(errno, "failed to poll: %m");
388 goto out;
389 }
390
391 for (i = 0; i < fdcount; i++) {
392 if (ev[i].data.fd == fd_monitor && ev[i].events & EPOLLIN) {
393 dev = udev_monitor_receive_device(worker_monitor);
394 break;
395 } else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN) {
396 struct signalfd_siginfo fdsi;
397 ssize_t size;
398
399 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
400 if (size != sizeof(struct signalfd_siginfo))
401 continue;
402 switch (fdsi.ssi_signo) {
403 case SIGTERM:
404 goto out;
405 }
406 }
407 }
408 }
409 }
410 out:
411 udev_device_unref(dev);
412 safe_close(fd_signal);
413 safe_close(fd_ep);
414 close(fd_inotify);
415 close(worker_watch[WRITE_END]);
416 udev_rules_unref(rules);
417 udev_builtin_exit(udev);
418 udev_unref(udev);
419 log_close();
420 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
421 }
422 case -1:
423 event->state = EVENT_QUEUED;
424 log_error_errno(errno, "fork of child failed: %m");
425 break;
426 default:
427 {
428 struct worker *worker;
429 int r;
430
431 r = worker_new(&worker, udev, worker_monitor, pid);
432 if (r < 0)
433 return;
434
435 worker_attach_event(worker, event);
436
437 log_debug("seq %llu forked new worker ["PID_FMT"]", udev_device_get_seqnum(event->dev), pid);
438 break;
439 }
440 }
441 }
442
event_run(struct event * event)443 static void event_run(struct event *event) {
444 struct worker *worker;
445 Iterator i;
446
447 HASHMAP_FOREACH(worker, workers, i) {
448 ssize_t count;
449
450 if (worker->state != WORKER_IDLE)
451 continue;
452
453 count = udev_monitor_send_device(monitor, worker->monitor, event->dev);
454 if (count < 0) {
455 log_error_errno(errno, "worker ["PID_FMT"] did not accept message %zi (%m), kill it",
456 worker->pid, count);
457 kill(worker->pid, SIGKILL);
458 worker->state = WORKER_KILLED;
459 continue;
460 }
461 worker_attach_event(worker, event);
462 return;
463 }
464
465 if (hashmap_size(workers) >= arg_children_max) {
466 if (arg_children_max > 1)
467 log_debug("maximum number (%i) of children reached", hashmap_size(workers));
468 return;
469 }
470
471 /* start new worker and pass initial device */
472 worker_spawn(event);
473 }
474
event_queue_insert(struct udev_device * dev)475 static int event_queue_insert(struct udev_device *dev) {
476 struct event *event;
477
478 event = new0(struct event, 1);
479 if (event == NULL)
480 return -1;
481
482 event->udev = udev_device_get_udev(dev);
483 event->dev = dev;
484 event->dev_kernel = udev_device_shallow_clone(dev);
485 udev_device_copy_properties(event->dev_kernel, dev);
486 event->seqnum = udev_device_get_seqnum(dev);
487 event->devpath = udev_device_get_devpath(dev);
488 event->devpath_len = strlen(event->devpath);
489 event->devpath_old = udev_device_get_devpath_old(dev);
490 event->devnum = udev_device_get_devnum(dev);
491 event->is_block = streq("block", udev_device_get_subsystem(dev));
492 event->ifindex = udev_device_get_ifindex(dev);
493
494 log_debug("seq %llu queued, '%s' '%s'", udev_device_get_seqnum(dev),
495 udev_device_get_action(dev), udev_device_get_subsystem(dev));
496
497 event->state = EVENT_QUEUED;
498 udev_list_node_append(&event->node, &event_list);
499 return 0;
500 }
501
worker_kill(void)502 static void worker_kill(void) {
503 struct worker *worker;
504 Iterator i;
505
506 HASHMAP_FOREACH(worker, workers, i) {
507 if (worker->state == WORKER_KILLED)
508 continue;
509
510 worker->state = WORKER_KILLED;
511 kill(worker->pid, SIGTERM);
512 }
513 }
514
515 /* lookup event for identical, parent, child device */
is_devpath_busy(struct event * event)516 static bool is_devpath_busy(struct event *event) {
517 struct udev_list_node *loop;
518 size_t common;
519
520 /* check if queue contains events we depend on */
521 udev_list_node_foreach(loop, &event_list) {
522 struct event *loop_event = node_to_event(loop);
523
524 /* we already found a later event, earlier can not block us, no need to check again */
525 if (loop_event->seqnum < event->delaying_seqnum)
526 continue;
527
528 /* event we checked earlier still exists, no need to check again */
529 if (loop_event->seqnum == event->delaying_seqnum)
530 return true;
531
532 /* found ourself, no later event can block us */
533 if (loop_event->seqnum >= event->seqnum)
534 break;
535
536 /* check major/minor */
537 if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
538 return true;
539
540 /* check network device ifindex */
541 if (event->ifindex != 0 && event->ifindex == loop_event->ifindex)
542 return true;
543
544 /* check our old name */
545 if (event->devpath_old != NULL && streq(loop_event->devpath, event->devpath_old)) {
546 event->delaying_seqnum = loop_event->seqnum;
547 return true;
548 }
549
550 /* compare devpath */
551 common = MIN(loop_event->devpath_len, event->devpath_len);
552
553 /* one devpath is contained in the other? */
554 if (memcmp(loop_event->devpath, event->devpath, common) != 0)
555 continue;
556
557 /* identical device event found */
558 if (loop_event->devpath_len == event->devpath_len) {
559 /* devices names might have changed/swapped in the meantime */
560 if (major(event->devnum) != 0 && (event->devnum != loop_event->devnum || event->is_block != loop_event->is_block))
561 continue;
562 if (event->ifindex != 0 && event->ifindex != loop_event->ifindex)
563 continue;
564 event->delaying_seqnum = loop_event->seqnum;
565 return true;
566 }
567
568 /* parent device event found */
569 if (event->devpath[common] == '/') {
570 event->delaying_seqnum = loop_event->seqnum;
571 return true;
572 }
573
574 /* child device event found */
575 if (loop_event->devpath[common] == '/') {
576 event->delaying_seqnum = loop_event->seqnum;
577 return true;
578 }
579
580 /* no matching device */
581 continue;
582 }
583
584 return false;
585 }
586
event_queue_start(struct udev * udev)587 static void event_queue_start(struct udev *udev) {
588 struct udev_list_node *loop;
589
590 udev_list_node_foreach(loop, &event_list) {
591 struct event *event = node_to_event(loop);
592
593 if (event->state != EVENT_QUEUED)
594 continue;
595
596 /* do not start event if parent or child event is still running */
597 if (is_devpath_busy(event))
598 continue;
599
600 event_run(event);
601 }
602 }
603
event_queue_cleanup(struct udev * udev,enum event_state match_type)604 static void event_queue_cleanup(struct udev *udev, enum event_state match_type) {
605 struct udev_list_node *loop, *tmp;
606
607 udev_list_node_foreach_safe(loop, tmp, &event_list) {
608 struct event *event = node_to_event(loop);
609
610 if (match_type != EVENT_UNDEF && match_type != event->state)
611 continue;
612
613 event_free(event);
614 }
615 }
616
worker_returned(int fd_worker)617 static void worker_returned(int fd_worker) {
618 for (;;) {
619 struct worker_message msg;
620 struct iovec iovec;
621 union {
622 struct cmsghdr cmsghdr;
623 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
624 } control = {};
625 struct msghdr msghdr;
626 struct cmsghdr *cmsg;
627 ssize_t size;
628 struct ucred *ucred = NULL;
629 struct worker *worker;
630
631 memzero(&iovec, sizeof(struct iovec));
632 iovec.iov_base = &msg;
633 iovec.iov_len = sizeof(msg);
634
635 memzero(&msghdr, sizeof(struct msghdr));
636 msghdr.msg_iov = &iovec;
637 msghdr.msg_iovlen = 1;
638 msghdr.msg_control = &control;
639 msghdr.msg_controllen = sizeof(control);
640
641 size = recvmsg(fd_worker, &msghdr, MSG_DONTWAIT);
642 if (size < 0) {
643 if (errno == EINTR)
644 continue;
645 else if (errno == EAGAIN)
646 /* nothing more to read */
647 break;
648
649 log_error_errno(errno, "failed to receive message: %m");
650 return;
651 } else if (size != sizeof(struct worker_message)) {
652 log_warning_errno(EIO, "ignoring worker message with invalid size %zi bytes", size);
653 return;
654 }
655
656 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
657 if (cmsg->cmsg_level == SOL_SOCKET &&
658 cmsg->cmsg_type == SCM_CREDENTIALS &&
659 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
660 ucred = (struct ucred*) CMSG_DATA(cmsg);
661 }
662
663 if (!ucred || ucred->pid <= 0) {
664 log_warning_errno(EIO, "ignoring worker message without valid PID");
665 continue;
666 }
667
668 /* lookup worker who sent the signal */
669 worker = hashmap_get(workers, UINT_TO_PTR(ucred->pid));
670 if (!worker) {
671 log_debug("worker ["PID_FMT"] returned, but is no longer tracked", ucred->pid);
672 continue;
673 }
674
675 if (worker->state != WORKER_KILLED)
676 worker->state = WORKER_IDLE;
677
678 /* worker returned */
679 event_free(worker->event);
680 }
681 }
682
event_queue_update(void)683 static void event_queue_update(void) {
684 int r;
685
686 if (!udev_list_node_is_empty(&event_list)) {
687 r = touch("/data/udev/queue");
688 if (r < 0)
689 log_warning_errno(r, "could not touch /run/udev/queue: %m");
690 } else {
691 r = unlink("/data/udev/queue");
692 if (r < 0 && errno != ENOENT)
693 log_warning("could not unlink /run/udev/queue: %m");
694 }
695 }
696
697 /* receive the udevd message from userspace */
handle_ctrl_msg(struct udev_ctrl * uctrl)698 static void handle_ctrl_msg(struct udev_ctrl *uctrl) {
699 _cleanup_udev_ctrl_connection_unref_ struct udev_ctrl_connection *ctrl_conn = NULL;
700 _cleanup_udev_ctrl_msg_unref_ struct udev_ctrl_msg *ctrl_msg = NULL;
701 const char *str;
702 int i;
703
704 assert(uctrl);
705
706 ctrl_conn = udev_ctrl_get_connection(uctrl);
707 if (!ctrl_conn)
708 return;
709
710 ctrl_msg = udev_ctrl_receive_msg(ctrl_conn);
711 if (!ctrl_msg)
712 return;
713
714 i = udev_ctrl_get_set_log_level(ctrl_msg);
715 if (i >= 0) {
716 log_debug("udevd message (SET_LOG_LEVEL) received, log_priority=%i", i);
717 log_set_max_level(i);
718 worker_kill();
719 }
720
721 if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
722 log_debug("udevd message (STOP_EXEC_QUEUE) received");
723 stop_exec_queue = true;
724 }
725
726 if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
727 log_debug("udevd message (START_EXEC_QUEUE) received");
728 stop_exec_queue = false;
729 }
730
731 if (udev_ctrl_get_reload(ctrl_msg) > 0) {
732 log_debug("udevd message (RELOAD) received");
733 reload = true;
734 }
735
736 str = udev_ctrl_get_set_env(ctrl_msg);
737 if (str != NULL) {
738 char *key;
739
740 key = strdup(str);
741 if (key != NULL) {
742 char *val;
743
744 val = strchr(key, '=');
745 if (val != NULL) {
746 val[0] = '\0';
747 val = &val[1];
748 if (val[0] == '\0') {
749 log_debug("udevd message (ENV) received, unset '%s'", key);
750 udev_list_entry_add(&properties_list, key, NULL);
751 } else {
752 log_debug("udevd message (ENV) received, set '%s=%s'", key, val);
753 udev_list_entry_add(&properties_list, key, val);
754 }
755 } else {
756 log_error("wrong key format '%s'", key);
757 }
758 free(key);
759 }
760 worker_kill();
761 }
762
763 i = udev_ctrl_get_set_children_max(ctrl_msg);
764 if (i >= 0) {
765 log_debug("udevd message (SET_MAX_CHILDREN) received, children_max=%i", i);
766 arg_children_max = i;
767 }
768
769 if (udev_ctrl_get_ping(ctrl_msg) > 0) {
770 log_debug("udevd message (SYNC) received");
771 /* tell settle that we are busy or idle, this needs to be before the
772 * PING handling
773 */
774 event_queue_update();
775 }
776
777 if (udev_ctrl_get_exit(ctrl_msg) > 0) {
778 log_debug("udevd message (EXIT) received");
779 udev_exit = true;
780 /* keep reference to block the client until we exit */
781 udev_ctrl_conn = udev_ctrl_connection_ref(ctrl_conn);
782 }
783
784 return;
785 }
786
synthesize_change(struct udev_device * dev)787 static int synthesize_change(struct udev_device *dev) {
788 char filename[UTIL_PATH_SIZE];
789 int r;
790
791 if (streq_ptr("block", udev_device_get_subsystem(dev)) &&
792 streq_ptr("disk", udev_device_get_devtype(dev)) &&
793 !startswith(udev_device_get_sysname(dev), "dm-")) {
794 bool part_table_read = false;
795 bool has_partitions = false;
796 int fd;
797 struct udev *udev = udev_device_get_udev(dev);
798 _cleanup_udev_enumerate_unref_ struct udev_enumerate *e = NULL;
799 struct udev_list_entry *item;
800
801 /*
802 * Try to re-read the partition table. This only succeeds if
803 * none of the devices is busy. The kernel returns 0 if no
804 * partition table is found, and we will not get an event for
805 * the disk.
806 */
807 fd = open(udev_device_get_devnode(dev), O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
808 if (fd >= 0) {
809 r = flock(fd, LOCK_EX|LOCK_NB);
810 if (r >= 0)
811 r = ioctl(fd, BLKRRPART, 0);
812
813 close(fd);
814 if (r >= 0)
815 part_table_read = true;
816 }
817
818 /* search for partitions */
819 e = udev_enumerate_new(udev);
820 if (!e)
821 return -ENOMEM;
822
823 r = udev_enumerate_add_match_parent(e, dev);
824 if (r < 0)
825 return r;
826
827 r = udev_enumerate_add_match_subsystem(e, "block");
828 if (r < 0)
829 return r;
830
831 r = udev_enumerate_scan_devices(e);
832 if (r < 0)
833 return r;
834
835 udev_list_entry_foreach(item, udev_enumerate_get_list_entry(e)) {
836 _cleanup_udev_device_unref_ struct udev_device *d = NULL;
837
838 d = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item));
839 if (!d)
840 continue;
841
842 if (!streq_ptr("partition", udev_device_get_devtype(d)))
843 continue;
844
845 has_partitions = true;
846 break;
847 }
848
849 /*
850 * We have partitions and re-read the table, the kernel already sent
851 * out a "change" event for the disk, and "remove/add" for all
852 * partitions.
853 */
854 if (part_table_read && has_partitions)
855 return 0;
856
857 /*
858 * We have partitions but re-reading the partition table did not
859 * work, synthesize "change" for the disk and all partitions.
860 */
861 log_debug("device %s closed, synthesising 'change'", udev_device_get_devnode(dev));
862 strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
863 write_string_file(filename, "change");
864
865 udev_list_entry_foreach(item, udev_enumerate_get_list_entry(e)) {
866 _cleanup_udev_device_unref_ struct udev_device *d = NULL;
867
868 d = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item));
869 if (!d)
870 continue;
871
872 if (!streq_ptr("partition", udev_device_get_devtype(d)))
873 continue;
874
875 log_debug("device %s closed, synthesising partition '%s' 'change'",
876 udev_device_get_devnode(dev), udev_device_get_devnode(d));
877 strscpyl(filename, sizeof(filename), udev_device_get_syspath(d), "/uevent", NULL);
878 write_string_file(filename, "change");
879 }
880
881 return 0;
882 }
883
884 log_debug("device %s closed, synthesising 'change'", udev_device_get_devnode(dev));
885 strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
886 write_string_file(filename, "change");
887
888 return 0;
889 }
890
handle_inotify(struct udev * udev)891 static int handle_inotify(struct udev *udev) {
892 union inotify_event_buffer buffer;
893 struct inotify_event *e;
894 ssize_t l;
895
896 l = read(fd_inotify, &buffer, sizeof(buffer));
897 if (l < 0) {
898 if (errno == EAGAIN || errno == EINTR)
899 return 0;
900
901 return log_error_errno(errno, "Failed to read inotify fd: %m");
902 }
903
904 FOREACH_INOTIFY_EVENT(e, buffer, l) {
905 struct udev_device *dev;
906
907 dev = udev_watch_lookup(udev, e->wd);
908 if (!dev)
909 continue;
910
911 log_debug("inotify event: %x for %s", e->mask, udev_device_get_devnode(dev));
912 if (e->mask & IN_CLOSE_WRITE)
913 synthesize_change(dev);
914 else if (e->mask & IN_IGNORED)
915 udev_watch_end(udev, dev);
916
917 udev_device_unref(dev);
918 }
919
920 return 0;
921 }
922
handle_signal(struct udev * udev,int signo)923 static void handle_signal(struct udev *udev, int signo) {
924 switch (signo) {
925 case SIGINT:
926 case SIGTERM:
927 udev_exit = true;
928 break;
929 case SIGCHLD:
930 for (;;) {
931 pid_t pid;
932 int status;
933 struct worker *worker;
934
935 pid = waitpid(-1, &status, WNOHANG);
936 if (pid <= 0)
937 break;
938
939 worker = hashmap_get(workers, UINT_TO_PTR(pid));
940 if (!worker) {
941 log_warning("worker ["PID_FMT"] is unknown, ignoring", pid);
942 continue;
943 }
944
945 if (WIFEXITED(status)) {
946 if (WEXITSTATUS(status) == 0)
947 log_debug("worker ["PID_FMT"] exited", pid);
948 else
949 log_warning("worker ["PID_FMT"] exited with return code %i", pid, WEXITSTATUS(status));
950 } else if (WIFSIGNALED(status)) {
951 log_warning("worker ["PID_FMT"] terminated by signal %i (%s)",
952 pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
953 } else if (WIFSTOPPED(status)) {
954 log_info("worker ["PID_FMT"] stopped", pid);
955 break;
956 } else if (WIFCONTINUED(status)) {
957 log_info("worker ["PID_FMT"] continued", pid);
958 break;
959 } else {
960 log_warning("worker ["PID_FMT"] exit with status 0x%04x", pid, status);
961 }
962
963 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
964 if (worker->event) {
965 log_error("worker ["PID_FMT"] failed while handling '%s'", pid, worker->event->devpath);
966 /* delete state from disk */
967 udev_device_delete_db(worker->event->dev);
968 udev_device_tag_index(worker->event->dev, NULL, false);
969 /* forward kernel event without amending it */
970 udev_monitor_send_device(monitor, NULL, worker->event->dev_kernel);
971 }
972 }
973
974 worker_free(worker);
975 }
976 break;
977 case SIGHUP:
978 reload = true;
979 break;
980 }
981 }
982
983 /*
984 * read the kernel command line, in case we need to get into debug mode
985 * udev.log-priority=<level> syslog priority
986 * udev.children-max=<number of workers> events are fully serialized if set to 1
987 * udev.exec-delay=<number of seconds> delay execution of every executed program
988 * udev.event-timeout=<number of seconds> seconds to wait before terminating an event
989 */
parse_proc_cmdline_item(const char * key,const char * value)990 static int parse_proc_cmdline_item(const char *key, const char *value) {
991 int r;
992
993 assert(key);
994
995 if (!value)
996 return 0;
997
998 if (startswith(key, "rd."))
999 key += strlen("rd.");
1000
1001 if (startswith(key, "udev."))
1002 key += strlen("udev.");
1003 else
1004 return 0;
1005
1006 if (streq(key, "log-priority")) {
1007 int prio;
1008
1009 prio = util_log_priority(value);
1010 log_set_max_level(prio);
1011 } else if (streq(key, "children-max")) {
1012 r = safe_atou(value, &arg_children_max);
1013 if (r < 0)
1014 log_warning("invalid udev.children-max ignored: %s", value);
1015 } else if (streq(key, "exec-delay")) {
1016 r = safe_atoi(value, &arg_exec_delay);
1017 if (r < 0)
1018 log_warning("invalid udev.exec-delay ignored: %s", value);
1019 } else if (streq(key, "event-timeout")) {
1020 r = safe_atou64(value, &arg_event_timeout_usec);
1021 if (r < 0)
1022 log_warning("invalid udev.event-timeout ignored: %s", value);
1023 else {
1024 arg_event_timeout_usec *= USEC_PER_SEC;
1025 arg_event_timeout_warn_usec = (arg_event_timeout_usec / 3) ? : 1;
1026 }
1027 }
1028
1029 return 0;
1030 }
1031
help(void)1032 static void help(void) {
1033 printf("%s [OPTIONS...]\n\n"
1034 "Manages devices.\n\n"
1035 " -h --help Print this message\n"
1036 " -V --version Print version of the program\n"
1037 " -d --daemon Detach and run in the background\n"
1038 " -D --debug Enable debug output\n"
1039 " -c --children-max=INT Set maximum number of workers\n"
1040 " -e --exec-delay=SECONDS Seconds to wait before executing RUN=\n"
1041 " -t --event-timeout=SECONDS Seconds to wait before terminating an event\n"
1042 " -N --resolve-names=early|late|never\n"
1043 " When to resolve users and groups\n"
1044 , program_invocation_short_name);
1045 }
1046
parse_argv(int argc,char * argv[])1047 static int parse_argv(int argc, char *argv[]) {
1048 static const struct option options[] = {
1049 { "daemon", no_argument, NULL, 'd' },
1050 { "debug", no_argument, NULL, 'D' },
1051 { "children-max", required_argument, NULL, 'c' },
1052 { "exec-delay", required_argument, NULL, 'e' },
1053 { "event-timeout", required_argument, NULL, 't' },
1054 { "resolve-names", required_argument, NULL, 'N' },
1055 { "help", no_argument, NULL, 'h' },
1056 { "version", no_argument, NULL, 'V' },
1057 {}
1058 };
1059
1060 int c;
1061
1062 assert(argc >= 0);
1063 assert(argv);
1064
1065 while ((c = getopt_long(argc, argv, "c:de:Dt:N:hV", options, NULL)) >= 0) {
1066 int r;
1067
1068 switch (c) {
1069
1070 case 'd':
1071 arg_daemonize = true;
1072 break;
1073 case 'c':
1074 r = safe_atou(optarg, &arg_children_max);
1075 if (r < 0)
1076 log_warning("Invalid --children-max ignored: %s", optarg);
1077 break;
1078 case 'e':
1079 r = safe_atoi(optarg, &arg_exec_delay);
1080 if (r < 0)
1081 log_warning("Invalid --exec-delay ignored: %s", optarg);
1082 break;
1083 case 't':
1084 r = safe_atou64(optarg, &arg_event_timeout_usec);
1085 if (r < 0)
1086 log_warning("Invalid --event-timeout ignored: %s", optarg);
1087 else {
1088 arg_event_timeout_usec *= USEC_PER_SEC;
1089 arg_event_timeout_warn_usec = (arg_event_timeout_usec / 3) ? : 1;
1090 }
1091 break;
1092 case 'D':
1093 arg_debug = true;
1094 break;
1095 case 'N':
1096 if (streq(optarg, "early")) {
1097 arg_resolve_names = 1;
1098 } else if (streq(optarg, "late")) {
1099 arg_resolve_names = 0;
1100 } else if (streq(optarg, "never")) {
1101 arg_resolve_names = -1;
1102 } else {
1103 log_error("resolve-names must be early, late or never");
1104 return 0;
1105 }
1106 break;
1107 case 'h':
1108 help();
1109 return 0;
1110 case 'V':
1111 printf("%s\n", UDEV_VERSION);
1112 return 0;
1113 case '?':
1114 return -EINVAL;
1115 default:
1116 assert_not_reached("Unhandled option");
1117
1118 }
1119 }
1120
1121 return 1;
1122 }
1123
main(int argc,char * argv[])1124 int main(int argc, char *argv[]) {
1125 struct udev *udev;
1126 sigset_t mask;
1127 FILE *f;
1128 int fd_ctrl = -1;
1129 int fd_netlink = -1;
1130 int fd_worker = -1;
1131 struct epoll_event ep_ctrl = { .events = EPOLLIN };
1132 struct epoll_event ep_inotify = { .events = EPOLLIN };
1133 struct epoll_event ep_signal = { .events = EPOLLIN };
1134 struct epoll_event ep_netlink = { .events = EPOLLIN };
1135 struct epoll_event ep_worker = { .events = EPOLLIN };
1136 int r = 0, one = 1;
1137
1138 udev = udev_new();
1139 if (!udev) {
1140 r = log_error_errno(errno, "could not allocate udev context: %m");
1141 goto exit;
1142 }
1143
1144 log_set_target(LOG_TARGET_AUTO);
1145 log_open();
1146
1147 r = parse_argv(argc, argv);
1148 if (r <= 0)
1149 goto exit;
1150
1151 r = parse_proc_cmdline(parse_proc_cmdline_item);
1152 if (r < 0)
1153 log_warning_errno(r, "failed to parse kernel command line, ignoring: %m");
1154
1155 if (arg_debug) {
1156 log_set_target(LOG_TARGET_CONSOLE);
1157 log_set_max_level(LOG_DEBUG);
1158 }
1159
1160 if (getuid() != 0) {
1161 r = log_error_errno(EPERM, "root privileges required");
1162 goto exit;
1163 }
1164
1165 r = mac_selinux_init("/dev");
1166 if (r < 0) {
1167 log_error_errno(r, "could not initialize labelling: %m");
1168 goto exit;
1169 }
1170
1171 /* set umask before creating any file/directory */
1172 r = chdir("/");
1173 if (r < 0) {
1174 r = log_error_errno(errno, "could not change dir to /: %m");
1175 goto exit;
1176 }
1177
1178 umask(022);
1179
1180 udev_list_init(udev, &properties_list, true);
1181
1182 r = mkdir(UDEV_ROOT_RUN "/udev", 0755);
1183 if (r < 0 && errno != EEXIST) {
1184 r = log_error_errno(errno, "could not create " UDEV_ROOT_RUN "/udev: %m");
1185 goto exit;
1186 }
1187
1188 dev_setup(NULL, UID_INVALID, GID_INVALID);
1189
1190 /* before opening new files, make sure std{in,out,err} fds are in a sane state */
1191 if (arg_daemonize) {
1192 int fd;
1193
1194 fd = open("/dev/null", O_RDWR);
1195 if (fd >= 0) {
1196 if (write(STDOUT_FILENO, 0, 0) < 0)
1197 dup2(fd, STDOUT_FILENO);
1198 if (write(STDERR_FILENO, 0, 0) < 0)
1199 dup2(fd, STDERR_FILENO);
1200 if (fd > STDERR_FILENO)
1201 close(fd);
1202 } else {
1203 log_error("cannot open /dev/null");
1204 }
1205 }
1206
1207 /* open control and netlink socket */
1208 udev_ctrl = udev_ctrl_new(udev);
1209 if (!udev_ctrl) {
1210 r = log_error_errno(EINVAL, "error initializing udev control socket");
1211 goto exit;
1212 }
1213 fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
1214
1215 monitor = udev_monitor_new_from_netlink(udev, "kernel");
1216 if (!monitor) {
1217 r = log_error_errno(EINVAL, "error initializing netlink socket");
1218 goto exit;
1219 }
1220 fd_netlink = udev_monitor_get_fd(monitor);
1221
1222 if (udev_monitor_enable_receiving(monitor) < 0) {
1223 r = log_error_errno(EINVAL, "error binding netlink socket");
1224 goto exit;
1225 }
1226
1227 if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
1228 r = log_error_errno(EINVAL, "error binding udev control socket");
1229 goto exit;
1230 }
1231
1232 udev_monitor_set_receive_buffer_size(monitor, 128 * 1024 * 1024);
1233
1234 log_info("starting version " VERSION);
1235
1236 udev_builtin_init(udev);
1237
1238 rules = udev_rules_new(udev, arg_resolve_names);
1239 if (!rules) {
1240 r = log_error_errno(ENOMEM, "error reading rules");
1241 goto exit;
1242 }
1243
1244 r = udev_rules_apply_static_dev_perms(rules);
1245 if (r < 0)
1246 log_error_errno(r, "failed to apply permissions on static device nodes: %m");
1247
1248 if (arg_daemonize) {
1249 pid_t pid;
1250
1251 pid = fork();
1252 switch (pid) {
1253 case 0:
1254 break;
1255 case -1:
1256 r = log_error_errno(errno, "fork of daemon failed: %m");
1257 goto exit;
1258 default:
1259 mac_selinux_finish();
1260 log_close();
1261 _exit(EXIT_SUCCESS);
1262 }
1263
1264 setsid();
1265
1266 write_string_file("/proc/self/oom_score_adj", "-1000");
1267 }
1268
1269 if (arg_children_max == 0) {
1270 cpu_set_t cpu_set;
1271
1272 arg_children_max = 8;
1273
1274 if (sched_getaffinity(0, sizeof (cpu_set), &cpu_set) == 0) {
1275 arg_children_max += CPU_COUNT(&cpu_set) * 2;
1276 }
1277 }
1278 log_debug("set children_max to %u", arg_children_max);
1279
1280 udev_list_node_init(&event_list);
1281
1282 f = fopen("/dev/kmsg", "w");
1283 if (f != NULL) {
1284 fprintf(f, "<30>udevd[%u]: starting eudev-" VERSION "\n", getpid());
1285 fclose(f);
1286 }
1287
1288 if (!arg_debug) {
1289 int fd;
1290
1291 fd = open("/dev/null", O_RDWR);
1292 if (fd >= 0) {
1293 dup2(fd, STDIN_FILENO);
1294 dup2(fd, STDOUT_FILENO);
1295 dup2(fd, STDERR_FILENO);
1296 close(fd);
1297 }
1298 }
1299
1300 fd_inotify = udev_watch_init(udev);
1301 if (fd_inotify < 0) {
1302 r = log_error_errno(ENOMEM, "error initializing inotify");
1303 goto exit;
1304 }
1305 /* watch rules.d paths for changes */
1306 inotify_add_watch(fd_inotify, UDEV_RULES_DIR,
1307 IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1308 inotify_add_watch(fd_inotify, UDEV_CONF_DIR "/rules.d",
1309 IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1310
1311 if (access(UDEV_ROOT_RUN "/udev/rules.d", F_OK) < 0) {
1312 udev_mkdir_p(UDEV_ROOT_RUN "/udev/rules.d", 0755);
1313 }
1314 inotify_add_watch(fd_inotify, UDEV_ROOT_RUN "/udev/rules.d",
1315 IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
1316
1317 udev_watch_restore(udev);
1318
1319 /* block and listen to all signals on signalfd */
1320 sigfillset(&mask);
1321 sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
1322 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
1323 if (fd_signal < 0) {
1324 r = log_error_errno(errno, "error creating signalfd");
1325 goto exit;
1326 }
1327
1328 /* unnamed socket from workers to the main daemon */
1329 if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
1330 r = log_error_errno(errno, "error creating socketpair");
1331 goto exit;
1332 }
1333 fd_worker = worker_watch[READ_END];
1334
1335 r = setsockopt(fd_worker, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
1336 if (r < 0)
1337 return log_error_errno(errno, "could not enable SO_PASSCRED: %m");
1338
1339 ep_ctrl.data.fd = fd_ctrl;
1340 ep_inotify.data.fd = fd_inotify;
1341 ep_signal.data.fd = fd_signal;
1342 ep_netlink.data.fd = fd_netlink;
1343 ep_worker.data.fd = fd_worker;
1344
1345 fd_ep = epoll_create1(EPOLL_CLOEXEC);
1346 if (fd_ep < 0) {
1347 log_error_errno(errno, "error creating epoll fd: %m");
1348 goto exit;
1349 }
1350 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_ctrl, &ep_ctrl) < 0 ||
1351 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_inotify, &ep_inotify) < 0 ||
1352 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
1353 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_netlink, &ep_netlink) < 0 ||
1354 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_worker, &ep_worker) < 0) {
1355 log_error_errno(errno, "fail to add fds to epoll: %m");
1356 goto exit;
1357 }
1358
1359 for (;;) {
1360 static usec_t last_usec;
1361 struct epoll_event ev[8];
1362 int fdcount;
1363 int timeout;
1364 bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
1365 int i;
1366
1367 if (udev_exit) {
1368 /* close sources of new events and discard buffered events */
1369 if (fd_ctrl >= 0) {
1370 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
1371 fd_ctrl = -1;
1372 }
1373 if (monitor != NULL) {
1374 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
1375 udev_monitor_unref(monitor);
1376 monitor = NULL;
1377 }
1378 if (fd_inotify >= 0) {
1379 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
1380 close(fd_inotify);
1381 fd_inotify = -1;
1382 }
1383
1384 /* discard queued events and kill workers */
1385 event_queue_cleanup(udev, EVENT_QUEUED);
1386 worker_kill();
1387
1388 /* exit after all has cleaned up */
1389 if (udev_list_node_is_empty(&event_list) && hashmap_isempty(workers))
1390 break;
1391
1392 /* timeout at exit for workers to finish */
1393 timeout = 30 * MSEC_PER_SEC;
1394 } else if (udev_list_node_is_empty(&event_list) && hashmap_isempty(workers)) {
1395 /* we are idle */
1396 timeout = -1;
1397 } else {
1398 /* kill idle or hanging workers */
1399 timeout = 3 * MSEC_PER_SEC;
1400 }
1401
1402 /* tell settle that we are busy or idle */
1403 event_queue_update();
1404
1405 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
1406 if (fdcount < 0)
1407 continue;
1408
1409 if (fdcount == 0) {
1410 struct worker *worker;
1411 Iterator j;
1412
1413 /* timeout */
1414 if (udev_exit) {
1415 log_error("timeout, giving up waiting for workers to finish");
1416 break;
1417 }
1418
1419 /* kill idle workers */
1420 if (udev_list_node_is_empty(&event_list)) {
1421 log_debug("cleanup idle workers");
1422 worker_kill();
1423 }
1424
1425 /* check for hanging events */
1426 HASHMAP_FOREACH(worker, workers, j) {
1427 struct event *event = worker->event;
1428 usec_t ts;
1429
1430 if (worker->state != WORKER_RUNNING)
1431 continue;
1432
1433 assert(event);
1434
1435 ts = now(CLOCK_MONOTONIC);
1436
1437 if ((ts - event->start_usec) > arg_event_timeout_warn_usec) {
1438 if ((ts - event->start_usec) > arg_event_timeout_usec) {
1439 log_error("worker ["PID_FMT"] %s timeout; kill it", worker->pid, event->devpath);
1440 kill(worker->pid, SIGKILL);
1441 worker->state = WORKER_KILLED;
1442
1443 log_error("seq %llu '%s' killed", udev_device_get_seqnum(event->dev), event->devpath);
1444 } else if (!event->warned) {
1445 log_warning("worker ["PID_FMT"] %s is taking a long time", worker->pid, event->devpath);
1446 event->warned = true;
1447 }
1448 }
1449 }
1450
1451 }
1452
1453 is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
1454 for (i = 0; i < fdcount; i++) {
1455 if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
1456 is_worker = true;
1457 else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
1458 is_netlink = true;
1459 else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
1460 is_signal = true;
1461 else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
1462 is_inotify = true;
1463 else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
1464 is_ctrl = true;
1465 }
1466
1467 /* check for changed config, every 3 seconds at most */
1468 if ((now(CLOCK_MONOTONIC) - last_usec) > 3 * USEC_PER_SEC) {
1469 if (udev_rules_check_timestamp(rules))
1470 reload = true;
1471 if (udev_builtin_validate(udev))
1472 reload = true;
1473
1474 last_usec = now(CLOCK_MONOTONIC);
1475 }
1476
1477 /* reload requested, HUP signal received, rules changed, builtin changed */
1478 if (reload) {
1479 worker_kill();
1480 rules = udev_rules_unref(rules);
1481 udev_builtin_exit(udev);
1482 reload = false;
1483 }
1484
1485 /* event has finished */
1486 if (is_worker)
1487 worker_returned(fd_worker);
1488
1489 if (is_netlink) {
1490 struct udev_device *dev;
1491
1492 dev = udev_monitor_receive_device(monitor);
1493 if (dev) {
1494 udev_device_ensure_usec_initialized(dev, NULL);
1495 if (event_queue_insert(dev) < 0)
1496 udev_device_unref(dev);
1497 }
1498 }
1499
1500 /* start new events */
1501 if (!udev_list_node_is_empty(&event_list) && !udev_exit && !stop_exec_queue) {
1502 udev_builtin_init(udev);
1503 if (rules == NULL)
1504 rules = udev_rules_new(udev, arg_resolve_names);
1505 if (rules != NULL)
1506 event_queue_start(udev);
1507 }
1508
1509 if (is_signal) {
1510 struct signalfd_siginfo fdsi;
1511 ssize_t size;
1512
1513 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
1514 if (size == sizeof(struct signalfd_siginfo))
1515 handle_signal(udev, fdsi.ssi_signo);
1516 }
1517
1518 /* we are shutting down, the events below are not handled anymore */
1519 if (udev_exit)
1520 continue;
1521
1522 /* device node watch */
1523 if (is_inotify) {
1524 handle_inotify(udev);
1525
1526 /*
1527 * settle might be waiting on us to determine the queue
1528 * state. If we just handled an inotify event, we might have
1529 * generated a "change" event, but we won't have queued up
1530 * the resultant uevent yet.
1531 *
1532 * Before we go ahead and potentially tell settle that the
1533 * queue is empty, lets loop one more time to update the
1534 * queue state again before deciding.
1535 */
1536 continue;
1537 }
1538
1539 /*
1540 * This needs to be after the inotify handling, to make sure,
1541 * that the ping is send back after the possibly generated
1542 * "change" events by the inotify device node watch.
1543 */
1544 if (is_ctrl)
1545 handle_ctrl_msg(udev_ctrl);
1546 }
1547
1548 exit:
1549 udev_ctrl_cleanup(udev_ctrl);
1550 unlink(UDEV_ROOT_RUN "/udev/queue");
1551
1552 if (fd_ep >= 0)
1553 close(fd_ep);
1554 workers_free();
1555 event_queue_cleanup(udev, EVENT_UNDEF);
1556 udev_rules_unref(rules);
1557 udev_builtin_exit(udev);
1558 if (fd_signal >= 0)
1559 close(fd_signal);
1560 if (worker_watch[READ_END] >= 0)
1561 close(worker_watch[READ_END]);
1562 if (worker_watch[WRITE_END] >= 0)
1563 close(worker_watch[WRITE_END]);
1564 udev_monitor_unref(monitor);
1565 udev_ctrl_connection_unref(udev_ctrl_conn);
1566 udev_ctrl_unref(udev_ctrl);
1567 mac_selinux_finish();
1568 udev_unref(udev);
1569 log_close();
1570 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1571 }
1572