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