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