2 * Copyright (C) 2003-2010 Kay Sievers <kay.sievers@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/ioctl.h>
29 #include <sys/prctl.h>
31 #include <sys/epoll.h>
33 #include <sys/socket.h>
34 #include <sys/signalfd.h>
35 #include <linux/sockios.h>
39 struct udev_event *udev_event_new(struct udev_device *dev)
41 struct udev *udev = udev_device_get_udev(dev);
42 struct udev_event *event;
44 event = calloc(1, sizeof(struct udev_event));
49 udev_list_init(udev, &event->run_list, false);
50 event->fd_signal = -1;
51 event->birth_usec = now_usec();
52 event->timeout_usec = 30 * 1000 * 1000;
56 void udev_event_unref(struct udev_event *event)
60 udev_list_cleanup(&event->run_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'\n", src);
182 if (i >= sizeof(attrbuf))
184 memcpy(attrbuf, from, i);
194 l = util_strpcpy(&s, l, udev_device_get_devpath(dev));
197 l = util_strpcpy(&s, l, udev_device_get_sysname(dev));
199 case SUBST_KERNEL_NUMBER:
200 if (udev_device_get_sysnum(dev) == NULL)
202 l = util_strpcpy(&s, l, udev_device_get_sysnum(dev));
205 if (event->dev_parent == NULL)
207 l = util_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 = util_strpcpy(&s, l, driver);
222 char num[UTIL_PATH_SIZE];
224 sprintf(num, "%d", major(udev_device_get_devnum(dev)));
225 l = util_strpcpy(&s, l, num);
229 char num[UTIL_PATH_SIZE];
231 sprintf(num, "%d", minor(udev_device_get_devnum(dev)));
232 l = util_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 util_strscpy(result, sizeof(result), event->program_result);
253 while (cpos[0] != '\0' && !isspace(cpos[0]))
255 while (isspace(cpos[0]))
259 log_error("requested part of result string not found\n");
262 util_strscpy(tmp, sizeof(tmp), cpos);
263 /* %{2+}c copies the whole string from the second part on */
264 if (rest[0] != '+') {
265 cpos = strchr(tmp, ' ');
269 l = util_strpcpy(&s, l, tmp);
271 l = util_strpcpy(&s, l, event->program_result);
276 const char *value = NULL;
277 char vbuf[UTIL_NAME_SIZE];
282 log_error("missing file parameter for attr\n");
286 /* try to read the value specified by "[dmi/id]product_name" */
287 if (util_resolve_subsys_kernel(event->udev, attr, vbuf, sizeof(vbuf), 1) == 0)
290 /* try to read the attribute the device */
292 value = udev_device_get_sysattr_value(event->dev, attr);
294 /* try to read the attribute of the parent device, other matches have selected */
295 if (value == NULL && event->dev_parent != NULL && event->dev_parent != event->dev)
296 value = udev_device_get_sysattr_value(event->dev_parent, attr);
301 /* strip trailing whitespace, and replace unwanted characters */
303 util_strscpy(vbuf, sizeof(vbuf), value);
305 while (len > 0 && isspace(vbuf[--len]))
307 count = util_replace_chars(vbuf, UDEV_ALLOWED_CHARS_INPUT);
309 log_debug("%i character(s) replaced\n" , count);
310 l = util_strpcpy(&s, l, vbuf);
314 struct udev_device *dev_parent;
317 dev_parent = udev_device_get_parent(event->dev);
318 if (dev_parent == NULL)
320 devnode = udev_device_get_devnode(dev_parent);
322 l = util_strpcpy(&s, l, devnode + strlen(TEST_PREFIX "/dev/"));
326 if (udev_device_get_devnode(dev) != NULL)
327 l = util_strpcpy(&s, l, udev_device_get_devnode(dev));
330 if (event->name != NULL)
331 l = util_strpcpy(&s, l, event->name);
332 else if (udev_device_get_devnode(dev) != NULL)
333 l = util_strpcpy(&s, l, udev_device_get_devnode(dev) + strlen(TEST_PREFIX "/dev/"));
335 l = util_strpcpy(&s, l, udev_device_get_sysname(dev));
338 struct udev_list_entry *list_entry;
340 list_entry = udev_device_get_devlinks_list_entry(dev);
341 if (list_entry == NULL)
343 l = util_strpcpy(&s, l, udev_list_entry_get_name(list_entry) + strlen(TEST_PREFIX "/dev/"));
344 udev_list_entry_foreach(list_entry, udev_list_entry_get_next(list_entry))
345 l = util_strpcpyl(&s, l, " ", udev_list_entry_get_name(list_entry) + strlen(TEST_PREFIX "/dev/"), NULL);
349 l = util_strpcpy(&s, l, TEST_PREFIX "/dev");
352 l = util_strpcpy(&s, l, TEST_PREFIX "/sys");
360 value = udev_device_get_property_value(event->dev, attr);
363 l = util_strpcpy(&s, l, value);
367 log_error("unknown substitution type=%i\n", type);
377 static int spawn_exec(struct udev_event *event,
378 const char *cmd, char *const argv[], char **envp, const sigset_t *sigmask,
379 int fd_stdout, int fd_stderr)
384 /* discard child output or connect to pipe */
385 fd = open("/dev/null", O_RDWR);
387 dup2(fd, STDIN_FILENO);
389 dup2(fd, STDOUT_FILENO);
391 dup2(fd, STDERR_FILENO);
394 log_error("open /dev/null failed: %m\n");
397 /* connect pipes to std{out,err} */
398 if (fd_stdout >= 0) {
399 dup2(fd_stdout, STDOUT_FILENO);
402 if (fd_stderr >= 0) {
403 dup2(fd_stderr, STDERR_FILENO);
407 /* terminate child in case parent goes away */
408 prctl(PR_SET_PDEATHSIG, SIGTERM);
410 /* restore original udev sigmask before exec */
412 sigprocmask(SIG_SETMASK, sigmask, NULL);
414 execve(argv[0], argv, envp);
418 log_error("failed to execute '%s' '%s': %m\n", argv[0], cmd);
422 static void spawn_read(struct udev_event *event,
424 int fd_stdout, int fd_stderr,
425 char *result, size_t ressize)
429 struct epoll_event ep_outpipe, ep_errpipe;
431 /* read from child if requested */
432 if (fd_stdout < 0 && fd_stderr < 0)
435 fd_ep = epoll_create1(EPOLL_CLOEXEC);
437 log_error("error creating epoll fd: %m\n");
441 if (fd_stdout >= 0) {
442 memset(&ep_outpipe, 0, sizeof(struct epoll_event));
443 ep_outpipe.events = EPOLLIN;
444 ep_outpipe.data.ptr = &fd_stdout;
445 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_stdout, &ep_outpipe) < 0) {
446 log_error("fail to add fd to epoll: %m\n");
451 if (fd_stderr >= 0) {
452 memset(&ep_errpipe, 0, sizeof(struct epoll_event));
453 ep_errpipe.events = EPOLLIN;
454 ep_errpipe.data.ptr = &fd_stderr;
455 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_stderr, &ep_errpipe) < 0) {
456 log_error("fail to add fd to epoll: %m\n");
461 /* read child output */
462 while (fd_stdout >= 0 || fd_stderr >= 0) {
465 struct epoll_event ev[4];
468 if (event->timeout_usec > 0) {
469 unsigned long long age_usec;
471 age_usec = now_usec() - event->birth_usec;
472 if (age_usec >= event->timeout_usec) {
473 log_error("timeout '%s'\n", cmd);
476 timeout = ((event->timeout_usec - age_usec) / 1000) + 1000;
481 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
485 log_error("failed to poll: %m\n");
489 log_error("timeout '%s'\n", cmd);
493 for (i = 0; i < fdcount; i++) {
494 int *fd = (int *)ev[i].data.ptr;
496 if (ev[i].events & EPOLLIN) {
500 count = read(*fd, buf, sizeof(buf)-1);
505 /* store stdout result */
506 if (result != NULL && *fd == fd_stdout) {
507 if (respos + count < ressize) {
508 memcpy(&result[respos], buf, count);
511 log_error("'%s' ressize %zd too short\n", cmd, ressize);
515 /* log debug output only if we watch stderr */
516 if (fd_stderr >= 0) {
521 while ((line = strsep(&pos, "\n"))) {
522 if (pos != NULL || line[0] != '\0')
523 log_debug("'%s'(%s) '%s'\n", cmd, *fd == fd_stdout ? "out" : "err" , line);
526 } else if (ev[i].events & EPOLLHUP) {
527 if (epoll_ctl(fd_ep, EPOLL_CTL_DEL, *fd, NULL) < 0) {
528 log_error("failed to remove fd from epoll: %m\n");
536 /* return the child's stdout string */
538 result[respos] = '\0';
544 static int spawn_wait(struct udev_event *event, const char *cmd, pid_t pid)
546 struct pollfd pfd[1];
549 pfd[0].events = POLLIN;
550 pfd[0].fd = event->fd_signal;
556 if (event->timeout_usec > 0) {
557 unsigned long long age_usec;
559 age_usec = now_usec() - event->birth_usec;
560 if (age_usec >= event->timeout_usec)
563 timeout = ((event->timeout_usec - age_usec) / 1000) + 1000;
568 fdcount = poll(pfd, 1, timeout);
573 log_error("failed to poll: %m\n");
577 log_error("timeout: killing '%s' [%u]\n", cmd, pid);
581 if (pfd[0].revents & POLLIN) {
582 struct signalfd_siginfo fdsi;
586 size = read(event->fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
587 if (size != sizeof(struct signalfd_siginfo))
590 switch (fdsi.ssi_signo) {
592 event->sigterm = true;
595 if (waitpid(pid, &status, WNOHANG) < 0)
597 if (WIFEXITED(status)) {
598 log_debug("'%s' [%u] exit with return code %i\n", cmd, pid, WEXITSTATUS(status));
599 if (WEXITSTATUS(status) != 0)
601 } else if (WIFSIGNALED(status)) {
602 log_error("'%s' [%u] terminated by signal %i (%s)\n", cmd, pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
604 } else if (WIFSTOPPED(status)) {
605 log_error("'%s' [%u] stopped\n", cmd, pid);
607 } else if (WIFCONTINUED(status)) {
608 log_error("'%s' [%u] continued\n", cmd, pid);
611 log_error("'%s' [%u] exit with status 0x%04x\n", cmd, pid, status);
623 int udev_build_argv(struct udev *udev, char *cmd, int *argc, char *argv[])
628 if (strchr(cmd, ' ') == NULL) {
634 while (pos != NULL && pos[0] != '\0') {
635 if (pos[0] == '\'') {
636 /* do not separate quotes */
638 argv[i] = strsep(&pos, "\'");
640 while (pos[0] == ' ')
643 argv[i] = strsep(&pos, " ");
645 while (pos[0] == ' ')
657 int udev_event_spawn(struct udev_event *event,
658 const char *cmd, char **envp, const sigset_t *sigmask,
659 char *result, size_t ressize)
661 struct udev *udev = event->udev;
662 int outpipe[2] = {-1, -1};
663 int errpipe[2] = {-1, -1};
665 char arg[UTIL_PATH_SIZE];
667 char program[UTIL_PATH_SIZE];
670 util_strscpy(arg, sizeof(arg), cmd);
671 udev_build_argv(event->udev, arg, NULL, argv);
673 /* pipes from child to parent */
674 if (result != NULL || udev_get_log_priority(udev) >= LOG_INFO) {
675 if (pipe2(outpipe, O_NONBLOCK) != 0) {
677 log_error("pipe failed: %m\n");
681 if (udev_get_log_priority(udev) >= LOG_INFO) {
682 if (pipe2(errpipe, O_NONBLOCK) != 0) {
684 log_error("pipe failed: %m\n");
689 /* allow programs in /usr/lib/udev/ to be called without the path */
690 if (argv[0][0] != '/') {
691 util_strscpyl(program, sizeof(program), UDEVLIBEXECDIR "/", argv[0], NULL);
698 /* child closes parent's ends of pipes */
699 if (outpipe[READ_END] >= 0) {
700 close(outpipe[READ_END]);
701 outpipe[READ_END] = -1;
703 if (errpipe[READ_END] >= 0) {
704 close(errpipe[READ_END]);
705 errpipe[READ_END] = -1;
708 log_debug("starting '%s'\n", cmd);
710 spawn_exec(event, cmd, argv, envp, sigmask,
711 outpipe[WRITE_END], errpipe[WRITE_END]);
715 log_error("fork of '%s' failed: %m\n", cmd);
719 /* parent closed child's ends of pipes */
720 if (outpipe[WRITE_END] >= 0) {
721 close(outpipe[WRITE_END]);
722 outpipe[WRITE_END] = -1;
724 if (errpipe[WRITE_END] >= 0) {
725 close(errpipe[WRITE_END]);
726 errpipe[WRITE_END] = -1;
729 spawn_read(event, cmd,
730 outpipe[READ_END], errpipe[READ_END],
733 err = spawn_wait(event, 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 void rename_netif_kernel_log(struct ifreq ifr)
753 klog = open("/dev/kmsg", O_WRONLY);
757 f = fdopen(klog, "w");
763 fprintf(f, "<30>udevd[%u]: renamed network interface %s to %s\n",
764 getpid(), ifr.ifr_name, ifr.ifr_newname);
768 static int rename_netif(struct udev_event *event)
770 struct udev_device *dev = event->dev;
776 log_debug("changing net interface name from '%s' to '%s'\n",
777 udev_device_get_sysname(dev), event->name);
779 sk = socket(PF_INET, SOCK_DGRAM, 0);
782 log_error("error opening socket: %m\n");
786 memset(&ifr, 0x00, sizeof(struct ifreq));
787 util_strscpy(ifr.ifr_name, IFNAMSIZ, udev_device_get_sysname(dev));
788 util_strscpy(ifr.ifr_newname, IFNAMSIZ, event->name);
789 err = ioctl(sk, SIOCSIFNAME, &ifr);
791 rename_netif_kernel_log(ifr);
795 /* keep trying if the destination interface name already exists */
800 /* free our own name, another process may wait for us */
801 snprintf(ifr.ifr_newname, IFNAMSIZ, "rename%u", udev_device_get_ifindex(dev));
802 err = ioctl(sk, SIOCSIFNAME, &ifr);
808 /* log temporary name */
809 rename_netif_kernel_log(ifr);
811 /* wait a maximum of 90 seconds for our target to become available */
812 util_strscpy(ifr.ifr_name, IFNAMSIZ, ifr.ifr_newname);
813 util_strscpy(ifr.ifr_newname, IFNAMSIZ, event->name);
816 const struct timespec duration = { 0, 1000 * 1000 * 1000 / 20 };
818 nanosleep(&duration, NULL);
820 err = ioctl(sk, SIOCSIFNAME, &ifr);
822 rename_netif_kernel_log(ifr);
832 log_error("error changing net interface name %s to %s: %m\n", ifr.ifr_name, ifr.ifr_newname);
837 int udev_event_execute_rules(struct udev_event *event, struct udev_rules *rules, const sigset_t *sigmask)
839 struct udev_device *dev = event->dev;
842 if (udev_device_get_subsystem(dev) == NULL)
845 if (strcmp(udev_device_get_action(dev), "remove") == 0) {
846 udev_device_read_db(dev, NULL);
847 udev_device_delete_db(dev);
848 udev_device_tag_index(dev, NULL, false);
850 if (major(udev_device_get_devnum(dev)) != 0)
851 udev_watch_end(event->udev, dev);
853 udev_rules_apply_to_event(rules, event, sigmask);
855 if (major(udev_device_get_devnum(dev)) != 0)
856 udev_node_remove(dev);
858 event->dev_db = udev_device_new_from_syspath(event->udev, udev_device_get_syspath(dev));
859 if (event->dev_db != NULL) {
860 udev_device_read_db(event->dev_db, NULL);
861 udev_device_set_info_loaded(event->dev_db);
863 /* disable watch during event processing */
864 if (major(udev_device_get_devnum(dev)) != 0)
865 udev_watch_end(event->udev, event->dev_db);
868 udev_rules_apply_to_event(rules, event, sigmask);
870 /* rename a new network interface, if needed */
871 if (udev_device_get_ifindex(dev) > 0 && strcmp(udev_device_get_action(dev), "add") == 0 &&
872 event->name != NULL && strcmp(event->name, udev_device_get_sysname(dev)) != 0) {
873 char syspath[UTIL_PATH_SIZE];
876 err = rename_netif(event);
878 log_debug("renamed netif to '%s'\n", event->name);
880 /* remember old name */
881 udev_device_add_property(dev, "INTERFACE_OLD", udev_device_get_sysname(dev));
883 /* now change the devpath, because the kernel device name has changed */
884 util_strscpy(syspath, sizeof(syspath), udev_device_get_syspath(dev));
885 pos = strrchr(syspath, '/');
888 util_strscpy(pos, sizeof(syspath) - (pos - syspath), event->name);
889 udev_device_set_syspath(event->dev, syspath);
890 udev_device_add_property(dev, "INTERFACE", udev_device_get_sysname(dev));
891 log_debug("changed devpath to '%s'\n", udev_device_get_devpath(dev));
896 if (major(udev_device_get_devnum(dev)) > 0) {
897 /* remove/update possible left-over symlinks from old database entry */
898 if (event->dev_db != NULL)
899 udev_node_update_old_links(dev, event->dev_db);
901 if (!event->mode_set) {
902 if (udev_device_get_devnode_mode(dev) > 0) {
903 /* kernel supplied value */
904 event->mode = udev_device_get_devnode_mode(dev);
905 } else if (event->gid > 0) {
906 /* default 0660 if a group is assigned */
914 udev_node_add(dev, event->mode, event->uid, event->gid);
917 /* preserve old, or get new initialization timestamp */
918 if (event->dev_db != NULL && udev_device_get_usec_initialized(event->dev_db) > 0)
919 udev_device_set_usec_initialized(event->dev, udev_device_get_usec_initialized(event->dev_db));
920 else if (udev_device_get_usec_initialized(event->dev) == 0)
921 udev_device_set_usec_initialized(event->dev, now_usec());
923 /* (re)write database file */
924 udev_device_update_db(dev);
925 udev_device_tag_index(dev, event->dev_db, true);
926 udev_device_set_is_initialized(dev);
928 udev_device_unref(event->dev_db);
929 event->dev_db = NULL;
934 void udev_event_execute_run(struct udev_event *event, const sigset_t *sigmask)
936 struct udev_list_entry *list_entry;
938 udev_list_entry_foreach(list_entry, udev_list_get_entry(&event->run_list)) {
939 const char *cmd = udev_list_entry_get_name(list_entry);
940 enum udev_builtin_cmd builtin_cmd = udev_list_entry_get_num(list_entry);
942 if (builtin_cmd < UDEV_BUILTIN_MAX) {
943 char command[UTIL_PATH_SIZE];
945 udev_event_apply_format(event, cmd, command, sizeof(command));
946 udev_builtin_run(event->dev, builtin_cmd, command, false);
948 char program[UTIL_PATH_SIZE];
951 if (event->exec_delay > 0) {
952 log_debug("delay execution of '%s'\n", program);
953 sleep(event->exec_delay);
956 udev_event_apply_format(event, cmd, program, sizeof(program));
957 envp = udev_device_get_properties_envp(event->dev);
958 udev_event_spawn(event, program, envp, sigmask, NULL, 0);