chiark / gitweb /
IMPORT=<file> allow to import a shell-var style config-file
[elogind.git] / udev_rules.c
1 /*
2  * udev_rules.c
3  *
4  * Userspace devfs
5  *
6  * Copyright (C) 2003 Greg Kroah-Hartman <greg@kroah.com>
7  * Copyright (C) 2003-2005 Kay Sievers <kay.sievers@vrfy.org>
8  *
9  *
10  *      This program is free software; you can redistribute it and/or modify it
11  *      under the terms of the GNU General Public License as published by the
12  *      Free Software Foundation version 2 of the License.
13  * 
14  *      This program is distributed in the hope that it will be useful, but
15  *      WITHOUT ANY WARRANTY; without even the implied warranty of
16  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  *      General Public License for more details.
18  * 
19  *      You should have received a copy of the GNU General Public License along
20  *      with this program; if not, write to the Free Software Foundation, Inc.,
21  *      675 Mass Ave, Cambridge, MA 02139, USA.
22  *
23  */
24
25 #include <stddef.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <stdio.h>
29 #include <fcntl.h>
30 #include <ctype.h>
31 #include <unistd.h>
32 #include <errno.h>
33 #include <sys/wait.h>
34
35 #include "libsysfs/sysfs/libsysfs.h"
36 #include "list.h"
37 #include "udev_libc_wrapper.h"
38 #include "udev.h"
39 #include "udev_utils.h"
40 #include "udev_version.h"
41 #include "logging.h"
42 #include "udev_rules.h"
43 #include "udev_db.h"
44
45
46 /* compare string with pattern (supports * ? [0-9] [!A-Z]) */
47 static int strcmp_pattern(const char *p, const char *s)
48 {
49         if (s[0] == '\0') {
50                 while (p[0] == '*')
51                         p++;
52                 return (p[0] != '\0');
53         }
54         switch (p[0]) {
55         case '[':
56                 {
57                         int not = 0;
58                         p++;
59                         if (p[0] == '!') {
60                                 not = 1;
61                                 p++;
62                         }
63                         while ((p[0] != '\0') && (p[0] != ']')) {
64                                 int match = 0;
65                                 if (p[1] == '-') {
66                                         if ((s[0] >= p[0]) && (s[0] <= p[2]))
67                                                 match = 1;
68                                         p += 3;
69                                 } else {
70                                         match = (p[0] == s[0]);
71                                         p++;
72                                 }
73                                 if (match ^ not) {
74                                         while ((p[0] != '\0') && (p[0] != ']'))
75                                                 p++;
76                                         if (p[0] == ']')
77                                                 return strcmp_pattern(p+1, s+1);
78                                 }
79                         }
80                 }
81                 break;
82         case '*':
83                 if (strcmp_pattern(p, s+1))
84                         return strcmp_pattern(p+1, s);
85                 return 0;
86         case '\0':
87                 if (s[0] == '\0') {
88                         return 0;
89                 }
90                 break;
91         default:
92                 if ((p[0] == s[0]) || (p[0] == '?'))
93                         return strcmp_pattern(p+1, s+1);
94                 break;
95         }
96         return 1;
97 }
98
99 /* extract possible {attr} and move str behind it */
100 static char *get_format_attribute(char **str)
101 {
102         char *pos;
103         char *attr = NULL;
104
105         if (*str[0] == '{') {
106                 pos = strchr(*str, '}');
107                 if (pos == NULL) {
108                         err("missing closing brace for format");
109                         return NULL;
110                 }
111                 pos[0] = '\0';
112                 attr = *str+1;
113                 *str = pos+1;
114                 dbg("attribute='%s', str='%s'", attr, *str);
115         }
116         return attr;
117 }
118
119 /* extract possible format length and move str behind it*/
120 static int get_format_len(char **str)
121 {
122         int num;
123         char *tail;
124
125         if (isdigit(*str[0])) {
126                 num = (int) strtoul(*str, &tail, 10);
127                 if (num > 0) {
128                         *str = tail;
129                         dbg("format length=%i", num);
130                         return num;
131                 } else {
132                         err("format parsing error '%s'", *str);
133                 }
134         }
135         return -1;
136 }
137
138 static int get_key(char **line, char **key, char **value)
139 {
140         char *linepos;
141         char *temp;
142
143         linepos = *line;
144         if (!linepos)
145                 return -1;
146
147         if (strchr(linepos, '\\')) {
148                 dbg("escaped characters are not supported, skip");
149                 return -1;
150         }
151
152         /* skip whitespace */
153         while (isspace(linepos[0]))
154                 linepos++;
155
156         /* get the key */
157         *key = linepos;
158         while (1) {
159                 linepos++;
160                 if (linepos[0] == '\0')
161                         return -1;
162                 if (isspace(linepos[0]))
163                         break;
164                 if (linepos[0] == '=')
165                         break;
166         }
167
168         /* terminate key */
169         linepos[0] = '\0';
170         linepos++;
171
172         /* skip whitespace */
173         while (isspace(linepos[0]))
174                 linepos++;
175
176         /* get the value*/
177         if (linepos[0] == '\0')
178                 return -1;
179
180         if (linepos[0] == '"') {
181                 linepos++;
182                 temp = strchr(linepos, '"');
183                 if (!temp)
184                         return -1;
185                 temp[0] = '\0';
186         } else if (linepos[0] == '\'') {
187                 linepos++;
188                 temp = strchr(linepos, '\'');
189                 if (!temp)
190                         return -1;
191                 temp[0] = '\0';
192         } else {
193                 temp = linepos;
194                 while (temp[0] && !isspace(temp[0]))
195                         temp++;
196                 temp[0] = '\0';
197         }
198         *value = linepos;
199
200         return 0;
201 }
202
203 static int import_file_into_env(const char *filename)
204 {
205         char line[LINE_SIZE];
206         char *bufline;
207         char *linepos;
208         char *variable;
209         char *value;
210         char *buf;
211         size_t bufsize;
212         size_t cur;
213         size_t count;
214         int lineno;
215         int retval = 0;
216
217         if (file_map(filename, &buf, &bufsize) != 0) {
218                 err("can't open '%s'", filename);
219                 return -1;
220         }
221
222         /* loop through the whole file */
223         lineno = 0;
224         cur = 0;
225         while (cur < bufsize) {
226                 count = buf_get_line(buf, bufsize, cur);
227                 bufline = &buf[cur];
228                 cur += count+1;
229                 lineno++;
230
231                 if (count >= sizeof(line)) {
232                         err("line too long, conf line skipped %s, line %d", udev_config_filename, lineno);
233                         continue;
234                 }
235
236                 /* eat the whitespace */
237                 while ((count > 0) && isspace(bufline[0])) {
238                         bufline++;
239                         count--;
240                 }
241                 if (count == 0)
242                         continue;
243
244                 /* see if this is a comment */
245                 if (bufline[0] == COMMENT_CHARACTER)
246                         continue;
247
248                 strlcpy(line, bufline, count+1);
249
250                 linepos = line;
251                 if (get_key(&linepos, &variable, &value) == 0) {
252                         dbg("import %s=%s", variable, value);
253                         setenv(variable, value, 0);
254                 }
255         }
256
257         file_unmap(buf, bufsize);
258         return retval;
259 }
260
261 /** Finds the lowest positive N such that <name>N isn't present in 
262  *  $(udevroot) either as a file or a symlink.
263  *
264  *  @param  name                Name to check for
265  *  @return                     0 if <name> didn't exist and N otherwise.
266  */
267 static int find_free_number(struct udevice *udev, const char *name)
268 {
269         char devpath[PATH_SIZE];
270         char filename[PATH_SIZE];
271         int num = 0;
272
273         strlcpy(filename, name, sizeof(filename));
274         while (1) {
275                 dbg("look for existing node '%s'", filename);
276                 if (udev_db_search_name(devpath, sizeof(devpath), filename) != 0) {
277                         dbg("free num=%d", num);
278                         return num;
279                 }
280
281                 num++;
282                 if (num > 1000) {
283                         info("find_free_number gone crazy (num=%d), aborted", num);
284                         return -1;
285                 }
286                 snprintf(filename, sizeof(filename), "%s%d", name, num);
287                 filename[sizeof(filename)-1] = '\0';
288         }
289 }
290
291 static int find_sysfs_attribute(struct sysfs_class_device *class_dev, struct sysfs_device *sysfs_device,
292                                 const char *name, char *value, size_t len)
293 {
294         struct sysfs_attribute *tmpattr;
295
296         dbg("look for device attribute '%s'", name);
297         if (class_dev) {
298                 dbg("look for class attribute '%s/%s'", class_dev->path, name);
299                 tmpattr = sysfs_get_classdev_attr(class_dev, name);
300                 if (tmpattr)
301                         goto attr_found;
302         }
303         if (sysfs_device) {
304                 dbg("look for devices attribute '%s/%s'", sysfs_device->path, name);
305                 tmpattr = sysfs_get_device_attr(sysfs_device, name);
306                 if (tmpattr)
307                         goto attr_found;
308         }
309         return -1;
310
311 attr_found:
312         strlcpy(value, tmpattr->value, len);
313         remove_trailing_char(value, '\n');
314
315         dbg("found attribute '%s'", tmpattr->path);
316         return 0;
317 }
318
319 static void apply_format(struct udevice *udev, char *string, size_t maxsize,
320                          struct sysfs_class_device *class_dev, struct sysfs_device *sysfs_device)
321 {
322         char temp[PATH_SIZE];
323         char temp2[PATH_SIZE];
324         char *head, *tail, *pos, *cpos, *attr, *rest;
325         int len;
326         int i;
327         unsigned int next_free_number;
328         struct sysfs_class_device *class_dev_parent;
329         enum subst_type {
330                 SUBST_UNKNOWN,
331                 SUBST_DEVPATH,
332                 SUBST_ID,
333                 SUBST_KERNEL_NUMBER,
334                 SUBST_KERNEL_NAME,
335                 SUBST_MAJOR,
336                 SUBST_MINOR,
337                 SUBST_RESULT,
338                 SUBST_SYSFS,
339                 SUBST_ENUM,
340                 SUBST_PARENT,
341                 SUBST_TEMP_NODE,
342                 SUBST_ROOT,
343                 SUBST_MODALIAS,
344                 SUBST_ENV,
345         };
346         static const struct subst_map {
347                 char *name;
348                 char fmt;
349                 enum subst_type type;
350         } map[] = {
351                 { .name = "devpath",            .fmt = 'p',     .type = SUBST_DEVPATH },
352                 { .name = "id",                 .fmt = 'b',     .type = SUBST_ID },
353                 { .name = "number",             .fmt = 'n',     .type = SUBST_KERNEL_NUMBER },
354                 { .name = "kernel",             .fmt = 'k',     .type = SUBST_KERNEL_NAME },
355                 { .name = "major",              .fmt = 'M',     .type = SUBST_MAJOR },
356                 { .name = "minor",              .fmt = 'm',     .type = SUBST_MINOR },
357                 { .name = "result",             .fmt = 'c',     .type = SUBST_RESULT },
358                 { .name = "sysfs",              .fmt = 's',     .type = SUBST_SYSFS },
359                 { .name = "enum",               .fmt = 'e',     .type = SUBST_ENUM },
360                 { .name = "parent",             .fmt = 'P',     .type = SUBST_PARENT },
361                 { .name = "tempnode",           .fmt = 'N',     .type = SUBST_TEMP_NODE },
362                 { .name = "root",               .fmt = 'r',     .type = SUBST_ROOT },
363                 { .name = "modalias",           .fmt = 'A',     .type = SUBST_MODALIAS },
364                 { .name = "env",                .fmt = 'E',     .type = SUBST_ENV },
365                 {}
366         };
367         enum subst_type type;
368         const struct subst_map *subst;
369
370         head = string;
371         while (1) {
372                 len = -1;
373                 while (head[0] != '\0') {
374                         if (head[0] == '$') {
375                                 /* substitute named variable */
376                                 if (head[1] == '\0')
377                                         break;
378                                 if (head[1] == '$') {
379                                         strlcpy(temp, head+2, sizeof(temp));
380                                         strlcpy(head+1, temp, maxsize);
381                                         head++;
382                                         continue;
383                                 }
384                                 head[0] = '\0';
385                                 for (subst = map; subst->name; subst++) {
386                                         if (strncasecmp(&head[1], subst->name, strlen(subst->name)) == 0) {
387                                                 type = subst->type;
388                                                 tail = head + strlen(subst->name)+1;
389                                                 dbg("will substitute format name '%s'", subst->name);
390                                                 goto found;
391                                         }
392                                 }
393                         }
394                         else if (head[0] == '%') {
395                                 /* substitute format char */
396                                 if (head[1] == '\0')
397                                         break;
398                                 if (head[1] == '%') {
399                                         strlcpy(temp, head+2, sizeof(temp));
400                                         strlcpy(head+1, temp, maxsize);
401                                         head++;
402                                         continue;
403                                 }
404                                 head[0] = '\0';
405                                 tail = head+1;
406                                 len = get_format_len(&tail);
407                                 for (subst = map; subst->name; subst++) {
408                                         if (tail[0] == subst->fmt) {
409                                                 type = subst->type;
410                                                 tail++;
411                                                 dbg("will substitute format char '%c'", subst->fmt);
412                                                 goto found;
413                                         }
414                                 }
415                         }
416                         head++;
417                 }
418                 break;
419 found:
420                 attr = get_format_attribute(&tail);
421                 strlcpy(temp, tail, sizeof(temp));
422                 dbg("format=%i, string='%s', tail='%s', class_dev=%p, sysfs_dev=%p",
423                     type ,string, tail, class_dev, sysfs_device);
424
425                 switch (type) {
426                 case SUBST_DEVPATH:
427                         strlcat(string, udev->devpath, maxsize);
428                         dbg("substitute devpath '%s'", udev->devpath);
429                         break;
430                 case SUBST_ID:
431                         strlcat(string, udev->bus_id, maxsize);
432                         dbg("substitute bus_id '%s'", udev->bus_id);
433                         break;
434                 case SUBST_KERNEL_NAME:
435                         strlcat(string, udev->kernel_name, maxsize);
436                         dbg("substitute kernel name '%s'", udev->kernel_name);
437                         break;
438                 case SUBST_KERNEL_NUMBER:
439                         strlcat(string, udev->kernel_number, maxsize);
440                         dbg("substitute kernel number '%s'", udev->kernel_number);
441                         break;
442                 case SUBST_MAJOR:
443                         sprintf(temp2, "%d", major(udev->devt));
444                         strlcat(string, temp2, maxsize);
445                         dbg("substitute major number '%s'", temp2);
446                         break;
447                 case SUBST_MINOR:
448                         sprintf(temp2, "%d", minor(udev->devt));
449                         strlcat(string, temp2, maxsize);
450                         dbg("substitute minor number '%s'", temp2);
451                         break;
452                 case SUBST_RESULT:
453                         if (udev->program_result[0] == '\0')
454                                 break;
455                         /* get part part of the result string */
456                         i = 0;
457                         if (attr != NULL)
458                                 i = strtoul(attr, &rest, 10);
459                         if (i > 0) {
460                                 dbg("request part #%d of result string", i);
461                                 cpos = udev->program_result;
462                                 while (--i) {
463                                         while (cpos[0] != '\0' && !isspace(cpos[0]))
464                                                 cpos++;
465                                         while (isspace(cpos[0]))
466                                                 cpos++;
467                                 }
468                                 if (i > 0) {
469                                         err("requested part of result string not found");
470                                         break;
471                                 }
472                                 strlcpy(temp2, cpos, sizeof(temp2));
473                                 /* %{2+}c copies the whole string from the second part on */
474                                 if (rest[0] != '+') {
475                                         cpos = strchr(temp2, ' ');
476                                         if (cpos)
477                                                 cpos[0] = '\0';
478                                 }
479                                 strlcat(string, temp2, maxsize);
480                                 dbg("substitute part of result string '%s'", temp2);
481                         } else {
482                                 strlcat(string, udev->program_result, maxsize);
483                                 dbg("substitute result string '%s'", udev->program_result);
484                         }
485                         break;
486                 case SUBST_SYSFS:
487                         if (attr == NULL) {
488                                 dbg("missing attribute");
489                                 break;
490                         }
491                         if (find_sysfs_attribute(class_dev, sysfs_device, attr, temp2, sizeof(temp2)) != 0) {
492                                 struct sysfs_device *parent_device;
493
494                                 dbg("sysfs attribute '%s' not found, walk up the physical devices", attr);
495                                 parent_device = sysfs_get_device_parent(sysfs_device);
496                                 while (parent_device) {
497                                         dbg("looking at '%s'", parent_device->path);
498                                         if (find_sysfs_attribute(NULL, parent_device, attr, temp2, sizeof(temp2)) == 0)
499                                                 break;
500                                         parent_device = sysfs_get_device_parent(parent_device);
501                                 }
502                                 if (!parent_device)
503                                         break;
504                         }
505                         /* strip trailing whitespace of sysfs value */
506                         i = strlen(temp2);
507                         while (i > 0 && isspace(temp2[i-1]))
508                                 temp2[--i] = '\0';
509                         replace_untrusted_chars(temp2);
510                         strlcat(string, temp2, maxsize);
511                         dbg("substitute sysfs value '%s'", temp2);
512                         break;
513                 case SUBST_ENUM:
514                         next_free_number = find_free_number(udev, string);
515                         if (next_free_number > 0) {
516                                 sprintf(temp2, "%d", next_free_number);
517                                 strlcat(string, temp2, maxsize);
518                         }
519                         break;
520                 case SUBST_PARENT:
521                         if (!class_dev)
522                                 break;
523                         class_dev_parent = sysfs_get_classdev_parent(class_dev);
524                         if (class_dev_parent != NULL) {
525                                 struct udevice udev_parent;
526
527                                 dbg("found parent '%s', get the node name", class_dev_parent->path);
528                                 udev_init_device(&udev_parent, NULL, NULL, NULL);
529                                 /* lookup the name in the udev_db with the DEVPATH of the parent */
530                                 if (udev_db_get_device(&udev_parent, &class_dev_parent->path[strlen(sysfs_path)]) == 0) {
531                                         strlcat(string, udev_parent.name, maxsize);
532                                         dbg("substitute parent node name'%s'", udev_parent.name);
533                                 } else
534                                         dbg("parent not found in database");
535                                 udev_cleanup_device(&udev_parent);
536                         }
537                         break;
538                 case SUBST_TEMP_NODE:
539                         if (udev->tmp_node[0] == '\0') {
540                                 dbg("create temporary device node for callout");
541                                 snprintf(udev->tmp_node, sizeof(udev->tmp_node), "%s/.tmp-%u-%u",
542                                          udev_root, major(udev->devt), minor(udev->devt));
543                                 udev->tmp_node[sizeof(udev->tmp_node)-1] = '\0';
544                                 udev_make_node(udev, udev->tmp_node, udev->devt, 0600, 0, 0);
545                         }
546                         strlcat(string, udev->tmp_node, maxsize);
547                         dbg("substitute temporary device node name '%s'", udev->tmp_node);
548                         break;
549                 case SUBST_ROOT:
550                         strlcat(string, udev_root, maxsize);
551                         dbg("substitute udev_root '%s'", udev_root);
552                         break;
553                 case SUBST_MODALIAS:
554                         if (find_sysfs_attribute(NULL, sysfs_device, "modalias", temp2, sizeof(temp2)) != 0)
555                                 break;
556                         strlcat(string, temp2, maxsize);
557                         dbg("substitute MODALIAS '%s'", temp2);
558                         break;
559                 case SUBST_ENV:
560                         if (attr == NULL) {
561                                 dbg("missing attribute");
562                                 break;
563                         }
564                         pos = getenv(attr);
565                         if (pos == NULL)
566                                 break;
567                         strlcat(string, pos, maxsize);
568                         dbg("substitute env '%s=%s'", attr, pos);
569                         break;
570                 default:
571                         err("unknown substitution type=%i", type);
572                         break;
573                 }
574                 /* possibly truncate to format-char specified length */
575                 if (len != -1) {
576                         head[len] = '\0';
577                         dbg("truncate to %i chars, subtitution string becomes '%s'", len, head);
578                 }
579
580                 strlcat(string, temp, maxsize);
581         }
582 }
583
584 static int execute_program_pipe(const char *command, const char *subsystem, char *value, int len)
585 {
586         int retval;
587         int count;
588         int status;
589         int pipefds[2];
590         pid_t pid;
591         char *pos;
592         char arg[PATH_SIZE];
593         char *argv[(sizeof(arg) / 2) + 1];
594         int devnull;
595         int i;
596
597         strlcpy(arg, command, sizeof(arg));
598         i = 0;
599         if (strchr(arg, ' ')) {
600                 pos = arg;
601                 while (pos != NULL) {
602                         if (pos[0] == '\'') {
603                                 /* don't separate if in apostrophes */
604                                 pos++;
605                                 argv[i] = strsep(&pos, "\'");
606                                 while (pos && pos[0] == ' ')
607                                         pos++;
608                         } else {
609                                 argv[i] = strsep(&pos, " ");
610                         }
611                         dbg("arg[%i] '%s'", i, argv[i]);
612                         i++;
613                 }
614                 argv[i] =  NULL;
615                 dbg("execute '%s' with parsed arguments", arg);
616         } else {
617                 argv[0] = arg;
618                 argv[1] = (char *) subsystem;
619                 argv[2] = NULL;
620                 dbg("execute '%s' with subsystem '%s' argument", arg, argv[1]);
621         }
622
623         retval = pipe(pipefds);
624         if (retval != 0) {
625                 err("pipe failed");
626                 return -1;
627         }
628
629         pid = fork();
630         switch(pid) {
631         case 0:
632                 /* child dup2 write side of pipe to STDOUT */
633                 devnull = open("/dev/null", O_RDWR);
634                 if (devnull >= 0) {
635                         dup2(devnull, STDIN_FILENO);
636                         dup2(devnull, STDERR_FILENO);
637                         close(devnull);
638                 }
639                 dup2(pipefds[1], STDOUT_FILENO);
640                 retval = execv(arg, argv);
641                 err("exec of program failed");
642                 _exit(1);
643         case -1:
644                 err("fork of '%s' failed", arg);
645                 retval = -1;
646                 break;
647         default:
648                 /* parent reads from pipefds[0] */
649                 close(pipefds[1]);
650                 retval = 0;
651                 i = 0;
652                 while (1) {
653                         count = read(pipefds[0], value + i, len - i-1);
654                         if (count < 0) {
655                                 err("read failed with '%s'", strerror(errno));
656                                 retval = -1;
657                         }
658
659                         if (count == 0)
660                                 break;
661
662                         i += count;
663                         if (i >= len-1) {
664                                 err("result len %d too short", len);
665                                 retval = -1;
666                                 break;
667                         }
668                 }
669                 value[i] = '\0';
670
671                 close(pipefds[0]);
672                 waitpid(pid, &status, 0);
673
674                 if (!WIFEXITED(status) || (WEXITSTATUS(status) != 0)) {
675                         dbg("exec program status 0x%x", status);
676                         retval = -1;
677                 }
678         }
679
680         if (!retval) {
681                 remove_trailing_char(value, '\n');
682                 dbg("result is '%s'", value);
683                 replace_untrusted_chars(value);
684         } else
685                 value[0] = '\0';
686
687         return retval;
688 }
689
690 static int match_rule(struct udevice *udev, struct udev_rule *rule,
691                       struct sysfs_class_device *class_dev, struct sysfs_device *sysfs_device)
692 {
693         struct sysfs_device *parent_device = sysfs_device;
694
695         if (rule->action_operation != KEY_OP_UNSET) {
696                 dbg("check for " KEY_ACTION " rule->action='%s' udev->action='%s'",
697                     rule->action, udev->action);
698                 if (strcmp_pattern(rule->action, udev->action) != 0) {
699                         dbg(KEY_ACTION " is not matching");
700                         if (rule->action_operation != KEY_OP_NOMATCH)
701                                 goto exit;
702                 } else {
703                         dbg(KEY_ACTION " matches");
704                         if (rule->action_operation == KEY_OP_NOMATCH)
705                                 goto exit;
706                 }
707                 dbg(KEY_ACTION " key is true");
708         }
709
710         if (rule->kernel_operation != KEY_OP_UNSET) {
711                 dbg("check for " KEY_KERNEL " rule->kernel='%s' udev_kernel_name='%s'",
712                     rule->kernel, udev->kernel_name);
713                 if (strcmp_pattern(rule->kernel, udev->kernel_name) != 0) {
714                         dbg(KEY_KERNEL " is not matching");
715                         if (rule->kernel_operation != KEY_OP_NOMATCH)
716                                 goto exit;
717                 } else {
718                         dbg(KEY_KERNEL " matches");
719                         if (rule->kernel_operation == KEY_OP_NOMATCH)
720                                 goto exit;
721                 }
722                 dbg(KEY_KERNEL " key is true");
723         }
724
725         if (rule->subsystem_operation != KEY_OP_UNSET) {
726                 dbg("check for " KEY_SUBSYSTEM " rule->subsystem='%s' udev->subsystem='%s'",
727                     rule->subsystem, udev->subsystem);
728                 if (strcmp_pattern(rule->subsystem, udev->subsystem) != 0) {
729                         dbg(KEY_SUBSYSTEM " is not matching");
730                         if (rule->subsystem_operation != KEY_OP_NOMATCH)
731                                 goto exit;
732                 } else {
733                         dbg(KEY_SUBSYSTEM " matches");
734                         if (rule->subsystem_operation == KEY_OP_NOMATCH)
735                                 goto exit;
736                 }
737                 dbg(KEY_SUBSYSTEM " key is true");
738         }
739
740         if (rule->devpath_operation != KEY_OP_UNSET) {
741                 dbg("check for " KEY_DEVPATH " rule->devpath='%s' udev->devpath='%s'",
742                     rule->devpath, udev->devpath);
743                 if (strcmp_pattern(rule->devpath, udev->devpath) != 0) {
744                         dbg(KEY_DEVPATH " is not matching");
745                         if (rule->devpath_operation != KEY_OP_NOMATCH)
746                                 goto exit;
747                 } else {
748                         dbg(KEY_DEVPATH " matches");
749                         if (rule->devpath_operation == KEY_OP_NOMATCH)
750                                 goto exit;
751                 }
752                 dbg(KEY_DEVPATH " key is true");
753         }
754
755         if (rule->modalias_operation != KEY_OP_UNSET) {
756                 char value[NAME_SIZE];
757
758                 if (find_sysfs_attribute(NULL, sysfs_device, "modalias", value, sizeof(value)) != 0) {
759                         dbg(KEY_MODALIAS " value not found");
760                         goto exit;
761                 }
762                 dbg("check for " KEY_MODALIAS " rule->modalias='%s' modalias='%s'",
763                     rule->modalias, value);
764                 if (strcmp_pattern(rule->modalias, value) != 0) {
765                         dbg(KEY_MODALIAS " is not matching");
766                         if (rule->modalias_operation != KEY_OP_NOMATCH)
767                                 goto exit;
768                 } else {
769                         dbg(KEY_MODALIAS " matches");
770                         if (rule->modalias_operation == KEY_OP_NOMATCH)
771                                 goto exit;
772                 }
773                 dbg(KEY_MODALIAS " key is true");
774         }
775
776         if (rule->env_pair_count) {
777                 int i;
778
779                 dbg("check for " KEY_ENV " pairs");
780                 for (i = 0; i < rule->env_pair_count; i++) {
781                         struct key_pair *pair;
782                         const char *value;
783
784                         pair = &rule->env_pair[i];
785                         value = getenv(pair->name);
786                         if (!value) {
787                                 dbg(KEY_ENV "{'%s'} is not found", pair->name);
788                                 goto exit;
789                         }
790                         if (strcmp_pattern(pair->value, value) != 0) {
791                                 dbg(KEY_ENV "{'%s'} is not matching", pair->name);
792                                 if (pair->operation != KEY_OP_NOMATCH)
793                                         goto exit;
794                         } else {
795                                 dbg(KEY_ENV "{'%s'} matches", pair->name);
796                                 if (pair->operation == KEY_OP_NOMATCH)
797                                         goto exit;
798                         }
799                 }
800                 dbg(KEY_ENV " key is true");
801         }
802
803         /* walk up the chain of physical devices and find a match */
804         while (1) {
805                 /* check for matching driver */
806                 if (rule->driver_operation != KEY_OP_UNSET) {
807                         if (parent_device == NULL) {
808                                 dbg("device has no sysfs_device");
809                                 goto exit;
810                         }
811                         dbg("check for " KEY_DRIVER " rule->driver='%s' sysfs_device->driver_name='%s'",
812                             rule->driver, parent_device->driver_name);
813                         if (strcmp_pattern(rule->driver, parent_device->driver_name) != 0) {
814                                 dbg(KEY_DRIVER " is not matching");
815                                 if (rule->driver_operation != KEY_OP_NOMATCH)
816                                         goto try_parent;
817                         } else {
818                                 dbg(KEY_DRIVER " matches");
819                                 if (rule->driver_operation == KEY_OP_NOMATCH)
820                                         goto try_parent;
821                         }
822                         dbg(KEY_DRIVER " key is true");
823                 }
824
825                 /* check for matching bus value */
826                 if (rule->bus_operation != KEY_OP_UNSET) {
827                         if (parent_device == NULL) {
828                                 dbg("device has no sysfs_device");
829                                 goto exit;
830                         }
831                         dbg("check for " KEY_BUS " rule->bus='%s' sysfs_device->bus='%s'",
832                             rule->bus, parent_device->bus);
833                         if (strcmp_pattern(rule->bus, parent_device->bus) != 0) {
834                                 dbg(KEY_BUS " is not matching");
835                                 if (rule->bus_operation != KEY_OP_NOMATCH)
836                                         goto try_parent;
837                         } else {
838                                 dbg(KEY_BUS " matches");
839                                 if (rule->bus_operation == KEY_OP_NOMATCH)
840                                         goto try_parent;
841                         }
842                         dbg(KEY_BUS " key is true");
843                 }
844
845                 /* check for matching bus id */
846                 if (rule->id_operation != KEY_OP_UNSET) {
847                         if (parent_device == NULL) {
848                                 dbg("device has no sysfs_device");
849                                 goto exit;
850                         }
851                         dbg("check " KEY_ID);
852                         if (strcmp_pattern(rule->id, parent_device->bus_id) != 0) {
853                                 dbg(KEY_ID " is not matching");
854                                 if (rule->id_operation != KEY_OP_NOMATCH)
855                                         goto try_parent;
856                         } else {
857                                 dbg(KEY_ID " matches");
858                                 if (rule->id_operation == KEY_OP_NOMATCH)
859                                         goto try_parent;
860                         }
861                         dbg(KEY_ID " key is true");
862                 }
863
864                 /* check for matching sysfs pairs */
865                 if (rule->sysfs_pair_count) {
866                         int i;
867
868                         dbg("check " KEY_SYSFS " pairs");
869                         for (i = 0; i < rule->sysfs_pair_count; i++) {
870                                 struct key_pair *pair;
871                                 char value[VALUE_SIZE];
872                                 size_t len;
873
874                                 pair = &rule->sysfs_pair[i];
875                                 if (find_sysfs_attribute(class_dev, parent_device, pair->name, value, sizeof(value)) != 0)
876                                         goto try_parent;
877
878                                 /* strip trailing whitespace of value, if not asked to match for it */
879                                 len = strlen(pair->value);
880                                 if (len && !isspace(pair->value[len-1])) {
881                                         len = strlen(value);
882                                         while (len > 0 && isspace(value[len-1]))
883                                                 value[--len] = '\0';
884                                         dbg("removed %i trailing whitespace chars from '%s'", strlen(value)-len, value);
885                                 }
886
887                                 dbg("compare attribute '%s' value '%s' with '%s'", pair->name, value, pair->value);
888                                 if (strcmp_pattern(pair->value, value) != 0) {
889                                         dbg(KEY_SYSFS "{'%s'} is not matching", pair->name);
890                                         if (pair->operation != KEY_OP_NOMATCH)
891                                                 goto try_parent;
892                                 } else {
893                                         dbg(KEY_SYSFS "{'%s'} matches", pair->name);
894                                         if (pair->operation == KEY_OP_NOMATCH)
895                                                 goto try_parent;
896                                 }
897                         }
898                         dbg(KEY_SYSFS " keys are true");
899                 }
900
901                 /* found matching physical device  */
902                 break;
903 try_parent:
904                 dbg("try parent sysfs device");
905                 parent_device = sysfs_get_device_parent(parent_device);
906                 if (parent_device == NULL)
907                         goto exit;
908                 dbg("look at sysfs_device->path='%s'", parent_device->path);
909                 dbg("look at sysfs_device->bus_id='%s'", parent_device->bus_id);
910         }
911
912         if (rule->import_operation != KEY_OP_UNSET) {
913                 char import[PATH_SIZE];
914
915                 strlcpy(import, rule->import, sizeof(import));
916                 apply_format(udev, import, sizeof(import), class_dev, sysfs_device);
917                 dbg("check for " KEY_IMPORT " import='%s", import);
918                 if (import_file_into_env(import) == 0) {
919                         dbg(KEY_IMPORT " file '%s' imported", rule->import);
920                         if (rule->import_operation == KEY_OP_NOMATCH)
921                                 goto exit;
922                 } else
923                         goto exit;
924                 dbg(KEY_IMPORT " key is true");
925         }
926
927         /* execute external program */
928         if (rule->program_operation != KEY_OP_UNSET) {
929                 char program[PATH_SIZE];
930
931                 strlcpy(program, rule->program, sizeof(program));
932                 apply_format(udev, program, sizeof(program), class_dev, sysfs_device);
933                 dbg("check for " KEY_PROGRAM " program='%s", program);
934                 if (execute_program_pipe(program, udev->subsystem,
935                                          udev->program_result, sizeof(udev->program_result)) != 0) {
936                         dbg(KEY_PROGRAM " returned nonzero");
937                         if (rule->program_operation != KEY_OP_NOMATCH)
938                                 goto exit;
939                 } else {
940                         dbg(KEY_PROGRAM " returned successful");
941                         if (rule->program_operation == KEY_OP_NOMATCH)
942                                 goto exit;
943                 }
944                 dbg(KEY_PROGRAM " key is true");
945         }
946
947         /* check for matching result of external program */
948         if (rule->result_operation != KEY_OP_UNSET) {
949                 dbg("check for " KEY_RESULT " rule->result='%s', udev->program_result='%s'",
950                    rule->result, udev->program_result);
951                 if (strcmp_pattern(rule->result, udev->program_result) != 0) {
952                         dbg(KEY_RESULT " is not matching");
953                         if (rule->result_operation != KEY_OP_NOMATCH)
954                                 goto exit;
955                 } else {
956                         dbg(KEY_RESULT " matches");
957                         if (rule->result_operation == KEY_OP_NOMATCH)
958                                 goto exit;
959                 }
960                 dbg(KEY_RESULT " key is true");
961         }
962
963         /* rule matches */
964         return 0;
965
966 exit:
967         return -1;
968 }
969
970 int udev_rules_get_name(struct udevice *udev, struct sysfs_class_device *class_dev)
971 {
972         struct sysfs_class_device *class_dev_parent;
973         struct sysfs_device *sysfs_device = NULL;
974         struct udev_rule *rule;
975
976         dbg("class_dev->name='%s'", class_dev->name);
977
978         /* Figure out where the "device"-symlink is at.  For char devices this will
979          * always be in the class_dev->path.  On block devices, only the main block
980          * device will have the device symlink in it's path. All partition devices
981          * need to look at the symlink in its parent directory.
982          */
983         class_dev_parent = sysfs_get_classdev_parent(class_dev);
984         if (class_dev_parent != NULL) {
985                 dbg("given class device has a parent, use this instead");
986                 sysfs_device = sysfs_get_classdev_device(class_dev_parent);
987         } else {
988                 sysfs_device = sysfs_get_classdev_device(class_dev);
989         }
990
991         if (sysfs_device) {
992                 dbg("found devices device: path='%s', bus_id='%s', bus='%s'",
993                     sysfs_device->path, sysfs_device->bus_id, sysfs_device->bus);
994                 strlcpy(udev->bus_id, sysfs_device->bus_id, sizeof(udev->bus_id));
995         }
996
997         dbg("udev->kernel_name='%s'", udev->kernel_name);
998
999         /* look for a matching rule to apply */
1000         udev_rules_iter_init();
1001         while (1) {
1002                 rule = udev_rules_iter_next();
1003                 if (rule == NULL)
1004                         break;
1005
1006                 if (udev->name_set && rule->name_operation != KEY_OP_UNSET) {
1007                         dbg("node name already set, rule ignored");
1008                         continue;
1009                 }
1010
1011                 dbg("process rule");
1012                 if (match_rule(udev, rule, class_dev, sysfs_device) == 0) {
1013                         /* apply options */
1014                         if (rule->ignore_device) {
1015                                 info("configured rule in '%s[%i]' applied, '%s' is ignored",
1016                                      rule->config_file, rule->config_line, udev->kernel_name);
1017                                 udev->ignore_device = 1;
1018                                 return 0;
1019                         }
1020                         if (rule->ignore_remove) {
1021                                 udev->ignore_remove = 1;
1022                                 dbg("remove event should be ignored");
1023                         }
1024                         /* apply all_partitions option only at a main block device */
1025                         if (rule->partitions && udev->type == DEV_BLOCK && udev->kernel_number[0] == '\0') {
1026                                 udev->partitions = rule->partitions;
1027                                 dbg("creation of partition nodes requested");
1028                         }
1029
1030                         /* apply permissions */
1031                         if (!udev->mode_final && rule->mode != 0000) {
1032                                 if (rule->mode_operation == KEY_OP_ASSIGN_FINAL)
1033                                         udev->mode_final = 1;
1034                                 udev->mode = rule->mode;
1035                                 dbg("applied mode=%#o to '%s'", udev->mode, udev->kernel_name);
1036                         }
1037                         if (!udev->owner_final && rule->owner[0] != '\0') {
1038                                 if (rule->owner_operation == KEY_OP_ASSIGN_FINAL)
1039                                         udev->owner_final = 1;
1040                                 strlcpy(udev->owner, rule->owner, sizeof(udev->owner));
1041                                 apply_format(udev, udev->owner, sizeof(udev->owner), class_dev, sysfs_device);
1042                                 dbg("applied owner='%s' to '%s'", udev->owner, udev->kernel_name);
1043                         }
1044                         if (!udev->group_final && rule->group[0] != '\0') {
1045                                 if (rule->group_operation == KEY_OP_ASSIGN_FINAL)
1046                                         udev->group_final = 1;
1047                                 strlcpy(udev->group, rule->group, sizeof(udev->group));
1048                                 apply_format(udev, udev->group, sizeof(udev->group), class_dev, sysfs_device);
1049                                 dbg("applied group='%s' to '%s'", udev->group, udev->kernel_name);
1050                         }
1051
1052                         /* collect symlinks */
1053                         if (!udev->symlink_final && rule->symlink_operation != KEY_OP_UNSET) {
1054                                 char temp[PATH_SIZE];
1055                                 char *pos, *next;
1056
1057                                 if (rule->symlink_operation == KEY_OP_ASSIGN_FINAL)
1058                                         udev->symlink_final = 1;
1059                                 if (rule->symlink_operation == KEY_OP_ASSIGN || rule->symlink_operation == KEY_OP_ASSIGN_FINAL) {
1060                                         struct name_entry *name_loop;
1061                                         struct name_entry *temp_loop;
1062
1063                                         info("reset symlink list");
1064                                         list_for_each_entry_safe(name_loop, temp_loop, &udev->symlink_list, node) {
1065                                                 list_del(&name_loop->node);
1066                                                 free(name_loop);
1067                                         }
1068                                 }
1069                                 if (rule->symlink[0] != '\0') {
1070                                         info("configured rule in '%s[%i]' applied, added symlink '%s'",
1071                                              rule->config_file, rule->config_line, rule->symlink);
1072                                         strlcpy(temp, rule->symlink, sizeof(temp));
1073                                         apply_format(udev, temp, sizeof(temp), class_dev, sysfs_device);
1074
1075                                         /* add multiple symlinks separated by spaces */
1076                                         pos = temp;
1077                                         next = strchr(temp, ' ');
1078                                         while (next) {
1079                                                 next[0] = '\0';
1080                                                 info("add symlink '%s'", pos);
1081                                                 name_list_add(&udev->symlink_list, pos, 0);
1082                                                 pos = &next[1];
1083                                                 next = strchr(pos, ' ');
1084                                         }
1085                                         info("add symlink '%s'", pos);
1086                                         name_list_add(&udev->symlink_list, pos, 0);
1087                                 }
1088                         }
1089
1090                         /* set name, later rules with name set will be ignored */
1091                         if (rule->name_operation != KEY_OP_UNSET) {
1092                                 udev->name_set = 1;
1093                                 if (rule->name[0] == '\0') {
1094                                         info("configured rule in '%s[%i]' applied, node handling for '%s' supressed",
1095                                              rule->config_file, rule->config_line, udev->kernel_name);
1096                                 } else {
1097                                         strlcpy(udev->name, rule->name, sizeof(udev->name));
1098                                         apply_format(udev, udev->name, sizeof(udev->name), class_dev, sysfs_device);
1099                                         strlcpy(udev->config_file, rule->config_file, sizeof(udev->config_file));
1100                                         udev->config_line = rule->config_line;
1101
1102                                         info("configured rule in '%s:%i' applied, '%s' becomes '%s'",
1103                                              rule->config_file, rule->config_line, udev->kernel_name, rule->name);
1104                                         if (udev->type != DEV_NET)
1105                                                 dbg("name, '%s' is going to have owner='%s', group='%s', mode=%#o partitions=%i",
1106                                                     udev->name, udev->owner, udev->group, udev->mode, udev->partitions);
1107                                 }
1108                         }
1109
1110                         if (!udev->run_final && rule->run_operation != KEY_OP_UNSET) {
1111                                 char program[PATH_SIZE];
1112
1113                                 if (rule->run_operation == KEY_OP_ASSIGN_FINAL)
1114                                         udev->run_final = 1;
1115                                 if (rule->run_operation == KEY_OP_ASSIGN || rule->run_operation == KEY_OP_ASSIGN_FINAL) {
1116                                         struct name_entry *name_loop;
1117                                         struct name_entry *temp_loop;
1118
1119                                         info("reset run list");
1120                                         list_for_each_entry_safe(name_loop, temp_loop, &udev->run_list, node) {
1121                                                 list_del(&name_loop->node);
1122                                                 free(name_loop);
1123                                         }
1124                                 }
1125                                 if (rule->run[0] != '\0') {
1126                                         strlcpy(program, rule->run, sizeof(program));
1127                                         apply_format(udev, program, sizeof(program), class_dev, sysfs_device);
1128                                         dbg("add run '%s'", program);
1129                                         name_list_add(&udev->run_list, program, 0);
1130                                 }
1131                         }
1132
1133                         if (rule->last_rule) {
1134                                 dbg("last rule to be applied");
1135                                 break;
1136                         }
1137                 }
1138         }
1139
1140         if (udev->name[0] == '\0') {
1141                 strlcpy(udev->name, udev->kernel_name, sizeof(udev->name));
1142                 info("no rule found, use kernel name '%s'", udev->name);
1143         }
1144
1145         if (udev->tmp_node[0] != '\0') {
1146                 dbg("removing temporary device node");
1147                 unlink_secure(udev->tmp_node);
1148                 udev->tmp_node[0] = '\0';
1149         }
1150
1151         return 0;
1152 }
1153
1154 int udev_rules_get_run(struct udevice *udev, struct sysfs_device *sysfs_device)
1155 {
1156         struct udev_rule *rule;
1157
1158         /* look for a matching rule to apply */
1159         udev_rules_iter_init();
1160         while (1) {
1161                 rule = udev_rules_iter_next();
1162                 if (rule == NULL)
1163                         break;
1164
1165                 dbg("process rule");
1166                 if (rule->run_operation == KEY_OP_UNSET)
1167                         continue;
1168
1169                 if (rule->name_operation != KEY_OP_UNSET || rule->symlink_operation != KEY_OP_UNSET ||
1170                     rule->mode != 0000 || rule->owner[0] != '\0' || rule->group[0] != '\0') {
1171                         dbg("skip rule that names a device");
1172                         continue;
1173                 }
1174
1175                 if (match_rule(udev, rule, NULL, sysfs_device) == 0) {
1176                         if (rule->ignore_device) {
1177                                 info("configured rule in '%s[%i]' applied, '%s' is ignored",
1178                                      rule->config_file, rule->config_line, udev->kernel_name);
1179                                 udev->ignore_device = 1;
1180                                 return 0;
1181                         }
1182
1183                         if (!udev->run_final && rule->run_operation != KEY_OP_UNSET) {
1184                                 char program[PATH_SIZE];
1185
1186                                 if (rule->run_operation == KEY_OP_ASSIGN || rule->run_operation == KEY_OP_ASSIGN_FINAL) {
1187                                         struct name_entry *name_loop;
1188                                         struct name_entry *temp_loop;
1189
1190                                         info("reset run list");
1191                                         list_for_each_entry_safe(name_loop, temp_loop, &udev->run_list, node) {
1192                                                 list_del(&name_loop->node);
1193                                                 free(name_loop);
1194                                         }
1195                                 }
1196                                 if (rule->run[0] != '\0') {
1197                                         strlcpy(program, rule->run, sizeof(program));
1198                                         apply_format(udev, program, sizeof(program), NULL, sysfs_device);
1199                                         dbg("add run '%s'", program);
1200                                         name_list_add(&udev->run_list, program, 0);
1201                                 }
1202                                 if (rule->run_operation == KEY_OP_ASSIGN_FINAL)
1203                                         break;
1204                         }
1205
1206                         if (rule->last_rule) {
1207                                 dbg("last rule to be applied");
1208                                 break;
1209                         }
1210                 }
1211         }
1212
1213         return 0;
1214 }