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