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