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