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