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