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