chiark / gitweb /
introduce ATTR{file}="value" to set sysfs attributes
[elogind.git] / udev_rules.c
1 /*
2  * udev_rules.c
3  *
4  * Copyright (C) 2003 Greg Kroah-Hartman <greg@kroah.com>
5  * Copyright (C) 2003-2006 Kay Sievers <kay.sievers@vrfy.org>
6  *
7  *      This program is free software; you can redistribute it and/or modify it
8  *      under the terms of the GNU General Public License as published by the
9  *      Free Software Foundation version 2 of the License.
10  *
11  *      This program is distributed in the hope that it will be useful, but
12  *      WITHOUT ANY WARRANTY; without even the implied warranty of
13  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  *      General Public License for more details.
15  *
16  *      You should have received a copy of the GNU General Public License along
17  *      with this program; if not, write to the Free Software Foundation, Inc.,
18  *      675 Mass Ave, Cambridge, MA 02139, USA.
19  *
20  */
21
22 #include <stddef.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <stdio.h>
26 #include <fcntl.h>
27 #include <ctype.h>
28 #include <unistd.h>
29 #include <errno.h>
30 #include <syslog.h>
31 #include <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 #define WAIT_LOOP_PER_SECOND            50
267 static int wait_for_sysfs(struct udevice *udev, const char *file, int timeout)
268 {
269         char devicepath[PATH_SIZE];
270         char filepath[PATH_SIZE];
271         struct stat stats;
272         int loop = timeout * WAIT_LOOP_PER_SECOND;
273
274         strlcpy(devicepath, sysfs_path, sizeof(devicepath));
275         strlcat(devicepath, udev->dev->devpath, sizeof(devicepath));
276         strlcpy(filepath, devicepath, sizeof(filepath));
277         strlcat(filepath, "/", sizeof(filepath));
278         strlcat(filepath, file, sizeof(filepath));
279
280         dbg("will wait %i sec for '%s'", timeout, filepath);
281         while (--loop) {
282                 /* lookup file */
283                 if (stat(filepath, &stats) == 0) {
284                         info("file '%s' appeared after %i loops", filepath, (timeout * WAIT_LOOP_PER_SECOND) - loop-1);
285                         return 0;
286                 }
287                 /* make sure the device does not have disappeared in the meantime */
288                 if (stat(devicepath, &stats) != 0) {
289                         info("device disappeared while waiting for '%s'", filepath);
290                         return -2;
291                 }
292                 info("wait for '%s' for %i mseconds", filepath, 1000 / WAIT_LOOP_PER_SECOND);
293                 usleep(1000 * 1000 / WAIT_LOOP_PER_SECOND);
294         }
295         err("waiting for '%s' failed", filepath);
296         return -1;
297 }
298
299 void udev_rules_apply_format(struct udevice *udev, char *string, size_t maxsize)
300 {
301         char temp[PATH_SIZE];
302         char temp2[PATH_SIZE];
303         char *head, *tail, *pos, *cpos, *attr, *rest;
304         int len;
305         int i;
306         int count;
307         enum subst_type {
308                 SUBST_UNKNOWN,
309                 SUBST_DEVPATH,
310                 SUBST_KERNEL,
311                 SUBST_KERNEL_NUMBER,
312                 SUBST_ID,
313                 SUBST_MAJOR,
314                 SUBST_MINOR,
315                 SUBST_RESULT,
316                 SUBST_ATTR,
317                 SUBST_PARENT,
318                 SUBST_TEMP_NODE,
319                 SUBST_ROOT,
320                 SUBST_ENV,
321         };
322         static const struct subst_map {
323                 char *name;
324                 char fmt;
325                 enum subst_type type;
326         } map[] = {
327                 { .name = "devpath",    .fmt = 'p',     .type = SUBST_DEVPATH },
328                 { .name = "number",     .fmt = 'n',     .type = SUBST_KERNEL_NUMBER },
329                 { .name = "kernel",     .fmt = 'k',     .type = SUBST_KERNEL },
330                 { .name = "id",         .fmt = 'b',     .type = SUBST_ID },
331                 { .name = "major",      .fmt = 'M',     .type = SUBST_MAJOR },
332                 { .name = "minor",      .fmt = 'm',     .type = SUBST_MINOR },
333                 { .name = "result",     .fmt = 'c',     .type = SUBST_RESULT },
334                 { .name = "attr",       .fmt = 's',     .type = SUBST_ATTR },
335                 { .name = "sysfs",      .fmt = 's',     .type = SUBST_ATTR },
336                 { .name = "parent",     .fmt = 'P',     .type = SUBST_PARENT },
337                 { .name = "tempnode",   .fmt = 'N',     .type = SUBST_TEMP_NODE },
338                 { .name = "root",       .fmt = 'r',     .type = SUBST_ROOT },
339                 { .name = "env",        .fmt = 'E',     .type = SUBST_ENV },
340                 { NULL, '\0', 0 }
341         };
342         enum subst_type type;
343         const struct subst_map *subst;
344
345         head = string;
346         while (1) {
347                 len = -1;
348                 while (head[0] != '\0') {
349                         if (head[0] == '$') {
350                                 /* substitute named variable */
351                                 if (head[1] == '\0')
352                                         break;
353                                 if (head[1] == '$') {
354                                         strlcpy(temp, head+2, sizeof(temp));
355                                         strlcpy(head+1, temp, maxsize);
356                                         head++;
357                                         continue;
358                                 }
359                                 head[0] = '\0';
360                                 for (subst = map; subst->name; subst++) {
361                                         if (strncasecmp(&head[1], subst->name, strlen(subst->name)) == 0) {
362                                                 type = subst->type;
363                                                 tail = head + strlen(subst->name)+1;
364                                                 dbg("will substitute format name '%s'", subst->name);
365                                                 goto found;
366                                         }
367                                 }
368                         } else if (head[0] == '%') {
369                                 /* substitute format char */
370                                 if (head[1] == '\0')
371                                         break;
372                                 if (head[1] == '%') {
373                                         strlcpy(temp, head+2, sizeof(temp));
374                                         strlcpy(head+1, temp, maxsize);
375                                         head++;
376                                         continue;
377                                 }
378                                 head[0] = '\0';
379                                 tail = head+1;
380                                 len = get_format_len(&tail);
381                                 for (subst = map; subst->name; subst++) {
382                                         if (tail[0] == subst->fmt) {
383                                                 type = subst->type;
384                                                 tail++;
385                                                 dbg("will substitute format char '%c'", subst->fmt);
386                                                 goto found;
387                                         }
388                                 }
389                         }
390                         head++;
391                 }
392                 break;
393 found:
394                 attr = get_format_attribute(&tail);
395                 strlcpy(temp, tail, sizeof(temp));
396                 dbg("format=%i, string='%s', tail='%s'", type ,string, tail);
397
398                 switch (type) {
399                 case SUBST_DEVPATH:
400                         strlcat(string, udev->dev->devpath, maxsize);
401                         dbg("substitute devpath '%s'", udev->dev->devpath);
402                         break;
403                 case SUBST_KERNEL:
404                         strlcat(string, udev->dev->kernel, maxsize);
405                         dbg("substitute kernel name '%s'", udev->dev->kernel);
406                         break;
407                 case SUBST_KERNEL_NUMBER:
408                         strlcat(string, udev->dev->kernel_number, maxsize);
409                         dbg("substitute kernel number '%s'", udev->dev->kernel_number);
410                         break;
411                 case SUBST_ID:
412                         if (udev->dev_parent != NULL) {
413                                 strlcat(string, udev->dev_parent->kernel, maxsize);
414                                 dbg("substitute id '%s'", udev->dev_parent->kernel);
415                         }
416                         break;
417                 case SUBST_MAJOR:
418                         sprintf(temp2, "%d", major(udev->devt));
419                         strlcat(string, temp2, maxsize);
420                         dbg("substitute major number '%s'", temp2);
421                         break;
422                 case SUBST_MINOR:
423                         sprintf(temp2, "%d", minor(udev->devt));
424                         strlcat(string, temp2, maxsize);
425                         dbg("substitute minor number '%s'", temp2);
426                         break;
427                 case SUBST_RESULT:
428                         if (udev->program_result[0] == '\0')
429                                 break;
430                         /* get part part of the result string */
431                         i = 0;
432                         if (attr != NULL)
433                                 i = strtoul(attr, &rest, 10);
434                         if (i > 0) {
435                                 dbg("request part #%d of result string", i);
436                                 cpos = udev->program_result;
437                                 while (--i) {
438                                         while (cpos[0] != '\0' && !isspace(cpos[0]))
439                                                 cpos++;
440                                         while (isspace(cpos[0]))
441                                                 cpos++;
442                                 }
443                                 if (i > 0) {
444                                         err("requested part of result string not found");
445                                         break;
446                                 }
447                                 strlcpy(temp2, cpos, sizeof(temp2));
448                                 /* %{2+}c copies the whole string from the second part on */
449                                 if (rest[0] != '+') {
450                                         cpos = strchr(temp2, ' ');
451                                         if (cpos)
452                                                 cpos[0] = '\0';
453                                 }
454                                 strlcat(string, temp2, maxsize);
455                                 dbg("substitute part of result string '%s'", temp2);
456                         } else {
457                                 strlcat(string, udev->program_result, maxsize);
458                                 dbg("substitute result string '%s'", udev->program_result);
459                         }
460                         break;
461                 case SUBST_ATTR:
462                         if (attr == NULL) {
463                                 dbg("missing attribute");
464                                 break;
465                         } else {
466                                 struct sysfs_device *dev_parent;
467                                 const char *value;
468
469                                 dev_parent = udev->dev;
470                                 do {
471                                         dbg("looking at '%s'", dev_parent->devpath);
472                                         value = sysfs_attr_get_value(dev_parent->devpath, attr);
473                                         if (value != NULL) {
474                                                 strlcpy(temp2, value, sizeof(temp2));
475                                                 break;
476                                         }
477                                         dev_parent = sysfs_device_get_parent(dev_parent);
478                                 } while (dev_parent != NULL);
479
480                                 /* strip trailing whitespace of sysfs value */
481                                 i = strlen(temp2);
482                                 while (i > 0 && isspace(temp2[i-1]))
483                                         temp2[--i] = '\0';
484                                 count = replace_untrusted_chars(temp2);
485                                 if (count)
486                                         info("%i untrusted character(s) replaced" , count);
487                                 strlcat(string, temp2, maxsize);
488                                 dbg("substitute sysfs value '%s'", temp2);
489                         }
490                         break;
491                 case SUBST_PARENT:
492                         {
493                                 struct sysfs_device *dev_parent;
494
495                                 dev_parent = sysfs_device_get_parent(udev->dev);
496                                 if (dev_parent != NULL) {
497                                         struct udevice *udev_parent;
498
499                                         dbg("found parent '%s', get the node name", dev_parent->devpath);
500                                         udev_parent = udev_device_init();
501                                         if (udev_parent != NULL) {
502                                                 /* lookup the name in the udev_db with the DEVPATH of the parent */
503                                                 if (udev_db_get_device(udev_parent, dev_parent->devpath) == 0) {
504                                                         strlcat(string, udev_parent->name, maxsize);
505                                                         dbg("substitute parent node name'%s'", udev_parent->name);
506                                                 } else
507                                                         dbg("parent not found in database");
508                                                 udev_device_cleanup(udev_parent);
509                                         }
510                                 }
511                         }
512                         break;
513                 case SUBST_TEMP_NODE:
514                         if (udev->tmp_node[0] == '\0') {
515                                 dbg("create temporary device node for callout");
516                                 snprintf(udev->tmp_node, sizeof(udev->tmp_node), "%s/.tmp-%u-%u",
517                                          udev_root, major(udev->devt), minor(udev->devt));
518                                 udev->tmp_node[sizeof(udev->tmp_node)-1] = '\0';
519                                 udev_node_mknod(udev, udev->tmp_node, udev->devt, 0600, 0, 0);
520                         }
521                         strlcat(string, udev->tmp_node, maxsize);
522                         dbg("substitute temporary device node name '%s'", udev->tmp_node);
523                         break;
524                 case SUBST_ROOT:
525                         strlcat(string, udev_root, maxsize);
526                         dbg("substitute udev_root '%s'", udev_root);
527                         break;
528                 case SUBST_ENV:
529                         if (attr == NULL) {
530                                 dbg("missing attribute");
531                                 break;
532                         }
533                         pos = getenv(attr);
534                         if (pos == NULL) {
535                                 dbg("env '%s' not available", attr);
536                                 break;
537                         }
538                         dbg("substitute env '%s=%s'", attr, pos);
539                         strlcat(string, pos, maxsize);
540                         break;
541                 default:
542                         err("unknown substitution type=%i", type);
543                         break;
544                 }
545                 /* possibly truncate to format-char specified length */
546                 if (len != -1) {
547                         head[len] = '\0';
548                         dbg("truncate to %i chars, subtitution string becomes '%s'", len, head);
549                 }
550                 strlcat(string, temp, maxsize);
551         }
552 }
553
554 static char *key_val(struct udev_rule *rule, struct key *key)
555 {
556         return rule->buf + key->val_off;
557 }
558
559 static char *key_pair_name(struct udev_rule *rule, struct key_pair *pair)
560 {
561         return rule->buf + pair->key_name_off;
562 }
563
564 static int match_key(const char *key_name, struct udev_rule *rule, struct key *key, const char *val)
565 {
566         int match;
567         char value[PATH_SIZE];
568         char *key_value;
569         char *pos;
570
571         if (key->operation != KEY_OP_MATCH &&
572             key->operation != KEY_OP_NOMATCH)
573                 return 0;
574
575         strlcpy(value, rule->buf + key->val_off, sizeof(value));
576         key_value = value;
577
578         dbg("key %s value='%s'", key_name, key_value);
579         while (key_value) {
580                 pos = strchr(key_value, '|');
581                 if (pos) {
582                         pos[0] = '\0';
583                         pos++;
584                 }
585                 dbg("match %s '%s' <-> '%s'", key_name, key_value, val);
586                 match = (strcmp_pattern(key_value, val) == 0);
587                 if (match && (key->operation != KEY_OP_NOMATCH)) {
588                         dbg("%s is true (matching value)", key_name);
589                         return 0;
590                 }
591                 if (!match && (key->operation == KEY_OP_NOMATCH)) {
592                         dbg("%s is true (non-matching value)", key_name);
593                         return 0;
594                 }
595                 key_value = pos;
596         }
597         dbg("%s is false", key_name);
598         return -1;
599 }
600
601 /* match a single rule against a given device and possibly its parent devices */
602 static int match_rule(struct udevice *udev, struct udev_rule *rule)
603 {
604         int i;
605
606         if (match_key("ACTION", rule, &rule->action, udev->action))
607                 goto nomatch;
608
609         if (match_key("KERNEL", rule, &rule->kernel, udev->dev->kernel))
610                 goto nomatch;
611
612         if (match_key("SUBSYSTEM", rule, &rule->subsystem, udev->dev->subsystem))
613                 goto nomatch;
614
615         if (match_key("DEVPATH", rule, &rule->devpath, udev->dev->devpath))
616                 goto nomatch;
617
618         if (match_key("DRIVER", rule, &rule->driver, udev->dev->driver))
619                 goto nomatch;
620
621         /* match NAME against a value assigned by an earlier rule */
622         if (match_key("NAME", rule, &rule->name, udev->name))
623                 goto nomatch;
624
625         for (i = 0; i < rule->env.count; i++) {
626                 struct key_pair *pair = &rule->env.keys[i];
627
628                 /* we only check for matches, assignments will be handled later */
629                 if (pair->key.operation == KEY_OP_MATCH ||
630                     pair->key.operation == KEY_OP_NOMATCH) {
631                         const char *key_name = key_pair_name(rule, pair);
632                         const char *value = getenv(key_name);
633
634                         if (!value) {
635                                 dbg("ENV{'%s'} is not set, treat as empty", key_name);
636                                 value = "";
637                         }
638                         if (match_key("ENV", rule, &pair->key, value))
639                                 goto nomatch;
640                 }
641         }
642
643         if (rule->wait_for_sysfs.operation != KEY_OP_UNSET) {
644                 int found;
645
646                 found = (wait_for_sysfs(udev, key_val(rule, &rule->wait_for_sysfs), 3) == 0);
647                 if (!found && (rule->wait_for_sysfs.operation != KEY_OP_NOMATCH))
648                         goto nomatch;
649         }
650
651         /* check for matching sysfs attribute pairs */
652         for (i = 0; i < rule->attr.count; i++) {
653                 struct key_pair *pair = &rule->attr.keys[i];
654
655                 if (pair->key.operation == KEY_OP_MATCH ||
656                     pair->key.operation == KEY_OP_NOMATCH) {
657                         const char *key_name = key_pair_name(rule, pair);
658                         const char *key_value = key_val(rule, &pair->key);
659                         const char *value;
660                         char val[VALUE_SIZE];
661                         size_t len;
662
663                         value = sysfs_attr_get_value(udev->dev->devpath, key_name);
664                         if (value == NULL)
665                                 goto nomatch;
666                         strlcpy(val, value, sizeof(val));
667
668                         /* strip trailing whitespace of value, if not asked to match for it */
669                         len = strlen(key_value);
670                         if (len > 0 && !isspace(key_value[len-1])) {
671                                 len = strlen(val);
672                                 while (len > 0 && isspace(val[len-1]))
673                                         val[--len] = '\0';
674                                 dbg("removed %zi trailing whitespace chars from '%s'", strlen(val)-len, val);
675                         }
676
677                         if (match_key("ATTR", rule, &pair->key, val))
678                                 goto nomatch;
679                 }
680         }
681
682         /* walk up the chain of parent devices and find a match */
683         udev->dev_parent = udev->dev;
684         while (1) {
685                 /* check for matching kernel device name */
686                 if (match_key("KERNELS", rule, &rule->kernels, udev->dev_parent->kernel))
687                         goto try_parent;
688
689                 /* check for matching subsystem value */
690                 if (match_key("SUBSYSTEMS", rule, &rule->subsystems, udev->dev_parent->subsystem))
691                         goto try_parent;
692
693                 /* check for matching driver */
694                 if (match_key("DRIVERS", rule, &rule->drivers, udev->dev_parent->driver))
695                         goto try_parent;
696
697                 /* check for matching sysfs attrubute pairs */
698                 for (i = 0; i < rule->attrs.count; i++) {
699                         struct key_pair *pair = &rule->attrs.keys[i];
700
701                         if (pair->key.operation == KEY_OP_MATCH ||
702                             pair->key.operation == KEY_OP_NOMATCH) {
703                                 const char *key_name = key_pair_name(rule, pair);
704                                 const char *key_value = key_val(rule, &pair->key);
705                                 const char *value;
706                                 char val[VALUE_SIZE];
707                                 size_t len;
708
709                                 value = sysfs_attr_get_value(udev->dev_parent->devpath, key_name);
710                                 if (value == NULL)
711                                         value = sysfs_attr_get_value(udev->dev->devpath, key_name);
712                                 if (value == NULL)
713                                         goto try_parent;
714                                 strlcpy(val, value, sizeof(val));
715
716                                 /* strip trailing whitespace of value, if not asked to match for it */
717                                 len = strlen(key_value);
718                                 if (len > 0 && !isspace(key_value[len-1])) {
719                                         len = strlen(val);
720                                         while (len > 0 && isspace(val[len-1]))
721                                                 val[--len] = '\0';
722                                         dbg("removed %zi trailing whitespace chars from '%s'", strlen(val)-len, val);
723                                 }
724
725                                 if (match_key("ATTRS", rule, &pair->key, val))
726                                         goto try_parent;
727                         }
728                 }
729
730                 /* found matching device  */
731                 break;
732 try_parent:
733                 /* move to parent device */
734                 dbg("try parent sysfs device");
735                 udev->dev_parent = sysfs_device_get_parent(udev->dev_parent);
736                 if (udev->dev_parent == NULL)
737                         goto nomatch;
738                 dbg("looking at dev_parent->devpath='%s'", udev->dev_parent->devpath);
739                 dbg("looking at dev_parent->kernel='%s'", udev->dev_parent->kernel);
740         }
741
742         /* execute external program */
743         if (rule->program.operation != KEY_OP_UNSET) {
744                 char program[PATH_SIZE];
745                 char result[PATH_SIZE];
746
747                 strlcpy(program, key_val(rule, &rule->program), sizeof(program));
748                 udev_rules_apply_format(udev, program, sizeof(program));
749                 if (run_program(program, udev->dev->subsystem, result, sizeof(result), NULL, (udev_log_priority >= LOG_INFO)) != 0) {
750                         dbg("PROGRAM is false");
751                         udev->program_result[0] = '\0';
752                         if (rule->program.operation != KEY_OP_NOMATCH)
753                                 goto nomatch;
754                 } else {
755                         int count;
756
757                         dbg("PROGRAM matches");
758                         remove_trailing_chars(result, '\n');
759                         count = replace_untrusted_chars(result);
760                         if (count)
761                                 info("%i untrusted character(s) replaced" , count);
762                         dbg("result is '%s'", result);
763                         strlcpy(udev->program_result, result, sizeof(udev->program_result));
764                         dbg("PROGRAM returned successful");
765                         if (rule->program.operation == KEY_OP_NOMATCH)
766                                 goto nomatch;
767                 }
768                 dbg("PROGRAM key is true");
769         }
770
771         /* check for matching result of external program */
772         if (match_key("RESULT", rule, &rule->result, udev->program_result))
773                 goto nomatch;
774
775         /* import variables returned from program or or file into environment */
776         if (rule->import.operation != KEY_OP_UNSET) {
777                 char import[PATH_SIZE];
778                 int rc = -1;
779
780                 strlcpy(import, key_val(rule, &rule->import), sizeof(import));
781                 udev_rules_apply_format(udev, import, sizeof(import));
782                 dbg("check for IMPORT import='%s'", import);
783                 if (rule->import_type == IMPORT_PROGRAM) {
784                         rc = import_program_into_env(udev, import);
785                 } else if (rule->import_type == IMPORT_FILE) {
786                         dbg("import file import='%s'", import);
787                         rc = import_file_into_env(udev, import);
788                 } else if (rule->import_type == IMPORT_PARENT) {
789                         dbg("import parent import='%s'", import);
790                         rc = import_parent_into_env(udev, import);
791                 }
792                 if (rc != 0) {
793                         dbg("IMPORT failed");
794                         if (rule->import.operation != KEY_OP_NOMATCH)
795                                 goto nomatch;
796                 } else
797                         dbg("IMPORT '%s' imported", key_val(rule, &rule->import));
798                 dbg("IMPORT key is true");
799         }
800
801         /* rule matches, if we have ENV assignments export it */
802         for (i = 0; i < rule->env.count; i++) {
803                 struct key_pair *pair = &rule->env.keys[i];
804
805                 if (pair->key.operation == KEY_OP_ASSIGN) {
806                         const char *key_name = key_pair_name(rule, pair);
807                         const char *value = key_val(rule, &pair->key);
808                         char *key_value = name_list_key_add(&udev->env_list, key_name, value);
809                         if (key_value == NULL)
810                                 break;
811
812                         udev_rules_apply_format(udev, key_value, NAME_SIZE);
813                         putenv(key_value);
814                         dbg("export ENV '%s'", key_value);
815                 }
816         }
817
818         /* if we have ATTR assignements write value to sysfs file */
819         for (i = 0; i < rule->attr.count; i++) {
820                 struct key_pair *pair = &rule->attr.keys[i];
821
822                 if (pair->key.operation == KEY_OP_ASSIGN) {
823                         const char *key_name = key_pair_name(rule, pair);
824                         const char *key_value = key_val(rule, &pair->key);
825                         char attr[PATH_SIZE];
826                         FILE *f;
827
828                         strlcpy(attr, sysfs_path, sizeof(attr));
829                         strlcat(attr, udev->dev->devpath, sizeof(attr));
830                         strlcat(attr, "/", sizeof(attr));
831                         strlcat(attr, key_name, sizeof(attr));
832                         dbg("write '%s' to '%s'", key_value, attr);
833                         f = fopen(attr, "w");
834                         if (f != NULL) {
835                                 if (fprintf(f, "%s\n", key_value) <= 0)
836                                         err("error writing ATTR{%s}: %s", attr, strerror(errno));
837                                 fclose(f);
838                         } else
839                                 err("error opening ATTR{%s} for writing: %s", attr, strerror(errno));
840                 }
841         }
842         return 0;
843
844 nomatch:
845         return -1;
846 }
847
848 int udev_rules_get_name(struct udev_rules *rules, struct udevice *udev)
849 {
850         struct udev_rule *rule;
851         int name_set = 0;
852
853         dbg("udev->dev->devpath='%s'", udev->dev->devpath);
854         dbg("udev->dev->kernel='%s'", udev->dev->kernel);
855
856         /* look for a matching rule to apply */
857         udev_rules_iter_init(rules);
858         while (1) {
859                 rule = udev_rules_iter_next(rules);
860                 if (rule == NULL)
861                         break;
862
863                 if (name_set &&
864                     (rule->name.operation == KEY_OP_ASSIGN ||
865                      rule->name.operation == KEY_OP_ASSIGN_FINAL ||
866                      rule->name.operation == KEY_OP_ADD)) {
867                         dbg("node name already set, rule ignored");
868                         continue;
869                 }
870
871                 dbg("process rule");
872                 if (match_rule(udev, rule) == 0) {
873                         /* apply options */
874                         if (rule->ignore_device) {
875                                 info("rule applied, '%s' is ignored", udev->dev->kernel);
876                                 udev->ignore_device = 1;
877                                 return 0;
878                         }
879                         if (rule->ignore_remove) {
880                                 udev->ignore_remove = 1;
881                                 dbg("remove event should be ignored");
882                         }
883                         /* apply all_partitions option only at a main block device */
884                         if (rule->partitions &&
885                             strcmp(udev->dev->subsystem, "block") == 0 && udev->dev->kernel_number[0] == '\0') {
886                                 udev->partitions = rule->partitions;
887                                 dbg("creation of partition nodes requested");
888                         }
889
890                         /* apply permissions */
891                         if (!udev->mode_final && rule->mode != 0000) {
892                                 if (rule->mode_operation == KEY_OP_ASSIGN_FINAL)
893                                         udev->mode_final = 1;
894                                 udev->mode = rule->mode;
895                                 dbg("applied mode=%#o to '%s'", rule->mode, udev->dev->kernel);
896                         }
897                         if (!udev->owner_final && rule->owner.operation != KEY_OP_UNSET) {
898                                 if (rule->owner.operation == KEY_OP_ASSIGN_FINAL)
899                                         udev->owner_final = 1;
900                                 strlcpy(udev->owner, key_val(rule, &rule->owner), sizeof(udev->owner));
901                                 udev_rules_apply_format(udev, udev->owner, sizeof(udev->owner));
902                                 dbg("applied owner='%s' to '%s'", udev->owner, udev->dev->kernel);
903                         }
904                         if (!udev->group_final && rule->group.operation != KEY_OP_UNSET) {
905                                 if (rule->group.operation == KEY_OP_ASSIGN_FINAL)
906                                         udev->group_final = 1;
907                                 strlcpy(udev->group, key_val(rule, &rule->group), sizeof(udev->group));
908                                 udev_rules_apply_format(udev, udev->group, sizeof(udev->group));
909                                 dbg("applied group='%s' to '%s'", udev->group, udev->dev->kernel);
910                         }
911
912                         /* collect symlinks */
913                         if (!udev->symlink_final && rule->symlink.operation != KEY_OP_UNSET) {
914                                 char temp[PATH_SIZE];
915                                 char *pos, *next;
916                                 int count;
917
918                                 if (rule->symlink.operation == KEY_OP_ASSIGN_FINAL)
919                                         udev->symlink_final = 1;
920                                 if (rule->symlink.operation == KEY_OP_ASSIGN || rule->symlink.operation == KEY_OP_ASSIGN_FINAL) {
921                                         info("reset symlink list");
922                                         name_list_cleanup(&udev->symlink_list);
923                                 }
924                                 strlcpy(temp, key_val(rule, &rule->symlink), sizeof(temp));
925                                 udev_rules_apply_format(udev, temp, sizeof(temp));
926                                 count = replace_untrusted_chars(temp);
927                                 if (count)
928                                         info("%i untrusted character(s) replaced" , count);
929                                 dbg("rule applied, added symlink(s) '%s'", temp);
930
931                                 /* add multiple symlinks separated by spaces */
932                                 pos = temp;
933                                 while (isspace(pos[0]))
934                                         pos++;
935                                 next = strchr(pos, ' ');
936                                 while (next) {
937                                         next[0] = '\0';
938                                         info("add symlink '%s'", pos);
939                                         name_list_add(&udev->symlink_list, pos, 0);
940                                         while (isspace(next[1]))
941                                                 next++;
942                                         pos = &next[1];
943                                         next = strchr(pos, ' ');
944                                 }
945                                 if (pos[0] != '\0') {
946                                         info("add symlink '%s'", pos);
947                                         name_list_add(&udev->symlink_list, pos, 0);
948                                 }
949                         }
950
951                         /* set name, later rules with name set will be ignored */
952                         if (rule->name.operation == KEY_OP_ASSIGN ||
953                             rule->name.operation == KEY_OP_ASSIGN_FINAL ||
954                             rule->name.operation == KEY_OP_ADD) {
955                                 int count;
956
957                                 name_set = 1;
958                                 strlcpy(udev->name, key_val(rule, &rule->name), sizeof(udev->name));
959                                 udev_rules_apply_format(udev, udev->name, sizeof(udev->name));
960                                 count = replace_untrusted_chars(udev->name);
961                                 if (count)
962                                         info("%i untrusted character(s) replaced", count);
963
964                                 info("rule applied, '%s' becomes '%s'", udev->dev->kernel, udev->name);
965                                 if (strcmp(udev->dev->subsystem, "net") != 0)
966                                         dbg("name, '%s' is going to have owner='%s', group='%s', mode=%#o partitions=%i",
967                                             udev->name, udev->owner, udev->group, udev->mode, udev->partitions);
968                         }
969
970                         if (!udev->run_final && rule->run.operation != KEY_OP_UNSET) {
971                                 if (rule->run.operation == KEY_OP_ASSIGN_FINAL)
972                                         udev->run_final = 1;
973                                 if (rule->run.operation == KEY_OP_ASSIGN || rule->run.operation == KEY_OP_ASSIGN_FINAL) {
974                                         info("reset run list");
975                                         name_list_cleanup(&udev->run_list);
976                                 }
977                                 dbg("add run '%s'", key_val(rule, &rule->run));
978                                 name_list_add(&udev->run_list, key_val(rule, &rule->run), 0);
979                         }
980
981                         if (rule->last_rule) {
982                                 dbg("last rule to be applied");
983                                 break;
984                         }
985
986                         if (rule->goto_label.operation != KEY_OP_UNSET) {
987                                 dbg("moving forward to label '%s'", key_val(rule, &rule->goto_label));
988                                 udev_rules_iter_label(rules, key_val(rule, &rule->goto_label));
989                         }
990                 }
991         }
992
993         if (!name_set) {
994                 strlcpy(udev->name, udev->dev->kernel, sizeof(udev->name));
995                 info("no node name set, will use kernel name '%s'", udev->name);
996         }
997
998         if (udev->tmp_node[0] != '\0') {
999                 dbg("removing temporary device node");
1000                 unlink_secure(udev->tmp_node);
1001                 udev->tmp_node[0] = '\0';
1002         }
1003
1004         return 0;
1005 }
1006
1007 int udev_rules_get_run(struct udev_rules *rules, struct udevice *udev)
1008 {
1009         struct udev_rule *rule;
1010
1011         dbg("udev->kernel='%s'", udev->dev->kernel);
1012
1013         /* look for a matching rule to apply */
1014         udev_rules_iter_init(rules);
1015         while (1) {
1016                 rule = udev_rules_iter_next(rules);
1017                 if (rule == NULL)
1018                         break;
1019
1020                 dbg("process rule");
1021                 if (rule->name.operation != KEY_OP_UNSET || rule->symlink.operation != KEY_OP_UNSET ||
1022                     rule->mode_operation != KEY_OP_UNSET || rule->owner.operation != KEY_OP_UNSET || rule->group.operation != KEY_OP_UNSET) {
1023                         dbg("skip rule that names a device");
1024                         continue;
1025                 }
1026
1027                 if (match_rule(udev, rule) == 0) {
1028                         if (rule->ignore_device) {
1029                                 info("rule applied, '%s' is ignored", udev->dev->kernel);
1030                                 udev->ignore_device = 1;
1031                                 return 0;
1032                         }
1033
1034                         if (!udev->run_final && rule->run.operation != KEY_OP_UNSET) {
1035                                 if (rule->run.operation == KEY_OP_ASSIGN || rule->run.operation == KEY_OP_ASSIGN_FINAL) {
1036                                         info("reset run list");
1037                                         name_list_cleanup(&udev->run_list);
1038                                 }
1039                                 dbg("add run '%s'", key_val(rule, &rule->run));
1040                                 name_list_add(&udev->run_list, key_val(rule, &rule->run), 0);
1041                                 if (rule->run.operation == KEY_OP_ASSIGN_FINAL)
1042                                         break;
1043                         }
1044
1045                         if (rule->last_rule) {
1046                                 dbg("last rule to be applied");
1047                                 break;
1048                         }
1049
1050                         if (rule->goto_label.operation != KEY_OP_UNSET) {
1051                                 dbg("moving forward to label '%s'", key_val(rule, &rule->goto_label));
1052                                 udev_rules_iter_label(rules, key_val(rule, &rule->goto_label));
1053                         }
1054                 }
1055         }
1056
1057         return 0;
1058 }