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