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