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