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