• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/ioctl.h>
29 #include <sys/prctl.h>
30 #include <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 #include <sys/sysmacros.h>
37 
38 #include "udev.h"
39 
udev_event_new(struct udev_device * dev)40 struct udev_event *udev_event_new(struct udev_device *dev) {
41         struct udev *udev = udev_device_get_udev(dev);
42         struct udev_event *event;
43 
44         event = new0(struct udev_event, 1);
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         udev_list_init(udev, &event->seclabel_list, false);
51         event->fd_signal = -1;
52         event->birth_usec = now(CLOCK_MONOTONIC);
53         return event;
54 }
55 
udev_event_unref(struct udev_event * event)56 void udev_event_unref(struct udev_event *event) {
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 
udev_event_apply_format(struct udev_event * event,const char * src,char * dest,size_t size,bool replace_whitespace)66 size_t udev_event_apply_format(struct udev_event *event,
67                                const char *src, char *dest, size_t size,
68                                bool replace_whitespace) {
69         struct udev_device *dev = event->dev;
70         enum subst_type {
71                 SUBST_UNKNOWN,
72                 SUBST_DEVNODE,
73                 SUBST_ATTR,
74                 SUBST_ENV,
75                 SUBST_KERNEL,
76                 SUBST_KERNEL_NUMBER,
77                 SUBST_DRIVER,
78                 SUBST_DEVPATH,
79                 SUBST_ID,
80                 SUBST_MAJOR,
81                 SUBST_MINOR,
82                 SUBST_RESULT,
83                 SUBST_PARENT,
84                 SUBST_NAME,
85                 SUBST_LINKS,
86                 SUBST_ROOT,
87                 SUBST_SYS,
88         };
89         static const struct subst_map {
90                 const char *name;
91                 const char fmt;
92                 enum subst_type type;
93         } map[] = {
94                 { .name = "devnode",  .fmt = 'N', .type = SUBST_DEVNODE },
95                 { .name = "tempnode", .fmt = 'N', .type = SUBST_DEVNODE },
96                 { .name = "attr",     .fmt = 's', .type = SUBST_ATTR },
97                 { .name = "sysfs",    .fmt = 's', .type = SUBST_ATTR },
98                 { .name = "env",      .fmt = 'E', .type = SUBST_ENV },
99                 { .name = "kernel",   .fmt = 'k', .type = SUBST_KERNEL },
100                 { .name = "number",   .fmt = 'n', .type = SUBST_KERNEL_NUMBER },
101                 { .name = "driver",   .fmt = 'd', .type = SUBST_DRIVER },
102                 { .name = "devpath",  .fmt = 'p', .type = SUBST_DEVPATH },
103                 { .name = "id",       .fmt = 'b', .type = SUBST_ID },
104                 { .name = "major",    .fmt = 'M', .type = SUBST_MAJOR },
105                 { .name = "minor",    .fmt = 'm', .type = SUBST_MINOR },
106                 { .name = "result",   .fmt = 'c', .type = SUBST_RESULT },
107                 { .name = "parent",   .fmt = 'P', .type = SUBST_PARENT },
108                 { .name = "name",     .fmt = 'D', .type = SUBST_NAME },
109                 { .name = "links",    .fmt = 'L', .type = SUBST_LINKS },
110                 { .name = "root",     .fmt = 'r', .type = SUBST_ROOT },
111                 { .name = "sys",      .fmt = 'S', .type = SUBST_SYS },
112         };
113         const char *from;
114         char *s;
115         size_t l;
116 
117         from = src;
118         s = dest;
119         l = size;
120 
121         for (;;) {
122                 enum subst_type type = SUBST_UNKNOWN;
123                 char attrbuf[UTIL_PATH_SIZE], sbuf[UTIL_PATH_SIZE];
124                 char *attr = NULL, *_s;
125                 size_t _l;
126                 bool replws = replace_whitespace;
127 
128                 while (from[0] != '\0') {
129                         if (from[0] == '$') {
130                                 /* substitute named variable */
131                                 unsigned int i;
132 
133                                 if (from[1] == '$') {
134                                         from++;
135                                         goto copy;
136                                 }
137 
138                                 for (i = 0; i < ELEMENTSOF(map); i++) {
139                                         if (startswith(&from[1], map[i].name)) {
140                                                 type = map[i].type;
141                                                 from += strlen(map[i].name)+1;
142                                                 goto subst;
143                                         }
144                                 }
145                         } else if (from[0] == '%') {
146                                 /* substitute format char */
147                                 unsigned int i;
148 
149                                 if (from[1] == '%') {
150                                         from++;
151                                         goto copy;
152                                 }
153 
154                                 for (i = 0; i < ELEMENTSOF(map); i++) {
155                                         if (from[1] == map[i].fmt) {
156                                                 type = map[i].type;
157                                                 from += 2;
158                                                 goto subst;
159                                         }
160                                 }
161                         }
162 copy:
163                         /* copy char */
164                         if (l == 0)
165                                 goto out;
166                         s[0] = from[0];
167                         from++;
168                         s++;
169                         l--;
170                 }
171 
172                 goto out;
173 subst:
174                 /* extract possible $format{attr} */
175                 if (from[0] == '{') {
176                         unsigned int i;
177 
178                         from++;
179                         for (i = 0; from[i] != '}'; i++) {
180                                 if (from[i] == '\0') {
181                                         log_error("missing closing brace for format '%s'", src);
182                                         goto out;
183                                 }
184                         }
185                         if (i >= sizeof(attrbuf))
186                                 goto out;
187                         memcpy(attrbuf, from, i);
188                         attrbuf[i] = '\0';
189                         from += i+1;
190                         attr = attrbuf;
191                 } else {
192                         attr = NULL;
193                 }
194 
195                 /* result subst handles space as field separator */
196                 if (type == SUBST_RESULT)
197                         replws = false;
198 
199                 if (replws) {
200                         /* store dest string ptr and remaining len */
201                         _s = s;
202                         _l = l;
203                         /* temporarily use sbuf */
204                         s = sbuf;
205                         l = UTIL_PATH_SIZE;
206                 }
207 
208                 switch (type) {
209                 case SUBST_DEVPATH:
210                         l = strpcpy(&s, l, udev_device_get_devpath(dev));
211                         break;
212                 case SUBST_KERNEL:
213                         l = strpcpy(&s, l, udev_device_get_sysname(dev));
214                         break;
215                 case SUBST_KERNEL_NUMBER:
216                         if (udev_device_get_sysnum(dev) == NULL)
217                                 break;
218                         l = strpcpy(&s, l, udev_device_get_sysnum(dev));
219                         break;
220                 case SUBST_ID:
221                         if (event->dev_parent == NULL)
222                                 break;
223                         l = strpcpy(&s, l, udev_device_get_sysname(event->dev_parent));
224                         break;
225                 case SUBST_DRIVER: {
226                         const char *driver;
227 
228                         if (event->dev_parent == NULL)
229                                 break;
230 
231                         driver = udev_device_get_driver(event->dev_parent);
232                         if (driver == NULL)
233                                 break;
234                         l = strpcpy(&s, l, driver);
235                         break;
236                 }
237                 case SUBST_MAJOR: {
238                         char num[UTIL_PATH_SIZE];
239 
240                         sprintf(num, "%u", major(udev_device_get_devnum(dev)));
241                         l = strpcpy(&s, l, num);
242                         break;
243                 }
244                 case SUBST_MINOR: {
245                         char num[UTIL_PATH_SIZE];
246 
247                         sprintf(num, "%u", minor(udev_device_get_devnum(dev)));
248                         l = strpcpy(&s, l, num);
249                         break;
250                 }
251                 case SUBST_RESULT: {
252                         char *rest;
253                         int i;
254 
255                         if (event->program_result == NULL)
256                                 break;
257                         /* get part part of the result string */
258                         i = 0;
259                         if (attr != NULL)
260                                 i = strtoul(attr, &rest, 10);
261                         if (i > 0) {
262                                 char result[UTIL_PATH_SIZE];
263                                 char tmp[UTIL_PATH_SIZE];
264                                 char *cpos;
265 
266                                 strscpy(result, sizeof(result), event->program_result);
267                                 cpos = result;
268                                 while (--i) {
269                                         while (cpos[0] != '\0' && !isspace(cpos[0]))
270                                                 cpos++;
271                                         while (isspace(cpos[0]))
272                                                 cpos++;
273                                         if (cpos[0] == '\0')
274                                                 break;
275                                 }
276                                 if (i > 0) {
277                                         log_error("requested part of result string not found");
278                                         break;
279                                 }
280                                 strscpy(tmp, sizeof(tmp), cpos);
281                                 /* %{2+}c copies the whole string from the second part on */
282                                 if (rest[0] != '+') {
283                                         cpos = strchr(tmp, ' ');
284                                         if (cpos)
285                                                 cpos[0] = '\0';
286                                 }
287                                 l = strpcpy(&s, l, tmp);
288                         } else {
289                                 l = strpcpy(&s, l, event->program_result);
290                         }
291                         break;
292                 }
293                 case SUBST_ATTR: {
294                         const char *value = NULL;
295                         char vbuf[UTIL_NAME_SIZE];
296                         size_t len;
297                         int count;
298 
299                         if (attr == NULL) {
300                                 log_error("missing file parameter for attr");
301                                 break;
302                         }
303 
304                         /* try to read the value specified by "[dmi/id]product_name" */
305                         if (util_resolve_subsys_kernel(event->udev, attr, vbuf, sizeof(vbuf), 1) == 0)
306                                 value = vbuf;
307 
308                         /* try to read the attribute the device */
309                         if (value == NULL)
310                                 value = udev_device_get_sysattr_value(event->dev, attr);
311 
312                         /* try to read the attribute of the parent device, other matches have selected */
313                         if (value == NULL && event->dev_parent != NULL && event->dev_parent != event->dev)
314                                 value = udev_device_get_sysattr_value(event->dev_parent, attr);
315 
316                         if (value == NULL)
317                                 break;
318 
319                         /* strip trailing whitespace, and replace unwanted characters */
320                         if (value != vbuf)
321                                 strscpy(vbuf, sizeof(vbuf), value);
322                         len = strlen(vbuf);
323                         while (len > 0 && isspace(vbuf[--len]))
324                                 vbuf[len] = '\0';
325                         count = util_replace_chars(vbuf, UDEV_ALLOWED_CHARS_INPUT);
326                         if (count > 0)
327                                 log_debug("%i character(s) replaced" , count);
328                         l = strpcpy(&s, l, vbuf);
329                         break;
330                 }
331                 case SUBST_PARENT: {
332                         struct udev_device *dev_parent;
333                         const char *devnode;
334 
335                         dev_parent = udev_device_get_parent(event->dev);
336                         if (dev_parent == NULL)
337                                 break;
338                         devnode = udev_device_get_devnode(dev_parent);
339                         if (devnode != NULL)
340                                 l = strpcpy(&s, l, devnode + strlen("/dev/"));
341                         break;
342                 }
343                 case SUBST_DEVNODE:
344                         if (udev_device_get_devnode(dev) != NULL)
345                                 l = strpcpy(&s, l, udev_device_get_devnode(dev));
346                         break;
347                 case SUBST_NAME:
348                         if (event->name != NULL)
349                                 l = strpcpy(&s, l, event->name);
350                         else if (udev_device_get_devnode(dev) != NULL)
351                                 l = strpcpy(&s, l, udev_device_get_devnode(dev) + strlen("/dev/"));
352                         else
353                                 l = strpcpy(&s, l, udev_device_get_sysname(dev));
354                         break;
355                 case SUBST_LINKS: {
356                         struct udev_list_entry *list_entry;
357 
358                         list_entry = udev_device_get_devlinks_list_entry(dev);
359                         if (list_entry == NULL)
360                                 break;
361                         l = strpcpy(&s, l, udev_list_entry_get_name(list_entry) + strlen("/dev/"));
362                         udev_list_entry_foreach(list_entry, udev_list_entry_get_next(list_entry))
363                                 l = strpcpyl(&s, l, " ", udev_list_entry_get_name(list_entry) + strlen("/dev/"), NULL);
364                         break;
365                 }
366                 case SUBST_ROOT:
367                         l = strpcpy(&s, l, "/dev");
368                         break;
369                 case SUBST_SYS:
370                         l = strpcpy(&s, l, "/sys");
371                         break;
372                 case SUBST_ENV:
373                         if (attr == NULL) {
374                                 break;
375                         } else {
376                                 const char *value;
377 
378                                 value = udev_device_get_property_value(event->dev, attr);
379                                 if (value == NULL)
380                                         break;
381                                 l = strpcpy(&s, l, value);
382                                 break;
383                         }
384                 default:
385                         log_error("unknown substitution type=%i", type);
386                         break;
387                 }
388 
389                 /* replace whitespace in sbuf and copy to dest */
390                 if (replws) {
391                         size_t tmplen = UTIL_PATH_SIZE - l;
392 
393                         /* restore s and l to dest string values */
394                         s = _s;
395                         l = _l;
396 
397                         /* copy ws-replaced value to s */
398                         tmplen = util_replace_whitespace(sbuf, s, MIN(tmplen, l));
399                         l -= tmplen;
400                         s += tmplen;
401                 }
402         }
403 
404 out:
405         s[0] = '\0';
406         return l;
407 }
408 
spawn_exec(struct udev_event * event,const char * cmd,char * const argv[],char ** envp,const sigset_t * sigmask,int fd_stdout,int fd_stderr)409 static int spawn_exec(struct udev_event *event,
410                       const char *cmd, char *const argv[], char **envp, const sigset_t *sigmask,
411                       int fd_stdout, int fd_stderr) {
412         _cleanup_close_ int fd = -1;
413 
414         /* discard child output or connect to pipe */
415         fd = open("/dev/null", O_RDWR);
416         if (fd >= 0) {
417                 dup2(fd, STDIN_FILENO);
418                 if (fd_stdout < 0)
419                         dup2(fd, STDOUT_FILENO);
420                 if (fd_stderr < 0)
421                         dup2(fd, STDERR_FILENO);
422         } else
423                 log_error_errno(errno, "open /dev/null failed: %m");
424 
425         /* connect pipes to std{out,err} */
426         if (fd_stdout >= 0) {
427                 dup2(fd_stdout, STDOUT_FILENO);
428                 safe_close(fd_stdout);
429         }
430         if (fd_stderr >= 0) {
431                 dup2(fd_stderr, STDERR_FILENO);
432                 safe_close(fd_stderr);
433         }
434 
435         /* terminate child in case parent goes away */
436         prctl(PR_SET_PDEATHSIG, SIGTERM);
437 
438         /* restore original udev sigmask before exec */
439         if (sigmask)
440                 sigprocmask(SIG_SETMASK, sigmask, NULL);
441 
442         //execve(argv[0], argv, envp);
443 
444         /* exec failed */
445         log_error_errno(errno, "failed to execute '%s' '%s': %m", argv[0], cmd);
446 
447         return -errno;
448 }
449 
spawn_read(struct udev_event * event,usec_t timeout_usec,const char * cmd,int fd_stdout,int fd_stderr,char * result,size_t ressize)450 static void spawn_read(struct udev_event *event,
451                        usec_t timeout_usec,
452                        const char *cmd,
453                        int fd_stdout, int fd_stderr,
454                        char *result, size_t ressize) {
455         _cleanup_close_ int fd_ep = -1;
456         struct epoll_event ep_outpipe = {
457                 .events = EPOLLIN,
458                 .data.ptr = &fd_stdout,
459         };
460         struct epoll_event ep_errpipe = {
461                 .events = EPOLLIN,
462                 .data.ptr = &fd_stderr,
463         };
464         size_t respos = 0;
465         int r;
466 
467         /* read from child if requested */
468         if (fd_stdout < 0 && fd_stderr < 0)
469                 return;
470 
471         fd_ep = epoll_create1(EPOLL_CLOEXEC);
472         if (fd_ep < 0) {
473                 log_error_errno(errno, "error creating epoll fd: %m");
474                 return;
475         }
476 
477         if (fd_stdout >= 0) {
478                 r = epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_stdout, &ep_outpipe);
479                 if (r < 0) {
480                         log_error_errno(errno, "fail to add stdout fd to epoll: %m");
481                         return;
482                 }
483         }
484 
485         if (fd_stderr >= 0) {
486                 r = epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_stderr, &ep_errpipe);
487                 if (r < 0) {
488                         log_error_errno(errno, "fail to add stderr fd to epoll: %m");
489                         return;
490                 }
491         }
492 
493         /* read child output */
494         while (fd_stdout >= 0 || fd_stderr >= 0) {
495                 int timeout;
496                 int fdcount;
497                 struct epoll_event ev[4];
498                 int i;
499 
500                 if (timeout_usec > 0) {
501                         usec_t age_usec;
502 
503                         age_usec = now(CLOCK_MONOTONIC) - event->birth_usec;
504                         if (age_usec >= timeout_usec) {
505                                 log_error("timeout '%s'", cmd);
506                                 return;
507                         }
508                         timeout = ((timeout_usec - age_usec) / USEC_PER_MSEC) + MSEC_PER_SEC;
509                 } else {
510                         timeout = -1;
511                 }
512 
513                 fdcount = epoll_wait(fd_ep, ev, ELEMENTSOF(ev), timeout);
514                 if (fdcount < 0) {
515                         if (errno == EINTR)
516                                 continue;
517                         log_error_errno(errno, "failed to poll: %m");
518                         return;
519                 } else if (fdcount == 0) {
520                         log_error("timeout '%s'", cmd);
521                         return;
522                 }
523 
524                 for (i = 0; i < fdcount; i++) {
525                         int *fd = (int *)ev[i].data.ptr;
526 
527                         if (*fd < 0)
528                                 continue;
529 
530                         if (ev[i].events & EPOLLIN) {
531                                 ssize_t count;
532                                 char buf[4096];
533 
534                                 count = read(*fd, buf, sizeof(buf)-1);
535                                 if (count <= 0)
536                                         continue;
537                                 buf[count] = '\0';
538 
539                                 /* store stdout result */
540                                 if (result != NULL && *fd == fd_stdout) {
541                                         if (respos + count < ressize) {
542                                                 memcpy(&result[respos], buf, count);
543                                                 respos += count;
544                                         } else {
545                                                 log_error("'%s' ressize %zu too short", cmd, ressize);
546                                         }
547                                 }
548 
549                                 /* log debug output only if we watch stderr */
550                                 if (fd_stderr >= 0) {
551                                         char *pos;
552                                         char *line;
553 
554                                         pos = buf;
555                                         while ((line = strsep(&pos, "\n"))) {
556                                                 if (pos != NULL || line[0] != '\0')
557                                                         log_debug("'%s'(%s) '%s'", cmd, *fd == fd_stdout ? "out" : "err" , line);
558                                         }
559                                 }
560                         } else if (ev[i].events & EPOLLHUP) {
561                                 r = epoll_ctl(fd_ep, EPOLL_CTL_DEL, *fd, NULL);
562                                 if (r < 0) {
563                                         log_error_errno(errno, "failed to remove fd from epoll: %m");
564                                         return;
565                                 }
566                                 *fd = -1;
567                         }
568                 }
569         }
570 
571         /* return the child's stdout string */
572         if (result != NULL)
573                 result[respos] = '\0';
574 }
575 
spawn_wait(struct udev_event * event,usec_t timeout_usec,usec_t timeout_warn_usec,const char * cmd,pid_t pid)576 static int spawn_wait(struct udev_event *event,
577                       usec_t timeout_usec,
578                       usec_t timeout_warn_usec,
579                       const char *cmd, pid_t pid) {
580         struct pollfd pfd[1];
581         int err = 0;
582 
583         pfd[0].events = POLLIN;
584         pfd[0].fd = event->fd_signal;
585 
586         while (pid > 0) {
587                 int timeout;
588                 int timeout_warn = 0;
589                 int fdcount;
590 
591                 if (timeout_usec > 0) {
592                         usec_t age_usec;
593 
594                         age_usec = now(CLOCK_MONOTONIC) - event->birth_usec;
595                         if (age_usec >= timeout_usec)
596                                 timeout = 1000;
597                         else {
598                                 if (timeout_warn_usec > 0)
599                                         timeout_warn = ((timeout_warn_usec - age_usec) / USEC_PER_MSEC) + MSEC_PER_SEC;
600 
601                                 timeout = ((timeout_usec - timeout_warn_usec - age_usec) / USEC_PER_MSEC) + MSEC_PER_SEC;
602                         }
603                 } else {
604                         timeout = -1;
605                 }
606 
607                 fdcount = poll(pfd, 1, timeout_warn);
608                 if (fdcount < 0) {
609                         if (errno == EINTR)
610                                 continue;
611                         err = -errno;
612                         log_error_errno(errno, "failed to poll: %m");
613                         goto out;
614                 }
615                 if (fdcount == 0) {
616                         log_warning("slow: '%s' ["PID_FMT"]", cmd, pid);
617 
618                         fdcount = poll(pfd, 1, timeout);
619                         if (fdcount < 0) {
620                                 if (errno == EINTR)
621                                         continue;
622                                 err = -errno;
623                                 log_error_errno(errno, "failed to poll: %m");
624                                 goto out;
625                         }
626                         if (fdcount == 0) {
627                                 log_error("timeout: killing '%s' ["PID_FMT"]", cmd, pid);
628                                 kill(pid, SIGKILL);
629                         }
630                 }
631 
632                 if (pfd[0].revents & POLLIN) {
633                         struct signalfd_siginfo fdsi;
634                         int status;
635                         ssize_t size;
636 
637                         size = read(event->fd_signal, &fdsi, sizeof(struct signalfd_siginfo));
638                         if (size != sizeof(struct signalfd_siginfo))
639                                 continue;
640 
641                         switch (fdsi.ssi_signo) {
642                         case SIGTERM:
643                                 event->sigterm = true;
644                                 break;
645                         case SIGCHLD:
646                                 if (waitpid(pid, &status, WNOHANG) < 0)
647                                         break;
648                                 if (WIFEXITED(status)) {
649                                         log_debug("'%s' ["PID_FMT"] exit with return code %i", cmd, pid, WEXITSTATUS(status));
650                                         if (WEXITSTATUS(status) != 0)
651                                                 err = -1;
652                                 } else if (WIFSIGNALED(status)) {
653                                         log_error("'%s' ["PID_FMT"] terminated by signal %i (%s)", cmd, pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
654                                         err = -1;
655                                 } else if (WIFSTOPPED(status)) {
656                                         log_error("'%s' ["PID_FMT"] stopped", cmd, pid);
657                                         err = -1;
658                                 } else if (WIFCONTINUED(status)) {
659                                         log_error("'%s' ["PID_FMT"] continued", cmd, pid);
660                                         err = -1;
661                                 } else {
662                                         log_error("'%s' ["PID_FMT"] exit with status 0x%04x", cmd, pid, status);
663                                         err = -1;
664                                 }
665                                 pid = 0;
666                                 break;
667                         }
668                 }
669         }
670 out:
671         return err;
672 }
673 
udev_build_argv(struct udev * udev,char * cmd,int * argc,char * argv[])674 int udev_build_argv(struct udev *udev, char *cmd, int *argc, char *argv[]) {
675         int i = 0;
676         char *pos;
677 
678         if (strchr(cmd, ' ') == NULL) {
679                 argv[i++] = cmd;
680                 goto out;
681         }
682 
683         pos = cmd;
684         while (pos != NULL && pos[0] != '\0') {
685                 if (pos[0] == '\'') {
686                         /* do not separate quotes */
687                         pos++;
688                         argv[i] = strsep(&pos, "\'");
689                         if (pos != NULL)
690                                 while (pos[0] == ' ')
691                                         pos++;
692                 } else {
693                         argv[i] = strsep(&pos, " ");
694                         if (pos != NULL)
695                                 while (pos[0] == ' ')
696                                         pos++;
697                 }
698                 i++;
699         }
700 out:
701         argv[i] = NULL;
702         if (argc)
703                 *argc = i;
704         return 0;
705 }
706 
udev_event_spawn(struct udev_event * event,usec_t timeout_usec,usec_t timeout_warn_usec,const char * cmd,char ** envp,const sigset_t * sigmask,char * result,size_t ressize)707 int udev_event_spawn(struct udev_event *event,
708                      usec_t timeout_usec,
709                      usec_t timeout_warn_usec,
710                      const char *cmd, char **envp, const sigset_t *sigmask,
711                      char *result, size_t ressize) {
712         int outpipe[2] = {-1, -1};
713         int errpipe[2] = {-1, -1};
714         pid_t pid;
715         char arg[UTIL_PATH_SIZE];
716         char *argv[128];
717         char program[UTIL_PATH_SIZE];
718         int err = 0;
719 
720         strscpy(arg, sizeof(arg), cmd);
721         udev_build_argv(event->udev, arg, NULL, argv);
722 
723         /* pipes from child to parent */
724         if (result != NULL || log_get_max_level() >= LOG_INFO) {
725                 if (pipe2(outpipe, O_NONBLOCK) != 0) {
726                         err = -errno;
727                         log_error_errno(errno, "pipe failed: %m");
728                         goto out;
729                 }
730         }
731         if (log_get_max_level() >= LOG_INFO) {
732                 if (pipe2(errpipe, O_NONBLOCK) != 0) {
733                         err = -errno;
734                         log_error_errno(errno, "pipe failed: %m");
735                         goto out;
736                 }
737         }
738 
739         /* allow programs in /usr/lib/udev/ to be called without the path */
740         if (argv[0][0] != '/') {
741                 strscpyl(program, sizeof(program), UDEV_LIBEXEC_DIR "/", argv[0], NULL);
742 #ifdef HAVE_SPLIT_USR
743                 if(access(program, X_OK))
744                         strscpyl(program, sizeof(program), "/usr/lib/udev/", argv[0], NULL);
745                 if(access(program, X_OK))
746                         strscpyl(program, sizeof(program), "/lib/udev/", argv[0], NULL);
747 #endif
748                 argv[0] = program;
749         }
750 
751         pid = fork();
752         switch(pid) {
753         case 0:
754                 /* child closes parent's ends of pipes */
755                 if (outpipe[READ_END] >= 0) {
756                         close(outpipe[READ_END]);
757                         outpipe[READ_END] = -1;
758                 }
759                 if (errpipe[READ_END] >= 0) {
760                         close(errpipe[READ_END]);
761                         errpipe[READ_END] = -1;
762                 }
763 
764                 log_debug("starting '%s'", cmd);
765 
766                 spawn_exec(event, cmd, argv, envp, sigmask,
767                            outpipe[WRITE_END], errpipe[WRITE_END]);
768 
769                 _exit(2 );
770         case -1:
771                 log_error_errno(errno, "fork of '%s' failed: %m", cmd);
772                 err = -1;
773                 goto out;
774         default:
775                 /* parent closed child's ends of pipes */
776                 if (outpipe[WRITE_END] >= 0) {
777                         close(outpipe[WRITE_END]);
778                         outpipe[WRITE_END] = -1;
779                 }
780                 if (errpipe[WRITE_END] >= 0) {
781                         close(errpipe[WRITE_END]);
782                         errpipe[WRITE_END] = -1;
783                 }
784 
785                 spawn_read(event,
786                            timeout_usec,
787                            cmd,
788                            outpipe[READ_END], errpipe[READ_END],
789                            result, ressize);
790 
791                 err = spawn_wait(event, timeout_usec, timeout_warn_usec, cmd, pid);
792         }
793 
794 out:
795         if (outpipe[READ_END] >= 0)
796                 close(outpipe[READ_END]);
797         if (outpipe[WRITE_END] >= 0)
798                 close(outpipe[WRITE_END]);
799         if (errpipe[READ_END] >= 0)
800                 close(errpipe[READ_END]);
801         if (errpipe[WRITE_END] >= 0)
802                 close(errpipe[WRITE_END]);
803         return err;
804 }
805 
806 #ifdef ENABLE_RULE_GENERATOR
807 /* function to return the count of rules that assign NAME= to a value matching arg#2 , defined in udev-rules.c */
808 int udev_rules_assigning_name_to(struct udev_rules *rules,const char *match_name);
809 #endif
810 
rename_netif_dev_fromname_toname(struct udev_device * dev,const char * oldname,const char * name)811 static int rename_netif_dev_fromname_toname(struct udev_device *dev,const char *oldname,const char *name) {
812         int r;
813         int sk;
814         struct ifreq ifr;
815 
816 	log_debug("changing net interface name from '%s' to '%s'\n",oldname,name);
817 
818         sk = socket(PF_INET, SOCK_DGRAM, 0);
819         if (sk < 0)
820                 return log_error_errno(-errno, "error opening socket: %m");
821 
822         memzero(&ifr, sizeof(struct ifreq));
823         strscpy(ifr.ifr_name, IFNAMSIZ, oldname);
824         strscpy(ifr.ifr_newname, IFNAMSIZ, name);
825         r = ioctl(sk, SIOCSIFNAME, &ifr);
826 
827 #ifdef ENABLE_RULE_GENERATOR
828 	int loop;
829 
830 	if (r == 0) {
831 		log_info("renamed network interface %s to %s\n", ifr.ifr_name, ifr.ifr_newname);
832 		goto out;
833 	}
834 	/* keep trying if the destination interface name already exists */
835 	log_debug("collision on rename of network interface %s to %s , retrying until timeout\n",
836 		ifr.ifr_name, ifr.ifr_newname);
837 
838 	r = -errno;
839 	if (r != -EEXIST)
840 		goto out;
841 
842 	/* wait a maximum of 90 seconds for our target to become available */
843 	loop = 90 * 20;
844 	while (loop--) {
845 		const struct timespec duration = { 0, 1000 * 1000 * 1000 / 20 };
846 
847 		nanosleep(&duration, NULL);
848 
849 		r = ioctl(sk, SIOCSIFNAME, &ifr);
850 		if (r == 0) {
851 			log_info("renamed network interface %s to %s\n", ifr.ifr_name, ifr.ifr_newname);
852 			break;
853 		}
854 		r = -errno;
855 		if (r != -EEXIST)
856 			break;
857 	}
858 
859 out:
860 #endif
861 	if (r < 0)
862                 log_error_errno(-errno, "Error changing net interface name %s to %s: %m\n", ifr.ifr_name, ifr.ifr_newname);
863 	else
864 	        log_debug("renamed network interface '%s' to '%s'", oldname, name);
865 
866         close(sk);
867         return r;
868 }
869 
rename_netif(struct udev_event * event)870 static int rename_netif(struct udev_event *event) {
871 	return rename_netif_dev_fromname_toname(event->dev,udev_device_get_sysname(event->dev),event->name);
872 }
873 
udev_event_execute_rules(struct udev_event * event,usec_t timeout_usec,usec_t timeout_warn_usec,struct udev_list * properties_list,struct udev_rules * rules,const sigset_t * sigmask)874 void udev_event_execute_rules(struct udev_event *event,
875                               usec_t timeout_usec, usec_t timeout_warn_usec,
876                               struct udev_list *properties_list,
877                               struct udev_rules *rules,
878                               const sigset_t *sigmask) {
879         struct udev_device *dev = event->dev;
880 
881         if (udev_device_get_subsystem(dev) == NULL)
882                 return;
883 
884         if (streq(udev_device_get_action(dev), "remove")) {
885                 udev_device_read_db(dev);
886                 udev_device_tag_index(dev, NULL, false);
887                 udev_device_delete_db(dev);
888 
889                 if (major(udev_device_get_devnum(dev)) != 0)
890                         udev_watch_end(event->udev, dev);
891 
892                 udev_rules_apply_to_event(rules, event,
893                                           timeout_usec, timeout_warn_usec,
894                                           properties_list,
895                                           sigmask);
896 
897                 if (major(udev_device_get_devnum(dev)) != 0)
898                         udev_node_remove(dev);
899         } else {
900                 event->dev_db = udev_device_clone_with_db(dev);
901                 if (event->dev_db != NULL) {
902                         /* disable watch during event processing */
903                         if (major(udev_device_get_devnum(dev)) != 0)
904                                 udev_watch_end(event->udev, event->dev_db);
905                 }
906 
907                 if (major(udev_device_get_devnum(dev)) == 0 &&
908                     streq(udev_device_get_action(dev), "move"))
909                         udev_device_copy_properties(dev, event->dev_db);
910 
911                 udev_rules_apply_to_event(rules, event,
912                                           timeout_usec, timeout_warn_usec,
913                                           properties_list,
914                                           sigmask);
915 
916                 /* rename a new network interface, if needed */
917 
918                 /* ENABLE_RULE_GENERATOR conditional:
919                  * if this is a net iface, and it is an add event,
920                  * and as long as all of the following are FALSE:
921                  *  - no NAME target and the current name is not being used
922                  *  - there is a NAME target and it is the same as the current name
923                  *  - the rules can successfully be searched for the current name (not really part of the conditional)
924                  * the run the rename.
925                  *
926                  * note - udev_rules_assigning_name_to is run when event->name is NULL to ensure renames happen,
927                  * but also on its own to check if a temp-rename is necessary when event->name exists.
928                  *
929                  * A temp-rename is necessary when:
930                  * - there is no rule renaming the current iface but the current name IS used in some other rule
931                  * - there is a rule renaming the current iface,
932                  *   the current name IS used AND the target name != the current name
933                  */
934 
935 #ifdef ENABLE_RULE_GENERATOR
936 		int r;
937                 if (udev_device_get_ifindex(dev) > 0 && streq(udev_device_get_action(dev), "add") &&
938                     (event->name == NULL && (r=udev_rules_assigning_name_to(rules,udev_device_get_sysname(dev))) > 0 ||
939                     event->name != NULL && !streq(event->name, udev_device_get_sysname(dev)))) {
940                         char syspath[UTIL_PATH_SIZE];
941                         char *pos;
942                         char *finalifname = event->name;
943                         char newifname[IFNAMSIZ];
944 
945                         /* r is the number of rules that assign a device with NAME= this sysname */
946                         if (r > 0 || (r=udev_rules_assigning_name_to(rules,udev_device_get_sysname(dev))) > 0) {
947                                 /* have a conflict, rename to a temp name */
948                                 char *newpos;
949                                 int ifidnum;
950 
951                                 /* build the temporary iface name */
952                                 strscpy(newifname, IFNAMSIZ, udev_device_get_sysname(dev));
953                                 newpos=pos=&newifname[strcspn(newifname,"0123456789")];
954                                 ifidnum=(int)strtol(pos,&newpos,10);
955                                 *pos='\0';
956                                 if (newpos > pos && *newpos == '\0') /* append new iface num to name */
957                                         /* use udev_device_get_ifindex(dev) as it is unique to every iface */
958                                         snprintf(pos,IFNAMSIZ+(newifname-pos), "%d", 128 - udev_device_get_ifindex(dev));
959 
960                                 /* note, r > 0, which will skip the post-rename stuff if no rename occurs */
961 
962                                 /* if sysname isn't already the tmpname (ie there is no numeric component), do the rename */
963                                 if (!streq(newifname,udev_device_get_sysname(dev))) {
964                                         r = rename_netif_dev_fromname_toname(dev,udev_device_get_sysname(dev),newifname);
965                                         if (r == 0) {
966                                                 finalifname = newifname;
967                                                 log_debug("renamed netif to '%s' for collision avoidance\n", newifname);
968                                         } else {
969                                                 log_error("could not rename netif to '%s' for collision avoidance\n",newifname);
970                                         }
971                                 }
972                                 /* rename it now to its final target if its not already there */
973                                 if (event->name != NULL && !streq(event->name, newifname)) {
974                                         r = rename_netif_dev_fromname_toname(dev,newifname,event->name);
975                                         if (r == 0)
976                                                 finalifname = event->name;
977                                }
978 
979                         } else { /* no need to rename to a tempname first, do a regular direct rename to event->name */
980 
981                                 r = 1; /* skip the post-rename stuff if no rename occurs */
982                                 if (!streq(event->name, udev_device_get_sysname(dev)))
983                                         r = rename_netif(event);
984                         }
985 
986                         if (r == 0) {
987                                 log_debug("renamed netif to '%s'\n", finalifname);
988                                 r = udev_device_rename(dev, finalifname);
989 #else
990                 if (udev_device_get_ifindex(dev) > 0 && streq(udev_device_get_action(dev), "add") &&
991                     event->name != NULL && !streq(event->name, udev_device_get_sysname(dev))) {
992                         int r;
993 
994                         r = rename_netif(event);
995                         if (r < 0)
996                                 log_warning_errno(r, "could not rename interface '%d' from '%s' to '%s': %m", udev_device_get_ifindex(dev),
997                                                   udev_device_get_sysname(dev), event->name);
998                         else {
999                                 r = udev_device_rename(dev, event->name);
1000 #endif
1001                                 if (r < 0)
1002                                         log_warning_errno(r, "renamed interface '%d' from '%s' to '%s', but could not update udev_device: %m",
1003                                                           udev_device_get_ifindex(dev), udev_device_get_sysname(dev), event->name);
1004                                 else
1005                                         log_debug("changed devpath to '%s'", udev_device_get_devpath(dev));
1006                         }
1007                 }
1008 
1009                 if (major(udev_device_get_devnum(dev)) > 0) {
1010                         bool apply;
1011 
1012                         /* remove/update possible left-over symlinks from old database entry */
1013                         if (event->dev_db != NULL)
1014                                 udev_node_update_old_links(dev, event->dev_db);
1015 
1016                         if (!event->owner_set)
1017                                 event->uid = udev_device_get_devnode_uid(dev);
1018 
1019                         if (!event->group_set)
1020                                 event->gid = udev_device_get_devnode_gid(dev);
1021 
1022                         if (!event->mode_set) {
1023                                 if (udev_device_get_devnode_mode(dev) > 0) {
1024                                         /* kernel supplied value */
1025                                         event->mode = udev_device_get_devnode_mode(dev);
1026                                 } else if (event->gid > 0) {
1027                                         /* default 0660 if a group is assigned */
1028                                         event->mode = 0660;
1029                                 } else {
1030                                         /* default 0600 */
1031                                         event->mode = 0600;
1032                                 }
1033                         }
1034 
1035                         apply = streq(udev_device_get_action(dev), "add") || event->owner_set || event->group_set || event->mode_set;
1036                         udev_node_add(dev, apply, event->mode, event->uid, event->gid, &event->seclabel_list);
1037                 }
1038 
1039                 /* preserve old, or get new initialization timestamp */
1040                 udev_device_ensure_usec_initialized(event->dev, event->dev_db);
1041 
1042                 /* (re)write database file */
1043                 udev_device_tag_index(dev, event->dev_db, true);
1044                 udev_device_update_db(dev);
1045                 udev_device_set_is_initialized(dev);
1046 
1047                 event->dev_db = udev_device_unref(event->dev_db);
1048         }
1049 }
1050 
1051 void udev_event_execute_run(struct udev_event *event, usec_t timeout_usec, usec_t timeout_warn_usec, const sigset_t *sigmask) {
1052         struct udev_list_entry *list_entry;
1053 
1054         udev_list_entry_foreach(list_entry, udev_list_get_entry(&event->run_list)) {
1055                 const char *cmd = udev_list_entry_get_name(list_entry);
1056                 enum udev_builtin_cmd builtin_cmd = udev_list_entry_get_num(list_entry);
1057 
1058                 if (builtin_cmd < UDEV_BUILTIN_MAX) {
1059                         char command[UTIL_PATH_SIZE];
1060 
1061                         udev_event_apply_format(event, cmd, command, sizeof(command), false);
1062                         udev_builtin_run(event->dev, builtin_cmd, command, false);
1063                 } else {
1064                         char program[UTIL_PATH_SIZE];
1065                         char **envp;
1066 
1067                         if (event->exec_delay > 0) {
1068                                 log_debug("delay execution of '%s'", program);
1069                                 sleep(event->exec_delay);
1070                         }
1071 
1072                         udev_event_apply_format(event, cmd, program, sizeof(program), false);
1073                         envp = udev_device_get_properties_envp(event->dev);
1074                         udev_event_spawn(event, timeout_usec, timeout_warn_usec, program, envp, sigmask, NULL, 0);
1075                 }
1076         }
1077 }
1078