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) {
38 struct udev *udev = udev_device_get_udev(dev);
39 struct udev_event *event;
41 event = new0(struct udev_event, 1);
46 udev_list_init(udev, &event->run_list, false);
47 udev_list_init(udev, &event->seclabel_list, false);
48 event->fd_signal = -1;
49 event->birth_usec = now(CLOCK_MONOTONIC);
53 void udev_event_unref(struct udev_event *event) {
56 sd_rtnl_unref(event->rtnl);
57 udev_list_cleanup(&event->run_list);
58 udev_list_cleanup(&event->seclabel_list);
59 free(event->program_result);
64 size_t udev_event_apply_format(struct udev_event *event, const char *src, char *dest, size_t size) {
65 struct udev_device *dev = event->dev;
85 static const struct subst_map {
90 { .name = "devnode", .fmt = 'N', .type = SUBST_DEVNODE },
91 { .name = "tempnode", .fmt = 'N', .type = SUBST_DEVNODE },
92 { .name = "attr", .fmt = 's', .type = SUBST_ATTR },
93 { .name = "sysfs", .fmt = 's', .type = SUBST_ATTR },
94 { .name = "env", .fmt = 'E', .type = SUBST_ENV },
95 { .name = "kernel", .fmt = 'k', .type = SUBST_KERNEL },
96 { .name = "number", .fmt = 'n', .type = SUBST_KERNEL_NUMBER },
97 { .name = "driver", .fmt = 'd', .type = SUBST_DRIVER },
98 { .name = "devpath", .fmt = 'p', .type = SUBST_DEVPATH },
99 { .name = "id", .fmt = 'b', .type = SUBST_ID },
100 { .name = "major", .fmt = 'M', .type = SUBST_MAJOR },
101 { .name = "minor", .fmt = 'm', .type = SUBST_MINOR },
102 { .name = "result", .fmt = 'c', .type = SUBST_RESULT },
103 { .name = "parent", .fmt = 'P', .type = SUBST_PARENT },
104 { .name = "name", .fmt = 'D', .type = SUBST_NAME },
105 { .name = "links", .fmt = 'L', .type = SUBST_LINKS },
106 { .name = "root", .fmt = 'r', .type = SUBST_ROOT },
107 { .name = "sys", .fmt = 'S', .type = SUBST_SYS },
118 enum subst_type type = SUBST_UNKNOWN;
119 char attrbuf[UTIL_PATH_SIZE];
122 while (from[0] != '\0') {
123 if (from[0] == '$') {
124 /* substitute named variable */
127 if (from[1] == '$') {
132 for (i = 0; i < ELEMENTSOF(map); i++) {
133 if (startswith(&from[1], map[i].name)) {
135 from += strlen(map[i].name)+1;
139 } else if (from[0] == '%') {
140 /* substitute format char */
143 if (from[1] == '%') {
148 for (i = 0; i < ELEMENTSOF(map); i++) {
149 if (from[1] == map[i].fmt) {
168 /* extract possible $format{attr} */
169 if (from[0] == '{') {
173 for (i = 0; from[i] != '}'; i++) {
174 if (from[i] == '\0') {
175 log_error("missing closing brace for format '%s'", src);
179 if (i >= sizeof(attrbuf))
181 memcpy(attrbuf, from, i);
191 l = strpcpy(&s, l, udev_device_get_devpath(dev));
194 l = strpcpy(&s, l, udev_device_get_sysname(dev));
196 case SUBST_KERNEL_NUMBER:
197 if (udev_device_get_sysnum(dev) == NULL)
199 l = strpcpy(&s, l, udev_device_get_sysnum(dev));
202 if (event->dev_parent == NULL)
204 l = strpcpy(&s, l, udev_device_get_sysname(event->dev_parent));
209 if (event->dev_parent == NULL)
212 driver = udev_device_get_driver(event->dev_parent);
215 l = strpcpy(&s, l, driver);
219 char num[UTIL_PATH_SIZE];
221 sprintf(num, "%d", major(udev_device_get_devnum(dev)));
222 l = strpcpy(&s, l, num);
226 char num[UTIL_PATH_SIZE];
228 sprintf(num, "%d", minor(udev_device_get_devnum(dev)));
229 l = strpcpy(&s, l, num);
236 if (event->program_result == NULL)
238 /* get part part of the result string */
241 i = strtoul(attr, &rest, 10);
243 char result[UTIL_PATH_SIZE];
244 char tmp[UTIL_PATH_SIZE];
247 strscpy(result, sizeof(result), event->program_result);
250 while (cpos[0] != '\0' && !isspace(cpos[0]))
252 while (isspace(cpos[0]))
258 log_error("requested part of result string not found");
261 strscpy(tmp, sizeof(tmp), cpos);
262 /* %{2+}c copies the whole string from the second part on */
263 if (rest[0] != '+') {
264 cpos = strchr(tmp, ' ');
268 l = strpcpy(&s, l, tmp);
270 l = strpcpy(&s, l, event->program_result);
275 const char *value = NULL;
276 char vbuf[UTIL_NAME_SIZE];
281 log_error("missing file parameter for attr");
285 /* try to read the value specified by "[dmi/id]product_name" */
286 if (util_resolve_subsys_kernel(event->udev, attr, vbuf, sizeof(vbuf), 1) == 0)
289 /* try to read the attribute the device */
291 value = udev_device_get_sysattr_value(event->dev, attr);
293 /* try to read the attribute of the parent device, other matches have selected */
294 if (value == NULL && event->dev_parent != NULL && event->dev_parent != event->dev)
295 value = udev_device_get_sysattr_value(event->dev_parent, attr);
300 /* strip trailing whitespace, and replace unwanted characters */
302 strscpy(vbuf, sizeof(vbuf), value);
304 while (len > 0 && isspace(vbuf[--len]))
306 count = util_replace_chars(vbuf, UDEV_ALLOWED_CHARS_INPUT);
308 log_debug("%i character(s) replaced" , count);
309 l = strpcpy(&s, l, vbuf);
313 struct udev_device *dev_parent;
316 dev_parent = udev_device_get_parent(event->dev);
317 if (dev_parent == NULL)
319 devnode = udev_device_get_devnode(dev_parent);
321 l = strpcpy(&s, l, devnode + strlen("/dev/"));
325 if (udev_device_get_devnode(dev) != NULL)
326 l = strpcpy(&s, l, udev_device_get_devnode(dev));
329 if (event->name != NULL)
330 l = strpcpy(&s, l, event->name);
331 else if (udev_device_get_devnode(dev) != NULL)
332 l = strpcpy(&s, l, udev_device_get_devnode(dev) + strlen("/dev/"));
334 l = strpcpy(&s, l, udev_device_get_sysname(dev));
337 struct udev_list_entry *list_entry;
339 list_entry = udev_device_get_devlinks_list_entry(dev);
340 if (list_entry == NULL)
342 l = strpcpy(&s, l, udev_list_entry_get_name(list_entry) + strlen("/dev/"));
343 udev_list_entry_foreach(list_entry, udev_list_entry_get_next(list_entry))
344 l = strpcpyl(&s, l, " ", udev_list_entry_get_name(list_entry) + strlen("/dev/"), NULL);
348 l = strpcpy(&s, l, "/dev");
351 l = strpcpy(&s, l, "/sys");
359 value = udev_device_get_property_value(event->dev, attr);
362 l = strpcpy(&s, l, value);
366 log_error("unknown substitution type=%i", type);
376 static int spawn_exec(struct udev_event *event,
377 const char *cmd, char *const argv[], char **envp, const sigset_t *sigmask,
378 int fd_stdout, int fd_stderr) {
382 /* discard child output or connect to pipe */
383 fd = open("/dev/null", O_RDWR);
385 dup2(fd, STDIN_FILENO);
387 dup2(fd, STDOUT_FILENO);
389 dup2(fd, STDERR_FILENO);
392 log_error("open /dev/null failed: %m");
395 /* connect pipes to std{out,err} */
396 if (fd_stdout >= 0) {
397 dup2(fd_stdout, STDOUT_FILENO);
400 if (fd_stderr >= 0) {
401 dup2(fd_stderr, STDERR_FILENO);
405 /* terminate child in case parent goes away */
406 prctl(PR_SET_PDEATHSIG, SIGTERM);
408 /* restore original udev sigmask before exec */
410 sigprocmask(SIG_SETMASK, sigmask, NULL);
412 execve(argv[0], argv, envp);
416 log_error("failed to execute '%s' '%s': %m", argv[0], cmd);
420 static void spawn_read(struct udev_event *event,
423 int fd_stdout, int fd_stderr,
424 char *result, size_t ressize) {
427 struct epoll_event ep_outpipe, ep_errpipe;
429 /* read from child if requested */
430 if (fd_stdout < 0 && fd_stderr < 0)
433 fd_ep = epoll_create1(EPOLL_CLOEXEC);
435 log_error("error creating epoll fd: %m");
439 if (fd_stdout >= 0) {
440 memzero(&ep_outpipe, sizeof(struct epoll_event));
441 ep_outpipe.events = EPOLLIN;
442 ep_outpipe.data.ptr = &fd_stdout;
443 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_stdout, &ep_outpipe) < 0) {
444 log_error("fail to add fd to epoll: %m");
449 if (fd_stderr >= 0) {
450 memzero(&ep_errpipe, sizeof(struct epoll_event));
451 ep_errpipe.events = EPOLLIN;
452 ep_errpipe.data.ptr = &fd_stderr;
453 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_stderr, &ep_errpipe) < 0) {
454 log_error("fail to add fd to epoll: %m");
459 /* read child output */
460 while (fd_stdout >= 0 || fd_stderr >= 0) {
463 struct epoll_event ev[4];
466 if (timeout_usec > 0) {
469 age_usec = now(CLOCK_MONOTONIC) - event->birth_usec;
470 if (age_usec >= timeout_usec) {
471 log_error("timeout '%s'", cmd);
474 timeout = ((timeout_usec - age_usec) / USEC_PER_MSEC) + MSEC_PER_SEC;
479 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
483 log_error("failed to poll: %m");
487 log_error("timeout '%s'", cmd);
491 for (i = 0; i < fdcount; i++) {
492 int *fd = (int *)ev[i].data.ptr;
494 if (ev[i].events & EPOLLIN) {
498 count = read(*fd, buf, sizeof(buf)-1);
503 /* store stdout result */
504 if (result != NULL && *fd == fd_stdout) {
505 if (respos + count < ressize) {
506 memcpy(&result[respos], buf, count);
509 log_error("'%s' ressize %zd too short", cmd, ressize);
513 /* log debug output only if we watch stderr */
514 if (fd_stderr >= 0) {
519 while ((line = strsep(&pos, "\n"))) {
520 if (pos != NULL || line[0] != '\0')
521 log_debug("'%s'(%s) '%s'", cmd, *fd == fd_stdout ? "out" : "err" , line);
524 } else if (ev[i].events & EPOLLHUP) {
525 if (epoll_ctl(fd_ep, EPOLL_CTL_DEL, *fd, NULL) < 0) {
526 log_error("failed to remove fd from epoll: %m");
534 /* return the child's stdout string */
536 result[respos] = '\0';
542 static int spawn_wait(struct udev_event *event,
544 const char *cmd, pid_t pid) {
545 struct pollfd pfd[1];
548 pfd[0].events = POLLIN;
549 pfd[0].fd = event->fd_signal;
555 if (timeout_usec > 0) {
558 age_usec = now(CLOCK_MONOTONIC) - event->birth_usec;
559 if (age_usec >= timeout_usec)
562 timeout = ((timeout_usec - age_usec) / USEC_PER_MSEC) + MSEC_PER_SEC;
567 fdcount = poll(pfd, 1, timeout);
572 log_error("failed to poll: %m");
576 log_error("timeout: killing '%s' [%u]", cmd, pid);
580 if (pfd[0].revents & POLLIN) {
581 struct signalfd_siginfo fdsi;
585 size = read(event->fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
586 if (size != sizeof(struct signalfd_siginfo))
589 switch (fdsi.ssi_signo) {
591 event->sigterm = true;
594 if (waitpid(pid, &status, WNOHANG) < 0)
596 if (WIFEXITED(status)) {
597 log_debug("'%s' [%u] exit with return code %i", cmd, pid, WEXITSTATUS(status));
598 if (WEXITSTATUS(status) != 0)
600 } else if (WIFSIGNALED(status)) {
601 log_error("'%s' [%u] terminated by signal %i (%s)", cmd, pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
603 } else if (WIFSTOPPED(status)) {
604 log_error("'%s' [%u] stopped", cmd, pid);
606 } else if (WIFCONTINUED(status)) {
607 log_error("'%s' [%u] continued", cmd, pid);
610 log_error("'%s' [%u] exit with status 0x%04x", cmd, pid, status);
622 int udev_build_argv(struct udev *udev, char *cmd, int *argc, char *argv[]) {
626 if (strchr(cmd, ' ') == NULL) {
632 while (pos != NULL && pos[0] != '\0') {
633 if (pos[0] == '\'') {
634 /* do not separate quotes */
636 argv[i] = strsep(&pos, "\'");
638 while (pos[0] == ' ')
641 argv[i] = strsep(&pos, " ");
643 while (pos[0] == ' ')
655 int udev_event_spawn(struct udev_event *event,
657 const char *cmd, char **envp, const sigset_t *sigmask,
658 char *result, size_t ressize) {
659 struct udev *udev = event->udev;
660 int outpipe[2] = {-1, -1};
661 int errpipe[2] = {-1, -1};
663 char arg[UTIL_PATH_SIZE];
665 char program[UTIL_PATH_SIZE];
668 strscpy(arg, sizeof(arg), cmd);
669 udev_build_argv(event->udev, arg, NULL, argv);
671 /* pipes from child to parent */
672 if (result != NULL || udev_get_log_priority(udev) >= LOG_INFO) {
673 if (pipe2(outpipe, O_NONBLOCK) != 0) {
675 log_error("pipe failed: %m");
679 if (udev_get_log_priority(udev) >= LOG_INFO) {
680 if (pipe2(errpipe, O_NONBLOCK) != 0) {
682 log_error("pipe failed: %m");
687 /* allow programs in /usr/lib/udev/ to be called without the path */
688 if (argv[0][0] != '/') {
689 strscpyl(program, sizeof(program), UDEVLIBEXECDIR "/", argv[0], NULL);
696 /* child closes parent's ends of pipes */
697 if (outpipe[READ_END] >= 0) {
698 close(outpipe[READ_END]);
699 outpipe[READ_END] = -1;
701 if (errpipe[READ_END] >= 0) {
702 close(errpipe[READ_END]);
703 errpipe[READ_END] = -1;
706 log_debug("starting '%s'", cmd);
708 spawn_exec(event, cmd, argv, envp, sigmask,
709 outpipe[WRITE_END], errpipe[WRITE_END]);
713 log_error("fork of '%s' failed: %m", cmd);
717 /* parent closed child's ends of pipes */
718 if (outpipe[WRITE_END] >= 0) {
719 close(outpipe[WRITE_END]);
720 outpipe[WRITE_END] = -1;
722 if (errpipe[WRITE_END] >= 0) {
723 close(errpipe[WRITE_END]);
724 errpipe[WRITE_END] = -1;
730 outpipe[READ_END], errpipe[READ_END],
733 err = spawn_wait(event, timeout_usec, cmd, pid);
737 if (outpipe[READ_END] >= 0)
738 close(outpipe[READ_END]);
739 if (outpipe[WRITE_END] >= 0)
740 close(outpipe[WRITE_END]);
741 if (errpipe[READ_END] >= 0)
742 close(errpipe[READ_END]);
743 if (errpipe[WRITE_END] >= 0)
744 close(errpipe[WRITE_END]);
748 static int rename_netif(struct udev_event *event) {
749 struct udev_device *dev = event->dev;
754 oldname = udev_device_get_sysname(dev);
756 strscpy(name, IFNAMSIZ, event->name);
758 r = rtnl_set_link_name(&event->rtnl, udev_device_get_ifindex(dev), name);
760 log_error("error changing net interface name '%s' to '%s': %s",
761 oldname, name, strerror(-r));
765 log_debug("renamed network interface '%s' to '%s'\n", oldname, name);
770 void udev_event_execute_rules(struct udev_event *event,
772 struct udev_rules *rules, const sigset_t *sigmask) {
773 struct udev_device *dev = event->dev;
775 if (udev_device_get_subsystem(dev) == NULL)
778 if (streq(udev_device_get_action(dev), "remove")) {
779 udev_device_read_db(dev, NULL);
780 udev_device_delete_db(dev);
781 udev_device_tag_index(dev, NULL, false);
783 if (major(udev_device_get_devnum(dev)) != 0)
784 udev_watch_end(event->udev, dev);
786 udev_rules_apply_to_event(rules, event, timeout_usec, sigmask);
788 if (major(udev_device_get_devnum(dev)) != 0)
789 udev_node_remove(dev);
791 event->dev_db = udev_device_new(event->udev);
792 if (event->dev_db != NULL) {
793 udev_device_set_syspath(event->dev_db, udev_device_get_syspath(dev));
794 udev_device_set_subsystem(event->dev_db, udev_device_get_subsystem(dev));
795 udev_device_read_db(event->dev_db, NULL);
796 udev_device_set_info_loaded(event->dev_db);
798 /* disable watch during event processing */
799 if (major(udev_device_get_devnum(dev)) != 0)
800 udev_watch_end(event->udev, event->dev_db);
803 if (major(udev_device_get_devnum(dev)) == 0 &&
804 streq(udev_device_get_action(dev), "move")) {
805 struct udev_list_entry *entry;
807 for ((entry = udev_device_get_properties_list_entry(event->dev_db)); entry; entry = udev_list_entry_get_next(entry)) {
808 const char *key, *value;
809 struct udev_list_entry *property;
811 key = udev_list_entry_get_name(entry);
812 value = udev_list_entry_get_value(entry);
814 property = udev_device_add_property(event->dev, key, value);
815 udev_list_entry_set_num(property, true);
819 udev_rules_apply_to_event(rules, event, timeout_usec, sigmask);
821 /* rename a new network interface, if needed */
822 if (udev_device_get_ifindex(dev) > 0 && streq(udev_device_get_action(dev), "add") &&
823 event->name != NULL && !streq(event->name, udev_device_get_sysname(dev))) {
824 char syspath[UTIL_PATH_SIZE];
828 r = rename_netif(event);
830 /* remember old name */
831 udev_device_add_property(dev, "INTERFACE_OLD", udev_device_get_sysname(dev));
833 /* now change the devpath, because the kernel device name has changed */
834 strscpy(syspath, sizeof(syspath), udev_device_get_syspath(dev));
835 pos = strrchr(syspath, '/');
838 strscpy(pos, sizeof(syspath) - (pos - syspath), event->name);
839 udev_device_set_syspath(event->dev, syspath);
840 udev_device_add_property(dev, "INTERFACE", udev_device_get_sysname(dev));
841 log_debug("changed devpath to '%s'", udev_device_get_devpath(dev));
846 if (major(udev_device_get_devnum(dev)) > 0) {
849 /* remove/update possible left-over symlinks from old database entry */
850 if (event->dev_db != NULL)
851 udev_node_update_old_links(dev, event->dev_db);
853 if (!event->owner_set)
854 event->uid = udev_device_get_devnode_uid(dev);
856 if (!event->group_set)
857 event->gid = udev_device_get_devnode_gid(dev);
859 if (!event->mode_set) {
860 if (udev_device_get_devnode_mode(dev) > 0) {
861 /* kernel supplied value */
862 event->mode = udev_device_get_devnode_mode(dev);
863 } else if (event->gid > 0) {
864 /* default 0660 if a group is assigned */
872 apply = streq(udev_device_get_action(dev), "add") || event->owner_set || event->group_set || event->mode_set;
873 udev_node_add(dev, apply, event->mode, event->uid, event->gid, &event->seclabel_list);
876 /* preserve old, or get new initialization timestamp */
877 if (event->dev_db != NULL && udev_device_get_usec_initialized(event->dev_db) > 0)
878 udev_device_set_usec_initialized(event->dev, udev_device_get_usec_initialized(event->dev_db));
879 else if (udev_device_get_usec_initialized(event->dev) == 0)
880 udev_device_set_usec_initialized(event->dev, now(CLOCK_MONOTONIC));
882 /* (re)write database file */
883 udev_device_update_db(dev);
884 udev_device_tag_index(dev, event->dev_db, true);
885 udev_device_set_is_initialized(dev);
887 udev_device_unref(event->dev_db);
888 event->dev_db = NULL;
892 void udev_event_execute_run(struct udev_event *event, usec_t timeout_usec, const sigset_t *sigmask) {
893 struct udev_list_entry *list_entry;
895 udev_list_entry_foreach(list_entry, udev_list_get_entry(&event->run_list)) {
896 const char *cmd = udev_list_entry_get_name(list_entry);
897 enum udev_builtin_cmd builtin_cmd = udev_list_entry_get_num(list_entry);
899 if (builtin_cmd < UDEV_BUILTIN_MAX) {
900 char command[UTIL_PATH_SIZE];
902 udev_event_apply_format(event, cmd, command, sizeof(command));
903 udev_builtin_run(event->dev, builtin_cmd, command, false);
905 char program[UTIL_PATH_SIZE];
908 if (event->exec_delay > 0) {
909 log_debug("delay execution of '%s'", program);
910 sleep(event->exec_delay);
913 udev_event_apply_format(event, cmd, program, sizeof(program));
914 envp = udev_device_get_properties_envp(event->dev);
915 udev_event_spawn(event, timeout_usec, program, envp, sigmask, NULL, 0);