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