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