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