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