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