chiark / gitweb /
Use strlen even for constant strings
[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 {
39         struct udev *udev = udev_device_get_udev(dev);
40         struct udev_event *event;
41
42         event = new0(struct udev_event, 1);
43         if (event == NULL)
44                 return NULL;
45         event->dev = dev;
46         event->udev = udev;
47         udev_list_init(udev, &event->run_list, false);
48         udev_list_init(udev, &event->seclabel_list, false);
49         event->fd_signal = -1;
50         event->birth_usec = now(CLOCK_MONOTONIC);
51         event->timeout_usec = 30 * 1000 * 1000;
52         return event;
53 }
54
55 void udev_event_unref(struct udev_event *event)
56 {
57         if (event == NULL)
58                 return;
59         udev_list_cleanup(&event->run_list);
60         udev_list_cleanup(&event->seclabel_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'", 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 = strpcpy(&s, l, udev_device_get_devpath(dev));
195                         break;
196                 case SUBST_KERNEL:
197                         l = 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 = strpcpy(&s, l, udev_device_get_sysnum(dev));
203                         break;
204                 case SUBST_ID:
205                         if (event->dev_parent == NULL)
206                                 break;
207                         l = 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 = 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 = 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 = 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                                 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                                         if (cpos[0] == '\0')
258                                                 break;
259                                 }
260                                 if (i > 0) {
261                                         log_error("requested part of result string not found");
262                                         break;
263                                 }
264                                 strscpy(tmp, sizeof(tmp), cpos);
265                                 /* %{2+}c copies the whole string from the second part on */
266                                 if (rest[0] != '+') {
267                                         cpos = strchr(tmp, ' ');
268                                         if (cpos)
269                                                 cpos[0] = '\0';
270                                 }
271                                 l = strpcpy(&s, l, tmp);
272                         } else {
273                                 l = strpcpy(&s, l, event->program_result);
274                         }
275                         break;
276                 }
277                 case SUBST_ATTR: {
278                         const char *value = NULL;
279                         char vbuf[UTIL_NAME_SIZE];
280                         size_t len;
281                         int count;
282
283                         if (attr == NULL) {
284                                 log_error("missing file parameter for attr");
285                                 break;
286                         }
287
288                         /* try to read the value specified by "[dmi/id]product_name" */
289                         if (util_resolve_subsys_kernel(event->udev, attr, vbuf, sizeof(vbuf), 1) == 0)
290                                 value = vbuf;
291
292                         /* try to read the attribute the device */
293                         if (value == NULL)
294                                 value = udev_device_get_sysattr_value(event->dev, attr);
295
296                         /* try to read the attribute of the parent device, other matches have selected */
297                         if (value == NULL && event->dev_parent != NULL && event->dev_parent != event->dev)
298                                 value = udev_device_get_sysattr_value(event->dev_parent, attr);
299
300                         if (value == NULL)
301                                 break;
302
303                         /* strip trailing whitespace, and replace unwanted characters */
304                         if (value != vbuf)
305                                 strscpy(vbuf, sizeof(vbuf), value);
306                         len = strlen(vbuf);
307                         while (len > 0 && isspace(vbuf[--len]))
308                                 vbuf[len] = '\0';
309                         count = util_replace_chars(vbuf, UDEV_ALLOWED_CHARS_INPUT);
310                         if (count > 0)
311                                 log_debug("%i character(s) replaced" , count);
312                         l = strpcpy(&s, l, vbuf);
313                         break;
314                 }
315                 case SUBST_PARENT: {
316                         struct udev_device *dev_parent;
317                         const char *devnode;
318
319                         dev_parent = udev_device_get_parent(event->dev);
320                         if (dev_parent == NULL)
321                                 break;
322                         devnode = udev_device_get_devnode(dev_parent);
323                         if (devnode != NULL)
324                                 l = strpcpy(&s, l, devnode + strlen("/dev/"));
325                         break;
326                 }
327                 case SUBST_DEVNODE:
328                         if (udev_device_get_devnode(dev) != NULL)
329                                 l = strpcpy(&s, l, udev_device_get_devnode(dev));
330                         break;
331                 case SUBST_NAME:
332                         if (event->name != NULL)
333                                 l = strpcpy(&s, l, event->name);
334                         else if (udev_device_get_devnode(dev) != NULL)
335                                 l = strpcpy(&s, l, udev_device_get_devnode(dev) + strlen("/dev/"));
336                         else
337                                 l = strpcpy(&s, l, udev_device_get_sysname(dev));
338                         break;
339                 case SUBST_LINKS: {
340                         struct udev_list_entry *list_entry;
341
342                         list_entry = udev_device_get_devlinks_list_entry(dev);
343                         if (list_entry == NULL)
344                                 break;
345                         l = strpcpy(&s, l, udev_list_entry_get_name(list_entry) + strlen("/dev/"));
346                         udev_list_entry_foreach(list_entry, udev_list_entry_get_next(list_entry))
347                                 l = strpcpyl(&s, l, " ", udev_list_entry_get_name(list_entry) + strlen("/dev/"), NULL);
348                         break;
349                 }
350                 case SUBST_ROOT:
351                         l = strpcpy(&s, l, "/dev");
352                         break;
353                 case SUBST_SYS:
354                         l = strpcpy(&s, l, "/sys");
355                         break;
356                 case SUBST_ENV:
357                         if (attr == NULL) {
358                                 break;
359                         } else {
360                                 const char *value;
361
362                                 value = udev_device_get_property_value(event->dev, attr);
363                                 if (value == NULL)
364                                         break;
365                                 l = strpcpy(&s, l, value);
366                                 break;
367                         }
368                 default:
369                         log_error("unknown substitution type=%i", type);
370                         break;
371                 }
372         }
373
374 out:
375         s[0] = '\0';
376         return l;
377 }
378
379 static int spawn_exec(struct udev_event *event,
380                       const char *cmd, char *const argv[], char **envp, const sigset_t *sigmask,
381                       int fd_stdout, int fd_stderr)
382 {
383         int err;
384         int fd;
385
386         /* discard child output or connect to pipe */
387         fd = open("/dev/null", O_RDWR);
388         if (fd >= 0) {
389                 dup2(fd, STDIN_FILENO);
390                 if (fd_stdout < 0)
391                         dup2(fd, STDOUT_FILENO);
392                 if (fd_stderr < 0)
393                         dup2(fd, STDERR_FILENO);
394                 close(fd);
395         } else {
396                 log_error("open /dev/null failed: %m");
397         }
398
399         /* connect pipes to std{out,err} */
400         if (fd_stdout >= 0) {
401                 dup2(fd_stdout, STDOUT_FILENO);
402                         close(fd_stdout);
403         }
404         if (fd_stderr >= 0) {
405                 dup2(fd_stderr, STDERR_FILENO);
406                 close(fd_stderr);
407         }
408
409         /* terminate child in case parent goes away */
410         prctl(PR_SET_PDEATHSIG, SIGTERM);
411
412         /* restore original udev sigmask before exec */
413         if (sigmask)
414                 sigprocmask(SIG_SETMASK, sigmask, NULL);
415
416         execve(argv[0], argv, envp);
417
418         /* exec failed */
419         err = -errno;
420         log_error("failed to execute '%s' '%s': %m", argv[0], cmd);
421         return err;
422 }
423
424 static void spawn_read(struct udev_event *event,
425                       const char *cmd,
426                       int fd_stdout, int fd_stderr,
427                       char *result, size_t ressize)
428 {
429         size_t respos = 0;
430         int fd_ep = -1;
431         struct epoll_event ep_outpipe, ep_errpipe;
432
433         /* read from child if requested */
434         if (fd_stdout < 0 && fd_stderr < 0)
435                 return;
436
437         fd_ep = epoll_create1(EPOLL_CLOEXEC);
438         if (fd_ep < 0) {
439                 log_error("error creating epoll fd: %m");
440                 goto out;
441         }
442
443         if (fd_stdout >= 0) {
444                 memzero(&ep_outpipe, sizeof(struct epoll_event));
445                 ep_outpipe.events = EPOLLIN;
446                 ep_outpipe.data.ptr = &fd_stdout;
447                 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_stdout, &ep_outpipe) < 0) {
448                         log_error("fail to add fd to epoll: %m");
449                         goto out;
450                 }
451         }
452
453         if (fd_stderr >= 0) {
454                 memzero(&ep_errpipe, sizeof(struct epoll_event));
455                 ep_errpipe.events = EPOLLIN;
456                 ep_errpipe.data.ptr = &fd_stderr;
457                 if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_stderr, &ep_errpipe) < 0) {
458                         log_error("fail to add fd to epoll: %m");
459                         goto out;
460                 }
461         }
462
463         /* read child output */
464         while (fd_stdout >= 0 || fd_stderr >= 0) {
465                 int timeout;
466                 int fdcount;
467                 struct epoll_event ev[4];
468                 int i;
469
470                 if (event->timeout_usec > 0) {
471                         usec_t age_usec;
472
473                         age_usec = now(CLOCK_MONOTONIC) - event->birth_usec;
474                         if (age_usec >= event->timeout_usec) {
475                                 log_error("timeout '%s'", cmd);
476                                 goto out;
477                         }
478                         timeout = ((event->timeout_usec - age_usec) / 1000) + 1000;
479                 } else {
480                         timeout = -1;
481                 }
482
483                 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
484                 if (fdcount < 0) {
485                         if (errno == EINTR)
486                                 continue;
487                         log_error("failed to poll: %m");
488                         goto out;
489                 }
490                 if (fdcount == 0) {
491                         log_error("timeout '%s'", cmd);
492                         goto out;
493                 }
494
495                 for (i = 0; i < fdcount; i++) {
496                         int *fd = (int *)ev[i].data.ptr;
497
498                         if (ev[i].events & EPOLLIN) {
499                                 ssize_t count;
500                                 char buf[4096];
501
502                                 count = read(*fd, buf, sizeof(buf)-1);
503                                 if (count <= 0)
504                                         continue;
505                                 buf[count] = '\0';
506
507                                 /* store stdout result */
508                                 if (result != NULL && *fd == fd_stdout) {
509                                         if (respos + count < ressize) {
510                                                 memcpy(&result[respos], buf, count);
511                                                 respos += count;
512                                         } else {
513                                                 log_error("'%s' ressize %zd too short", cmd, ressize);
514                                         }
515                                 }
516
517                                 /* log debug output only if we watch stderr */
518                                 if (fd_stderr >= 0) {
519                                         char *pos;
520                                         char *line;
521
522                                         pos = buf;
523                                         while ((line = strsep(&pos, "\n"))) {
524                                                 if (pos != NULL || line[0] != '\0')
525                                                         log_debug("'%s'(%s) '%s'", cmd, *fd == fd_stdout ? "out" : "err" , line);
526                                         }
527                                 }
528                         } else if (ev[i].events & EPOLLHUP) {
529                                 if (epoll_ctl(fd_ep, EPOLL_CTL_DEL, *fd, NULL) < 0) {
530                                         log_error("failed to remove fd from epoll: %m");
531                                         goto out;
532                                 }
533                                 *fd = -1;
534                         }
535                 }
536         }
537
538         /* return the child's stdout string */
539         if (result != NULL)
540                 result[respos] = '\0';
541 out:
542         if (fd_ep >= 0)
543                 close(fd_ep);
544 }
545
546 static int spawn_wait(struct udev_event *event, const char *cmd, pid_t pid)
547 {
548         struct pollfd pfd[1];
549         int err = 0;
550
551         pfd[0].events = POLLIN;
552         pfd[0].fd = event->fd_signal;
553
554         while (pid > 0) {
555                 int timeout;
556                 int fdcount;
557
558                 if (event->timeout_usec > 0) {
559                         usec_t age_usec;
560
561                         age_usec = now(CLOCK_MONOTONIC) - event->birth_usec;
562                         if (age_usec >= event->timeout_usec)
563                                 timeout = 1000;
564                         else
565                                 timeout = ((event->timeout_usec - age_usec) / 1000) + 1000;
566                 } else {
567                         timeout = -1;
568                 }
569
570                 fdcount = poll(pfd, 1, timeout);
571                 if (fdcount < 0) {
572                         if (errno == EINTR)
573                                 continue;
574                         err = -errno;
575                         log_error("failed to poll: %m");
576                         goto out;
577                 }
578                 if (fdcount == 0) {
579                         log_error("timeout: killing '%s' [%u]", cmd, pid);
580                         kill(pid, SIGKILL);
581                 }
582
583                 if (pfd[0].revents & POLLIN) {
584                         struct signalfd_siginfo fdsi;
585                         int status;
586                         ssize_t size;
587
588                         size = read(event->fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
589                         if (size != sizeof(struct signalfd_siginfo))
590                                 continue;
591
592                         switch (fdsi.ssi_signo) {
593                         case SIGTERM:
594                                 event->sigterm = true;
595                                 break;
596                         case SIGCHLD:
597                                 if (waitpid(pid, &status, WNOHANG) < 0)
598                                         break;
599                                 if (WIFEXITED(status)) {
600                                         log_debug("'%s' [%u] exit with return code %i", cmd, pid, WEXITSTATUS(status));
601                                         if (WEXITSTATUS(status) != 0)
602                                                 err = -1;
603                                 } else if (WIFSIGNALED(status)) {
604                                         log_error("'%s' [%u] terminated by signal %i (%s)", cmd, pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
605                                         err = -1;
606                                 } else if (WIFSTOPPED(status)) {
607                                         log_error("'%s' [%u] stopped", cmd, pid);
608                                         err = -1;
609                                 } else if (WIFCONTINUED(status)) {
610                                         log_error("'%s' [%u] continued", cmd, pid);
611                                         err = -1;
612                                 } else {
613                                         log_error("'%s' [%u] exit with status 0x%04x", cmd, pid, status);
614                                         err = -1;
615                                 }
616                                 pid = 0;
617                                 break;
618                         }
619                 }
620         }
621 out:
622         return err;
623 }
624
625 int udev_build_argv(struct udev *udev, char *cmd, int *argc, char *argv[])
626 {
627         int i = 0;
628         char *pos;
629
630         if (strchr(cmd, ' ') == NULL) {
631                 argv[i++] = cmd;
632                 goto out;
633         }
634
635         pos = cmd;
636         while (pos != NULL && pos[0] != '\0') {
637                 if (pos[0] == '\'') {
638                         /* do not separate quotes */
639                         pos++;
640                         argv[i] = strsep(&pos, "\'");
641                         if (pos != NULL)
642                                 while (pos[0] == ' ')
643                                         pos++;
644                 } else {
645                         argv[i] = strsep(&pos, " ");
646                         if (pos != NULL)
647                                 while (pos[0] == ' ')
648                                         pos++;
649                 }
650                 i++;
651         }
652 out:
653         argv[i] = NULL;
654         if (argc)
655                 *argc = i;
656         return 0;
657 }
658
659 int udev_event_spawn(struct udev_event *event,
660                      const char *cmd, char **envp, const sigset_t *sigmask,
661                      char *result, size_t ressize)
662 {
663         struct udev *udev = event->udev;
664         int outpipe[2] = {-1, -1};
665         int errpipe[2] = {-1, -1};
666         pid_t pid;
667         char arg[UTIL_PATH_SIZE];
668         char *argv[128];
669         char program[UTIL_PATH_SIZE];
670         int err = 0;
671
672         strscpy(arg, sizeof(arg), cmd);
673         udev_build_argv(event->udev, arg, NULL, argv);
674
675         /* pipes from child to parent */
676         if (result != NULL || udev_get_log_priority(udev) >= LOG_INFO) {
677                 if (pipe2(outpipe, O_NONBLOCK) != 0) {
678                         err = -errno;
679                         log_error("pipe failed: %m");
680                         goto out;
681                 }
682         }
683         if (udev_get_log_priority(udev) >= LOG_INFO) {
684                 if (pipe2(errpipe, O_NONBLOCK) != 0) {
685                         err = -errno;
686                         log_error("pipe failed: %m");
687                         goto out;
688                 }
689         }
690
691         /* allow programs in /usr/lib/udev/ to be called without the path */
692         if (argv[0][0] != '/') {
693                 strscpyl(program, sizeof(program), UDEVLIBEXECDIR "/", argv[0], NULL);
694                 argv[0] = program;
695         }
696
697         pid = fork();
698         switch(pid) {
699         case 0:
700                 /* child closes parent's ends of pipes */
701                 if (outpipe[READ_END] >= 0) {
702                         close(outpipe[READ_END]);
703                         outpipe[READ_END] = -1;
704                 }
705                 if (errpipe[READ_END] >= 0) {
706                         close(errpipe[READ_END]);
707                         errpipe[READ_END] = -1;
708                 }
709
710                 log_debug("starting '%s'", cmd);
711
712                 spawn_exec(event, cmd, argv, envp, sigmask,
713                            outpipe[WRITE_END], errpipe[WRITE_END]);
714
715                 _exit(2 );
716         case -1:
717                 log_error("fork of '%s' failed: %m", cmd);
718                 err = -1;
719                 goto out;
720         default:
721                 /* parent closed child's ends of pipes */
722                 if (outpipe[WRITE_END] >= 0) {
723                         close(outpipe[WRITE_END]);
724                         outpipe[WRITE_END] = -1;
725                 }
726                 if (errpipe[WRITE_END] >= 0) {
727                         close(errpipe[WRITE_END]);
728                         errpipe[WRITE_END] = -1;
729                 }
730
731                 spawn_read(event, cmd,
732                          outpipe[READ_END], errpipe[READ_END],
733                          result, ressize);
734
735                 err = spawn_wait(event, cmd, pid);
736         }
737
738 out:
739         if (outpipe[READ_END] >= 0)
740                 close(outpipe[READ_END]);
741         if (outpipe[WRITE_END] >= 0)
742                 close(outpipe[WRITE_END]);
743         if (errpipe[READ_END] >= 0)
744                 close(errpipe[READ_END]);
745         if (errpipe[WRITE_END] >= 0)
746                 close(errpipe[WRITE_END]);
747         return err;
748 }
749
750 static int rename_netif(struct udev_event *event)
751 {
752         struct udev_device *dev = event->dev;
753         _cleanup_rtnl_unref_ sd_rtnl *rtnl = NULL;
754         char name[IFNAMSIZ];
755         const char *oldname;
756         int r;
757
758         oldname = udev_device_get_sysname(dev);
759
760         log_debug("changing net interface name from '%s' to '%s'",
761                   oldname, event->name);
762
763         strscpy(name, IFNAMSIZ, event->name);
764
765         r = sd_rtnl_open(&rtnl, 0);
766         if (r < 0)
767                 return r;
768
769         r = rtnl_set_link_name(rtnl, udev_device_get_ifindex(dev), name);
770         if (r < 0)
771                 log_error("error changing net interface name %s to %s: %s",
772                           oldname, name, strerror(-r));
773         else
774                 print_kmsg("renamed network interface %s to %s", oldname, name);
775
776         return r;
777 }
778
779 int udev_event_execute_rules(struct udev_event *event, struct udev_rules *rules, const sigset_t *sigmask)
780 {
781         struct udev_device *dev = event->dev;
782         int err = 0;
783
784         if (udev_device_get_subsystem(dev) == NULL)
785                 return -1;
786
787         if (streq(udev_device_get_action(dev), "remove")) {
788                 udev_device_read_db(dev, NULL);
789                 udev_device_delete_db(dev);
790                 udev_device_tag_index(dev, NULL, false);
791
792                 if (major(udev_device_get_devnum(dev)) != 0)
793                         udev_watch_end(event->udev, dev);
794
795                 udev_rules_apply_to_event(rules, event, sigmask);
796
797                 if (major(udev_device_get_devnum(dev)) != 0)
798                         udev_node_remove(dev);
799         } else {
800                 event->dev_db = udev_device_new(event->udev);
801                 if (event->dev_db != NULL) {
802                         udev_device_set_syspath(event->dev_db, udev_device_get_syspath(dev));
803                         udev_device_set_subsystem(event->dev_db, udev_device_get_subsystem(dev));
804                         udev_device_read_db(event->dev_db, NULL);
805                         udev_device_set_info_loaded(event->dev_db);
806
807                         /* disable watch during event processing */
808                         if (major(udev_device_get_devnum(dev)) != 0)
809                                 udev_watch_end(event->udev, event->dev_db);
810                 }
811
812                 udev_rules_apply_to_event(rules, event, sigmask);
813
814                 /* rename a new network interface, if needed */
815                 if (udev_device_get_ifindex(dev) > 0 && streq(udev_device_get_action(dev), "add") &&
816                     event->name != NULL && !streq(event->name, udev_device_get_sysname(dev))) {
817                         char syspath[UTIL_PATH_SIZE];
818                         char *pos;
819
820                         err = rename_netif(event);
821                         if (err == 0) {
822                                 log_debug("renamed netif to '%s'", event->name);
823
824                                 /* remember old name */
825                                 udev_device_add_property(dev, "INTERFACE_OLD", udev_device_get_sysname(dev));
826
827                                 /* now change the devpath, because the kernel device name has changed */
828                                 strscpy(syspath, sizeof(syspath), udev_device_get_syspath(dev));
829                                 pos = strrchr(syspath, '/');
830                                 if (pos != NULL) {
831                                         pos++;
832                                         strscpy(pos, sizeof(syspath) - (pos - syspath), event->name);
833                                         udev_device_set_syspath(event->dev, syspath);
834                                         udev_device_add_property(dev, "INTERFACE", udev_device_get_sysname(dev));
835                                         log_debug("changed devpath to '%s'", udev_device_get_devpath(dev));
836                                 }
837                         }
838                 }
839
840                 if (major(udev_device_get_devnum(dev)) > 0) {
841                         bool apply;
842
843                         /* remove/update possible left-over symlinks from old database entry */
844                         if (event->dev_db != NULL)
845                                 udev_node_update_old_links(dev, event->dev_db);
846
847                         if (!event->owner_set)
848                                 event->uid = udev_device_get_devnode_uid(dev);
849
850                         if (!event->group_set)
851                                 event->gid = udev_device_get_devnode_gid(dev);
852
853                         if (!event->mode_set) {
854                                 if (udev_device_get_devnode_mode(dev) > 0) {
855                                         /* kernel supplied value */
856                                         event->mode = udev_device_get_devnode_mode(dev);
857                                 } else if (event->gid > 0) {
858                                         /* default 0660 if a group is assigned */
859                                         event->mode = 0660;
860                                 } else {
861                                         /* default 0600 */
862                                         event->mode = 0600;
863                                 }
864                         }
865
866                         apply = streq(udev_device_get_action(dev), "add") || event->owner_set || event->group_set || event->mode_set;
867                         udev_node_add(dev, apply, event->mode, event->uid, event->gid, &event->seclabel_list);
868                 }
869
870                 /* preserve old, or get new initialization timestamp */
871                 if (event->dev_db != NULL && udev_device_get_usec_initialized(event->dev_db) > 0)
872                         udev_device_set_usec_initialized(event->dev, udev_device_get_usec_initialized(event->dev_db));
873                 else if (udev_device_get_usec_initialized(event->dev) == 0)
874                         udev_device_set_usec_initialized(event->dev, now(CLOCK_MONOTONIC));
875
876                 /* (re)write database file */
877                 udev_device_update_db(dev);
878                 udev_device_tag_index(dev, event->dev_db, true);
879                 udev_device_set_is_initialized(dev);
880
881                 udev_device_unref(event->dev_db);
882                 event->dev_db = NULL;
883         }
884         return err;
885 }
886
887 void udev_event_execute_run(struct udev_event *event, const sigset_t *sigmask)
888 {
889         struct udev_list_entry *list_entry;
890
891         udev_list_entry_foreach(list_entry, udev_list_get_entry(&event->run_list)) {
892                 const char *cmd = udev_list_entry_get_name(list_entry);
893                 enum udev_builtin_cmd builtin_cmd = udev_list_entry_get_num(list_entry);
894
895                 if (builtin_cmd < UDEV_BUILTIN_MAX) {
896                         char command[UTIL_PATH_SIZE];
897
898                         udev_event_apply_format(event, cmd, command, sizeof(command));
899                         udev_builtin_run(event->dev, builtin_cmd, command, false);
900                 } else {
901                         char program[UTIL_PATH_SIZE];
902                         char **envp;
903
904                         if (event->exec_delay > 0) {
905                                 log_debug("delay execution of '%s'", program);
906                                 sleep(event->exec_delay);
907                         }
908
909                         udev_event_apply_format(event, cmd, program, sizeof(program));
910                         envp = udev_device_get_properties_envp(event->dev);
911                         udev_event_spawn(event, program, envp, sigmask, NULL, 0);
912                 }
913         }
914 }