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