chiark / gitweb /
selinux: unify systemd and udev code
[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                 mkdir_parents(filename, 0755);
861                 label_context_set(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                 label_context_clear();
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         struct stdlinks {
875                 const char *link;
876                 const char *target;
877         };
878         static const struct stdlinks stdlinks[] = {
879                 { "/dev/core", "/proc/kcore" },
880                 { "/dev/fd", "/proc/self/fd" },
881                 { "/dev/stdin", "/proc/self/fd/0" },
882                 { "/dev/stdout", "/proc/self/fd/1" },
883                 { "/dev/stderr", "/proc/self/fd/2" },
884         };
885         unsigned int i;
886
887         for (i = 0; i < ELEMENTSOF(stdlinks); i++) {
888                 struct stat sb;
889
890                 if (stat(stdlinks[i].target, &sb) == 0) {
891                         label_context_set(stdlinks[i].link, S_IFLNK);
892                         if (symlink(stdlinks[i].target, stdlinks[i].link) < 0 && errno == EEXIST)
893                                 utimensat(AT_FDCWD, stdlinks[i].link, NULL, AT_SYMLINK_NOFOLLOW);
894                         label_context_clear();
895                 }
896         }
897 }
898
899 static int mem_size_mb(void)
900 {
901         FILE *f;
902         char buf[4096];
903         long int memsize = -1;
904
905         f = fopen("/proc/meminfo", "r");
906         if (f == NULL)
907                 return -1;
908
909         while (fgets(buf, sizeof(buf), f) != NULL) {
910                 long int value;
911
912                 if (sscanf(buf, "MemTotal: %ld kB", &value) == 1) {
913                         memsize = value / 1024;
914                         break;
915                 }
916         }
917
918         fclose(f);
919         return memsize;
920 }
921
922 static int convert_db(struct udev *udev)
923 {
924         char filename[UTIL_PATH_SIZE];
925         FILE *f;
926         struct udev_enumerate *udev_enumerate;
927         struct udev_list_entry *list_entry;
928
929         /* current database */
930         if (access("/run/udev/data", F_OK) >= 0)
931                 return 0;
932
933         /* make sure we do not get here again */
934         mkdir_parents("/run/udev/data", 0755);
935         mkdir(filename, 0755);
936
937         /* old database */
938         util_strscpyl(filename, sizeof(filename), "/dev/.udev/db", NULL);
939         if (access(filename, F_OK) < 0)
940                 return 0;
941
942         f = fopen("/dev/kmsg", "w");
943         if (f != NULL) {
944                 fprintf(f, "<30>udevd[%u]: converting old udev database\n", getpid());
945                 fclose(f);
946         }
947
948         udev_enumerate = udev_enumerate_new(udev);
949         if (udev_enumerate == NULL)
950                 return -1;
951         udev_enumerate_scan_devices(udev_enumerate);
952         udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(udev_enumerate)) {
953                 struct udev_device *device;
954
955                 device = udev_device_new_from_syspath(udev, udev_list_entry_get_name(list_entry));
956                 if (device == NULL)
957                         continue;
958
959                 /* try to find the old database for devices without a current one */
960                 if (udev_device_read_db(device, NULL) < 0) {
961                         bool have_db;
962                         const char *id;
963                         struct stat stats;
964                         char devpath[UTIL_PATH_SIZE];
965                         char from[UTIL_PATH_SIZE];
966
967                         have_db = false;
968
969                         /* find database in old location */
970                         id = udev_device_get_id_filename(device);
971                         util_strscpyl(from, sizeof(from), "/dev/.udev/db/", id, NULL);
972                         if (lstat(from, &stats) == 0) {
973                                 if (!have_db) {
974                                         udev_device_read_db(device, from);
975                                         have_db = true;
976                                 }
977                                 unlink(from);
978                         }
979
980                         /* find old database with $subsys:$sysname name */
981                         util_strscpyl(from, sizeof(from), "/dev/.udev/db/",
982                                       udev_device_get_subsystem(device), ":", udev_device_get_sysname(device), NULL);
983                         if (lstat(from, &stats) == 0) {
984                                 if (!have_db) {
985                                         udev_device_read_db(device, from);
986                                         have_db = true;
987                                 }
988                                 unlink(from);
989                         }
990
991                         /* find old database with the encoded devpath name */
992                         util_path_encode(udev_device_get_devpath(device), devpath, sizeof(devpath));
993                         util_strscpyl(from, sizeof(from), "/dev/.udev/db/", devpath, NULL);
994                         if (lstat(from, &stats) == 0) {
995                                 if (!have_db) {
996                                         udev_device_read_db(device, from);
997                                         have_db = true;
998                                 }
999                                 unlink(from);
1000                         }
1001
1002                         /* write out new database */
1003                         if (have_db)
1004                                 udev_device_update_db(device);
1005                 }
1006                 udev_device_unref(device);
1007         }
1008         udev_enumerate_unref(udev_enumerate);
1009         return 0;
1010 }
1011
1012 static int systemd_fds(struct udev *udev, int *rctrl, int *rnetlink)
1013 {
1014         int ctrl = -1, netlink = -1;
1015         int fd, n;
1016
1017         n = sd_listen_fds(true);
1018         if (n <= 0)
1019                 return -1;
1020
1021         for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
1022                 if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1)) {
1023                         if (ctrl >= 0)
1024                                 return -1;
1025                         ctrl = fd;
1026                         continue;
1027                 }
1028
1029                 if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1)) {
1030                         if (netlink >= 0)
1031                                 return -1;
1032                         netlink = fd;
1033                         continue;
1034                 }
1035
1036                 return -1;
1037         }
1038
1039         if (ctrl < 0 || netlink < 0)
1040                 return -1;
1041
1042         log_debug("ctrl=%i netlink=%i\n", ctrl, netlink);
1043         *rctrl = ctrl;
1044         *rnetlink = netlink;
1045         return 0;
1046 }
1047
1048 int main(int argc, char *argv[])
1049 {
1050         struct udev *udev;
1051         FILE *f;
1052         sigset_t mask;
1053         int daemonize = false;
1054         int resolve_names = 1;
1055         static const struct option options[] = {
1056                 { "daemon", no_argument, NULL, 'd' },
1057                 { "debug", no_argument, NULL, 'D' },
1058                 { "children-max", required_argument, NULL, 'c' },
1059                 { "exec-delay", required_argument, NULL, 'e' },
1060                 { "resolve-names", required_argument, NULL, 'N' },
1061                 { "help", no_argument, NULL, 'h' },
1062                 { "version", no_argument, NULL, 'V' },
1063                 {}
1064         };
1065         int fd_ctrl = -1;
1066         int fd_netlink = -1;
1067         int fd_worker = -1;
1068         struct epoll_event ep_ctrl, ep_inotify, ep_signal, ep_netlink, ep_worker;
1069         struct udev_ctrl_connection *ctrl_conn = NULL;
1070         int rc = 1;
1071
1072         udev = udev_new();
1073         if (udev == NULL)
1074                 goto exit;
1075
1076         log_open();
1077         log_parse_environment();
1078         udev_set_log_fn(udev, udev_main_log);
1079         log_debug("version %s\n", VERSION);
1080         label_init("/dev");
1081
1082         for (;;) {
1083                 int option;
1084
1085                 option = getopt_long(argc, argv, "c:deDtN:hV", options, NULL);
1086                 if (option == -1)
1087                         break;
1088
1089                 switch (option) {
1090                 case 'd':
1091                         daemonize = true;
1092                         break;
1093                 case 'c':
1094                         children_max = strtoul(optarg, NULL, 0);
1095                         break;
1096                 case 'e':
1097                         exec_delay = strtoul(optarg, NULL, 0);
1098                         break;
1099                 case 'D':
1100                         debug = true;
1101                         log_set_max_level(LOG_DEBUG);
1102                         udev_set_log_priority(udev, LOG_INFO);
1103                         break;
1104                 case 'N':
1105                         if (strcmp (optarg, "early") == 0) {
1106                                 resolve_names = 1;
1107                         } else if (strcmp (optarg, "late") == 0) {
1108                                 resolve_names = 0;
1109                         } else if (strcmp (optarg, "never") == 0) {
1110                                 resolve_names = -1;
1111                         } else {
1112                                 fprintf(stderr, "resolve-names must be early, late or never\n");
1113                                 log_error("resolve-names must be early, late or never\n");
1114                                 goto exit;
1115                         }
1116                         break;
1117                 case 'h':
1118                         printf("Usage: udevd OPTIONS\n"
1119                                "  --daemon\n"
1120                                "  --debug\n"
1121                                "  --children-max=<maximum number of workers>\n"
1122                                "  --exec-delay=<seconds to wait before executing RUN=>\n"
1123                                "  --resolve-names=early|late|never\n"
1124                                "  --version\n"
1125                                "  --help\n"
1126                                "\n");
1127                         goto exit;
1128                 case 'V':
1129                         printf("%s\n", VERSION);
1130                         goto exit;
1131                 default:
1132                         goto exit;
1133                 }
1134         }
1135
1136         /*
1137          * read the kernel commandline, in case we need to get into debug mode
1138          *   udev.log-priority=<level>              syslog priority
1139          *   udev.children-max=<number of workers>  events are fully serialized if set to 1
1140          *
1141          */
1142         f = fopen("/proc/cmdline", "r");
1143         if (f != NULL) {
1144                 char cmdline[4096];
1145
1146                 if (fgets(cmdline, sizeof(cmdline), f) != NULL) {
1147                         char *pos;
1148
1149                         pos = strstr(cmdline, "udev.log-priority=");
1150                         if (pos != NULL) {
1151                                 pos += strlen("udev.log-priority=");
1152                                 udev_set_log_priority(udev, util_log_priority(pos));
1153                         }
1154
1155                         pos = strstr(cmdline, "udev.children-max=");
1156                         if (pos != NULL) {
1157                                 pos += strlen("udev.children-max=");
1158                                 children_max = strtoul(pos, NULL, 0);
1159                         }
1160
1161                         pos = strstr(cmdline, "udev.exec-delay=");
1162                         if (pos != NULL) {
1163                                 pos += strlen("udev.exec-delay=");
1164                                 exec_delay = strtoul(pos, NULL, 0);
1165                         }
1166                 }
1167                 fclose(f);
1168         }
1169
1170         if (getuid() != 0) {
1171                 fprintf(stderr, "root privileges required\n");
1172                 log_error("root privileges required\n");
1173                 goto exit;
1174         }
1175
1176         /* set umask before creating any file/directory */
1177         chdir("/");
1178         umask(022);
1179
1180         mkdir("/run/udev", 0755);
1181
1182         /* create standard links, copy static nodes, create nodes from modules */
1183         static_dev_create_links(udev);
1184         static_dev_create_from_modules(udev);
1185
1186         /* before opening new files, make sure std{in,out,err} fds are in a sane state */
1187         if (daemonize) {
1188                 int fd;
1189
1190                 fd = open("/dev/null", O_RDWR);
1191                 if (fd >= 0) {
1192                         if (write(STDOUT_FILENO, 0, 0) < 0)
1193                                 dup2(fd, STDOUT_FILENO);
1194                         if (write(STDERR_FILENO, 0, 0) < 0)
1195                                 dup2(fd, STDERR_FILENO);
1196                         if (fd > STDERR_FILENO)
1197                                 close(fd);
1198                 } else {
1199                         fprintf(stderr, "cannot open /dev/null\n");
1200                         log_error("cannot open /dev/null\n");
1201                 }
1202         }
1203
1204         if (systemd_fds(udev, &fd_ctrl, &fd_netlink) >= 0) {
1205                 /* get control and netlink socket from from systemd */
1206                 udev_ctrl = udev_ctrl_new_from_fd(udev, fd_ctrl);
1207                 if (udev_ctrl == NULL) {
1208                         log_error("error taking over udev control socket");
1209                         rc = 1;
1210                         goto exit;
1211                 }
1212
1213                 monitor = udev_monitor_new_from_netlink_fd(udev, "kernel", fd_netlink);
1214                 if (monitor == NULL) {
1215                         log_error("error taking over netlink socket\n");
1216                         rc = 3;
1217                         goto exit;
1218                 }
1219
1220                 /* get our own cgroup, we regularly kill everything udev has left behind */
1221                 if (cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 0, &udev_cgroup) < 0)
1222                         udev_cgroup = NULL;
1223         } else {
1224                 /* open control and netlink socket */
1225                 udev_ctrl = udev_ctrl_new(udev);
1226                 if (udev_ctrl == NULL) {
1227                         fprintf(stderr, "error initializing udev control socket");
1228                         log_error("error initializing udev control socket");
1229                         rc = 1;
1230                         goto exit;
1231                 }
1232                 fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
1233
1234                 monitor = udev_monitor_new_from_netlink(udev, "kernel");
1235                 if (monitor == NULL) {
1236                         fprintf(stderr, "error initializing netlink socket\n");
1237                         log_error("error initializing netlink socket\n");
1238                         rc = 3;
1239                         goto exit;
1240                 }
1241                 fd_netlink = udev_monitor_get_fd(monitor);
1242         }
1243
1244         if (udev_monitor_enable_receiving(monitor) < 0) {
1245                 fprintf(stderr, "error binding netlink socket\n");
1246                 log_error("error binding netlink socket\n");
1247                 rc = 3;
1248                 goto exit;
1249         }
1250
1251         if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
1252                 fprintf(stderr, "error binding udev control socket\n");
1253                 log_error("error binding udev control socket\n");
1254                 rc = 1;
1255                 goto exit;
1256         }
1257
1258         udev_monitor_set_receive_buffer_size(monitor, 128*1024*1024);
1259
1260         /* create queue file before signalling 'ready', to make sure we block 'settle' */
1261         udev_queue_export = udev_queue_export_new(udev);
1262         if (udev_queue_export == NULL) {
1263                 log_error("error creating queue file\n");
1264                 goto exit;
1265         }
1266
1267         if (daemonize) {
1268                 pid_t pid;
1269                 int fd;
1270
1271                 pid = fork();
1272                 switch (pid) {
1273                 case 0:
1274                         break;
1275                 case -1:
1276                         log_error("fork of daemon failed: %m\n");
1277                         rc = 4;
1278                         goto exit;
1279                 default:
1280                         rc = EXIT_SUCCESS;
1281                         goto exit_daemonize;
1282                 }
1283
1284                 setsid();
1285
1286                 fd = open("/proc/self/oom_score_adj", O_RDWR);
1287                 if (fd < 0) {
1288                         /* Fallback to old interface */
1289                         fd = open("/proc/self/oom_adj", O_RDWR);
1290                         if (fd < 0) {
1291                                 log_error("error disabling OOM: %m\n");
1292                         } else {
1293                                 /* OOM_DISABLE == -17 */
1294                                 write(fd, "-17", 3);
1295                                 close(fd);
1296                         }
1297                 } else {
1298                         write(fd, "-1000", 5);
1299                         close(fd);
1300                 }
1301         } else {
1302                 sd_notify(1, "READY=1");
1303         }
1304
1305         f = fopen("/dev/kmsg", "w");
1306         if (f != NULL) {
1307                 fprintf(f, "<30>udevd[%u]: starting version " VERSION "\n", getpid());
1308                 fclose(f);
1309         }
1310
1311         if (!debug) {
1312                 int fd;
1313
1314                 fd = open("/dev/null", O_RDWR);
1315                 if (fd >= 0) {
1316                         dup2(fd, STDIN_FILENO);
1317                         dup2(fd, STDOUT_FILENO);
1318                         dup2(fd, STDERR_FILENO);
1319                         close(fd);
1320                 }
1321         }
1322
1323         fd_inotify = udev_watch_init(udev);
1324         if (fd_inotify < 0) {
1325                 fprintf(stderr, "error initializing inotify\n");
1326                 log_error("error initializing inotify\n");
1327                 rc = 4;
1328                 goto exit;
1329         }
1330         udev_watch_restore(udev);
1331
1332         /* block and listen to all signals on signalfd */
1333         sigfillset(&mask);
1334         sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
1335         fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
1336         if (fd_signal < 0) {
1337                 fprintf(stderr, "error creating signalfd\n");
1338                 log_error("error creating signalfd\n");
1339                 rc = 5;
1340                 goto exit;
1341         }
1342
1343         /* unnamed socket from workers to the main daemon */
1344         if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
1345                 fprintf(stderr, "error creating socketpair\n");
1346                 log_error("error creating socketpair\n");
1347                 rc = 6;
1348                 goto exit;
1349         }
1350         fd_worker = worker_watch[READ_END];
1351
1352         udev_builtin_init(udev);
1353
1354         rules = udev_rules_new(udev, resolve_names);
1355         if (rules == NULL) {
1356                 log_error("error reading rules\n");
1357                 goto exit;
1358         }
1359
1360         memset(&ep_ctrl, 0, sizeof(struct epoll_event));
1361         ep_ctrl.events = EPOLLIN;
1362         ep_ctrl.data.fd = fd_ctrl;
1363
1364         memset(&ep_inotify, 0, sizeof(struct epoll_event));
1365         ep_inotify.events = EPOLLIN;
1366         ep_inotify.data.fd = fd_inotify;
1367
1368         memset(&ep_signal, 0, sizeof(struct epoll_event));
1369         ep_signal.events = EPOLLIN;
1370         ep_signal.data.fd = fd_signal;
1371
1372         memset(&ep_netlink, 0, sizeof(struct epoll_event));
1373         ep_netlink.events = EPOLLIN;
1374         ep_netlink.data.fd = fd_netlink;
1375
1376         memset(&ep_worker, 0, sizeof(struct epoll_event));
1377         ep_worker.events = EPOLLIN;
1378         ep_worker.data.fd = fd_worker;
1379
1380         fd_ep = epoll_create1(EPOLL_CLOEXEC);
1381         if (fd_ep < 0) {
1382                 log_error("error creating epoll fd: %m\n");
1383                 goto exit;
1384         }
1385         if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_ctrl, &ep_ctrl) < 0 ||
1386             epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_inotify, &ep_inotify) < 0 ||
1387             epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
1388             epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_netlink, &ep_netlink) < 0 ||
1389             epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_worker, &ep_worker) < 0) {
1390                 log_error("fail to add fds to epoll: %m\n");
1391                 goto exit;
1392         }
1393
1394         /* if needed, convert old database from earlier udev version */
1395         convert_db(udev);
1396
1397         if (children_max <= 0) {
1398                 int memsize = mem_size_mb();
1399
1400                 /* set value depending on the amount of RAM */
1401                 if (memsize > 0)
1402                         children_max = 128 + (memsize / 8);
1403                 else
1404                         children_max = 128;
1405         }
1406         log_debug("set children_max to %u\n", children_max);
1407
1408         udev_rules_apply_static_dev_perms(rules);
1409
1410         udev_list_node_init(&event_list);
1411         udev_list_node_init(&worker_list);
1412
1413         for (;;) {
1414                 static unsigned long long last_usec;
1415                 struct epoll_event ev[8];
1416                 int fdcount;
1417                 int timeout;
1418                 bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
1419                 int i;
1420
1421                 if (udev_exit) {
1422                         /* close sources of new events and discard buffered events */
1423                         if (fd_ctrl >= 0) {
1424                                 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
1425                                 fd_ctrl = -1;
1426                         }
1427                         if (monitor != NULL) {
1428                                 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
1429                                 udev_monitor_unref(monitor);
1430                                 monitor = NULL;
1431                         }
1432                         if (fd_inotify >= 0) {
1433                                 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
1434                                 close(fd_inotify);
1435                                 fd_inotify = -1;
1436                         }
1437
1438                         /* discard queued events and kill workers */
1439                         event_queue_cleanup(udev, EVENT_QUEUED);
1440                         worker_kill(udev);
1441
1442                         /* exit after all has cleaned up */
1443                         if (udev_list_node_is_empty(&event_list) && udev_list_node_is_empty(&worker_list))
1444                                 break;
1445
1446                         /* timeout at exit for workers to finish */
1447                         timeout = 30 * 1000;
1448                 } else if (udev_list_node_is_empty(&event_list) && !children) {
1449                         /* we are idle */
1450                         timeout = -1;
1451
1452                         /* cleanup possible left-over processes in our cgroup */
1453                         if (udev_cgroup)
1454                                 cg_kill(SYSTEMD_CGROUP_CONTROLLER, udev_cgroup, SIGKILL, false, true, NULL);
1455                 } else {
1456                         /* kill idle or hanging workers */
1457                         timeout = 3 * 1000;
1458                 }
1459                 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
1460                 if (fdcount < 0)
1461                         continue;
1462
1463                 if (fdcount == 0) {
1464                         struct udev_list_node *loop;
1465
1466                         /* timeout */
1467                         if (udev_exit) {
1468                                 log_error("timeout, giving up waiting for workers to finish\n");
1469                                 break;
1470                         }
1471
1472                         /* kill idle workers */
1473                         if (udev_list_node_is_empty(&event_list)) {
1474                                 log_debug("cleanup idle workers\n");
1475                                 worker_kill(udev);
1476                         }
1477
1478                         /* check for hanging events */
1479                         udev_list_node_foreach(loop, &worker_list) {
1480                                 struct worker *worker = node_to_worker(loop);
1481
1482                                 if (worker->state != WORKER_RUNNING)
1483                                         continue;
1484
1485                                 if ((now_usec() - worker->event_start_usec) > 30 * 1000 * 1000) {
1486                                         log_error("worker [%u] %s timeout; kill it\n", worker->pid,
1487                                             worker->event ? worker->event->devpath : "<idle>");
1488                                         kill(worker->pid, SIGKILL);
1489                                         worker->state = WORKER_KILLED;
1490                                         /* drop reference taken for state 'running' */
1491                                         worker_unref(worker);
1492                                         if (worker->event) {
1493                                                 log_error("seq %llu '%s' killed\n",
1494                                                           udev_device_get_seqnum(worker->event->dev), worker->event->devpath);
1495                                                 worker->event->exitcode = -64;
1496                                                 event_queue_delete(worker->event, true);
1497                                                 worker->event = NULL;
1498                                         }
1499                                 }
1500                         }
1501
1502                 }
1503
1504                 is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
1505                 for (i = 0; i < fdcount; i++) {
1506                         if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
1507                                 is_worker = true;
1508                         else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
1509                                 is_netlink = true;
1510                         else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
1511                                 is_signal = true;
1512                         else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
1513                                 is_inotify = true;
1514                         else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
1515                                 is_ctrl = true;
1516                 }
1517
1518                 /* check for changed config, every 3 seconds at most */
1519                 if ((now_usec() - last_usec) > 3 * 1000 * 1000) {
1520                         if (udev_rules_check_timestamp(rules))
1521                                 reload = true;
1522                         if (udev_builtin_validate(udev))
1523                                 reload = true;
1524
1525                         last_usec = now_usec();
1526                 }
1527
1528                 /* reload requested, HUP signal received, rules changed, builtin changed */
1529                 if (reload) {
1530                         worker_kill(udev);
1531                         rules = udev_rules_unref(rules);
1532                         udev_builtin_exit(udev);
1533                         reload = 0;
1534                 }
1535
1536                 /* event has finished */
1537                 if (is_worker)
1538                         worker_returned(fd_worker);
1539
1540                 if (is_netlink) {
1541                         struct udev_device *dev;
1542
1543                         dev = udev_monitor_receive_device(monitor);
1544                         if (dev != NULL) {
1545                                 udev_device_set_usec_initialized(dev, now_usec());
1546                                 if (event_queue_insert(dev) < 0)
1547                                         udev_device_unref(dev);
1548                         }
1549                 }
1550
1551                 /* start new events */
1552                 if (!udev_list_node_is_empty(&event_list) && !udev_exit && !stop_exec_queue) {
1553                         if (rules == NULL)
1554                                 rules = udev_rules_new(udev, resolve_names);
1555                         if (rules != NULL)
1556                                 event_queue_start(udev);
1557                 }
1558
1559                 if (is_signal) {
1560                         struct signalfd_siginfo fdsi;
1561                         ssize_t size;
1562
1563                         size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
1564                         if (size == sizeof(struct signalfd_siginfo))
1565                                 handle_signal(udev, fdsi.ssi_signo);
1566                 }
1567
1568                 /* we are shutting down, the events below are not handled anymore */
1569                 if (udev_exit)
1570                         continue;
1571
1572                 /* device node watch */
1573                 if (is_inotify)
1574                         handle_inotify(udev);
1575
1576                 /*
1577                  * This needs to be after the inotify handling, to make sure,
1578                  * that the ping is send back after the possibly generated
1579                  * "change" events by the inotify device node watch.
1580                  *
1581                  * A single time we may receive a client connection which we need to
1582                  * keep open to block the client. It will be closed right before we
1583                  * exit.
1584                  */
1585                 if (is_ctrl)
1586                         ctrl_conn = handle_ctrl_msg(udev_ctrl);
1587         }
1588
1589         rc = EXIT_SUCCESS;
1590 exit:
1591         udev_queue_export_cleanup(udev_queue_export);
1592         udev_ctrl_cleanup(udev_ctrl);
1593 exit_daemonize:
1594         if (fd_ep >= 0)
1595                 close(fd_ep);
1596         worker_list_cleanup(udev);
1597         event_queue_cleanup(udev, EVENT_UNDEF);
1598         udev_rules_unref(rules);
1599         udev_builtin_exit(udev);
1600         if (fd_signal >= 0)
1601                 close(fd_signal);
1602         if (worker_watch[READ_END] >= 0)
1603                 close(worker_watch[READ_END]);
1604         if (worker_watch[WRITE_END] >= 0)
1605                 close(worker_watch[WRITE_END]);
1606         udev_monitor_unref(monitor);
1607         udev_queue_export_unref(udev_queue_export);
1608         udev_ctrl_connection_unref(ctrl_conn);
1609         udev_ctrl_unref(udev_ctrl);
1610         label_finish();
1611         udev_unref(udev);
1612         log_close();
1613         return rc;
1614 }