chiark / gitweb /
readahead: avoid running of readahead services if readahead is already done
[elogind.git] / src / udev / udev-event.c
1 /*
2  * Copyright (C) 2003-2010 Kay Sievers <kay.sievers@vrfy.org>
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <stddef.h>
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <errno.h>
24 #include <ctype.h>
25 #include <string.h>
26 #include <time.h>
27 #include <net/if.h>
28 #include <sys/ioctl.h>
29 #include <sys/prctl.h>
30 #include <sys/poll.h>
31 #include <sys/epoll.h>
32 #include <sys/wait.h>
33 #include <sys/socket.h>
34 #include <sys/signalfd.h>
35 #include <linux/sockios.h>
36
37 #include "udev.h"
38
39 struct udev_event *udev_event_new(struct udev_device *dev)
40 {
41         struct udev *udev = udev_device_get_udev(dev);
42         struct udev_event *event;
43
44         event = calloc(1, sizeof(struct udev_event));
45         if (event == NULL)
46                 return NULL;
47         event->dev = dev;
48         event->udev = udev;
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;
53         return event;
54 }
55
56 void udev_event_unref(struct udev_event *event)
57 {
58         if (event == NULL)
59                 return;
60         udev_list_cleanup(&event->run_list);
61         free(event->program_result);
62         free(event->name);
63         free(event);
64 }
65
66 size_t udev_event_apply_format(struct udev_event *event, const char *src, char *dest, size_t size)
67 {
68         struct udev_device *dev = event->dev;
69         enum subst_type {
70                 SUBST_UNKNOWN,
71                 SUBST_DEVNODE,
72                 SUBST_ATTR,
73                 SUBST_ENV,
74                 SUBST_KERNEL,
75                 SUBST_KERNEL_NUMBER,
76                 SUBST_DRIVER,
77                 SUBST_DEVPATH,
78                 SUBST_ID,
79                 SUBST_MAJOR,
80                 SUBST_MINOR,
81                 SUBST_RESULT,
82                 SUBST_PARENT,
83                 SUBST_NAME,
84                 SUBST_LINKS,
85                 SUBST_ROOT,
86                 SUBST_SYS,
87         };
88         static const struct subst_map {
89                 const char *name;
90                 const char fmt;
91                 enum subst_type type;
92         } 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 },
111         };
112         const char *from;
113         char *s;
114         size_t l;
115
116         from = src;
117         s = dest;
118         l = size;
119
120         for (;;) {
121                 enum subst_type type = SUBST_UNKNOWN;
122                 char attrbuf[UTIL_PATH_SIZE];
123                 char *attr = NULL;
124
125                 while (from[0] != '\0') {
126                         if (from[0] == '$') {
127                                 /* substitute named variable */
128                                 unsigned int i;
129
130                                 if (from[1] == '$') {
131                                         from++;
132                                         goto copy;
133                                 }
134
135                                 for (i = 0; i < ELEMENTSOF(map); i++) {
136                                         if (startswith(&from[1], map[i].name)) {
137                                                 type = map[i].type;
138                                                 from += strlen(map[i].name)+1;
139                                                 goto subst;
140                                         }
141                                 }
142                         } else if (from[0] == '%') {
143                                 /* substitute format char */
144                                 unsigned int i;
145
146                                 if (from[1] == '%') {
147                                         from++;
148                                         goto copy;
149                                 }
150
151                                 for (i = 0; i < ELEMENTSOF(map); i++) {
152                                         if (from[1] == map[i].fmt) {
153                                                 type = map[i].type;
154                                                 from += 2;
155                                                 goto subst;
156                                         }
157                                 }
158                         }
159 copy:
160                         /* copy char */
161                         if (l == 0)
162                                 goto out;
163                         s[0] = from[0];
164                         from++;
165                         s++;
166                         l--;
167                 }
168
169                 goto out;
170 subst:
171                 /* extract possible $format{attr} */
172                 if (from[0] == '{') {
173                         unsigned int i;
174
175                         from++;
176                         for (i = 0; from[i] != '}'; i++) {
177                                 if (from[i] == '\0') {
178                                         log_error("missing closing brace for format '%s'\n", src);
179                                         goto out;
180                                 }
181                         }
182                         if (i >= sizeof(attrbuf))
183                                 goto out;
184                         memcpy(attrbuf, from, i);
185                         attrbuf[i] = '\0';
186                         from += i+1;
187                         attr = attrbuf;
188                 } else {
189                         attr = NULL;
190                 }
191
192                 switch (type) {
193                 case SUBST_DEVPATH:
194                         l = util_strpcpy(&s, l, udev_device_get_devpath(dev));
195                         break;
196                 case SUBST_KERNEL:
197                         l = util_strpcpy(&s, l, udev_device_get_sysname(dev));
198                         break;
199                 case SUBST_KERNEL_NUMBER:
200                         if (udev_device_get_sysnum(dev) == NULL)
201                                 break;
202                         l = util_strpcpy(&s, l, udev_device_get_sysnum(dev));
203                         break;
204                 case SUBST_ID:
205                         if (event->dev_parent == NULL)
206                                 break;
207                         l = util_strpcpy(&s, l, udev_device_get_sysname(event->dev_parent));
208                         break;
209                 case SUBST_DRIVER: {
210                         const char *driver;
211
212                         if (event->dev_parent == NULL)
213                                 break;
214
215                         driver = udev_device_get_driver(event->dev_parent);
216                         if (driver == NULL)
217                                 break;
218                         l = util_strpcpy(&s, l, driver);
219                         break;
220                 }
221                 case SUBST_MAJOR: {
222                         char num[UTIL_PATH_SIZE];
223
224                         sprintf(num, "%d", major(udev_device_get_devnum(dev)));
225                         l = util_strpcpy(&s, l, num);
226                         break;
227                 }
228                 case SUBST_MINOR: {
229                         char num[UTIL_PATH_SIZE];
230
231                         sprintf(num, "%d", minor(udev_device_get_devnum(dev)));
232                         l = util_strpcpy(&s, l, num);
233                         break;
234                 }
235                 case SUBST_RESULT: {
236                         char *rest;
237                         int i;
238
239                         if (event->program_result == NULL)
240                                 break;
241                         /* get part part of the result string */
242                         i = 0;
243                         if (attr != NULL)
244                                 i = strtoul(attr, &rest, 10);
245                         if (i > 0) {
246                                 char result[UTIL_PATH_SIZE];
247                                 char tmp[UTIL_PATH_SIZE];
248                                 char *cpos;
249
250                                 util_strscpy(result, sizeof(result), event->program_result);
251                                 cpos = result;
252                                 while (--i) {
253                                         while (cpos[0] != '\0' && !isspace(cpos[0]))
254                                                 cpos++;
255                                         while (isspace(cpos[0]))
256                                                 cpos++;
257                                 }
258                                 if (i > 0) {
259                                         log_error("requested part of result string not found\n");
260                                         break;
261                                 }
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, ' ');
266                                         if (cpos)
267                                                 cpos[0] = '\0';
268                                 }
269                                 l = util_strpcpy(&s, l, tmp);
270                         } else {
271                                 l = util_strpcpy(&s, l, event->program_result);
272                         }
273                         break;
274                 }
275                 case SUBST_ATTR: {
276                         const char *value = NULL;
277                         char vbuf[UTIL_NAME_SIZE];
278                         size_t len;
279                         int count;
280
281                         if (attr == NULL) {
282                                 log_error("missing file parameter for attr\n");
283                                 break;
284                         }
285
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)
288                                 value = vbuf;
289
290                         /* try to read the attribute the device */
291                         if (value == NULL)
292                                 value = udev_device_get_sysattr_value(event->dev, attr);
293
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);
297
298                         if (value == NULL)
299                                 break;
300
301                         /* strip trailing whitespace, and replace unwanted characters */
302                         if (value != vbuf)
303                                 util_strscpy(vbuf, sizeof(vbuf), value);
304                         len = strlen(vbuf);
305                         while (len > 0 && isspace(vbuf[--len]))
306                                 vbuf[len] = '\0';
307                         count = util_replace_chars(vbuf, UDEV_ALLOWED_CHARS_INPUT);
308                         if (count > 0)
309                                 log_debug("%i character(s) replaced\n" , count);
310                         l = util_strpcpy(&s, l, vbuf);
311                         break;
312                 }
313                 case SUBST_PARENT: {
314                         struct udev_device *dev_parent;
315                         const char *devnode;
316
317                         dev_parent = udev_device_get_parent(event->dev);
318                         if (dev_parent == NULL)
319                                 break;
320                         devnode = udev_device_get_devnode(dev_parent);
321                         if (devnode != NULL)
322                                 l = util_strpcpy(&s, l, devnode + strlen(TEST_PREFIX "/dev/"));
323                         break;
324                 }
325                 case SUBST_DEVNODE:
326                         if (udev_device_get_devnode(dev) != NULL)
327                                 l = util_strpcpy(&s, l, udev_device_get_devnode(dev));
328                         break;
329                 case SUBST_NAME:
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/"));
334                         else
335                                 l = util_strpcpy(&s, l, udev_device_get_sysname(dev));
336                         break;
337                 case SUBST_LINKS: {
338                         struct udev_list_entry *list_entry;
339
340                         list_entry = udev_device_get_devlinks_list_entry(dev);
341                         if (list_entry == NULL)
342                                 break;
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);
346                         break;
347                 }
348                 case SUBST_ROOT:
349                         l = util_strpcpy(&s, l, TEST_PREFIX "/dev");
350                         break;
351                 case SUBST_SYS:
352                         l = util_strpcpy(&s, l, TEST_PREFIX "/sys");
353                         break;
354                 case SUBST_ENV:
355                         if (attr == NULL) {
356                                 break;
357                         } else {
358                                 const char *value;
359
360                                 value = udev_device_get_property_value(event->dev, attr);
361                                 if (value == NULL)
362                                         break;
363                                 l = util_strpcpy(&s, l, value);
364                                 break;
365                         }
366                 default:
367                         log_error("unknown substitution type=%i\n", type);
368                         break;
369                 }
370         }
371
372 out:
373         s[0] = '\0';
374         return l;
375 }
376
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)
380 {
381         int err;
382         int fd;
383
384         /* discard child output or connect to pipe */
385         fd = open("/dev/null", O_RDWR);
386         if (fd >= 0) {
387                 dup2(fd, STDIN_FILENO);
388                 if (fd_stdout < 0)
389                         dup2(fd, STDOUT_FILENO);
390                 if (fd_stderr < 0)
391                         dup2(fd, STDERR_FILENO);
392                 close(fd);
393         } else {
394                 log_error("open /dev/null failed: %m\n");
395         }
396
397         /* connect pipes to std{out,err} */
398         if (fd_stdout >= 0) {
399                 dup2(fd_stdout, STDOUT_FILENO);
400                         close(fd_stdout);
401         }
402         if (fd_stderr >= 0) {
403                 dup2(fd_stderr, STDERR_FILENO);
404                 close(fd_stderr);
405         }
406
407         /* terminate child in case parent goes away */
408         prctl(PR_SET_PDEATHSIG, SIGTERM);
409
410         /* restore original udev sigmask before exec */
411         if (sigmask)
412                 sigprocmask(SIG_SETMASK, sigmask, NULL);
413
414         execve(argv[0], argv, envp);
415
416         /* exec failed */
417         err = -errno;
418         log_error("failed to execute '%s' '%s': %m\n", argv[0], cmd);
419         return err;
420 }
421
422 static void spawn_read(struct udev_event *event,
423                       const char *cmd,
424                       int fd_stdout, int fd_stderr,
425                       char *result, size_t ressize)
426 {
427         size_t respos = 0;
428         int fd_ep = -1;
429         struct epoll_event ep_outpipe, ep_errpipe;
430
431         /* read from child if requested */
432         if (fd_stdout < 0 && fd_stderr < 0)
433                 return;
434
435         fd_ep = epoll_create1(EPOLL_CLOEXEC);
436         if (fd_ep < 0) {
437                 log_error("error creating epoll fd: %m\n");
438                 goto out;
439         }
440
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");
447                         goto out;
448                 }
449         }
450
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");
457                         goto out;
458                 }
459         }
460
461         /* read child output */
462         while (fd_stdout >= 0 || fd_stderr >= 0) {
463                 int timeout;
464                 int fdcount;
465                 struct epoll_event ev[4];
466                 int i;
467
468                 if (event->timeout_usec > 0) {
469                         unsigned long long age_usec;
470
471                         age_usec = now_usec() - event->birth_usec;
472                         if (age_usec >= event->timeout_usec) {
473                                 log_error("timeout '%s'\n", cmd);
474                                 goto out;
475                         }
476                         timeout = ((event->timeout_usec - age_usec) / 1000) + 1000;
477                 } else {
478                         timeout = -1;
479                 }
480
481                 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
482                 if (fdcount < 0) {
483                         if (errno == EINTR)
484                                 continue;
485                         log_error("failed to poll: %m\n");
486                         goto out;
487                 }
488                 if (fdcount == 0) {
489                         log_error("timeout '%s'\n", cmd);
490                         goto out;
491                 }
492
493                 for (i = 0; i < fdcount; i++) {
494                         int *fd = (int *)ev[i].data.ptr;
495
496                         if (ev[i].events & EPOLLIN) {
497                                 ssize_t count;
498                                 char buf[4096];
499
500                                 count = read(*fd, buf, sizeof(buf)-1);
501                                 if (count <= 0)
502                                         continue;
503                                 buf[count] = '\0';
504
505                                 /* store stdout result */
506                                 if (result != NULL && *fd == fd_stdout) {
507                                         if (respos + count < ressize) {
508                                                 memcpy(&result[respos], buf, count);
509                                                 respos += count;
510                                         } else {
511                                                 log_error("'%s' ressize %zd too short\n", cmd, ressize);
512                                         }
513                                 }
514
515                                 /* log debug output only if we watch stderr */
516                                 if (fd_stderr >= 0) {
517                                         char *pos;
518                                         char *line;
519
520                                         pos = buf;
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);
524                                         }
525                                 }
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");
529                                         goto out;
530                                 }
531                                 *fd = -1;
532                         }
533                 }
534         }
535
536         /* return the child's stdout string */
537         if (result != NULL)
538                 result[respos] = '\0';
539 out:
540         if (fd_ep >= 0)
541                 close(fd_ep);
542 }
543
544 static int spawn_wait(struct udev_event *event, const char *cmd, pid_t pid)
545 {
546         struct pollfd pfd[1];
547         int err = 0;
548
549         pfd[0].events = POLLIN;
550         pfd[0].fd = event->fd_signal;
551
552         while (pid > 0) {
553                 int timeout;
554                 int fdcount;
555
556                 if (event->timeout_usec > 0) {
557                         unsigned long long age_usec;
558
559                         age_usec = now_usec() - event->birth_usec;
560                         if (age_usec >= event->timeout_usec)
561                                 timeout = 1000;
562                         else
563                                 timeout = ((event->timeout_usec - age_usec) / 1000) + 1000;
564                 } else {
565                         timeout = -1;
566                 }
567
568                 fdcount = poll(pfd, 1, timeout);
569                 if (fdcount < 0) {
570                         if (errno == EINTR)
571                                 continue;
572                         err = -errno;
573                         log_error("failed to poll: %m\n");
574                         goto out;
575                 }
576                 if (fdcount == 0) {
577                         log_error("timeout: killing '%s' [%u]\n", cmd, pid);
578                         kill(pid, SIGKILL);
579                 }
580
581                 if (pfd[0].revents & POLLIN) {
582                         struct signalfd_siginfo fdsi;
583                         int status;
584                         ssize_t size;
585
586                         size = read(event->fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
587                         if (size != sizeof(struct signalfd_siginfo))
588                                 continue;
589
590                         switch (fdsi.ssi_signo) {
591                         case SIGTERM:
592                                 event->sigterm = true;
593                                 break;
594                         case SIGCHLD:
595                                 if (waitpid(pid, &status, WNOHANG) < 0)
596                                         break;
597                                 if (WIFEXITED(status)) {
598                                         log_debug("'%s' [%u] exit with return code %i\n", cmd, pid, WEXITSTATUS(status));
599                                         if (WEXITSTATUS(status) != 0)
600                                                 err = -1;
601                                 } else if (WIFSIGNALED(status)) {
602                                         log_error("'%s' [%u] terminated by signal %i (%s)\n", cmd, pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
603                                         err = -1;
604                                 } else if (WIFSTOPPED(status)) {
605                                         log_error("'%s' [%u] stopped\n", cmd, pid);
606                                         err = -1;
607                                 } else if (WIFCONTINUED(status)) {
608                                         log_error("'%s' [%u] continued\n", cmd, pid);
609                                         err = -1;
610                                 } else {
611                                         log_error("'%s' [%u] exit with status 0x%04x\n", cmd, pid, status);
612                                         err = -1;
613                                 }
614                                 pid = 0;
615                                 break;
616                         }
617                 }
618         }
619 out:
620         return err;
621 }
622
623 int udev_build_argv(struct udev *udev, char *cmd, int *argc, char *argv[])
624 {
625         int i = 0;
626         char *pos;
627
628         if (strchr(cmd, ' ') == NULL) {
629                 argv[i++] = cmd;
630                 goto out;
631         }
632
633         pos = cmd;
634         while (pos != NULL && pos[0] != '\0') {
635                 if (pos[0] == '\'') {
636                         /* do not separate quotes */
637                         pos++;
638                         argv[i] = strsep(&pos, "\'");
639                         if (pos != NULL)
640                                 while (pos[0] == ' ')
641                                         pos++;
642                 } else {
643                         argv[i] = strsep(&pos, " ");
644                         if (pos != NULL)
645                                 while (pos[0] == ' ')
646                                         pos++;
647                 }
648                 i++;
649         }
650 out:
651         argv[i] = NULL;
652         if (argc)
653                 *argc = i;
654         return 0;
655 }
656
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)
660 {
661         struct udev *udev = event->udev;
662         int outpipe[2] = {-1, -1};
663         int errpipe[2] = {-1, -1};
664         pid_t pid;
665         char arg[UTIL_PATH_SIZE];
666         char *argv[128];
667         char program[UTIL_PATH_SIZE];
668         int err = 0;
669
670         util_strscpy(arg, sizeof(arg), cmd);
671         udev_build_argv(event->udev, arg, NULL, argv);
672
673         /* pipes from child to parent */
674         if (result != NULL || udev_get_log_priority(udev) >= LOG_INFO) {
675                 if (pipe2(outpipe, O_NONBLOCK) != 0) {
676                         err = -errno;
677                         log_error("pipe failed: %m\n");
678                         goto out;
679                 }
680         }
681         if (udev_get_log_priority(udev) >= LOG_INFO) {
682                 if (pipe2(errpipe, O_NONBLOCK) != 0) {
683                         err = -errno;
684                         log_error("pipe failed: %m\n");
685                         goto out;
686                 }
687         }
688
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);
692                 argv[0] = program;
693         }
694
695         pid = fork();
696         switch(pid) {
697         case 0:
698                 /* child closes parent's ends of pipes */
699                 if (outpipe[READ_END] >= 0) {
700                         close(outpipe[READ_END]);
701                         outpipe[READ_END] = -1;
702                 }
703                 if (errpipe[READ_END] >= 0) {
704                         close(errpipe[READ_END]);
705                         errpipe[READ_END] = -1;
706                 }
707
708                 log_debug("starting '%s'\n", cmd);
709
710                 spawn_exec(event, cmd, argv, envp, sigmask,
711                            outpipe[WRITE_END], errpipe[WRITE_END]);
712
713                 _exit(2 );
714         case -1:
715                 log_error("fork of '%s' failed: %m\n", cmd);
716                 err = -1;
717                 goto out;
718         default:
719                 /* parent closed child's ends of pipes */
720                 if (outpipe[WRITE_END] >= 0) {
721                         close(outpipe[WRITE_END]);
722                         outpipe[WRITE_END] = -1;
723                 }
724                 if (errpipe[WRITE_END] >= 0) {
725                         close(errpipe[WRITE_END]);
726                         errpipe[WRITE_END] = -1;
727                 }
728
729                 spawn_read(event, cmd,
730                          outpipe[READ_END], errpipe[READ_END],
731                          result, ressize);
732
733                 err = spawn_wait(event, cmd, pid);
734         }
735
736 out:
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]);
745         return err;
746 }
747
748 static void rename_netif_kernel_log(struct ifreq ifr)
749 {
750         int klog;
751         FILE *f;
752
753         klog = open("/dev/kmsg", O_WRONLY);
754         if (klog < 0)
755                 return;
756
757         f = fdopen(klog, "w");
758         if (f == NULL) {
759                 close(klog);
760                 return;
761         }
762
763         fprintf(f, "<30>udevd[%u]: renamed network interface %s to %s\n",
764                 getpid(), ifr.ifr_name, ifr.ifr_newname);
765         fclose(f);
766 }
767
768 static int rename_netif(struct udev_event *event)
769 {
770         struct udev_device *dev = event->dev;
771         int sk;
772         struct ifreq ifr;
773         int loop;
774         int err;
775
776         log_debug("changing net interface name from '%s' to '%s'\n",
777                   udev_device_get_sysname(dev), event->name);
778
779         sk = socket(PF_INET, SOCK_DGRAM, 0);
780         if (sk < 0) {
781                 err = -errno;
782                 log_error("error opening socket: %m\n");
783                 return err;
784         }
785
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);
790         if (err == 0) {
791                 rename_netif_kernel_log(ifr);
792                 goto out;
793         }
794
795         /* keep trying if the destination interface name already exists */
796         err = -errno;
797         if (err != -EEXIST)
798                 goto out;
799
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);
803         if (err < 0) {
804                 err = -errno;
805                 goto out;
806         }
807
808         /* log temporary name */
809         rename_netif_kernel_log(ifr);
810
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);
814         loop = 90 * 20;
815         while (loop--) {
816                 const struct timespec duration = { 0, 1000 * 1000 * 1000 / 20 };
817
818                 nanosleep(&duration, NULL);
819
820                 err = ioctl(sk, SIOCSIFNAME, &ifr);
821                 if (err == 0) {
822                         rename_netif_kernel_log(ifr);
823                         break;
824                 }
825                 err = -errno;
826                 if (err != -EEXIST)
827                         break;
828         }
829
830 out:
831         if (err < 0)
832                 log_error("error changing net interface name %s to %s: %m\n", ifr.ifr_name, ifr.ifr_newname);
833         close(sk);
834         return err;
835 }
836
837 int udev_event_execute_rules(struct udev_event *event, struct udev_rules *rules, const sigset_t *sigmask)
838 {
839         struct udev_device *dev = event->dev;
840         int err = 0;
841
842         if (udev_device_get_subsystem(dev) == NULL)
843                 return -1;
844
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);
849
850                 if (major(udev_device_get_devnum(dev)) != 0)
851                         udev_watch_end(event->udev, dev);
852
853                 udev_rules_apply_to_event(rules, event, sigmask);
854
855                 if (major(udev_device_get_devnum(dev)) != 0)
856                         udev_node_remove(dev);
857         } else {
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);
862
863                         /* disable watch during event processing */
864                         if (major(udev_device_get_devnum(dev)) != 0)
865                                 udev_watch_end(event->udev, event->dev_db);
866                 }
867
868                 udev_rules_apply_to_event(rules, event, sigmask);
869
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];
874                         char *pos;
875
876                         err = rename_netif(event);
877                         if (err == 0) {
878                                 log_debug("renamed netif to '%s'\n", event->name);
879
880                                 /* remember old name */
881                                 udev_device_add_property(dev, "INTERFACE_OLD", udev_device_get_sysname(dev));
882
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, '/');
886                                 if (pos != NULL) {
887                                         pos++;
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));
892                                 }
893                         }
894                 }
895
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);
900
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 */
907                                         event->mode = 0660;
908                                 } else {
909                                         /* default 0600 */
910                                         event->mode = 0600;
911                                 }
912                         }
913
914                         udev_node_add(dev, event->mode, event->uid, event->gid);
915                 }
916
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());
922
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);
927
928                 udev_device_unref(event->dev_db);
929                 event->dev_db = NULL;
930         }
931         return err;
932 }
933
934 void udev_event_execute_run(struct udev_event *event, const sigset_t *sigmask)
935 {
936         struct udev_list_entry *list_entry;
937
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);
941
942                 if (builtin_cmd < UDEV_BUILTIN_MAX) {
943                         char command[UTIL_PATH_SIZE];
944
945                         udev_event_apply_format(event, cmd, command, sizeof(command));
946                         udev_builtin_run(event->dev, builtin_cmd, command, false);
947                 } else {
948                         char program[UTIL_PATH_SIZE];
949                         char **envp;
950
951                         if (event->exec_delay > 0) {
952                                 log_debug("delay execution of '%s'\n", program);
953                                 sleep(event->exec_delay);
954                         }
955
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);
959                 }
960         }
961 }