chiark / gitweb /
add debug output to sysfs operations
[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("will wait %i sec for '%s'", timeout, filename);
352
353         while (--loop) {
354                 if (stat(filename, &stats) == 0) {
355                         info("file '%s' appeared after %i loops", filename, (timeout * WAIT_LOOP_PER_SECOND) - loop-1);
356                         return 0;
357                 }
358                 info("wait for '%s' for %i mseconds", filename, 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 void udev_rules_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_ID,
380                 SUBST_MAJOR,
381                 SUBST_MINOR,
382                 SUBST_RESULT,
383                 SUBST_SYSFS,
384                 SUBST_ENUM,
385                 SUBST_PARENT,
386                 SUBST_TEMP_NODE,
387                 SUBST_ROOT,
388                 SUBST_MODALIAS,
389                 SUBST_ENV,
390         };
391         static const struct subst_map {
392                 char *name;
393                 char fmt;
394                 enum subst_type type;
395         } map[] = {
396                 { .name = "devpath",            .fmt = 'p',     .type = SUBST_DEVPATH },
397                 { .name = "number",             .fmt = 'n',     .type = SUBST_KERNEL_NUMBER },
398                 { .name = "kernel",             .fmt = 'k',     .type = SUBST_KERNEL_NAME },
399                 { .name = "id",                 .fmt = 'b',     .type = SUBST_ID },
400                 { .name = "major",              .fmt = 'M',     .type = SUBST_MAJOR },
401                 { .name = "minor",              .fmt = 'm',     .type = SUBST_MINOR },
402                 { .name = "result",             .fmt = 'c',     .type = SUBST_RESULT },
403                 { .name = "sysfs",              .fmt = 's',     .type = SUBST_SYSFS },
404                 { .name = "enum",               .fmt = 'e',     .type = SUBST_ENUM },
405                 { .name = "parent",             .fmt = 'P',     .type = SUBST_PARENT },
406                 { .name = "tempnode",           .fmt = 'N',     .type = SUBST_TEMP_NODE },
407                 { .name = "root",               .fmt = 'r',     .type = SUBST_ROOT },
408                 { .name = "modalias",           .fmt = 'A',     .type = SUBST_MODALIAS },
409                 { .name = "env",                .fmt = 'E',     .type = SUBST_ENV },
410                 { NULL, '\0', 0 }
411         };
412         enum subst_type type;
413         const struct subst_map *subst;
414
415         head = string;
416         while (1) {
417                 len = -1;
418                 while (head[0] != '\0') {
419                         if (head[0] == '$') {
420                                 /* substitute named variable */
421                                 if (head[1] == '\0')
422                                         break;
423                                 if (head[1] == '$') {
424                                         strlcpy(temp, head+2, sizeof(temp));
425                                         strlcpy(head+1, temp, maxsize);
426                                         head++;
427                                         continue;
428                                 }
429                                 head[0] = '\0';
430                                 for (subst = map; subst->name; subst++) {
431                                         if (strncasecmp(&head[1], subst->name, strlen(subst->name)) == 0) {
432                                                 type = subst->type;
433                                                 tail = head + strlen(subst->name)+1;
434                                                 dbg("will substitute format name '%s'", subst->name);
435                                                 goto found;
436                                         }
437                                 }
438                         }
439                         else if (head[0] == '%') {
440                                 /* substitute format char */
441                                 if (head[1] == '\0')
442                                         break;
443                                 if (head[1] == '%') {
444                                         strlcpy(temp, head+2, sizeof(temp));
445                                         strlcpy(head+1, temp, maxsize);
446                                         head++;
447                                         continue;
448                                 }
449                                 head[0] = '\0';
450                                 tail = head+1;
451                                 len = get_format_len(&tail);
452                                 for (subst = map; subst->name; subst++) {
453                                         if (tail[0] == subst->fmt) {
454                                                 type = subst->type;
455                                                 tail++;
456                                                 dbg("will substitute format char '%c'", subst->fmt);
457                                                 goto found;
458                                         }
459                                 }
460                         }
461                         head++;
462                 }
463                 break;
464 found:
465                 attr = get_format_attribute(&tail);
466                 strlcpy(temp, tail, sizeof(temp));
467                 dbg("format=%i, string='%s', tail='%s'", type ,string, tail);
468
469                 switch (type) {
470                 case SUBST_DEVPATH:
471                         strlcat(string, udev->dev->devpath, maxsize);
472                         dbg("substitute devpath '%s'", udev->dev->devpath);
473                         break;
474                 case SUBST_KERNEL_NAME:
475                         strlcat(string, udev->dev->kernel_name, maxsize);
476                         dbg("substitute kernel name '%s'", udev->dev->kernel_name);
477                         break;
478                 case SUBST_KERNEL_NUMBER:
479                         strlcat(string, udev->dev->kernel_number, maxsize);
480                         dbg("substitute kernel number '%s'", udev->dev->kernel_number);
481                         break;
482                 case SUBST_ID:
483                         if (udev->dev_parent != NULL) {
484                                 strlcat(string, udev->dev_parent->kernel_name, maxsize);
485                                 dbg("substitute id '%s'", udev->dev_parent->kernel_name);
486                         }
487                         break;
488                 case SUBST_MAJOR:
489                         sprintf(temp2, "%d", major(udev->devt));
490                         strlcat(string, temp2, maxsize);
491                         dbg("substitute major number '%s'", temp2);
492                         break;
493                 case SUBST_MINOR:
494                         sprintf(temp2, "%d", minor(udev->devt));
495                         strlcat(string, temp2, maxsize);
496                         dbg("substitute minor number '%s'", temp2);
497                         break;
498                 case SUBST_RESULT:
499                         if (udev->program_result[0] == '\0')
500                                 break;
501                         /* get part part of the result string */
502                         i = 0;
503                         if (attr != NULL)
504                                 i = strtoul(attr, &rest, 10);
505                         if (i > 0) {
506                                 dbg("request part #%d of result string", i);
507                                 cpos = udev->program_result;
508                                 while (--i) {
509                                         while (cpos[0] != '\0' && !isspace(cpos[0]))
510                                                 cpos++;
511                                         while (isspace(cpos[0]))
512                                                 cpos++;
513                                 }
514                                 if (i > 0) {
515                                         err("requested part of result string not found");
516                                         break;
517                                 }
518                                 strlcpy(temp2, cpos, sizeof(temp2));
519                                 /* %{2+}c copies the whole string from the second part on */
520                                 if (rest[0] != '+') {
521                                         cpos = strchr(temp2, ' ');
522                                         if (cpos)
523                                                 cpos[0] = '\0';
524                                 }
525                                 strlcat(string, temp2, maxsize);
526                                 dbg("substitute part of result string '%s'", temp2);
527                         } else {
528                                 strlcat(string, udev->program_result, maxsize);
529                                 dbg("substitute result string '%s'", udev->program_result);
530                         }
531                         break;
532                 case SUBST_SYSFS:
533                         if (attr == NULL) {
534                                 dbg("missing attribute");
535                                 break;
536                         } else {
537                                 struct sysfs_device *dev_parent;
538                                 const char *value;
539
540                                 dev_parent = udev->dev;
541                                 do {
542                                         dbg("looking at '%s'", dev_parent->devpath);
543                                         value = sysfs_attr_get_value(dev_parent->devpath, attr);
544                                         if (value != NULL) {
545                                                 strlcpy(temp2, value, sizeof(temp2));
546                                                 break;
547                                         }
548                                         dev_parent = sysfs_device_get_parent(dev_parent);
549                                 } while (dev_parent != NULL);
550
551                                 /* strip trailing whitespace of sysfs value */
552                                 i = strlen(temp2);
553                                 while (i > 0 && isspace(temp2[i-1]))
554                                         temp2[--i] = '\0';
555                                 count = replace_untrusted_chars(temp2);
556                                 if (count)
557                                         info("%i untrusted character(s) replaced" , count);
558                                 strlcat(string, temp2, maxsize);
559                                 dbg("substitute sysfs value '%s'", temp2);
560                         }
561                         break;
562                 case SUBST_ENUM:
563                         next_free_number = find_free_number(string, udev->dev->devpath);
564                         if (next_free_number > 0) {
565                                 sprintf(temp2, "%d", next_free_number);
566                                 strlcat(string, temp2, maxsize);
567                         }
568                         break;
569                 case SUBST_PARENT:
570                         {
571                                 struct sysfs_device *dev_parent;
572
573                                 dev_parent = sysfs_device_get_parent(udev->dev);
574                                 if (dev_parent != NULL) {
575                                         struct udevice *udev_parent;
576
577                                         dbg("found parent '%s', get the node name", dev_parent->devpath);
578                                         udev_parent = udev_device_init();
579                                         if (udev_parent != NULL) {
580                                                 /* lookup the name in the udev_db with the DEVPATH of the parent */
581                                                 if (udev_db_get_device(udev_parent, dev_parent->devpath) == 0) {
582                                                         strlcat(string, udev_parent->name, maxsize);
583                                                         dbg("substitute parent node name'%s'", udev_parent->name);
584                                                 } else
585                                                         dbg("parent not found in database");
586                                                 udev_device_cleanup(udev_parent);
587                                         }
588                                 }
589                         }
590                         break;
591                 case SUBST_TEMP_NODE:
592                         if (udev->tmp_node[0] == '\0') {
593                                 dbg("create temporary device node for callout");
594                                 snprintf(udev->tmp_node, sizeof(udev->tmp_node), "%s/.tmp-%u-%u",
595                                          udev_root, major(udev->devt), minor(udev->devt));
596                                 udev->tmp_node[sizeof(udev->tmp_node)-1] = '\0';
597                                 udev_make_node(udev, udev->tmp_node, udev->devt, 0600, 0, 0);
598                         }
599                         strlcat(string, udev->tmp_node, maxsize);
600                         dbg("substitute temporary device node name '%s'", udev->tmp_node);
601                         break;
602                 case SUBST_ROOT:
603                         strlcat(string, udev_root, maxsize);
604                         dbg("substitute udev_root '%s'", udev_root);
605                         break;
606                 case SUBST_MODALIAS:
607                         {
608                                 const char *value;
609
610                                 value = sysfs_attr_get_value(udev->dev->devpath, "modalias");
611                                 if (value != NULL) {
612                                         strlcat(string, value, maxsize);
613                                         dbg("substitute MODALIAS '%s'", temp2);
614                                 }
615                         }
616                         break;
617                 case SUBST_ENV:
618                         if (attr == NULL) {
619                                 dbg("missing attribute");
620                                 break;
621                         }
622                         pos = getenv(attr);
623                         if (pos == NULL) {
624                                 dbg("env '%s' not available", attr);
625                                 break;
626                         }
627                         dbg("substitute env '%s=%s'", attr, pos);
628                         strlcat(string, pos, maxsize);
629                         break;
630                 default:
631                         err("unknown substitution type=%i", type);
632                         break;
633                 }
634                 /* possibly truncate to format-char specified length */
635                 if (len != -1) {
636                         head[len] = '\0';
637                         dbg("truncate to %i chars, subtitution string becomes '%s'", len, head);
638                 }
639                 strlcat(string, temp, maxsize);
640         }
641 }
642
643 static char *key_val(struct udev_rule *rule, struct key *key)
644 {
645         return rule->buf + key->val_off;
646 }
647
648 static char *key_pair_name(struct udev_rule *rule, struct key_pair *pair)
649 {
650         return rule->buf + pair->key_name_off;
651 }
652
653 static int match_key(const char *key_name, struct udev_rule *rule, struct key *key, const char *val)
654 {
655         int match;
656         char value[PATH_SIZE];
657         char *key_value;
658         char *pos;
659
660         if (key->operation == KEY_OP_UNSET)
661                 return 0;
662
663         strlcpy(value, rule->buf + key->val_off, sizeof(value));
664         key_value = value;
665
666         dbg("key %s value='%s'", key_name, key_value);
667         while (key_value) {
668                 pos = strchr(key_value, '|');
669                 if (pos) {
670                         pos[0] = '\0';
671                         pos++;
672                 }
673                 dbg("match %s '%s' <-> '%s'", key_name, key_value, val);
674                 match = (strcmp_pattern(key_value, val) == 0);
675                 if (match && (key->operation != KEY_OP_NOMATCH)) {
676                         dbg("%s is true (matching value)", key_name);
677                         return 0;
678                 }
679                 if (!match && (key->operation == KEY_OP_NOMATCH)) {
680                         dbg("%s is true (non-matching value)", key_name);
681                         return 0;
682                 }
683                 key_value = pos;
684         }
685         dbg("%s is false", key_name);
686         return -1;
687 }
688
689 /* match a single rule against a given device and possibly its parent devices */
690 static int match_rule(struct udevice *udev, struct udev_rule *rule)
691 {
692         int i;
693
694         if (match_key("ACTION", rule, &rule->action, udev->action))
695                 goto nomatch;
696
697         if (match_key("KERNEL", rule, &rule->kernel_name, udev->dev->kernel_name))
698                 goto nomatch;
699
700         if (match_key("SUBSYSTEM", rule, &rule->subsystem, udev->dev->subsystem))
701                 goto nomatch;
702
703         if (match_key("DEVPATH", rule, &rule->devpath, udev->dev->devpath))
704                 goto nomatch;
705
706         if (rule->modalias.operation != KEY_OP_UNSET) {
707                 const char *value;
708
709                 value = sysfs_attr_get_value(udev->dev->devpath, "modalias");
710                 if (value == NULL) {
711                         dbg("MODALIAS value not found");
712                         goto nomatch;
713                 }
714                 if (match_key("MODALIAS", rule, &rule->modalias, value))
715                         goto nomatch;
716         }
717
718         for (i = 0; i < rule->env.count; i++) {
719                 struct key_pair *pair = &rule->env.keys[i];
720
721                 /* we only check for matches, assignments will be handled later */
722                 if (pair->key.operation != KEY_OP_ASSIGN) {
723                         const char *key_name = key_pair_name(rule, pair);
724                         const char *value = getenv(key_name);
725
726                         if (!value) {
727                                 dbg("ENV{'%s'} is not set, treat as empty", key_name);
728                                 value = "";
729                         }
730                         if (match_key("ENV", rule, &pair->key, value))
731                                 goto nomatch;
732                 }
733         }
734
735         if (rule->wait_for_sysfs.operation != KEY_OP_UNSET) {
736                 int match;
737
738                 match = (wait_for_sysfs(udev, key_val(rule, &rule->wait_for_sysfs), 3) == 0);
739                 if (match && (rule->wait_for_sysfs.operation != KEY_OP_NOMATCH)) {
740                         dbg("WAIT_FOR_SYSFS is true (matching value)");
741                         return 0;
742                 }
743                 if (!match && (rule->wait_for_sysfs.operation == KEY_OP_NOMATCH)) {
744                         dbg("WAIT_FOR_SYSFS is true, (non matching value)");
745                         return 0;
746                 }
747                 dbg("WAIT_FOR_SYSFS is false");
748                 return -1;
749         }
750
751         /* walk up the chain of parent devices and find a match */
752         udev->dev_parent = udev->dev;
753         while (1) {
754                 /* check for matching driver */
755                 if (rule->driver.operation != KEY_OP_UNSET) {
756                         if (match_key("DRIVER", rule, &rule->driver, udev->dev_parent->driver))
757                                 goto try_parent;
758                 }
759
760                 /* check for matching subsystem/bus value */
761                 if (rule->bus.operation != KEY_OP_UNSET) {
762                         if (match_key("BUS", rule, &rule->bus, udev->dev_parent->subsystem))
763                                 goto try_parent;
764                 }
765
766                 /* check for matching bus id (device name) */
767                 if (rule->id.operation != KEY_OP_UNSET) {
768                         if (match_key("ID", rule, &rule->id, udev->dev_parent->kernel_name))
769                                 goto try_parent;
770                 }
771
772                 /* check for matching sysfs pairs */
773                 if (rule->sysfs.count) {
774                         dbg("check %i SYSFS keys", rule->sysfs.count);
775                         for (i = 0; i < rule->sysfs.count; i++) {
776                                 struct key_pair *pair = &rule->sysfs.keys[i];
777                                 const char *key_name = key_pair_name(rule, pair);
778                                 const char *key_value = key_val(rule, &pair->key);
779                                 const char *value;
780                                 char val[VALUE_SIZE];
781                                 size_t len;
782
783                                 value = sysfs_attr_get_value(udev->dev_parent->devpath, key_name);
784                                 if (value == NULL)
785                                         value = sysfs_attr_get_value(udev->dev->devpath, key_name);
786                                 if (value == NULL)
787                                         goto try_parent;
788                                 strlcpy(val, value, sizeof(val));
789
790                                 /* strip trailing whitespace of value, if not asked to match for it */
791                                 len = strlen(key_value);
792                                 if (len > 0 && !isspace(key_value[len-1])) {
793                                         len = strlen(val);
794                                         while (len > 0 && isspace(val[len-1]))
795                                                 val[--len] = '\0';
796                                         dbg("removed %zi trailing whitespace chars from '%s'", strlen(val)-len, val);
797                                 }
798
799                                 if (match_key("SYSFS", rule, &pair->key, val))
800                                         goto try_parent;
801                         }
802                         dbg("all %i SYSFS keys matched", rule->sysfs.count);
803                 }
804
805                 /* found matching device  */
806                 break;
807 try_parent:
808                 /* move to parent device */
809                 dbg("try parent sysfs device");
810                 udev->dev_parent = sysfs_device_get_parent(udev->dev_parent);
811                 if (udev->dev_parent == NULL)
812                         goto nomatch;
813                 dbg("looking at dev_parent->devpath='%s'", udev->dev_parent->devpath);
814                 dbg("looking at dev_parent->bus_kernel_name='%s'", udev->dev_parent->kernel_name);
815         }
816
817         /* execute external program */
818         if (rule->program.operation != KEY_OP_UNSET) {
819                 char program[PATH_SIZE];
820                 char result[PATH_SIZE];
821
822                 strlcpy(program, key_val(rule, &rule->program), sizeof(program));
823                 udev_rules_apply_format(udev, program, sizeof(program));
824                 if (run_program(program, udev->dev->subsystem, result, sizeof(result), NULL, (udev_log_priority >= LOG_INFO)) != 0) {
825                         dbg("PROGRAM is false");
826                         udev->program_result[0] = '\0';
827                         if (rule->program.operation != KEY_OP_NOMATCH)
828                                 goto nomatch;
829                 } else {
830                         int count;
831
832                         dbg("PROGRAM matches");
833                         remove_trailing_chars(result, '\n');
834                         count = replace_untrusted_chars(result);
835                         if (count)
836                                 info("%i untrusted character(s) replaced" , count);
837                         dbg("result is '%s'", result);
838                         strlcpy(udev->program_result, result, sizeof(udev->program_result));
839                         dbg("PROGRAM returned successful");
840                         if (rule->program.operation == KEY_OP_NOMATCH)
841                                 goto nomatch;
842                 }
843                 dbg("PROGRAM key is true");
844         }
845
846         /* check for matching result of external program */
847         if (match_key("RESULT", rule, &rule->result, udev->program_result))
848                 goto nomatch;
849
850         /* import variables returned from program or or file into environment */
851         if (rule->import.operation != KEY_OP_UNSET) {
852                 char import[PATH_SIZE];
853                 int rc = -1;
854
855                 strlcpy(import, key_val(rule, &rule->import), sizeof(import));
856                 udev_rules_apply_format(udev, import, sizeof(import));
857                 dbg("check for IMPORT import='%s'", import);
858                 if (rule->import_type == IMPORT_PROGRAM) {
859                         rc = import_program_into_env(udev, import);
860                 } else if (rule->import_type == IMPORT_FILE) {
861                         dbg("import file import='%s'", import);
862                         rc = import_file_into_env(udev, import);
863                 } else if (rule->import_type == IMPORT_PARENT) {
864                         dbg("import parent import='%s'", import);
865                         rc = import_parent_into_env(udev, import);
866                 }
867                 if (rc != 0) {
868                         dbg("IMPORT failed");
869                         if (rule->import.operation != KEY_OP_NOMATCH)
870                                 goto nomatch;
871                 } else
872                         dbg("IMPORT '%s' imported", key_val(rule, &rule->import));
873                 dbg("IMPORT key is true");
874         }
875
876         /* rule matches, if we have ENV assignments export it */
877         for (i = 0; i < rule->env.count; i++) {
878                 struct key_pair *pair = &rule->env.keys[i];
879
880                 if (pair->key.operation == KEY_OP_ASSIGN) {
881                         const char *key_name = key_pair_name(rule, pair);
882                         const char *value = key_val(rule, &pair->key);
883
884                         name_list_key_add(&udev->env_list, key_name, value);
885                         setenv(key_name, value, 1);
886                         dbg("export ENV '%s=%s'", key_name, value);
887                 }
888         }
889
890         return 0;
891
892 nomatch:
893         return -1;
894 }
895
896 int udev_rules_get_name(struct udev_rules *rules, struct udevice *udev)
897 {
898         struct udev_rule *rule;
899         int name_set = 0;
900
901         dbg("udev->dev->devpath='%s'", udev->dev->devpath);
902         dbg("udev->dev->kernel_name='%s'", udev->dev->kernel_name);
903
904         /* look for a matching rule to apply */
905         udev_rules_iter_init(rules);
906         while (1) {
907                 rule = udev_rules_iter_next(rules);
908                 if (rule == NULL)
909                         break;
910
911                 if (name_set && rule->name.operation != KEY_OP_UNSET) {
912                         dbg("node name already set, rule ignored");
913                         continue;
914                 }
915
916                 dbg("process rule");
917                 if (match_rule(udev, rule) == 0) {
918                         /* apply options */
919                         if (rule->ignore_device) {
920                                 info("rule applied, '%s' is ignored", udev->dev->kernel_name);
921                                 udev->ignore_device = 1;
922                                 return 0;
923                         }
924                         if (rule->ignore_remove) {
925                                 udev->ignore_remove = 1;
926                                 dbg("remove event should be ignored");
927                         }
928                         /* apply all_partitions option only at a main block device */
929                         if (rule->partitions &&
930                             strcmp(udev->dev->subsystem, "block") == 0 && udev->dev->kernel_number[0] == '\0') {
931                                 udev->partitions = rule->partitions;
932                                 dbg("creation of partition nodes requested");
933                         }
934
935                         /* apply permissions */
936                         if (!udev->mode_final && rule->mode != 0000) {
937                                 if (rule->mode_operation == KEY_OP_ASSIGN_FINAL)
938                                         udev->mode_final = 1;
939                                 udev->mode = rule->mode;
940                                 dbg("applied mode=%#o to '%s'", rule->mode, udev->dev->kernel_name);
941                         }
942                         if (!udev->owner_final && rule->owner.operation != KEY_OP_UNSET) {
943                                 if (rule->owner.operation == KEY_OP_ASSIGN_FINAL)
944                                         udev->owner_final = 1;
945                                 strlcpy(udev->owner, key_val(rule, &rule->owner), sizeof(udev->owner));
946                                 udev_rules_apply_format(udev, udev->owner, sizeof(udev->owner));
947                                 dbg("applied owner='%s' to '%s'", udev->owner, udev->dev->kernel_name);
948                         }
949                         if (!udev->group_final && rule->group.operation != KEY_OP_UNSET) {
950                                 if (rule->group.operation == KEY_OP_ASSIGN_FINAL)
951                                         udev->group_final = 1;
952                                 strlcpy(udev->group, key_val(rule, &rule->group), sizeof(udev->group));
953                                 udev_rules_apply_format(udev, udev->group, sizeof(udev->group));
954                                 dbg("applied group='%s' to '%s'", udev->group, udev->dev->kernel_name);
955                         }
956
957                         /* collect symlinks */
958                         if (!udev->symlink_final && rule->symlink.operation != KEY_OP_UNSET) {
959                                 char temp[PATH_SIZE];
960                                 char *pos, *next;
961                                 int count;
962
963                                 if (rule->symlink.operation == KEY_OP_ASSIGN_FINAL)
964                                         udev->symlink_final = 1;
965                                 if (rule->symlink.operation == KEY_OP_ASSIGN || rule->symlink.operation == KEY_OP_ASSIGN_FINAL) {
966                                         info("reset symlink list");
967                                         name_list_cleanup(&udev->symlink_list);
968                                 }
969                                 strlcpy(temp, key_val(rule, &rule->symlink), sizeof(temp));
970                                 udev_rules_apply_format(udev, temp, sizeof(temp));
971                                 count = replace_untrusted_chars(temp);
972                                 if (count)
973                                         info("%i untrusted character(s) replaced" , count);
974                                 dbg("rule applied, added symlink(s) '%s'", temp);
975
976                                 /* add multiple symlinks separated by spaces */
977                                 pos = temp;
978                                 while (isspace(pos[0]))
979                                         pos++;
980                                 next = strchr(pos, ' ');
981                                 while (next) {
982                                         next[0] = '\0';
983                                         info("add symlink '%s'", pos);
984                                         name_list_add(&udev->symlink_list, pos, 0);
985                                         while (isspace(next[1]))
986                                                 next++;
987                                         pos = &next[1];
988                                         next = strchr(pos, ' ');
989                                 }
990                                 if (pos[0] != '\0') {
991                                         info("add symlink '%s'", pos);
992                                         name_list_add(&udev->symlink_list, pos, 0);
993                                 }
994                         }
995
996                         /* set name, later rules with name set will be ignored */
997                         if (rule->name.operation != KEY_OP_UNSET) {
998                                 int count;
999
1000                                 name_set = 1;
1001                                 strlcpy(udev->name, key_val(rule, &rule->name), sizeof(udev->name));
1002                                 udev_rules_apply_format(udev, udev->name, sizeof(udev->name));
1003                                 count = replace_untrusted_chars(udev->name);
1004                                 if (count)
1005                                         info("%i untrusted character(s) replaced", count);
1006
1007                                 info("rule applied, '%s' becomes '%s'", udev->dev->kernel_name, udev->name);
1008                                 if (strcmp(udev->dev->subsystem, "net") != 0)
1009                                         dbg("name, '%s' is going to have owner='%s', group='%s', mode=%#o partitions=%i",
1010                                             udev->name, udev->owner, udev->group, udev->mode, udev->partitions);
1011                         }
1012
1013                         if (!udev->run_final && rule->run.operation != KEY_OP_UNSET) {
1014                                 if (rule->run.operation == KEY_OP_ASSIGN_FINAL)
1015                                         udev->run_final = 1;
1016                                 if (rule->run.operation == KEY_OP_ASSIGN || rule->run.operation == KEY_OP_ASSIGN_FINAL) {
1017                                         info("reset run list");
1018                                         name_list_cleanup(&udev->run_list);
1019                                 }
1020                                 dbg("add run '%s'", key_val(rule, &rule->run));
1021                                 name_list_add(&udev->run_list, key_val(rule, &rule->run), 0);
1022                         }
1023
1024                         if (rule->last_rule) {
1025                                 dbg("last rule to be applied");
1026                                 break;
1027                         }
1028
1029                         if (rule->goto_label.operation != KEY_OP_UNSET) {
1030                                 dbg("moving forward to label '%s'", key_val(rule, &rule->goto_label));
1031                                 udev_rules_iter_label(rules, key_val(rule, &rule->goto_label));
1032                         }
1033                 }
1034         }
1035
1036         if (!name_set) {
1037                 strlcpy(udev->name, udev->dev->kernel_name, sizeof(udev->name));
1038                 info("no node name set, will use kernel name '%s'", udev->name);
1039         }
1040
1041         if (udev->tmp_node[0] != '\0') {
1042                 dbg("removing temporary device node");
1043                 unlink_secure(udev->tmp_node);
1044                 udev->tmp_node[0] = '\0';
1045         }
1046
1047         return 0;
1048 }
1049
1050 int udev_rules_get_run(struct udev_rules *rules, struct udevice *udev)
1051 {
1052         struct udev_rule *rule;
1053
1054         dbg("udev->kernel_name='%s'", udev->dev->kernel_name);
1055
1056         /* look for a matching rule to apply */
1057         udev_rules_iter_init(rules);
1058         while (1) {
1059                 rule = udev_rules_iter_next(rules);
1060                 if (rule == NULL)
1061                         break;
1062
1063                 dbg("process rule");
1064                 if (rule->name.operation != KEY_OP_UNSET || rule->symlink.operation != KEY_OP_UNSET ||
1065                     rule->mode_operation != KEY_OP_UNSET || rule->owner.operation != KEY_OP_UNSET || rule->group.operation != KEY_OP_UNSET) {
1066                         dbg("skip rule that names a device");
1067                         continue;
1068                 }
1069
1070                 if (match_rule(udev, rule) == 0) {
1071                         if (rule->ignore_device) {
1072                                 info("rule applied, '%s' is ignored", udev->dev->kernel_name);
1073                                 udev->ignore_device = 1;
1074                                 return 0;
1075                         }
1076
1077                         if (!udev->run_final && rule->run.operation != KEY_OP_UNSET) {
1078                                 if (rule->run.operation == KEY_OP_ASSIGN || rule->run.operation == KEY_OP_ASSIGN_FINAL) {
1079                                         info("reset run list");
1080                                         name_list_cleanup(&udev->run_list);
1081                                 }
1082                                 dbg("add run '%s'", key_val(rule, &rule->run));
1083                                 name_list_add(&udev->run_list, key_val(rule, &rule->run), 0);
1084                                 if (rule->run.operation == KEY_OP_ASSIGN_FINAL)
1085                                         break;
1086                         }
1087
1088                         if (rule->last_rule) {
1089                                 dbg("last rule to be applied");
1090                                 break;
1091                         }
1092
1093                         if (rule->goto_label.operation != KEY_OP_UNSET) {
1094                                 dbg("moving forward to label '%s'", key_val(rule, &rule->goto_label));
1095                                 udev_rules_iter_label(rules, key_val(rule, &rule->goto_label));
1096                         }
1097                 }
1098         }
1099
1100         return 0;
1101 }