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