chiark / gitweb /
merge udev-rules.c and udev-rules-parse.c
[elogind.git] / udev / udev-rules.c
1 /*
2  * Copyright (C) 2003 Greg Kroah-Hartman <greg@kroah.com>
3  * Copyright (C) 2003-2008 Kay Sievers <kay.sievers@vrfy.org>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 #include <stddef.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <stdio.h>
23 #include <fcntl.h>
24 #include <ctype.h>
25 #include <unistd.h>
26 #include <errno.h>
27 #include <syslog.h>
28 #include <dirent.h>
29 #include <fnmatch.h>
30 #include <sys/socket.h>
31 #include <sys/un.h>
32 #include <sys/wait.h>
33 #include <sys/stat.h>
34
35 #include "udev.h"
36
37 #define PAIRS_MAX               5
38
39 enum key_operation {
40         KEY_OP_UNSET,
41         KEY_OP_MATCH,
42         KEY_OP_NOMATCH,
43         KEY_OP_ADD,
44         KEY_OP_ASSIGN,
45         KEY_OP_ASSIGN_FINAL,
46 };
47
48 struct key {
49         enum key_operation operation;
50         size_t val_off;
51 };
52
53 struct key_pair {
54         struct key key;
55         size_t key_name_off;
56 };
57
58 struct key_pairs {
59         int count;
60         struct key_pair keys[PAIRS_MAX];
61 };
62
63 enum import_type {
64         IMPORT_UNSET,
65         IMPORT_PROGRAM,
66         IMPORT_FILE,
67         IMPORT_PARENT,
68 };
69
70 enum escape_type {
71         ESCAPE_UNSET,
72         ESCAPE_NONE,
73         ESCAPE_REPLACE,
74 };
75
76 struct udev_rule {
77         struct key action;
78         struct key devpath;
79         struct key kernel;
80         struct key subsystem;
81         struct key driver;
82         struct key_pairs attr;
83
84         struct key kernels;
85         struct key subsystems;
86         struct key drivers;
87         struct key_pairs attrs;
88
89         struct key_pairs env;
90         struct key program;
91         struct key result;
92         struct key import;
93         enum import_type import_type;
94         struct key test;
95         mode_t test_mode_mask;
96         struct key run;
97         struct key wait_for;
98         struct key label;
99         struct key goto_label;
100         size_t goto_rule_off;
101
102         struct key name;
103         struct key symlink;
104         struct key symlink_match;
105         struct key owner;
106         struct key group;
107         struct key mode;
108         enum escape_type string_escape;
109
110         unsigned int link_priority;
111         int event_timeout;
112         unsigned int partitions;
113         unsigned int last_rule:1,
114                      run_ignore_error:1,
115                      ignore_device:1,
116                      ignore_remove:1;
117
118         size_t bufsize;
119         char buf[];
120 };
121
122 struct udev_rules_iter {
123         struct udev_rules *rules;
124         size_t current;
125 };
126
127 static void udev_rules_iter_init(struct udev_rules_iter *iter, struct udev_rules *rules)
128 {
129         dbg(rules->udev, "bufsize=%zi\n", rules->bufsize);
130         iter->rules = rules;
131         iter->current = 0;
132 }
133
134 static struct udev_rule *udev_rules_iter_next(struct udev_rules_iter *iter)
135 {
136         struct udev_rules *rules;
137         struct udev_rule *rule;
138
139         rules = iter->rules;
140         if (!rules)
141                 return NULL;
142
143         dbg(rules->udev, "current=%zi\n", iter->current);
144         if (iter->current >= rules->bufsize) {
145                 dbg(rules->udev, "no more rules\n");
146                 return NULL;
147         }
148
149         /* get next rule */
150         rule = (struct udev_rule *) (rules->buf + iter->current);
151         iter->current += sizeof(struct udev_rule) + rule->bufsize;
152
153         return rule;
154 }
155
156 static struct udev_rule *udev_rules_iter_goto(struct udev_rules_iter *iter, size_t rule_off)
157 {
158         struct udev_rules *rules = iter->rules;
159         struct udev_rule *rule;
160
161         dbg(rules->udev, "current=%zi\n", iter->current);
162         iter->current = rule_off;
163         rule = (struct udev_rule *) (rules->buf + iter->current);
164
165         return rule;
166 }
167
168 static size_t find_label(const struct udev_rules_iter *iter, const char *label)
169 {
170         struct udev_rule *rule;
171         struct udev_rules *rules = iter->rules;
172         size_t current = iter->current;
173
174 next:
175         dbg(rules->udev, "current=%zi\n", current);
176         if (current >= rules->bufsize) {
177                 dbg(rules->udev, "LABEL='%s' not found\n", label);
178                 return 0;
179         }
180         rule = (struct udev_rule *) (rules->buf + current);
181
182         if (strcmp(&rule->buf[rule->label.val_off], label) != 0) {
183                 dbg(rules->udev, "moving forward, looking for label '%s'\n", label);
184                 current += sizeof(struct udev_rule) + rule->bufsize;
185                 goto next;
186         }
187
188         dbg(rules->udev, "found label '%s'\n", label);
189         return current;
190 }
191
192 /* extract possible {attr} and move str behind it */
193 static char *get_format_attribute(struct udev *udev, char **str)
194 {
195         char *pos;
196         char *attr = NULL;
197
198         if (*str[0] == '{') {
199                 pos = strchr(*str, '}');
200                 if (pos == NULL) {
201                         err(udev, "missing closing brace for format\n");
202                         return NULL;
203                 }
204                 pos[0] = '\0';
205                 attr = *str+1;
206                 *str = pos+1;
207                 dbg(udev, "attribute='%s', str='%s'\n", attr, *str);
208         }
209         return attr;
210 }
211
212 /* extract possible format length and move str behind it*/
213 static int get_format_len(struct udev *udev, char **str)
214 {
215         int num;
216         char *tail;
217
218         if (isdigit(*str[0])) {
219                 num = (int) strtoul(*str, &tail, 10);
220                 if (num > 0) {
221                         *str = tail;
222                         dbg(udev, "format length=%i\n", num);
223                         return num;
224                 } else {
225                         err(udev, "format parsing error '%s'\n", *str);
226                 }
227         }
228         return -1;
229 }
230
231 static int run_program(struct udev_device *dev, const char *command,
232                        char *result, size_t ressize, size_t *reslen)
233 {
234         struct udev *udev = udev_device_get_udev(dev);
235         int status;
236         char **envp;
237         int outpipe[2] = {-1, -1};
238         int errpipe[2] = {-1, -1};
239         pid_t pid;
240         char arg[UTIL_PATH_SIZE];
241         char program[UTIL_PATH_SIZE];
242         char *argv[(sizeof(arg) / 2) + 1];
243         int devnull;
244         int i;
245         int err = 0;
246
247         /* build argv from command */
248         util_strlcpy(arg, command, sizeof(arg));
249         i = 0;
250         if (strchr(arg, ' ') != NULL) {
251                 char *pos = arg;
252
253                 while (pos != NULL && pos[0] != '\0') {
254                         if (pos[0] == '\'') {
255                                 /* do not separate quotes */
256                                 pos++;
257                                 argv[i] = strsep(&pos, "\'");
258                                 while (pos != NULL && pos[0] == ' ')
259                                         pos++;
260                         } else {
261                                 argv[i] = strsep(&pos, " ");
262                         }
263                         dbg(udev, "arg[%i] '%s'\n", i, argv[i]);
264                         i++;
265                 }
266                 argv[i] = NULL;
267         } else {
268                 argv[0] = arg;
269                 argv[1] = NULL;
270         }
271         info(udev, "'%s'\n", command);
272
273         /* prepare pipes from child to parent */
274         if (result != NULL || udev_get_log_priority(udev) >= LOG_INFO) {
275                 if (pipe(outpipe) != 0) {
276                         err(udev, "pipe failed: %m\n");
277                         return -1;
278                 }
279         }
280         if (udev_get_log_priority(udev) >= LOG_INFO) {
281                 if (pipe(errpipe) != 0) {
282                         err(udev, "pipe failed: %m\n");
283                         return -1;
284                 }
285         }
286
287         /* allow programs in /lib/udev/ to be called without the path */
288         if (strchr(argv[0], '/') == NULL) {
289                 util_strlcpy(program, UDEV_PREFIX "/lib/udev/", sizeof(program));
290                 util_strlcat(program, argv[0], sizeof(program));
291                 argv[0] = program;
292         }
293
294         envp = udev_device_get_properties_envp(dev);
295
296         pid = fork();
297         switch(pid) {
298         case 0:
299                 /* child closes parent ends of pipes */
300                 if (outpipe[READ_END] > 0)
301                         close(outpipe[READ_END]);
302                 if (errpipe[READ_END] > 0)
303                         close(errpipe[READ_END]);
304
305                 /* discard child output or connect to pipe */
306                 devnull = open("/dev/null", O_RDWR);
307                 if (devnull > 0) {
308                         dup2(devnull, STDIN_FILENO);
309                         if (outpipe[WRITE_END] < 0)
310                                 dup2(devnull, STDOUT_FILENO);
311                         if (errpipe[WRITE_END] < 0)
312                                 dup2(devnull, STDERR_FILENO);
313                         close(devnull);
314                 } else
315                         err(udev, "open /dev/null failed: %m\n");
316                 if (outpipe[WRITE_END] > 0) {
317                         dup2(outpipe[WRITE_END], STDOUT_FILENO);
318                         close(outpipe[WRITE_END]);
319                 }
320                 if (errpipe[WRITE_END] > 0) {
321                         dup2(errpipe[WRITE_END], STDERR_FILENO);
322                         close(errpipe[WRITE_END]);
323                 }
324                 execve(argv[0], argv, envp);
325                 if (errno == ENOENT || errno == ENOTDIR) {
326                         /* may be on a filesytem which is not mounted right now */
327                         info(udev, "program '%s' not found\n", argv[0]);
328                 } else {
329                         /* other problems */
330                         err(udev, "exec of program '%s' failed\n", argv[0]);
331                 }
332                 _exit(1);
333         case -1:
334                 err(udev, "fork of '%s' failed: %m\n", argv[0]);
335                 return -1;
336         default:
337                 /* read from child if requested */
338                 if (outpipe[READ_END] > 0 || errpipe[READ_END] > 0) {
339                         ssize_t count;
340                         size_t respos = 0;
341
342                         /* parent closes child ends of pipes */
343                         if (outpipe[WRITE_END] > 0)
344                                 close(outpipe[WRITE_END]);
345                         if (errpipe[WRITE_END] > 0)
346                                 close(errpipe[WRITE_END]);
347
348                         /* read child output */
349                         while (outpipe[READ_END] > 0 || errpipe[READ_END] > 0) {
350                                 int fdcount;
351                                 fd_set readfds;
352
353                                 FD_ZERO(&readfds);
354                                 if (outpipe[READ_END] > 0)
355                                         FD_SET(outpipe[READ_END], &readfds);
356                                 if (errpipe[READ_END] > 0)
357                                         FD_SET(errpipe[READ_END], &readfds);
358                                 fdcount = select(UDEV_MAX(outpipe[READ_END], errpipe[READ_END])+1, &readfds, NULL, NULL, NULL);
359                                 if (fdcount < 0) {
360                                         if (errno == EINTR)
361                                                 continue;
362                                         err = -1;
363                                         break;
364                                 }
365
366                                 /* get stdout */
367                                 if (outpipe[READ_END] > 0 && FD_ISSET(outpipe[READ_END], &readfds)) {
368                                         char inbuf[1024];
369                                         char *pos;
370                                         char *line;
371
372                                         count = read(outpipe[READ_END], inbuf, sizeof(inbuf)-1);
373                                         if (count <= 0) {
374                                                 close(outpipe[READ_END]);
375                                                 outpipe[READ_END] = -1;
376                                                 if (count < 0) {
377                                                         err(udev, "stdin read failed: %m\n");
378                                                         err = -1;
379                                                 }
380                                                 continue;
381                                         }
382                                         inbuf[count] = '\0';
383
384                                         /* store result for rule processing */
385                                         if (result) {
386                                                 if (respos + count < ressize) {
387                                                         memcpy(&result[respos], inbuf, count);
388                                                         respos += count;
389                                                 } else {
390                                                         err(udev, "ressize %ld too short\n", (long)ressize);
391                                                         err = -1;
392                                                 }
393                                         }
394                                         pos = inbuf;
395                                         while ((line = strsep(&pos, "\n")))
396                                                 if (pos || line[0] != '\0')
397                                                         info(udev, "'%s' (stdout) '%s'\n", argv[0], line);
398                                 }
399
400                                 /* get stderr */
401                                 if (errpipe[READ_END] > 0 && FD_ISSET(errpipe[READ_END], &readfds)) {
402                                         char errbuf[1024];
403                                         char *pos;
404                                         char *line;
405
406                                         count = read(errpipe[READ_END], errbuf, sizeof(errbuf)-1);
407                                         if (count <= 0) {
408                                                 close(errpipe[READ_END]);
409                                                 errpipe[READ_END] = -1;
410                                                 if (count < 0)
411                                                         err(udev, "stderr read failed: %m\n");
412                                                 continue;
413                                         }
414                                         errbuf[count] = '\0';
415                                         pos = errbuf;
416                                         while ((line = strsep(&pos, "\n")))
417                                                 if (pos || line[0] != '\0')
418                                                         info(udev, "'%s' (stderr) '%s'\n", argv[0], line);
419                                 }
420                         }
421                         if (outpipe[READ_END] > 0)
422                                 close(outpipe[READ_END]);
423                         if (errpipe[READ_END] > 0)
424                                 close(errpipe[READ_END]);
425
426                         /* return the childs stdout string */
427                         if (result) {
428                                 result[respos] = '\0';
429                                 dbg(udev, "result='%s'\n", result);
430                                 if (reslen)
431                                         *reslen = respos;
432                         }
433                 }
434                 waitpid(pid, &status, 0);
435                 if (WIFEXITED(status)) {
436                         info(udev, "'%s' returned with status %i\n", argv[0], WEXITSTATUS(status));
437                         if (WEXITSTATUS(status) != 0)
438                                 err = -1;
439                 } else {
440                         err(udev, "'%s' abnormal exit\n", argv[0]);
441                         err = -1;
442                 }
443         }
444
445         return err;
446 }
447
448 static int import_property_from_string(struct udev_device *dev, char *line)
449 {
450         struct udev *udev = udev_device_get_udev(dev);
451         char *key;
452         char *val;
453         size_t len;
454
455         /* find key */
456         key = line;
457         while (isspace(key[0]))
458                 key++;
459
460         /* comment or empty line */
461         if (key[0] == '#' || key[0] == '\0')
462                 return -1;
463
464         /* split key/value */
465         val = strchr(key, '=');
466         if (val == NULL)
467                 return -1;
468         val[0] = '\0';
469         val++;
470
471         /* find value */
472         while (isspace(val[0]))
473                 val++;
474
475         /* terminate key */
476         len = strlen(key);
477         if (len == 0)
478                 return -1;
479         while (isspace(key[len-1]))
480                 len--;
481         key[len] = '\0';
482
483         /* terminate value */
484         len = strlen(val);
485         if (len == 0)
486                 return -1;
487         while (isspace(val[len-1]))
488                 len--;
489         val[len] = '\0';
490
491         if (len == 0)
492                 return -1;
493
494         /* unquote */
495         if (val[0] == '"' || val[0] == '\'') {
496                 if (val[len-1] != val[0]) {
497                         info(udev, "inconsistent quoting: '%s', skip\n", line);
498                         return -1;
499                 }
500                 val[len-1] = '\0';
501                 val++;
502         }
503
504         info(udev, "adding '%s'='%s'\n", key, val);
505
506         /* handle device, renamed by external tool, returning new path */
507         if (strcmp(key, "DEVPATH") == 0) {
508                 char syspath[UTIL_PATH_SIZE];
509
510                 info(udev, "updating devpath from '%s' to '%s'\n",
511                      udev_device_get_devpath(dev), val);
512                 util_strlcpy(syspath, udev_get_sys_path(udev), sizeof(syspath));
513                 util_strlcat(syspath, val, sizeof(syspath));
514                 udev_device_set_syspath(dev, syspath);
515         } else {
516                 struct udev_list_entry *entry;
517
518                 entry = udev_device_add_property(dev, key, val);
519                 /* store in db */
520                 udev_list_entry_set_flag(entry, 1);
521         }
522         return 0;
523 }
524
525 static int import_file_into_env(struct udev_device *dev, const char *filename)
526 {
527         FILE *f;
528         char line[UTIL_LINE_SIZE];
529
530         f = fopen(filename, "r");
531         if (f == NULL)
532                 return -1;
533         while (fgets(line, sizeof(line), f) != NULL)
534                 import_property_from_string(dev, line);
535         fclose(f);
536         return 0;
537 }
538
539 static int import_program_into_env(struct udev_device *dev, const char *program)
540 {
541         char result[2048];
542         size_t reslen;
543         char *line;
544
545         if (run_program(dev, program, result, sizeof(result), &reslen) != 0)
546                 return -1;
547
548         line = result;
549         while (line != NULL) {
550                 char *pos;
551
552                 pos = strchr(line, '\n');
553                 if (pos != NULL) {
554                         pos[0] = '\0';
555                         pos = &pos[1];
556                 }
557                 import_property_from_string(dev, line);
558                 line = pos;
559         }
560         return 0;
561 }
562
563 static int import_parent_into_env(struct udev_device *dev, const char *filter)
564 {
565         struct udev *udev = udev_device_get_udev(dev);
566         struct udev_device *dev_parent;
567         struct udev_list_entry *list_entry;
568
569         dev_parent = udev_device_get_parent(dev);
570         if (dev_parent == NULL)
571                 return -1;
572
573         dbg(udev, "found parent '%s', get the node name\n", udev_device_get_syspath(dev_parent));
574         udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(dev_parent)) {
575                 const char *key = udev_list_entry_get_name(list_entry);
576                 const char *val = udev_list_entry_get_value(list_entry);
577
578                 if (fnmatch(filter, key, 0) == 0) {
579                         struct udev_list_entry *entry;
580
581                         dbg(udev, "import key '%s=%s'\n", key, val);
582                         entry = udev_device_add_property(dev, key, val);
583                         /* store in db */
584                         udev_list_entry_set_flag(entry, 1);
585                 }
586         }
587         return 0;
588 }
589
590 int udev_rules_run(struct udev_event *event)
591 {
592         struct udev_list_entry *list_entry;
593         int err = 0;
594
595         dbg(event->udev, "executing run list\n");
596         udev_list_entry_foreach(list_entry, udev_list_get_entry(&event->run_list)) {
597                 const char *cmd = udev_list_entry_get_name(list_entry);
598
599                 if (strncmp(cmd, "socket:", strlen("socket:")) == 0) {
600                         struct udev_monitor *monitor;
601
602                         monitor = udev_monitor_new_from_socket(event->udev, &cmd[strlen("socket:")]);
603                         if (monitor == NULL)
604                                 continue;
605                         udev_monitor_send_device(monitor, event->dev);
606                         udev_monitor_unref(monitor);
607                 } else {
608                         char program[UTIL_PATH_SIZE];
609
610                         util_strlcpy(program, cmd, sizeof(program));
611                         udev_rules_apply_format(event, program, sizeof(program));
612                         if (run_program(event->dev, program, NULL, 0, NULL) != 0) {
613                                 if (!udev_list_entry_get_flag(list_entry))
614                                         err = -1;
615                         }
616                 }
617         }
618         return err;
619 }
620
621 #define WAIT_LOOP_PER_SECOND            50
622 static int wait_for_file(struct udev_event *event, const char *file, int timeout)
623 {
624         char filepath[UTIL_PATH_SIZE];
625         char devicepath[UTIL_PATH_SIZE] = "";
626         struct stat stats;
627         int loop = timeout * WAIT_LOOP_PER_SECOND;
628
629         /* a relative path is a device attribute */
630         if (file[0] != '/') {
631                 util_strlcpy(devicepath, udev_get_sys_path(event->udev), sizeof(devicepath));
632                 util_strlcat(devicepath, udev_device_get_devpath(event->dev), sizeof(devicepath));
633
634                 util_strlcpy(filepath, devicepath, sizeof(filepath));
635                 util_strlcat(filepath, "/", sizeof(filepath));
636                 util_strlcat(filepath, file, sizeof(filepath));
637                 file = filepath;
638         }
639
640         dbg(event->udev, "will wait %i sec for '%s'\n", timeout, file);
641         while (--loop) {
642                 /* lookup file */
643                 if (stat(file, &stats) == 0) {
644                         info(event->udev, "file '%s' appeared after %i loops\n", file, (timeout * WAIT_LOOP_PER_SECOND) - loop-1);
645                         return 0;
646                 }
647                 /* make sure, the device did not disappear in the meantime */
648                 if (devicepath[0] != '\0' && stat(devicepath, &stats) != 0) {
649                         info(event->udev, "device disappeared while waiting for '%s'\n", file);
650                         return -2;
651                 }
652                 info(event->udev, "wait for '%s' for %i mseconds\n", file, 1000 / WAIT_LOOP_PER_SECOND);
653                 usleep(1000 * 1000 / WAIT_LOOP_PER_SECOND);
654         }
655         info(event->udev, "waiting for '%s' failed\n", file);
656         return -1;
657 }
658
659 /* handle "[$SUBSYSTEM/$KERNEL]<attribute>" lookup */
660 static int split_subsys_sysname(struct udev *udev, char *attrstr, char **subsys, char **sysname, char **attr)
661 {
662         char *pos;
663
664         if (attrstr[0] != '[')
665                 return -1;
666
667         *subsys = &attrstr[1];
668         pos = strchr(*subsys, ']');
669         if (pos == NULL)
670                 return -1;
671         pos[0] = '\0';
672         pos = &pos[1];
673
674         if (pos[0] == '/')
675                 pos = &pos[1];
676         if (pos[0] != '\0')
677                 *attr = pos;
678         else
679                 *attr = NULL;
680
681         pos = strchr(*subsys, '/');
682         if (pos == NULL)
683                 return -1;
684         pos[0] = '\0';
685         *sysname = &pos[1];
686         return 0;
687 }
688
689 static int attr_subst_subdir(char *attr, size_t len)
690 {
691         char *pos;
692         int found = 0;
693
694         pos = strstr(attr, "/*/");
695         if (pos != NULL) {
696                 char str[UTIL_PATH_SIZE];
697                 DIR *dir;
698
699                 pos[1] = '\0';
700                 util_strlcpy(str, &pos[2], sizeof(str));
701                 dir = opendir(attr);
702                 if (dir != NULL) {
703                         struct dirent *dent;
704
705                         for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
706                                 struct stat stats;
707
708                                 if (dent->d_name[0] == '.')
709                                         continue;
710                                 util_strlcat(attr, dent->d_name, len);
711                                 util_strlcat(attr, str, len);
712                                 if (stat(attr, &stats) == 0) {
713                                         found = 1;
714                                         break;
715                                 }
716                                 pos[1] = '\0';
717                         }
718                         closedir(dir);
719                 }
720                 if (!found)
721                         util_strlcat(attr, str, len);
722         }
723
724         return found;
725 }
726
727 void udev_rules_apply_format(struct udev_event *event, char *string, size_t maxsize)
728 {
729         struct udev_device *dev = event->dev;
730         char temp[UTIL_PATH_SIZE];
731         char temp2[UTIL_PATH_SIZE];
732         char *head, *tail, *cpos, *attr, *rest;
733         int len;
734         int i;
735         int count;
736         enum subst_type {
737                 SUBST_UNKNOWN,
738                 SUBST_DEVPATH,
739                 SUBST_KERNEL,
740                 SUBST_KERNEL_NUMBER,
741                 SUBST_ID,
742                 SUBST_DRIVER,
743                 SUBST_MAJOR,
744                 SUBST_MINOR,
745                 SUBST_RESULT,
746                 SUBST_ATTR,
747                 SUBST_PARENT,
748                 SUBST_TEMP_NODE,
749                 SUBST_NAME,
750                 SUBST_LINKS,
751                 SUBST_ROOT,
752                 SUBST_SYS,
753                 SUBST_ENV,
754         };
755         static const struct subst_map {
756                 char *name;
757                 char fmt;
758                 enum subst_type type;
759         } map[] = {
760                 { .name = "devpath",    .fmt = 'p',     .type = SUBST_DEVPATH },
761                 { .name = "number",     .fmt = 'n',     .type = SUBST_KERNEL_NUMBER },
762                 { .name = "kernel",     .fmt = 'k',     .type = SUBST_KERNEL },
763                 { .name = "id",         .fmt = 'b',     .type = SUBST_ID },
764                 { .name = "driver",     .fmt = 'd',     .type = SUBST_DRIVER },
765                 { .name = "major",      .fmt = 'M',     .type = SUBST_MAJOR },
766                 { .name = "minor",      .fmt = 'm',     .type = SUBST_MINOR },
767                 { .name = "result",     .fmt = 'c',     .type = SUBST_RESULT },
768                 { .name = "attr",       .fmt = 's',     .type = SUBST_ATTR },
769                 { .name = "sysfs",      .fmt = 's',     .type = SUBST_ATTR },
770                 { .name = "parent",     .fmt = 'P',     .type = SUBST_PARENT },
771                 { .name = "tempnode",   .fmt = 'N',     .type = SUBST_TEMP_NODE },
772                 { .name = "name",       .fmt = 'D',     .type = SUBST_NAME },
773                 { .name = "links",      .fmt = 'L',     .type = SUBST_LINKS },
774                 { .name = "root",       .fmt = 'r',     .type = SUBST_ROOT },
775                 { .name = "sys",        .fmt = 'S',     .type = SUBST_SYS },
776                 { .name = "env",        .fmt = 'E',     .type = SUBST_ENV },
777                 { NULL, '\0', 0 }
778         };
779         enum subst_type type;
780         const struct subst_map *subst;
781
782         head = string;
783         while (1) {
784                 len = -1;
785                 while (head[0] != '\0') {
786                         if (head[0] == '$') {
787                                 /* substitute named variable */
788                                 if (head[1] == '\0')
789                                         break;
790                                 if (head[1] == '$') {
791                                         util_strlcpy(temp, head+2, sizeof(temp));
792                                         util_strlcpy(head+1, temp, maxsize);
793                                         head++;
794                                         continue;
795                                 }
796                                 head[0] = '\0';
797                                 for (subst = map; subst->name; subst++) {
798                                         if (strncasecmp(&head[1], subst->name, strlen(subst->name)) == 0) {
799                                                 type = subst->type;
800                                                 tail = head + strlen(subst->name)+1;
801                                                 dbg(event->udev, "will substitute format name '%s'\n", subst->name);
802                                                 goto found;
803                                         }
804                                 }
805                                 head[0] = '$';
806                                 err(event->udev, "unknown format variable '%s'\n", head);
807                         } else if (head[0] == '%') {
808                                 /* substitute format char */
809                                 if (head[1] == '\0')
810                                         break;
811                                 if (head[1] == '%') {
812                                         util_strlcpy(temp, head+2, sizeof(temp));
813                                         util_strlcpy(head+1, temp, maxsize);
814                                         head++;
815                                         continue;
816                                 }
817                                 head[0] = '\0';
818                                 tail = head+1;
819                                 len = get_format_len(event->udev, &tail);
820                                 for (subst = map; subst->name; subst++) {
821                                         if (tail[0] == subst->fmt) {
822                                                 type = subst->type;
823                                                 tail++;
824                                                 dbg(event->udev, "will substitute format char '%c'\n", subst->fmt);
825                                                 goto found;
826                                         }
827                                 }
828                                 head[0] = '%';
829                                 err(event->udev, "unknown format char '%c'\n", tail[0]);
830                         }
831                         head++;
832                 }
833                 break;
834 found:
835                 attr = get_format_attribute(event->udev, &tail);
836                 util_strlcpy(temp, tail, sizeof(temp));
837                 dbg(event->udev, "format=%i, string='%s', tail='%s'\n", type ,string, tail);
838
839                 switch (type) {
840                 case SUBST_DEVPATH:
841                         util_strlcat(string, udev_device_get_devpath(dev), maxsize);
842                         dbg(event->udev, "substitute devpath '%s'\n", udev_device_get_devpath(dev));
843                         break;
844                 case SUBST_KERNEL:
845                         util_strlcat(string, udev_device_get_sysname(dev), maxsize);
846                         dbg(event->udev, "substitute kernel name '%s'\n", udev_device_get_sysname(dev));
847                         break;
848                 case SUBST_KERNEL_NUMBER:
849                         if (udev_device_get_sysnum(dev) == NULL)
850                                 break;
851                         util_strlcat(string, udev_device_get_sysnum(dev), maxsize);
852                         dbg(event->udev, "substitute kernel number '%s'\n", udev_device_get_sysnum(dev));
853                         break;
854                 case SUBST_ID:
855                         if (event->dev_parent != NULL) {
856                                 util_strlcat(string, udev_device_get_sysname(event->dev_parent), maxsize);
857                                 dbg(event->udev, "substitute id '%s'\n", udev_device_get_sysname(event->dev_parent));
858                         }
859                         break;
860                 case SUBST_DRIVER:
861                         if (event->dev_parent != NULL) {
862                                 const char *driver = udev_device_get_driver(event->dev_parent);
863
864                                 if (driver == NULL)
865                                         break;
866                                 util_strlcat(string, driver, maxsize);
867                                 dbg(event->udev, "substitute driver '%s'\n", driver);
868                         }
869                         break;
870                 case SUBST_MAJOR:
871                         sprintf(temp2, "%d", major(udev_device_get_devnum(dev)));
872                         util_strlcat(string, temp2, maxsize);
873                         dbg(event->udev, "substitute major number '%s'\n", temp2);
874                         break;
875                 case SUBST_MINOR:
876                         sprintf(temp2, "%d", minor(udev_device_get_devnum(dev)));
877                         util_strlcat(string, temp2, maxsize);
878                         dbg(event->udev, "substitute minor number '%s'\n", temp2);
879                         break;
880                 case SUBST_RESULT:
881                         if (event->program_result[0] == '\0')
882                                 break;
883                         /* get part part of the result string */
884                         i = 0;
885                         if (attr != NULL)
886                                 i = strtoul(attr, &rest, 10);
887                         if (i > 0) {
888                                 dbg(event->udev, "request part #%d of result string\n", i);
889                                 cpos = event->program_result;
890                                 while (--i) {
891                                         while (cpos[0] != '\0' && !isspace(cpos[0]))
892                                                 cpos++;
893                                         while (isspace(cpos[0]))
894                                                 cpos++;
895                                 }
896                                 if (i > 0) {
897                                         err(event->udev, "requested part of result string not found\n");
898                                         break;
899                                 }
900                                 util_strlcpy(temp2, cpos, sizeof(temp2));
901                                 /* %{2+}c copies the whole string from the second part on */
902                                 if (rest[0] != '+') {
903                                         cpos = strchr(temp2, ' ');
904                                         if (cpos)
905                                                 cpos[0] = '\0';
906                                 }
907                                 util_strlcat(string, temp2, maxsize);
908                                 dbg(event->udev, "substitute part of result string '%s'\n", temp2);
909                         } else {
910                                 util_strlcat(string, event->program_result, maxsize);
911                                 dbg(event->udev, "substitute result string '%s'\n", event->program_result);
912                         }
913                         break;
914                 case SUBST_ATTR:
915                         if (attr == NULL)
916                                 err(event->udev, "missing file parameter for attr\n");
917                         else {
918                                 char *subsys;
919                                 char *sysname;
920                                 char *attrib;
921                                 char value[UTIL_NAME_SIZE] = "";
922                                 size_t size;
923
924                                 if (split_subsys_sysname(event->udev, attr, &subsys, &sysname, &attrib) == 0) {
925                                         struct udev_device *d;
926                                         const char *val;
927
928                                         if (attrib == NULL)
929                                                 break;
930                                         d = udev_device_new_from_subsystem_sysname(event->udev, subsys, sysname);
931                                         if (d == NULL)
932                                                 break;
933                                         val = udev_device_get_attr_value(d, attrib);
934                                         if (val != NULL)
935                                                 util_strlcpy(value, val, sizeof(value));
936                                         udev_device_unref(d);
937                                 }
938
939                                 /* try the current device, other matches may have selected */
940                                 if (value[0]=='\0' && event->dev_parent != NULL && event->dev_parent != event->dev) {
941                                         const char *val;
942
943                                         val = udev_device_get_attr_value(event->dev_parent, attr);
944                                         if (val != NULL)
945                                                 util_strlcpy(value, val, sizeof(value));
946                                 }
947
948                                 /* look at all devices along the chain of parents */
949                                 if (value[0]=='\0') {
950                                         struct udev_device *dev_parent = dev;
951                                         const char *val;
952
953                                         do {
954                                                 dbg(event->udev, "looking at '%s'\n", udev_device_get_syspath(dev_parent));
955                                                 val = udev_device_get_attr_value(dev_parent, attr);
956                                                 if (val != NULL) {
957                                                         util_strlcpy(value, val, sizeof(value));
958                                                         break;
959                                                 }
960                                                 dev_parent = udev_device_get_parent(dev_parent);
961                                         } while (dev_parent != NULL);
962                                 }
963
964                                 if (value[0]=='\0')
965                                         break;
966
967                                 /* strip trailing whitespace, and replace unwanted characters */
968                                 size = strlen(value);
969                                 while (size > 0 && isspace(value[--size]))
970                                         value[size] = '\0';
971                                 count = util_replace_chars(value, ALLOWED_CHARS_INPUT);
972                                 if (count > 0)
973                                         info(event->udev, "%i character(s) replaced\n" , count);
974                                 util_strlcat(string, value, maxsize);
975                                 dbg(event->udev, "substitute sysfs value '%s'\n", value);
976                         }
977                         break;
978                 case SUBST_PARENT:
979                         {
980                                 struct udev_device *dev_parent;
981                                 const char *devnode;
982
983                                 dev_parent = udev_device_get_parent(event->dev);
984                                 if (dev_parent == NULL)
985                                         break;
986                                 devnode = udev_device_get_devnode(dev_parent);
987                                 if (devnode != NULL) {
988                                         size_t devlen = strlen(udev_get_dev_path(event->udev))+1;
989
990                                         util_strlcat(string, &devnode[devlen], maxsize);
991                                         dbg(event->udev, "found parent '%s', got node name '%s'\n",
992                                             udev_device_get_syspath(dev_parent), &devnode[devlen]);
993                                 }
994                         }
995                         break;
996                 case SUBST_TEMP_NODE:
997                         if (event->tmp_node[0] == '\0' && major(udev_device_get_devnum(dev)) > 0) {
998                                 dbg(event->udev, "create temporary device node for callout\n");
999                                 snprintf(event->tmp_node, sizeof(event->tmp_node), "%s/.tmp-%u-%u",
1000                                          udev_get_dev_path(event->udev),
1001                                          major(udev_device_get_devnum(dev)), minor(udev_device_get_devnum(dev)));
1002                                 udev_node_mknod(dev, event->tmp_node, makedev(0,0), 0600, 0, 0);
1003                         }
1004                         util_strlcat(string, event->tmp_node, maxsize);
1005                         dbg(event->udev, "substitute temporary device node name '%s'\n", event->tmp_node);
1006                         break;
1007                 case SUBST_NAME:
1008                         if (event->name != NULL) {
1009                                 util_strlcat(string, event->name, maxsize);
1010                                 dbg(event->udev, "substitute name '%s'\n", event->name);
1011                         } else {
1012                                 util_strlcat(string, udev_device_get_sysname(dev), maxsize);
1013                                 dbg(event->udev, "substitute sysname '%s'\n", udev_device_get_sysname(dev));
1014                         }
1015                         break;
1016                 case SUBST_LINKS:
1017                         {
1018                                 struct udev_list_entry *list_entry;
1019
1020                                 list_entry = udev_device_get_properties_list_entry(dev);
1021                                 util_strlcpy(string, udev_list_entry_get_name(list_entry), maxsize);
1022                                 udev_list_entry_foreach(list_entry, udev_list_entry_get_next(list_entry)) {
1023                                         util_strlcat(string, " ", maxsize);
1024                                         util_strlcat(string, udev_list_entry_get_name(list_entry), maxsize);
1025                                 }
1026                         }
1027                         break;
1028                 case SUBST_ROOT:
1029                         util_strlcat(string, udev_get_dev_path(event->udev), maxsize);
1030                         dbg(event->udev, "substitute udev_root '%s'\n", udev_get_dev_path(event->udev));
1031                         break;
1032                 case SUBST_SYS:
1033                         util_strlcat(string, udev_get_sys_path(event->udev), maxsize);
1034                         dbg(event->udev, "substitute sys_path '%s'\n", udev_get_sys_path(event->udev));
1035                         break;
1036                 case SUBST_ENV:
1037                         if (attr == NULL) {
1038                                 dbg(event->udev, "missing attribute\n");
1039                                 break;
1040                         } else {
1041                                 struct udev_list_entry *list_entry;
1042                                 const char *value;
1043
1044                                 list_entry = udev_device_get_properties_list_entry(event->dev);
1045                                 list_entry = udev_list_entry_get_by_name(list_entry, attr);
1046                                 if (list_entry == NULL)
1047                                         break;
1048                                 value = udev_list_entry_get_value(list_entry);
1049                                 dbg(event->udev, "substitute env '%s=%s'\n", attr, value);
1050                                 util_strlcat(string, value, maxsize);
1051                                 break;
1052                         }
1053                 default:
1054                         err(event->udev, "unknown substitution type=%i\n", type);
1055                         break;
1056                 }
1057                 /* possibly truncate to format-char specified length */
1058                 if (len >= 0 && len < (int)strlen(head)) {
1059                         head[len] = '\0';
1060                         dbg(event->udev, "truncate to %i chars, subtitution string becomes '%s'\n", len, head);
1061                 }
1062                 util_strlcat(string, temp, maxsize);
1063         }
1064 }
1065
1066 static char *key_val(struct udev_rule *rule, struct key *key)
1067 {
1068         return rule->buf + key->val_off;
1069 }
1070
1071 static char *key_pair_name(struct udev_rule *rule, struct key_pair *pair)
1072 {
1073         return rule->buf + pair->key_name_off;
1074 }
1075
1076 static int match_key(struct udev *udev, const char *key_name, struct udev_rule *rule, struct key *key, const char *val)
1077 {
1078         char value[UTIL_PATH_SIZE];
1079         char *key_value;
1080         char *pos;
1081         int match = 0;
1082
1083         if (key->operation != KEY_OP_MATCH &&
1084             key->operation != KEY_OP_NOMATCH)
1085                 return 0;
1086
1087         if (val == NULL)
1088                 val = "";
1089
1090         /* look for a matching string, parts are separated by '|' */
1091         util_strlcpy(value, rule->buf + key->val_off, sizeof(value));
1092         key_value = value;
1093         dbg(udev, "key %s value='%s'\n", key_name, key_value);
1094         while (key_value != NULL) {
1095                 pos = strchr(key_value, '|');
1096                 if (pos != NULL) {
1097                         pos[0] = '\0';
1098                         pos = &pos[1];
1099                 }
1100
1101                 dbg(udev, "match %s '%s' <-> '%s'\n", key_name, key_value, val);
1102                 match = (fnmatch(key_value, val, 0) == 0);
1103                 if (match)
1104                         break;
1105
1106                 key_value = pos;
1107         }
1108
1109         if (match && (key->operation == KEY_OP_MATCH)) {
1110                 dbg(udev, "%s is true (matching value)\n", key_name);
1111                 return 0;
1112         }
1113         if (!match && (key->operation == KEY_OP_NOMATCH)) {
1114                 dbg(udev, "%s is true (non-matching value)\n", key_name);
1115                 return 0;
1116         }
1117         return -1;
1118 }
1119
1120 /* match a single rule against a given device and possibly its parent devices */
1121 static int match_rule(struct udev_event *event, struct udev_rule *rule)
1122 {
1123         struct udev_device *dev = event->dev;
1124         int i;
1125
1126         if (match_key(event->udev, "ACTION", rule, &rule->action, udev_device_get_action(dev)))
1127                 goto nomatch;
1128
1129         if (match_key(event->udev, "KERNEL", rule, &rule->kernel, udev_device_get_sysname(dev)))
1130                 goto nomatch;
1131
1132         if (match_key(event->udev, "SUBSYSTEM", rule, &rule->subsystem, udev_device_get_subsystem(dev)))
1133                 goto nomatch;
1134
1135         if (match_key(event->udev, "DEVPATH", rule, &rule->devpath, udev_device_get_devpath(dev)))
1136                 goto nomatch;
1137
1138         if (match_key(event->udev, "DRIVER", rule, &rule->driver, udev_device_get_driver(dev)))
1139                 goto nomatch;
1140
1141         /* match NAME against a value assigned by an earlier rule */
1142         if (match_key(event->udev, "NAME", rule, &rule->name, event->name))
1143                 goto nomatch;
1144
1145         /* match against current list of symlinks */
1146         if (rule->symlink_match.operation == KEY_OP_MATCH ||
1147             rule->symlink_match.operation == KEY_OP_NOMATCH) {
1148                 size_t devlen = strlen(udev_get_dev_path(event->udev))+1;
1149                 struct udev_list_entry *list_entry;
1150                 int match = 0;
1151
1152                 udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(dev)) {
1153                         const char *devlink;
1154
1155                         devlink =  &udev_list_entry_get_name(list_entry)[devlen];
1156                         if (match_key(event->udev, "SYMLINK", rule, &rule->symlink_match, devlink) == 0) {
1157                                 match = 1;
1158                                 break;
1159                         }
1160                 }
1161                 if (!match)
1162                         goto nomatch;
1163         }
1164
1165         for (i = 0; i < rule->env.count; i++) {
1166                 struct key_pair *pair = &rule->env.keys[i];
1167
1168                 /* we only check for matches, assignments will be handled later */
1169                 if (pair->key.operation == KEY_OP_MATCH ||
1170                     pair->key.operation == KEY_OP_NOMATCH) {
1171                         struct udev_list_entry *list_entry;
1172                         const char *key_name = key_pair_name(rule, pair);
1173                         const char *value;
1174
1175                         list_entry = udev_device_get_properties_list_entry(event->dev);
1176                         list_entry = udev_list_entry_get_by_name(list_entry, key_name);
1177                         value = udev_list_entry_get_value(list_entry);
1178                         if (value == NULL) {
1179                                 dbg(event->udev, "ENV{%s} is not set, treat as empty\n", key_name);
1180                                 value = "";
1181                         }
1182                         if (match_key(event->udev, "ENV", rule, &pair->key, value))
1183                                 goto nomatch;
1184                 }
1185         }
1186
1187         if (rule->test.operation == KEY_OP_MATCH ||
1188             rule->test.operation == KEY_OP_NOMATCH) {
1189                 char filename[UTIL_PATH_SIZE];
1190                 char *subsys;
1191                 char *sysname;
1192                 char *attrib;
1193                 struct stat statbuf;
1194                 int match;
1195
1196                 util_strlcpy(filename, key_val(rule, &rule->test), sizeof(filename));
1197                 udev_rules_apply_format(event, filename, sizeof(filename));
1198
1199                 if (split_subsys_sysname(event->udev, filename, &subsys, &sysname, &attrib) == 0) {
1200                         struct udev_device *d;
1201                         d = udev_device_new_from_subsystem_sysname(event->udev, subsys, sysname);
1202                         if (d != NULL) {
1203                                 util_strlcpy(filename, udev_device_get_syspath(d), sizeof(filename));
1204                                 if (attrib != NULL) {
1205                                         util_strlcat(filename, "/", sizeof(filename));
1206                                         util_strlcat(filename, attrib, sizeof(filename));
1207                                 }
1208                                 udev_device_unref(d);
1209                         }
1210                 } else if (filename[0] != '/') {
1211                         char tmp[UTIL_PATH_SIZE];
1212
1213                         util_strlcpy(tmp, udev_device_get_syspath(dev), sizeof(tmp));
1214                         util_strlcat(tmp, "/", sizeof(tmp));
1215                         util_strlcat(tmp, filename, sizeof(tmp));
1216                         util_strlcpy(filename, tmp, sizeof(filename));
1217                 }
1218
1219                 attr_subst_subdir(filename, sizeof(filename));
1220
1221                 match = (stat(filename, &statbuf) == 0);
1222                 info(event->udev, "'%s' %s", filename, match ? "exists\n" : "does not exist\n");
1223                 if (match && rule->test_mode_mask > 0) {
1224                         match = ((statbuf.st_mode & rule->test_mode_mask) > 0);
1225                         info(event->udev, "'%s' has mode=%#o and %s %#o\n", filename, statbuf.st_mode,
1226                              match ? "matches" : "does not match",
1227                              rule->test_mode_mask);
1228                 }
1229                 if (match && rule->test.operation == KEY_OP_NOMATCH)
1230                         goto nomatch;
1231                 if (!match && rule->test.operation == KEY_OP_MATCH)
1232                         goto nomatch;
1233                 dbg(event->udev, "TEST key is true\n");
1234         }
1235
1236         if (rule->wait_for.operation != KEY_OP_UNSET) {
1237                 char filename[UTIL_PATH_SIZE];
1238                 int found;
1239
1240                 util_strlcpy(filename, key_val(rule, &rule->wait_for), sizeof(filename));
1241                 udev_rules_apply_format(event, filename, sizeof(filename));
1242                 found = (wait_for_file(event, filename, 10) == 0);
1243                 if (!found && (rule->wait_for.operation != KEY_OP_NOMATCH))
1244                         goto nomatch;
1245         }
1246
1247         /* check for matching sysfs attribute pairs */
1248         for (i = 0; i < rule->attr.count; i++) {
1249                 struct key_pair *pair = &rule->attr.keys[i];
1250
1251                 if (pair->key.operation == KEY_OP_MATCH ||
1252                     pair->key.operation == KEY_OP_NOMATCH) {
1253                         char attr[UTIL_PATH_SIZE];
1254                         const char *key_name = key_pair_name(rule, pair);
1255                         const char *key_value = key_val(rule, &pair->key);
1256                         char *subsys;
1257                         char *sysname;
1258                         char *attrib;
1259                         char value[UTIL_NAME_SIZE] = "";
1260                         size_t len;
1261
1262                         util_strlcpy(attr, key_name, sizeof(attr));
1263                         if (split_subsys_sysname(event->udev, attr, &subsys, &sysname, &attrib) == 0) {
1264                                 struct udev_device *d;
1265                                 const char *val;
1266
1267                                 if (attrib == NULL)
1268                                         goto nomatch;
1269                                 d = udev_device_new_from_subsystem_sysname(event->udev, subsys, sysname);
1270                                 if (d == NULL)
1271                                         goto nomatch;
1272                                 val = udev_device_get_attr_value(d, attrib);
1273                                 if (val != NULL)
1274                                         util_strlcpy(value, val, sizeof(value));
1275                                 udev_device_unref(d);
1276                         }
1277
1278                         if (value[0]=='\0') {
1279                                 const char *val;
1280
1281                                 val = udev_device_get_attr_value(dev, key_name);
1282                                 if (val != NULL)
1283                                         util_strlcpy(value, val, sizeof(value));
1284                         }
1285
1286                         if (value[0]=='\0')
1287                                 goto nomatch;
1288
1289                         /* strip trailing whitespace of value, if not asked to match for it */
1290                         len = strlen(key_value);
1291                         if (len > 0 && !isspace(key_value[len-1])) {
1292                                 len = strlen(value);
1293                                 while (len > 0 && isspace(value[--len]))
1294                                         value[len] = '\0';
1295                                 dbg(event->udev, "removed trailing whitespace from '%s'\n", value);
1296                         }
1297
1298                         if (match_key(event->udev, "ATTR", rule, &pair->key, value))
1299                                 goto nomatch;
1300                 }
1301         }
1302
1303         /* walk up the chain of parent devices and find a match */
1304         event->dev_parent = dev;
1305         while (1) {
1306                 /* check for matching kernel device name */
1307                 if (match_key(event->udev, "KERNELS", rule,
1308                               &rule->kernels, udev_device_get_sysname(event->dev_parent)))
1309                         goto try_parent;
1310
1311                 /* check for matching subsystem value */
1312                 if (match_key(event->udev, "SUBSYSTEMS", rule,
1313                               &rule->subsystems, udev_device_get_subsystem(event->dev_parent)))
1314                         goto try_parent;
1315
1316                 /* check for matching driver */
1317                 if (match_key(event->udev, "DRIVERS", rule,
1318                               &rule->drivers, udev_device_get_driver(event->dev_parent)))
1319                         goto try_parent;
1320
1321                 /* check for matching sysfs attribute pairs */
1322                 for (i = 0; i < rule->attrs.count; i++) {
1323                         struct key_pair *pair = &rule->attrs.keys[i];
1324
1325                         if (pair->key.operation == KEY_OP_MATCH ||
1326                             pair->key.operation == KEY_OP_NOMATCH) {
1327                                 const char *key_name = key_pair_name(rule, pair);
1328                                 const char *key_value = key_val(rule, &pair->key);
1329                                 const char *val;
1330                                 char value[UTIL_NAME_SIZE];
1331                                 size_t len;
1332
1333                                 val = udev_device_get_attr_value(event->dev_parent, key_name);
1334                                 if (val == NULL)
1335                                         val = udev_device_get_attr_value(dev, key_name);
1336                                 if (val == NULL)
1337                                         goto try_parent;
1338                                 util_strlcpy(value, val, sizeof(value));
1339
1340                                 /* strip trailing whitespace of value, if not asked to match for it */
1341                                 len = strlen(key_value);
1342                                 if (len > 0 && !isspace(key_value[len-1])) {
1343                                         len = strlen(value);
1344                                         while (len > 0 && isspace(value[--len]))
1345                                                 value[len] = '\0';
1346                                         dbg(event->udev, "removed trailing whitespace from '%s'\n", value);
1347                                 }
1348
1349                                 if (match_key(event->udev, "ATTRS", rule, &pair->key, value))
1350                                         goto try_parent;
1351                         }
1352                 }
1353
1354                 /* found matching device  */
1355                 break;
1356 try_parent:
1357                 /* move to parent device */
1358                 dbg(event->udev, "try parent sysfs device\n");
1359                 event->dev_parent = udev_device_get_parent(event->dev_parent);
1360                 if (event->dev_parent == NULL)
1361                         goto nomatch;
1362                 dbg(event->udev, "looking at dev_parent->devpath='%s'\n",
1363                     udev_device_get_syspath(event->dev_parent));
1364         }
1365
1366         /* execute external program */
1367         if (rule->program.operation != KEY_OP_UNSET) {
1368                 char program[UTIL_PATH_SIZE];
1369                 char result[UTIL_PATH_SIZE];
1370
1371                 util_strlcpy(program, key_val(rule, &rule->program), sizeof(program));
1372                 udev_rules_apply_format(event, program, sizeof(program));
1373                 if (run_program(event->dev, program, result, sizeof(result), NULL) != 0) {
1374                         dbg(event->udev, "PROGRAM is false\n");
1375                         event->program_result[0] = '\0';
1376                         if (rule->program.operation != KEY_OP_NOMATCH)
1377                                 goto nomatch;
1378                 } else {
1379                         int count;
1380
1381                         dbg(event->udev, "PROGRAM matches\n");
1382                         util_remove_trailing_chars(result, '\n');
1383                         if (rule->string_escape == ESCAPE_UNSET ||
1384                             rule->string_escape == ESCAPE_REPLACE) {
1385                                 count = util_replace_chars(result, ALLOWED_CHARS_INPUT);
1386                                 if (count > 0)
1387                                         info(event->udev, "%i character(s) replaced\n" , count);
1388                         }
1389                         dbg(event->udev, "result is '%s'\n", result);
1390                         util_strlcpy(event->program_result, result, sizeof(event->program_result));
1391                         dbg(event->udev, "PROGRAM returned successful\n");
1392                         if (rule->program.operation == KEY_OP_NOMATCH)
1393                                 goto nomatch;
1394                 }
1395                 dbg(event->udev, "PROGRAM key is true\n");
1396         }
1397
1398         /* check for matching result of external program */
1399         if (match_key(event->udev, "RESULT", rule, &rule->result, event->program_result))
1400                 goto nomatch;
1401
1402         /* import variables returned from program or or file into properties */
1403         if (rule->import.operation != KEY_OP_UNSET) {
1404                 char import[UTIL_PATH_SIZE];
1405                 int rc = -1;
1406
1407                 util_strlcpy(import, key_val(rule, &rule->import), sizeof(import));
1408                 udev_rules_apply_format(event, import, sizeof(import));
1409                 dbg(event->udev, "check for IMPORT import='%s'\n", import);
1410                 if (rule->import_type == IMPORT_PROGRAM) {
1411                         rc = import_program_into_env(event->dev, import);
1412                 } else if (rule->import_type == IMPORT_FILE) {
1413                         dbg(event->udev, "import file import='%s'\n", import);
1414                         rc = import_file_into_env(event->dev, import);
1415                 } else if (rule->import_type == IMPORT_PARENT) {
1416                         dbg(event->udev, "import parent import='%s'\n", import);
1417                         rc = import_parent_into_env(event->dev, import);
1418                 }
1419                 if (rc != 0) {
1420                         dbg(event->udev, "IMPORT failed\n");
1421                         if (rule->import.operation != KEY_OP_NOMATCH)
1422                                 goto nomatch;
1423                 } else
1424                         dbg(event->udev, "IMPORT '%s' imported\n", key_val(rule, &rule->import));
1425                 dbg(event->udev, "IMPORT key is true\n");
1426         }
1427
1428         /* rule matches, if we have ENV assignments export it */
1429         for (i = 0; i < rule->env.count; i++) {
1430                 struct key_pair *pair = &rule->env.keys[i];
1431
1432                 if (pair->key.operation == KEY_OP_ASSIGN) {
1433                         char temp_value[UTIL_NAME_SIZE];
1434                         const char *key_name = key_pair_name(rule, pair);
1435                         const char *value = key_val(rule, &pair->key);
1436
1437                         /* make sure we don't write to the same string we possibly read from */
1438                         util_strlcpy(temp_value, value, sizeof(temp_value));
1439                         udev_rules_apply_format(event, temp_value, sizeof(temp_value));
1440
1441                         if (temp_value[0] != '\0') {
1442                                 struct udev_list_entry *entry;
1443
1444                                 info(event->udev, "set ENV '%s=%s'\n", key_name, temp_value);
1445                                 entry = udev_device_add_property(dev, key_name, temp_value);
1446                                 /* store in db */
1447                                 udev_list_entry_set_flag(entry, 1);
1448                         }
1449                 }
1450         }
1451
1452         /* if we have ATTR assignments, write value to sysfs file */
1453         for (i = 0; i < rule->attr.count; i++) {
1454                 struct key_pair *pair = &rule->attr.keys[i];
1455
1456                 if (pair->key.operation == KEY_OP_ASSIGN) {
1457                         const char *key_name = key_pair_name(rule, pair);
1458                         char *subsys;
1459                         char *sysname;
1460                         char *attrib;
1461                         char attr[UTIL_PATH_SIZE];
1462                         char value[UTIL_NAME_SIZE];
1463                         FILE *f;
1464
1465                         util_strlcpy(attr, key_name, sizeof(attr));
1466                         if (split_subsys_sysname(event->udev, attr, &subsys, &sysname, &attrib) == 0) {
1467                                 struct udev_device *d;
1468
1469                                 d = udev_device_new_from_subsystem_sysname(event->udev, subsys, sysname);
1470                                 if (d != NULL) {
1471                                         util_strlcpy(attr, udev_device_get_syspath(d), sizeof(attr));
1472                                         if (attrib != NULL) {
1473                                                 util_strlcat(attr, "/", sizeof(attr));
1474                                                 util_strlcat(attr, attrib, sizeof(attr));
1475                                         }
1476                                         udev_device_unref(d);
1477                                 }
1478                         } else {
1479                                 util_strlcpy(attr, udev_device_get_syspath(dev), sizeof(attr));
1480                                 util_strlcat(attr, "/", sizeof(attr));
1481                                 util_strlcat(attr, key_name, sizeof(attr));
1482                         }
1483
1484                         attr_subst_subdir(attr, sizeof(attr));
1485
1486                         util_strlcpy(value, key_val(rule, &pair->key), sizeof(value));
1487                         udev_rules_apply_format(event, value, sizeof(value));
1488                         info(event->udev, "writing '%s' to sysfs file '%s'\n", value, attr);
1489                         f = fopen(attr, "w");
1490                         if (f != NULL) {
1491                                 if (!event->test)
1492                                         if (fprintf(f, "%s", value) <= 0)
1493                                                 err(event->udev, "error writing ATTR{%s}: %m\n", attr);
1494                                 fclose(f);
1495                         } else
1496                                 err(event->udev, "error opening ATTR{%s} for writing: %m\n", attr);
1497                 }
1498         }
1499         return 0;
1500
1501 nomatch:
1502         return -1;
1503 }
1504
1505 int udev_rules_get_name(struct udev_rules *rules, struct udev_event *event)
1506 {
1507         struct udev_device *dev = event->dev;
1508         struct udev_rules_iter iter;
1509         struct udev_rule *rule;
1510         int name_set = 0;
1511
1512         dbg(event->udev, "device: '%s'\n", udev_device_get_syspath(dev));
1513
1514         /* look for a matching rule to apply */
1515         udev_rules_iter_init(&iter, rules);
1516         while (1) {
1517                 rule = udev_rules_iter_next(&iter);
1518                 if (rule == NULL)
1519                         break;
1520
1521                 if (name_set &&
1522                     (rule->name.operation == KEY_OP_ASSIGN ||
1523                      rule->name.operation == KEY_OP_ASSIGN_FINAL ||
1524                      rule->name.operation == KEY_OP_ADD)) {
1525                         dbg(event->udev, "node name already set, rule ignored\n");
1526                         continue;
1527                 }
1528
1529                 dbg(event->udev, "process rule\n");
1530                 if (match_rule(event, rule) == 0) {
1531                         /* apply options */
1532                         if (rule->ignore_device) {
1533                                 info(event->udev, "rule applied, '%s' is ignored\n", udev_device_get_sysname(dev));
1534                                 event->ignore_device = 1;
1535                                 return 0;
1536                         }
1537                         if (rule->ignore_remove) {
1538                                 udev_device_set_ignore_remove(dev, 1);
1539                                 dbg(event->udev, "remove event should be ignored\n");
1540                         }
1541                         if (rule->link_priority != 0) {
1542                                 udev_device_set_devlink_priority(dev, rule->link_priority);
1543                                 info(event->udev, "devlink_priority=%i\n", rule->link_priority);
1544                         }
1545                         if (rule->event_timeout >= 0) {
1546                                 udev_device_set_event_timeout(dev, rule->event_timeout);
1547                                 info(event->udev, "event_timeout=%i\n", rule->event_timeout);
1548                         }
1549                         /* apply all_partitions option only at a disk device */
1550                         if (rule->partitions > 0 &&
1551                             strcmp(udev_device_get_subsystem(dev), "block") == 0 &&
1552                             udev_device_get_sysnum(dev) == NULL) {
1553                                 udev_device_set_num_fake_partitions(dev, rule->partitions);
1554                                 dbg(event->udev, "creation of partition nodes requested\n");
1555                         }
1556
1557                         /* apply permissions */
1558                         if (!event->mode_final && rule->mode.operation != KEY_OP_UNSET) {
1559                                 if (rule->mode.operation == KEY_OP_ASSIGN_FINAL)
1560                                         event->mode_final = 1;
1561                                 char buf[20];
1562                                 util_strlcpy(buf, key_val(rule, &rule->mode), sizeof(buf));
1563                                 udev_rules_apply_format(event, buf, sizeof(buf));
1564                                 event->mode = strtol(buf, NULL, 8);
1565                                 dbg(event->udev, "applied mode=%#o to '%s'\n",
1566                                     event->mode, udev_device_get_sysname(dev));
1567                         }
1568                         if (!event->owner_final && rule->owner.operation != KEY_OP_UNSET) {
1569                                 if (rule->owner.operation == KEY_OP_ASSIGN_FINAL)
1570                                         event->owner_final = 1;
1571                                 util_strlcpy(event->owner, key_val(rule, &rule->owner), sizeof(event->owner));
1572                                 udev_rules_apply_format(event, event->owner, sizeof(event->owner));
1573                                 dbg(event->udev, "applied owner='%s' to '%s'\n",
1574                                     event->owner, udev_device_get_sysname(dev));
1575                         }
1576                         if (!event->group_final && rule->group.operation != KEY_OP_UNSET) {
1577                                 if (rule->group.operation == KEY_OP_ASSIGN_FINAL)
1578                                         event->group_final = 1;
1579                                 util_strlcpy(event->group, key_val(rule, &rule->group), sizeof(event->group));
1580                                 udev_rules_apply_format(event, event->group, sizeof(event->group));
1581                                 dbg(event->udev, "applied group='%s' to '%s'\n",
1582                                     event->group, udev_device_get_sysname(dev));
1583                         }
1584
1585                         /* collect symlinks */
1586                         if (!event->devlink_final &&
1587                             (rule->symlink.operation == KEY_OP_ASSIGN ||
1588                              rule->symlink.operation == KEY_OP_ASSIGN_FINAL ||
1589                              rule->symlink.operation == KEY_OP_ADD)) {
1590                                 char temp[UTIL_PATH_SIZE];
1591                                 char filename[UTIL_PATH_SIZE];
1592                                 char *pos, *next;
1593                                 int count = 0;
1594
1595                                 if (rule->symlink.operation == KEY_OP_ASSIGN_FINAL)
1596                                         event->devlink_final = 1;
1597                                 if (rule->symlink.operation == KEY_OP_ASSIGN ||
1598                                     rule->symlink.operation == KEY_OP_ASSIGN_FINAL) {
1599                                         info(event->udev, "reset symlink list\n");
1600                                         udev_device_cleanup_devlinks_list(dev);
1601                                 }
1602                                 /* allow  multiple symlinks separated by spaces */
1603                                 util_strlcpy(temp, key_val(rule, &rule->symlink), sizeof(temp));
1604                                 udev_rules_apply_format(event, temp, sizeof(temp));
1605                                 if (rule->string_escape == ESCAPE_UNSET)
1606                                         count = util_replace_chars(temp, ALLOWED_CHARS_FILE " ");
1607                                 else if (rule->string_escape == ESCAPE_REPLACE)
1608                                         count = util_replace_chars(temp, ALLOWED_CHARS_FILE);
1609                                 if (count > 0)
1610                                         info(event->udev, "%i character(s) replaced\n" , count);
1611                                 dbg(event->udev, "rule applied, added symlink(s) '%s'\n", temp);
1612                                 pos = temp;
1613                                 while (isspace(pos[0]))
1614                                         pos++;
1615                                 next = strchr(pos, ' ');
1616                                 while (next) {
1617                                         next[0] = '\0';
1618                                         info(event->udev, "add symlink '%s'\n", pos);
1619                                         util_strlcpy(filename, udev_get_dev_path(event->udev), sizeof(filename));
1620                                         util_strlcat(filename, "/", sizeof(filename));
1621                                         util_strlcat(filename, pos, sizeof(filename));
1622                                         udev_device_add_devlink(dev, filename);
1623                                         while (isspace(next[1]))
1624                                                 next++;
1625                                         pos = &next[1];
1626                                         next = strchr(pos, ' ');
1627                                 }
1628                                 if (pos[0] != '\0') {
1629                                         info(event->udev, "add symlink '%s'\n", pos);
1630                                         util_strlcpy(filename, udev_get_dev_path(event->udev), sizeof(filename));
1631                                         util_strlcat(filename, "/", sizeof(filename));
1632                                         util_strlcat(filename, pos, sizeof(filename));
1633                                         udev_device_add_devlink(dev, filename);
1634                                 }
1635                         }
1636
1637                         /* set name, later rules with name set will be ignored */
1638                         if (rule->name.operation == KEY_OP_ASSIGN ||
1639                             rule->name.operation == KEY_OP_ASSIGN_FINAL ||
1640                             rule->name.operation == KEY_OP_ADD) {
1641                                 int count;
1642
1643                                 name_set = 1;
1644                                 util_strlcpy(event->name, key_val(rule, &rule->name), sizeof(event->name));
1645                                 udev_rules_apply_format(event, event->name, sizeof(event->name));
1646                                 if (rule->string_escape == ESCAPE_UNSET ||
1647                                     rule->string_escape == ESCAPE_REPLACE) {
1648                                         count = util_replace_chars(event->name, ALLOWED_CHARS_FILE);
1649                                         if (count > 0)
1650                                                 info(event->udev, "%i character(s) replaced\n", count);
1651                                 }
1652
1653                                 info(event->udev, "rule applied, '%s' becomes '%s'\n",
1654                                      udev_device_get_sysname(dev), event->name);
1655                                 if (strcmp(udev_device_get_subsystem(dev), "net") != 0)
1656                                         dbg(event->udev, "'%s' owner='%s', group='%s', mode=%#o partitions=%i\n",
1657                                             event->name, event->owner, event->group, event->mode,
1658                                             udev_device_get_num_fake_partitions(dev));
1659                         }
1660
1661                         if (!event->run_final && rule->run.operation != KEY_OP_UNSET) {
1662                                 struct udev_list_entry *list_entry;
1663
1664                                 if (rule->run.operation == KEY_OP_ASSIGN_FINAL)
1665                                         event->run_final = 1;
1666                                 if (rule->run.operation == KEY_OP_ASSIGN || rule->run.operation == KEY_OP_ASSIGN_FINAL) {
1667                                         info(event->udev, "reset run list\n");
1668                                         udev_list_cleanup(event->udev, &event->run_list);
1669                                 }
1670                                 dbg(event->udev, "add run '%s'\n", key_val(rule, &rule->run));
1671                                 list_entry = udev_list_entry_add(event->udev, &event->run_list,
1672                                                                  key_val(rule, &rule->run), NULL, 1, 0);
1673                                 if (rule->run_ignore_error && list_entry != NULL)
1674                                         udev_list_entry_set_flag(list_entry, 1);
1675                         }
1676
1677                         if (rule->last_rule) {
1678                                 dbg(event->udev, "last rule to be applied\n");
1679                                 break;
1680                         }
1681
1682                         if (rule->goto_label.operation != KEY_OP_UNSET) {
1683                                 dbg(event->udev, "moving forward to label '%s'\n", key_val(rule, &rule->goto_label));
1684                                 udev_rules_iter_goto(&iter, rule->goto_rule_off);
1685                         }
1686                 }
1687         }
1688
1689         if (!name_set) {
1690                 info(event->udev, "no node name set, will use kernel name '%s'\n",
1691                      udev_device_get_sysname(dev));
1692                 util_strlcpy(event->name, udev_device_get_sysname(dev), sizeof(event->name));
1693         }
1694
1695         if (event->tmp_node[0] != '\0') {
1696                 dbg(event->udev, "removing temporary device node\n");
1697                 unlink_secure(event->udev, event->tmp_node);
1698                 event->tmp_node[0] = '\0';
1699         }
1700         return 0;
1701 }
1702
1703 int udev_rules_get_run(struct udev_rules *rules, struct udev_event *event)
1704 {
1705         struct udev_device *dev = event->dev;
1706         struct udev_rules_iter iter;
1707         struct udev_rule *rule;
1708
1709         dbg(event->udev, "sysname: '%s'\n", udev_device_get_sysname(dev));
1710
1711         /* look for a matching rule to apply */
1712         udev_rules_iter_init(&iter, rules);
1713         while (1) {
1714                 rule = udev_rules_iter_next(&iter);
1715                 if (rule == NULL)
1716                         break;
1717
1718                 dbg(event->udev, "process rule\n");
1719                 if (rule->name.operation == KEY_OP_ASSIGN ||
1720                     rule->name.operation == KEY_OP_ASSIGN_FINAL ||
1721                     rule->name.operation == KEY_OP_ADD ||
1722                     rule->symlink.operation == KEY_OP_ASSIGN ||
1723                     rule->symlink.operation == KEY_OP_ASSIGN_FINAL ||
1724                     rule->symlink.operation == KEY_OP_ADD ||
1725                     rule->mode.operation != KEY_OP_UNSET ||
1726                     rule->owner.operation != KEY_OP_UNSET || rule->group.operation != KEY_OP_UNSET) {
1727                         dbg(event->udev, "skip rule that names a device\n");
1728                         continue;
1729                 }
1730
1731                 if (match_rule(event, rule) == 0) {
1732                         if (rule->ignore_device) {
1733                                 info(event->udev, "rule applied, '%s' is ignored\n", udev_device_get_sysname(dev));
1734                                 event->ignore_device = 1;
1735                                 return 0;
1736                         }
1737                         if (rule->ignore_remove) {
1738                                 udev_device_set_ignore_remove(dev, 1);
1739                                 dbg(event->udev, "remove event should be ignored\n");
1740                         }
1741
1742                         if (!event->run_final && rule->run.operation != KEY_OP_UNSET) {
1743                                 struct udev_list_entry *list_entry;
1744
1745                                 if (rule->run.operation == KEY_OP_ASSIGN ||
1746                                     rule->run.operation == KEY_OP_ASSIGN_FINAL) {
1747                                         info(event->udev, "reset run list\n");
1748                                         udev_list_cleanup(event->udev, &event->run_list);
1749                                 }
1750                                 dbg(event->udev, "add run '%s'\n", key_val(rule, &rule->run));
1751                                 list_entry = udev_list_entry_add(event->udev, &event->run_list,
1752                                                                  key_val(rule, &rule->run), NULL, 1, 0);
1753                                 if (rule->run_ignore_error && list_entry != NULL)
1754                                         udev_list_entry_set_flag(list_entry, 1);
1755                                 if (rule->run.operation == KEY_OP_ASSIGN_FINAL)
1756                                         break;
1757                         }
1758
1759                         if (rule->last_rule) {
1760                                 dbg(event->udev, "last rule to be applied\n");
1761                                 break;
1762                         }
1763
1764                         if (rule->goto_label.operation != KEY_OP_UNSET) {
1765                                 dbg(event->udev, "moving forward to label '%s'\n", key_val(rule, &rule->goto_label));
1766                                 udev_rules_iter_goto(&iter, rule->goto_rule_off);
1767                         }
1768                 }
1769         }
1770
1771         return 0;
1772 }
1773
1774 static int get_key(struct udev_rules *rules, char **line, char **key, enum key_operation *operation, char **value)
1775 {
1776         char *linepos;
1777         char *temp;
1778
1779         linepos = *line;
1780         if (linepos == NULL && linepos[0] == '\0')
1781                 return -1;
1782
1783         /* skip whitespace */
1784         while (isspace(linepos[0]) || linepos[0] == ',')
1785                 linepos++;
1786
1787         /* get the key */
1788         if (linepos[0] == '\0')
1789                 return -1;
1790         *key = linepos;
1791
1792         while (1) {
1793                 linepos++;
1794                 if (linepos[0] == '\0')
1795                         return -1;
1796                 if (isspace(linepos[0]))
1797                         break;
1798                 if (linepos[0] == '=')
1799                         break;
1800                 if ((linepos[0] == '+') || (linepos[0] == '!') || (linepos[0] == ':'))
1801                         if (linepos[1] == '=')
1802                                 break;
1803         }
1804
1805         /* remember end of key */
1806         temp = linepos;
1807
1808         /* skip whitespace after key */
1809         while (isspace(linepos[0]))
1810                 linepos++;
1811         if (linepos[0] == '\0')
1812                 return -1;
1813
1814         /* get operation type */
1815         if (linepos[0] == '=' && linepos[1] == '=') {
1816                 *operation = KEY_OP_MATCH;
1817                 linepos += 2;
1818                 dbg(rules->udev, "match:\n");
1819         } else if (linepos[0] == '!' && linepos[1] == '=') {
1820                 *operation = KEY_OP_NOMATCH;
1821                 linepos += 2;
1822                 dbg(rules->udev, "nomatch:\n");
1823         } else if (linepos[0] == '+' && linepos[1] == '=') {
1824                 *operation = KEY_OP_ADD;
1825                 linepos += 2;
1826                 dbg(rules->udev, "add:\n");
1827         } else if (linepos[0] == '=') {
1828                 *operation = KEY_OP_ASSIGN;
1829                 linepos++;
1830                 dbg(rules->udev, "assign:\n");
1831         } else if (linepos[0] == ':' && linepos[1] == '=') {
1832                 *operation = KEY_OP_ASSIGN_FINAL;
1833                 linepos += 2;
1834                 dbg(rules->udev, "assign_final:\n");
1835         } else
1836                 return -1;
1837
1838         /* terminate key */
1839         temp[0] = '\0';
1840
1841         /* skip whitespace after operator */
1842         while (isspace(linepos[0]))
1843                 linepos++;
1844         if (linepos[0] == '\0')
1845                 return -1;
1846
1847         /* get the value*/
1848         if (linepos[0] == '"')
1849                 linepos++;
1850         else
1851                 return -1;
1852         *value = linepos;
1853
1854         temp = strchr(linepos, '"');
1855         if (!temp)
1856                 return -1;
1857         temp[0] = '\0';
1858         temp++;
1859         dbg(rules->udev, "'%s'-'%s'\n", *key, *value);
1860
1861         /* move line to next key */
1862         *line = temp;
1863
1864         return 0;
1865 }
1866
1867 /* extract possible KEY{attr} */
1868 static char *get_key_attribute(struct udev_rules *rules, char *str)
1869 {
1870         char *pos;
1871         char *attr;
1872
1873         attr = strchr(str, '{');
1874         if (attr != NULL) {
1875                 attr++;
1876                 pos = strchr(attr, '}');
1877                 if (pos == NULL) {
1878                         err(rules->udev, "missing closing brace for format\n");
1879                         return NULL;
1880                 }
1881                 pos[0] = '\0';
1882                 dbg(rules->udev, "attribute='%s'\n", attr);
1883                 return attr;
1884         }
1885
1886         return NULL;
1887 }
1888
1889 static int add_rule_key(struct udev_rule *rule, struct key *key,
1890                         enum key_operation operation, const char *value)
1891 {
1892         size_t val_len = strnlen(value, UTIL_PATH_SIZE);
1893
1894         key->operation = operation;
1895
1896         key->val_off = rule->bufsize;
1897         util_strlcpy(rule->buf + rule->bufsize, value, val_len+1);
1898         rule->bufsize += val_len+1;
1899
1900         return 0;
1901 }
1902
1903 static int add_rule_key_pair(struct udev_rules *rules, struct udev_rule *rule, struct key_pairs *pairs,
1904                              enum key_operation operation, const char *key, const char *value)
1905 {
1906         size_t key_len = strnlen(key, UTIL_PATH_SIZE);
1907
1908         if (pairs->count >= PAIRS_MAX) {
1909                 err(rules->udev, "skip, too many keys of the same type in a single rule\n");
1910                 return -1;
1911         }
1912
1913         add_rule_key(rule, &pairs->keys[pairs->count].key, operation, value);
1914
1915         /* add the key-name of the pair */
1916         pairs->keys[pairs->count].key_name_off = rule->bufsize;
1917         util_strlcpy(rule->buf + rule->bufsize, key, key_len+1);
1918         rule->bufsize += key_len+1;
1919
1920         pairs->count++;
1921
1922         return 0;
1923 }
1924
1925 static int add_to_rules(struct udev_rules *rules, char *line, const char *filename, unsigned int lineno)
1926 {
1927         char buf[sizeof(struct udev_rule) + UTIL_LINE_SIZE];
1928         struct udev_rule *rule;
1929         size_t rule_size;
1930         int valid;
1931         char *linepos;
1932         char *attr;
1933         size_t padding;
1934         int physdev = 0;
1935         int retval;
1936
1937         memset(buf, 0x00, sizeof(buf));
1938         rule = (struct udev_rule *) buf;
1939         rule->event_timeout = -1;
1940         linepos = line;
1941         valid = 0;
1942
1943         /* get all the keys */
1944         while (1) {
1945                 char *key;
1946                 char *value;
1947                 enum key_operation operation = KEY_OP_UNSET;
1948
1949                 retval = get_key(rules, &linepos, &key, &operation, &value);
1950                 if (retval)
1951                         break;
1952
1953                 if (strcasecmp(key, "ACTION") == 0) {
1954                         if (operation != KEY_OP_MATCH &&
1955                             operation != KEY_OP_NOMATCH) {
1956                                 err(rules->udev, "invalid ACTION operation\n");
1957                                 goto invalid;
1958                         }
1959                         add_rule_key(rule, &rule->action, operation, value);
1960                         valid = 1;
1961                         continue;
1962                 }
1963
1964                 if (strcasecmp(key, "DEVPATH") == 0) {
1965                         if (operation != KEY_OP_MATCH &&
1966                             operation != KEY_OP_NOMATCH) {
1967                                 err(rules->udev, "invalid DEVPATH operation\n");
1968                                 goto invalid;
1969                         }
1970                         add_rule_key(rule, &rule->devpath, operation, value);
1971                         valid = 1;
1972                         continue;
1973                 }
1974
1975                 if (strcasecmp(key, "KERNEL") == 0) {
1976                         if (operation != KEY_OP_MATCH &&
1977                             operation != KEY_OP_NOMATCH) {
1978                                 err(rules->udev, "invalid KERNEL operation\n");
1979                                 goto invalid;
1980                         }
1981                         add_rule_key(rule, &rule->kernel, operation, value);
1982                         valid = 1;
1983                         continue;
1984                 }
1985
1986                 if (strcasecmp(key, "SUBSYSTEM") == 0) {
1987                         if (operation != KEY_OP_MATCH &&
1988                             operation != KEY_OP_NOMATCH) {
1989                                 err(rules->udev, "invalid SUBSYSTEM operation\n");
1990                                 goto invalid;
1991                         }
1992                         /* bus, class, subsystem events should all be the same */
1993                         if (strcmp(value, "subsystem") == 0 ||
1994                             strcmp(value, "bus") == 0 ||
1995                             strcmp(value, "class") == 0) {
1996                                 if (strcmp(value, "bus") == 0 || strcmp(value, "class") == 0)
1997                                         err(rules->udev, "'%s' must be specified as 'subsystem' \n"
1998                                             "please fix it in %s:%u", value, filename, lineno);
1999                                 add_rule_key(rule, &rule->subsystem, operation, "subsystem|class|bus");
2000                         } else
2001                                 add_rule_key(rule, &rule->subsystem, operation, value);
2002                         valid = 1;
2003                         continue;
2004                 }
2005
2006                 if (strcasecmp(key, "DRIVER") == 0) {
2007                         if (operation != KEY_OP_MATCH &&
2008                             operation != KEY_OP_NOMATCH) {
2009                                 err(rules->udev, "invalid DRIVER operation\n");
2010                                 goto invalid;
2011                         }
2012                         add_rule_key(rule, &rule->driver, operation, value);
2013                         valid = 1;
2014                         continue;
2015                 }
2016
2017                 if (strncasecmp(key, "ATTR{", sizeof("ATTR{")-1) == 0) {
2018                         attr = get_key_attribute(rules, key + sizeof("ATTR")-1);
2019                         if (attr == NULL) {
2020                                 err(rules->udev, "error parsing ATTR attribute\n");
2021                                 goto invalid;
2022                         }
2023                         if (add_rule_key_pair(rules, rule, &rule->attr, operation, attr, value) != 0)
2024                                 goto invalid;
2025                         valid = 1;
2026                         continue;
2027                 }
2028
2029                 if (strcasecmp(key, "KERNELS") == 0 ||
2030                     strcasecmp(key, "ID") == 0) {
2031                         if (operation != KEY_OP_MATCH &&
2032                             operation != KEY_OP_NOMATCH) {
2033                                 err(rules->udev, "invalid KERNELS operation\n");
2034                                 goto invalid;
2035                         }
2036                         add_rule_key(rule, &rule->kernels, operation, value);
2037                         valid = 1;
2038                         continue;
2039                 }
2040
2041                 if (strcasecmp(key, "SUBSYSTEMS") == 0 ||
2042                     strcasecmp(key, "BUS") == 0) {
2043                         if (operation != KEY_OP_MATCH &&
2044                             operation != KEY_OP_NOMATCH) {
2045                                 err(rules->udev, "invalid SUBSYSTEMS operation\n");
2046                                 goto invalid;
2047                         }
2048                         add_rule_key(rule, &rule->subsystems, operation, value);
2049                         valid = 1;
2050                         continue;
2051                 }
2052
2053                 if (strcasecmp(key, "DRIVERS") == 0) {
2054                         if (operation != KEY_OP_MATCH &&
2055                             operation != KEY_OP_NOMATCH) {
2056                                 err(rules->udev, "invalid DRIVERS operation\n");
2057                                 goto invalid;
2058                         }
2059                         add_rule_key(rule, &rule->drivers, operation, value);
2060                         valid = 1;
2061                         continue;
2062                 }
2063
2064                 if (strncasecmp(key, "ATTRS{", sizeof("ATTRS{")-1) == 0 ||
2065                     strncasecmp(key, "SYSFS{", sizeof("SYSFS{")-1) == 0) {
2066                         if (operation != KEY_OP_MATCH &&
2067                             operation != KEY_OP_NOMATCH) {
2068                                 err(rules->udev, "invalid ATTRS operation\n");
2069                                 goto invalid;
2070                         }
2071                         attr = get_key_attribute(rules, key + sizeof("ATTRS")-1);
2072                         if (attr == NULL) {
2073                                 err(rules->udev, "error parsing ATTRS attribute\n");
2074                                 goto invalid;
2075                         }
2076                         if (strncmp(attr, "device/", 7) == 0)
2077                                 err(rules->udev, "the 'device' link may not be available in a future kernel, "
2078                                     "please fix it in %s:%u", filename, lineno);
2079                         else if (strstr(attr, "../") != NULL)
2080                                 err(rules->udev, "do not reference parent sysfs directories directly, "
2081                                     "it may break with a future kernel, please fix it in %s:%u", filename, lineno);
2082                         if (add_rule_key_pair(rules, rule, &rule->attrs, operation, attr, value) != 0)
2083                                 goto invalid;
2084                         valid = 1;
2085                         continue;
2086                 }
2087
2088                 if (strncasecmp(key, "ENV{", sizeof("ENV{")-1) == 0) {
2089                         attr = get_key_attribute(rules, key + sizeof("ENV")-1);
2090                         if (attr == NULL) {
2091                                 err(rules->udev, "error parsing ENV attribute\n");
2092                                 goto invalid;
2093                         }
2094                         if (strncmp(attr, "PHYSDEV", 7) == 0)
2095                                 physdev = 1;
2096                         if (add_rule_key_pair(rules, rule, &rule->env, operation, attr, value) != 0)
2097                                 goto invalid;
2098                         valid = 1;
2099                         continue;
2100                 }
2101
2102                 if (strcasecmp(key, "PROGRAM") == 0) {
2103                         add_rule_key(rule, &rule->program, operation, value);
2104                         valid = 1;
2105                         continue;
2106                 }
2107
2108                 if (strcasecmp(key, "RESULT") == 0) {
2109                         if (operation != KEY_OP_MATCH &&
2110                             operation != KEY_OP_NOMATCH) {
2111                                 err(rules->udev, "invalid RESULT operation\n");
2112                                 goto invalid;
2113                         }
2114                         add_rule_key(rule, &rule->result, operation, value);
2115                         valid = 1;
2116                         continue;
2117                 }
2118
2119                 if (strncasecmp(key, "IMPORT", sizeof("IMPORT")-1) == 0) {
2120                         attr = get_key_attribute(rules, key + sizeof("IMPORT")-1);
2121                         if (attr != NULL && strstr(attr, "program")) {
2122                                 dbg(rules->udev, "IMPORT will be executed\n");
2123                                 rule->import_type  = IMPORT_PROGRAM;
2124                         } else if (attr != NULL && strstr(attr, "file")) {
2125                                 dbg(rules->udev, "IMPORT will be included as file\n");
2126                                 rule->import_type  = IMPORT_FILE;
2127                         } else if (attr != NULL && strstr(attr, "parent")) {
2128                                 dbg(rules->udev, "IMPORT will include the parent values\n");
2129                                 rule->import_type = IMPORT_PARENT;
2130                         } else {
2131                                 /* figure it out if it is executable */
2132                                 char file[UTIL_PATH_SIZE];
2133                                 char *pos;
2134                                 struct stat statbuf;
2135
2136                                 util_strlcpy(file, value, sizeof(file));
2137                                 pos = strchr(file, ' ');
2138                                 if (pos)
2139                                         pos[0] = '\0';
2140
2141                                 /* allow programs in /lib/udev called without the path */
2142                                 if (strchr(file, '/') == NULL) {
2143                                         util_strlcpy(file, UDEV_PREFIX "/lib/udev/", sizeof(file));
2144                                         util_strlcat(file, value, sizeof(file));
2145                                         pos = strchr(file, ' ');
2146                                         if (pos)
2147                                                 pos[0] = '\0';
2148                                 }
2149
2150                                 dbg(rules->udev, "IMPORT auto mode for '%s'\n", file);
2151                                 if (!lstat(file, &statbuf) && (statbuf.st_mode & S_IXUSR)) {
2152                                         dbg(rules->udev, "IMPORT is executable, will be executed (autotype)\n");
2153                                         rule->import_type  = IMPORT_PROGRAM;
2154                                 } else {
2155                                         dbg(rules->udev, "IMPORT is not executable, will be included as file (autotype)\n");
2156                                         rule->import_type  = IMPORT_FILE;
2157                                 }
2158                         }
2159                         add_rule_key(rule, &rule->import, operation, value);
2160                         valid = 1;
2161                         continue;
2162                 }
2163
2164                 if (strncasecmp(key, "TEST", sizeof("TEST")-1) == 0) {
2165                         if (operation != KEY_OP_MATCH &&
2166                             operation != KEY_OP_NOMATCH) {
2167                                 err(rules->udev, "invalid TEST operation\n");
2168                                 goto invalid;
2169                         }
2170                         attr = get_key_attribute(rules, key + sizeof("TEST")-1);
2171                         if (attr != NULL)
2172                                 rule->test_mode_mask = strtol(attr, NULL, 8);
2173                         add_rule_key(rule, &rule->test, operation, value);
2174                         valid = 1;
2175                         continue;
2176                 }
2177
2178                 if (strncasecmp(key, "RUN", sizeof("RUN")-1) == 0) {
2179                         attr = get_key_attribute(rules, key + sizeof("RUN")-1);
2180                         if (attr != NULL) {
2181                                 if (strstr(attr, "ignore_error"))
2182                                         rule->run_ignore_error = 1;
2183                         }
2184                         add_rule_key(rule, &rule->run, operation, value);
2185                         valid = 1;
2186                         continue;
2187                 }
2188
2189                 if (strcasecmp(key, "WAIT_FOR") == 0 || strcasecmp(key, "WAIT_FOR_SYSFS") == 0) {
2190                         add_rule_key(rule, &rule->wait_for, operation, value);
2191                         valid = 1;
2192                         continue;
2193                 }
2194
2195                 if (strcasecmp(key, "LABEL") == 0) {
2196                         add_rule_key(rule, &rule->label, operation, value);
2197                         valid = 1;
2198                         continue;
2199                 }
2200
2201                 if (strcasecmp(key, "GOTO") == 0) {
2202                         add_rule_key(rule, &rule->goto_label, operation, value);
2203                         valid = 1;
2204                         continue;
2205                 }
2206
2207                 if (strncasecmp(key, "NAME", sizeof("NAME")-1) == 0) {
2208                         attr = get_key_attribute(rules, key + sizeof("NAME")-1);
2209                         if (attr != NULL) {
2210                                 if (strstr(attr, "all_partitions") != NULL) {
2211                                         dbg(rules->udev, "creation of partition nodes requested\n");
2212                                         rule->partitions = DEFAULT_FAKE_PARTITIONS_COUNT;
2213                                 }
2214                                 if (strstr(attr, "ignore_remove") != NULL) {
2215                                         dbg(rules->udev, "remove event should be ignored\n");
2216                                         rule->ignore_remove = 1;
2217                                 }
2218                         }
2219                         if (value[0] == '\0')
2220                                 dbg(rules->udev, "name empty, node creation supressed\n");
2221                         add_rule_key(rule, &rule->name, operation, value);
2222                         continue;
2223                 }
2224
2225                 if (strcasecmp(key, "SYMLINK") == 0) {
2226                         if (operation == KEY_OP_MATCH ||
2227                             operation == KEY_OP_NOMATCH)
2228                                 add_rule_key(rule, &rule->symlink_match, operation, value);
2229                         else
2230                                 add_rule_key(rule, &rule->symlink, operation, value);
2231                         valid = 1;
2232                         continue;
2233                 }
2234
2235                 if (strcasecmp(key, "OWNER") == 0) {
2236                         valid = 1;
2237                         if (rules->resolve_names && (!strchr(value, '$') && !strchr(value, '%'))) {
2238                                 char *endptr;
2239                                 strtoul(value, &endptr, 10);
2240                                 if (endptr[0] != '\0') {
2241                                         char owner[32];
2242                                         uid_t uid = lookup_user(rules->udev, value);
2243                                         dbg(rules->udev, "replacing username='%s' by id=%i\n", value, uid);
2244                                         sprintf(owner, "%u", (unsigned int) uid);
2245                                         add_rule_key(rule, &rule->owner, operation, owner);
2246                                         continue;
2247                                 }
2248                         }
2249
2250                         add_rule_key(rule, &rule->owner, operation, value);
2251                         continue;
2252                 }
2253
2254                 if (strcasecmp(key, "GROUP") == 0) {
2255                         valid = 1;
2256                         if (rules->resolve_names && (!strchr(value, '$') && !strchr(value, '%'))) {
2257                                 char *endptr;
2258                                 strtoul(value, &endptr, 10);
2259                                 if (endptr[0] != '\0') {
2260                                         char group[32];
2261                                         gid_t gid = lookup_group(rules->udev, value);
2262                                         dbg(rules->udev, "replacing groupname='%s' by id=%i\n", value, gid);
2263                                         sprintf(group, "%u", (unsigned int) gid);
2264                                         add_rule_key(rule, &rule->group, operation, group);
2265                                         continue;
2266                                 }
2267                         }
2268
2269                         add_rule_key(rule, &rule->group, operation, value);
2270                         continue;
2271                 }
2272
2273                 if (strcasecmp(key, "MODE") == 0) {
2274                         add_rule_key(rule, &rule->mode, operation, value);
2275                         valid = 1;
2276                         continue;
2277                 }
2278
2279                 if (strcasecmp(key, "OPTIONS") == 0) {
2280                         const char *pos;
2281
2282                         if (strstr(value, "last_rule") != NULL) {
2283                                 dbg(rules->udev, "last rule to be applied\n");
2284                                 rule->last_rule = 1;
2285                         }
2286                         if (strstr(value, "ignore_device") != NULL) {
2287                                 dbg(rules->udev, "device should be ignored\n");
2288                                 rule->ignore_device = 1;
2289                         }
2290                         if (strstr(value, "ignore_remove") != NULL) {
2291                                 dbg(rules->udev, "remove event should be ignored\n");
2292                                 rule->ignore_remove = 1;
2293                         }
2294                         pos = strstr(value, "link_priority=");
2295                         if (pos != NULL) {
2296                                 rule->link_priority = atoi(&pos[strlen("link_priority=")]);
2297                                 dbg(rules->udev, "link priority=%i\n", rule->link_priority);
2298                         }
2299                         pos = strstr(value, "event_timeout=");
2300                         if (pos != NULL) {
2301                                 rule->event_timeout = atoi(&pos[strlen("event_timeout=")]);
2302                                 dbg(rules->udev, "event timout=%i\n", rule->event_timeout);
2303                         }
2304                         pos = strstr(value, "string_escape=");
2305                         if (pos != NULL) {
2306                                 pos = &pos[strlen("string_escape=")];
2307                                 if (strncmp(pos, "none", strlen("none")) == 0)
2308                                         rule->string_escape = ESCAPE_NONE;
2309                                 else if (strncmp(pos, "replace", strlen("replace")) == 0)
2310                                         rule->string_escape = ESCAPE_REPLACE;
2311                         }
2312                         if (strstr(value, "all_partitions") != NULL) {
2313                                 dbg(rules->udev, "creation of partition nodes requested\n");
2314                                 rule->partitions = DEFAULT_FAKE_PARTITIONS_COUNT;
2315                         }
2316                         valid = 1;
2317                         continue;
2318                 }
2319
2320                 err(rules->udev, "unknown key '%s' in %s:%u\n", key, filename, lineno);
2321         }
2322
2323         if (physdev && rule->wait_for.operation == KEY_OP_UNSET)
2324                 err(rules->udev, "PHYSDEV* values are deprecated and will be removed from a future kernel, \n"
2325                     "please fix it in %s:%u", filename, lineno);
2326
2327         /* skip line if not any valid key was found */
2328         if (!valid)
2329                 goto invalid;
2330
2331         /* grow buffer and add rule */
2332         rule_size = sizeof(struct udev_rule) + rule->bufsize;
2333         padding = (sizeof(size_t) - rule_size % sizeof(size_t)) % sizeof(size_t);
2334         dbg(rules->udev, "add %zi padding bytes\n", padding);
2335         rule_size += padding;
2336         rule->bufsize += padding;
2337
2338         rules->buf = realloc(rules->buf, rules->bufsize + rule_size);
2339         if (!rules->buf) {
2340                 err(rules->udev, "realloc failed\n");
2341                 goto exit;
2342         }
2343         dbg(rules->udev, "adding rule to offset %zi\n", rules->bufsize);
2344         memcpy(rules->buf + rules->bufsize, rule, rule_size);
2345         rules->bufsize += rule_size;
2346 exit:
2347         return 0;
2348
2349 invalid:
2350         err(rules->udev, "invalid rule '%s:%u'\n", filename, lineno);
2351         return -1;
2352 }
2353
2354 static int parse_file(struct udev_rules *rules, const char *filename)
2355 {
2356         FILE *f;
2357         char line[UTIL_LINE_SIZE];
2358         size_t start;
2359         struct udev_rule *rule;
2360         struct udev_rules_iter iter;
2361
2362         start = rules->bufsize;
2363         info(rules->udev, "reading '%s' as rules file\n", filename);
2364
2365         f = fopen(filename, "r");
2366         if (f == NULL)
2367                 return -1;
2368
2369         while(fgets(line, sizeof(line), f) != NULL) {
2370                 int line_nr = 0;
2371                 char *key;
2372                 size_t len;
2373
2374                 /* skip whitespace */
2375                 line_nr++;
2376                 key = line;
2377                 while (isspace(key[0]))
2378                         key++;
2379
2380                 /* comment */
2381                 if (key[0] == '#')
2382                         continue;
2383
2384                 len = strlen(line);
2385                 if (len < 3)
2386                         continue;
2387
2388                 /* continue reading if backslash+newline is found */
2389                 while (line[len-2] == '\\') {
2390                         if (fgets(&line[len-2], (sizeof(line)-len)+2, f) == NULL)
2391                                 break;
2392                         line_nr++;
2393                         len = strlen(line);
2394                 }
2395
2396                 if (len+1 >= sizeof(line)) {
2397                         err(rules->udev, "line too long '%s':%u, ignored\n", filename, line_nr);
2398                         continue;
2399                 }
2400                 add_to_rules(rules, key, filename, line_nr);
2401         }
2402         fclose(f);
2403
2404         /* compute all goto targets within this file */
2405         udev_rules_iter_init(&iter, rules);
2406         udev_rules_iter_goto(&iter, start);
2407         while((rule = udev_rules_iter_next(&iter))) {
2408                 if (rule->goto_label.operation != KEY_OP_UNSET) {
2409                         char *goto_label = &rule->buf[rule->goto_label.val_off];
2410
2411                         dbg(rules->udev, "resolving goto label '%s'\n", goto_label);
2412                         rule->goto_rule_off = find_label(&iter, goto_label);
2413                         if (rule->goto_rule_off == 0) {
2414                                 err(rules->udev, "ignore goto to nonexistent label '%s' in '%s'\n",
2415                                     goto_label, filename);
2416                                 rule->goto_rule_off = iter.current;
2417                         }
2418                 }
2419         }
2420         return 0;
2421 }
2422
2423 static int add_matching_files(struct udev *udev, struct udev_list_node *file_list, const char *dirname, const char *suffix)
2424 {
2425         struct dirent *ent;
2426         DIR *dir;
2427         char filename[UTIL_PATH_SIZE];
2428
2429         dbg(udev, "open directory '%s'\n", dirname);
2430         dir = opendir(dirname);
2431         if (dir == NULL) {
2432                 err(udev, "unable to open '%s': %m\n", dirname);
2433                 return -1;
2434         }
2435
2436         while (1) {
2437                 ent = readdir(dir);
2438                 if (ent == NULL || ent->d_name[0] == '\0')
2439                         break;
2440
2441                 if ((ent->d_name[0] == '.') || (ent->d_name[0] == '#'))
2442                         continue;
2443
2444                 /* look for file matching with specified suffix */
2445                 if (suffix != NULL) {
2446                         const char *ext;
2447
2448                         ext = strrchr(ent->d_name, '.');
2449                         if (ext == NULL)
2450                                 continue;
2451                         if (strcmp(ext, suffix) != 0)
2452                                 continue;
2453                 }
2454                 dbg(udev, "put file '%s/%s' into list\n", dirname, ent->d_name);
2455
2456                 snprintf(filename, sizeof(filename), "%s/%s", dirname, ent->d_name);
2457                 filename[sizeof(filename)-1] = '\0';
2458                 udev_list_entry_add(udev, file_list, filename, NULL, 1, 1);
2459         }
2460
2461         closedir(dir);
2462         return 0;
2463 }
2464
2465 int udev_rules_init(struct udev *udev, struct udev_rules *rules, int resolve_names)
2466 {
2467         struct stat statbuf;
2468         char filename[PATH_MAX];
2469         struct udev_list_node file_list;
2470         struct udev_list_entry *file_loop, *file_tmp;
2471         int retval = 0;
2472
2473         memset(rules, 0x00, sizeof(struct udev_rules));
2474         rules->udev = udev;
2475         rules->resolve_names = resolve_names;
2476         udev_list_init(&file_list);
2477
2478         if (udev_get_rules_path(udev) != NULL) {
2479                 /* custom rules location for testing */
2480                 add_matching_files(udev, &file_list, udev_get_rules_path(udev), ".rules");
2481         } else {
2482                 struct udev_list_node sort_list;
2483                 struct udev_list_entry *sort_loop, *sort_tmp;
2484
2485                 /* read user/custom rules */
2486                 add_matching_files(udev, &file_list, SYSCONFDIR "/udev/rules.d", ".rules");
2487
2488                 /* read dynamic/temporary rules */
2489                 util_strlcpy(filename, udev_get_dev_path(udev), sizeof(filename));
2490                 util_strlcat(filename, "/.udev/rules.d", sizeof(filename));
2491                 if (stat(filename, &statbuf) != 0) {
2492                         create_path(udev, filename);
2493                         udev_selinux_setfscreatecon(udev, filename, S_IFDIR|0755);
2494                         mkdir(filename, 0755);
2495                         udev_selinux_resetfscreatecon(udev);
2496                 }
2497                 udev_list_init(&sort_list);
2498                 add_matching_files(udev, &sort_list, filename, ".rules");
2499
2500                 /* read default rules */
2501                 add_matching_files(udev, &sort_list, UDEV_PREFIX "/lib/udev/rules.d", ".rules");
2502
2503                 /* sort all rules files by basename into list of files */
2504                 udev_list_entry_foreach_safe(sort_loop, sort_tmp, udev_list_get_entry(&sort_list)) {
2505                         const char *sort_name = udev_list_entry_get_name(sort_loop);
2506                         const char *sort_base = strrchr(sort_name, '/');
2507
2508                         if (sort_base == NULL)
2509                                 continue;
2510
2511                         udev_list_entry_foreach_safe(file_loop, file_tmp, udev_list_get_entry(&file_list)) {
2512                                 const char *file_name = udev_list_entry_get_name(file_loop);
2513                                 const char *file_base = strrchr(file_name, '/');
2514
2515                                 if (file_base == NULL)
2516                                         continue;
2517                                 if (strcmp(file_base, sort_base) == 0) {
2518                                         info(udev, "rule file basename '%s' already added, ignoring '%s'\n",
2519                                              file_name, sort_name);
2520                                         udev_list_entry_remove(sort_loop);
2521                                         sort_loop = NULL;
2522                                         break;
2523                                 }
2524                                 if (strcmp(file_base, sort_base) > 0)
2525                                         break;
2526                         }
2527                         if (sort_loop != NULL)
2528                                 udev_list_entry_move_before(sort_loop, file_loop);
2529                 }
2530         }
2531
2532         /* parse list of files */
2533         udev_list_entry_foreach_safe(file_loop, file_tmp, udev_list_get_entry(&file_list)) {
2534                 const char *file_name = udev_list_entry_get_name(file_loop);
2535
2536                 if (stat(file_name, &statbuf) == 0 && statbuf.st_size > 0)
2537                         parse_file(rules, file_name);
2538                 else
2539                         info(udev, "can not read '%s'\n", file_name);
2540                 udev_list_entry_remove(file_loop);
2541         }
2542         return retval;
2543 }
2544
2545 void udev_rules_cleanup(struct udev_rules *rules)
2546 {
2547         if (rules->buf) {
2548                 free(rules->buf);
2549                 rules->buf = NULL;
2550         }
2551 }