]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/udev/udevd.c
udev: always close lock file descriptor
[thirdparty/systemd.git] / src / udev / udevd.c
1 /*
2 * Copyright (C) 2004-2012 Kay Sievers <kay@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/file.h>
35 #include <sys/time.h>
36 #include <sys/prctl.h>
37 #include <sys/socket.h>
38 #include <sys/un.h>
39 #include <sys/signalfd.h>
40 #include <sys/epoll.h>
41 #include <sys/poll.h>
42 #include <sys/wait.h>
43 #include <sys/stat.h>
44 #include <sys/ioctl.h>
45 #include <sys/inotify.h>
46 #include <sys/utsname.h>
47
48 #include "udev.h"
49 #include "sd-daemon.h"
50 #include "cgroup-util.h"
51 #include "dev-setup.h"
52 #include "fileio.h"
53
54 static bool debug;
55
56 void udev_main_log(struct udev *udev, int priority,
57 const char *file, int line, const char *fn,
58 const char *format, va_list args)
59 {
60 log_metav(priority, file, line, fn, format, args);
61 }
62
63 static struct udev_rules *rules;
64 static struct udev_ctrl *udev_ctrl;
65 static struct udev_monitor *monitor;
66 static int worker_watch[2] = { -1, -1 };
67 static int fd_signal = -1;
68 static int fd_ep = -1;
69 static int fd_inotify = -1;
70 static bool stop_exec_queue;
71 static bool reload;
72 static int children;
73 static int children_max;
74 static int exec_delay;
75 static sigset_t sigmask_orig;
76 static UDEV_LIST(event_list);
77 static UDEV_LIST(worker_list);
78 static char *udev_cgroup;
79 static bool udev_exit;
80
81 enum event_state {
82 EVENT_UNDEF,
83 EVENT_QUEUED,
84 EVENT_RUNNING,
85 };
86
87 struct event {
88 struct udev_list_node node;
89 struct udev *udev;
90 struct udev_device *dev;
91 enum event_state state;
92 int exitcode;
93 unsigned long long int delaying_seqnum;
94 unsigned long long int seqnum;
95 const char *devpath;
96 size_t devpath_len;
97 const char *devpath_old;
98 dev_t devnum;
99 int ifindex;
100 bool is_block;
101 #ifdef HAVE_FIRMWARE
102 bool nodelay;
103 #endif
104 };
105
106 static inline struct event *node_to_event(struct udev_list_node *node)
107 {
108 return container_of(node, struct event, node);
109 }
110
111 static void event_queue_cleanup(struct udev *udev, enum event_state type);
112
113 enum worker_state {
114 WORKER_UNDEF,
115 WORKER_RUNNING,
116 WORKER_IDLE,
117 WORKER_KILLED,
118 };
119
120 struct worker {
121 struct udev_list_node node;
122 struct udev *udev;
123 int refcount;
124 pid_t pid;
125 struct udev_monitor *monitor;
126 enum worker_state state;
127 struct event *event;
128 usec_t event_start_usec;
129 };
130
131 /* passed from worker to main process */
132 struct worker_message {
133 pid_t pid;
134 int exitcode;
135 };
136
137 static inline struct worker *node_to_worker(struct udev_list_node *node)
138 {
139 return container_of(node, struct worker, node);
140 }
141
142 static void event_queue_delete(struct event *event)
143 {
144 udev_list_node_remove(&event->node);
145 udev_device_unref(event->dev);
146 free(event);
147 }
148
149 static struct worker *worker_ref(struct worker *worker)
150 {
151 worker->refcount++;
152 return worker;
153 }
154
155 static void worker_cleanup(struct worker *worker)
156 {
157 udev_list_node_remove(&worker->node);
158 udev_monitor_unref(worker->monitor);
159 children--;
160 free(worker);
161 }
162
163 static void worker_unref(struct worker *worker)
164 {
165 worker->refcount--;
166 if (worker->refcount > 0)
167 return;
168 log_debug("worker [%u] cleaned up", worker->pid);
169 worker_cleanup(worker);
170 }
171
172 static void worker_list_cleanup(struct udev *udev)
173 {
174 struct udev_list_node *loop, *tmp;
175
176 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
177 struct worker *worker = node_to_worker(loop);
178
179 worker_cleanup(worker);
180 }
181 }
182
183 static void worker_new(struct event *event)
184 {
185 struct udev *udev = event->udev;
186 struct worker *worker;
187 struct udev_monitor *worker_monitor;
188 pid_t pid;
189
190 /* listen for new events */
191 worker_monitor = udev_monitor_new_from_netlink(udev, NULL);
192 if (worker_monitor == NULL)
193 return;
194 /* allow the main daemon netlink address to send devices to the worker */
195 udev_monitor_allow_unicast_sender(worker_monitor, monitor);
196 udev_monitor_enable_receiving(worker_monitor);
197
198 worker = new0(struct worker, 1);
199 if (worker == NULL) {
200 udev_monitor_unref(worker_monitor);
201 return;
202 }
203 /* worker + event reference */
204 worker->refcount = 2;
205 worker->udev = udev;
206
207 pid = fork();
208 switch (pid) {
209 case 0: {
210 struct udev_device *dev = NULL;
211 int fd_monitor;
212 struct epoll_event ep_signal, ep_monitor;
213 sigset_t mask;
214 int rc = EXIT_SUCCESS;
215
216 /* take initial device from queue */
217 dev = event->dev;
218 event->dev = NULL;
219
220 free(worker);
221 worker_list_cleanup(udev);
222 event_queue_cleanup(udev, EVENT_UNDEF);
223 udev_monitor_unref(monitor);
224 udev_ctrl_unref(udev_ctrl);
225 close(fd_signal);
226 close(fd_ep);
227 close(worker_watch[READ_END]);
228
229 sigfillset(&mask);
230 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
231 if (fd_signal < 0) {
232 log_error("error creating signalfd %m");
233 rc = 2;
234 goto out;
235 }
236
237 fd_ep = epoll_create1(EPOLL_CLOEXEC);
238 if (fd_ep < 0) {
239 log_error("error creating epoll fd: %m");
240 rc = 3;
241 goto out;
242 }
243
244 memzero(&ep_signal, sizeof(struct epoll_event));
245 ep_signal.events = EPOLLIN;
246 ep_signal.data.fd = fd_signal;
247
248 fd_monitor = udev_monitor_get_fd(worker_monitor);
249 memzero(&ep_monitor, sizeof(struct epoll_event));
250 ep_monitor.events = EPOLLIN;
251 ep_monitor.data.fd = fd_monitor;
252
253 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
254 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_monitor, &ep_monitor) < 0) {
255 log_error("fail to add fds to epoll: %m");
256 rc = 4;
257 goto out;
258 }
259
260 /* request TERM signal if parent exits */
261 prctl(PR_SET_PDEATHSIG, SIGTERM);
262
263 /* reset OOM score, we only protect the main daemon */
264 write_string_file("/proc/self/oom_score_adj", "0");
265
266 for (;;) {
267 struct udev_event *udev_event;
268 struct worker_message msg;
269 int fd_lock = -1;
270 int err = 0;
271
272 log_debug("seq %llu running", udev_device_get_seqnum(dev));
273 udev_event = udev_event_new(dev);
274 if (udev_event == NULL) {
275 rc = 5;
276 goto out;
277 }
278
279 /* needed for SIGCHLD/SIGTERM in spawn() */
280 udev_event->fd_signal = fd_signal;
281
282 if (exec_delay > 0)
283 udev_event->exec_delay = exec_delay;
284
285 /*
286 * Take a "read lock" on the device node; this establishes
287 * a concept of device "ownership" to serialize device
288 * access. External processes holding a "write lock" will
289 * cause udev to skip the event handling; in the case udev
290 * acquired the lock, the external process will block until
291 * udev has finished its event handling.
292 */
293 if (streq_ptr("block", udev_device_get_subsystem(dev))) {
294 struct udev_device *d = dev;
295
296 if (streq_ptr("partition", udev_device_get_devtype(d)))
297 d = udev_device_get_parent(d);
298
299 if (d) {
300 fd_lock = open(udev_device_get_devnode(d), O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
301 if (fd_lock >= 0 && flock(fd_lock, LOCK_SH|LOCK_NB) < 0) {
302 log_debug("Unable to flock(%s), skipping event handling: %m", udev_device_get_devnode(d));
303 err = -EWOULDBLOCK;
304 fd_lock = safe_close(fd_lock);
305 goto skip;
306 }
307 }
308 }
309
310 /* apply rules, create node, symlinks */
311 udev_event_execute_rules(udev_event, rules, &sigmask_orig);
312
313 udev_event_execute_run(udev_event, &sigmask_orig);
314
315 /* apply/restore inotify watch */
316 if (udev_event->inotify_watch) {
317 udev_watch_begin(udev, dev);
318 udev_device_update_db(dev);
319 }
320
321 safe_close(fd_lock);
322
323 /* send processed event back to libudev listeners */
324 udev_monitor_send_device(worker_monitor, NULL, dev);
325
326 skip:
327 /* send udevd the result of the event execution */
328 memzero(&msg, sizeof(struct worker_message));
329 msg.exitcode = err;
330 msg.pid = getpid();
331 send(worker_watch[WRITE_END], &msg, sizeof(struct worker_message), 0);
332
333 log_debug("seq %llu processed with %i", udev_device_get_seqnum(dev), err);
334
335 udev_device_unref(dev);
336 dev = NULL;
337
338 if (udev_event->sigterm) {
339 udev_event_unref(udev_event);
340 goto out;
341 }
342
343 udev_event_unref(udev_event);
344
345 /* wait for more device messages from main udevd, or term signal */
346 while (dev == NULL) {
347 struct epoll_event ev[4];
348 int fdcount;
349 int i;
350
351 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), -1);
352 if (fdcount < 0) {
353 if (errno == EINTR)
354 continue;
355 log_error("failed to poll: %m");
356 goto out;
357 }
358
359 for (i = 0; i < fdcount; i++) {
360 if (ev[i].data.fd == fd_monitor && ev[i].events & EPOLLIN) {
361 dev = udev_monitor_receive_device(worker_monitor);
362 break;
363 } else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN) {
364 struct signalfd_siginfo fdsi;
365 ssize_t size;
366
367 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
368 if (size != sizeof(struct signalfd_siginfo))
369 continue;
370 switch (fdsi.ssi_signo) {
371 case SIGTERM:
372 goto out;
373 }
374 }
375 }
376 }
377 }
378 out:
379 udev_device_unref(dev);
380 safe_close(fd_signal);
381 safe_close(fd_ep);
382 close(fd_inotify);
383 close(worker_watch[WRITE_END]);
384 udev_rules_unref(rules);
385 udev_builtin_exit(udev);
386 udev_monitor_unref(worker_monitor);
387 udev_unref(udev);
388 log_close();
389 exit(rc);
390 }
391 case -1:
392 udev_monitor_unref(worker_monitor);
393 event->state = EVENT_QUEUED;
394 free(worker);
395 log_error("fork of child failed: %m");
396 break;
397 default:
398 /* close monitor, but keep address around */
399 udev_monitor_disconnect(worker_monitor);
400 worker->monitor = worker_monitor;
401 worker->pid = pid;
402 worker->state = WORKER_RUNNING;
403 worker->event_start_usec = now(CLOCK_MONOTONIC);
404 worker->event = event;
405 event->state = EVENT_RUNNING;
406 udev_list_node_append(&worker->node, &worker_list);
407 children++;
408 log_debug("seq %llu forked new worker [%u]", udev_device_get_seqnum(event->dev), pid);
409 break;
410 }
411 }
412
413 static void event_run(struct event *event)
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 log_error("worker [%u] did not accept message %zi (%m), kill it", 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 worker->event_start_usec = now(CLOCK_MONOTONIC);
435 event->state = EVENT_RUNNING;
436 return;
437 }
438
439 if (children >= children_max) {
440 if (children_max > 1)
441 log_debug("maximum number (%i) of children reached", children);
442 return;
443 }
444
445 /* start new worker and pass initial device */
446 worker_new(event);
447 }
448
449 static int event_queue_insert(struct udev_device *dev)
450 {
451 struct event *event;
452
453 event = new0(struct event, 1);
454 if (event == NULL)
455 return -1;
456
457 event->udev = udev_device_get_udev(dev);
458 event->dev = dev;
459 event->seqnum = udev_device_get_seqnum(dev);
460 event->devpath = udev_device_get_devpath(dev);
461 event->devpath_len = strlen(event->devpath);
462 event->devpath_old = udev_device_get_devpath_old(dev);
463 event->devnum = udev_device_get_devnum(dev);
464 event->is_block = streq("block", udev_device_get_subsystem(dev));
465 event->ifindex = udev_device_get_ifindex(dev);
466 #ifdef HAVE_FIRMWARE
467 if (streq(udev_device_get_subsystem(dev), "firmware"))
468 event->nodelay = true;
469 #endif
470
471 log_debug("seq %llu queued, '%s' '%s'", udev_device_get_seqnum(dev),
472 udev_device_get_action(dev), udev_device_get_subsystem(dev));
473
474 event->state = EVENT_QUEUED;
475 udev_list_node_append(&event->node, &event_list);
476 return 0;
477 }
478
479 static void worker_kill(struct udev *udev)
480 {
481 struct udev_list_node *loop;
482
483 udev_list_node_foreach(loop, &worker_list) {
484 struct worker *worker = node_to_worker(loop);
485
486 if (worker->state == WORKER_KILLED)
487 continue;
488
489 worker->state = WORKER_KILLED;
490 kill(worker->pid, SIGTERM);
491 }
492 }
493
494 /* lookup event for identical, parent, child device */
495 static bool is_devpath_busy(struct event *event)
496 {
497 struct udev_list_node *loop;
498 size_t common;
499
500 /* check if queue contains events we depend on */
501 udev_list_node_foreach(loop, &event_list) {
502 struct event *loop_event = node_to_event(loop);
503
504 /* we already found a later event, earlier can not block us, no need to check again */
505 if (loop_event->seqnum < event->delaying_seqnum)
506 continue;
507
508 /* event we checked earlier still exists, no need to check again */
509 if (loop_event->seqnum == event->delaying_seqnum)
510 return true;
511
512 /* found ourself, no later event can block us */
513 if (loop_event->seqnum >= event->seqnum)
514 break;
515
516 /* check major/minor */
517 if (major(event->devnum) != 0 && event->devnum == loop_event->devnum && event->is_block == loop_event->is_block)
518 return true;
519
520 /* check network device ifindex */
521 if (event->ifindex != 0 && event->ifindex == loop_event->ifindex)
522 return true;
523
524 /* check our old name */
525 if (event->devpath_old != NULL && streq(loop_event->devpath, event->devpath_old)) {
526 event->delaying_seqnum = loop_event->seqnum;
527 return true;
528 }
529
530 /* compare devpath */
531 common = MIN(loop_event->devpath_len, event->devpath_len);
532
533 /* one devpath is contained in the other? */
534 if (memcmp(loop_event->devpath, event->devpath, common) != 0)
535 continue;
536
537 /* identical device event found */
538 if (loop_event->devpath_len == event->devpath_len) {
539 /* devices names might have changed/swapped in the meantime */
540 if (major(event->devnum) != 0 && (event->devnum != loop_event->devnum || event->is_block != loop_event->is_block))
541 continue;
542 if (event->ifindex != 0 && event->ifindex != loop_event->ifindex)
543 continue;
544 event->delaying_seqnum = loop_event->seqnum;
545 return true;
546 }
547
548 #ifdef HAVE_FIRMWARE
549 /* allow to bypass the dependency tracking */
550 if (event->nodelay)
551 continue;
552 #endif
553
554 /* parent device event found */
555 if (event->devpath[common] == '/') {
556 event->delaying_seqnum = loop_event->seqnum;
557 return true;
558 }
559
560 /* child device event found */
561 if (loop_event->devpath[common] == '/') {
562 event->delaying_seqnum = loop_event->seqnum;
563 return true;
564 }
565
566 /* no matching device */
567 continue;
568 }
569
570 return false;
571 }
572
573 static void event_queue_start(struct udev *udev)
574 {
575 struct udev_list_node *loop;
576
577 udev_list_node_foreach(loop, &event_list) {
578 struct event *event = node_to_event(loop);
579
580 if (event->state != EVENT_QUEUED)
581 continue;
582
583 /* do not start event if parent or child event is still running */
584 if (is_devpath_busy(event))
585 continue;
586
587 event_run(event);
588 }
589 }
590
591 static void event_queue_cleanup(struct udev *udev, enum event_state match_type)
592 {
593 struct udev_list_node *loop, *tmp;
594
595 udev_list_node_foreach_safe(loop, tmp, &event_list) {
596 struct event *event = node_to_event(loop);
597
598 if (match_type != EVENT_UNDEF && match_type != event->state)
599 continue;
600
601 event_queue_delete(event);
602 }
603 }
604
605 static void worker_returned(int fd_worker)
606 {
607 for (;;) {
608 struct worker_message msg;
609 ssize_t size;
610 struct udev_list_node *loop;
611
612 size = recv(fd_worker, &msg, sizeof(struct worker_message), MSG_DONTWAIT);
613 if (size != sizeof(struct worker_message))
614 break;
615
616 /* lookup worker who sent the signal */
617 udev_list_node_foreach(loop, &worker_list) {
618 struct worker *worker = node_to_worker(loop);
619
620 if (worker->pid != msg.pid)
621 continue;
622
623 /* worker returned */
624 if (worker->event) {
625 worker->event->exitcode = msg.exitcode;
626 event_queue_delete(worker->event);
627 worker->event = NULL;
628 }
629 if (worker->state != WORKER_KILLED)
630 worker->state = WORKER_IDLE;
631 worker_unref(worker);
632 break;
633 }
634 }
635 }
636
637 /* receive the udevd message from userspace */
638 static struct udev_ctrl_connection *handle_ctrl_msg(struct udev_ctrl *uctrl)
639 {
640 struct udev *udev = udev_ctrl_get_udev(uctrl);
641 struct udev_ctrl_connection *ctrl_conn;
642 struct udev_ctrl_msg *ctrl_msg = NULL;
643 const char *str;
644 int i;
645
646 ctrl_conn = udev_ctrl_get_connection(uctrl);
647 if (ctrl_conn == NULL)
648 goto out;
649
650 ctrl_msg = udev_ctrl_receive_msg(ctrl_conn);
651 if (ctrl_msg == NULL)
652 goto out;
653
654 i = udev_ctrl_get_set_log_level(ctrl_msg);
655 if (i >= 0) {
656 log_debug("udevd message (SET_LOG_LEVEL) received, log_priority=%i", i);
657 log_set_max_level(i);
658 udev_set_log_priority(udev, i);
659 worker_kill(udev);
660 }
661
662 if (udev_ctrl_get_stop_exec_queue(ctrl_msg) > 0) {
663 log_debug("udevd message (STOP_EXEC_QUEUE) received");
664 stop_exec_queue = true;
665 }
666
667 if (udev_ctrl_get_start_exec_queue(ctrl_msg) > 0) {
668 log_debug("udevd message (START_EXEC_QUEUE) received");
669 stop_exec_queue = false;
670 }
671
672 if (udev_ctrl_get_reload(ctrl_msg) > 0) {
673 log_debug("udevd message (RELOAD) received");
674 reload = true;
675 }
676
677 str = udev_ctrl_get_set_env(ctrl_msg);
678 if (str != NULL) {
679 char *key;
680
681 key = strdup(str);
682 if (key != NULL) {
683 char *val;
684
685 val = strchr(key, '=');
686 if (val != NULL) {
687 val[0] = '\0';
688 val = &val[1];
689 if (val[0] == '\0') {
690 log_debug("udevd message (ENV) received, unset '%s'", key);
691 udev_add_property(udev, key, NULL);
692 } else {
693 log_debug("udevd message (ENV) received, set '%s=%s'", key, val);
694 udev_add_property(udev, key, val);
695 }
696 } else {
697 log_error("wrong key format '%s'", key);
698 }
699 free(key);
700 }
701 worker_kill(udev);
702 }
703
704 i = udev_ctrl_get_set_children_max(ctrl_msg);
705 if (i >= 0) {
706 log_debug("udevd message (SET_MAX_CHILDREN) received, children_max=%i", i);
707 children_max = i;
708 }
709
710 if (udev_ctrl_get_ping(ctrl_msg) > 0)
711 log_debug("udevd message (SYNC) received");
712
713 if (udev_ctrl_get_exit(ctrl_msg) > 0) {
714 log_debug("udevd message (EXIT) received");
715 udev_exit = true;
716 /* keep reference to block the client until we exit */
717 udev_ctrl_connection_ref(ctrl_conn);
718 }
719 out:
720 udev_ctrl_msg_unref(ctrl_msg);
721 return udev_ctrl_connection_unref(ctrl_conn);
722 }
723
724 /* read inotify messages */
725 static int handle_inotify(struct udev *udev)
726 {
727 int nbytes, pos;
728 char *buf;
729 struct inotify_event *ev;
730
731 if ((ioctl(fd_inotify, FIONREAD, &nbytes) < 0) || (nbytes <= 0))
732 return 0;
733
734 buf = malloc(nbytes);
735 if (buf == NULL) {
736 log_error("error getting buffer for inotify");
737 return -1;
738 }
739
740 nbytes = read(fd_inotify, buf, nbytes);
741
742 for (pos = 0; pos < nbytes; pos += sizeof(struct inotify_event) + ev->len) {
743 struct udev_device *dev;
744
745 ev = (struct inotify_event *)(buf + pos);
746 dev = udev_watch_lookup(udev, ev->wd);
747 if (dev != NULL) {
748 log_debug("inotify event: %x for %s", ev->mask, udev_device_get_devnode(dev));
749 if (ev->mask & IN_CLOSE_WRITE) {
750 char filename[UTIL_PATH_SIZE];
751 int fd;
752
753 log_debug("device %s closed, synthesising 'change'", udev_device_get_devnode(dev));
754 strscpyl(filename, sizeof(filename), udev_device_get_syspath(dev), "/uevent", NULL);
755 fd = open(filename, O_WRONLY|O_CLOEXEC);
756 if (fd >= 0) {
757 if (write(fd, "change", 6) < 0)
758 log_debug("error writing uevent: %m");
759 close(fd);
760 }
761 }
762 if (ev->mask & IN_IGNORED)
763 udev_watch_end(udev, dev);
764
765 udev_device_unref(dev);
766 }
767
768 }
769
770 free(buf);
771 return 0;
772 }
773
774 static void handle_signal(struct udev *udev, int signo)
775 {
776 switch (signo) {
777 case SIGINT:
778 case SIGTERM:
779 udev_exit = true;
780 break;
781 case SIGCHLD:
782 for (;;) {
783 pid_t pid;
784 int status;
785 struct udev_list_node *loop, *tmp;
786
787 pid = waitpid(-1, &status, WNOHANG);
788 if (pid <= 0)
789 break;
790
791 udev_list_node_foreach_safe(loop, tmp, &worker_list) {
792 struct worker *worker = node_to_worker(loop);
793
794 if (worker->pid != pid)
795 continue;
796 log_debug("worker [%u] exit", pid);
797
798 if (WIFEXITED(status)) {
799 if (WEXITSTATUS(status) != 0)
800 log_error("worker [%u] exit with return code %i",
801 pid, WEXITSTATUS(status));
802 } else if (WIFSIGNALED(status)) {
803 log_error("worker [%u] terminated by signal %i (%s)",
804 pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
805 } else if (WIFSTOPPED(status)) {
806 log_error("worker [%u] stopped", pid);
807 } else if (WIFCONTINUED(status)) {
808 log_error("worker [%u] continued", pid);
809 } else {
810 log_error("worker [%u] exit with status 0x%04x", pid, status);
811 }
812
813 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
814 if (worker->event) {
815 log_error("worker [%u] failed while handling '%s'",
816 pid, worker->event->devpath);
817 worker->event->exitcode = -32;
818 event_queue_delete(worker->event);
819
820 /* drop reference taken for state 'running' */
821 worker_unref(worker);
822 }
823 }
824 worker_unref(worker);
825 break;
826 }
827 }
828 break;
829 case SIGHUP:
830 reload = true;
831 break;
832 }
833 }
834
835 static int systemd_fds(struct udev *udev, int *rctrl, int *rnetlink)
836 {
837 int ctrl = -1, netlink = -1;
838 int fd, n;
839
840 n = sd_listen_fds(true);
841 if (n <= 0)
842 return -1;
843
844 for (fd = SD_LISTEN_FDS_START; fd < n + SD_LISTEN_FDS_START; fd++) {
845 if (sd_is_socket(fd, AF_LOCAL, SOCK_SEQPACKET, -1)) {
846 if (ctrl >= 0)
847 return -1;
848 ctrl = fd;
849 continue;
850 }
851
852 if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1)) {
853 if (netlink >= 0)
854 return -1;
855 netlink = fd;
856 continue;
857 }
858
859 return -1;
860 }
861
862 if (ctrl < 0 || netlink < 0)
863 return -1;
864
865 log_debug("ctrl=%i netlink=%i", ctrl, netlink);
866 *rctrl = ctrl;
867 *rnetlink = netlink;
868 return 0;
869 }
870
871 /*
872 * read the kernel commandline, in case we need to get into debug mode
873 * udev.log-priority=<level> syslog priority
874 * udev.children-max=<number of workers> events are fully serialized if set to 1
875 * udev.exec-delay=<number of seconds> delay execution of every executed program
876 */
877 static void kernel_cmdline_options(struct udev *udev)
878 {
879 _cleanup_free_ char *line = NULL;
880 char *w, *state;
881 size_t l;
882 int r;
883
884 r = proc_cmdline(&line);
885 if (r < 0)
886 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
887 if (r <= 0)
888 return;
889
890 FOREACH_WORD_QUOTED(w, l, line, state) {
891 char *s, *opt;
892
893 s = strndup(w, l);
894 if (!s)
895 break;
896
897 /* accept the same options for the initrd, prefixed with "rd." */
898 if (in_initrd() && startswith(s, "rd."))
899 opt = s + 3;
900 else
901 opt = s;
902
903 if (startswith(opt, "udev.log-priority=")) {
904 int prio;
905
906 prio = util_log_priority(opt + 18);
907 log_set_max_level(prio);
908 udev_set_log_priority(udev, prio);
909 } else if (startswith(opt, "udev.children-max=")) {
910 children_max = strtoul(opt + 18, NULL, 0);
911 } else if (startswith(opt, "udev.exec-delay=")) {
912 exec_delay = strtoul(opt + 16, NULL, 0);
913 }
914
915 free(s);
916 }
917 }
918
919 int main(int argc, char *argv[])
920 {
921 struct udev *udev;
922 sigset_t mask;
923 int daemonize = false;
924 int resolve_names = 1;
925 static const struct option options[] = {
926 { "daemon", no_argument, NULL, 'd' },
927 { "debug", no_argument, NULL, 'D' },
928 { "children-max", required_argument, NULL, 'c' },
929 { "exec-delay", required_argument, NULL, 'e' },
930 { "resolve-names", required_argument, NULL, 'N' },
931 { "help", no_argument, NULL, 'h' },
932 { "version", no_argument, NULL, 'V' },
933 {}
934 };
935 int fd_ctrl = -1;
936 int fd_netlink = -1;
937 int fd_worker = -1;
938 struct epoll_event ep_ctrl, ep_inotify, ep_signal, ep_netlink, ep_worker;
939 struct udev_ctrl_connection *ctrl_conn = NULL;
940 int rc = 1;
941
942 udev = udev_new();
943 if (udev == NULL)
944 goto exit;
945
946 log_set_target(LOG_TARGET_AUTO);
947 log_parse_environment();
948 log_open();
949
950 udev_set_log_fn(udev, udev_main_log);
951 log_set_max_level(udev_get_log_priority(udev));
952
953 log_debug("version %s", VERSION);
954 label_init("/dev");
955
956 for (;;) {
957 int option;
958
959 option = getopt_long(argc, argv, "c:de:DtN:hV", options, NULL);
960 if (option == -1)
961 break;
962
963 switch (option) {
964 case 'd':
965 daemonize = true;
966 break;
967 case 'c':
968 children_max = strtoul(optarg, NULL, 0);
969 break;
970 case 'e':
971 exec_delay = strtoul(optarg, NULL, 0);
972 break;
973 case 'D':
974 debug = true;
975 log_set_max_level(LOG_DEBUG);
976 udev_set_log_priority(udev, LOG_DEBUG);
977 break;
978 case 'N':
979 if (streq(optarg, "early")) {
980 resolve_names = 1;
981 } else if (streq(optarg, "late")) {
982 resolve_names = 0;
983 } else if (streq(optarg, "never")) {
984 resolve_names = -1;
985 } else {
986 fprintf(stderr, "resolve-names must be early, late or never\n");
987 log_error("resolve-names must be early, late or never");
988 goto exit;
989 }
990 break;
991 case 'h':
992 printf("Usage: udevd OPTIONS\n"
993 " --daemon\n"
994 " --debug\n"
995 " --children-max=<maximum number of workers>\n"
996 " --exec-delay=<seconds to wait before executing RUN=>\n"
997 " --resolve-names=early|late|never\n"
998 " --version\n"
999 " --help\n"
1000 "\n");
1001 goto exit;
1002 case 'V':
1003 printf("%s\n", VERSION);
1004 goto exit;
1005 default:
1006 goto exit;
1007 }
1008 }
1009
1010 kernel_cmdline_options(udev);
1011
1012 if (getuid() != 0) {
1013 fprintf(stderr, "root privileges required\n");
1014 log_error("root privileges required");
1015 goto exit;
1016 }
1017
1018 /* set umask before creating any file/directory */
1019 chdir("/");
1020 umask(022);
1021
1022 mkdir("/run/udev", 0755);
1023
1024 dev_setup(NULL);
1025
1026 /* before opening new files, make sure std{in,out,err} fds are in a sane state */
1027 if (daemonize) {
1028 int fd;
1029
1030 fd = open("/dev/null", O_RDWR);
1031 if (fd >= 0) {
1032 if (write(STDOUT_FILENO, 0, 0) < 0)
1033 dup2(fd, STDOUT_FILENO);
1034 if (write(STDERR_FILENO, 0, 0) < 0)
1035 dup2(fd, STDERR_FILENO);
1036 if (fd > STDERR_FILENO)
1037 close(fd);
1038 } else {
1039 fprintf(stderr, "cannot open /dev/null\n");
1040 log_error("cannot open /dev/null");
1041 }
1042 }
1043
1044 if (systemd_fds(udev, &fd_ctrl, &fd_netlink) >= 0) {
1045 /* get control and netlink socket from systemd */
1046 udev_ctrl = udev_ctrl_new_from_fd(udev, fd_ctrl);
1047 if (udev_ctrl == NULL) {
1048 log_error("error taking over udev control socket");
1049 rc = 1;
1050 goto exit;
1051 }
1052
1053 monitor = udev_monitor_new_from_netlink_fd(udev, "kernel", fd_netlink);
1054 if (monitor == NULL) {
1055 log_error("error taking over netlink socket");
1056 rc = 3;
1057 goto exit;
1058 }
1059
1060 /* get our own cgroup, we regularly kill everything udev has left behind */
1061 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &udev_cgroup) < 0)
1062 udev_cgroup = NULL;
1063 } else {
1064 /* open control and netlink socket */
1065 udev_ctrl = udev_ctrl_new(udev);
1066 if (udev_ctrl == NULL) {
1067 fprintf(stderr, "error initializing udev control socket");
1068 log_error("error initializing udev control socket");
1069 rc = 1;
1070 goto exit;
1071 }
1072 fd_ctrl = udev_ctrl_get_fd(udev_ctrl);
1073
1074 monitor = udev_monitor_new_from_netlink(udev, "kernel");
1075 if (monitor == NULL) {
1076 fprintf(stderr, "error initializing netlink socket\n");
1077 log_error("error initializing netlink socket");
1078 rc = 3;
1079 goto exit;
1080 }
1081 fd_netlink = udev_monitor_get_fd(monitor);
1082 }
1083
1084 if (udev_monitor_enable_receiving(monitor) < 0) {
1085 fprintf(stderr, "error binding netlink socket\n");
1086 log_error("error binding netlink socket");
1087 rc = 3;
1088 goto exit;
1089 }
1090
1091 if (udev_ctrl_enable_receiving(udev_ctrl) < 0) {
1092 fprintf(stderr, "error binding udev control socket\n");
1093 log_error("error binding udev control socket");
1094 rc = 1;
1095 goto exit;
1096 }
1097
1098 udev_monitor_set_receive_buffer_size(monitor, 128 * 1024 * 1024);
1099
1100 if (daemonize) {
1101 pid_t pid;
1102
1103 pid = fork();
1104 switch (pid) {
1105 case 0:
1106 break;
1107 case -1:
1108 log_error("fork of daemon failed: %m");
1109 rc = 4;
1110 goto exit;
1111 default:
1112 rc = EXIT_SUCCESS;
1113 goto exit_daemonize;
1114 }
1115
1116 setsid();
1117
1118 write_string_file("/proc/self/oom_score_adj", "-1000");
1119 } else {
1120 sd_notify(1, "READY=1");
1121 }
1122
1123 print_kmsg("starting version " VERSION "\n");
1124
1125 if (!debug) {
1126 int fd;
1127
1128 fd = open("/dev/null", O_RDWR);
1129 if (fd >= 0) {
1130 dup2(fd, STDIN_FILENO);
1131 dup2(fd, STDOUT_FILENO);
1132 dup2(fd, STDERR_FILENO);
1133 close(fd);
1134 }
1135 }
1136
1137 fd_inotify = udev_watch_init(udev);
1138 if (fd_inotify < 0) {
1139 fprintf(stderr, "error initializing inotify\n");
1140 log_error("error initializing inotify");
1141 rc = 4;
1142 goto exit;
1143 }
1144 udev_watch_restore(udev);
1145
1146 /* block and listen to all signals on signalfd */
1147 sigfillset(&mask);
1148 sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
1149 fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
1150 if (fd_signal < 0) {
1151 fprintf(stderr, "error creating signalfd\n");
1152 log_error("error creating signalfd");
1153 rc = 5;
1154 goto exit;
1155 }
1156
1157 /* unnamed socket from workers to the main daemon */
1158 if (socketpair(AF_LOCAL, SOCK_DGRAM|SOCK_CLOEXEC, 0, worker_watch) < 0) {
1159 fprintf(stderr, "error creating socketpair\n");
1160 log_error("error creating socketpair");
1161 rc = 6;
1162 goto exit;
1163 }
1164 fd_worker = worker_watch[READ_END];
1165
1166 udev_builtin_init(udev);
1167
1168 rules = udev_rules_new(udev, resolve_names);
1169 if (rules == NULL) {
1170 log_error("error reading rules");
1171 goto exit;
1172 }
1173
1174 memzero(&ep_ctrl, sizeof(struct epoll_event));
1175 ep_ctrl.events = EPOLLIN;
1176 ep_ctrl.data.fd = fd_ctrl;
1177
1178 memzero(&ep_inotify, sizeof(struct epoll_event));
1179 ep_inotify.events = EPOLLIN;
1180 ep_inotify.data.fd = fd_inotify;
1181
1182 memzero(&ep_signal, sizeof(struct epoll_event));
1183 ep_signal.events = EPOLLIN;
1184 ep_signal.data.fd = fd_signal;
1185
1186 memzero(&ep_netlink, sizeof(struct epoll_event));
1187 ep_netlink.events = EPOLLIN;
1188 ep_netlink.data.fd = fd_netlink;
1189
1190 memzero(&ep_worker, sizeof(struct epoll_event));
1191 ep_worker.events = EPOLLIN;
1192 ep_worker.data.fd = fd_worker;
1193
1194 fd_ep = epoll_create1(EPOLL_CLOEXEC);
1195 if (fd_ep < 0) {
1196 log_error("error creating epoll fd: %m");
1197 goto exit;
1198 }
1199 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_ctrl, &ep_ctrl) < 0 ||
1200 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_inotify, &ep_inotify) < 0 ||
1201 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_signal, &ep_signal) < 0 ||
1202 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_netlink, &ep_netlink) < 0 ||
1203 epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_worker, &ep_worker) < 0) {
1204 log_error("fail to add fds to epoll: %m");
1205 goto exit;
1206 }
1207
1208 if (children_max <= 0) {
1209 cpu_set_t cpu_set;
1210
1211 children_max = 8;
1212
1213 if (sched_getaffinity(0, sizeof (cpu_set), &cpu_set) == 0) {
1214 children_max += CPU_COUNT(&cpu_set) * 2;
1215 }
1216 }
1217 log_debug("set children_max to %u", children_max);
1218
1219 rc = udev_rules_apply_static_dev_perms(rules);
1220 if (rc < 0)
1221 log_error("failed to apply permissions on static device nodes - %s", strerror(-rc));
1222
1223 udev_list_node_init(&event_list);
1224 udev_list_node_init(&worker_list);
1225
1226 for (;;) {
1227 static usec_t last_usec;
1228 struct epoll_event ev[8];
1229 int fdcount;
1230 int timeout;
1231 bool is_worker, is_signal, is_inotify, is_netlink, is_ctrl;
1232 int i;
1233
1234 if (udev_exit) {
1235 /* close sources of new events and discard buffered events */
1236 if (fd_ctrl >= 0) {
1237 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_ctrl, NULL);
1238 fd_ctrl = -1;
1239 }
1240 if (monitor != NULL) {
1241 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_netlink, NULL);
1242 udev_monitor_unref(monitor);
1243 monitor = NULL;
1244 }
1245 if (fd_inotify >= 0) {
1246 epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd_inotify, NULL);
1247 close(fd_inotify);
1248 fd_inotify = -1;
1249 }
1250
1251 /* discard queued events and kill workers */
1252 event_queue_cleanup(udev, EVENT_QUEUED);
1253 worker_kill(udev);
1254
1255 /* exit after all has cleaned up */
1256 if (udev_list_node_is_empty(&event_list) && children == 0)
1257 break;
1258
1259 /* timeout at exit for workers to finish */
1260 timeout = 30 * MSEC_PER_SEC;
1261 } else if (udev_list_node_is_empty(&event_list) && children == 0) {
1262 /* we are idle */
1263 timeout = -1;
1264
1265 /* cleanup possible left-over processes in our cgroup */
1266 if (udev_cgroup)
1267 cg_kill(SYSTEMD_CGROUP_CONTROLLER, udev_cgroup, SIGKILL, false, true, NULL);
1268 } else {
1269 /* kill idle or hanging workers */
1270 timeout = 3 * MSEC_PER_SEC;
1271 }
1272
1273 /* tell settle that we are busy or idle */
1274 if (!udev_list_node_is_empty(&event_list)) {
1275 int fd;
1276
1277 fd = open("/run/udev/queue", O_WRONLY|O_CREAT|O_CLOEXEC|O_TRUNC|O_NOFOLLOW, 0444);
1278 if (fd >= 0)
1279 close(fd);
1280 } else {
1281 unlink("/run/udev/queue");
1282 }
1283
1284 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
1285 if (fdcount < 0)
1286 continue;
1287
1288 if (fdcount == 0) {
1289 struct udev_list_node *loop;
1290
1291 /* timeout */
1292 if (udev_exit) {
1293 log_error("timeout, giving up waiting for workers to finish");
1294 break;
1295 }
1296
1297 /* kill idle workers */
1298 if (udev_list_node_is_empty(&event_list)) {
1299 log_debug("cleanup idle workers");
1300 worker_kill(udev);
1301 }
1302
1303 /* check for hanging events */
1304 udev_list_node_foreach(loop, &worker_list) {
1305 struct worker *worker = node_to_worker(loop);
1306
1307 if (worker->state != WORKER_RUNNING)
1308 continue;
1309
1310 if ((now(CLOCK_MONOTONIC) - worker->event_start_usec) > 30 * USEC_PER_SEC) {
1311 log_error("worker [%u] %s timeout; kill it", worker->pid,
1312 worker->event ? worker->event->devpath : "<idle>");
1313 kill(worker->pid, SIGKILL);
1314 worker->state = WORKER_KILLED;
1315
1316 /* drop reference taken for state 'running' */
1317 worker_unref(worker);
1318 if (worker->event) {
1319 log_error("seq %llu '%s' killed", udev_device_get_seqnum(worker->event->dev), worker->event->devpath);
1320 worker->event->exitcode = -64;
1321 event_queue_delete(worker->event);
1322 worker->event = NULL;
1323 }
1324 }
1325 }
1326
1327 }
1328
1329 is_worker = is_signal = is_inotify = is_netlink = is_ctrl = false;
1330 for (i = 0; i < fdcount; i++) {
1331 if (ev[i].data.fd == fd_worker && ev[i].events & EPOLLIN)
1332 is_worker = true;
1333 else if (ev[i].data.fd == fd_netlink && ev[i].events & EPOLLIN)
1334 is_netlink = true;
1335 else if (ev[i].data.fd == fd_signal && ev[i].events & EPOLLIN)
1336 is_signal = true;
1337 else if (ev[i].data.fd == fd_inotify && ev[i].events & EPOLLIN)
1338 is_inotify = true;
1339 else if (ev[i].data.fd == fd_ctrl && ev[i].events & EPOLLIN)
1340 is_ctrl = true;
1341 }
1342
1343 /* check for changed config, every 3 seconds at most */
1344 if ((now(CLOCK_MONOTONIC) - last_usec) > 3 * USEC_PER_SEC) {
1345 if (udev_rules_check_timestamp(rules))
1346 reload = true;
1347 if (udev_builtin_validate(udev))
1348 reload = true;
1349
1350 last_usec = now(CLOCK_MONOTONIC);
1351 }
1352
1353 /* reload requested, HUP signal received, rules changed, builtin changed */
1354 if (reload) {
1355 worker_kill(udev);
1356 rules = udev_rules_unref(rules);
1357 udev_builtin_exit(udev);
1358 reload = false;
1359 }
1360
1361 /* event has finished */
1362 if (is_worker)
1363 worker_returned(fd_worker);
1364
1365 if (is_netlink) {
1366 struct udev_device *dev;
1367
1368 dev = udev_monitor_receive_device(monitor);
1369 if (dev != NULL) {
1370 udev_device_set_usec_initialized(dev, now(CLOCK_MONOTONIC));
1371 if (event_queue_insert(dev) < 0)
1372 udev_device_unref(dev);
1373 }
1374 }
1375
1376 /* start new events */
1377 if (!udev_list_node_is_empty(&event_list) && !udev_exit && !stop_exec_queue) {
1378 udev_builtin_init(udev);
1379 if (rules == NULL)
1380 rules = udev_rules_new(udev, resolve_names);
1381 if (rules != NULL)
1382 event_queue_start(udev);
1383 }
1384
1385 if (is_signal) {
1386 struct signalfd_siginfo fdsi;
1387 ssize_t size;
1388
1389 size = read(fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
1390 if (size == sizeof(struct signalfd_siginfo))
1391 handle_signal(udev, fdsi.ssi_signo);
1392 }
1393
1394 /* we are shutting down, the events below are not handled anymore */
1395 if (udev_exit)
1396 continue;
1397
1398 /* device node watch */
1399 if (is_inotify)
1400 handle_inotify(udev);
1401
1402 /*
1403 * This needs to be after the inotify handling, to make sure,
1404 * that the ping is send back after the possibly generated
1405 * "change" events by the inotify device node watch.
1406 *
1407 * A single time we may receive a client connection which we need to
1408 * keep open to block the client. It will be closed right before we
1409 * exit.
1410 */
1411 if (is_ctrl)
1412 ctrl_conn = handle_ctrl_msg(udev_ctrl);
1413 }
1414
1415 rc = EXIT_SUCCESS;
1416 exit:
1417 udev_ctrl_cleanup(udev_ctrl);
1418 unlink("/run/udev/queue");
1419 exit_daemonize:
1420 if (fd_ep >= 0)
1421 close(fd_ep);
1422 worker_list_cleanup(udev);
1423 event_queue_cleanup(udev, EVENT_UNDEF);
1424 udev_rules_unref(rules);
1425 udev_builtin_exit(udev);
1426 if (fd_signal >= 0)
1427 close(fd_signal);
1428 if (worker_watch[READ_END] >= 0)
1429 close(worker_watch[READ_END]);
1430 if (worker_watch[WRITE_END] >= 0)
1431 close(worker_watch[WRITE_END]);
1432 udev_monitor_unref(monitor);
1433 udev_ctrl_connection_unref(ctrl_conn);
1434 udev_ctrl_unref(udev_ctrl);
1435 label_finish();
1436 udev_unref(udev);
1437 log_close();
1438 return rc;
1439 }