chiark / gitweb /
27fb0a89a607065207e689d995f07433314b4b83
[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] == '"') {
178                 linepos++;
179                 temp = strchr(linepos, '"');
180                 if (!temp) {
181                         dbg("missing closing quote");
182                         return -1;
183                 }
184                 dbg("value is quoted");
185                 temp[0] = '\0';
186         } else if (linepos[0] == '\'') {
187                 linepos++;
188                 temp = strchr(linepos, '\'');
189                 if (!temp) {
190                         dbg("missing closing quote");
191                         return -1;
192                 }
193                 dbg("value is quoted");
194                 temp[0] = '\0';
195         } else if (linepos[0] == '\0') {
196                 dbg("value is empty");
197         } else {
198                 temp = linepos;
199                 while (temp[0] && !isspace(temp[0]))
200                         temp++;
201                 temp[0] = '\0';
202         }
203         *value = linepos;
204
205         return 0;
206 }
207
208 static int import_keys_into_env(struct udevice *udev, const char *buf, size_t bufsize)
209 {
210         char line[LINE_SIZE];
211         const char *bufline;
212         char *linepos;
213         char *variable;
214         char *value;
215         size_t cur;
216         size_t count;
217         int lineno;
218
219         /* loop through the whole buffer */
220         lineno = 0;
221         cur = 0;
222         while (cur < bufsize) {
223                 count = buf_get_line(buf, bufsize, cur);
224                 bufline = &buf[cur];
225                 cur += count+1;
226                 lineno++;
227
228                 if (count >= sizeof(line)) {
229                         err("line too long, conf line skipped %s, line %d", udev_config_filename, lineno);
230                         continue;
231                 }
232
233                 /* eat the whitespace */
234                 while ((count > 0) && isspace(bufline[0])) {
235                         bufline++;
236                         count--;
237                 }
238                 if (count == 0)
239                         continue;
240
241                 /* see if this is a comment */
242                 if (bufline[0] == COMMENT_CHARACTER)
243                         continue;
244
245                 strlcpy(line, bufline, count+1);
246
247                 linepos = line;
248                 if (get_key(&linepos, &variable, &value) == 0) {
249                         dbg("import '%s=%s'", variable, value);
250                         name_list_key_add(&udev->env_list, variable, value);
251                         setenv(variable, value, 1);
252                 }
253         }
254
255         return 0;
256 }
257
258 static int import_file_into_env(struct udevice *udev, const char *filename)
259 {
260         char *buf;
261         size_t bufsize;
262
263         if (file_map(filename, &buf, &bufsize) != 0) {
264                 err("can't open '%s'", filename);
265                 return -1;
266         }
267         import_keys_into_env(udev, buf, bufsize);
268         file_unmap(buf, bufsize);
269
270         return 0;
271 }
272
273 static int import_program_into_env(struct udevice *udev, const char *program)
274 {
275         char result[1024];
276         size_t reslen;
277
278         if (execute_program(program, udev->subsystem, result, sizeof(result), &reslen) != 0)
279                 return -1;
280         return import_keys_into_env(udev, result, reslen);
281 }
282
283 /* finds the lowest positive N such that <name>N isn't present in the udevdb
284  * if <name> doesn't exist, 0 is returned, N otherwise
285  */
286 static int find_free_number(struct udevice *udev, const char *name)
287 {
288         char devpath[PATH_SIZE];
289         char filename[PATH_SIZE];
290         int num = 0;
291
292         strlcpy(filename, name, sizeof(filename));
293         while (1) {
294                 dbg("look for existing node '%s'", filename);
295                 if (udev_db_search_name(devpath, sizeof(devpath), filename) != 0) {
296                         dbg("free num=%d", num);
297                         return num;
298                 }
299
300                 num++;
301                 if (num > 1000) {
302                         info("find_free_number gone crazy (num=%d), aborted", num);
303                         return -1;
304                 }
305                 snprintf(filename, sizeof(filename), "%s%d", name, num);
306                 filename[sizeof(filename)-1] = '\0';
307         }
308 }
309
310 static int find_sysfs_attribute(struct sysfs_class_device *class_dev, struct sysfs_device *sysfs_device,
311                                 const char *name, char *value, size_t len)
312 {
313         struct sysfs_attribute *tmpattr;
314
315         dbg("look for device attribute '%s'", name);
316         if (class_dev) {
317                 dbg("look for class attribute '%s/%s'", class_dev->path, name);
318                 tmpattr = sysfs_get_classdev_attr(class_dev, name);
319                 if (tmpattr)
320                         goto attr_found;
321         }
322         if (sysfs_device) {
323                 dbg("look for devices attribute '%s/%s'", sysfs_device->path, name);
324                 tmpattr = sysfs_get_device_attr(sysfs_device, name);
325                 if (tmpattr)
326                         goto attr_found;
327         }
328         return -1;
329
330 attr_found:
331         strlcpy(value, tmpattr->value, len);
332         remove_trailing_char(value, '\n');
333
334         dbg("found attribute '%s'", tmpattr->path);
335         return 0;
336 }
337
338 #define WAIT_LOOP_PER_SECOND                    20
339 static int wait_for_sysfs(struct udevice *udev, const char *file, int timeout)
340 {
341         char filename[PATH_SIZE];
342         struct stat stats;
343         int loop = timeout * WAIT_LOOP_PER_SECOND;
344
345         snprintf(filename, sizeof(filename), "%s%s/%s", sysfs_path, udev->devpath, file);
346         filename[sizeof(filename)-1] = '\0';
347         dbg("wait %i sec for '%s'", timeout, filename);
348
349         while (--loop) {
350                 if (stat(filename, &stats) == 0) {
351                         dbg("file appeared after %i loops", (timeout * WAIT_LOOP_PER_SECOND) - loop-1);
352                         return 0;
353                 }
354                 usleep(1000 * 1000 / WAIT_LOOP_PER_SECOND);
355         }
356         dbg("waiting for '%s' failed", filename);
357         return -1;
358 }
359
360 static void apply_format(struct udevice *udev, char *string, size_t maxsize,
361                          struct sysfs_class_device *class_dev, struct sysfs_device *sysfs_device)
362 {
363         char temp[PATH_SIZE];
364         char temp2[PATH_SIZE];
365         char *head, *tail, *pos, *cpos, *attr, *rest;
366         int len;
367         int i;
368         unsigned int next_free_number;
369         struct sysfs_class_device *class_dev_parent;
370         enum subst_type {
371                 SUBST_UNKNOWN,
372                 SUBST_DEVPATH,
373                 SUBST_ID,
374                 SUBST_KERNEL_NUMBER,
375                 SUBST_KERNEL_NAME,
376                 SUBST_MAJOR,
377                 SUBST_MINOR,
378                 SUBST_RESULT,
379                 SUBST_SYSFS,
380                 SUBST_ENUM,
381                 SUBST_PARENT,
382                 SUBST_TEMP_NODE,
383                 SUBST_ROOT,
384                 SUBST_MODALIAS,
385                 SUBST_ENV,
386         };
387         static const struct subst_map {
388                 char *name;
389                 char fmt;
390                 enum subst_type type;
391         } map[] = {
392                 { .name = "devpath",            .fmt = 'p',     .type = SUBST_DEVPATH },
393                 { .name = "id",                 .fmt = 'b',     .type = SUBST_ID },
394                 { .name = "number",             .fmt = 'n',     .type = SUBST_KERNEL_NUMBER },
395                 { .name = "kernel",             .fmt = 'k',     .type = SUBST_KERNEL_NAME },
396                 { .name = "major",              .fmt = 'M',     .type = SUBST_MAJOR },
397                 { .name = "minor",              .fmt = 'm',     .type = SUBST_MINOR },
398                 { .name = "result",             .fmt = 'c',     .type = SUBST_RESULT },
399                 { .name = "sysfs",              .fmt = 's',     .type = SUBST_SYSFS },
400                 { .name = "enum",               .fmt = 'e',     .type = SUBST_ENUM },
401                 { .name = "parent",             .fmt = 'P',     .type = SUBST_PARENT },
402                 { .name = "tempnode",           .fmt = 'N',     .type = SUBST_TEMP_NODE },
403                 { .name = "root",               .fmt = 'r',     .type = SUBST_ROOT },
404                 { .name = "modalias",           .fmt = 'A',     .type = SUBST_MODALIAS },
405                 { .name = "env",                .fmt = 'E',     .type = SUBST_ENV },
406                 {}
407         };
408         enum subst_type type;
409         const struct subst_map *subst;
410
411         head = string;
412         while (1) {
413                 len = -1;
414                 while (head[0] != '\0') {
415                         if (head[0] == '$') {
416                                 /* substitute named variable */
417                                 if (head[1] == '\0')
418                                         break;
419                                 if (head[1] == '$') {
420                                         strlcpy(temp, head+2, sizeof(temp));
421                                         strlcpy(head+1, temp, maxsize);
422                                         head++;
423                                         continue;
424                                 }
425                                 head[0] = '\0';
426                                 for (subst = map; subst->name; subst++) {
427                                         if (strncasecmp(&head[1], subst->name, strlen(subst->name)) == 0) {
428                                                 type = subst->type;
429                                                 tail = head + strlen(subst->name)+1;
430                                                 dbg("will substitute format name '%s'", subst->name);
431                                                 goto found;
432                                         }
433                                 }
434                         }
435                         else if (head[0] == '%') {
436                                 /* substitute format char */
437                                 if (head[1] == '\0')
438                                         break;
439                                 if (head[1] == '%') {
440                                         strlcpy(temp, head+2, sizeof(temp));
441                                         strlcpy(head+1, temp, maxsize);
442                                         head++;
443                                         continue;
444                                 }
445                                 head[0] = '\0';
446                                 tail = head+1;
447                                 len = get_format_len(&tail);
448                                 for (subst = map; subst->name; subst++) {
449                                         if (tail[0] == subst->fmt) {
450                                                 type = subst->type;
451                                                 tail++;
452                                                 dbg("will substitute format char '%c'", subst->fmt);
453                                                 goto found;
454                                         }
455                                 }
456                         }
457                         head++;
458                 }
459                 break;
460 found:
461                 attr = get_format_attribute(&tail);
462                 strlcpy(temp, tail, sizeof(temp));
463                 dbg("format=%i, string='%s', tail='%s', class_dev=%p, sysfs_dev=%p",
464                     type ,string, tail, class_dev, sysfs_device);
465
466                 switch (type) {
467                 case SUBST_DEVPATH:
468                         strlcat(string, udev->devpath, maxsize);
469                         dbg("substitute devpath '%s'", udev->devpath);
470                         break;
471                 case SUBST_ID:
472                         strlcat(string, udev->bus_id, maxsize);
473                         dbg("substitute bus_id '%s'", udev->bus_id);
474                         break;
475                 case SUBST_KERNEL_NAME:
476                         strlcat(string, udev->kernel_name, maxsize);
477                         dbg("substitute kernel name '%s'", udev->kernel_name);
478                         break;
479                 case SUBST_KERNEL_NUMBER:
480                         strlcat(string, udev->kernel_number, maxsize);
481                         dbg("substitute kernel number '%s'", udev->kernel_number);
482                         break;
483                 case SUBST_MAJOR:
484                         sprintf(temp2, "%d", major(udev->devt));
485                         strlcat(string, temp2, maxsize);
486                         dbg("substitute major number '%s'", temp2);
487                         break;
488                 case SUBST_MINOR:
489                         sprintf(temp2, "%d", minor(udev->devt));
490                         strlcat(string, temp2, maxsize);
491                         dbg("substitute minor number '%s'", temp2);
492                         break;
493                 case SUBST_RESULT:
494                         if (udev->program_result[0] == '\0')
495                                 break;
496                         /* get part part of the result string */
497                         i = 0;
498                         if (attr != NULL)
499                                 i = strtoul(attr, &rest, 10);
500                         if (i > 0) {
501                                 dbg("request part #%d of result string", i);
502                                 cpos = udev->program_result;
503                                 while (--i) {
504                                         while (cpos[0] != '\0' && !isspace(cpos[0]))
505                                                 cpos++;
506                                         while (isspace(cpos[0]))
507                                                 cpos++;
508                                 }
509                                 if (i > 0) {
510                                         err("requested part of result string not found");
511                                         break;
512                                 }
513                                 strlcpy(temp2, cpos, sizeof(temp2));
514                                 /* %{2+}c copies the whole string from the second part on */
515                                 if (rest[0] != '+') {
516                                         cpos = strchr(temp2, ' ');
517                                         if (cpos)
518                                                 cpos[0] = '\0';
519                                 }
520                                 strlcat(string, temp2, maxsize);
521                                 dbg("substitute part of result string '%s'", temp2);
522                         } else {
523                                 strlcat(string, udev->program_result, maxsize);
524                                 dbg("substitute result string '%s'", udev->program_result);
525                         }
526                         break;
527                 case SUBST_SYSFS:
528                         if (attr == NULL) {
529                                 dbg("missing attribute");
530                                 break;
531                         }
532                         if (find_sysfs_attribute(class_dev, sysfs_device, attr, temp2, sizeof(temp2)) != 0) {
533                                 struct sysfs_device *parent_device;
534
535                                 dbg("sysfs attribute '%s' not found, walk up the physical devices", attr);
536                                 parent_device = sysfs_get_device_parent(sysfs_device);
537                                 while (parent_device) {
538                                         dbg("looking at '%s'", parent_device->path);
539                                         if (find_sysfs_attribute(NULL, parent_device, attr, temp2, sizeof(temp2)) == 0)
540                                                 break;
541                                         parent_device = sysfs_get_device_parent(parent_device);
542                                 }
543                                 if (!parent_device)
544                                         break;
545                         }
546                         /* strip trailing whitespace of sysfs value */
547                         i = strlen(temp2);
548                         while (i > 0 && isspace(temp2[i-1]))
549                                 temp2[--i] = '\0';
550                         replace_untrusted_chars(temp2);
551                         strlcat(string, temp2, maxsize);
552                         dbg("substitute sysfs value '%s'", temp2);
553                         break;
554                 case SUBST_ENUM:
555                         next_free_number = find_free_number(udev, string);
556                         if (next_free_number > 0) {
557                                 sprintf(temp2, "%d", next_free_number);
558                                 strlcat(string, temp2, maxsize);
559                         }
560                         break;
561                 case SUBST_PARENT:
562                         if (!class_dev)
563                                 break;
564                         class_dev_parent = sysfs_get_classdev_parent(class_dev);
565                         if (class_dev_parent != NULL) {
566                                 struct udevice udev_parent;
567
568                                 dbg("found parent '%s', get the node name", class_dev_parent->path);
569                                 udev_init_device(&udev_parent, NULL, NULL, NULL);
570                                 /* lookup the name in the udev_db with the DEVPATH of the parent */
571                                 if (udev_db_get_device(&udev_parent, &class_dev_parent->path[strlen(sysfs_path)]) == 0) {
572                                         strlcat(string, udev_parent.name, maxsize);
573                                         dbg("substitute parent node name'%s'", udev_parent.name);
574                                 } else
575                                         dbg("parent not found in database");
576                                 udev_cleanup_device(&udev_parent);
577                         }
578                         break;
579                 case SUBST_TEMP_NODE:
580                         if (udev->tmp_node[0] == '\0') {
581                                 dbg("create temporary device node for callout");
582                                 snprintf(udev->tmp_node, sizeof(udev->tmp_node), "%s/.tmp-%u-%u",
583                                          udev_root, major(udev->devt), minor(udev->devt));
584                                 udev->tmp_node[sizeof(udev->tmp_node)-1] = '\0';
585                                 udev_make_node(udev, udev->tmp_node, udev->devt, 0600, 0, 0);
586                         }
587                         strlcat(string, udev->tmp_node, maxsize);
588                         dbg("substitute temporary device node name '%s'", udev->tmp_node);
589                         break;
590                 case SUBST_ROOT:
591                         strlcat(string, udev_root, maxsize);
592                         dbg("substitute udev_root '%s'", udev_root);
593                         break;
594                 case SUBST_MODALIAS:
595                         if (find_sysfs_attribute(NULL, sysfs_device, "modalias", temp2, sizeof(temp2)) != 0)
596                                 break;
597                         strlcat(string, temp2, maxsize);
598                         dbg("substitute MODALIAS '%s'", temp2);
599                         break;
600                 case SUBST_ENV:
601                         if (attr == NULL) {
602                                 dbg("missing attribute");
603                                 break;
604                         }
605                         pos = getenv(attr);
606                         if (pos == NULL)
607                                 break;
608                         strlcat(string, pos, maxsize);
609                         dbg("substitute env '%s=%s'", attr, pos);
610                         break;
611                 default:
612                         err("unknown substitution type=%i", type);
613                         break;
614                 }
615                 /* possibly truncate to format-char specified length */
616                 if (len != -1) {
617                         head[len] = '\0';
618                         dbg("truncate to %i chars, subtitution string becomes '%s'", len, head);
619                 }
620                 strlcat(string, temp, maxsize);
621         }
622 }
623
624 static char *key_val(struct udev_rule *rule, struct key *key)
625 {
626         return rule->buf + key->val_off;
627 }
628
629 static char *key_pair_name(struct udev_rule *rule, struct key_pair *pair)
630 {
631         return rule->buf + pair->key_name_off;
632 }
633
634 static int match_key(const char *key_name, struct udev_rule *rule, struct key *key, const char *val)
635 {
636         int match;
637         char *key_value;
638
639         if (key->operation == KEY_OP_UNSET)
640                 return 0;
641
642         key_value = rule->buf + key->val_off;
643
644         dbg("check for %s '%s' <-> '%s'", key_name, key_value, val);
645         match = (strcmp_pattern(key_value, val) == 0);
646         if (match && (key->operation != KEY_OP_NOMATCH)) {
647                 dbg("%s is matching (matching value)", key_name);
648                 return 0;
649         }
650         if (!match && (key->operation == KEY_OP_NOMATCH)) {
651                 dbg("%s is matching, (non matching value)", key_name);
652                 return 0;
653         }
654
655         dbg("%s is not matching", key_name);
656         return -1;
657 }
658
659 static int match_rule(struct udevice *udev, struct udev_rule *rule,
660                       struct sysfs_class_device *class_dev, struct sysfs_device *sysfs_device)
661 {
662         struct sysfs_device *parent_device = sysfs_device;
663
664         if (match_key("ACTION", rule, &rule->action, udev->action))
665                 goto exit;
666
667         if (match_key("KERNEL", rule, &rule->kernel_name, udev->kernel_name))
668                 goto exit;
669
670         if (match_key("SUBSYSTEM", rule, &rule->subsystem, udev->subsystem))
671                 goto exit;
672
673         if (match_key("DEVPATH", rule, &rule->devpath, udev->devpath))
674                 goto exit;
675
676         if (rule->modalias.operation != KEY_OP_UNSET) {
677                 char value[NAME_SIZE];
678
679                 if (find_sysfs_attribute(NULL, sysfs_device, "modalias", value, sizeof(value)) != 0) {
680                         dbg("MODALIAS value not found");
681                         goto exit;
682                 }
683                 if (match_key("MODALIAS", rule, &rule->modalias, value))
684                         goto exit;
685         }
686
687         if (rule->env.count) {
688                 int i;
689
690                 dbg("check %i ENV keys", rule->env.count);
691                 for (i = 0; i < rule->env.count; i++) {
692                         struct key_pair *pair = &rule->env.keys[i];
693                         const char *key_name = key_pair_name(rule, pair);
694                         const char *value = getenv(key_name);
695
696                         if (!value) {
697                                 dbg("ENV{'%s'} is not found", key_name);
698                                 goto exit;
699                         }
700                         if (match_key("ENV", rule, &pair->key, value))
701                                 goto exit;
702                 }
703                 dbg("all %i ENV keys matched", rule->env.count);
704         }
705
706         if (rule->wait_for_sysfs.operation != KEY_OP_UNSET) {
707                 int match;
708
709                 match = (wait_for_sysfs(udev, key_val(rule, &rule->wait_for_sysfs), 3) == 0);
710                 if (match && (rule->wait_for_sysfs.operation != KEY_OP_NOMATCH)) {
711                         dbg("WAIT_FOR_SYSFS is matching (matching value)");
712                         return 0;
713                 }
714                 if (!match && (rule->wait_for_sysfs.operation == KEY_OP_NOMATCH)) {
715                         dbg("WAIT_FOR_SYSFS is matching, (non matching value)");
716                         return 0;
717                 }
718                 dbg("WAIT_FOR_SYSFS is not matching");
719                 return -1;
720         }
721
722         /* walk up the chain of physical devices and find a match */
723         while (1) {
724                 /* check for matching driver */
725                 if (rule->driver.operation != KEY_OP_UNSET) {
726                         if (parent_device == NULL) {
727                                 dbg("device has no sysfs_device");
728                                 goto exit;
729                         }
730                         if (match_key("DRIVER", rule, &rule->driver, parent_device->driver_name))
731                                 goto try_parent;
732                 }
733
734                 /* check for matching bus value */
735                 if (rule->bus.operation != KEY_OP_UNSET) {
736                         if (parent_device == NULL) {
737                                 dbg("device has no sysfs_device");
738                                 goto exit;
739                         }
740                         if (match_key("BUS", rule, &rule->bus, parent_device->bus))
741                                 goto try_parent;
742                 }
743
744                 /* check for matching bus id */
745                 if (rule->id.operation != KEY_OP_UNSET) {
746                         if (parent_device == NULL) {
747                                 dbg("device has no sysfs_device");
748                                 goto exit;
749                         }
750                         if (match_key("ID", rule, &rule->id, parent_device->bus_id))
751                                 goto try_parent;
752                 }
753
754                 /* check for matching sysfs pairs */
755                 if (rule->sysfs.count) {
756                         int i;
757
758                         dbg("check %i SYSFS keys", rule->sysfs.count);
759                         for (i = 0; i < rule->sysfs.count; i++) {
760                                 struct key_pair *pair = &rule->sysfs.keys[i];
761                                 const char *key_name = key_pair_name(rule, pair);
762                                 const char *key_value = key_val(rule, &pair->key);
763                                 char value[VALUE_SIZE];
764                                 size_t len;
765
766                                 if (find_sysfs_attribute(class_dev, parent_device, key_name, value, sizeof(value)) != 0)
767                                         goto try_parent;
768
769                                 /* strip trailing whitespace of value, if not asked to match for it */
770                                 len = strlen(key_value);
771                                 if (len && !isspace(key_value[len-1])) {
772                                         len = strlen(value);
773                                         while (len > 0 && isspace(value[len-1]))
774                                                 value[--len] = '\0';
775                                         dbg("removed %zi trailing whitespace chars from '%s'", strlen(value)-len, value);
776                                 }
777
778                                 if (match_key("SYSFS", rule, &pair->key, value))
779                                         goto try_parent;
780                         }
781                         dbg("all %i SYSFS keys matched", rule->sysfs.count);
782                 }
783
784                 /* found matching physical device  */
785                 break;
786 try_parent:
787                 dbg("try parent sysfs device");
788                 parent_device = sysfs_get_device_parent(parent_device);
789                 if (parent_device == NULL)
790                         goto exit;
791                 dbg("look at sysfs_device->path='%s'", parent_device->path);
792                 dbg("look at sysfs_device->bus_id='%s'", parent_device->bus_id);
793         }
794
795         /* import variables from file into environment */
796         if (rule->import.operation != KEY_OP_UNSET) {
797                 char import[PATH_SIZE];
798                 int rc = -1;
799
800                 strlcpy(import, key_val(rule, &rule->import), sizeof(import));
801                 apply_format(udev, import, sizeof(import), class_dev, sysfs_device);
802                 dbg("check for IMPORT import='%s'", import);
803                 if (rule->import_exec) {
804                         dbg("run executable file import='%s'", import);
805                         rc = import_program_into_env(udev, import);
806                 } else {
807                         dbg("import file import='%s'", import);
808                         rc = import_file_into_env(udev, import);
809                 }
810                 if (rc) {
811                         dbg("IMPORT failed");
812                         if (rule->import.operation != KEY_OP_NOMATCH)
813                                 goto exit;
814                 } else
815                         dbg("IMPORT '%s' imported", key_val(rule, &rule->import));
816                 dbg("IMPORT key is true");
817         }
818
819         /* execute external program */
820         if (rule->program.operation != KEY_OP_UNSET) {
821                 char program[PATH_SIZE];
822                 char result[PATH_SIZE];
823
824                 strlcpy(program, key_val(rule, &rule->program), sizeof(program));
825                 apply_format(udev, program, sizeof(program), class_dev, sysfs_device);
826                 dbg("check for PROGRAM program='%s", program);
827                 if (execute_program(program, udev->subsystem, result, sizeof(result), NULL) != 0) {
828                         dbg("PROGRAM is not matching");
829                         if (rule->program.operation != KEY_OP_NOMATCH)
830                                 goto exit;
831                 } else {
832                         dbg("PROGRAM matches");
833                         remove_trailing_char(result, '\n');
834                         replace_untrusted_chars(result);
835                         dbg("result is '%s'", result);
836                         strlcpy(udev->program_result, result, sizeof(udev->program_result));
837                         dbg("PROGRAM returned successful");
838                         if (rule->program.operation == KEY_OP_NOMATCH)
839                                 goto exit;
840                 }
841                 dbg("PROGRAM key is true");
842         }
843
844         /* check for matching result of external program */
845         if (match_key("RESULT", rule, &rule->result, udev->program_result))
846                 goto exit;
847
848         /* rule matches */
849         return 0;
850
851 exit:
852         return -1;
853 }
854
855 int udev_rules_get_name(struct udev_rules *rules, struct udevice *udev, struct sysfs_class_device *class_dev)
856 {
857         struct sysfs_class_device *class_dev_parent;
858         struct sysfs_device *sysfs_device = NULL;
859         struct udev_rule *rule;
860         int name_set = 0;
861
862         dbg("class_dev->name='%s'", class_dev->name);
863
864         /* Figure out where the "device"-symlink is at.  For char devices this will
865          * always be in the class_dev->path.  On block devices, only the main block
866          * device will have the device symlink in it's path. All partition devices
867          * need to look at the symlink in its parent directory.
868          */
869         class_dev_parent = sysfs_get_classdev_parent(class_dev);
870         if (class_dev_parent != NULL) {
871                 dbg("given class device has a parent, use this instead");
872                 sysfs_device = sysfs_get_classdev_device(class_dev_parent);
873         } else {
874                 sysfs_device = sysfs_get_classdev_device(class_dev);
875         }
876
877         if (sysfs_device) {
878                 dbg("found devices device: path='%s', bus_id='%s', bus='%s'",
879                     sysfs_device->path, sysfs_device->bus_id, sysfs_device->bus);
880                 strlcpy(udev->bus_id, sysfs_device->bus_id, sizeof(udev->bus_id));
881         }
882
883         dbg("udev->kernel_name='%s'", udev->kernel_name);
884
885         /* look for a matching rule to apply */
886         udev_rules_iter_init(rules);
887         while (1) {
888                 rule = udev_rules_iter_next(rules);
889                 if (rule == NULL)
890                         break;
891
892                 if (name_set && rule->name.operation != KEY_OP_UNSET) {
893                         dbg("node name already set, rule ignored");
894                         continue;
895                 }
896
897                 dbg("process rule");
898                 if (match_rule(udev, rule, class_dev, sysfs_device) == 0) {
899                         /* apply options */
900                         if (rule->ignore_device) {
901                                 info("rule applied, '%s' is ignored", udev->kernel_name);
902                                 udev->ignore_device = 1;
903                                 return 0;
904                         }
905                         if (rule->ignore_remove) {
906                                 udev->ignore_remove = 1;
907                                 dbg("remove event should be ignored");
908                         }
909                         /* apply all_partitions option only at a main block device */
910                         if (rule->partitions && udev->type == DEV_BLOCK && udev->kernel_number[0] == '\0') {
911                                 udev->partitions = rule->partitions;
912                                 dbg("creation of partition nodes requested");
913                         }
914
915                         /* apply permissions */
916                         if (!udev->mode_final && rule->mode != 0000) {
917                                 if (rule->mode_operation == KEY_OP_ASSIGN_FINAL)
918                                         udev->mode_final = 1;
919                                 udev->mode = rule->mode;
920                                 dbg("applied mode=%#o to '%s'", rule->mode, udev->kernel_name);
921                         }
922                         if (!udev->owner_final && rule->owner.operation != KEY_OP_UNSET) {
923                                 if (rule->owner.operation == KEY_OP_ASSIGN_FINAL)
924                                         udev->owner_final = 1;
925                                 strlcpy(udev->owner, key_val(rule, &rule->owner), sizeof(udev->owner));
926                                 apply_format(udev, udev->owner, sizeof(udev->owner), class_dev, sysfs_device);
927                                 dbg("applied owner='%s' to '%s'", udev->owner, udev->kernel_name);
928                         }
929                         if (!udev->group_final && rule->group.operation != KEY_OP_UNSET) {
930                                 if (rule->group.operation == KEY_OP_ASSIGN_FINAL)
931                                         udev->group_final = 1;
932                                 strlcpy(udev->group, key_val(rule, &rule->group), sizeof(udev->group));
933                                 apply_format(udev, key_val(rule, &rule->group), sizeof(udev->group), class_dev, sysfs_device);
934                                 dbg("applied group='%s' to '%s'", udev->group, udev->kernel_name);
935                         }
936
937                         /* collect symlinks */
938                         if (!udev->symlink_final && rule->symlink.operation != KEY_OP_UNSET) {
939                                 char temp[PATH_SIZE];
940                                 char *pos, *next;
941
942                                 if (rule->symlink.operation == KEY_OP_ASSIGN_FINAL)
943                                         udev->symlink_final = 1;
944                                 if (rule->symlink.operation == KEY_OP_ASSIGN || rule->symlink.operation == KEY_OP_ASSIGN_FINAL) {
945                                         struct name_entry *name_loop;
946                                         struct name_entry *temp_loop;
947
948                                         info("reset symlink list");
949                                         list_for_each_entry_safe(name_loop, temp_loop, &udev->symlink_list, node) {
950                                                 list_del(&name_loop->node);
951                                                 free(name_loop);
952                                         }
953                                 }
954                                 strlcpy(temp, key_val(rule, &rule->symlink), sizeof(temp));
955                                 apply_format(udev, temp, sizeof(temp), class_dev, sysfs_device);
956                                 info("rule applied, added symlink '%s'", temp);
957
958                                 /* add multiple symlinks separated by spaces */
959                                 pos = temp;
960                                 next = strchr(temp, ' ');
961                                 while (next) {
962                                         next[0] = '\0';
963                                         info("add symlink '%s'", pos);
964                                         name_list_add(&udev->symlink_list, pos, 0);
965                                         pos = &next[1];
966                                         next = strchr(pos, ' ');
967                                 }
968                                 info("add symlink '%s'", pos);
969                                 name_list_add(&udev->symlink_list, pos, 0);
970                         }
971
972                         /* set name, later rules with name set will be ignored */
973                         if (rule->name.operation != KEY_OP_UNSET) {
974                                 name_set = 1;
975                                 strlcpy(udev->name, key_val(rule, &rule->name), sizeof(udev->name));
976                                 apply_format(udev, udev->name, sizeof(udev->name), class_dev, sysfs_device);
977
978                                 info("rule applied, '%s' becomes '%s'", udev->kernel_name, udev->name);
979                                 if (udev->type != DEV_NET)
980                                         dbg("name, '%s' is going to have owner='%s', group='%s', mode=%#o partitions=%i",
981                                             udev->name, udev->owner, udev->group, udev->mode, udev->partitions);
982                         }
983
984                         if (!udev->run_final && rule->run.operation != KEY_OP_UNSET) {
985                                 char program[PATH_SIZE];
986
987                                 if (rule->run.operation == KEY_OP_ASSIGN_FINAL)
988                                         udev->run_final = 1;
989                                 if (rule->run.operation == KEY_OP_ASSIGN || rule->run.operation == KEY_OP_ASSIGN_FINAL) {
990                                         struct name_entry *name_loop;
991                                         struct name_entry *temp_loop;
992
993                                         info("reset run list");
994                                         list_for_each_entry_safe(name_loop, temp_loop, &udev->run_list, node) {
995                                                 list_del(&name_loop->node);
996                                                 free(name_loop);
997                                         }
998                                 }
999                                 strlcpy(program, key_val(rule, &rule->run), sizeof(program));
1000                                 apply_format(udev, program, sizeof(program), class_dev, sysfs_device);
1001                                 dbg("add run '%s'", program);
1002                                 name_list_add(&udev->run_list, program, 0);
1003                         }
1004
1005                         if (rule->last_rule) {
1006                                 dbg("last rule to be applied");
1007                                 break;
1008                         }
1009                 }
1010         }
1011
1012         if (!name_set) {
1013                 strlcpy(udev->name, udev->kernel_name, sizeof(udev->name));
1014                 info("no rule found, will use kernel name '%s'", udev->name);
1015         }
1016
1017         if (udev->tmp_node[0] != '\0') {
1018                 dbg("removing temporary device node");
1019                 unlink_secure(udev->tmp_node);
1020                 udev->tmp_node[0] = '\0';
1021         }
1022
1023         return 0;
1024 }
1025
1026 int udev_rules_get_run(struct udev_rules *rules, struct udevice *udev, struct sysfs_device *sysfs_device)
1027 {
1028         struct udev_rule *rule;
1029
1030         /* look for a matching rule to apply */
1031         udev_rules_iter_init(rules);
1032         while (1) {
1033                 rule = udev_rules_iter_next(rules);
1034                 if (rule == NULL)
1035                         break;
1036
1037                 dbg("process rule");
1038                 if (rule->name.operation != KEY_OP_UNSET || rule->symlink.operation != KEY_OP_UNSET ||
1039                     rule->mode_operation != KEY_OP_UNSET || rule->owner.operation != KEY_OP_UNSET || rule->group.operation != KEY_OP_UNSET) {
1040                         dbg("skip rule that names a device");
1041                         continue;
1042                 }
1043
1044                 if (match_rule(udev, rule, NULL, sysfs_device) == 0) {
1045                         if (rule->ignore_device) {
1046                                 info("rule applied, '%s' is ignored", udev->kernel_name);
1047                                 udev->ignore_device = 1;
1048                                 return 0;
1049                         }
1050
1051                         if (!udev->run_final && rule->run.operation != KEY_OP_UNSET) {
1052                                 char program[PATH_SIZE];
1053
1054                                 if (rule->run.operation == KEY_OP_ASSIGN || rule->run.operation == KEY_OP_ASSIGN_FINAL) {
1055                                         struct name_entry *name_loop;
1056                                         struct name_entry *temp_loop;
1057
1058                                         info("reset run list");
1059                                         list_for_each_entry_safe(name_loop, temp_loop, &udev->run_list, node) {
1060                                                 list_del(&name_loop->node);
1061                                                 free(name_loop);
1062                                         }
1063                                 }
1064                                 strlcpy(program, key_val(rule, &rule->run), sizeof(program));
1065                                 apply_format(udev, program, sizeof(program), NULL, sysfs_device);
1066                                 dbg("add run '%s'", program);
1067                                 name_list_add(&udev->run_list, program, 0);
1068                                 if (rule->run.operation == KEY_OP_ASSIGN_FINAL)
1069                                         break;
1070                         }
1071
1072                         if (rule->last_rule) {
1073                                 dbg("last rule to be applied");
1074                                 break;
1075                         }
1076                 }
1077         }
1078
1079         return 0;
1080 }