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