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