chiark / gitweb /
readahead-analyze: don't call fclose on null
[elogind.git] / src / udev / udev-rules.c
1 /*
2  * Copyright (C) 2003-2012 Kay Sievers <kay.sievers@vrfy.org>
3  * Copyright (C) 2008 Alan Jenkins <alan-jenkins@tuffmail.co.uk>
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 <limits.h>
21 #include <stdlib.h>
22 #include <stdbool.h>
23 #include <string.h>
24 #include <stdio.h>
25 #include <fcntl.h>
26 #include <ctype.h>
27 #include <unistd.h>
28 #include <errno.h>
29 #include <dirent.h>
30 #include <fnmatch.h>
31 #include <time.h>
32
33 #include "udev.h"
34 #include "path-util.h"
35 #include "conf-files.h"
36
37 #define PREALLOC_TOKEN          2048
38 #define PREALLOC_STRBUF         32 * 1024
39 #define PREALLOC_TRIE           256
40
41 struct uid_gid {
42         unsigned int name_off;
43         union {
44                 uid_t uid;
45                 gid_t gid;
46         };
47 };
48
49 struct trie_node {
50         /* this node's first child */
51         unsigned int child_idx;
52         /* the next child of our parent node's child list */
53         unsigned int next_child_idx;
54         /* this node's last child (shortcut for append) */
55         unsigned int last_child_idx;
56         unsigned int value_off;
57         unsigned short value_len;
58         unsigned char key;
59 };
60
61 struct udev_rules {
62         struct udev *udev;
63         char **dirs;
64         unsigned long long *dirs_ts_usec;
65         int resolve_names;
66
67         /* every key in the rules file becomes a token */
68         struct token *tokens;
69         unsigned int token_cur;
70         unsigned int token_max;
71
72         /* all key strings are copied to a single string buffer */
73         char *buf;
74         size_t buf_cur;
75         size_t buf_max;
76         unsigned int buf_count;
77
78         /* during rule parsing, strings are indexed and de-duplicated */
79         struct trie_node *trie_nodes;
80         unsigned int trie_nodes_cur;
81         unsigned int trie_nodes_max;
82
83         /* during rule parsing, uid/gid lookup results are cached */
84         struct uid_gid *uids;
85         unsigned int uids_cur;
86         unsigned int uids_max;
87         struct uid_gid *gids;
88         unsigned int gids_cur;
89         unsigned int gids_max;
90 };
91
92 /* KEY=="", KEY!="", KEY+="", KEY="", KEY:="" */
93 enum operation_type {
94         OP_UNSET,
95
96         OP_MATCH,
97         OP_NOMATCH,
98         OP_MATCH_MAX,
99
100         OP_ADD,
101         OP_ASSIGN,
102         OP_ASSIGN_FINAL,
103 };
104
105 enum string_glob_type {
106         GL_UNSET,
107         GL_PLAIN,                       /* no special chars */
108         GL_GLOB,                        /* shell globs ?,*,[] */
109         GL_SPLIT,                       /* multi-value A|B */
110         GL_SPLIT_GLOB,                  /* multi-value with glob A*|B* */
111         GL_SOMETHING,                   /* commonly used "?*" */
112 };
113
114 enum string_subst_type {
115         SB_UNSET,
116         SB_NONE,
117         SB_FORMAT,
118         SB_SUBSYS,
119 };
120
121 /* tokens of a rule are sorted/handled in this order */
122 enum token_type {
123         TK_UNSET,
124         TK_RULE,
125
126         TK_M_ACTION,                    /* val */
127         TK_M_DEVPATH,                   /* val */
128         TK_M_KERNEL,                    /* val */
129         TK_M_DEVLINK,                   /* val */
130         TK_M_NAME,                      /* val */
131         TK_M_ENV,                       /* val, attr */
132         TK_M_TAG,                       /* val */
133         TK_M_SUBSYSTEM,                 /* val */
134         TK_M_DRIVER,                    /* val */
135         TK_M_WAITFOR,                   /* val */
136         TK_M_ATTR,                      /* val, attr */
137
138         TK_M_PARENTS_MIN,
139         TK_M_KERNELS,                   /* val */
140         TK_M_SUBSYSTEMS,                /* val */
141         TK_M_DRIVERS,                   /* val */
142         TK_M_ATTRS,                     /* val, attr */
143         TK_M_TAGS,                      /* val */
144         TK_M_PARENTS_MAX,
145
146         TK_M_TEST,                      /* val, mode_t */
147         TK_M_EVENT_TIMEOUT,             /* int */
148         TK_M_PROGRAM,                   /* val */
149         TK_M_IMPORT_FILE,               /* val */
150         TK_M_IMPORT_PROG,               /* val */
151         TK_M_IMPORT_BUILTIN,            /* val */
152         TK_M_IMPORT_DB,                 /* val */
153         TK_M_IMPORT_CMDLINE,            /* val */
154         TK_M_IMPORT_PARENT,             /* val */
155         TK_M_RESULT,                    /* val */
156         TK_M_MAX,
157
158         TK_A_STRING_ESCAPE_NONE,
159         TK_A_STRING_ESCAPE_REPLACE,
160         TK_A_DB_PERSIST,
161         TK_A_INOTIFY_WATCH,             /* int */
162         TK_A_DEVLINK_PRIO,              /* int */
163         TK_A_OWNER,                     /* val */
164         TK_A_GROUP,                     /* val */
165         TK_A_MODE,                      /* val */
166         TK_A_OWNER_ID,                  /* uid_t */
167         TK_A_GROUP_ID,                  /* gid_t */
168         TK_A_MODE_ID,                   /* mode_t */
169         TK_A_STATIC_NODE,               /* val */
170         TK_A_ENV,                       /* val, attr */
171         TK_A_TAG,                       /* val */
172         TK_A_NAME,                      /* val */
173         TK_A_DEVLINK,                   /* val */
174         TK_A_ATTR,                      /* val, attr */
175         TK_A_RUN_BUILTIN,               /* val, bool */
176         TK_A_RUN_PROGRAM,               /* val, bool */
177         TK_A_GOTO,                      /* size_t */
178
179         TK_END,
180 };
181
182 /* we try to pack stuff in a way that we take only 12 bytes per token */
183 struct token {
184         union {
185                 unsigned char type;                /* same in rule and key */
186                 struct {
187                         enum token_type type:8;
188                         bool can_set_name:1;
189                         bool has_static_node:1;
190                         unsigned int unused:6;
191                         unsigned short token_count;
192                         unsigned int label_off;
193                         unsigned short filename_off;
194                         unsigned short filename_line;
195                 } rule;
196                 struct {
197                         enum token_type type:8;
198                         enum operation_type op:8;
199                         enum string_glob_type glob:8;
200                         enum string_subst_type subst:4;
201                         enum string_subst_type attrsubst:4;
202                         unsigned int value_off;
203                         union {
204                                 unsigned int attr_off;
205                                 int devlink_unique;
206                                 unsigned int rule_goto;
207                                 mode_t  mode;
208                                 uid_t uid;
209                                 gid_t gid;
210                                 int devlink_prio;
211                                 int event_timeout;
212                                 int watch;
213                                 enum udev_builtin_cmd builtin_cmd;
214                         };
215                 } key;
216         };
217 };
218
219 #define MAX_TK                64
220 struct rule_tmp {
221         struct udev_rules *rules;
222         struct token rule;
223         struct token token[MAX_TK];
224         unsigned int token_cur;
225 };
226
227 #ifdef DEBUG
228 static const char *operation_str(enum operation_type type)
229 {
230         static const char *operation_strs[] = {
231                 [OP_UNSET] =            "UNSET",
232                 [OP_MATCH] =            "match",
233                 [OP_NOMATCH] =          "nomatch",
234                 [OP_MATCH_MAX] =        "MATCH_MAX",
235
236                 [OP_ADD] =              "add",
237                 [OP_ASSIGN] =           "assign",
238                 [OP_ASSIGN_FINAL] =     "assign-final",
239 }        ;
240
241         return operation_strs[type];
242 }
243
244 static const char *string_glob_str(enum string_glob_type type)
245 {
246         static const char *string_glob_strs[] = {
247                 [GL_UNSET] =            "UNSET",
248                 [GL_PLAIN] =            "plain",
249                 [GL_GLOB] =             "glob",
250                 [GL_SPLIT] =            "split",
251                 [GL_SPLIT_GLOB] =       "split-glob",
252                 [GL_SOMETHING] =        "split-glob",
253         };
254
255         return string_glob_strs[type];
256 }
257
258 static const char *token_str(enum token_type type)
259 {
260         static const char *token_strs[] = {
261                 [TK_UNSET] =                    "UNSET",
262                 [TK_RULE] =                     "RULE",
263
264                 [TK_M_ACTION] =                 "M ACTION",
265                 [TK_M_DEVPATH] =                "M DEVPATH",
266                 [TK_M_KERNEL] =                 "M KERNEL",
267                 [TK_M_DEVLINK] =                "M DEVLINK",
268                 [TK_M_NAME] =                   "M NAME",
269                 [TK_M_ENV] =                    "M ENV",
270                 [TK_M_TAG] =                    "M TAG",
271                 [TK_M_SUBSYSTEM] =              "M SUBSYSTEM",
272                 [TK_M_DRIVER] =                 "M DRIVER",
273                 [TK_M_WAITFOR] =                "M WAITFOR",
274                 [TK_M_ATTR] =                   "M ATTR",
275
276                 [TK_M_PARENTS_MIN] =            "M PARENTS_MIN",
277                 [TK_M_KERNELS] =                "M KERNELS",
278                 [TK_M_SUBSYSTEMS] =             "M SUBSYSTEMS",
279                 [TK_M_DRIVERS] =                "M DRIVERS",
280                 [TK_M_ATTRS] =                  "M ATTRS",
281                 [TK_M_TAGS] =                   "M TAGS",
282                 [TK_M_PARENTS_MAX] =            "M PARENTS_MAX",
283
284                 [TK_M_TEST] =                   "M TEST",
285                 [TK_M_EVENT_TIMEOUT] =          "M EVENT_TIMEOUT",
286                 [TK_M_PROGRAM] =                "M PROGRAM",
287                 [TK_M_IMPORT_FILE] =            "M IMPORT_FILE",
288                 [TK_M_IMPORT_PROG] =            "M IMPORT_PROG",
289                 [TK_M_IMPORT_BUILTIN] =         "M IMPORT_BUILTIN",
290                 [TK_M_IMPORT_DB] =              "M IMPORT_DB",
291                 [TK_M_IMPORT_CMDLINE] =         "M IMPORT_CMDLINE",
292                 [TK_M_IMPORT_PARENT] =          "M IMPORT_PARENT",
293                 [TK_M_RESULT] =                 "M RESULT",
294                 [TK_M_MAX] =                    "M MAX",
295
296                 [TK_A_STRING_ESCAPE_NONE] =     "A STRING_ESCAPE_NONE",
297                 [TK_A_STRING_ESCAPE_REPLACE] =  "A STRING_ESCAPE_REPLACE",
298                 [TK_A_DB_PERSIST] =             "A DB_PERSIST",
299                 [TK_A_INOTIFY_WATCH] =          "A INOTIFY_WATCH",
300                 [TK_A_DEVLINK_PRIO] =           "A DEVLINK_PRIO",
301                 [TK_A_OWNER] =                  "A OWNER",
302                 [TK_A_GROUP] =                  "A GROUP",
303                 [TK_A_MODE] =                   "A MODE",
304                 [TK_A_OWNER_ID] =               "A OWNER_ID",
305                 [TK_A_GROUP_ID] =               "A GROUP_ID",
306                 [TK_A_STATIC_NODE] =            "A STATIC_NODE",
307                 [TK_A_MODE_ID] =                "A MODE_ID",
308                 [TK_A_ENV] =                    "A ENV",
309                 [TK_A_TAG] =                    "A ENV",
310                 [TK_A_NAME] =                   "A NAME",
311                 [TK_A_DEVLINK] =                "A DEVLINK",
312                 [TK_A_ATTR] =                   "A ATTR",
313                 [TK_A_RUN_BUILTIN] =            "A RUN_BUILTIN",
314                 [TK_A_RUN_PROGRAM] =            "A RUN_PROGRAM",
315                 [TK_A_GOTO] =                   "A GOTO",
316
317                 [TK_END] =                      "END",
318         };
319
320         return token_strs[type];
321 }
322
323 static void dump_token(struct udev_rules *rules, struct token *token)
324 {
325         enum token_type type = token->type;
326         enum operation_type op = token->key.op;
327         enum string_glob_type glob = token->key.glob;
328         const char *value = &rules->buf[token->key.value_off];
329         const char *attr = &rules->buf[token->key.attr_off];
330
331         switch (type) {
332         case TK_RULE:
333                 {
334                         const char *tks_ptr = (char *)rules->tokens;
335                         const char *tk_ptr = (char *)token;
336                         unsigned int idx = (tk_ptr - tks_ptr) / sizeof(struct token);
337
338                         log_debug("* RULE %s:%u, token: %u, count: %u, label: '%s'\n",
339                                   &rules->buf[token->rule.filename_off], token->rule.filename_line,
340                                   idx, token->rule.token_count,
341                                   &rules->buf[token->rule.label_off]);
342                         break;
343                 }
344         case TK_M_ACTION:
345         case TK_M_DEVPATH:
346         case TK_M_KERNEL:
347         case TK_M_SUBSYSTEM:
348         case TK_M_DRIVER:
349         case TK_M_WAITFOR:
350         case TK_M_DEVLINK:
351         case TK_M_NAME:
352         case TK_M_KERNELS:
353         case TK_M_SUBSYSTEMS:
354         case TK_M_DRIVERS:
355         case TK_M_TAGS:
356         case TK_M_PROGRAM:
357         case TK_M_IMPORT_FILE:
358         case TK_M_IMPORT_PROG:
359         case TK_M_IMPORT_DB:
360         case TK_M_IMPORT_CMDLINE:
361         case TK_M_IMPORT_PARENT:
362         case TK_M_RESULT:
363         case TK_A_NAME:
364         case TK_A_DEVLINK:
365         case TK_A_OWNER:
366         case TK_A_GROUP:
367         case TK_A_MODE:
368         case TK_A_RUN_BUILTIN:
369         case TK_A_RUN_PROGRAM:
370                 log_debug("%s %s '%s'(%s)\n",
371                           token_str(type), operation_str(op), value, string_glob_str(glob));
372                 break;
373         case TK_M_IMPORT_BUILTIN:
374                 log_debug("%s %i '%s'\n", token_str(type), token->key.builtin_cmd, value);
375                 break;
376         case TK_M_ATTR:
377         case TK_M_ATTRS:
378         case TK_M_ENV:
379         case TK_A_ATTR:
380         case TK_A_ENV:
381                 log_debug("%s %s '%s' '%s'(%s)\n",
382                           token_str(type), operation_str(op), attr, value, string_glob_str(glob));
383                 break;
384         case TK_M_TAG:
385         case TK_A_TAG:
386                 log_debug("%s %s '%s'\n", token_str(type), operation_str(op), value);
387                 break;
388         case TK_A_STRING_ESCAPE_NONE:
389         case TK_A_STRING_ESCAPE_REPLACE:
390         case TK_A_DB_PERSIST:
391                 log_debug("%s\n", token_str(type));
392                 break;
393         case TK_M_TEST:
394                 log_debug("%s %s '%s'(%s) %#o\n",
395                           token_str(type), operation_str(op), value, string_glob_str(glob), token->key.mode);
396                 break;
397         case TK_A_INOTIFY_WATCH:
398                 log_debug("%s %u\n", token_str(type), token->key.watch);
399                 break;
400         case TK_A_DEVLINK_PRIO:
401                 log_debug("%s %u\n", token_str(type), token->key.devlink_prio);
402                 break;
403         case TK_A_OWNER_ID:
404                 log_debug("%s %s %u\n", token_str(type), operation_str(op), token->key.uid);
405                 break;
406         case TK_A_GROUP_ID:
407                 log_debug("%s %s %u\n", token_str(type), operation_str(op), token->key.gid);
408                 break;
409         case TK_A_MODE_ID:
410                 log_debug("%s %s %#o\n", token_str(type), operation_str(op), token->key.mode);
411                 break;
412         case TK_A_STATIC_NODE:
413                 log_debug("%s '%s'\n", token_str(type), value);
414                 break;
415         case TK_M_EVENT_TIMEOUT:
416                 log_debug("%s %u\n", token_str(type), token->key.event_timeout);
417                 break;
418         case TK_A_GOTO:
419                 log_debug("%s '%s' %u\n", token_str(type), value, token->key.rule_goto);
420                 break;
421         case TK_END:
422                 log_debug("* %s\n", token_str(type));
423                 break;
424         case TK_M_PARENTS_MIN:
425         case TK_M_PARENTS_MAX:
426         case TK_M_MAX:
427         case TK_UNSET:
428                 log_debug("unknown type %u\n", type);
429                 break;
430         }
431 }
432
433 static void dump_rules(struct udev_rules *rules)
434 {
435         unsigned int i;
436
437         log_debug("dumping %u (%zu bytes) tokens, %u (%zu bytes) strings\n",
438                   rules->token_cur,
439                   rules->token_cur * sizeof(struct token),
440                   rules->buf_count,
441                   rules->buf_cur);
442         for(i = 0; i < rules->token_cur; i++)
443                 dump_token(rules, &rules->tokens[i]);
444 }
445 #else
446 static inline const char *operation_str(enum operation_type type) { return NULL; }
447 static inline const char *token_str(enum token_type type) { return NULL; }
448 static inline void dump_token(struct udev_rules *rules, struct token *token) {}
449 static inline void dump_rules(struct udev_rules *rules) {}
450 #endif /* DEBUG */
451
452 static int add_new_string(struct udev_rules *rules, const char *str, size_t bytes)
453 {
454         int off;
455
456         /* grow buffer if needed */
457         if (rules->buf_cur + bytes+1 >= rules->buf_max) {
458                 char *buf;
459                 unsigned int add;
460
461                 /* double the buffer size */
462                 add = rules->buf_max;
463                 if (add < bytes * 8)
464                         add = bytes * 8;
465
466                 buf = realloc(rules->buf, rules->buf_max + add);
467                 if (buf == NULL)
468                         return -1;
469                 rules->buf = buf;
470                 rules->buf_max += add;
471         }
472         off = rules->buf_cur;
473         memcpy(&rules->buf[rules->buf_cur], str, bytes);
474         rules->buf_cur += bytes;
475         rules->buf_count++;
476         return off;
477 }
478
479 static int add_string(struct udev_rules *rules, const char *str)
480 {
481         unsigned int node_idx;
482         struct trie_node *new_node;
483         unsigned int new_node_idx;
484         unsigned char key;
485         unsigned short len;
486         unsigned int depth;
487         unsigned int off;
488         struct trie_node *parent;
489
490         /* walk trie, start from last character of str to find matching tails */
491         len = strlen(str);
492         key = str[len-1];
493         node_idx = 0;
494         for (depth = 0; depth <= len; depth++) {
495                 struct trie_node *node;
496                 unsigned int child_idx;
497
498                 node = &rules->trie_nodes[node_idx];
499                 off = node->value_off + node->value_len - len;
500
501                 /* match against current node */
502                 if (depth == len || (node->value_len >= len && memcmp(&rules->buf[off], str, len) == 0))
503                         return off;
504
505                 /* lookup child node */
506                 key = str[len - 1 - depth];
507                 child_idx = node->child_idx;
508                 while (child_idx > 0) {
509                         struct trie_node *child;
510
511                         child = &rules->trie_nodes[child_idx];
512                         if (child->key == key)
513                                 break;
514                         child_idx = child->next_child_idx;
515                 }
516                 if (child_idx == 0)
517                         break;
518                 node_idx = child_idx;
519         }
520
521         /* string not found, add it */
522         off = add_new_string(rules, str, len + 1);
523
524         /* grow trie nodes if needed */
525         if (rules->trie_nodes_cur >= rules->trie_nodes_max) {
526                 struct trie_node *nodes;
527                 unsigned int add;
528
529                 /* double the buffer size */
530                 add = rules->trie_nodes_max;
531                 if (add < 8)
532                         add = 8;
533
534                 nodes = realloc(rules->trie_nodes, (rules->trie_nodes_max + add) * sizeof(struct trie_node));
535                 if (nodes == NULL)
536                         return -1;
537                 rules->trie_nodes = nodes;
538                 rules->trie_nodes_max += add;
539         }
540
541         /* get a new node */
542         new_node_idx = rules->trie_nodes_cur;
543         rules->trie_nodes_cur++;
544         new_node = &rules->trie_nodes[new_node_idx];
545         memset(new_node, 0x00, sizeof(struct trie_node));
546         new_node->value_off = off;
547         new_node->value_len = len;
548         new_node->key = key;
549
550         /* join the parent's child list */
551         parent = &rules->trie_nodes[node_idx];
552         if (parent->child_idx == 0) {
553                 parent->child_idx = new_node_idx;
554         } else {
555                 struct trie_node *last_child;
556
557                 last_child = &rules->trie_nodes[parent->last_child_idx];
558                 last_child->next_child_idx = new_node_idx;
559         }
560         parent->last_child_idx = new_node_idx;
561         return off;
562 }
563
564 static int add_token(struct udev_rules *rules, struct token *token)
565 {
566         /* grow buffer if needed */
567         if (rules->token_cur+1 >= rules->token_max) {
568                 struct token *tokens;
569                 unsigned int add;
570
571                 /* double the buffer size */
572                 add = rules->token_max;
573                 if (add < 8)
574                         add = 8;
575
576                 tokens = realloc(rules->tokens, (rules->token_max + add ) * sizeof(struct token));
577                 if (tokens == NULL)
578                         return -1;
579                 rules->tokens = tokens;
580                 rules->token_max += add;
581         }
582         memcpy(&rules->tokens[rules->token_cur], token, sizeof(struct token));
583         rules->token_cur++;
584         return 0;
585 }
586
587 static uid_t add_uid(struct udev_rules *rules, const char *owner)
588 {
589         unsigned int i;
590         uid_t uid;
591         unsigned int off;
592
593         /* lookup, if we know it already */
594         for (i = 0; i < rules->uids_cur; i++) {
595                 off = rules->uids[i].name_off;
596                 if (streq(&rules->buf[off], owner)) {
597                         uid = rules->uids[i].uid;
598                         return uid;
599                 }
600         }
601         uid = util_lookup_user(rules->udev, owner);
602
603         /* grow buffer if needed */
604         if (rules->uids_cur+1 >= rules->uids_max) {
605                 struct uid_gid *uids;
606                 unsigned int add;
607
608                 /* double the buffer size */
609                 add = rules->uids_max;
610                 if (add < 1)
611                         add = 8;
612
613                 uids = realloc(rules->uids, (rules->uids_max + add ) * sizeof(struct uid_gid));
614                 if (uids == NULL)
615                         return uid;
616                 rules->uids = uids;
617                 rules->uids_max += add;
618         }
619         rules->uids[rules->uids_cur].uid = uid;
620         off = add_string(rules, owner);
621         if (off <= 0)
622                 return uid;
623         rules->uids[rules->uids_cur].name_off = off;
624         rules->uids_cur++;
625         return uid;
626 }
627
628 static gid_t add_gid(struct udev_rules *rules, const char *group)
629 {
630         unsigned int i;
631         gid_t gid;
632         unsigned int off;
633
634         /* lookup, if we know it already */
635         for (i = 0; i < rules->gids_cur; i++) {
636                 off = rules->gids[i].name_off;
637                 if (streq(&rules->buf[off], group)) {
638                         gid = rules->gids[i].gid;
639                         return gid;
640                 }
641         }
642         gid = util_lookup_group(rules->udev, group);
643
644         /* grow buffer if needed */
645         if (rules->gids_cur+1 >= rules->gids_max) {
646                 struct uid_gid *gids;
647                 unsigned int add;
648
649                 /* double the buffer size */
650                 add = rules->gids_max;
651                 if (add < 1)
652                         add = 8;
653
654                 gids = realloc(rules->gids, (rules->gids_max + add ) * sizeof(struct uid_gid));
655                 if (gids == NULL)
656                         return gid;
657                 rules->gids = gids;
658                 rules->gids_max += add;
659         }
660         rules->gids[rules->gids_cur].gid = gid;
661         off = add_string(rules, group);
662         if (off <= 0)
663                 return gid;
664         rules->gids[rules->gids_cur].name_off = off;
665         rules->gids_cur++;
666         return gid;
667 }
668
669 static int import_property_from_string(struct udev_device *dev, char *line)
670 {
671         char *key;
672         char *val;
673         size_t len;
674
675         /* find key */
676         key = line;
677         while (isspace(key[0]))
678                 key++;
679
680         /* comment or empty line */
681         if (key[0] == '#' || key[0] == '\0')
682                 return -1;
683
684         /* split key/value */
685         val = strchr(key, '=');
686         if (val == NULL)
687                 return -1;
688         val[0] = '\0';
689         val++;
690
691         /* find value */
692         while (isspace(val[0]))
693                 val++;
694
695         /* terminate key */
696         len = strlen(key);
697         if (len == 0)
698                 return -1;
699         while (isspace(key[len-1]))
700                 len--;
701         key[len] = '\0';
702
703         /* terminate value */
704         len = strlen(val);
705         if (len == 0)
706                 return -1;
707         while (isspace(val[len-1]))
708                 len--;
709         val[len] = '\0';
710
711         if (len == 0)
712                 return -1;
713
714         /* unquote */
715         if (val[0] == '"' || val[0] == '\'') {
716                 if (val[len-1] != val[0]) {
717                         log_debug("inconsistent quoting: '%s', skip\n", line);
718                         return -1;
719                 }
720                 val[len-1] = '\0';
721                 val++;
722         }
723
724         /* handle device, renamed by external tool, returning new path */
725         if (streq(key, "DEVPATH")) {
726                 char syspath[UTIL_PATH_SIZE];
727
728                 log_debug("updating devpath from '%s' to '%s'\n",
729                           udev_device_get_devpath(dev), val);
730                 util_strscpyl(syspath, sizeof(syspath), "/sys", val, NULL);
731                 udev_device_set_syspath(dev, syspath);
732         } else {
733                 struct udev_list_entry *entry;
734
735                 entry = udev_device_add_property(dev, key, val);
736                 /* store in db, skip private keys */
737                 if (key[0] != '.')
738                         udev_list_entry_set_num(entry, true);
739         }
740         return 0;
741 }
742
743 static int import_file_into_properties(struct udev_device *dev, const char *filename)
744 {
745         FILE *f;
746         char line[UTIL_LINE_SIZE];
747
748         f = fopen(filename, "re");
749         if (f == NULL)
750                 return -1;
751         while (fgets(line, sizeof(line), f) != NULL)
752                 import_property_from_string(dev, line);
753         fclose(f);
754         return 0;
755 }
756
757 static int import_program_into_properties(struct udev_event *event, const char *program, const sigset_t *sigmask)
758 {
759         struct udev_device *dev = event->dev;
760         char **envp;
761         char result[UTIL_LINE_SIZE];
762         char *line;
763         int err;
764
765         envp = udev_device_get_properties_envp(dev);
766         err = udev_event_spawn(event, program, envp, sigmask, result, sizeof(result));
767         if (err < 0)
768                 return err;
769
770         line = result;
771         while (line != NULL) {
772                 char *pos;
773
774                 pos = strchr(line, '\n');
775                 if (pos != NULL) {
776                         pos[0] = '\0';
777                         pos = &pos[1];
778                 }
779                 import_property_from_string(dev, line);
780                 line = pos;
781         }
782         return 0;
783 }
784
785 static int import_parent_into_properties(struct udev_device *dev, const char *filter)
786 {
787         struct udev_device *dev_parent;
788         struct udev_list_entry *list_entry;
789
790         dev_parent = udev_device_get_parent(dev);
791         if (dev_parent == NULL)
792                 return -1;
793
794         udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(dev_parent)) {
795                 const char *key = udev_list_entry_get_name(list_entry);
796                 const char *val = udev_list_entry_get_value(list_entry);
797
798                 if (fnmatch(filter, key, 0) == 0) {
799                         struct udev_list_entry *entry;
800
801                         entry = udev_device_add_property(dev, key, val);
802                         /* store in db, skip private keys */
803                         if (key[0] != '.')
804                                 udev_list_entry_set_num(entry, true);
805                 }
806         }
807         return 0;
808 }
809
810 #define WAIT_LOOP_PER_SECOND                50
811 static int wait_for_file(struct udev_device *dev, const char *file, int timeout)
812 {
813         char filepath[UTIL_PATH_SIZE];
814         char devicepath[UTIL_PATH_SIZE];
815         struct stat stats;
816         int loop = timeout * WAIT_LOOP_PER_SECOND;
817
818         /* a relative path is a device attribute */
819         devicepath[0] = '\0';
820         if (file[0] != '/') {
821                 util_strscpyl(devicepath, sizeof(devicepath), udev_device_get_syspath(dev), NULL);
822                 util_strscpyl(filepath, sizeof(filepath), devicepath, "/", file, NULL);
823                 file = filepath;
824         }
825
826         while (--loop) {
827                 const struct timespec duration = { 0, 1000 * 1000 * 1000 / WAIT_LOOP_PER_SECOND };
828
829                 /* lookup file */
830                 if (stat(file, &stats) == 0) {
831                         log_debug("file '%s' appeared after %i loops\n", file, (timeout * WAIT_LOOP_PER_SECOND) - loop-1);
832                         return 0;
833                 }
834                 /* make sure, the device did not disappear in the meantime */
835                 if (devicepath[0] != '\0' && stat(devicepath, &stats) != 0) {
836                         log_debug("device disappeared while waiting for '%s'\n", file);
837                         return -2;
838                 }
839                 log_debug("wait for '%s' for %i mseconds\n", file, 1000 / WAIT_LOOP_PER_SECOND);
840                 nanosleep(&duration, NULL);
841         }
842         log_debug("waiting for '%s' failed\n", file);
843         return -1;
844 }
845
846 static int attr_subst_subdir(char *attr, size_t len)
847 {
848         bool found = false;
849
850         if (strstr(attr, "/*/")) {
851                 char *pos;
852                 char dirname[UTIL_PATH_SIZE];
853                 const char *tail;
854                 DIR *dir;
855
856                 util_strscpy(dirname, sizeof(dirname), attr);
857                 pos = strstr(dirname, "/*/");
858                 if (pos == NULL)
859                         return -1;
860                 pos[0] = '\0';
861                 tail = &pos[2];
862                 dir = opendir(dirname);
863                 if (dir != NULL) {
864                         struct dirent *dent;
865
866                         for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
867                                 struct stat stats;
868
869                                 if (dent->d_name[0] == '.')
870                                         continue;
871                                 util_strscpyl(attr, len, dirname, "/", dent->d_name, tail, NULL);
872                                 if (stat(attr, &stats) == 0) {
873                                         found = true;
874                                         break;
875                                 }
876                         }
877                         closedir(dir);
878                 }
879         }
880
881         return found;
882 }
883
884 static int get_key(struct udev *udev, char **line, char **key, enum operation_type *op, char **value)
885 {
886         char *linepos;
887         char *temp;
888
889         linepos = *line;
890         if (linepos == NULL || linepos[0] == '\0')
891                 return -1;
892
893         /* skip whitespace */
894         while (isspace(linepos[0]) || linepos[0] == ',')
895                 linepos++;
896
897         /* get the key */
898         if (linepos[0] == '\0')
899                 return -1;
900         *key = linepos;
901
902         for (;;) {
903                 linepos++;
904                 if (linepos[0] == '\0')
905                         return -1;
906                 if (isspace(linepos[0]))
907                         break;
908                 if (linepos[0] == '=')
909                         break;
910                 if ((linepos[0] == '+') || (linepos[0] == '!') || (linepos[0] == ':'))
911                         if (linepos[1] == '=')
912                                 break;
913         }
914
915         /* remember end of key */
916         temp = linepos;
917
918         /* skip whitespace after key */
919         while (isspace(linepos[0]))
920                 linepos++;
921         if (linepos[0] == '\0')
922                 return -1;
923
924         /* get operation type */
925         if (linepos[0] == '=' && linepos[1] == '=') {
926                 *op = OP_MATCH;
927                 linepos += 2;
928         } else if (linepos[0] == '!' && linepos[1] == '=') {
929                 *op = OP_NOMATCH;
930                 linepos += 2;
931         } else if (linepos[0] == '+' && linepos[1] == '=') {
932                 *op = OP_ADD;
933                 linepos += 2;
934         } else if (linepos[0] == '=') {
935                 *op = OP_ASSIGN;
936                 linepos++;
937         } else if (linepos[0] == ':' && linepos[1] == '=') {
938                 *op = OP_ASSIGN_FINAL;
939                 linepos += 2;
940         } else
941                 return -1;
942
943         /* terminate key */
944         temp[0] = '\0';
945
946         /* skip whitespace after operator */
947         while (isspace(linepos[0]))
948                 linepos++;
949         if (linepos[0] == '\0')
950                 return -1;
951
952         /* get the value */
953         if (linepos[0] == '"')
954                 linepos++;
955         else
956                 return -1;
957         *value = linepos;
958
959         /* terminate */
960         temp = strchr(linepos, '"');
961         if (!temp)
962                 return -1;
963         temp[0] = '\0';
964         temp++;
965
966         /* move line to next key */
967         *line = temp;
968         return 0;
969 }
970
971 /* extract possible KEY{attr} */
972 static const char *get_key_attribute(struct udev *udev, char *str)
973 {
974         char *pos;
975         char *attr;
976
977         attr = strchr(str, '{');
978         if (attr != NULL) {
979                 attr++;
980                 pos = strchr(attr, '}');
981                 if (pos == NULL) {
982                         log_error("missing closing brace for format\n");
983                         return NULL;
984                 }
985                 pos[0] = '\0';
986                 return attr;
987         }
988         return NULL;
989 }
990
991 static int rule_add_key(struct rule_tmp *rule_tmp, enum token_type type,
992                         enum operation_type op,
993                         const char *value, const void *data)
994 {
995         struct token *token = &rule_tmp->token[rule_tmp->token_cur];
996         const char *attr = NULL;
997
998         memset(token, 0x00, sizeof(struct token));
999
1000         switch (type) {
1001         case TK_M_ACTION:
1002         case TK_M_DEVPATH:
1003         case TK_M_KERNEL:
1004         case TK_M_SUBSYSTEM:
1005         case TK_M_DRIVER:
1006         case TK_M_WAITFOR:
1007         case TK_M_DEVLINK:
1008         case TK_M_NAME:
1009         case TK_M_KERNELS:
1010         case TK_M_SUBSYSTEMS:
1011         case TK_M_DRIVERS:
1012         case TK_M_TAGS:
1013         case TK_M_PROGRAM:
1014         case TK_M_IMPORT_FILE:
1015         case TK_M_IMPORT_PROG:
1016         case TK_M_IMPORT_DB:
1017         case TK_M_IMPORT_CMDLINE:
1018         case TK_M_IMPORT_PARENT:
1019         case TK_M_RESULT:
1020         case TK_A_OWNER:
1021         case TK_A_GROUP:
1022         case TK_A_MODE:
1023         case TK_A_NAME:
1024         case TK_A_GOTO:
1025         case TK_M_TAG:
1026         case TK_A_TAG:
1027                 token->key.value_off = add_string(rule_tmp->rules, value);
1028                 break;
1029         case TK_M_IMPORT_BUILTIN:
1030                 token->key.value_off = add_string(rule_tmp->rules, value);
1031                 token->key.builtin_cmd = *(enum udev_builtin_cmd *)data;
1032                 break;
1033         case TK_M_ENV:
1034         case TK_M_ATTR:
1035         case TK_M_ATTRS:
1036         case TK_A_ATTR:
1037         case TK_A_ENV:
1038                 attr = data;
1039                 token->key.value_off = add_string(rule_tmp->rules, value);
1040                 token->key.attr_off = add_string(rule_tmp->rules, attr);
1041                 break;
1042         case TK_A_DEVLINK:
1043                 token->key.value_off = add_string(rule_tmp->rules, value);
1044                 token->key.devlink_unique = *(int *)data;
1045                 break;
1046         case TK_M_TEST:
1047                 token->key.value_off = add_string(rule_tmp->rules, value);
1048                 if (data != NULL)
1049                         token->key.mode = *(mode_t *)data;
1050                 break;
1051         case TK_A_STRING_ESCAPE_NONE:
1052         case TK_A_STRING_ESCAPE_REPLACE:
1053         case TK_A_DB_PERSIST:
1054                 break;
1055         case TK_A_RUN_BUILTIN:
1056         case TK_A_RUN_PROGRAM:
1057                 token->key.builtin_cmd = *(enum udev_builtin_cmd *)data;
1058                 token->key.value_off = add_string(rule_tmp->rules, value);
1059                 break;
1060         case TK_A_INOTIFY_WATCH:
1061         case TK_A_DEVLINK_PRIO:
1062                 token->key.devlink_prio = *(int *)data;
1063                 break;
1064         case TK_A_OWNER_ID:
1065                 token->key.uid = *(uid_t *)data;
1066                 break;
1067         case TK_A_GROUP_ID:
1068                 token->key.gid = *(gid_t *)data;
1069                 break;
1070         case TK_A_MODE_ID:
1071                 token->key.mode = *(mode_t *)data;
1072                 break;
1073         case TK_A_STATIC_NODE:
1074                 token->key.value_off = add_string(rule_tmp->rules, value);
1075                 break;
1076         case TK_M_EVENT_TIMEOUT:
1077                 token->key.event_timeout = *(int *)data;
1078                 break;
1079         case TK_RULE:
1080         case TK_M_PARENTS_MIN:
1081         case TK_M_PARENTS_MAX:
1082         case TK_M_MAX:
1083         case TK_END:
1084         case TK_UNSET:
1085                 log_error("wrong type %u\n", type);
1086                 return -1;
1087         }
1088
1089         if (value != NULL && type < TK_M_MAX) {
1090                 /* check if we need to split or call fnmatch() while matching rules */
1091                 enum string_glob_type glob;
1092                 int has_split;
1093                 int has_glob;
1094
1095                 has_split = (strchr(value, '|') != NULL);
1096                 has_glob = (strchr(value, '*') != NULL || strchr(value, '?') != NULL || strchr(value, '[') != NULL);
1097                 if (has_split && has_glob) {
1098                         glob = GL_SPLIT_GLOB;
1099                 } else if (has_split) {
1100                         glob = GL_SPLIT;
1101                 } else if (has_glob) {
1102                         if (streq(value, "?*"))
1103                                 glob = GL_SOMETHING;
1104                         else
1105                                 glob = GL_GLOB;
1106                 } else {
1107                         glob = GL_PLAIN;
1108                 }
1109                 token->key.glob = glob;
1110         }
1111
1112         if (value != NULL && type > TK_M_MAX) {
1113                 /* check if assigned value has substitution chars */
1114                 if (value[0] == '[')
1115                         token->key.subst = SB_SUBSYS;
1116                 else if (strchr(value, '%') != NULL || strchr(value, '$') != NULL)
1117                         token->key.subst = SB_FORMAT;
1118                 else
1119                         token->key.subst = SB_NONE;
1120         }
1121
1122         if (attr != NULL) {
1123                 /* check if property/attribut name has substitution chars */
1124                 if (attr[0] == '[')
1125                         token->key.attrsubst = SB_SUBSYS;
1126                 else if (strchr(attr, '%') != NULL || strchr(attr, '$') != NULL)
1127                         token->key.attrsubst = SB_FORMAT;
1128                 else
1129                         token->key.attrsubst = SB_NONE;
1130         }
1131
1132         token->key.type = type;
1133         token->key.op = op;
1134         rule_tmp->token_cur++;
1135         if (rule_tmp->token_cur >= ELEMENTSOF(rule_tmp->token)) {
1136                 log_error("temporary rule array too small\n");
1137                 return -1;
1138         }
1139         return 0;
1140 }
1141
1142 static int sort_token(struct udev_rules *rules, struct rule_tmp *rule_tmp)
1143 {
1144         unsigned int i;
1145         unsigned int start = 0;
1146         unsigned int end = rule_tmp->token_cur;
1147
1148         for (i = 0; i < rule_tmp->token_cur; i++) {
1149                 enum token_type next_val = TK_UNSET;
1150                 unsigned int next_idx = 0;
1151                 unsigned int j;
1152
1153                 /* find smallest value */
1154                 for (j = start; j < end; j++) {
1155                         if (rule_tmp->token[j].type == TK_UNSET)
1156                                 continue;
1157                         if (next_val == TK_UNSET || rule_tmp->token[j].type < next_val) {
1158                                 next_val = rule_tmp->token[j].type;
1159                                 next_idx = j;
1160                         }
1161                 }
1162
1163                 /* add token and mark done */
1164                 if (add_token(rules, &rule_tmp->token[next_idx]) != 0)
1165                         return -1;
1166                 rule_tmp->token[next_idx].type = TK_UNSET;
1167
1168                 /* shrink range */
1169                 if (next_idx == start)
1170                         start++;
1171                 if (next_idx+1 == end)
1172                         end--;
1173         }
1174         return 0;
1175 }
1176
1177 static int add_rule(struct udev_rules *rules, char *line,
1178                     const char *filename, unsigned int filename_off, unsigned int lineno)
1179 {
1180         char *linepos;
1181         const char *attr;
1182         struct rule_tmp rule_tmp;
1183
1184         memset(&rule_tmp, 0x00, sizeof(struct rule_tmp));
1185         rule_tmp.rules = rules;
1186         rule_tmp.rule.type = TK_RULE;
1187         /* the offset in the rule is limited to unsigned short */
1188         if (filename_off < USHRT_MAX)
1189                 rule_tmp.rule.rule.filename_off = filename_off;
1190         rule_tmp.rule.rule.filename_line = lineno;
1191
1192         linepos = line;
1193         for (;;) {
1194                 char *key;
1195                 char *value;
1196                 enum operation_type op;
1197
1198                 if (get_key(rules->udev, &linepos, &key, &op, &value) != 0)
1199                         break;
1200
1201                 if (streq(key, "ACTION")) {
1202                         if (op > OP_MATCH_MAX) {
1203                                 log_error("invalid ACTION operation\n");
1204                                 goto invalid;
1205                         }
1206                         rule_add_key(&rule_tmp, TK_M_ACTION, op, value, NULL);
1207                         continue;
1208                 }
1209
1210                 if (streq(key, "DEVPATH")) {
1211                         if (op > OP_MATCH_MAX) {
1212                                 log_error("invalid DEVPATH operation\n");
1213                                 goto invalid;
1214                         }
1215                         rule_add_key(&rule_tmp, TK_M_DEVPATH, op, value, NULL);
1216                         continue;
1217                 }
1218
1219                 if (streq(key, "KERNEL")) {
1220                         if (op > OP_MATCH_MAX) {
1221                                 log_error("invalid KERNEL operation\n");
1222                                 goto invalid;
1223                         }
1224                         rule_add_key(&rule_tmp, TK_M_KERNEL, op, value, NULL);
1225                         continue;
1226                 }
1227
1228                 if (streq(key, "SUBSYSTEM")) {
1229                         if (op > OP_MATCH_MAX) {
1230                                 log_error("invalid SUBSYSTEM operation\n");
1231                                 goto invalid;
1232                         }
1233                         /* bus, class, subsystem events should all be the same */
1234                         if (streq(value, "subsystem") ||
1235                             streq(value, "bus") ||
1236                             streq(value, "class")) {
1237                                 if (streq(value, "bus") || streq(value, "class"))
1238                                         log_error("'%s' must be specified as 'subsystem' \n"
1239                                             "please fix it in %s:%u", value, filename, lineno);
1240                                 rule_add_key(&rule_tmp, TK_M_SUBSYSTEM, op, "subsystem|class|bus", NULL);
1241                         } else
1242                                 rule_add_key(&rule_tmp, TK_M_SUBSYSTEM, op, value, NULL);
1243                         continue;
1244                 }
1245
1246                 if (streq(key, "DRIVER")) {
1247                         if (op > OP_MATCH_MAX) {
1248                                 log_error("invalid DRIVER operation\n");
1249                                 goto invalid;
1250                         }
1251                         rule_add_key(&rule_tmp, TK_M_DRIVER, op, value, NULL);
1252                         continue;
1253                 }
1254
1255                 if (startswith(key, "ATTR{")) {
1256                         attr = get_key_attribute(rules->udev, key + sizeof("ATTR")-1);
1257                         if (attr == NULL) {
1258                                 log_error("error parsing ATTR attribute\n");
1259                                 goto invalid;
1260                         }
1261                         if (op < OP_MATCH_MAX) {
1262                                 rule_add_key(&rule_tmp, TK_M_ATTR, op, value, attr);
1263                         } else {
1264                                 rule_add_key(&rule_tmp, TK_A_ATTR, op, value, attr);
1265                         }
1266                         continue;
1267                 }
1268
1269                 if (streq(key, "KERNELS")) {
1270                         if (op > OP_MATCH_MAX) {
1271                                 log_error("invalid KERNELS operation\n");
1272                                 goto invalid;
1273                         }
1274                         rule_add_key(&rule_tmp, TK_M_KERNELS, op, value, NULL);
1275                         continue;
1276                 }
1277
1278                 if (streq(key, "SUBSYSTEMS")) {
1279                         if (op > OP_MATCH_MAX) {
1280                                 log_error("invalid SUBSYSTEMS operation\n");
1281                                 goto invalid;
1282                         }
1283                         rule_add_key(&rule_tmp, TK_M_SUBSYSTEMS, op, value, NULL);
1284                         continue;
1285                 }
1286
1287                 if (streq(key, "DRIVERS")) {
1288                         if (op > OP_MATCH_MAX) {
1289                                 log_error("invalid DRIVERS operation\n");
1290                                 goto invalid;
1291                         }
1292                         rule_add_key(&rule_tmp, TK_M_DRIVERS, op, value, NULL);
1293                         continue;
1294                 }
1295
1296                 if (startswith(key, "ATTRS{")) {
1297                         if (op > OP_MATCH_MAX) {
1298                                 log_error("invalid ATTRS operation\n");
1299                                 goto invalid;
1300                         }
1301                         attr = get_key_attribute(rules->udev, key + sizeof("ATTRS")-1);
1302                         if (attr == NULL) {
1303                                 log_error("error parsing ATTRS attribute\n");
1304                                 goto invalid;
1305                         }
1306                         if (startswith(attr, "device/"))
1307                                 log_error("the 'device' link may not be available in a future kernel, "
1308                                     "please fix it in %s:%u", filename, lineno);
1309                         else if (strstr(attr, "../") != NULL)
1310                                 log_error("do not reference parent sysfs directories directly, "
1311                                     "it may break with a future kernel, please fix it in %s:%u", filename, lineno);
1312                         rule_add_key(&rule_tmp, TK_M_ATTRS, op, value, attr);
1313                         continue;
1314                 }
1315
1316                 if (streq(key, "TAGS")) {
1317                         if (op > OP_MATCH_MAX) {
1318                                 log_error("invalid TAGS operation\n");
1319                                 goto invalid;
1320                         }
1321                         rule_add_key(&rule_tmp, TK_M_TAGS, op, value, NULL);
1322                         continue;
1323                 }
1324
1325                 if (startswith(key, "ENV{")) {
1326                         attr = get_key_attribute(rules->udev, key + sizeof("ENV")-1);
1327                         if (attr == NULL) {
1328                                 log_error("error parsing ENV attribute\n");
1329                                 goto invalid;
1330                         }
1331                         if (op < OP_MATCH_MAX) {
1332                                 if (rule_add_key(&rule_tmp, TK_M_ENV, op, value, attr) != 0)
1333                                         goto invalid;
1334                         } else {
1335                                 static const char *blacklist[] = {
1336                                         "ACTION",
1337                                         "SUBSYSTEM",
1338                                         "DEVTYPE",
1339                                         "MAJOR",
1340                                         "MINOR",
1341                                         "DRIVER",
1342                                         "IFINDEX",
1343                                         "DEVNAME",
1344                                         "DEVLINKS",
1345                                         "DEVPATH",
1346                                         "TAGS",
1347                                 };
1348                                 unsigned int i;
1349
1350                                 for (i = 0; i < ELEMENTSOF(blacklist); i++) {
1351                                         if (!streq(attr, blacklist[i]))
1352                                                 continue;
1353                                         log_error("invalid ENV attribute, '%s' can not be set %s:%u\n", attr, filename, lineno);
1354                                         goto invalid;
1355                                 }
1356                                 if (rule_add_key(&rule_tmp, TK_A_ENV, op, value, attr) != 0)
1357                                         goto invalid;
1358                         }
1359                         continue;
1360                 }
1361
1362                 if (streq(key, "TAG")) {
1363                         if (op < OP_MATCH_MAX)
1364                                 rule_add_key(&rule_tmp, TK_M_TAG, op, value, NULL);
1365                         else
1366                                 rule_add_key(&rule_tmp, TK_A_TAG, op, value, NULL);
1367                         continue;
1368                 }
1369
1370                 if (streq(key, "PROGRAM")) {
1371                         rule_add_key(&rule_tmp, TK_M_PROGRAM, op, value, NULL);
1372                         continue;
1373                 }
1374
1375                 if (streq(key, "RESULT")) {
1376                         if (op > OP_MATCH_MAX) {
1377                                 log_error("invalid RESULT operation\n");
1378                                 goto invalid;
1379                         }
1380                         rule_add_key(&rule_tmp, TK_M_RESULT, op, value, NULL);
1381                         continue;
1382                 }
1383
1384                 if (startswith(key, "IMPORT")) {
1385                         attr = get_key_attribute(rules->udev, key + sizeof("IMPORT")-1);
1386                         if (attr == NULL) {
1387                                 log_error("IMPORT{} type missing, ignoring IMPORT %s:%u\n", filename, lineno);
1388                                 continue;
1389                         }
1390                         if (streq(attr, "program")) {
1391                                 /* find known built-in command */
1392                                 if (value[0] != '/') {
1393                                         enum udev_builtin_cmd cmd;
1394
1395                                         cmd = udev_builtin_lookup(value);
1396                                         if (cmd < UDEV_BUILTIN_MAX) {
1397                                                 log_debug("IMPORT found builtin '%s', replacing %s:%u\n",
1398                                                           value, filename, lineno);
1399                                                 rule_add_key(&rule_tmp, TK_M_IMPORT_BUILTIN, op, value, &cmd);
1400                                                 continue;
1401                                         }
1402                                 }
1403                                 rule_add_key(&rule_tmp, TK_M_IMPORT_PROG, op, value, NULL);
1404                         } else if (streq(attr, "builtin")) {
1405                                 enum udev_builtin_cmd cmd = udev_builtin_lookup(value);
1406
1407                                 if (cmd < UDEV_BUILTIN_MAX)
1408                                         rule_add_key(&rule_tmp, TK_M_IMPORT_BUILTIN, op, value, &cmd);
1409                                 else
1410                                         log_error("IMPORT{builtin}: '%s' unknown %s:%u\n", value, filename, lineno);
1411                         } else if (streq(attr, "file")) {
1412                                 rule_add_key(&rule_tmp, TK_M_IMPORT_FILE, op, value, NULL);
1413                         } else if (streq(attr, "db")) {
1414                                 rule_add_key(&rule_tmp, TK_M_IMPORT_DB, op, value, NULL);
1415                         } else if (streq(attr, "cmdline")) {
1416                                 rule_add_key(&rule_tmp, TK_M_IMPORT_CMDLINE, op, value, NULL);
1417                         } else if (streq(attr, "parent")) {
1418                                 rule_add_key(&rule_tmp, TK_M_IMPORT_PARENT, op, value, NULL);
1419                         } else
1420                                 log_error("IMPORT{} unknown type, ignoring IMPORT %s:%u\n", filename, lineno);
1421                         continue;
1422                 }
1423
1424                 if (startswith(key, "TEST")) {
1425                         mode_t mode = 0;
1426
1427                         if (op > OP_MATCH_MAX) {
1428                                 log_error("invalid TEST operation\n");
1429                                 goto invalid;
1430                         }
1431                         attr = get_key_attribute(rules->udev, key + sizeof("TEST")-1);
1432                         if (attr != NULL) {
1433                                 mode = strtol(attr, NULL, 8);
1434                                 rule_add_key(&rule_tmp, TK_M_TEST, op, value, &mode);
1435                         } else {
1436                                 rule_add_key(&rule_tmp, TK_M_TEST, op, value, NULL);
1437                         }
1438                         continue;
1439                 }
1440
1441                 if (startswith(key, "RUN")) {
1442                         attr = get_key_attribute(rules->udev, key + sizeof("RUN")-1);
1443                         if (attr == NULL)
1444                                 attr = "program";
1445
1446                         if (streq(attr, "builtin")) {
1447                                 enum udev_builtin_cmd cmd = udev_builtin_lookup(value);
1448
1449                                 if (cmd < UDEV_BUILTIN_MAX)
1450                                         rule_add_key(&rule_tmp, TK_A_RUN_BUILTIN, op, value, &cmd);
1451                                 else
1452                                         log_error("IMPORT{builtin}: '%s' unknown %s:%u\n", value, filename, lineno);
1453                         } else if (streq(attr, "program")) {
1454                                 enum udev_builtin_cmd cmd = UDEV_BUILTIN_MAX;
1455
1456                                 rule_add_key(&rule_tmp, TK_A_RUN_PROGRAM, op, value, &cmd);
1457                         } else {
1458                                 log_error("RUN{} unknown type, ignoring RUN %s:%u\n", filename, lineno);
1459                         }
1460
1461                         continue;
1462                 }
1463
1464                 if (streq(key, "WAIT_FOR") || streq(key, "WAIT_FOR_SYSFS")) {
1465                         rule_add_key(&rule_tmp, TK_M_WAITFOR, 0, value, NULL);
1466                         continue;
1467                 }
1468
1469                 if (streq(key, "LABEL")) {
1470                         rule_tmp.rule.rule.label_off = add_string(rules, value);
1471                         continue;
1472                 }
1473
1474                 if (streq(key, "GOTO")) {
1475                         rule_add_key(&rule_tmp, TK_A_GOTO, 0, value, NULL);
1476                         continue;
1477                 }
1478
1479                 if (startswith(key, "NAME")) {
1480                         if (op < OP_MATCH_MAX) {
1481                                 rule_add_key(&rule_tmp, TK_M_NAME, op, value, NULL);
1482                         } else {
1483                                 if (streq(value, "%k")) {
1484                                         log_error("NAME=\"%%k\" is ignored, because it breaks kernel supplied names, "
1485                                             "please remove it from %s:%u\n", filename, lineno);
1486                                         continue;
1487                                 }
1488                                 if (value[0] == '\0') {
1489                                         log_debug("NAME=\"\" is ignored, because udev will not delete any device nodes, "
1490                                                   "please remove it from %s:%u\n", filename, lineno);
1491                                         continue;
1492                                 }
1493                                 rule_add_key(&rule_tmp, TK_A_NAME, op, value, NULL);
1494                         }
1495                         rule_tmp.rule.rule.can_set_name = true;
1496                         continue;
1497                 }
1498
1499                 if (startswith(key, "SYMLINK")) {
1500                         if (op < OP_MATCH_MAX) {
1501                                 rule_add_key(&rule_tmp, TK_M_DEVLINK, op, value, NULL);
1502                         } else {
1503                                 int flag = 0;
1504
1505                                 attr = get_key_attribute(rules->udev, key + sizeof("SYMLINK")-1);
1506                                 if (attr != NULL && strstr(attr, "unique") != NULL)
1507                                         flag = 1;
1508                                 rule_add_key(&rule_tmp, TK_A_DEVLINK, op, value, &flag);
1509                         }
1510                         rule_tmp.rule.rule.can_set_name = true;
1511                         continue;
1512                 }
1513
1514                 if (streq(key, "OWNER")) {
1515                         uid_t uid;
1516                         char *endptr;
1517
1518                         uid = strtoul(value, &endptr, 10);
1519                         if (endptr[0] == '\0') {
1520                                 rule_add_key(&rule_tmp, TK_A_OWNER_ID, op, NULL, &uid);
1521                         } else if ((rules->resolve_names > 0) && strchr("$%", value[0]) == NULL) {
1522                                 uid = add_uid(rules, value);
1523                                 rule_add_key(&rule_tmp, TK_A_OWNER_ID, op, NULL, &uid);
1524                         } else if (rules->resolve_names >= 0) {
1525                                 rule_add_key(&rule_tmp, TK_A_OWNER, op, value, NULL);
1526                         }
1527                         rule_tmp.rule.rule.can_set_name = true;
1528                         continue;
1529                 }
1530
1531                 if (streq(key, "GROUP")) {
1532                         gid_t gid;
1533                         char *endptr;
1534
1535                         gid = strtoul(value, &endptr, 10);
1536                         if (endptr[0] == '\0') {
1537                                 rule_add_key(&rule_tmp, TK_A_GROUP_ID, op, NULL, &gid);
1538                         } else if ((rules->resolve_names > 0) && strchr("$%", value[0]) == NULL) {
1539                                 gid = add_gid(rules, value);
1540                                 rule_add_key(&rule_tmp, TK_A_GROUP_ID, op, NULL, &gid);
1541                         } else if (rules->resolve_names >= 0) {
1542                                 rule_add_key(&rule_tmp, TK_A_GROUP, op, value, NULL);
1543                         }
1544                         rule_tmp.rule.rule.can_set_name = true;
1545                         continue;
1546                 }
1547
1548                 if (streq(key, "MODE")) {
1549                         mode_t mode;
1550                         char *endptr;
1551
1552                         mode = strtol(value, &endptr, 8);
1553                         if (endptr[0] == '\0')
1554                                 rule_add_key(&rule_tmp, TK_A_MODE_ID, op, NULL, &mode);
1555                         else
1556                                 rule_add_key(&rule_tmp, TK_A_MODE, op, value, NULL);
1557                         rule_tmp.rule.rule.can_set_name = true;
1558                         continue;
1559                 }
1560
1561                 if (streq(key, "OPTIONS")) {
1562                         const char *pos;
1563
1564                         pos = strstr(value, "link_priority=");
1565                         if (pos != NULL) {
1566                                 int prio = atoi(&pos[strlen("link_priority=")]);
1567
1568                                 rule_add_key(&rule_tmp, TK_A_DEVLINK_PRIO, op, NULL, &prio);
1569                         }
1570
1571                         pos = strstr(value, "event_timeout=");
1572                         if (pos != NULL) {
1573                                 int tout = atoi(&pos[strlen("event_timeout=")]);
1574
1575                                 rule_add_key(&rule_tmp, TK_M_EVENT_TIMEOUT, op, NULL, &tout);
1576                         }
1577
1578                         pos = strstr(value, "string_escape=");
1579                         if (pos != NULL) {
1580                                 pos = &pos[strlen("string_escape=")];
1581                                 if (startswith(pos, "none"))
1582                                         rule_add_key(&rule_tmp, TK_A_STRING_ESCAPE_NONE, op, NULL, NULL);
1583                                 else if (startswith(pos, "replace"))
1584                                         rule_add_key(&rule_tmp, TK_A_STRING_ESCAPE_REPLACE, op, NULL, NULL);
1585                         }
1586
1587                         pos = strstr(value, "db_persist");
1588                         if (pos != NULL)
1589                                 rule_add_key(&rule_tmp, TK_A_DB_PERSIST, op, NULL, NULL);
1590
1591                         pos = strstr(value, "nowatch");
1592                         if (pos != NULL) {
1593                                 const int off = 0;
1594
1595                                 rule_add_key(&rule_tmp, TK_A_INOTIFY_WATCH, op, NULL, &off);
1596                         } else {
1597                                 pos = strstr(value, "watch");
1598                                 if (pos != NULL) {
1599                                         const int on = 1;
1600
1601                                         rule_add_key(&rule_tmp, TK_A_INOTIFY_WATCH, op, NULL, &on);
1602                                 }
1603                         }
1604
1605                         pos = strstr(value, "static_node=");
1606                         if (pos != NULL) {
1607                                 rule_add_key(&rule_tmp, TK_A_STATIC_NODE, op, &pos[strlen("static_node=")], NULL);
1608                                 rule_tmp.rule.rule.has_static_node = true;
1609                         }
1610
1611                         continue;
1612                 }
1613
1614                 log_error("unknown key '%s' in %s:%u\n", key, filename, lineno);
1615                 goto invalid;
1616         }
1617
1618         /* add rule token */
1619         rule_tmp.rule.rule.token_count = 1 + rule_tmp.token_cur;
1620         if (add_token(rules, &rule_tmp.rule) != 0)
1621                 goto invalid;
1622
1623         /* add tokens to list, sorted by type */
1624         if (sort_token(rules, &rule_tmp) != 0)
1625                 goto invalid;
1626
1627         return 0;
1628 invalid:
1629         log_error("invalid rule '%s:%u'\n", filename, lineno);
1630         return -1;
1631 }
1632
1633 static int parse_file(struct udev_rules *rules, const char *filename)
1634 {
1635         FILE *f;
1636         unsigned int first_token;
1637         unsigned int filename_off;
1638         char line[UTIL_LINE_SIZE];
1639         int line_nr = 0;
1640         unsigned int i;
1641
1642         if (null_or_empty_path(filename)) {
1643                 log_debug("skip empty file: %s\n", filename);
1644                 return 0;
1645         }
1646         log_debug("read rules file: %s\n", filename);
1647
1648         f = fopen(filename, "re");
1649         if (f == NULL)
1650                 return -1;
1651
1652         first_token = rules->token_cur;
1653         filename_off = add_string(rules, filename);
1654
1655         while (fgets(line, sizeof(line), f) != NULL) {
1656                 char *key;
1657                 size_t len;
1658
1659                 /* skip whitespace */
1660                 line_nr++;
1661                 key = line;
1662                 while (isspace(key[0]))
1663                         key++;
1664
1665                 /* comment */
1666                 if (key[0] == '#')
1667                         continue;
1668
1669                 len = strlen(line);
1670                 if (len < 3)
1671                         continue;
1672
1673                 /* continue reading if backslash+newline is found */
1674                 while (line[len-2] == '\\') {
1675                         if (fgets(&line[len-2], (sizeof(line)-len)+2, f) == NULL)
1676                                 break;
1677                         if (strlen(&line[len-2]) < 2)
1678                                 break;
1679                         line_nr++;
1680                         len = strlen(line);
1681                 }
1682
1683                 if (len+1 >= sizeof(line)) {
1684                         log_error("line too long '%s':%u, ignored\n", filename, line_nr);
1685                         continue;
1686                 }
1687                 add_rule(rules, key, filename, filename_off, line_nr);
1688         }
1689         fclose(f);
1690
1691         /* link GOTOs to LABEL rules in this file to be able to fast-forward */
1692         for (i = first_token+1; i < rules->token_cur; i++) {
1693                 if (rules->tokens[i].type == TK_A_GOTO) {
1694                         char *label = &rules->buf[rules->tokens[i].key.value_off];
1695                         unsigned int j;
1696
1697                         for (j = i+1; j < rules->token_cur; j++) {
1698                                 if (rules->tokens[j].type != TK_RULE)
1699                                         continue;
1700                                 if (rules->tokens[j].rule.label_off == 0)
1701                                         continue;
1702                                 if (!streq(label, &rules->buf[rules->tokens[j].rule.label_off]))
1703                                         continue;
1704                                 rules->tokens[i].key.rule_goto = j;
1705                                 break;
1706                         }
1707                         if (rules->tokens[i].key.rule_goto == 0)
1708                                 log_error("GOTO '%s' has no matching label in: '%s'\n", label, filename);
1709                 }
1710         }
1711         return 0;
1712 }
1713
1714 struct udev_rules *udev_rules_new(struct udev *udev, int resolve_names)
1715 {
1716         struct udev_rules *rules;
1717         struct udev_list file_list;
1718         struct token end_token;
1719         char **files, **f;
1720         int r;
1721
1722         rules = calloc(1, sizeof(struct udev_rules));
1723         if (rules == NULL)
1724                 return NULL;
1725         rules->udev = udev;
1726         rules->resolve_names = resolve_names;
1727         udev_list_init(udev, &file_list, true);
1728
1729         /* init token array and string buffer */
1730         rules->tokens = malloc(PREALLOC_TOKEN * sizeof(struct token));
1731         if (rules->tokens == NULL) {
1732                 free(rules);
1733                 return NULL;
1734         }
1735         rules->token_max = PREALLOC_TOKEN;
1736
1737         rules->buf = malloc(PREALLOC_STRBUF);
1738         if (rules->buf == NULL) {
1739                 free(rules->tokens);
1740                 free(rules);
1741                 return NULL;
1742         }
1743         rules->buf_max = PREALLOC_STRBUF;
1744         /* offset 0 is always '\0' */
1745         rules->buf[0] = '\0';
1746         rules->buf_cur = 1;
1747
1748         rules->trie_nodes = malloc(PREALLOC_TRIE * sizeof(struct trie_node));
1749         if (rules->trie_nodes == NULL) {
1750                 free(rules->buf);
1751                 free(rules->tokens);
1752                 free(rules);
1753                 return NULL;
1754         }
1755         rules->trie_nodes_max = PREALLOC_TRIE;
1756         /* offset 0 is the trie root, with an empty string */
1757         memset(rules->trie_nodes, 0x00, sizeof(struct trie_node));
1758         rules->trie_nodes_cur = 1;
1759
1760         rules->dirs = strv_new(SYSCONFDIR "/udev/rules.d",
1761                                "/run/udev/rules.d",
1762                                UDEVLIBEXECDIR "/rules.d",
1763                                NULL);
1764         if (!rules->dirs) {
1765                 log_error("failed to build config directory array");
1766                 return NULL;
1767         }
1768         if (!path_strv_canonicalize(rules->dirs)) {
1769                 log_error("failed to canonicalize config directories\n");
1770                 return NULL;
1771         }
1772         strv_uniq(rules->dirs);
1773
1774         rules->dirs_ts_usec = calloc(strv_length(rules->dirs), sizeof(long long));
1775         udev_rules_check_timestamp(rules);
1776
1777         r = conf_files_list_strv(&files, ".rules", (const char **)rules->dirs);
1778         if (r < 0) {
1779                 log_error("failed to enumerate rules files: %s\n", strerror(-r));
1780                 return NULL;
1781         }
1782
1783         /*
1784          * The offset value in the rules strct is limited; add all
1785          * rules file names to the beginning of the string buffer.
1786          */
1787         STRV_FOREACH(f, files)
1788                 add_string(rules, *f);
1789
1790         STRV_FOREACH(f, files)
1791                 parse_file(rules, *f);
1792
1793         strv_free(files);
1794
1795         memset(&end_token, 0x00, sizeof(struct token));
1796         end_token.type = TK_END;
1797         add_token(rules, &end_token);
1798
1799         /* shrink allocated token and string buffer */
1800         if (rules->token_cur < rules->token_max) {
1801                 struct token *tokens;
1802
1803                 tokens = realloc(rules->tokens, rules->token_cur * sizeof(struct token));
1804                 if (tokens != NULL || rules->token_cur == 0) {
1805                         rules->tokens = tokens;
1806                         rules->token_max = rules->token_cur;
1807                 }
1808         }
1809         if (rules->buf_cur < rules->buf_max) {
1810                 char *buf;
1811
1812                 buf = realloc(rules->buf, rules->buf_cur);
1813                 if (buf != NULL || rules->buf_cur == 0) {
1814                         rules->buf = buf;
1815                         rules->buf_max = rules->buf_cur;
1816                 }
1817         }
1818         log_debug("rules use %zu bytes tokens (%u * %zu bytes), %zu bytes buffer\n",
1819                   rules->token_max * sizeof(struct token), rules->token_max, sizeof(struct token), rules->buf_max);
1820         log_debug("temporary index used %zu bytes (%u * %zu bytes)\n",
1821                   rules->trie_nodes_cur * sizeof(struct trie_node),
1822                   rules->trie_nodes_cur, sizeof(struct trie_node));
1823
1824         /* cleanup trie */
1825         free(rules->trie_nodes);
1826         rules->trie_nodes = NULL;
1827         rules->trie_nodes_cur = 0;
1828         rules->trie_nodes_max = 0;
1829
1830         /* cleanup uid/gid cache */
1831         free(rules->uids);
1832         rules->uids = NULL;
1833         rules->uids_cur = 0;
1834         rules->uids_max = 0;
1835         free(rules->gids);
1836         rules->gids = NULL;
1837         rules->gids_cur = 0;
1838         rules->gids_max = 0;
1839
1840         dump_rules(rules);
1841         return rules;
1842 }
1843
1844 struct udev_rules *udev_rules_unref(struct udev_rules *rules)
1845 {
1846         if (rules == NULL)
1847                 return NULL;
1848         free(rules->tokens);
1849         free(rules->buf);
1850         free(rules->trie_nodes);
1851         free(rules->uids);
1852         free(rules->gids);
1853         strv_free(rules->dirs);
1854         free(rules->dirs_ts_usec);
1855         free(rules);
1856         return NULL;
1857 }
1858
1859 bool udev_rules_check_timestamp(struct udev_rules *rules)
1860 {
1861         unsigned int i;
1862         bool changed = false;
1863
1864         if (rules == NULL)
1865                 goto out;
1866
1867         for (i = 0; rules->dirs[i]; i++) {
1868                 struct stat stats;
1869
1870                 if (stat(rules->dirs[i], &stats) < 0)
1871                         continue;
1872
1873                 if (rules->dirs_ts_usec[i] == ts_usec(&stats.st_mtim))
1874                         continue;
1875
1876                 /* first check */
1877                 if (rules->dirs_ts_usec[i] != 0) {
1878                         log_debug("reload - timestamp of '%s' changed\n", rules->dirs[i]);
1879                         changed = true;
1880                 }
1881
1882                 /* update timestamp */
1883                 rules->dirs_ts_usec[i] = ts_usec(&stats.st_mtim);
1884         }
1885 out:
1886         return changed;
1887 }
1888
1889 static int match_key(struct udev_rules *rules, struct token *token, const char *val)
1890 {
1891         char *key_value = &rules->buf[token->key.value_off];
1892         char *pos;
1893         bool match = false;
1894
1895         if (val == NULL)
1896                 val = "";
1897
1898         switch (token->key.glob) {
1899         case GL_PLAIN:
1900                 match = (streq(key_value, val));
1901                 break;
1902         case GL_GLOB:
1903                 match = (fnmatch(key_value, val, 0) == 0);
1904                 break;
1905         case GL_SPLIT:
1906                 {
1907                         const char *s;
1908                         size_t len;
1909
1910                         s = &rules->buf[token->key.value_off];
1911                         len = strlen(val);
1912                         for (;;) {
1913                                 const char *next;
1914
1915                                 next = strchr(s, '|');
1916                                 if (next != NULL) {
1917                                         size_t matchlen = (size_t)(next - s);
1918
1919                                         match = (matchlen == len && strncmp(s, val, matchlen) == 0);
1920                                         if (match)
1921                                                 break;
1922                                 } else {
1923                                         match = (streq(s, val));
1924                                         break;
1925                                 }
1926                                 s = &next[1];
1927                         }
1928                         break;
1929                 }
1930         case GL_SPLIT_GLOB:
1931                 {
1932                         char value[UTIL_PATH_SIZE];
1933
1934                         util_strscpy(value, sizeof(value), &rules->buf[token->key.value_off]);
1935                         key_value = value;
1936                         while (key_value != NULL) {
1937                                 pos = strchr(key_value, '|');
1938                                 if (pos != NULL) {
1939                                         pos[0] = '\0';
1940                                         pos = &pos[1];
1941                                 }
1942                                 match = (fnmatch(key_value, val, 0) == 0);
1943                                 if (match)
1944                                         break;
1945                                 key_value = pos;
1946                         }
1947                         break;
1948                 }
1949         case GL_SOMETHING:
1950                 match = (val[0] != '\0');
1951                 break;
1952         case GL_UNSET:
1953                 return -1;
1954         }
1955
1956         if (match && (token->key.op == OP_MATCH))
1957                 return 0;
1958         if (!match && (token->key.op == OP_NOMATCH))
1959                 return 0;
1960         return -1;
1961 }
1962
1963 static int match_attr(struct udev_rules *rules, struct udev_device *dev, struct udev_event *event, struct token *cur)
1964 {
1965         const char *name;
1966         char nbuf[UTIL_NAME_SIZE];
1967         const char *value;
1968         char vbuf[UTIL_NAME_SIZE];
1969         size_t len;
1970
1971         name = &rules->buf[cur->key.attr_off];
1972         switch (cur->key.attrsubst) {
1973         case SB_FORMAT:
1974                 udev_event_apply_format(event, name, nbuf, sizeof(nbuf));
1975                 name = nbuf;
1976                 /* fall through */
1977         case SB_NONE:
1978                 value = udev_device_get_sysattr_value(dev, name);
1979                 if (value == NULL)
1980                         return -1;
1981                 break;
1982         case SB_SUBSYS:
1983                 if (util_resolve_subsys_kernel(event->udev, name, vbuf, sizeof(vbuf), 1) != 0)
1984                         return -1;
1985                 value = vbuf;
1986                 break;
1987         default:
1988                 return -1;
1989         }
1990
1991         /* remove trailing whitespace, if not asked to match for it */
1992         len = strlen(value);
1993         if (len > 0 && isspace(value[len-1])) {
1994                 const char *key_value;
1995                 size_t klen;
1996
1997                 key_value = &rules->buf[cur->key.value_off];
1998                 klen = strlen(key_value);
1999                 if (klen > 0 && !isspace(key_value[klen-1])) {
2000                         if (value != vbuf) {
2001                                 util_strscpy(vbuf, sizeof(vbuf), value);
2002                                 value = vbuf;
2003                         }
2004                         while (len > 0 && isspace(vbuf[--len]))
2005                                 vbuf[len] = '\0';
2006                 }
2007         }
2008
2009         return match_key(rules, cur, value);
2010 }
2011
2012 enum escape_type {
2013         ESCAPE_UNSET,
2014         ESCAPE_NONE,
2015         ESCAPE_REPLACE,
2016 };
2017
2018 int udev_rules_apply_to_event(struct udev_rules *rules, struct udev_event *event, const sigset_t *sigmask)
2019 {
2020         struct token *cur;
2021         struct token *rule;
2022         enum escape_type esc = ESCAPE_UNSET;
2023         bool can_set_name;
2024
2025         if (rules->tokens == NULL)
2026                 return -1;
2027
2028         can_set_name = ((!streq(udev_device_get_action(event->dev), "remove")) &&
2029                         (major(udev_device_get_devnum(event->dev)) > 0 ||
2030                          udev_device_get_ifindex(event->dev) > 0));
2031
2032         /* loop through token list, match, run actions or forward to next rule */
2033         cur = &rules->tokens[0];
2034         rule = cur;
2035         for (;;) {
2036                 dump_token(rules, cur);
2037                 switch (cur->type) {
2038                 case TK_RULE:
2039                         /* current rule */
2040                         rule = cur;
2041                         /* possibly skip rules which want to set NAME, SYMLINK, OWNER, GROUP, MODE */
2042                         if (!can_set_name && rule->rule.can_set_name)
2043                                 goto nomatch;
2044                         esc = ESCAPE_UNSET;
2045                         break;
2046                 case TK_M_ACTION:
2047                         if (match_key(rules, cur, udev_device_get_action(event->dev)) != 0)
2048                                 goto nomatch;
2049                         break;
2050                 case TK_M_DEVPATH:
2051                         if (match_key(rules, cur, udev_device_get_devpath(event->dev)) != 0)
2052                                 goto nomatch;
2053                         break;
2054                 case TK_M_KERNEL:
2055                         if (match_key(rules, cur, udev_device_get_sysname(event->dev)) != 0)
2056                                 goto nomatch;
2057                         break;
2058                 case TK_M_DEVLINK: {
2059                         struct udev_list_entry *list_entry;
2060                         bool match = false;
2061
2062                         udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(event->dev)) {
2063                                 const char *devlink;
2064
2065                                 devlink =  udev_list_entry_get_name(list_entry) + strlen("/dev/");
2066                                 if (match_key(rules, cur, devlink) == 0) {
2067                                         match = true;
2068                                         break;
2069                                 }
2070                         }
2071                         if (!match)
2072                                 goto nomatch;
2073                         break;
2074                 }
2075                 case TK_M_NAME:
2076                         if (match_key(rules, cur, event->name) != 0)
2077                                 goto nomatch;
2078                         break;
2079                 case TK_M_ENV: {
2080                         const char *key_name = &rules->buf[cur->key.attr_off];
2081                         const char *value;
2082
2083                         value = udev_device_get_property_value(event->dev, key_name);
2084                         if (value == NULL)
2085                                 value = "";
2086                         if (match_key(rules, cur, value))
2087                                 goto nomatch;
2088                         break;
2089                 }
2090                 case TK_M_TAG: {
2091                         struct udev_list_entry *list_entry;
2092                         bool match = false;
2093
2094                         udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(event->dev)) {
2095                                 if (streq(&rules->buf[cur->key.value_off], udev_list_entry_get_name(list_entry))) {
2096                                         match = true;
2097                                         break;
2098                                 }
2099                         }
2100                         if (!match && (cur->key.op != OP_NOMATCH))
2101                                 goto nomatch;
2102                         break;
2103                 }
2104                 case TK_M_SUBSYSTEM:
2105                         if (match_key(rules, cur, udev_device_get_subsystem(event->dev)) != 0)
2106                                 goto nomatch;
2107                         break;
2108                 case TK_M_DRIVER:
2109                         if (match_key(rules, cur, udev_device_get_driver(event->dev)) != 0)
2110                                 goto nomatch;
2111                         break;
2112                 case TK_M_WAITFOR: {
2113                         char filename[UTIL_PATH_SIZE];
2114                         int found;
2115
2116                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], filename, sizeof(filename));
2117                         found = (wait_for_file(event->dev, filename, 10) == 0);
2118                         if (!found && (cur->key.op != OP_NOMATCH))
2119                                 goto nomatch;
2120                         break;
2121                 }
2122                 case TK_M_ATTR:
2123                         if (match_attr(rules, event->dev, event, cur) != 0)
2124                                 goto nomatch;
2125                         break;
2126                 case TK_M_KERNELS:
2127                 case TK_M_SUBSYSTEMS:
2128                 case TK_M_DRIVERS:
2129                 case TK_M_ATTRS:
2130                 case TK_M_TAGS: {
2131                         struct token *next;
2132
2133                         /* get whole sequence of parent matches */
2134                         next = cur;
2135                         while (next->type > TK_M_PARENTS_MIN && next->type < TK_M_PARENTS_MAX)
2136                                 next++;
2137
2138                         /* loop over parents */
2139                         event->dev_parent = event->dev;
2140                         for (;;) {
2141                                 struct token *key;
2142
2143                                 /* loop over sequence of parent match keys */
2144                                 for (key = cur; key < next; key++ ) {
2145                                         dump_token(rules, key);
2146                                         switch(key->type) {
2147                                         case TK_M_KERNELS:
2148                                                 if (match_key(rules, key, udev_device_get_sysname(event->dev_parent)) != 0)
2149                                                         goto try_parent;
2150                                                 break;
2151                                         case TK_M_SUBSYSTEMS:
2152                                                 if (match_key(rules, key, udev_device_get_subsystem(event->dev_parent)) != 0)
2153                                                         goto try_parent;
2154                                                 break;
2155                                         case TK_M_DRIVERS:
2156                                                 if (match_key(rules, key, udev_device_get_driver(event->dev_parent)) != 0)
2157                                                         goto try_parent;
2158                                                 break;
2159                                         case TK_M_ATTRS:
2160                                                 if (match_attr(rules, event->dev_parent, event, key) != 0)
2161                                                         goto try_parent;
2162                                                 break;
2163                                         case TK_M_TAGS: {
2164                                                 bool match = udev_device_has_tag(event->dev_parent, &rules->buf[cur->key.value_off]);
2165
2166                                                 if (match && key->key.op == OP_NOMATCH)
2167                                                         goto try_parent;
2168                                                 if (!match && key->key.op == OP_MATCH)
2169                                                         goto try_parent;
2170                                                 break;
2171                                         }
2172                                         default:
2173                                                 goto nomatch;
2174                                         }
2175                                 }
2176                                 break;
2177
2178                         try_parent:
2179                                 event->dev_parent = udev_device_get_parent(event->dev_parent);
2180                                 if (event->dev_parent == NULL)
2181                                         goto nomatch;
2182                         }
2183                         /* move behind our sequence of parent match keys */
2184                         cur = next;
2185                         continue;
2186                 }
2187                 case TK_M_TEST: {
2188                         char filename[UTIL_PATH_SIZE];
2189                         struct stat statbuf;
2190                         int match;
2191
2192                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], filename, sizeof(filename));
2193                         if (util_resolve_subsys_kernel(event->udev, filename, filename, sizeof(filename), 0) != 0) {
2194                                 if (filename[0] != '/') {
2195                                         char tmp[UTIL_PATH_SIZE];
2196
2197                                         util_strscpy(tmp, sizeof(tmp), filename);
2198                                         util_strscpyl(filename, sizeof(filename),
2199                                                       udev_device_get_syspath(event->dev), "/", tmp, NULL);
2200                                 }
2201                         }
2202                         attr_subst_subdir(filename, sizeof(filename));
2203
2204                         match = (stat(filename, &statbuf) == 0);
2205                         if (match && cur->key.mode > 0)
2206                                 match = ((statbuf.st_mode & cur->key.mode) > 0);
2207                         if (match && cur->key.op == OP_NOMATCH)
2208                                 goto nomatch;
2209                         if (!match && cur->key.op == OP_MATCH)
2210                                 goto nomatch;
2211                         break;
2212                 }
2213                 case TK_M_EVENT_TIMEOUT:
2214                         log_debug("OPTIONS event_timeout=%u\n", cur->key.event_timeout);
2215                         event->timeout_usec = cur->key.event_timeout * 1000 * 1000;
2216                         break;
2217                 case TK_M_PROGRAM: {
2218                         char program[UTIL_PATH_SIZE];
2219                         char **envp;
2220                         char result[UTIL_PATH_SIZE];
2221
2222                         free(event->program_result);
2223                         event->program_result = NULL;
2224                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], program, sizeof(program));
2225                         envp = udev_device_get_properties_envp(event->dev);
2226                         log_debug("PROGRAM '%s' %s:%u\n",
2227                                   program,
2228                                   &rules->buf[rule->rule.filename_off],
2229                                   rule->rule.filename_line);
2230
2231                         if (udev_event_spawn(event, program, envp, sigmask, result, sizeof(result)) < 0) {
2232                                 if (cur->key.op != OP_NOMATCH)
2233                                         goto nomatch;
2234                         } else {
2235                                 int count;
2236
2237                                 util_remove_trailing_chars(result, '\n');
2238                                 if (esc == ESCAPE_UNSET || esc == ESCAPE_REPLACE) {
2239                                         count = util_replace_chars(result, UDEV_ALLOWED_CHARS_INPUT);
2240                                         if (count > 0)
2241                                                 log_debug("%i character(s) replaced\n" , count);
2242                                 }
2243                                 event->program_result = strdup(result);
2244                                 if (cur->key.op == OP_NOMATCH)
2245                                         goto nomatch;
2246                         }
2247                         break;
2248                 }
2249                 case TK_M_IMPORT_FILE: {
2250                         char import[UTIL_PATH_SIZE];
2251
2252                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], import, sizeof(import));
2253                         if (import_file_into_properties(event->dev, import) != 0)
2254                                 if (cur->key.op != OP_NOMATCH)
2255                                         goto nomatch;
2256                         break;
2257                 }
2258                 case TK_M_IMPORT_PROG: {
2259                         char import[UTIL_PATH_SIZE];
2260
2261                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], import, sizeof(import));
2262                         log_debug("IMPORT '%s' %s:%u\n",
2263                                   import,
2264                                   &rules->buf[rule->rule.filename_off],
2265                                   rule->rule.filename_line);
2266
2267                         if (import_program_into_properties(event, import, sigmask) != 0)
2268                                 if (cur->key.op != OP_NOMATCH)
2269                                         goto nomatch;
2270                         break;
2271                 }
2272                 case TK_M_IMPORT_BUILTIN: {
2273                         char command[UTIL_PATH_SIZE];
2274
2275                         if (udev_builtin_run_once(cur->key.builtin_cmd)) {
2276                                 /* check if we ran already */
2277                                 if (event->builtin_run & (1 << cur->key.builtin_cmd)) {
2278                                         log_debug("IMPORT builtin skip '%s' %s:%u\n",
2279                                                   udev_builtin_name(cur->key.builtin_cmd),
2280                                                   &rules->buf[rule->rule.filename_off],
2281                                                   rule->rule.filename_line);
2282                                         /* return the result from earlier run */
2283                                         if (event->builtin_ret & (1 << cur->key.builtin_cmd))
2284                                         if (cur->key.op != OP_NOMATCH)
2285                                                         goto nomatch;
2286                                         break;
2287                                 }
2288                                 /* mark as ran */
2289                                 event->builtin_run |= (1 << cur->key.builtin_cmd);
2290                         }
2291
2292                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], command, sizeof(command));
2293                         log_debug("IMPORT builtin '%s' %s:%u\n",
2294                                   udev_builtin_name(cur->key.builtin_cmd),
2295                                   &rules->buf[rule->rule.filename_off],
2296                                   rule->rule.filename_line);
2297
2298                         if (udev_builtin_run(event->dev, cur->key.builtin_cmd, command, false) != 0) {
2299                                 /* remember failure */
2300                                 log_debug("IMPORT builtin '%s' returned non-zero\n",
2301                                           udev_builtin_name(cur->key.builtin_cmd));
2302                                 event->builtin_ret |= (1 << cur->key.builtin_cmd);
2303                                 if (cur->key.op != OP_NOMATCH)
2304                                         goto nomatch;
2305                         }
2306                         break;
2307                 }
2308                 case TK_M_IMPORT_DB: {
2309                         const char *key = &rules->buf[cur->key.value_off];
2310                         const char *value;
2311
2312                         value = udev_device_get_property_value(event->dev_db, key);
2313                         if (value != NULL) {
2314                                 struct udev_list_entry *entry;
2315
2316                                 entry = udev_device_add_property(event->dev, key, value);
2317                                 udev_list_entry_set_num(entry, true);
2318                         } else {
2319                                 if (cur->key.op != OP_NOMATCH)
2320                                         goto nomatch;
2321                         }
2322                         break;
2323                 }
2324                 case TK_M_IMPORT_CMDLINE: {
2325                         FILE *f;
2326                         bool imported = false;
2327
2328                         f = fopen("/proc/cmdline", "re");
2329                         if (f != NULL) {
2330                                 char cmdline[4096];
2331
2332                                 if (fgets(cmdline, sizeof(cmdline), f) != NULL) {
2333                                         const char *key = &rules->buf[cur->key.value_off];
2334                                         char *pos;
2335
2336                                         pos = strstr(cmdline, key);
2337                                         if (pos != NULL) {
2338                                                 struct udev_list_entry *entry;
2339
2340                                                 pos += strlen(key);
2341                                                 if (pos[0] == '\0' || isspace(pos[0])) {
2342                                                         /* we import simple flags as 'FLAG=1' */
2343                                                         entry = udev_device_add_property(event->dev, key, "1");
2344                                                         udev_list_entry_set_num(entry, true);
2345                                                         imported = true;
2346                                                 } else if (pos[0] == '=') {
2347                                                         const char *value;
2348
2349                                                         pos++;
2350                                                         value = pos;
2351                                                         while (pos[0] != '\0' && !isspace(pos[0]))
2352                                                                 pos++;
2353                                                         pos[0] = '\0';
2354                                                         entry = udev_device_add_property(event->dev, key, value);
2355                                                         udev_list_entry_set_num(entry, true);
2356                                                         imported = true;
2357                                                 }
2358                                         }
2359                                 }
2360                                 fclose(f);
2361                         }
2362                         if (!imported && cur->key.op != OP_NOMATCH)
2363                                 goto nomatch;
2364                         break;
2365                 }
2366                 case TK_M_IMPORT_PARENT: {
2367                         char import[UTIL_PATH_SIZE];
2368
2369                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], import, sizeof(import));
2370                         if (import_parent_into_properties(event->dev, import) != 0)
2371                                 if (cur->key.op != OP_NOMATCH)
2372                                         goto nomatch;
2373                         break;
2374                 }
2375                 case TK_M_RESULT:
2376                         if (match_key(rules, cur, event->program_result) != 0)
2377                                 goto nomatch;
2378                         break;
2379                 case TK_A_STRING_ESCAPE_NONE:
2380                         esc = ESCAPE_NONE;
2381                         break;
2382                 case TK_A_STRING_ESCAPE_REPLACE:
2383                         esc = ESCAPE_REPLACE;
2384                         break;
2385                 case TK_A_DB_PERSIST:
2386                         udev_device_set_db_persist(event->dev);
2387                         break;
2388                 case TK_A_INOTIFY_WATCH:
2389                         if (event->inotify_watch_final)
2390                                 break;
2391                         if (cur->key.op == OP_ASSIGN_FINAL)
2392                                 event->inotify_watch_final = true;
2393                         event->inotify_watch = cur->key.watch;
2394                         break;
2395                 case TK_A_DEVLINK_PRIO:
2396                         udev_device_set_devlink_priority(event->dev, cur->key.devlink_prio);
2397                         break;
2398                 case TK_A_OWNER: {
2399                         char owner[UTIL_NAME_SIZE];
2400
2401                         if (event->owner_final)
2402                                 break;
2403                         if (cur->key.op == OP_ASSIGN_FINAL)
2404                                 event->owner_final = true;
2405                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], owner, sizeof(owner));
2406                         event->uid = util_lookup_user(event->udev, owner);
2407                         log_debug("OWNER %u %s:%u\n",
2408                                   event->uid,
2409                                   &rules->buf[rule->rule.filename_off],
2410                                   rule->rule.filename_line);
2411                         break;
2412                 }
2413                 case TK_A_GROUP: {
2414                         char group[UTIL_NAME_SIZE];
2415
2416                         if (event->group_final)
2417                                 break;
2418                         if (cur->key.op == OP_ASSIGN_FINAL)
2419                                 event->group_final = true;
2420                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], group, sizeof(group));
2421                         event->gid = util_lookup_group(event->udev, group);
2422                         log_debug("GROUP %u %s:%u\n",
2423                                   event->gid,
2424                                   &rules->buf[rule->rule.filename_off],
2425                                   rule->rule.filename_line);
2426                         break;
2427                 }
2428                 case TK_A_MODE: {
2429                         char mode_str[UTIL_NAME_SIZE];
2430                         mode_t mode;
2431                         char *endptr;
2432
2433                         if (event->mode_final)
2434                                 break;
2435                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], mode_str, sizeof(mode_str));
2436                         mode = strtol(mode_str, &endptr, 8);
2437                         if (endptr[0] != '\0') {
2438                                 log_error("ignoring invalid mode '%s'\n", mode_str);
2439                                 break;
2440                         }
2441                         if (cur->key.op == OP_ASSIGN_FINAL)
2442                                 event->mode_final = true;
2443                         event->mode_set = true;
2444                         event->mode = mode;
2445                         log_debug("MODE %#o %s:%u\n",
2446                                   event->mode,
2447                                   &rules->buf[rule->rule.filename_off],
2448                                   rule->rule.filename_line);
2449                         break;
2450                 }
2451                 case TK_A_OWNER_ID:
2452                         if (event->owner_final)
2453                                 break;
2454                         if (cur->key.op == OP_ASSIGN_FINAL)
2455                                 event->owner_final = true;
2456                         event->uid = cur->key.uid;
2457                         log_debug("OWNER %u %s:%u\n",
2458                                   event->uid,
2459                                   &rules->buf[rule->rule.filename_off],
2460                                   rule->rule.filename_line);
2461                         break;
2462                 case TK_A_GROUP_ID:
2463                         if (event->group_final)
2464                                 break;
2465                         if (cur->key.op == OP_ASSIGN_FINAL)
2466                                 event->group_final = true;
2467                         event->gid = cur->key.gid;
2468                         log_debug("GROUP %u %s:%u\n",
2469                                   event->gid,
2470                                   &rules->buf[rule->rule.filename_off],
2471                                   rule->rule.filename_line);
2472                         break;
2473                 case TK_A_MODE_ID:
2474                         if (event->mode_final)
2475                                 break;
2476                         if (cur->key.op == OP_ASSIGN_FINAL)
2477                                 event->mode_final = true;
2478                         event->mode_set = true;
2479                         event->mode = cur->key.mode;
2480                         log_debug("MODE %#o %s:%u\n",
2481                                   event->mode,
2482                                   &rules->buf[rule->rule.filename_off],
2483                                   rule->rule.filename_line);
2484                         break;
2485                 case TK_A_ENV: {
2486                         const char *name = &rules->buf[cur->key.attr_off];
2487                         char *value = &rules->buf[cur->key.value_off];
2488
2489                         if (value[0] != '\0') {
2490                                 char temp_value[UTIL_NAME_SIZE];
2491                                 struct udev_list_entry *entry;
2492
2493                                 udev_event_apply_format(event, value, temp_value, sizeof(temp_value));
2494                                 entry = udev_device_add_property(event->dev, name, temp_value);
2495                                 /* store in db, skip private keys */
2496                                 if (name[0] != '.')
2497                                         udev_list_entry_set_num(entry, true);
2498                         } else {
2499                                 udev_device_add_property(event->dev, name, NULL);
2500                         }
2501                         break;
2502                 }
2503                 case TK_A_TAG: {
2504                         char tag[UTIL_PATH_SIZE];
2505                         const char *p;
2506
2507                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], tag, sizeof(tag));
2508                         if (cur->key.op == OP_ASSIGN || cur->key.op == OP_ASSIGN_FINAL)
2509                                 udev_device_cleanup_tags_list(event->dev);
2510                         for (p = tag; *p != '\0'; p++) {
2511                                 if ((*p >= 'a' && *p <= 'z') ||
2512                                     (*p >= 'A' && *p <= 'Z') ||
2513                                     (*p >= '0' && *p <= '9') ||
2514                                     *p == '-' || *p == '_')
2515                                         continue;
2516                                 log_error("ignoring invalid tag name '%s'\n", tag);
2517                                 break;
2518                         }
2519                         udev_device_add_tag(event->dev, tag);
2520                         break;
2521                 }
2522                 case TK_A_NAME: {
2523                         const char *name  = &rules->buf[cur->key.value_off];
2524
2525                         char name_str[UTIL_PATH_SIZE];
2526                         int count;
2527
2528                         if (event->name_final)
2529                                 break;
2530                         if (cur->key.op == OP_ASSIGN_FINAL)
2531                                 event->name_final = true;
2532                         udev_event_apply_format(event, name, name_str, sizeof(name_str));
2533                         if (esc == ESCAPE_UNSET || esc == ESCAPE_REPLACE) {
2534                                 count = util_replace_chars(name_str, "/");
2535                                 if (count > 0)
2536                                         log_debug("%i character(s) replaced\n", count);
2537                         }
2538                         if (major(udev_device_get_devnum(event->dev)) &&
2539                             (!streq(name_str, udev_device_get_devnode(event->dev) + strlen("/dev/")))) {
2540                                 log_error("NAME=\"%s\" ignored, kernel device nodes "
2541                                     "can not be renamed; please fix it in %s:%u\n", name,
2542                                     &rules->buf[rule->rule.filename_off], rule->rule.filename_line);
2543                                 break;
2544                         }
2545                         free(event->name);
2546                         event->name = strdup(name_str);
2547                         log_debug("NAME '%s' %s:%u\n",
2548                                   event->name,
2549                                   &rules->buf[rule->rule.filename_off],
2550                                   rule->rule.filename_line);
2551                         break;
2552                 }
2553                 case TK_A_DEVLINK: {
2554                         char temp[UTIL_PATH_SIZE];
2555                         char filename[UTIL_PATH_SIZE];
2556                         char *pos, *next;
2557                         int count = 0;
2558
2559                         if (event->devlink_final)
2560                                 break;
2561                         if (major(udev_device_get_devnum(event->dev)) == 0)
2562                                 break;
2563                         if (cur->key.op == OP_ASSIGN_FINAL)
2564                                 event->devlink_final = true;
2565                         if (cur->key.op == OP_ASSIGN || cur->key.op == OP_ASSIGN_FINAL)
2566                                 udev_device_cleanup_devlinks_list(event->dev);
2567
2568                         /* allow  multiple symlinks separated by spaces */
2569                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], temp, sizeof(temp));
2570                         if (esc == ESCAPE_UNSET)
2571                                 count = util_replace_chars(temp, "/ ");
2572                         else if (esc == ESCAPE_REPLACE)
2573                                 count = util_replace_chars(temp, "/");
2574                         if (count > 0)
2575                                 log_debug("%i character(s) replaced\n" , count);
2576                         pos = temp;
2577                         while (isspace(pos[0]))
2578                                 pos++;
2579                         next = strchr(pos, ' ');
2580                         while (next != NULL) {
2581                                 next[0] = '\0';
2582                                 log_debug("LINK '%s' %s:%u\n", pos,
2583                                           &rules->buf[rule->rule.filename_off], rule->rule.filename_line);
2584                                 util_strscpyl(filename, sizeof(filename), "/dev/", pos, NULL);
2585                                 udev_device_add_devlink(event->dev, filename, cur->key.devlink_unique);
2586                                 while (isspace(next[1]))
2587                                         next++;
2588                                 pos = &next[1];
2589                                 next = strchr(pos, ' ');
2590                         }
2591                         if (pos[0] != '\0') {
2592                                 log_debug("LINK '%s' %s:%u\n", pos,
2593                                           &rules->buf[rule->rule.filename_off], rule->rule.filename_line);
2594                                 util_strscpyl(filename, sizeof(filename), "/dev/", pos, NULL);
2595                                 udev_device_add_devlink(event->dev, filename, cur->key.devlink_unique);
2596                         }
2597                         break;
2598                 }
2599                 case TK_A_ATTR: {
2600                         const char *key_name = &rules->buf[cur->key.attr_off];
2601                         char attr[UTIL_PATH_SIZE];
2602                         char value[UTIL_NAME_SIZE];
2603                         FILE *f;
2604
2605                         if (util_resolve_subsys_kernel(event->udev, key_name, attr, sizeof(attr), 0) != 0)
2606                                 util_strscpyl(attr, sizeof(attr), udev_device_get_syspath(event->dev), "/", key_name, NULL);
2607                         attr_subst_subdir(attr, sizeof(attr));
2608
2609                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], value, sizeof(value));
2610                         log_debug("ATTR '%s' writing '%s' %s:%u\n", attr, value,
2611                                   &rules->buf[rule->rule.filename_off],
2612                                   rule->rule.filename_line);
2613                         f = fopen(attr, "we");
2614                         if (f != NULL) {
2615                                 if (fprintf(f, "%s", value) <= 0)
2616                                         log_error("error writing ATTR{%s}: %m\n", attr);
2617                                 fclose(f);
2618                         } else {
2619                                 log_error("error opening ATTR{%s} for writing: %m\n", attr);
2620                         }
2621                         break;
2622                 }
2623                 case TK_A_RUN_BUILTIN:
2624                 case TK_A_RUN_PROGRAM: {
2625                         struct udev_list_entry *entry;
2626
2627                         if (cur->key.op == OP_ASSIGN || cur->key.op == OP_ASSIGN_FINAL)
2628                                 udev_list_cleanup(&event->run_list);
2629                         log_debug("RUN '%s' %s:%u\n",
2630                                   &rules->buf[cur->key.value_off],
2631                                   &rules->buf[rule->rule.filename_off],
2632                                   rule->rule.filename_line);
2633                         entry = udev_list_entry_add(&event->run_list, &rules->buf[cur->key.value_off], NULL);
2634                         udev_list_entry_set_num(entry, cur->key.builtin_cmd);
2635                         break;
2636                 }
2637                 case TK_A_GOTO:
2638                         if (cur->key.rule_goto == 0)
2639                                 break;
2640                         cur = &rules->tokens[cur->key.rule_goto];
2641                         continue;
2642                 case TK_END:
2643                         return 0;
2644
2645                 case TK_M_PARENTS_MIN:
2646                 case TK_M_PARENTS_MAX:
2647                 case TK_M_MAX:
2648                 case TK_UNSET:
2649                         log_error("wrong type %u\n", cur->type);
2650                         goto nomatch;
2651                 }
2652
2653                 cur++;
2654                 continue;
2655         nomatch:
2656                 /* fast-forward to next rule */
2657                 cur = rule + rule->rule.token_count;
2658         }
2659 }
2660
2661 void udev_rules_apply_static_dev_perms(struct udev_rules *rules)
2662 {
2663         struct token *cur;
2664         struct token *rule;
2665         uid_t uid = 0;
2666         gid_t gid = 0;
2667         mode_t mode = 0;
2668
2669         if (rules->tokens == NULL)
2670                 return;
2671
2672         cur = &rules->tokens[0];
2673         rule = cur;
2674         for (;;) {
2675                 switch (cur->type) {
2676                 case TK_RULE:
2677                         /* current rule */
2678                         rule = cur;
2679
2680                         /* skip rules without a static_node tag */
2681                         if (!rule->rule.has_static_node)
2682                                 goto next;
2683
2684                         uid = 0;
2685                         gid = 0;
2686                         mode = 0;
2687                         break;
2688                 case TK_A_OWNER_ID:
2689                         uid = cur->key.uid;
2690                         break;
2691                 case TK_A_GROUP_ID:
2692                         gid = cur->key.gid;
2693                         break;
2694                 case TK_A_MODE_ID:
2695                         mode = cur->key.mode;
2696                         break;
2697                 case TK_A_STATIC_NODE: {
2698                         char filename[UTIL_PATH_SIZE];
2699                         struct stat stats;
2700
2701                         /* we assure, that the permissions tokens are sorted before the static token */
2702                         if (mode == 0 && uid == 0 && gid == 0)
2703                                 goto next;
2704                         util_strscpyl(filename, sizeof(filename), "/dev/",
2705                                       &rules->buf[cur->key.value_off], NULL);
2706                         if (stat(filename, &stats) != 0)
2707                                 goto next;
2708                         if (!S_ISBLK(stats.st_mode) && !S_ISCHR(stats.st_mode))
2709                                 goto next;
2710                         if (mode == 0) {
2711                                 if (gid > 0)
2712                                         mode = 0660;
2713                                 else
2714                                         mode = 0600;
2715                         }
2716                         if (mode != (stats.st_mode & 01777)) {
2717                                 chmod(filename, mode);
2718                                 log_debug("chmod '%s' %#o\n", filename, mode);
2719                         }
2720
2721                         if ((uid != 0 && uid != stats.st_uid) || (gid != 0 && gid != stats.st_gid)) {
2722                                 chown(filename, uid, gid);
2723                                 log_debug("chown '%s' %u %u\n", filename, uid, gid);
2724                         }
2725
2726                         utimensat(AT_FDCWD, filename, NULL, 0);
2727                         break;
2728                 }
2729                 case TK_END:
2730                         return;
2731                 }
2732
2733                 cur++;
2734                 continue;
2735 next:
2736                 /* fast-forward to next rule */
2737                 cur = rule + rule->rule.token_count;
2738                 continue;
2739         }
2740 }