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