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