chiark / gitweb /
a8fd18cf8a5e5c6815dba3906f809ea232f0678a
[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) != 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 int udev_rules_run(struct udevice *udev)
242 {
243         struct name_entry *name_loop;
244         int retval = 0;
245
246         dbg("executing run list");
247         list_for_each_entry(name_loop, &udev->run_list, node) {
248                 if (strncmp(name_loop->name, "socket:", strlen("socket:")) == 0) {
249                         pass_env_to_socket(&name_loop->name[strlen("socket:")], udev->dev->devpath, udev->action);
250                 } else {
251                         char program[PATH_SIZE];
252
253                         strlcpy(program, name_loop->name, sizeof(program));
254                         udev_rules_apply_format(udev, program, sizeof(program));
255                         if (run_program(program, udev->dev->subsystem, NULL, 0, NULL) != 0)
256                                 if (!name_loop->ignore_error)
257                                         retval = -1;
258                 }
259         }
260
261         return retval;
262 }
263
264 #define WAIT_LOOP_PER_SECOND            50
265 static int wait_for_sysfs(struct udevice *udev, const char *file, int timeout)
266 {
267         char devicepath[PATH_SIZE];
268         char filepath[PATH_SIZE];
269         struct stat stats;
270         int loop = timeout * WAIT_LOOP_PER_SECOND;
271
272         strlcpy(devicepath, sysfs_path, sizeof(devicepath));
273         strlcat(devicepath, udev->dev->devpath, sizeof(devicepath));
274         strlcpy(filepath, devicepath, sizeof(filepath));
275         strlcat(filepath, "/", sizeof(filepath));
276         strlcat(filepath, file, sizeof(filepath));
277
278         dbg("will wait %i sec for '%s'", timeout, filepath);
279         while (--loop) {
280                 /* lookup file */
281                 if (stat(filepath, &stats) == 0) {
282                         info("file '%s' appeared after %i loops", filepath, (timeout * WAIT_LOOP_PER_SECOND) - loop-1);
283                         return 0;
284                 }
285                 /* make sure, the device did not disappear in the meantime */
286                 if (stat(devicepath, &stats) != 0) {
287                         info("device disappeared while waiting for '%s'", filepath);
288                         return -2;
289                 }
290                 info("wait for '%s' for %i mseconds", filepath, 1000 / WAIT_LOOP_PER_SECOND);
291                 usleep(1000 * 1000 / WAIT_LOOP_PER_SECOND);
292         }
293         info("waiting for '%s' failed", filepath);
294         return -1;
295 }
296
297 /* handle "[$SUBSYSTEM/$KERNEL]<attribute>" lookup */
298 static int attr_get_by_subsys_id(const char *attrstr, char *devpath, size_t len, char **attr)
299 {
300         char subsys[NAME_SIZE];
301         char *attrib;
302         char *id;
303         int found = 0;
304
305         if (attrstr[0] != '[')
306                 goto out;
307
308         strlcpy(subsys, &attrstr[1], sizeof(subsys));
309
310         attrib = strchr(subsys, ']');
311         if (attrib == NULL)
312                 goto out;
313         attrib[0] = '\0';
314         attrib = &attrib[1];
315
316         id = strchr(subsys, '/');
317         if (id == NULL)
318                 goto out;
319         id[0] = '\0';
320         id = &id[1];
321
322         if (sysfs_lookup_devpath_by_subsys_id(devpath, len, subsys, id)) {
323                 if (attr != NULL) {
324                         if (attrib[0] != '\0')
325                                 *attr = attrib;
326                         else
327                                 *attr = NULL;
328                 }
329                 found = 1;
330         }
331 out:
332         return found;
333 }
334
335 void udev_rules_apply_format(struct udevice *udev, char *string, size_t maxsize)
336 {
337         char temp[PATH_SIZE];
338         char temp2[PATH_SIZE];
339         char *head, *tail, *pos, *cpos, *attr, *rest;
340         int len;
341         int i;
342         int count;
343         enum subst_type {
344                 SUBST_UNKNOWN,
345                 SUBST_DEVPATH,
346                 SUBST_KERNEL,
347                 SUBST_KERNEL_NUMBER,
348                 SUBST_ID,
349                 SUBST_MAJOR,
350                 SUBST_MINOR,
351                 SUBST_RESULT,
352                 SUBST_ATTR,
353                 SUBST_PARENT,
354                 SUBST_TEMP_NODE,
355                 SUBST_ROOT,
356                 SUBST_SYS,
357                 SUBST_ENV,
358         };
359         static const struct subst_map {
360                 char *name;
361                 char fmt;
362                 enum subst_type type;
363         } map[] = {
364                 { .name = "devpath",    .fmt = 'p',     .type = SUBST_DEVPATH },
365                 { .name = "number",     .fmt = 'n',     .type = SUBST_KERNEL_NUMBER },
366                 { .name = "kernel",     .fmt = 'k',     .type = SUBST_KERNEL },
367                 { .name = "id",         .fmt = 'b',     .type = SUBST_ID },
368                 { .name = "major",      .fmt = 'M',     .type = SUBST_MAJOR },
369                 { .name = "minor",      .fmt = 'm',     .type = SUBST_MINOR },
370                 { .name = "result",     .fmt = 'c',     .type = SUBST_RESULT },
371                 { .name = "attr",       .fmt = 's',     .type = SUBST_ATTR },
372                 { .name = "sysfs",      .fmt = 's',     .type = SUBST_ATTR },
373                 { .name = "parent",     .fmt = 'P',     .type = SUBST_PARENT },
374                 { .name = "tempnode",   .fmt = 'N',     .type = SUBST_TEMP_NODE },
375                 { .name = "root",       .fmt = 'r',     .type = SUBST_ROOT },
376                 { .name = "sys",        .fmt = 'S',     .type = SUBST_SYS },
377                 { .name = "env",        .fmt = 'E',     .type = SUBST_ENV },
378                 { NULL, '\0', 0 }
379         };
380         enum subst_type type;
381         const struct subst_map *subst;
382
383         head = string;
384         while (1) {
385                 len = -1;
386                 while (head[0] != '\0') {
387                         if (head[0] == '$') {
388                                 /* substitute named variable */
389                                 if (head[1] == '\0')
390                                         break;
391                                 if (head[1] == '$') {
392                                         strlcpy(temp, head+2, sizeof(temp));
393                                         strlcpy(head+1, temp, maxsize);
394                                         head++;
395                                         continue;
396                                 }
397                                 head[0] = '\0';
398                                 for (subst = map; subst->name; subst++) {
399                                         if (strncasecmp(&head[1], subst->name, strlen(subst->name)) == 0) {
400                                                 type = subst->type;
401                                                 tail = head + strlen(subst->name)+1;
402                                                 dbg("will substitute format name '%s'", subst->name);
403                                                 goto found;
404                                         }
405                                 }
406                                 head[0] = '$';
407                                 err("unknown format variable '%s'", head);
408                         } else if (head[0] == '%') {
409                                 /* substitute format char */
410                                 if (head[1] == '\0')
411                                         break;
412                                 if (head[1] == '%') {
413                                         strlcpy(temp, head+2, sizeof(temp));
414                                         strlcpy(head+1, temp, maxsize);
415                                         head++;
416                                         continue;
417                                 }
418                                 head[0] = '\0';
419                                 tail = head+1;
420                                 len = get_format_len(&tail);
421                                 for (subst = map; subst->name; subst++) {
422                                         if (tail[0] == subst->fmt) {
423                                                 type = subst->type;
424                                                 tail++;
425                                                 dbg("will substitute format char '%c'", subst->fmt);
426                                                 goto found;
427                                         }
428                                 }
429                                 head[0] = '%';
430                                 err("unknown format char '%c'", tail[0]);
431                         }
432                         head++;
433                 }
434                 break;
435 found:
436                 attr = get_format_attribute(&tail);
437                 strlcpy(temp, tail, sizeof(temp));
438                 dbg("format=%i, string='%s', tail='%s'", type ,string, tail);
439
440                 switch (type) {
441                 case SUBST_DEVPATH:
442                         strlcat(string, udev->dev->devpath, maxsize);
443                         dbg("substitute devpath '%s'", udev->dev->devpath);
444                         break;
445                 case SUBST_KERNEL:
446                         strlcat(string, udev->dev->kernel, maxsize);
447                         dbg("substitute kernel name '%s'", udev->dev->kernel);
448                         break;
449                 case SUBST_KERNEL_NUMBER:
450                         strlcat(string, udev->dev->kernel_number, maxsize);
451                         dbg("substitute kernel number '%s'", udev->dev->kernel_number);
452                         break;
453                 case SUBST_ID:
454                         if (udev->dev_parent != NULL) {
455                                 strlcat(string, udev->dev_parent->kernel, maxsize);
456                                 dbg("substitute id '%s'", udev->dev_parent->kernel);
457                         }
458                         break;
459                 case SUBST_MAJOR:
460                         sprintf(temp2, "%d", major(udev->devt));
461                         strlcat(string, temp2, maxsize);
462                         dbg("substitute major number '%s'", temp2);
463                         break;
464                 case SUBST_MINOR:
465                         sprintf(temp2, "%d", minor(udev->devt));
466                         strlcat(string, temp2, maxsize);
467                         dbg("substitute minor number '%s'", temp2);
468                         break;
469                 case SUBST_RESULT:
470                         if (udev->program_result[0] == '\0')
471                                 break;
472                         /* get part part of the result string */
473                         i = 0;
474                         if (attr != NULL)
475                                 i = strtoul(attr, &rest, 10);
476                         if (i > 0) {
477                                 dbg("request part #%d of result string", i);
478                                 cpos = udev->program_result;
479                                 while (--i) {
480                                         while (cpos[0] != '\0' && !isspace(cpos[0]))
481                                                 cpos++;
482                                         while (isspace(cpos[0]))
483                                                 cpos++;
484                                 }
485                                 if (i > 0) {
486                                         err("requested part of result string not found");
487                                         break;
488                                 }
489                                 strlcpy(temp2, cpos, sizeof(temp2));
490                                 /* %{2+}c copies the whole string from the second part on */
491                                 if (rest[0] != '+') {
492                                         cpos = strchr(temp2, ' ');
493                                         if (cpos)
494                                                 cpos[0] = '\0';
495                                 }
496                                 strlcat(string, temp2, maxsize);
497                                 dbg("substitute part of result string '%s'", temp2);
498                         } else {
499                                 strlcat(string, udev->program_result, maxsize);
500                                 dbg("substitute result string '%s'", udev->program_result);
501                         }
502                         break;
503                 case SUBST_ATTR:
504                         if (attr == NULL)
505                                 err("missing file parameter for attr");
506                         else {
507                                 char devpath[PATH_SIZE];
508                                 char *attrib;
509                                 const char *value = NULL;
510                                 size_t size;
511
512                                 if (attr_get_by_subsys_id(attr, devpath, sizeof(devpath), &attrib)) {
513                                         if (attrib != NULL)
514                                                 value = sysfs_attr_get_value(devpath, attrib);
515                                         else
516                                                 break;
517                                 }
518
519                                 /* try the current device, other matches may have selected */
520                                 if (value == NULL && udev->dev_parent != NULL && udev->dev_parent != udev->dev)
521                                         value = sysfs_attr_get_value(udev->dev_parent->devpath, attr);
522
523                                 /* look at all devices along the chain of parents */
524                                 if (value == NULL) {
525                                         struct sysfs_device *dev_parent = udev->dev;
526
527                                         do {
528                                                 dbg("looking at '%s'", dev_parent->devpath);
529                                                 value = sysfs_attr_get_value(dev_parent->devpath, attr);
530                                                 if (value != NULL) {
531                                                         strlcpy(temp2, value, sizeof(temp2));
532                                                         break;
533                                                 }
534                                                 dev_parent = sysfs_device_get_parent(dev_parent);
535                                         } while (dev_parent != NULL);
536                                 }
537
538                                 if (value == NULL)
539                                         break;
540
541                                 /* strip trailing whitespace, and replace unwanted characters */
542                                 size = strlcpy(temp2, value, sizeof(temp2));
543                                 if (size >= sizeof(temp2))
544                                         size = sizeof(temp2)-1;
545                                 while (size > 0 && isspace(temp2[size-1]))
546                                         temp2[--size] = '\0';
547                                 count = replace_chars(temp2, ALLOWED_CHARS_INPUT);
548                                 if (count > 0)
549                                         info("%i character(s) replaced" , count);
550                                 strlcat(string, temp2, maxsize);
551                                 dbg("substitute sysfs value '%s'", temp2);
552                         }
553                         break;
554                 case SUBST_PARENT:
555                         {
556                                 struct sysfs_device *dev_parent;
557
558                                 dev_parent = sysfs_device_get_parent(udev->dev);
559                                 if (dev_parent != NULL) {
560                                         struct udevice *udev_parent;
561
562                                         dbg("found parent '%s', get the node name", dev_parent->devpath);
563                                         udev_parent = udev_device_init(NULL);
564                                         if (udev_parent != NULL) {
565                                                 /* lookup the name in the udev_db with the DEVPATH of the parent */
566                                                 if (udev_db_get_device(udev_parent, dev_parent->devpath) == 0) {
567                                                         strlcat(string, udev_parent->name, maxsize);
568                                                         dbg("substitute parent node name'%s'", udev_parent->name);
569                                                 } else
570                                                         dbg("parent not found in database");
571                                                 udev_device_cleanup(udev_parent);
572                                         }
573                                 }
574                         }
575                         break;
576                 case SUBST_TEMP_NODE:
577                         if (udev->tmp_node[0] == '\0' && major(udev->devt) > 0) {
578                                 dbg("create temporary device node for callout");
579                                 snprintf(udev->tmp_node, sizeof(udev->tmp_node), "%s/.tmp-%u-%u",
580                                          udev_root, major(udev->devt), minor(udev->devt));
581                                 udev->tmp_node[sizeof(udev->tmp_node)-1] = '\0';
582                                 udev_node_mknod(udev, udev->tmp_node, udev->devt, 0600, 0, 0);
583                         }
584                         strlcat(string, udev->tmp_node, maxsize);
585                         dbg("substitute temporary device node name '%s'", udev->tmp_node);
586                         break;
587                 case SUBST_ROOT:
588                         strlcat(string, udev_root, maxsize);
589                         dbg("substitute udev_root '%s'", udev_root);
590                         break;
591                 case SUBST_SYS:
592                         strlcat(string, sysfs_path, maxsize);
593                         dbg("substitute sysfs_path '%s'", sysfs_path);
594                         break;
595                 case SUBST_ENV:
596                         if (attr == NULL) {
597                                 dbg("missing attribute");
598                                 break;
599                         }
600                         pos = getenv(attr);
601                         if (pos == NULL) {
602                                 dbg("env '%s' not available", attr);
603                                 break;
604                         }
605                         dbg("substitute env '%s=%s'", attr, pos);
606                         strlcat(string, pos, maxsize);
607                         break;
608                 default:
609                         err("unknown substitution type=%i", type);
610                         break;
611                 }
612                 /* possibly truncate to format-char specified length */
613                 if (len >= 0 && len < (int)strlen(head)) {
614                         head[len] = '\0';
615                         dbg("truncate to %i chars, subtitution string becomes '%s'", len, head);
616                 }
617                 strlcat(string, temp, maxsize);
618         }
619 }
620
621 static char *key_val(struct udev_rule *rule, struct key *key)
622 {
623         return rule->buf + key->val_off;
624 }
625
626 static char *key_pair_name(struct udev_rule *rule, struct key_pair *pair)
627 {
628         return rule->buf + pair->key_name_off;
629 }
630
631 static int match_key(const char *key_name, struct udev_rule *rule, struct key *key, const char *val)
632 {
633         char value[PATH_SIZE];
634         char *key_value;
635         char *pos;
636         int match = 0;
637
638         if (key->operation != KEY_OP_MATCH &&
639             key->operation != KEY_OP_NOMATCH)
640                 return 0;
641
642         /* look for a matching string, parts are separated by '|' */
643         strlcpy(value, rule->buf + key->val_off, sizeof(value));
644         key_value = value;
645         dbg("key %s value='%s'", key_name, key_value);
646         while (key_value) {
647                 pos = strchr(key_value, '|');
648                 if (pos) {
649                         pos[0] = '\0';
650                         pos++;
651                 }
652
653                 dbg("match %s '%s' <-> '%s'", key_name, key_value, val);
654                 match = (fnmatch(key_value, val, 0) == 0);
655                 if (match)
656                         break;
657
658                 key_value = pos;
659         }
660
661         if (match && (key->operation == KEY_OP_MATCH)) {
662                 dbg("%s is true (matching value)", key_name);
663                 return 0;
664         }
665         if (!match && (key->operation == KEY_OP_NOMATCH)) {
666                 dbg("%s is true (non-matching value)", key_name);
667                 return 0;
668         }
669         return -1;
670 }
671
672 /* match a single rule against a given device and possibly its parent devices */
673 static int match_rule(struct udevice *udev, struct udev_rule *rule)
674 {
675         int i;
676
677         if (match_key("ACTION", rule, &rule->action, udev->action))
678                 goto nomatch;
679
680         if (match_key("KERNEL", rule, &rule->kernel, udev->dev->kernel))
681                 goto nomatch;
682
683         if (match_key("SUBSYSTEM", rule, &rule->subsystem, udev->dev->subsystem))
684                 goto nomatch;
685
686         if (match_key("DEVPATH", rule, &rule->devpath, udev->dev->devpath))
687                 goto nomatch;
688
689         if (match_key("DRIVER", rule, &rule->driver, udev->dev->driver))
690                 goto nomatch;
691
692         /* match NAME against a value assigned by an earlier rule */
693         if (match_key("NAME", rule, &rule->name, udev->name))
694                 goto nomatch;
695
696         for (i = 0; i < rule->env.count; i++) {
697                 struct key_pair *pair = &rule->env.keys[i];
698
699                 /* we only check for matches, assignments will be handled later */
700                 if (pair->key.operation == KEY_OP_MATCH ||
701                     pair->key.operation == KEY_OP_NOMATCH) {
702                         const char *key_name = key_pair_name(rule, pair);
703                         const char *value = getenv(key_name);
704
705                         if (!value) {
706                                 dbg("ENV{'%s'} is not set, treat as empty", key_name);
707                                 value = "";
708                         }
709                         if (match_key("ENV", rule, &pair->key, value))
710                                 goto nomatch;
711                 }
712         }
713
714         if (rule->test.operation != KEY_OP_UNSET) {
715                 char filename[PATH_SIZE];
716                 char devpath[PATH_SIZE];
717                 char *attr;
718                 struct stat statbuf;
719                 int match;
720
721                 strlcpy(filename, key_val(rule, &rule->test), sizeof(filename));
722                 udev_rules_apply_format(udev, filename, sizeof(filename));
723
724                 if (attr_get_by_subsys_id(filename, devpath, sizeof(devpath), &attr)) {
725                         strlcpy(filename, sysfs_path, sizeof(filename));
726                         strlcat(filename, devpath, sizeof(filename));
727                         if (attr != NULL) {
728                                 strlcat(filename, "/", sizeof(filename));
729                                 strlcat(filename, attr, sizeof(filename));
730                         }
731                 }
732
733                 match = (stat(filename, &statbuf) == 0);
734                 info("'%s' %s", filename, match ? "exists" : "does not exist");
735                 if (match && rule->test_mode_mask > 0) {
736                         match = ((statbuf.st_mode & rule->test_mode_mask) > 0);
737                         info("'%s' has mode=%#o and %s %#o", filename, statbuf.st_mode,
738                              match ? "matches" : "does not match",
739                              rule->test_mode_mask);
740                 }
741                 if (match && rule->test.operation == KEY_OP_NOMATCH)
742                         goto nomatch;
743                 if (!match && rule->test.operation == KEY_OP_MATCH)
744                         goto nomatch;
745                 dbg("TEST key is true");
746         }
747
748         if (rule->wait_for_sysfs.operation != KEY_OP_UNSET) {
749                 int found;
750
751                 found = (wait_for_sysfs(udev, key_val(rule, &rule->wait_for_sysfs), 3) == 0);
752                 if (!found && (rule->wait_for_sysfs.operation != KEY_OP_NOMATCH))
753                         goto nomatch;
754         }
755
756         /* check for matching sysfs attribute pairs */
757         for (i = 0; i < rule->attr.count; i++) {
758                 struct key_pair *pair = &rule->attr.keys[i];
759
760                 if (pair->key.operation == KEY_OP_MATCH ||
761                     pair->key.operation == KEY_OP_NOMATCH) {
762                         const char *key_name = key_pair_name(rule, pair);
763                         const char *key_value = key_val(rule, &pair->key);
764                         char devpath[PATH_SIZE];
765                         char *attrib;
766                         const char *value = NULL;
767                         char val[VALUE_SIZE];
768                         size_t len;
769
770                         if (attr_get_by_subsys_id(key_name, devpath, sizeof(devpath), &attrib)) {
771                                 if (attrib != NULL)
772                                         value = sysfs_attr_get_value(devpath, attrib);
773                                 else
774                                         goto nomatch;
775                         }
776                         if (value == NULL)
777                                 value = sysfs_attr_get_value(udev->dev->devpath, key_name);
778                         if (value == NULL)
779                                 goto nomatch;
780                         strlcpy(val, value, sizeof(val));
781
782                         /* strip trailing whitespace of value, if not asked to match for it */
783                         len = strlen(key_value);
784                         if (len > 0 && !isspace(key_value[len-1])) {
785                                 len = strlen(val);
786                                 while (len > 0 && isspace(val[len-1]))
787                                         val[--len] = '\0';
788                                 dbg("removed %zi trailing whitespace chars from '%s'", strlen(val)-len, val);
789                         }
790
791                         if (match_key("ATTR", rule, &pair->key, val))
792                                 goto nomatch;
793                 }
794         }
795
796         /* walk up the chain of parent devices and find a match */
797         udev->dev_parent = udev->dev;
798         while (1) {
799                 /* check for matching kernel device name */
800                 if (match_key("KERNELS", rule, &rule->kernels, udev->dev_parent->kernel))
801                         goto try_parent;
802
803                 /* check for matching subsystem value */
804                 if (match_key("SUBSYSTEMS", rule, &rule->subsystems, udev->dev_parent->subsystem))
805                         goto try_parent;
806
807                 /* check for matching driver */
808                 if (match_key("DRIVERS", rule, &rule->drivers, udev->dev_parent->driver))
809                         goto try_parent;
810
811                 /* check for matching sysfs attribute pairs */
812                 for (i = 0; i < rule->attrs.count; i++) {
813                         struct key_pair *pair = &rule->attrs.keys[i];
814
815                         if (pair->key.operation == KEY_OP_MATCH ||
816                             pair->key.operation == KEY_OP_NOMATCH) {
817                                 const char *key_name = key_pair_name(rule, pair);
818                                 const char *key_value = key_val(rule, &pair->key);
819                                 const char *value;
820                                 char val[VALUE_SIZE];
821                                 size_t len;
822
823                                 value = sysfs_attr_get_value(udev->dev_parent->devpath, key_name);
824                                 if (value == NULL)
825                                         value = sysfs_attr_get_value(udev->dev->devpath, key_name);
826                                 if (value == NULL)
827                                         goto try_parent;
828                                 strlcpy(val, value, sizeof(val));
829
830                                 /* strip trailing whitespace of value, if not asked to match for it */
831                                 len = strlen(key_value);
832                                 if (len > 0 && !isspace(key_value[len-1])) {
833                                         len = strlen(val);
834                                         while (len > 0 && isspace(val[len-1]))
835                                                 val[--len] = '\0';
836                                         dbg("removed %zi trailing whitespace chars from '%s'", strlen(val)-len, val);
837                                 }
838
839                                 if (match_key("ATTRS", rule, &pair->key, val))
840                                         goto try_parent;
841                         }
842                 }
843
844                 /* found matching device  */
845                 break;
846 try_parent:
847                 /* move to parent device */
848                 dbg("try parent sysfs device");
849                 udev->dev_parent = sysfs_device_get_parent(udev->dev_parent);
850                 if (udev->dev_parent == NULL)
851                         goto nomatch;
852                 dbg("looking at dev_parent->devpath='%s'", udev->dev_parent->devpath);
853                 dbg("looking at dev_parent->kernel='%s'", udev->dev_parent->kernel);
854         }
855
856         /* execute external program */
857         if (rule->program.operation != KEY_OP_UNSET) {
858                 char program[PATH_SIZE];
859                 char result[PATH_SIZE];
860
861                 strlcpy(program, key_val(rule, &rule->program), sizeof(program));
862                 udev_rules_apply_format(udev, program, sizeof(program));
863                 if (run_program(program, udev->dev->subsystem, result, sizeof(result), NULL) != 0) {
864                         dbg("PROGRAM is false");
865                         udev->program_result[0] = '\0';
866                         if (rule->program.operation != KEY_OP_NOMATCH)
867                                 goto nomatch;
868                 } else {
869                         int count;
870
871                         dbg("PROGRAM matches");
872                         remove_trailing_chars(result, '\n');
873                         if (rule->string_escape == ESCAPE_UNSET ||
874                             rule->string_escape == ESCAPE_REPLACE) {
875                                 count = replace_chars(result, ALLOWED_CHARS_INPUT);
876                                 if (count > 0)
877                                         info("%i character(s) replaced" , count);
878                         }
879                         dbg("result is '%s'", result);
880                         strlcpy(udev->program_result, result, sizeof(udev->program_result));
881                         dbg("PROGRAM returned successful");
882                         if (rule->program.operation == KEY_OP_NOMATCH)
883                                 goto nomatch;
884                 }
885                 dbg("PROGRAM key is true");
886         }
887
888         /* check for matching result of external program */
889         if (match_key("RESULT", rule, &rule->result, udev->program_result))
890                 goto nomatch;
891
892         /* import variables returned from program or or file into environment */
893         if (rule->import.operation != KEY_OP_UNSET) {
894                 char import[PATH_SIZE];
895                 int rc = -1;
896
897                 strlcpy(import, key_val(rule, &rule->import), sizeof(import));
898                 udev_rules_apply_format(udev, import, sizeof(import));
899                 dbg("check for IMPORT import='%s'", import);
900                 if (rule->import_type == IMPORT_PROGRAM) {
901                         rc = import_program_into_env(udev, import);
902                 } else if (rule->import_type == IMPORT_FILE) {
903                         dbg("import file import='%s'", import);
904                         rc = import_file_into_env(udev, import);
905                 } else if (rule->import_type == IMPORT_PARENT) {
906                         dbg("import parent import='%s'", import);
907                         rc = import_parent_into_env(udev, import);
908                 }
909                 if (rc != 0) {
910                         dbg("IMPORT failed");
911                         if (rule->import.operation != KEY_OP_NOMATCH)
912                                 goto nomatch;
913                 } else
914                         dbg("IMPORT '%s' imported", key_val(rule, &rule->import));
915                 dbg("IMPORT key is true");
916         }
917
918         /* rule matches, if we have ENV assignments export it */
919         for (i = 0; i < rule->env.count; i++) {
920                 struct key_pair *pair = &rule->env.keys[i];
921
922                 if (pair->key.operation == KEY_OP_ASSIGN) {
923                         char temp_value[NAME_SIZE];
924                         const char *key_name = key_pair_name(rule, pair);
925                         const char *value = key_val(rule, &pair->key);
926
927                         /* make sure we don't write to the same string we possibly read from */
928                         strlcpy(temp_value, value, sizeof(temp_value));
929                         udev_rules_apply_format(udev, temp_value, NAME_SIZE);
930
931                         if (temp_value[0] == '\0') {
932                                 name_list_key_remove(&udev->env_list, key_name);
933                                 unsetenv(key_name);
934                                 info("unset ENV '%s'", key_name);
935                         } else {
936                                 struct name_entry *entry;
937
938                                 entry = name_list_key_add(&udev->env_list, key_name, temp_value);
939                                 if (entry == NULL)
940                                         break;
941                                 putenv(entry->name);
942                                 info("set ENV '%s'", entry->name);
943                         }
944                 }
945         }
946
947         /* if we have ATTR assignments, write value to sysfs file */
948         for (i = 0; i < rule->attr.count; i++) {
949                 struct key_pair *pair = &rule->attr.keys[i];
950
951                 if (pair->key.operation == KEY_OP_ASSIGN) {
952                         const char *key_name = key_pair_name(rule, pair);
953                         char devpath[PATH_SIZE];
954                         char *attrib;
955                         char attr[PATH_SIZE] = "";
956                         char value[NAME_SIZE];
957                         FILE *f;
958
959                         if (attr_get_by_subsys_id(key_name, devpath, sizeof(devpath), &attrib)) {
960                                 if (attrib != NULL) {
961                                         strlcpy(attr, sysfs_path, sizeof(attr));
962                                         strlcat(attr, devpath, sizeof(attr));
963                                         strlcat(attr, "/", sizeof(attr));
964                                         strlcat(attr, attrib, sizeof(attr));
965                                 }
966                         }
967
968                         if (attr[0] == '\0') {
969                                 strlcpy(attr, sysfs_path, sizeof(attr));
970                                 strlcat(attr, udev->dev->devpath, sizeof(attr));
971                                 strlcat(attr, "/", sizeof(attr));
972                                 strlcat(attr, key_name, sizeof(attr));
973                         }
974
975                         strlcpy(value, key_val(rule, &pair->key), sizeof(value));
976                         udev_rules_apply_format(udev, value, sizeof(value));
977                         info("writing '%s' to sysfs file '%s'", value, attr);
978                         f = fopen(attr, "w");
979                         if (f != NULL) {
980                                 if (!udev->test_run)
981                                         if (fprintf(f, "%s", value) <= 0)
982                                                 err("error writing ATTR{%s}: %s", attr, strerror(errno));
983                                 fclose(f);
984                         } else
985                                 err("error opening ATTR{%s} for writing: %s", attr, strerror(errno));
986                 }
987         }
988         return 0;
989
990 nomatch:
991         return -1;
992 }
993
994 int udev_rules_get_name(struct udev_rules *rules, struct udevice *udev)
995 {
996         struct udev_rule *rule;
997         int name_set = 0;
998
999         dbg("udev->dev->devpath='%s'", udev->dev->devpath);
1000         dbg("udev->dev->kernel='%s'", udev->dev->kernel);
1001
1002         /* look for a matching rule to apply */
1003         udev_rules_iter_init(rules);
1004         while (1) {
1005                 rule = udev_rules_iter_next(rules);
1006                 if (rule == NULL)
1007                         break;
1008
1009                 if (name_set &&
1010                     (rule->name.operation == KEY_OP_ASSIGN ||
1011                      rule->name.operation == KEY_OP_ASSIGN_FINAL ||
1012                      rule->name.operation == KEY_OP_ADD)) {
1013                         dbg("node name already set, rule ignored");
1014                         continue;
1015                 }
1016
1017                 dbg("process rule");
1018                 if (match_rule(udev, rule) == 0) {
1019                         /* apply options */
1020                         if (rule->ignore_device) {
1021                                 info("rule applied, '%s' is ignored", udev->dev->kernel);
1022                                 udev->ignore_device = 1;
1023                                 return 0;
1024                         }
1025                         if (rule->ignore_remove) {
1026                                 udev->ignore_remove = 1;
1027                                 dbg("remove event should be ignored");
1028                         }
1029                         if (rule->link_priority != 0) {
1030                                 udev->link_priority = rule->link_priority;
1031                                 info("link_priority=%i", udev->link_priority);
1032                         }
1033                         /* apply all_partitions option only at a main block device */
1034                         if (rule->partitions &&
1035                             strcmp(udev->dev->subsystem, "block") == 0 && udev->dev->kernel_number[0] == '\0') {
1036                                 udev->partitions = rule->partitions;
1037                                 dbg("creation of partition nodes requested");
1038                         }
1039
1040                         /* apply permissions */
1041                         if (!udev->mode_final && rule->mode != 0000) {
1042                                 if (rule->mode_operation == KEY_OP_ASSIGN_FINAL)
1043                                         udev->mode_final = 1;
1044                                 udev->mode = rule->mode;
1045                                 dbg("applied mode=%#o to '%s'", rule->mode, udev->dev->kernel);
1046                         }
1047                         if (!udev->owner_final && rule->owner.operation != KEY_OP_UNSET) {
1048                                 if (rule->owner.operation == KEY_OP_ASSIGN_FINAL)
1049                                         udev->owner_final = 1;
1050                                 strlcpy(udev->owner, key_val(rule, &rule->owner), sizeof(udev->owner));
1051                                 udev_rules_apply_format(udev, udev->owner, sizeof(udev->owner));
1052                                 dbg("applied owner='%s' to '%s'", udev->owner, udev->dev->kernel);
1053                         }
1054                         if (!udev->group_final && rule->group.operation != KEY_OP_UNSET) {
1055                                 if (rule->group.operation == KEY_OP_ASSIGN_FINAL)
1056                                         udev->group_final = 1;
1057                                 strlcpy(udev->group, key_val(rule, &rule->group), sizeof(udev->group));
1058                                 udev_rules_apply_format(udev, udev->group, sizeof(udev->group));
1059                                 dbg("applied group='%s' to '%s'", udev->group, udev->dev->kernel);
1060                         }
1061
1062                         /* collect symlinks */
1063                         if (!udev->symlink_final && rule->symlink.operation != KEY_OP_UNSET) {
1064                                 char temp[PATH_SIZE];
1065                                 char *pos, *next;
1066                                 int count;
1067
1068                                 if (rule->symlink.operation == KEY_OP_ASSIGN_FINAL)
1069                                         udev->symlink_final = 1;
1070                                 if (rule->symlink.operation == KEY_OP_ASSIGN || rule->symlink.operation == KEY_OP_ASSIGN_FINAL) {
1071                                         info("reset symlink list");
1072                                         name_list_cleanup(&udev->symlink_list);
1073                                 }
1074                                 /* allow  multiple symlinks separated by spaces */
1075                                 strlcpy(temp, key_val(rule, &rule->symlink), sizeof(temp));
1076                                 udev_rules_apply_format(udev, temp, sizeof(temp));
1077                                 if (rule->string_escape == ESCAPE_UNSET ||
1078                                     rule->string_escape == ESCAPE_REPLACE) {
1079                                         count = replace_chars(temp, ALLOWED_CHARS_FILE " ");
1080                                         if (count > 0)
1081                                                 info("%i character(s) replaced" , count);
1082                                 }
1083                                 dbg("rule applied, added symlink(s) '%s'", temp);
1084                                 pos = temp;
1085                                 while (isspace(pos[0]))
1086                                         pos++;
1087                                 next = strchr(pos, ' ');
1088                                 while (next) {
1089                                         next[0] = '\0';
1090                                         info("add symlink '%s'", pos);
1091                                         name_list_add(&udev->symlink_list, pos, 0);
1092                                         while (isspace(next[1]))
1093                                                 next++;
1094                                         pos = &next[1];
1095                                         next = strchr(pos, ' ');
1096                                 }
1097                                 if (pos[0] != '\0') {
1098                                         info("add symlink '%s'", pos);
1099                                         name_list_add(&udev->symlink_list, pos, 0);
1100                                 }
1101                         }
1102
1103                         /* set name, later rules with name set will be ignored */
1104                         if (rule->name.operation == KEY_OP_ASSIGN ||
1105                             rule->name.operation == KEY_OP_ASSIGN_FINAL ||
1106                             rule->name.operation == KEY_OP_ADD) {
1107                                 int count;
1108
1109                                 name_set = 1;
1110                                 strlcpy(udev->name, key_val(rule, &rule->name), sizeof(udev->name));
1111                                 udev_rules_apply_format(udev, udev->name, sizeof(udev->name));
1112                                 if (rule->string_escape == ESCAPE_UNSET ||
1113                                     rule->string_escape == ESCAPE_REPLACE) {
1114                                         count = replace_chars(udev->name, ALLOWED_CHARS_FILE);
1115                                         if (count > 0)
1116                                                 info("%i character(s) replaced", count);
1117                                 }
1118
1119                                 info("rule applied, '%s' becomes '%s'", udev->dev->kernel, udev->name);
1120                                 if (strcmp(udev->dev->subsystem, "net") != 0)
1121                                         dbg("name, '%s' is going to have owner='%s', group='%s', mode=%#o partitions=%i",
1122                                             udev->name, udev->owner, udev->group, udev->mode, udev->partitions);
1123                         }
1124
1125                         if (!udev->run_final && rule->run.operation != KEY_OP_UNSET) {
1126                                 struct name_entry *entry;
1127
1128                                 if (rule->run.operation == KEY_OP_ASSIGN_FINAL)
1129                                         udev->run_final = 1;
1130                                 if (rule->run.operation == KEY_OP_ASSIGN || rule->run.operation == KEY_OP_ASSIGN_FINAL) {
1131                                         info("reset run list");
1132                                         name_list_cleanup(&udev->run_list);
1133                                 }
1134                                 dbg("add run '%s'", key_val(rule, &rule->run));
1135                                 entry = name_list_add(&udev->run_list, key_val(rule, &rule->run), 0);
1136                                 if (rule->run_ignore_error)
1137                                         entry->ignore_error = 1;
1138                         }
1139
1140                         if (rule->last_rule) {
1141                                 dbg("last rule to be applied");
1142                                 break;
1143                         }
1144
1145                         if (rule->goto_label.operation != KEY_OP_UNSET) {
1146                                 dbg("moving forward to label '%s'", key_val(rule, &rule->goto_label));
1147                                 udev_rules_iter_label(rules, key_val(rule, &rule->goto_label));
1148                         }
1149                 }
1150         }
1151
1152         if (!name_set) {
1153                 strlcpy(udev->name, udev->dev->kernel, sizeof(udev->name));
1154                 info("no node name set, will use kernel name '%s'", udev->name);
1155         }
1156
1157         if (udev->tmp_node[0] != '\0') {
1158                 dbg("removing temporary device node");
1159                 unlink_secure(udev->tmp_node);
1160                 udev->tmp_node[0] = '\0';
1161         }
1162
1163         return 0;
1164 }
1165
1166 int udev_rules_get_run(struct udev_rules *rules, struct udevice *udev)
1167 {
1168         struct udev_rule *rule;
1169
1170         dbg("udev->kernel='%s'", udev->dev->kernel);
1171
1172         /* look for a matching rule to apply */
1173         udev_rules_iter_init(rules);
1174         while (1) {
1175                 rule = udev_rules_iter_next(rules);
1176                 if (rule == NULL)
1177                         break;
1178
1179                 dbg("process rule");
1180                 if (rule->name.operation != KEY_OP_UNSET || rule->symlink.operation != KEY_OP_UNSET ||
1181                     rule->mode_operation != KEY_OP_UNSET || rule->owner.operation != KEY_OP_UNSET ||
1182                     rule->group.operation != KEY_OP_UNSET) {
1183                         dbg("skip rule that names a device");
1184                         continue;
1185                 }
1186
1187                 if (match_rule(udev, rule) == 0) {
1188                         if (rule->ignore_device) {
1189                                 info("rule applied, '%s' is ignored", udev->dev->kernel);
1190                                 udev->ignore_device = 1;
1191                                 return 0;
1192                         }
1193
1194                         if (!udev->run_final && rule->run.operation != KEY_OP_UNSET) {
1195                                 struct name_entry *entry;
1196
1197                                 if (rule->run.operation == KEY_OP_ASSIGN ||
1198                                     rule->run.operation == KEY_OP_ASSIGN_FINAL) {
1199                                         info("reset run list");
1200                                         name_list_cleanup(&udev->run_list);
1201                                 }
1202                                 dbg("add run '%s'", key_val(rule, &rule->run));
1203                                 entry = name_list_add(&udev->run_list, key_val(rule, &rule->run), 0);
1204                                 if (rule->run_ignore_error)
1205                                         entry->ignore_error = 1;
1206                                 if (rule->run.operation == KEY_OP_ASSIGN_FINAL)
1207                                         break;
1208                         }
1209
1210                         if (rule->last_rule) {
1211                                 dbg("last rule to be applied");
1212                                 break;
1213                         }
1214
1215                         if (rule->goto_label.operation != KEY_OP_UNSET) {
1216                                 dbg("moving forward to label '%s'", key_val(rule, &rule->goto_label));
1217                                 udev_rules_iter_label(rules, key_val(rule, &rule->goto_label));
1218                         }
1219                 }
1220         }
1221
1222         return 0;
1223 }