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