chiark / gitweb /
udev: drop duplicate logging
[elogind.git] / src / udev / udev-event.c
1 /*
2  * Copyright (C) 2003-2013 Kay Sievers <kay@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/prctl.h>
29 #include <sys/poll.h>
30 #include <sys/epoll.h>
31 #include <sys/wait.h>
32 #include <sys/signalfd.h>
33
34 #include "udev.h"
35 #include "rtnl-util.h"
36
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;
40
41         event = new0(struct udev_event, 1);
42         if (event == NULL)
43                 return NULL;
44         event->dev = dev;
45         event->udev = udev;
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);
50         return event;
51 }
52
53 void udev_event_unref(struct udev_event *event) {
54         if (event == NULL)
55                 return;
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);
60         free(event->name);
61         free(event);
62 }
63
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;
66         enum subst_type {
67                 SUBST_UNKNOWN,
68                 SUBST_DEVNODE,
69                 SUBST_ATTR,
70                 SUBST_ENV,
71                 SUBST_KERNEL,
72                 SUBST_KERNEL_NUMBER,
73                 SUBST_DRIVER,
74                 SUBST_DEVPATH,
75                 SUBST_ID,
76                 SUBST_MAJOR,
77                 SUBST_MINOR,
78                 SUBST_RESULT,
79                 SUBST_PARENT,
80                 SUBST_NAME,
81                 SUBST_LINKS,
82                 SUBST_ROOT,
83                 SUBST_SYS,
84         };
85         static const struct subst_map {
86                 const char *name;
87                 const char fmt;
88                 enum subst_type type;
89         } 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 },
108         };
109         const char *from;
110         char *s;
111         size_t l;
112
113         from = src;
114         s = dest;
115         l = size;
116
117         for (;;) {
118                 enum subst_type type = SUBST_UNKNOWN;
119                 char attrbuf[UTIL_PATH_SIZE];
120                 char *attr = NULL;
121
122                 while (from[0] != '\0') {
123                         if (from[0] == '$') {
124                                 /* substitute named variable */
125                                 unsigned int i;
126
127                                 if (from[1] == '$') {
128                                         from++;
129                                         goto copy;
130                                 }
131
132                                 for (i = 0; i < ELEMENTSOF(map); i++) {
133                                         if (startswith(&from[1], map[i].name)) {
134                                                 type = map[i].type;
135                                                 from += strlen(map[i].name)+1;
136                                                 goto subst;
137                                         }
138                                 }
139                         } else if (from[0] == '%') {
140                                 /* substitute format char */
141                                 unsigned int i;
142
143                                 if (from[1] == '%') {
144                                         from++;
145                                         goto copy;
146                                 }
147
148                                 for (i = 0; i < ELEMENTSOF(map); i++) {
149                                         if (from[1] == map[i].fmt) {
150                                                 type = map[i].type;
151                                                 from += 2;
152                                                 goto subst;
153                                         }
154                                 }
155                         }
156 copy:
157                         /* copy char */
158                         if (l == 0)
159                                 goto out;
160                         s[0] = from[0];
161                         from++;
162                         s++;
163                         l--;
164                 }
165
166                 goto out;
167 subst:
168                 /* extract possible $format{attr} */
169                 if (from[0] == '{') {
170                         unsigned int i;
171
172                         from++;
173                         for (i = 0; from[i] != '}'; i++) {
174                                 if (from[i] == '\0') {
175                                         log_error("missing closing brace for format '%s'", src);
176                                         goto out;
177                                 }
178                         }
179                         if (i >= sizeof(attrbuf))
180                                 goto out;
181                         memcpy(attrbuf, from, i);
182                         attrbuf[i] = '\0';
183                         from += i+1;
184                         attr = attrbuf;
185                 } else {
186                         attr = NULL;
187                 }
188
189                 switch (type) {
190                 case SUBST_DEVPATH:
191                         l = strpcpy(&s, l, udev_device_get_devpath(dev));
192                         break;
193                 case SUBST_KERNEL:
194                         l = strpcpy(&s, l, udev_device_get_sysname(dev));
195                         break;
196                 case SUBST_KERNEL_NUMBER:
197                         if (udev_device_get_sysnum(dev) == NULL)
198                                 break;
199                         l = strpcpy(&s, l, udev_device_get_sysnum(dev));
200                         break;
201                 case SUBST_ID:
202                         if (event->dev_parent == NULL)
203                                 break;
204                         l = strpcpy(&s, l, udev_device_get_sysname(event->dev_parent));
205                         break;
206                 case SUBST_DRIVER: {
207                         const char *driver;
208
209                         if (event->dev_parent == NULL)
210                                 break;
211
212                         driver = udev_device_get_driver(event->dev_parent);
213                         if (driver == NULL)
214                                 break;
215                         l = strpcpy(&s, l, driver);
216                         break;
217                 }
218                 case SUBST_MAJOR: {
219                         char num[UTIL_PATH_SIZE];
220
221                         sprintf(num, "%d", major(udev_device_get_devnum(dev)));
222                         l = strpcpy(&s, l, num);
223                         break;
224                 }
225                 case SUBST_MINOR: {
226                         char num[UTIL_PATH_SIZE];
227
228                         sprintf(num, "%d", minor(udev_device_get_devnum(dev)));
229                         l = strpcpy(&s, l, num);
230                         break;
231                 }
232                 case SUBST_RESULT: {
233                         char *rest;
234                         int i;
235
236                         if (event->program_result == NULL)
237                                 break;
238                         /* get part part of the result string */
239                         i = 0;
240                         if (attr != NULL)
241                                 i = strtoul(attr, &rest, 10);
242                         if (i > 0) {
243                                 char result[UTIL_PATH_SIZE];
244                                 char tmp[UTIL_PATH_SIZE];
245                                 char *cpos;
246
247                                 strscpy(result, sizeof(result), event->program_result);
248                                 cpos = result;
249                                 while (--i) {
250                                         while (cpos[0] != '\0' && !isspace(cpos[0]))
251                                                 cpos++;
252                                         while (isspace(cpos[0]))
253                                                 cpos++;
254                                         if (cpos[0] == '\0')
255                                                 break;
256                                 }
257                                 if (i > 0) {
258                                         log_error("requested part of result string not found");
259                                         break;
260                                 }
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, ' ');
265                                         if (cpos)
266                                                 cpos[0] = '\0';
267                                 }
268                                 l = strpcpy(&s, l, tmp);
269                         } else {
270                                 l = strpcpy(&s, l, event->program_result);
271                         }
272                         break;
273                 }
274                 case SUBST_ATTR: {
275                         const char *value = NULL;
276                         char vbuf[UTIL_NAME_SIZE];
277                         size_t len;
278                         int count;
279
280                         if (attr == NULL) {
281                                 log_error("missing file parameter for attr");
282                                 break;
283                         }
284
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)
287                                 value = vbuf;
288
289                         /* try to read the attribute the device */
290                         if (value == NULL)
291                                 value = udev_device_get_sysattr_value(event->dev, attr);
292
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);
296
297                         if (value == NULL)
298                                 break;
299
300                         /* strip trailing whitespace, and replace unwanted characters */
301                         if (value != vbuf)
302                                 strscpy(vbuf, sizeof(vbuf), value);
303                         len = strlen(vbuf);
304                         while (len > 0 && isspace(vbuf[--len]))
305                                 vbuf[len] = '\0';
306                         count = util_replace_chars(vbuf, UDEV_ALLOWED_CHARS_INPUT);
307                         if (count > 0)
308                                 log_debug("%i character(s) replaced" , count);
309                         l = strpcpy(&s, l, vbuf);
310                         break;
311                 }
312                 case SUBST_PARENT: {
313                         struct udev_device *dev_parent;
314                         const char *devnode;
315
316                         dev_parent = udev_device_get_parent(event->dev);
317                         if (dev_parent == NULL)
318                                 break;
319                         devnode = udev_device_get_devnode(dev_parent);
320                         if (devnode != NULL)
321                                 l = strpcpy(&s, l, devnode + strlen("/dev/"));
322                         break;
323                 }
324                 case SUBST_DEVNODE:
325                         if (udev_device_get_devnode(dev) != NULL)
326                                 l = strpcpy(&s, l, udev_device_get_devnode(dev));
327                         break;
328                 case SUBST_NAME:
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/"));
333                         else
334                                 l = strpcpy(&s, l, udev_device_get_sysname(dev));
335                         break;
336                 case SUBST_LINKS: {
337                         struct udev_list_entry *list_entry;
338
339                         list_entry = udev_device_get_devlinks_list_entry(dev);
340                         if (list_entry == NULL)
341                                 break;
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);
345                         break;
346                 }
347                 case SUBST_ROOT:
348                         l = strpcpy(&s, l, "/dev");
349                         break;
350                 case SUBST_SYS:
351                         l = strpcpy(&s, l, "/sys");
352                         break;
353                 case SUBST_ENV:
354                         if (attr == NULL) {
355                                 break;
356                         } else {
357                                 const char *value;
358
359                                 value = udev_device_get_property_value(event->dev, attr);
360                                 if (value == NULL)
361                                         break;
362                                 l = strpcpy(&s, l, value);
363                                 break;
364                         }
365                 default:
366                         log_error("unknown substitution type=%i", type);
367                         break;
368                 }
369         }
370
371 out:
372         s[0] = '\0';
373         return l;
374 }
375
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) {
379         int err;
380         int fd;
381
382         /* discard child output or connect to pipe */
383         fd = open("/dev/null", O_RDWR);
384         if (fd >= 0) {
385                 dup2(fd, STDIN_FILENO);
386                 if (fd_stdout < 0)
387                         dup2(fd, STDOUT_FILENO);
388                 if (fd_stderr < 0)
389                         dup2(fd, STDERR_FILENO);
390                 close(fd);
391         } else {
392                 log_error("open /dev/null failed: %m");
393         }
394
395         /* connect pipes to std{out,err} */
396         if (fd_stdout >= 0) {
397                 dup2(fd_stdout, STDOUT_FILENO);
398                         close(fd_stdout);
399         }
400         if (fd_stderr >= 0) {
401                 dup2(fd_stderr, STDERR_FILENO);
402                 close(fd_stderr);
403         }
404
405         /* terminate child in case parent goes away */
406         prctl(PR_SET_PDEATHSIG, SIGTERM);
407
408         /* restore original udev sigmask before exec */
409         if (sigmask)
410                 sigprocmask(SIG_SETMASK, sigmask, NULL);
411
412         execve(argv[0], argv, envp);
413
414         /* exec failed */
415         err = -errno;
416         log_error("failed to execute '%s' '%s': %m", argv[0], cmd);
417         return err;
418 }
419
420 static void spawn_read(struct udev_event *event,
421                        usec_t timeout_usec,
422                        const char *cmd,
423                        int fd_stdout, int fd_stderr,
424                        char *result, size_t ressize) {
425         size_t respos = 0;
426         int fd_ep = -1;
427         struct epoll_event ep_outpipe, ep_errpipe;
428
429         /* read from child if requested */
430         if (fd_stdout < 0 && fd_stderr < 0)
431                 return;
432
433         fd_ep = epoll_create1(EPOLL_CLOEXEC);
434         if (fd_ep < 0) {
435                 log_error("error creating epoll fd: %m");
436                 goto out;
437         }
438
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");
445                         goto out;
446                 }
447         }
448
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");
455                         goto out;
456                 }
457         }
458
459         /* read child output */
460         while (fd_stdout >= 0 || fd_stderr >= 0) {
461                 int timeout;
462                 int fdcount;
463                 struct epoll_event ev[4];
464                 int i;
465
466                 if (timeout_usec > 0) {
467                         usec_t age_usec;
468
469                         age_usec = now(CLOCK_MONOTONIC) - event->birth_usec;
470                         if (age_usec >= timeout_usec) {
471                                 log_error("timeout '%s'", cmd);
472                                 goto out;
473                         }
474                         timeout = ((timeout_usec - age_usec) / USEC_PER_MSEC) + MSEC_PER_SEC;
475                 } else {
476                         timeout = -1;
477                 }
478
479                 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
480                 if (fdcount < 0) {
481                         if (errno == EINTR)
482                                 continue;
483                         log_error("failed to poll: %m");
484                         goto out;
485                 }
486                 if (fdcount == 0) {
487                         log_error("timeout '%s'", cmd);
488                         goto out;
489                 }
490
491                 for (i = 0; i < fdcount; i++) {
492                         int *fd = (int *)ev[i].data.ptr;
493
494                         if (ev[i].events & EPOLLIN) {
495                                 ssize_t count;
496                                 char buf[4096];
497
498                                 count = read(*fd, buf, sizeof(buf)-1);
499                                 if (count <= 0)
500                                         continue;
501                                 buf[count] = '\0';
502
503                                 /* store stdout result */
504                                 if (result != NULL && *fd == fd_stdout) {
505                                         if (respos + count < ressize) {
506                                                 memcpy(&result[respos], buf, count);
507                                                 respos += count;
508                                         } else {
509                                                 log_error("'%s' ressize %zd too short", cmd, ressize);
510                                         }
511                                 }
512
513                                 /* log debug output only if we watch stderr */
514                                 if (fd_stderr >= 0) {
515                                         char *pos;
516                                         char *line;
517
518                                         pos = buf;
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);
522                                         }
523                                 }
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");
527                                         goto out;
528                                 }
529                                 *fd = -1;
530                         }
531                 }
532         }
533
534         /* return the child's stdout string */
535         if (result != NULL)
536                 result[respos] = '\0';
537 out:
538         if (fd_ep >= 0)
539                 close(fd_ep);
540 }
541
542 static int spawn_wait(struct udev_event *event,
543                       usec_t timeout_usec,
544                       usec_t timeout_warn_usec,
545                       const char *cmd, pid_t pid) {
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 timeout_warn = 0;
555                 int fdcount;
556
557                 if (timeout_usec > 0) {
558                         usec_t age_usec;
559
560                         age_usec = now(CLOCK_MONOTONIC) - event->birth_usec;
561                         if (age_usec >= timeout_usec)
562                                 timeout = 1000;
563                         else {
564                                 if (timeout_warn_usec > 0)
565                                         timeout_warn = ((timeout_warn_usec - age_usec) / USEC_PER_MSEC) + MSEC_PER_SEC;
566
567                                 timeout = ((timeout_usec - timeout_warn_usec - age_usec) / USEC_PER_MSEC) + MSEC_PER_SEC;
568                         }
569                 } else {
570                         timeout = -1;
571                 }
572
573                 fdcount = poll(pfd, 1, timeout_warn);
574                 if (fdcount < 0) {
575                         if (errno == EINTR)
576                                 continue;
577                         err = -errno;
578                         log_error("failed to poll: %m");
579                         goto out;
580                 }
581                 if (fdcount == 0) {
582                         log_warning("slow: '%s' [%u]", cmd, pid);
583
584                         fdcount = poll(pfd, 1, timeout);
585                         if (fdcount < 0) {
586                                 if (errno == EINTR)
587                                         continue;
588                                 err = -errno;
589                                 log_error("failed to poll: %m");
590                                 goto out;
591                         }
592                         if (fdcount == 0) {
593                                 log_error("timeout: killing '%s' [%u]", cmd, pid);
594                                 kill(pid, SIGKILL);
595                         }
596                 }
597
598                 if (pfd[0].revents & POLLIN) {
599                         struct signalfd_siginfo fdsi;
600                         int status;
601                         ssize_t size;
602
603                         size = read(event->fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
604                         if (size != sizeof(struct signalfd_siginfo))
605                                 continue;
606
607                         switch (fdsi.ssi_signo) {
608                         case SIGTERM:
609                                 event->sigterm = true;
610                                 break;
611                         case SIGCHLD:
612                                 if (waitpid(pid, &status, WNOHANG) < 0)
613                                         break;
614                                 if (WIFEXITED(status)) {
615                                         log_debug("'%s' [%u] exit with return code %i", cmd, pid, WEXITSTATUS(status));
616                                         if (WEXITSTATUS(status) != 0)
617                                                 err = -1;
618                                 } else if (WIFSIGNALED(status)) {
619                                         log_error("'%s' [%u] terminated by signal %i (%s)", cmd, pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
620                                         err = -1;
621                                 } else if (WIFSTOPPED(status)) {
622                                         log_error("'%s' [%u] stopped", cmd, pid);
623                                         err = -1;
624                                 } else if (WIFCONTINUED(status)) {
625                                         log_error("'%s' [%u] continued", cmd, pid);
626                                         err = -1;
627                                 } else {
628                                         log_error("'%s' [%u] exit with status 0x%04x", cmd, pid, status);
629                                         err = -1;
630                                 }
631                                 pid = 0;
632                                 break;
633                         }
634                 }
635         }
636 out:
637         return err;
638 }
639
640 int udev_build_argv(struct udev *udev, char *cmd, int *argc, char *argv[]) {
641         int i = 0;
642         char *pos;
643
644         if (strchr(cmd, ' ') == NULL) {
645                 argv[i++] = cmd;
646                 goto out;
647         }
648
649         pos = cmd;
650         while (pos != NULL && pos[0] != '\0') {
651                 if (pos[0] == '\'') {
652                         /* do not separate quotes */
653                         pos++;
654                         argv[i] = strsep(&pos, "\'");
655                         if (pos != NULL)
656                                 while (pos[0] == ' ')
657                                         pos++;
658                 } else {
659                         argv[i] = strsep(&pos, " ");
660                         if (pos != NULL)
661                                 while (pos[0] == ' ')
662                                         pos++;
663                 }
664                 i++;
665         }
666 out:
667         argv[i] = NULL;
668         if (argc)
669                 *argc = i;
670         return 0;
671 }
672
673 int udev_event_spawn(struct udev_event *event,
674                      usec_t timeout_usec,
675                      usec_t timeout_warn_usec,
676                      const char *cmd, char **envp, const sigset_t *sigmask,
677                      char *result, size_t ressize) {
678         struct udev *udev = event->udev;
679         int outpipe[2] = {-1, -1};
680         int errpipe[2] = {-1, -1};
681         pid_t pid;
682         char arg[UTIL_PATH_SIZE];
683         char *argv[128];
684         char program[UTIL_PATH_SIZE];
685         int err = 0;
686
687         strscpy(arg, sizeof(arg), cmd);
688         udev_build_argv(event->udev, arg, NULL, argv);
689
690         /* pipes from child to parent */
691         if (result != NULL || udev_get_log_priority(udev) >= LOG_INFO) {
692                 if (pipe2(outpipe, O_NONBLOCK) != 0) {
693                         err = -errno;
694                         log_error("pipe failed: %m");
695                         goto out;
696                 }
697         }
698         if (udev_get_log_priority(udev) >= LOG_INFO) {
699                 if (pipe2(errpipe, O_NONBLOCK) != 0) {
700                         err = -errno;
701                         log_error("pipe failed: %m");
702                         goto out;
703                 }
704         }
705
706         /* allow programs in /usr/lib/udev/ to be called without the path */
707         if (argv[0][0] != '/') {
708                 strscpyl(program, sizeof(program), UDEVLIBEXECDIR "/", argv[0], NULL);
709                 argv[0] = program;
710         }
711
712         pid = fork();
713         switch(pid) {
714         case 0:
715                 /* child closes parent's ends of pipes */
716                 if (outpipe[READ_END] >= 0) {
717                         close(outpipe[READ_END]);
718                         outpipe[READ_END] = -1;
719                 }
720                 if (errpipe[READ_END] >= 0) {
721                         close(errpipe[READ_END]);
722                         errpipe[READ_END] = -1;
723                 }
724
725                 log_debug("starting '%s'", cmd);
726
727                 spawn_exec(event, cmd, argv, envp, sigmask,
728                            outpipe[WRITE_END], errpipe[WRITE_END]);
729
730                 _exit(2 );
731         case -1:
732                 log_error("fork of '%s' failed: %m", cmd);
733                 err = -1;
734                 goto out;
735         default:
736                 /* parent closed child's ends of pipes */
737                 if (outpipe[WRITE_END] >= 0) {
738                         close(outpipe[WRITE_END]);
739                         outpipe[WRITE_END] = -1;
740                 }
741                 if (errpipe[WRITE_END] >= 0) {
742                         close(errpipe[WRITE_END]);
743                         errpipe[WRITE_END] = -1;
744                 }
745
746                 spawn_read(event,
747                            timeout_usec,
748                            cmd,
749                            outpipe[READ_END], errpipe[READ_END],
750                            result, ressize);
751
752                 err = spawn_wait(event, timeout_usec, timeout_warn_usec, cmd, pid);
753         }
754
755 out:
756         if (outpipe[READ_END] >= 0)
757                 close(outpipe[READ_END]);
758         if (outpipe[WRITE_END] >= 0)
759                 close(outpipe[WRITE_END]);
760         if (errpipe[READ_END] >= 0)
761                 close(errpipe[READ_END]);
762         if (errpipe[WRITE_END] >= 0)
763                 close(errpipe[WRITE_END]);
764         return err;
765 }
766
767 static int rename_netif(struct udev_event *event) {
768         struct udev_device *dev = event->dev;
769         char name[IFNAMSIZ];
770         const char *oldname;
771         int r;
772
773         oldname = udev_device_get_sysname(dev);
774
775         strscpy(name, IFNAMSIZ, event->name);
776
777         r = rtnl_set_link_name(&event->rtnl, udev_device_get_ifindex(dev), name);
778         if (r < 0) {
779                 log_error("error changing net interface name '%s' to '%s': %s",
780                           oldname, name, strerror(-r));
781                 return r;
782         }
783
784         log_debug("renamed network interface '%s' to '%s'\n", oldname, name);
785
786         return 0;
787 }
788
789 void udev_event_execute_rules(struct udev_event *event,
790                               usec_t timeout_usec,
791                               usec_t timeout_warn_usec,
792                               struct udev_rules *rules, const sigset_t *sigmask) {
793         struct udev_device *dev = event->dev;
794
795         if (udev_device_get_subsystem(dev) == NULL)
796                 return;
797
798         if (streq(udev_device_get_action(dev), "remove")) {
799                 udev_device_read_db(dev, NULL);
800                 udev_device_delete_db(dev);
801                 udev_device_tag_index(dev, NULL, false);
802
803                 if (major(udev_device_get_devnum(dev)) != 0)
804                         udev_watch_end(event->udev, dev);
805
806                 udev_rules_apply_to_event(rules, event, timeout_usec, timeout_warn_usec, sigmask);
807
808                 if (major(udev_device_get_devnum(dev)) != 0)
809                         udev_node_remove(dev);
810         } else {
811                 event->dev_db = udev_device_new(event->udev);
812                 if (event->dev_db != NULL) {
813                         udev_device_set_syspath(event->dev_db, udev_device_get_syspath(dev));
814                         udev_device_set_subsystem(event->dev_db, udev_device_get_subsystem(dev));
815                         udev_device_read_db(event->dev_db, NULL);
816                         udev_device_set_info_loaded(event->dev_db);
817
818                         /* disable watch during event processing */
819                         if (major(udev_device_get_devnum(dev)) != 0)
820                                 udev_watch_end(event->udev, event->dev_db);
821                 }
822
823                 if (major(udev_device_get_devnum(dev)) == 0 &&
824                     streq(udev_device_get_action(dev), "move")) {
825                         struct udev_list_entry *entry;
826
827                         for ((entry = udev_device_get_properties_list_entry(event->dev_db)); entry; entry = udev_list_entry_get_next(entry)) {
828                                 const char *key, *value;
829                                 struct udev_list_entry *property;
830
831                                 key = udev_list_entry_get_name(entry);
832                                 value = udev_list_entry_get_value(entry);
833
834                                 property = udev_device_add_property(event->dev, key, value);
835                                 udev_list_entry_set_num(property, true);
836                         }
837                 }
838
839                 udev_rules_apply_to_event(rules, event, timeout_usec, timeout_warn_usec, sigmask);
840
841                 /* rename a new network interface, if needed */
842                 if (udev_device_get_ifindex(dev) > 0 && streq(udev_device_get_action(dev), "add") &&
843                     event->name != NULL && !streq(event->name, udev_device_get_sysname(dev))) {
844                         char syspath[UTIL_PATH_SIZE];
845                         char *pos;
846                         int r;
847
848                         r = rename_netif(event);
849                         if (r >= 0) {
850                                 /* remember old name */
851                                 udev_device_add_property(dev, "INTERFACE_OLD", udev_device_get_sysname(dev));
852
853                                 /* now change the devpath, because the kernel device name has changed */
854                                 strscpy(syspath, sizeof(syspath), udev_device_get_syspath(dev));
855                                 pos = strrchr(syspath, '/');
856                                 if (pos != NULL) {
857                                         pos++;
858                                         strscpy(pos, sizeof(syspath) - (pos - syspath), event->name);
859                                         udev_device_set_syspath(event->dev, syspath);
860                                         udev_device_add_property(dev, "INTERFACE", udev_device_get_sysname(dev));
861                                         log_debug("changed devpath to '%s'", udev_device_get_devpath(dev));
862                                 }
863                         }
864                 }
865
866                 if (major(udev_device_get_devnum(dev)) > 0) {
867                         bool apply;
868
869                         /* remove/update possible left-over symlinks from old database entry */
870                         if (event->dev_db != NULL)
871                                 udev_node_update_old_links(dev, event->dev_db);
872
873                         if (!event->owner_set)
874                                 event->uid = udev_device_get_devnode_uid(dev);
875
876                         if (!event->group_set)
877                                 event->gid = udev_device_get_devnode_gid(dev);
878
879                         if (!event->mode_set) {
880                                 if (udev_device_get_devnode_mode(dev) > 0) {
881                                         /* kernel supplied value */
882                                         event->mode = udev_device_get_devnode_mode(dev);
883                                 } else if (event->gid > 0) {
884                                         /* default 0660 if a group is assigned */
885                                         event->mode = 0660;
886                                 } else {
887                                         /* default 0600 */
888                                         event->mode = 0600;
889                                 }
890                         }
891
892                         apply = streq(udev_device_get_action(dev), "add") || event->owner_set || event->group_set || event->mode_set;
893                         udev_node_add(dev, apply, event->mode, event->uid, event->gid, &event->seclabel_list);
894                 }
895
896                 /* preserve old, or get new initialization timestamp */
897                 if (event->dev_db != NULL && udev_device_get_usec_initialized(event->dev_db) > 0)
898                         udev_device_set_usec_initialized(event->dev, udev_device_get_usec_initialized(event->dev_db));
899                 else if (udev_device_get_usec_initialized(event->dev) == 0)
900                         udev_device_set_usec_initialized(event->dev, now(CLOCK_MONOTONIC));
901
902                 /* (re)write database file */
903                 udev_device_update_db(dev);
904                 udev_device_tag_index(dev, event->dev_db, true);
905                 udev_device_set_is_initialized(dev);
906
907                 udev_device_unref(event->dev_db);
908                 event->dev_db = NULL;
909         }
910 }
911
912 void udev_event_execute_run(struct udev_event *event, usec_t timeout_usec, usec_t timeout_warn_usec, const sigset_t *sigmask) {
913         struct udev_list_entry *list_entry;
914
915         udev_list_entry_foreach(list_entry, udev_list_get_entry(&event->run_list)) {
916                 const char *cmd = udev_list_entry_get_name(list_entry);
917                 enum udev_builtin_cmd builtin_cmd = udev_list_entry_get_num(list_entry);
918
919                 if (builtin_cmd < UDEV_BUILTIN_MAX) {
920                         char command[UTIL_PATH_SIZE];
921
922                         udev_event_apply_format(event, cmd, command, sizeof(command));
923                         udev_builtin_run(event->dev, builtin_cmd, command, false);
924                 } else {
925                         char program[UTIL_PATH_SIZE];
926                         char **envp;
927
928                         if (event->exec_delay > 0) {
929                                 log_debug("delay execution of '%s'", program);
930                                 sleep(event->exec_delay);
931                         }
932
933                         udev_event_apply_format(event, cmd, program, sizeof(program));
934                         envp = udev_device_get_properties_envp(event->dev);
935                         udev_event_spawn(event, timeout_usec, timeout_warn_usec, program, envp, sigmask, NULL, 0);
936                 }
937         }
938 }