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