2 * Copyright (C) 2003-2013 Kay Sievers <kay@vrfy.org>
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
28 #include <sys/prctl.h>
30 #include <sys/epoll.h>
32 #include <sys/signalfd.h>
35 #include "rtnl-util.h"
37 struct udev_event *udev_event_new(struct udev_device *dev)
39 struct udev *udev = udev_device_get_udev(dev);
40 struct udev_event *event;
42 event = new0(struct udev_event, 1);
47 udev_list_init(udev, &event->run_list, false);
48 udev_list_init(udev, &event->seclabel_list, false);
49 event->fd_signal = -1;
50 event->birth_usec = now(CLOCK_MONOTONIC);
51 event->timeout_usec = 30 * 1000 * 1000;
55 void udev_event_unref(struct udev_event *event)
59 udev_list_cleanup(&event->run_list);
60 udev_list_cleanup(&event->seclabel_list);
61 free(event->program_result);
66 size_t udev_event_apply_format(struct udev_event *event, const char *src, char *dest, size_t size)
68 struct udev_device *dev = event->dev;
88 static const struct subst_map {
93 { .name = "devnode", .fmt = 'N', .type = SUBST_DEVNODE },
94 { .name = "tempnode", .fmt = 'N', .type = SUBST_DEVNODE },
95 { .name = "attr", .fmt = 's', .type = SUBST_ATTR },
96 { .name = "sysfs", .fmt = 's', .type = SUBST_ATTR },
97 { .name = "env", .fmt = 'E', .type = SUBST_ENV },
98 { .name = "kernel", .fmt = 'k', .type = SUBST_KERNEL },
99 { .name = "number", .fmt = 'n', .type = SUBST_KERNEL_NUMBER },
100 { .name = "driver", .fmt = 'd', .type = SUBST_DRIVER },
101 { .name = "devpath", .fmt = 'p', .type = SUBST_DEVPATH },
102 { .name = "id", .fmt = 'b', .type = SUBST_ID },
103 { .name = "major", .fmt = 'M', .type = SUBST_MAJOR },
104 { .name = "minor", .fmt = 'm', .type = SUBST_MINOR },
105 { .name = "result", .fmt = 'c', .type = SUBST_RESULT },
106 { .name = "parent", .fmt = 'P', .type = SUBST_PARENT },
107 { .name = "name", .fmt = 'D', .type = SUBST_NAME },
108 { .name = "links", .fmt = 'L', .type = SUBST_LINKS },
109 { .name = "root", .fmt = 'r', .type = SUBST_ROOT },
110 { .name = "sys", .fmt = 'S', .type = SUBST_SYS },
121 enum subst_type type = SUBST_UNKNOWN;
122 char attrbuf[UTIL_PATH_SIZE];
125 while (from[0] != '\0') {
126 if (from[0] == '$') {
127 /* substitute named variable */
130 if (from[1] == '$') {
135 for (i = 0; i < ELEMENTSOF(map); i++) {
136 if (startswith(&from[1], map[i].name)) {
138 from += strlen(map[i].name)+1;
142 } else if (from[0] == '%') {
143 /* substitute format char */
146 if (from[1] == '%') {
151 for (i = 0; i < ELEMENTSOF(map); i++) {
152 if (from[1] == map[i].fmt) {
171 /* extract possible $format{attr} */
172 if (from[0] == '{') {
176 for (i = 0; from[i] != '}'; i++) {
177 if (from[i] == '\0') {
178 log_error("missing closing brace for format '%s'", src);
182 if (i >= sizeof(attrbuf))
184 memcpy(attrbuf, from, i);
194 l = strpcpy(&s, l, udev_device_get_devpath(dev));
197 l = strpcpy(&s, l, udev_device_get_sysname(dev));
199 case SUBST_KERNEL_NUMBER:
200 if (udev_device_get_sysnum(dev) == NULL)
202 l = strpcpy(&s, l, udev_device_get_sysnum(dev));
205 if (event->dev_parent == NULL)
207 l = strpcpy(&s, l, udev_device_get_sysname(event->dev_parent));
212 if (event->dev_parent == NULL)
215 driver = udev_device_get_driver(event->dev_parent);
218 l = strpcpy(&s, l, driver);
222 char num[UTIL_PATH_SIZE];
224 sprintf(num, "%d", major(udev_device_get_devnum(dev)));
225 l = strpcpy(&s, l, num);
229 char num[UTIL_PATH_SIZE];
231 sprintf(num, "%d", minor(udev_device_get_devnum(dev)));
232 l = strpcpy(&s, l, num);
239 if (event->program_result == NULL)
241 /* get part part of the result string */
244 i = strtoul(attr, &rest, 10);
246 char result[UTIL_PATH_SIZE];
247 char tmp[UTIL_PATH_SIZE];
250 strscpy(result, sizeof(result), event->program_result);
253 while (cpos[0] != '\0' && !isspace(cpos[0]))
255 while (isspace(cpos[0]))
261 log_error("requested part of result string not found");
264 strscpy(tmp, sizeof(tmp), cpos);
265 /* %{2+}c copies the whole string from the second part on */
266 if (rest[0] != '+') {
267 cpos = strchr(tmp, ' ');
271 l = strpcpy(&s, l, tmp);
273 l = strpcpy(&s, l, event->program_result);
278 const char *value = NULL;
279 char vbuf[UTIL_NAME_SIZE];
284 log_error("missing file parameter for attr");
288 /* try to read the value specified by "[dmi/id]product_name" */
289 if (util_resolve_subsys_kernel(event->udev, attr, vbuf, sizeof(vbuf), 1) == 0)
292 /* try to read the attribute the device */
294 value = udev_device_get_sysattr_value(event->dev, attr);
296 /* try to read the attribute of the parent device, other matches have selected */
297 if (value == NULL && event->dev_parent != NULL && event->dev_parent != event->dev)
298 value = udev_device_get_sysattr_value(event->dev_parent, attr);
303 /* strip trailing whitespace, and replace unwanted characters */
305 strscpy(vbuf, sizeof(vbuf), value);
307 while (len > 0 && isspace(vbuf[--len]))
309 count = util_replace_chars(vbuf, UDEV_ALLOWED_CHARS_INPUT);
311 log_debug("%i character(s) replaced" , count);
312 l = strpcpy(&s, l, vbuf);
316 struct udev_device *dev_parent;
319 dev_parent = udev_device_get_parent(event->dev);
320 if (dev_parent == NULL)
322 devnode = udev_device_get_devnode(dev_parent);
324 l = strpcpy(&s, l, devnode + strlen("/dev/"));
328 if (udev_device_get_devnode(dev) != NULL)
329 l = strpcpy(&s, l, udev_device_get_devnode(dev));
332 if (event->name != NULL)
333 l = strpcpy(&s, l, event->name);
334 else if (udev_device_get_devnode(dev) != NULL)
335 l = strpcpy(&s, l, udev_device_get_devnode(dev) + strlen("/dev/"));
337 l = strpcpy(&s, l, udev_device_get_sysname(dev));
340 struct udev_list_entry *list_entry;
342 list_entry = udev_device_get_devlinks_list_entry(dev);
343 if (list_entry == NULL)
345 l = strpcpy(&s, l, udev_list_entry_get_name(list_entry) + strlen("/dev/"));
346 udev_list_entry_foreach(list_entry, udev_list_entry_get_next(list_entry))
347 l = strpcpyl(&s, l, " ", udev_list_entry_get_name(list_entry) + strlen("/dev/"), NULL);
351 l = strpcpy(&s, l, "/dev");
354 l = strpcpy(&s, l, "/sys");
362 value = udev_device_get_property_value(event->dev, attr);
365 l = strpcpy(&s, l, value);
369 log_error("unknown substitution type=%i", type);
379 static int spawn_exec(struct udev_event *event,
380 const char *cmd, char *const argv[], char **envp, const sigset_t *sigmask,
381 int fd_stdout, int fd_stderr)
386 /* discard child output or connect to pipe */
387 fd = open("/dev/null", O_RDWR);
389 dup2(fd, STDIN_FILENO);
391 dup2(fd, STDOUT_FILENO);
393 dup2(fd, STDERR_FILENO);
396 log_error("open /dev/null failed: %m");
399 /* connect pipes to std{out,err} */
400 if (fd_stdout >= 0) {
401 dup2(fd_stdout, STDOUT_FILENO);
404 if (fd_stderr >= 0) {
405 dup2(fd_stderr, STDERR_FILENO);
409 /* terminate child in case parent goes away */
410 prctl(PR_SET_PDEATHSIG, SIGTERM);
412 /* restore original udev sigmask before exec */
414 sigprocmask(SIG_SETMASK, sigmask, NULL);
416 execve(argv[0], argv, envp);
420 log_error("failed to execute '%s' '%s': %m", argv[0], cmd);
424 static void spawn_read(struct udev_event *event,
426 int fd_stdout, int fd_stderr,
427 char *result, size_t ressize)
431 struct epoll_event ep_outpipe, ep_errpipe;
433 /* read from child if requested */
434 if (fd_stdout < 0 && fd_stderr < 0)
437 fd_ep = epoll_create1(EPOLL_CLOEXEC);
439 log_error("error creating epoll fd: %m");
443 if (fd_stdout >= 0) {
444 memzero(&ep_outpipe, sizeof(struct epoll_event));
445 ep_outpipe.events = EPOLLIN;
446 ep_outpipe.data.ptr = &fd_stdout;
447 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_stdout, &ep_outpipe) < 0) {
448 log_error("fail to add fd to epoll: %m");
453 if (fd_stderr >= 0) {
454 memzero(&ep_errpipe, sizeof(struct epoll_event));
455 ep_errpipe.events = EPOLLIN;
456 ep_errpipe.data.ptr = &fd_stderr;
457 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_stderr, &ep_errpipe) < 0) {
458 log_error("fail to add fd to epoll: %m");
463 /* read child output */
464 while (fd_stdout >= 0 || fd_stderr >= 0) {
467 struct epoll_event ev[4];
470 if (event->timeout_usec > 0) {
473 age_usec = now(CLOCK_MONOTONIC) - event->birth_usec;
474 if (age_usec >= event->timeout_usec) {
475 log_error("timeout '%s'", cmd);
478 timeout = ((event->timeout_usec - age_usec) / 1000) + 1000;
483 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
487 log_error("failed to poll: %m");
491 log_error("timeout '%s'", cmd);
495 for (i = 0; i < fdcount; i++) {
496 int *fd = (int *)ev[i].data.ptr;
498 if (ev[i].events & EPOLLIN) {
502 count = read(*fd, buf, sizeof(buf)-1);
507 /* store stdout result */
508 if (result != NULL && *fd == fd_stdout) {
509 if (respos + count < ressize) {
510 memcpy(&result[respos], buf, count);
513 log_error("'%s' ressize %zd too short", cmd, ressize);
517 /* log debug output only if we watch stderr */
518 if (fd_stderr >= 0) {
523 while ((line = strsep(&pos, "\n"))) {
524 if (pos != NULL || line[0] != '\0')
525 log_debug("'%s'(%s) '%s'", cmd, *fd == fd_stdout ? "out" : "err" , line);
528 } else if (ev[i].events & EPOLLHUP) {
529 if (epoll_ctl(fd_ep, EPOLL_CTL_DEL, *fd, NULL) < 0) {
530 log_error("failed to remove fd from epoll: %m");
538 /* return the child's stdout string */
540 result[respos] = '\0';
546 static int spawn_wait(struct udev_event *event, const char *cmd, pid_t pid)
548 struct pollfd pfd[1];
551 pfd[0].events = POLLIN;
552 pfd[0].fd = event->fd_signal;
558 if (event->timeout_usec > 0) {
561 age_usec = now(CLOCK_MONOTONIC) - event->birth_usec;
562 if (age_usec >= event->timeout_usec)
565 timeout = ((event->timeout_usec - age_usec) / 1000) + 1000;
570 fdcount = poll(pfd, 1, timeout);
575 log_error("failed to poll: %m");
579 log_error("timeout: killing '%s' [%u]", cmd, pid);
583 if (pfd[0].revents & POLLIN) {
584 struct signalfd_siginfo fdsi;
588 size = read(event->fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
589 if (size != sizeof(struct signalfd_siginfo))
592 switch (fdsi.ssi_signo) {
594 event->sigterm = true;
597 if (waitpid(pid, &status, WNOHANG) < 0)
599 if (WIFEXITED(status)) {
600 log_debug("'%s' [%u] exit with return code %i", cmd, pid, WEXITSTATUS(status));
601 if (WEXITSTATUS(status) != 0)
603 } else if (WIFSIGNALED(status)) {
604 log_error("'%s' [%u] terminated by signal %i (%s)", cmd, pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
606 } else if (WIFSTOPPED(status)) {
607 log_error("'%s' [%u] stopped", cmd, pid);
609 } else if (WIFCONTINUED(status)) {
610 log_error("'%s' [%u] continued", cmd, pid);
613 log_error("'%s' [%u] exit with status 0x%04x", cmd, pid, status);
625 int udev_build_argv(struct udev *udev, char *cmd, int *argc, char *argv[])
630 if (strchr(cmd, ' ') == NULL) {
636 while (pos != NULL && pos[0] != '\0') {
637 if (pos[0] == '\'') {
638 /* do not separate quotes */
640 argv[i] = strsep(&pos, "\'");
642 while (pos[0] == ' ')
645 argv[i] = strsep(&pos, " ");
647 while (pos[0] == ' ')
659 int udev_event_spawn(struct udev_event *event,
660 const char *cmd, char **envp, const sigset_t *sigmask,
661 char *result, size_t ressize)
663 struct udev *udev = event->udev;
664 int outpipe[2] = {-1, -1};
665 int errpipe[2] = {-1, -1};
667 char arg[UTIL_PATH_SIZE];
669 char program[UTIL_PATH_SIZE];
672 strscpy(arg, sizeof(arg), cmd);
673 udev_build_argv(event->udev, arg, NULL, argv);
675 /* pipes from child to parent */
676 if (result != NULL || udev_get_log_priority(udev) >= LOG_INFO) {
677 if (pipe2(outpipe, O_NONBLOCK) != 0) {
679 log_error("pipe failed: %m");
683 if (udev_get_log_priority(udev) >= LOG_INFO) {
684 if (pipe2(errpipe, O_NONBLOCK) != 0) {
686 log_error("pipe failed: %m");
691 /* allow programs in /usr/lib/udev/ to be called without the path */
692 if (argv[0][0] != '/') {
693 strscpyl(program, sizeof(program), UDEVLIBEXECDIR "/", argv[0], NULL);
700 /* child closes parent's ends of pipes */
701 if (outpipe[READ_END] >= 0) {
702 close(outpipe[READ_END]);
703 outpipe[READ_END] = -1;
705 if (errpipe[READ_END] >= 0) {
706 close(errpipe[READ_END]);
707 errpipe[READ_END] = -1;
710 log_debug("starting '%s'", cmd);
712 spawn_exec(event, cmd, argv, envp, sigmask,
713 outpipe[WRITE_END], errpipe[WRITE_END]);
717 log_error("fork of '%s' failed: %m", cmd);
721 /* parent closed child's ends of pipes */
722 if (outpipe[WRITE_END] >= 0) {
723 close(outpipe[WRITE_END]);
724 outpipe[WRITE_END] = -1;
726 if (errpipe[WRITE_END] >= 0) {
727 close(errpipe[WRITE_END]);
728 errpipe[WRITE_END] = -1;
731 spawn_read(event, cmd,
732 outpipe[READ_END], errpipe[READ_END],
735 err = spawn_wait(event, cmd, pid);
739 if (outpipe[READ_END] >= 0)
740 close(outpipe[READ_END]);
741 if (outpipe[WRITE_END] >= 0)
742 close(outpipe[WRITE_END]);
743 if (errpipe[READ_END] >= 0)
744 close(errpipe[READ_END]);
745 if (errpipe[WRITE_END] >= 0)
746 close(errpipe[WRITE_END]);
750 static int rename_netif(struct udev_event *event)
752 struct udev_device *dev = event->dev;
753 _cleanup_rtnl_unref_ sd_rtnl *rtnl = NULL;
758 oldname = udev_device_get_sysname(dev);
760 log_debug("changing net interface name from '%s' to '%s'",
761 oldname, event->name);
763 strscpy(name, IFNAMSIZ, event->name);
765 r = sd_rtnl_open(&rtnl, 0);
769 r = rtnl_set_link_name(rtnl, udev_device_get_ifindex(dev), name);
771 log_error("error changing net interface name %s to %s: %s",
772 oldname, name, strerror(-r));
774 print_kmsg("renamed network interface %s to %s\n", oldname, name);
779 void udev_event_execute_rules(struct udev_event *event, struct udev_rules *rules, const sigset_t *sigmask)
781 struct udev_device *dev = event->dev;
783 if (udev_device_get_subsystem(dev) == NULL)
786 if (streq(udev_device_get_action(dev), "remove")) {
787 udev_device_read_db(dev, NULL);
788 udev_device_delete_db(dev);
789 udev_device_tag_index(dev, NULL, false);
791 if (major(udev_device_get_devnum(dev)) != 0)
792 udev_watch_end(event->udev, dev);
794 udev_rules_apply_to_event(rules, event, sigmask);
796 if (major(udev_device_get_devnum(dev)) != 0)
797 udev_node_remove(dev);
799 event->dev_db = udev_device_new(event->udev);
800 if (event->dev_db != NULL) {
801 udev_device_set_syspath(event->dev_db, udev_device_get_syspath(dev));
802 udev_device_set_subsystem(event->dev_db, udev_device_get_subsystem(dev));
803 udev_device_read_db(event->dev_db, NULL);
804 udev_device_set_info_loaded(event->dev_db);
806 /* disable watch during event processing */
807 if (major(udev_device_get_devnum(dev)) != 0)
808 udev_watch_end(event->udev, event->dev_db);
811 udev_rules_apply_to_event(rules, event, sigmask);
813 /* rename a new network interface, if needed */
814 if (udev_device_get_ifindex(dev) > 0 && streq(udev_device_get_action(dev), "add") &&
815 event->name != NULL && !streq(event->name, udev_device_get_sysname(dev))) {
816 char syspath[UTIL_PATH_SIZE];
820 r = rename_netif(event);
822 log_debug("renamed netif to '%s'", event->name);
824 /* remember old name */
825 udev_device_add_property(dev, "INTERFACE_OLD", udev_device_get_sysname(dev));
827 /* now change the devpath, because the kernel device name has changed */
828 strscpy(syspath, sizeof(syspath), udev_device_get_syspath(dev));
829 pos = strrchr(syspath, '/');
832 strscpy(pos, sizeof(syspath) - (pos - syspath), event->name);
833 udev_device_set_syspath(event->dev, syspath);
834 udev_device_add_property(dev, "INTERFACE", udev_device_get_sysname(dev));
835 log_debug("changed devpath to '%s'", udev_device_get_devpath(dev));
840 if (major(udev_device_get_devnum(dev)) > 0) {
843 /* remove/update possible left-over symlinks from old database entry */
844 if (event->dev_db != NULL)
845 udev_node_update_old_links(dev, event->dev_db);
847 if (!event->owner_set)
848 event->uid = udev_device_get_devnode_uid(dev);
850 if (!event->group_set)
851 event->gid = udev_device_get_devnode_gid(dev);
853 if (!event->mode_set) {
854 if (udev_device_get_devnode_mode(dev) > 0) {
855 /* kernel supplied value */
856 event->mode = udev_device_get_devnode_mode(dev);
857 } else if (event->gid > 0) {
858 /* default 0660 if a group is assigned */
866 apply = streq(udev_device_get_action(dev), "add") || event->owner_set || event->group_set || event->mode_set;
867 udev_node_add(dev, apply, event->mode, event->uid, event->gid, &event->seclabel_list);
870 /* preserve old, or get new initialization timestamp */
871 if (event->dev_db != NULL && udev_device_get_usec_initialized(event->dev_db) > 0)
872 udev_device_set_usec_initialized(event->dev, udev_device_get_usec_initialized(event->dev_db));
873 else if (udev_device_get_usec_initialized(event->dev) == 0)
874 udev_device_set_usec_initialized(event->dev, now(CLOCK_MONOTONIC));
876 /* (re)write database file */
877 udev_device_update_db(dev);
878 udev_device_tag_index(dev, event->dev_db, true);
879 udev_device_set_is_initialized(dev);
881 udev_device_unref(event->dev_db);
882 event->dev_db = NULL;
886 void udev_event_execute_run(struct udev_event *event, const sigset_t *sigmask)
888 struct udev_list_entry *list_entry;
890 udev_list_entry_foreach(list_entry, udev_list_get_entry(&event->run_list)) {
891 const char *cmd = udev_list_entry_get_name(list_entry);
892 enum udev_builtin_cmd builtin_cmd = udev_list_entry_get_num(list_entry);
894 if (builtin_cmd < UDEV_BUILTIN_MAX) {
895 char command[UTIL_PATH_SIZE];
897 udev_event_apply_format(event, cmd, command, sizeof(command));
898 udev_builtin_run(event->dev, builtin_cmd, command, false);
900 char program[UTIL_PATH_SIZE];
903 if (event->exec_delay > 0) {
904 log_debug("delay execution of '%s'", program);
905 sleep(event->exec_delay);
908 udev_event_apply_format(event, cmd, program, sizeof(program));
909 envp = udev_device_get_properties_envp(event->dev);
910 udev_event_spawn(event, program, envp, sigmask, NULL, 0);