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