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