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