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