chiark / gitweb /
replace_chars: replace spaces in node name
[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 == NULL)
83                 return -1;
84
85         /* skip whitespace */
86         while (isspace(linepos[0]))
87                 linepos++;
88
89         /* get the key */
90         *key = linepos;
91         while (1) {
92                 linepos++;
93                 if (linepos[0] == '\0')
94                         return -1;
95                 if (isspace(linepos[0]))
96                         break;
97                 if (linepos[0] == '=')
98                         break;
99         }
100
101         /* terminate key */
102         linepos[0] = '\0';
103         linepos++;
104
105         /* skip whitespace */
106         while (isspace(linepos[0]))
107                 linepos++;
108
109         /* get the value*/
110         if (linepos[0] == '"') {
111                 linepos++;
112                 temp = strchr(linepos, '"');
113                 if (!temp) {
114                         dbg("missing closing quote");
115                         return -1;
116                 }
117                 dbg("value is quoted");
118                 temp[0] = '\0';
119         } else if (linepos[0] == '\'') {
120                 linepos++;
121                 temp = strchr(linepos, '\'');
122                 if (!temp) {
123                         dbg("missing closing quote");
124                         return -1;
125                 }
126                 dbg("value is quoted");
127                 temp[0] = '\0';
128         } else if (linepos[0] == '\0') {
129                 dbg("value is empty");
130         } else {
131                 temp = linepos;
132                 while (temp[0] && !isspace(temp[0]))
133                         temp++;
134                 temp[0] = '\0';
135         }
136         *value = linepos;
137
138         return 0;
139 }
140
141 static int import_keys_into_env(struct udevice *udev, const char *buf, size_t bufsize)
142 {
143         char line[LINE_SIZE];
144         const char *bufline;
145         char *linepos;
146         char *variable;
147         char *value;
148         size_t cur;
149         size_t count;
150         int lineno;
151
152         /* loop through the whole buffer */
153         lineno = 0;
154         cur = 0;
155         while (cur < bufsize) {
156                 count = buf_get_line(buf, bufsize, cur);
157                 bufline = &buf[cur];
158                 cur += count+1;
159                 lineno++;
160
161                 if (count >= sizeof(line)) {
162                         err("line too long, conf line skipped %s, line %d", udev_config_filename, lineno);
163                         continue;
164                 }
165
166                 /* eat the whitespace */
167                 while ((count > 0) && isspace(bufline[0])) {
168                         bufline++;
169                         count--;
170                 }
171                 if (count == 0)
172                         continue;
173
174                 /* see if this is a comment */
175                 if (bufline[0] == COMMENT_CHARACTER)
176                         continue;
177
178                 memcpy(line, bufline, count);
179                 line[count] = '\0';
180
181                 linepos = line;
182                 if (get_key(&linepos, &variable, &value) == 0) {
183                         dbg("import '%s=%s'", variable, value);
184
185                         /* handle device, renamed by external tool, returning new path */
186                         if (strcmp(variable, "DEVPATH") == 0) {
187                                 info("updating devpath from '%s' to '%s'", udev->dev->devpath, value);
188                                 sysfs_device_set_values(udev->dev, value, NULL, NULL);
189                         } else
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[2048];
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(NULL);
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 (fnmatch(filter, name, 0) == 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 did not disappear 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                                 head[0] = '$';
369                                 err("unknown format variable '%s'", head);
370                         } else if (head[0] == '%') {
371                                 /* substitute format char */
372                                 if (head[1] == '\0')
373                                         break;
374                                 if (head[1] == '%') {
375                                         strlcpy(temp, head+2, sizeof(temp));
376                                         strlcpy(head+1, temp, maxsize);
377                                         head++;
378                                         continue;
379                                 }
380                                 head[0] = '\0';
381                                 tail = head+1;
382                                 len = get_format_len(&tail);
383                                 for (subst = map; subst->name; subst++) {
384                                         if (tail[0] == subst->fmt) {
385                                                 type = subst->type;
386                                                 tail++;
387                                                 dbg("will substitute format char '%c'", subst->fmt);
388                                                 goto found;
389                                         }
390                                 }
391                                 head[0] = '%';
392                                 err("unknown format char '%c'", tail[0]);
393                         }
394                         head++;
395                 }
396                 break;
397 found:
398                 attr = get_format_attribute(&tail);
399                 strlcpy(temp, tail, sizeof(temp));
400                 dbg("format=%i, string='%s', tail='%s'", type ,string, tail);
401
402                 switch (type) {
403                 case SUBST_DEVPATH:
404                         strlcat(string, udev->dev->devpath, maxsize);
405                         dbg("substitute devpath '%s'", udev->dev->devpath);
406                         break;
407                 case SUBST_KERNEL:
408                         strlcat(string, udev->dev->kernel, maxsize);
409                         dbg("substitute kernel name '%s'", udev->dev->kernel);
410                         break;
411                 case SUBST_KERNEL_NUMBER:
412                         strlcat(string, udev->dev->kernel_number, maxsize);
413                         dbg("substitute kernel number '%s'", udev->dev->kernel_number);
414                         break;
415                 case SUBST_ID:
416                         if (udev->dev_parent != NULL) {
417                                 strlcat(string, udev->dev_parent->kernel, maxsize);
418                                 dbg("substitute id '%s'", udev->dev_parent->kernel);
419                         }
420                         break;
421                 case SUBST_MAJOR:
422                         sprintf(temp2, "%d", major(udev->devt));
423                         strlcat(string, temp2, maxsize);
424                         dbg("substitute major number '%s'", temp2);
425                         break;
426                 case SUBST_MINOR:
427                         sprintf(temp2, "%d", minor(udev->devt));
428                         strlcat(string, temp2, maxsize);
429                         dbg("substitute minor number '%s'", temp2);
430                         break;
431                 case SUBST_RESULT:
432                         if (udev->program_result[0] == '\0')
433                                 break;
434                         /* get part part of the result string */
435                         i = 0;
436                         if (attr != NULL)
437                                 i = strtoul(attr, &rest, 10);
438                         if (i > 0) {
439                                 dbg("request part #%d of result string", i);
440                                 cpos = udev->program_result;
441                                 while (--i) {
442                                         while (cpos[0] != '\0' && !isspace(cpos[0]))
443                                                 cpos++;
444                                         while (isspace(cpos[0]))
445                                                 cpos++;
446                                 }
447                                 if (i > 0) {
448                                         err("requested part of result string not found");
449                                         break;
450                                 }
451                                 strlcpy(temp2, cpos, sizeof(temp2));
452                                 /* %{2+}c copies the whole string from the second part on */
453                                 if (rest[0] != '+') {
454                                         cpos = strchr(temp2, ' ');
455                                         if (cpos)
456                                                 cpos[0] = '\0';
457                                 }
458                                 strlcat(string, temp2, maxsize);
459                                 dbg("substitute part of result string '%s'", temp2);
460                         } else {
461                                 strlcat(string, udev->program_result, maxsize);
462                                 dbg("substitute result string '%s'", udev->program_result);
463                         }
464                         break;
465                 case SUBST_ATTR:
466                         if (attr == NULL)
467                                 err("missing file parameter for attr");
468                         else {
469                                 const char *value = NULL;
470                                 size_t size;
471
472                                 /* first try the current device, other matches may have selected */
473                                 if (udev->dev_parent != NULL && udev->dev_parent != udev->dev)
474                                         value = sysfs_attr_get_value(udev->dev_parent->devpath, attr);
475
476                                 /* look at all devices along the chain of parents */
477                                 if (value == NULL) {
478                                         struct sysfs_device *dev_parent = udev->dev;
479
480                                         do {
481                                                 dbg("looking at '%s'", dev_parent->devpath);
482                                                 value = sysfs_attr_get_value(dev_parent->devpath, attr);
483                                                 if (value != NULL) {
484                                                         strlcpy(temp2, value, sizeof(temp2));
485                                                         break;
486                                                 }
487                                                 dev_parent = sysfs_device_get_parent(dev_parent);
488                                         } while (dev_parent != NULL);
489                                 }
490
491                                 if (value == NULL)
492                                         break;
493
494                                 /* strip trailing whitespace, and replace unwanted characters */
495                                 size = strlcpy(temp2, value, sizeof(temp2));
496                                 if (size >= sizeof(temp2))
497                                         size = sizeof(temp2)-1;
498                                 while (size > 0 && isspace(temp2[size-1]))
499                                         temp2[--size] = '\0';
500                                 count = replace_chars(temp2, ALLOWED_CHARS_INPUT);
501                                 if (count > 0)
502                                         info("%i character(s) replaced" , count);
503                                 strlcat(string, temp2, maxsize);
504                                 dbg("substitute sysfs value '%s'", temp2);
505                         }
506                         break;
507                 case SUBST_PARENT:
508                         {
509                                 struct sysfs_device *dev_parent;
510
511                                 dev_parent = sysfs_device_get_parent(udev->dev);
512                                 if (dev_parent != NULL) {
513                                         struct udevice *udev_parent;
514
515                                         dbg("found parent '%s', get the node name", dev_parent->devpath);
516                                         udev_parent = udev_device_init(NULL);
517                                         if (udev_parent != NULL) {
518                                                 /* lookup the name in the udev_db with the DEVPATH of the parent */
519                                                 if (udev_db_get_device(udev_parent, dev_parent->devpath) == 0) {
520                                                         strlcat(string, udev_parent->name, maxsize);
521                                                         dbg("substitute parent node name'%s'", udev_parent->name);
522                                                 } else
523                                                         dbg("parent not found in database");
524                                                 udev_device_cleanup(udev_parent);
525                                         }
526                                 }
527                         }
528                         break;
529                 case SUBST_TEMP_NODE:
530                         if (udev->tmp_node[0] == '\0' && major(udev->devt) > 0) {
531                                 dbg("create temporary device node for callout");
532                                 snprintf(udev->tmp_node, sizeof(udev->tmp_node), "%s/.tmp-%u-%u",
533                                          udev_root, major(udev->devt), minor(udev->devt));
534                                 udev->tmp_node[sizeof(udev->tmp_node)-1] = '\0';
535                                 udev_node_mknod(udev, udev->tmp_node, udev->devt, 0600, 0, 0);
536                         }
537                         strlcat(string, udev->tmp_node, maxsize);
538                         dbg("substitute temporary device node name '%s'", udev->tmp_node);
539                         break;
540                 case SUBST_ROOT:
541                         strlcat(string, udev_root, maxsize);
542                         dbg("substitute udev_root '%s'", udev_root);
543                         break;
544                 case SUBST_ENV:
545                         if (attr == NULL) {
546                                 dbg("missing attribute");
547                                 break;
548                         }
549                         pos = getenv(attr);
550                         if (pos == NULL) {
551                                 dbg("env '%s' not available", attr);
552                                 break;
553                         }
554                         dbg("substitute env '%s=%s'", attr, pos);
555                         strlcat(string, pos, maxsize);
556                         break;
557                 default:
558                         err("unknown substitution type=%i", type);
559                         break;
560                 }
561                 /* possibly truncate to format-char specified length */
562                 if (len >= 0 && len < (int)strlen(head)) {
563                         head[len] = '\0';
564                         dbg("truncate to %i chars, subtitution string becomes '%s'", len, head);
565                 }
566                 strlcat(string, temp, maxsize);
567         }
568 }
569
570 static char *key_val(struct udev_rule *rule, struct key *key)
571 {
572         return rule->buf + key->val_off;
573 }
574
575 static char *key_pair_name(struct udev_rule *rule, struct key_pair *pair)
576 {
577         return rule->buf + pair->key_name_off;
578 }
579
580 static int match_key(const char *key_name, struct udev_rule *rule, struct key *key, const char *val)
581 {
582         char value[PATH_SIZE];
583         char *key_value;
584         char *pos;
585         int match = 0;
586
587         if (key->operation != KEY_OP_MATCH &&
588             key->operation != KEY_OP_NOMATCH)
589                 return 0;
590
591         /* look for a matching string, parts are separated by '|' */
592         strlcpy(value, rule->buf + key->val_off, sizeof(value));
593         key_value = value;
594         dbg("key %s value='%s'", key_name, key_value);
595         while (key_value) {
596                 pos = strchr(key_value, '|');
597                 if (pos) {
598                         pos[0] = '\0';
599                         pos++;
600                 }
601
602                 dbg("match %s '%s' <-> '%s'", key_name, key_value, val);
603                 match = (fnmatch(key_value, val, 0) == 0);
604                 if (match)
605                         break;
606
607                 key_value = pos;
608         }
609
610         if (match && (key->operation == KEY_OP_MATCH)) {
611                 dbg("%s is true (matching value)", key_name);
612                 return 0;
613         }
614         if (!match && (key->operation == KEY_OP_NOMATCH)) {
615                 dbg("%s is true (non-matching value)", key_name);
616                 return 0;
617         }
618         return -1;
619 }
620
621 /* match a single rule against a given device and possibly its parent devices */
622 static int match_rule(struct udevice *udev, struct udev_rule *rule)
623 {
624         int i;
625
626         if (match_key("ACTION", rule, &rule->action, udev->action))
627                 goto nomatch;
628
629         if (match_key("KERNEL", rule, &rule->kernel, udev->dev->kernel))
630                 goto nomatch;
631
632         if (match_key("SUBSYSTEM", rule, &rule->subsystem, udev->dev->subsystem))
633                 goto nomatch;
634
635         if (match_key("DEVPATH", rule, &rule->devpath, udev->dev->devpath))
636                 goto nomatch;
637
638         if (match_key("DRIVER", rule, &rule->driver, udev->dev->driver))
639                 goto nomatch;
640
641         /* match NAME against a value assigned by an earlier rule */
642         if (match_key("NAME", rule, &rule->name, udev->name))
643                 goto nomatch;
644
645         for (i = 0; i < rule->env.count; i++) {
646                 struct key_pair *pair = &rule->env.keys[i];
647
648                 /* we only check for matches, assignments will be handled later */
649                 if (pair->key.operation == KEY_OP_MATCH ||
650                     pair->key.operation == KEY_OP_NOMATCH) {
651                         const char *key_name = key_pair_name(rule, pair);
652                         const char *value = getenv(key_name);
653
654                         if (!value) {
655                                 dbg("ENV{'%s'} is not set, treat as empty", key_name);
656                                 value = "";
657                         }
658                         if (match_key("ENV", rule, &pair->key, value))
659                                 goto nomatch;
660                 }
661         }
662
663         if (rule->wait_for_sysfs.operation != KEY_OP_UNSET) {
664                 int found;
665
666                 found = (wait_for_sysfs(udev, key_val(rule, &rule->wait_for_sysfs), 3) == 0);
667                 if (!found && (rule->wait_for_sysfs.operation != KEY_OP_NOMATCH))
668                         goto nomatch;
669         }
670
671         /* check for matching sysfs attribute pairs */
672         for (i = 0; i < rule->attr.count; i++) {
673                 struct key_pair *pair = &rule->attr.keys[i];
674
675                 if (pair->key.operation == KEY_OP_MATCH ||
676                     pair->key.operation == KEY_OP_NOMATCH) {
677                         const char *key_name = key_pair_name(rule, pair);
678                         const char *key_value = key_val(rule, &pair->key);
679                         const char *value;
680                         char val[VALUE_SIZE];
681                         size_t len;
682
683                         value = sysfs_attr_get_value(udev->dev->devpath, key_name);
684                         if (value == NULL)
685                                 goto nomatch;
686                         strlcpy(val, value, sizeof(val));
687
688                         /* strip trailing whitespace of value, if not asked to match for it */
689                         len = strlen(key_value);
690                         if (len > 0 && !isspace(key_value[len-1])) {
691                                 len = strlen(val);
692                                 while (len > 0 && isspace(val[len-1]))
693                                         val[--len] = '\0';
694                                 dbg("removed %zi trailing whitespace chars from '%s'", strlen(val)-len, val);
695                         }
696
697                         if (match_key("ATTR", rule, &pair->key, val))
698                                 goto nomatch;
699                 }
700         }
701
702         /* walk up the chain of parent devices and find a match */
703         udev->dev_parent = udev->dev;
704         while (1) {
705                 /* check for matching kernel device name */
706                 if (match_key("KERNELS", rule, &rule->kernels, udev->dev_parent->kernel))
707                         goto try_parent;
708
709                 /* check for matching subsystem value */
710                 if (match_key("SUBSYSTEMS", rule, &rule->subsystems, udev->dev_parent->subsystem))
711                         goto try_parent;
712
713                 /* check for matching driver */
714                 if (match_key("DRIVERS", rule, &rule->drivers, udev->dev_parent->driver))
715                         goto try_parent;
716
717                 /* check for matching sysfs attribute pairs */
718                 for (i = 0; i < rule->attrs.count; i++) {
719                         struct key_pair *pair = &rule->attrs.keys[i];
720
721                         if (pair->key.operation == KEY_OP_MATCH ||
722                             pair->key.operation == KEY_OP_NOMATCH) {
723                                 const char *key_name = key_pair_name(rule, pair);
724                                 const char *key_value = key_val(rule, &pair->key);
725                                 const char *value;
726                                 char val[VALUE_SIZE];
727                                 size_t len;
728
729                                 value = sysfs_attr_get_value(udev->dev_parent->devpath, key_name);
730                                 if (value == NULL)
731                                         value = sysfs_attr_get_value(udev->dev->devpath, key_name);
732                                 if (value == NULL)
733                                         goto try_parent;
734                                 strlcpy(val, value, sizeof(val));
735
736                                 /* strip trailing whitespace of value, if not asked to match for it */
737                                 len = strlen(key_value);
738                                 if (len > 0 && !isspace(key_value[len-1])) {
739                                         len = strlen(val);
740                                         while (len > 0 && isspace(val[len-1]))
741                                                 val[--len] = '\0';
742                                         dbg("removed %zi trailing whitespace chars from '%s'", strlen(val)-len, val);
743                                 }
744
745                                 if (match_key("ATTRS", rule, &pair->key, val))
746                                         goto try_parent;
747                         }
748                 }
749
750                 /* found matching device  */
751                 break;
752 try_parent:
753                 /* move to parent device */
754                 dbg("try parent sysfs device");
755                 udev->dev_parent = sysfs_device_get_parent(udev->dev_parent);
756                 if (udev->dev_parent == NULL)
757                         goto nomatch;
758                 dbg("looking at dev_parent->devpath='%s'", udev->dev_parent->devpath);
759                 dbg("looking at dev_parent->kernel='%s'", udev->dev_parent->kernel);
760         }
761
762         /* execute external program */
763         if (rule->program.operation != KEY_OP_UNSET) {
764                 char program[PATH_SIZE];
765                 char result[PATH_SIZE];
766
767                 strlcpy(program, key_val(rule, &rule->program), sizeof(program));
768                 udev_rules_apply_format(udev, program, sizeof(program));
769                 if (run_program(program, udev->dev->subsystem, result, sizeof(result), NULL, (udev_log_priority >= LOG_INFO)) != 0) {
770                         dbg("PROGRAM is false");
771                         udev->program_result[0] = '\0';
772                         if (rule->program.operation != KEY_OP_NOMATCH)
773                                 goto nomatch;
774                 } else {
775                         int count;
776
777                         dbg("PROGRAM matches");
778                         remove_trailing_chars(result, '\n');
779                         count = replace_chars(result, ALLOWED_CHARS_INPUT);
780                         if (count)
781                                 info("%i character(s) replaced" , count);
782                         dbg("result is '%s'", result);
783                         strlcpy(udev->program_result, result, sizeof(udev->program_result));
784                         dbg("PROGRAM returned successful");
785                         if (rule->program.operation == KEY_OP_NOMATCH)
786                                 goto nomatch;
787                 }
788                 dbg("PROGRAM key is true");
789         }
790
791         /* check for matching result of external program */
792         if (match_key("RESULT", rule, &rule->result, udev->program_result))
793                 goto nomatch;
794
795         /* import variables returned from program or or file into environment */
796         if (rule->import.operation != KEY_OP_UNSET) {
797                 char import[PATH_SIZE];
798                 int rc = -1;
799
800                 strlcpy(import, key_val(rule, &rule->import), sizeof(import));
801                 udev_rules_apply_format(udev, import, sizeof(import));
802                 dbg("check for IMPORT import='%s'", import);
803                 if (rule->import_type == IMPORT_PROGRAM) {
804                         rc = import_program_into_env(udev, import);
805                 } else if (rule->import_type == IMPORT_FILE) {
806                         dbg("import file import='%s'", import);
807                         rc = import_file_into_env(udev, import);
808                 } else if (rule->import_type == IMPORT_PARENT) {
809                         dbg("import parent import='%s'", import);
810                         rc = import_parent_into_env(udev, import);
811                 }
812                 if (rc != 0) {
813                         dbg("IMPORT failed");
814                         if (rule->import.operation != KEY_OP_NOMATCH)
815                                 goto nomatch;
816                 } else
817                         dbg("IMPORT '%s' imported", key_val(rule, &rule->import));
818                 dbg("IMPORT key is true");
819         }
820
821         /* rule matches, if we have ENV assignments export it */
822         for (i = 0; i < rule->env.count; i++) {
823                 struct key_pair *pair = &rule->env.keys[i];
824
825                 if (pair->key.operation == KEY_OP_ASSIGN) {
826                         char temp_value[NAME_SIZE];
827                         const char *key_name = key_pair_name(rule, pair);
828                         const char *value = key_val(rule, &pair->key);
829
830                         /* make sure we don't write to the same string we possibly read from */
831                         strlcpy(temp_value, value, sizeof(temp_value));
832                         udev_rules_apply_format(udev, temp_value, NAME_SIZE);
833
834                         if (temp_value[0] == '\0') {
835                                 name_list_key_remove(&udev->env_list, key_name);
836                                 unsetenv(key_name);
837                                 info("unset ENV '%s'", key_name);
838                         } else {
839                                 char *key_value = name_list_key_add(&udev->env_list, key_name, temp_value);
840
841                                 if (key_value == NULL)
842                                         break;
843                                 putenv(key_value);
844                                 info("set ENV '%s'", key_value);
845                         }
846                 }
847         }
848
849         /* if we have ATTR assignments, write value to sysfs file */
850         for (i = 0; i < rule->attr.count; i++) {
851                 struct key_pair *pair = &rule->attr.keys[i];
852
853                 if (pair->key.operation == KEY_OP_ASSIGN) {
854                         const char *key_name = key_pair_name(rule, pair);
855                         char attr[PATH_SIZE];
856                         char value[NAME_SIZE];
857                         FILE *f;
858
859                         strlcpy(attr, sysfs_path, sizeof(attr));
860                         strlcat(attr, udev->dev->devpath, sizeof(attr));
861                         strlcat(attr, "/", sizeof(attr));
862                         strlcat(attr, key_name, sizeof(attr));
863                         strlcpy(value, key_val(rule, &pair->key), sizeof(value));
864                         udev_rules_apply_format(udev, value, sizeof(value));
865                         info("writing '%s' to sysfs file '%s'", value, attr);
866                         f = fopen(attr, "w");
867                         if (f != NULL) {
868                                 if (!udev->test_run)
869                                         if (fprintf(f, "%s", value) <= 0)
870                                                 err("error writing ATTR{%s}: %s", attr, strerror(errno));
871                                 fclose(f);
872                         } else
873                                 err("error opening ATTR{%s} for writing: %s", attr, strerror(errno));
874                 }
875         }
876         return 0;
877
878 nomatch:
879         return -1;
880 }
881
882 int udev_rules_get_name(struct udev_rules *rules, struct udevice *udev)
883 {
884         struct udev_rule *rule;
885         int name_set = 0;
886
887         dbg("udev->dev->devpath='%s'", udev->dev->devpath);
888         dbg("udev->dev->kernel='%s'", udev->dev->kernel);
889
890         /* look for a matching rule to apply */
891         udev_rules_iter_init(rules);
892         while (1) {
893                 rule = udev_rules_iter_next(rules);
894                 if (rule == NULL)
895                         break;
896
897                 if (name_set &&
898                     (rule->name.operation == KEY_OP_ASSIGN ||
899                      rule->name.operation == KEY_OP_ASSIGN_FINAL ||
900                      rule->name.operation == KEY_OP_ADD)) {
901                         dbg("node name already set, rule ignored");
902                         continue;
903                 }
904
905                 dbg("process rule");
906                 if (match_rule(udev, rule) == 0) {
907                         /* apply options */
908                         if (rule->ignore_device) {
909                                 info("rule applied, '%s' is ignored", udev->dev->kernel);
910                                 udev->ignore_device = 1;
911                                 return 0;
912                         }
913                         if (rule->ignore_remove) {
914                                 udev->ignore_remove = 1;
915                                 dbg("remove event should be ignored");
916                         }
917                         if (rule->link_priority != 0) {
918                                 udev->link_priority = rule->link_priority;
919                                 info("link_priority=%i", udev->link_priority);
920                         }
921                         /* apply all_partitions option only at a main block device */
922                         if (rule->partitions &&
923                             strcmp(udev->dev->subsystem, "block") == 0 && udev->dev->kernel_number[0] == '\0') {
924                                 udev->partitions = rule->partitions;
925                                 dbg("creation of partition nodes requested");
926                         }
927
928                         /* apply permissions */
929                         if (!udev->mode_final && rule->mode != 0000) {
930                                 if (rule->mode_operation == KEY_OP_ASSIGN_FINAL)
931                                         udev->mode_final = 1;
932                                 udev->mode = rule->mode;
933                                 dbg("applied mode=%#o to '%s'", rule->mode, udev->dev->kernel);
934                         }
935                         if (!udev->owner_final && rule->owner.operation != KEY_OP_UNSET) {
936                                 if (rule->owner.operation == KEY_OP_ASSIGN_FINAL)
937                                         udev->owner_final = 1;
938                                 strlcpy(udev->owner, key_val(rule, &rule->owner), sizeof(udev->owner));
939                                 udev_rules_apply_format(udev, udev->owner, sizeof(udev->owner));
940                                 dbg("applied owner='%s' to '%s'", udev->owner, udev->dev->kernel);
941                         }
942                         if (!udev->group_final && rule->group.operation != KEY_OP_UNSET) {
943                                 if (rule->group.operation == KEY_OP_ASSIGN_FINAL)
944                                         udev->group_final = 1;
945                                 strlcpy(udev->group, key_val(rule, &rule->group), sizeof(udev->group));
946                                 udev_rules_apply_format(udev, udev->group, sizeof(udev->group));
947                                 dbg("applied group='%s' to '%s'", udev->group, udev->dev->kernel);
948                         }
949
950                         /* collect symlinks */
951                         if (!udev->symlink_final && rule->symlink.operation != KEY_OP_UNSET) {
952                                 char temp[PATH_SIZE];
953                                 char *pos, *next;
954                                 int count;
955
956                                 if (rule->symlink.operation == KEY_OP_ASSIGN_FINAL)
957                                         udev->symlink_final = 1;
958                                 if (rule->symlink.operation == KEY_OP_ASSIGN || rule->symlink.operation == KEY_OP_ASSIGN_FINAL) {
959                                         info("reset symlink list");
960                                         name_list_cleanup(&udev->symlink_list);
961                                 }
962                                 /* allow  multiple symlinks separated by spaces */
963                                 strlcpy(temp, key_val(rule, &rule->symlink), sizeof(temp));
964                                 udev_rules_apply_format(udev, temp, sizeof(temp));
965                                 count = replace_chars(temp, ALLOWED_CHARS_FILE " ");
966                                 if (count)
967                                         info("%i character(s) replaced" , count);
968                                 dbg("rule applied, added symlink(s) '%s'", temp);
969                                 pos = temp;
970                                 while (isspace(pos[0]))
971                                         pos++;
972                                 next = strchr(pos, ' ');
973                                 while (next) {
974                                         next[0] = '\0';
975                                         info("add symlink '%s'", pos);
976                                         name_list_add(&udev->symlink_list, pos, 0);
977                                         while (isspace(next[1]))
978                                                 next++;
979                                         pos = &next[1];
980                                         next = strchr(pos, ' ');
981                                 }
982                                 if (pos[0] != '\0') {
983                                         info("add symlink '%s'", pos);
984                                         name_list_add(&udev->symlink_list, pos, 0);
985                                 }
986                         }
987
988                         /* set name, later rules with name set will be ignored */
989                         if (rule->name.operation == KEY_OP_ASSIGN ||
990                             rule->name.operation == KEY_OP_ASSIGN_FINAL ||
991                             rule->name.operation == KEY_OP_ADD) {
992                                 int count;
993
994                                 name_set = 1;
995                                 strlcpy(udev->name, key_val(rule, &rule->name), sizeof(udev->name));
996                                 udev_rules_apply_format(udev, udev->name, sizeof(udev->name));
997                                 count = replace_chars(udev->name, ALLOWED_CHARS_FILE);
998                                 if (count)
999                                         info("%i character(s) replaced", count);
1000
1001                                 info("rule applied, '%s' becomes '%s'", udev->dev->kernel, udev->name);
1002                                 if (strcmp(udev->dev->subsystem, "net") != 0)
1003                                         dbg("name, '%s' is going to have owner='%s', group='%s', mode=%#o partitions=%i",
1004                                             udev->name, udev->owner, udev->group, udev->mode, udev->partitions);
1005                         }
1006
1007                         if (!udev->run_final && rule->run.operation != KEY_OP_UNSET) {
1008                                 if (rule->run.operation == KEY_OP_ASSIGN_FINAL)
1009                                         udev->run_final = 1;
1010                                 if (rule->run.operation == KEY_OP_ASSIGN || rule->run.operation == KEY_OP_ASSIGN_FINAL) {
1011                                         info("reset run list");
1012                                         name_list_cleanup(&udev->run_list);
1013                                 }
1014                                 dbg("add run '%s'", key_val(rule, &rule->run));
1015                                 name_list_add(&udev->run_list, key_val(rule, &rule->run), 0);
1016                         }
1017
1018                         if (rule->last_rule) {
1019                                 dbg("last rule to be applied");
1020                                 break;
1021                         }
1022
1023                         if (rule->goto_label.operation != KEY_OP_UNSET) {
1024                                 dbg("moving forward to label '%s'", key_val(rule, &rule->goto_label));
1025                                 udev_rules_iter_label(rules, key_val(rule, &rule->goto_label));
1026                         }
1027                 }
1028         }
1029
1030         if (!name_set) {
1031                 strlcpy(udev->name, udev->dev->kernel, sizeof(udev->name));
1032                 info("no node name set, will use kernel name '%s'", udev->name);
1033         }
1034
1035         if (udev->tmp_node[0] != '\0') {
1036                 dbg("removing temporary device node");
1037                 unlink_secure(udev->tmp_node);
1038                 udev->tmp_node[0] = '\0';
1039         }
1040
1041         return 0;
1042 }
1043
1044 int udev_rules_get_run(struct udev_rules *rules, struct udevice *udev)
1045 {
1046         struct udev_rule *rule;
1047
1048         dbg("udev->kernel='%s'", udev->dev->kernel);
1049
1050         /* look for a matching rule to apply */
1051         udev_rules_iter_init(rules);
1052         while (1) {
1053                 rule = udev_rules_iter_next(rules);
1054                 if (rule == NULL)
1055                         break;
1056
1057                 dbg("process rule");
1058                 if (rule->name.operation != KEY_OP_UNSET || rule->symlink.operation != KEY_OP_UNSET ||
1059                     rule->mode_operation != KEY_OP_UNSET || rule->owner.operation != KEY_OP_UNSET || rule->group.operation != KEY_OP_UNSET) {
1060                         dbg("skip rule that names a device");
1061                         continue;
1062                 }
1063
1064                 if (match_rule(udev, rule) == 0) {
1065                         if (rule->ignore_device) {
1066                                 info("rule applied, '%s' is ignored", udev->dev->kernel);
1067                                 udev->ignore_device = 1;
1068                                 return 0;
1069                         }
1070
1071                         if (!udev->run_final && rule->run.operation != KEY_OP_UNSET) {
1072                                 if (rule->run.operation == KEY_OP_ASSIGN || rule->run.operation == KEY_OP_ASSIGN_FINAL) {
1073                                         info("reset run list");
1074                                         name_list_cleanup(&udev->run_list);
1075                                 }
1076                                 dbg("add run '%s'", key_val(rule, &rule->run));
1077                                 name_list_add(&udev->run_list, key_val(rule, &rule->run), 0);
1078                                 if (rule->run.operation == KEY_OP_ASSIGN_FINAL)
1079                                         break;
1080                         }
1081
1082                         if (rule->last_rule) {
1083                                 dbg("last rule to be applied");
1084                                 break;
1085                         }
1086
1087                         if (rule->goto_label.operation != KEY_OP_UNSET) {
1088                                 dbg("moving forward to label '%s'", key_val(rule, &rule->goto_label));
1089                                 udev_rules_iter_label(rules, key_val(rule, &rule->goto_label));
1090                         }
1091                 }
1092         }
1093
1094         return 0;
1095 }