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