chiark / gitweb /
logind: use bus_method_call_with_reply() where posible
[elogind.git] / src / udev / udev-rules.c
1 /*
2  * Copyright (C) 2003-2010 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         r = conf_files_list_strv(&files, ".rules", (const char **)rules->dirs);
1774         if (r < 0) {
1775                 log_error("failed to enumerate rules files: %s\n", strerror(-r));
1776                 return NULL;
1777         }
1778         rules->dirs_ts_usec = calloc(strv_length(rules->dirs), sizeof(long long));
1779
1780         /*
1781          * The offset value in the rules strct is limited; add all
1782          * rules file names to the beginning of the string buffer.
1783          */
1784         STRV_FOREACH(f, files)
1785                 add_string(rules, *f);
1786
1787         STRV_FOREACH(f, files)
1788                 parse_file(rules, *f);
1789
1790         strv_free(files);
1791
1792         memset(&end_token, 0x00, sizeof(struct token));
1793         end_token.type = TK_END;
1794         add_token(rules, &end_token);
1795
1796         /* shrink allocated token and string buffer */
1797         if (rules->token_cur < rules->token_max) {
1798                 struct token *tokens;
1799
1800                 tokens = realloc(rules->tokens, rules->token_cur * sizeof(struct token));
1801                 if (tokens != NULL || rules->token_cur == 0) {
1802                         rules->tokens = tokens;
1803                         rules->token_max = rules->token_cur;
1804                 }
1805         }
1806         if (rules->buf_cur < rules->buf_max) {
1807                 char *buf;
1808
1809                 buf = realloc(rules->buf, rules->buf_cur);
1810                 if (buf != NULL || rules->buf_cur == 0) {
1811                         rules->buf = buf;
1812                         rules->buf_max = rules->buf_cur;
1813                 }
1814         }
1815         log_debug("rules use %zu bytes tokens (%u * %zu bytes), %zu bytes buffer\n",
1816                   rules->token_max * sizeof(struct token), rules->token_max, sizeof(struct token), rules->buf_max);
1817         log_debug("temporary index used %zu bytes (%u * %zu bytes)\n",
1818                   rules->trie_nodes_cur * sizeof(struct trie_node),
1819                   rules->trie_nodes_cur, sizeof(struct trie_node));
1820
1821         /* cleanup trie */
1822         free(rules->trie_nodes);
1823         rules->trie_nodes = NULL;
1824         rules->trie_nodes_cur = 0;
1825         rules->trie_nodes_max = 0;
1826
1827         /* cleanup uid/gid cache */
1828         free(rules->uids);
1829         rules->uids = NULL;
1830         rules->uids_cur = 0;
1831         rules->uids_max = 0;
1832         free(rules->gids);
1833         rules->gids = NULL;
1834         rules->gids_cur = 0;
1835         rules->gids_max = 0;
1836
1837         dump_rules(rules);
1838         return rules;
1839 }
1840
1841 struct udev_rules *udev_rules_unref(struct udev_rules *rules)
1842 {
1843         if (rules == NULL)
1844                 return NULL;
1845         free(rules->tokens);
1846         free(rules->buf);
1847         free(rules->trie_nodes);
1848         free(rules->uids);
1849         free(rules->gids);
1850         strv_free(rules->dirs);
1851         free(rules->dirs_ts_usec);
1852         free(rules);
1853         return NULL;
1854 }
1855
1856 bool udev_rules_check_timestamp(struct udev_rules *rules)
1857 {
1858         unsigned int i;
1859         bool changed = false;
1860
1861         if (rules == NULL)
1862                 goto out;
1863
1864         for (i = 0; rules->dirs[i]; i++) {
1865                 struct stat stats;
1866
1867                 if (stat(rules->dirs[i], &stats) < 0)
1868                         continue;
1869
1870                 if (rules->dirs_ts_usec[i] == ts_usec(&stats.st_mtim))
1871                         continue;
1872
1873                 /* first check */
1874                 if (rules->dirs_ts_usec[i] != 0) {
1875                         log_debug("reload - timestamp of '%s' changed\n", rules->dirs[i]);
1876                         changed = true;
1877                 }
1878
1879                 /* update timestamp */
1880                 rules->dirs_ts_usec[i] = ts_usec(&stats.st_mtim);
1881         }
1882 out:
1883         return changed;
1884 }
1885
1886 static int match_key(struct udev_rules *rules, struct token *token, const char *val)
1887 {
1888         char *key_value = &rules->buf[token->key.value_off];
1889         char *pos;
1890         bool match = false;
1891
1892         if (val == NULL)
1893                 val = "";
1894
1895         switch (token->key.glob) {
1896         case GL_PLAIN:
1897                 match = (streq(key_value, val));
1898                 break;
1899         case GL_GLOB:
1900                 match = (fnmatch(key_value, val, 0) == 0);
1901                 break;
1902         case GL_SPLIT:
1903                 {
1904                         const char *s;
1905                         size_t len;
1906
1907                         s = &rules->buf[token->key.value_off];
1908                         len = strlen(val);
1909                         for (;;) {
1910                                 const char *next;
1911
1912                                 next = strchr(s, '|');
1913                                 if (next != NULL) {
1914                                         size_t matchlen = (size_t)(next - s);
1915
1916                                         match = (matchlen == len && strncmp(s, val, matchlen) == 0);
1917                                         if (match)
1918                                                 break;
1919                                 } else {
1920                                         match = (streq(s, val));
1921                                         break;
1922                                 }
1923                                 s = &next[1];
1924                         }
1925                         break;
1926                 }
1927         case GL_SPLIT_GLOB:
1928                 {
1929                         char value[UTIL_PATH_SIZE];
1930
1931                         util_strscpy(value, sizeof(value), &rules->buf[token->key.value_off]);
1932                         key_value = value;
1933                         while (key_value != NULL) {
1934                                 pos = strchr(key_value, '|');
1935                                 if (pos != NULL) {
1936                                         pos[0] = '\0';
1937                                         pos = &pos[1];
1938                                 }
1939                                 match = (fnmatch(key_value, val, 0) == 0);
1940                                 if (match)
1941                                         break;
1942                                 key_value = pos;
1943                         }
1944                         break;
1945                 }
1946         case GL_SOMETHING:
1947                 match = (val[0] != '\0');
1948                 break;
1949         case GL_UNSET:
1950                 return -1;
1951         }
1952
1953         if (match && (token->key.op == OP_MATCH))
1954                 return 0;
1955         if (!match && (token->key.op == OP_NOMATCH))
1956                 return 0;
1957         return -1;
1958 }
1959
1960 static int match_attr(struct udev_rules *rules, struct udev_device *dev, struct udev_event *event, struct token *cur)
1961 {
1962         const char *name;
1963         char nbuf[UTIL_NAME_SIZE];
1964         const char *value;
1965         char vbuf[UTIL_NAME_SIZE];
1966         size_t len;
1967
1968         name = &rules->buf[cur->key.attr_off];
1969         switch (cur->key.attrsubst) {
1970         case SB_FORMAT:
1971                 udev_event_apply_format(event, name, nbuf, sizeof(nbuf));
1972                 name = nbuf;
1973                 /* fall through */
1974         case SB_NONE:
1975                 value = udev_device_get_sysattr_value(dev, name);
1976                 if (value == NULL)
1977                         return -1;
1978                 break;
1979         case SB_SUBSYS:
1980                 if (util_resolve_subsys_kernel(event->udev, name, vbuf, sizeof(vbuf), 1) != 0)
1981                         return -1;
1982                 value = vbuf;
1983                 break;
1984         default:
1985                 return -1;
1986         }
1987
1988         /* remove trailing whitespace, if not asked to match for it */
1989         len = strlen(value);
1990         if (len > 0 && isspace(value[len-1])) {
1991                 const char *key_value;
1992                 size_t klen;
1993
1994                 key_value = &rules->buf[cur->key.value_off];
1995                 klen = strlen(key_value);
1996                 if (klen > 0 && !isspace(key_value[klen-1])) {
1997                         if (value != vbuf) {
1998                                 util_strscpy(vbuf, sizeof(vbuf), value);
1999                                 value = vbuf;
2000                         }
2001                         while (len > 0 && isspace(vbuf[--len]))
2002                                 vbuf[len] = '\0';
2003                 }
2004         }
2005
2006         return match_key(rules, cur, value);
2007 }
2008
2009 enum escape_type {
2010         ESCAPE_UNSET,
2011         ESCAPE_NONE,
2012         ESCAPE_REPLACE,
2013 };
2014
2015 int udev_rules_apply_to_event(struct udev_rules *rules, struct udev_event *event, const sigset_t *sigmask)
2016 {
2017         struct token *cur;
2018         struct token *rule;
2019         enum escape_type esc = ESCAPE_UNSET;
2020         bool can_set_name;
2021
2022         if (rules->tokens == NULL)
2023                 return -1;
2024
2025         can_set_name = ((!streq(udev_device_get_action(event->dev), "remove")) &&
2026                         (major(udev_device_get_devnum(event->dev)) > 0 ||
2027                          udev_device_get_ifindex(event->dev) > 0));
2028
2029         /* loop through token list, match, run actions or forward to next rule */
2030         cur = &rules->tokens[0];
2031         rule = cur;
2032         for (;;) {
2033                 dump_token(rules, cur);
2034                 switch (cur->type) {
2035                 case TK_RULE:
2036                         /* current rule */
2037                         rule = cur;
2038                         /* possibly skip rules which want to set NAME, SYMLINK, OWNER, GROUP, MODE */
2039                         if (!can_set_name && rule->rule.can_set_name)
2040                                 goto nomatch;
2041                         esc = ESCAPE_UNSET;
2042                         break;
2043                 case TK_M_ACTION:
2044                         if (match_key(rules, cur, udev_device_get_action(event->dev)) != 0)
2045                                 goto nomatch;
2046                         break;
2047                 case TK_M_DEVPATH:
2048                         if (match_key(rules, cur, udev_device_get_devpath(event->dev)) != 0)
2049                                 goto nomatch;
2050                         break;
2051                 case TK_M_KERNEL:
2052                         if (match_key(rules, cur, udev_device_get_sysname(event->dev)) != 0)
2053                                 goto nomatch;
2054                         break;
2055                 case TK_M_DEVLINK: {
2056                         struct udev_list_entry *list_entry;
2057                         bool match = false;
2058
2059                         udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(event->dev)) {
2060                                 const char *devlink;
2061
2062                                 devlink =  udev_list_entry_get_name(list_entry) + strlen("/dev/");
2063                                 if (match_key(rules, cur, devlink) == 0) {
2064                                         match = true;
2065                                         break;
2066                                 }
2067                         }
2068                         if (!match)
2069                                 goto nomatch;
2070                         break;
2071                 }
2072                 case TK_M_NAME:
2073                         if (match_key(rules, cur, event->name) != 0)
2074                                 goto nomatch;
2075                         break;
2076                 case TK_M_ENV: {
2077                         const char *key_name = &rules->buf[cur->key.attr_off];
2078                         const char *value;
2079
2080                         value = udev_device_get_property_value(event->dev, key_name);
2081                         if (value == NULL)
2082                                 value = "";
2083                         if (match_key(rules, cur, value))
2084                                 goto nomatch;
2085                         break;
2086                 }
2087                 case TK_M_TAG: {
2088                         struct udev_list_entry *list_entry;
2089                         bool match = false;
2090
2091                         udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(event->dev)) {
2092                                 if (streq(&rules->buf[cur->key.value_off], udev_list_entry_get_name(list_entry))) {
2093                                         match = true;
2094                                         break;
2095                                 }
2096                         }
2097                         if (!match && (cur->key.op != OP_NOMATCH))
2098                                 goto nomatch;
2099                         break;
2100                 }
2101                 case TK_M_SUBSYSTEM:
2102                         if (match_key(rules, cur, udev_device_get_subsystem(event->dev)) != 0)
2103                                 goto nomatch;
2104                         break;
2105                 case TK_M_DRIVER:
2106                         if (match_key(rules, cur, udev_device_get_driver(event->dev)) != 0)
2107                                 goto nomatch;
2108                         break;
2109                 case TK_M_WAITFOR: {
2110                         char filename[UTIL_PATH_SIZE];
2111                         int found;
2112
2113                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], filename, sizeof(filename));
2114                         found = (wait_for_file(event->dev, filename, 10) == 0);
2115                         if (!found && (cur->key.op != OP_NOMATCH))
2116                                 goto nomatch;
2117                         break;
2118                 }
2119                 case TK_M_ATTR:
2120                         if (match_attr(rules, event->dev, event, cur) != 0)
2121                                 goto nomatch;
2122                         break;
2123                 case TK_M_KERNELS:
2124                 case TK_M_SUBSYSTEMS:
2125                 case TK_M_DRIVERS:
2126                 case TK_M_ATTRS:
2127                 case TK_M_TAGS: {
2128                         struct token *next;
2129
2130                         /* get whole sequence of parent matches */
2131                         next = cur;
2132                         while (next->type > TK_M_PARENTS_MIN && next->type < TK_M_PARENTS_MAX)
2133                                 next++;
2134
2135                         /* loop over parents */
2136                         event->dev_parent = event->dev;
2137                         for (;;) {
2138                                 struct token *key;
2139
2140                                 /* loop over sequence of parent match keys */
2141                                 for (key = cur; key < next; key++ ) {
2142                                         dump_token(rules, key);
2143                                         switch(key->type) {
2144                                         case TK_M_KERNELS:
2145                                                 if (match_key(rules, key, udev_device_get_sysname(event->dev_parent)) != 0)
2146                                                         goto try_parent;
2147                                                 break;
2148                                         case TK_M_SUBSYSTEMS:
2149                                                 if (match_key(rules, key, udev_device_get_subsystem(event->dev_parent)) != 0)
2150                                                         goto try_parent;
2151                                                 break;
2152                                         case TK_M_DRIVERS:
2153                                                 if (match_key(rules, key, udev_device_get_driver(event->dev_parent)) != 0)
2154                                                         goto try_parent;
2155                                                 break;
2156                                         case TK_M_ATTRS:
2157                                                 if (match_attr(rules, event->dev_parent, event, key) != 0)
2158                                                         goto try_parent;
2159                                                 break;
2160                                         case TK_M_TAGS: {
2161                                                 bool match = udev_device_has_tag(event->dev_parent, &rules->buf[cur->key.value_off]);
2162
2163                                                 if (match && key->key.op == OP_NOMATCH)
2164                                                         goto try_parent;
2165                                                 if (!match && key->key.op == OP_MATCH)
2166                                                         goto try_parent;
2167                                                 break;
2168                                         }
2169                                         default:
2170                                                 goto nomatch;
2171                                         }
2172                                 }
2173                                 break;
2174
2175                         try_parent:
2176                                 event->dev_parent = udev_device_get_parent(event->dev_parent);
2177                                 if (event->dev_parent == NULL)
2178                                         goto nomatch;
2179                         }
2180                         /* move behind our sequence of parent match keys */
2181                         cur = next;
2182                         continue;
2183                 }
2184                 case TK_M_TEST: {
2185                         char filename[UTIL_PATH_SIZE];
2186                         struct stat statbuf;
2187                         int match;
2188
2189                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], filename, sizeof(filename));
2190                         if (util_resolve_subsys_kernel(event->udev, filename, filename, sizeof(filename), 0) != 0) {
2191                                 if (filename[0] != '/') {
2192                                         char tmp[UTIL_PATH_SIZE];
2193
2194                                         util_strscpy(tmp, sizeof(tmp), filename);
2195                                         util_strscpyl(filename, sizeof(filename),
2196                                                       udev_device_get_syspath(event->dev), "/", tmp, NULL);
2197                                 }
2198                         }
2199                         attr_subst_subdir(filename, sizeof(filename));
2200
2201                         match = (stat(filename, &statbuf) == 0);
2202                         if (match && cur->key.mode > 0)
2203                                 match = ((statbuf.st_mode & cur->key.mode) > 0);
2204                         if (match && cur->key.op == OP_NOMATCH)
2205                                 goto nomatch;
2206                         if (!match && cur->key.op == OP_MATCH)
2207                                 goto nomatch;
2208                         break;
2209                 }
2210                 case TK_M_EVENT_TIMEOUT:
2211                         log_debug("OPTIONS event_timeout=%u\n", cur->key.event_timeout);
2212                         event->timeout_usec = cur->key.event_timeout * 1000 * 1000;
2213                         break;
2214                 case TK_M_PROGRAM: {
2215                         char program[UTIL_PATH_SIZE];
2216                         char **envp;
2217                         char result[UTIL_PATH_SIZE];
2218
2219                         free(event->program_result);
2220                         event->program_result = NULL;
2221                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], program, sizeof(program));
2222                         envp = udev_device_get_properties_envp(event->dev);
2223                         log_debug("PROGRAM '%s' %s:%u\n",
2224                                   program,
2225                                   &rules->buf[rule->rule.filename_off],
2226                                   rule->rule.filename_line);
2227
2228                         if (udev_event_spawn(event, program, envp, sigmask, result, sizeof(result)) < 0) {
2229                                 if (cur->key.op != OP_NOMATCH)
2230                                         goto nomatch;
2231                         } else {
2232                                 int count;
2233
2234                                 util_remove_trailing_chars(result, '\n');
2235                                 if (esc == ESCAPE_UNSET || esc == ESCAPE_REPLACE) {
2236                                         count = util_replace_chars(result, UDEV_ALLOWED_CHARS_INPUT);
2237                                         if (count > 0)
2238                                                 log_debug("%i character(s) replaced\n" , count);
2239                                 }
2240                                 event->program_result = strdup(result);
2241                                 if (cur->key.op == OP_NOMATCH)
2242                                         goto nomatch;
2243                         }
2244                         break;
2245                 }
2246                 case TK_M_IMPORT_FILE: {
2247                         char import[UTIL_PATH_SIZE];
2248
2249                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], import, sizeof(import));
2250                         if (import_file_into_properties(event->dev, import) != 0)
2251                                 if (cur->key.op != OP_NOMATCH)
2252                                         goto nomatch;
2253                         break;
2254                 }
2255                 case TK_M_IMPORT_PROG: {
2256                         char import[UTIL_PATH_SIZE];
2257
2258                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], import, sizeof(import));
2259                         log_debug("IMPORT '%s' %s:%u\n",
2260                                   import,
2261                                   &rules->buf[rule->rule.filename_off],
2262                                   rule->rule.filename_line);
2263
2264                         if (import_program_into_properties(event, import, sigmask) != 0)
2265                                 if (cur->key.op != OP_NOMATCH)
2266                                         goto nomatch;
2267                         break;
2268                 }
2269                 case TK_M_IMPORT_BUILTIN: {
2270                         char command[UTIL_PATH_SIZE];
2271
2272                         if (udev_builtin_run_once(cur->key.builtin_cmd)) {
2273                                 /* check if we ran already */
2274                                 if (event->builtin_run & (1 << cur->key.builtin_cmd)) {
2275                                         log_debug("IMPORT builtin skip '%s' %s:%u\n",
2276                                                   udev_builtin_name(cur->key.builtin_cmd),
2277                                                   &rules->buf[rule->rule.filename_off],
2278                                                   rule->rule.filename_line);
2279                                         /* return the result from earlier run */
2280                                         if (event->builtin_ret & (1 << cur->key.builtin_cmd))
2281                                         if (cur->key.op != OP_NOMATCH)
2282                                                         goto nomatch;
2283                                         break;
2284                                 }
2285                                 /* mark as ran */
2286                                 event->builtin_run |= (1 << cur->key.builtin_cmd);
2287                         }
2288
2289                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], command, sizeof(command));
2290                         log_debug("IMPORT builtin '%s' %s:%u\n",
2291                                   udev_builtin_name(cur->key.builtin_cmd),
2292                                   &rules->buf[rule->rule.filename_off],
2293                                   rule->rule.filename_line);
2294
2295                         if (udev_builtin_run(event->dev, cur->key.builtin_cmd, command, false) != 0) {
2296                                 /* remember failure */
2297                                 log_debug("IMPORT builtin '%s' returned non-zero\n",
2298                                           udev_builtin_name(cur->key.builtin_cmd));
2299                                 event->builtin_ret |= (1 << cur->key.builtin_cmd);
2300                                 if (cur->key.op != OP_NOMATCH)
2301                                         goto nomatch;
2302                         }
2303                         break;
2304                 }
2305                 case TK_M_IMPORT_DB: {
2306                         const char *key = &rules->buf[cur->key.value_off];
2307                         const char *value;
2308
2309                         value = udev_device_get_property_value(event->dev_db, key);
2310                         if (value != NULL) {
2311                                 struct udev_list_entry *entry;
2312
2313                                 entry = udev_device_add_property(event->dev, key, value);
2314                                 udev_list_entry_set_num(entry, true);
2315                         } else {
2316                                 if (cur->key.op != OP_NOMATCH)
2317                                         goto nomatch;
2318                         }
2319                         break;
2320                 }
2321                 case TK_M_IMPORT_CMDLINE: {
2322                         FILE *f;
2323                         bool imported = false;
2324
2325                         f = fopen("/proc/cmdline", "re");
2326                         if (f != NULL) {
2327                                 char cmdline[4096];
2328
2329                                 if (fgets(cmdline, sizeof(cmdline), f) != NULL) {
2330                                         const char *key = &rules->buf[cur->key.value_off];
2331                                         char *pos;
2332
2333                                         pos = strstr(cmdline, key);
2334                                         if (pos != NULL) {
2335                                                 struct udev_list_entry *entry;
2336
2337                                                 pos += strlen(key);
2338                                                 if (pos[0] == '\0' || isspace(pos[0])) {
2339                                                         /* we import simple flags as 'FLAG=1' */
2340                                                         entry = udev_device_add_property(event->dev, key, "1");
2341                                                         udev_list_entry_set_num(entry, true);
2342                                                         imported = true;
2343                                                 } else if (pos[0] == '=') {
2344                                                         const char *value;
2345
2346                                                         pos++;
2347                                                         value = pos;
2348                                                         while (pos[0] != '\0' && !isspace(pos[0]))
2349                                                                 pos++;
2350                                                         pos[0] = '\0';
2351                                                         entry = udev_device_add_property(event->dev, key, value);
2352                                                         udev_list_entry_set_num(entry, true);
2353                                                         imported = true;
2354                                                 }
2355                                         }
2356                                 }
2357                                 fclose(f);
2358                         }
2359                         if (!imported && cur->key.op != OP_NOMATCH)
2360                                 goto nomatch;
2361                         break;
2362                 }
2363                 case TK_M_IMPORT_PARENT: {
2364                         char import[UTIL_PATH_SIZE];
2365
2366                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], import, sizeof(import));
2367                         if (import_parent_into_properties(event->dev, import) != 0)
2368                                 if (cur->key.op != OP_NOMATCH)
2369                                         goto nomatch;
2370                         break;
2371                 }
2372                 case TK_M_RESULT:
2373                         if (match_key(rules, cur, event->program_result) != 0)
2374                                 goto nomatch;
2375                         break;
2376                 case TK_A_STRING_ESCAPE_NONE:
2377                         esc = ESCAPE_NONE;
2378                         break;
2379                 case TK_A_STRING_ESCAPE_REPLACE:
2380                         esc = ESCAPE_REPLACE;
2381                         break;
2382                 case TK_A_DB_PERSIST:
2383                         udev_device_set_db_persist(event->dev);
2384                         break;
2385                 case TK_A_INOTIFY_WATCH:
2386                         if (event->inotify_watch_final)
2387                                 break;
2388                         if (cur->key.op == OP_ASSIGN_FINAL)
2389                                 event->inotify_watch_final = true;
2390                         event->inotify_watch = cur->key.watch;
2391                         break;
2392                 case TK_A_DEVLINK_PRIO:
2393                         udev_device_set_devlink_priority(event->dev, cur->key.devlink_prio);
2394                         break;
2395                 case TK_A_OWNER: {
2396                         char owner[UTIL_NAME_SIZE];
2397
2398                         if (event->owner_final)
2399                                 break;
2400                         if (cur->key.op == OP_ASSIGN_FINAL)
2401                                 event->owner_final = true;
2402                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], owner, sizeof(owner));
2403                         event->uid = util_lookup_user(event->udev, owner);
2404                         log_debug("OWNER %u %s:%u\n",
2405                                   event->uid,
2406                                   &rules->buf[rule->rule.filename_off],
2407                                   rule->rule.filename_line);
2408                         break;
2409                 }
2410                 case TK_A_GROUP: {
2411                         char group[UTIL_NAME_SIZE];
2412
2413                         if (event->group_final)
2414                                 break;
2415                         if (cur->key.op == OP_ASSIGN_FINAL)
2416                                 event->group_final = true;
2417                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], group, sizeof(group));
2418                         event->gid = util_lookup_group(event->udev, group);
2419                         log_debug("GROUP %u %s:%u\n",
2420                                   event->gid,
2421                                   &rules->buf[rule->rule.filename_off],
2422                                   rule->rule.filename_line);
2423                         break;
2424                 }
2425                 case TK_A_MODE: {
2426                         char mode_str[UTIL_NAME_SIZE];
2427                         mode_t mode;
2428                         char *endptr;
2429
2430                         if (event->mode_final)
2431                                 break;
2432                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], mode_str, sizeof(mode_str));
2433                         mode = strtol(mode_str, &endptr, 8);
2434                         if (endptr[0] != '\0') {
2435                                 log_error("ignoring invalid mode '%s'\n", mode_str);
2436                                 break;
2437                         }
2438                         if (cur->key.op == OP_ASSIGN_FINAL)
2439                                 event->mode_final = true;
2440                         event->mode_set = true;
2441                         event->mode = mode;
2442                         log_debug("MODE %#o %s:%u\n",
2443                                   event->mode,
2444                                   &rules->buf[rule->rule.filename_off],
2445                                   rule->rule.filename_line);
2446                         break;
2447                 }
2448                 case TK_A_OWNER_ID:
2449                         if (event->owner_final)
2450                                 break;
2451                         if (cur->key.op == OP_ASSIGN_FINAL)
2452                                 event->owner_final = true;
2453                         event->uid = cur->key.uid;
2454                         log_debug("OWNER %u %s:%u\n",
2455                                   event->uid,
2456                                   &rules->buf[rule->rule.filename_off],
2457                                   rule->rule.filename_line);
2458                         break;
2459                 case TK_A_GROUP_ID:
2460                         if (event->group_final)
2461                                 break;
2462                         if (cur->key.op == OP_ASSIGN_FINAL)
2463                                 event->group_final = true;
2464                         event->gid = cur->key.gid;
2465                         log_debug("GROUP %u %s:%u\n",
2466                                   event->gid,
2467                                   &rules->buf[rule->rule.filename_off],
2468                                   rule->rule.filename_line);
2469                         break;
2470                 case TK_A_MODE_ID:
2471                         if (event->mode_final)
2472                                 break;
2473                         if (cur->key.op == OP_ASSIGN_FINAL)
2474                                 event->mode_final = true;
2475                         event->mode_set = true;
2476                         event->mode = cur->key.mode;
2477                         log_debug("MODE %#o %s:%u\n",
2478                                   event->mode,
2479                                   &rules->buf[rule->rule.filename_off],
2480                                   rule->rule.filename_line);
2481                         break;
2482                 case TK_A_ENV: {
2483                         const char *name = &rules->buf[cur->key.attr_off];
2484                         char *value = &rules->buf[cur->key.value_off];
2485
2486                         if (value[0] != '\0') {
2487                                 char temp_value[UTIL_NAME_SIZE];
2488                                 struct udev_list_entry *entry;
2489
2490                                 udev_event_apply_format(event, value, temp_value, sizeof(temp_value));
2491                                 entry = udev_device_add_property(event->dev, name, temp_value);
2492                                 /* store in db, skip private keys */
2493                                 if (name[0] != '.')
2494                                         udev_list_entry_set_num(entry, true);
2495                         } else {
2496                                 udev_device_add_property(event->dev, name, NULL);
2497                         }
2498                         break;
2499                 }
2500                 case TK_A_TAG: {
2501                         char tag[UTIL_PATH_SIZE];
2502                         const char *p;
2503
2504                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], tag, sizeof(tag));
2505                         if (cur->key.op == OP_ASSIGN || cur->key.op == OP_ASSIGN_FINAL)
2506                                 udev_device_cleanup_tags_list(event->dev);
2507                         for (p = tag; *p != '\0'; p++) {
2508                                 if ((*p >= 'a' && *p <= 'z') ||
2509                                     (*p >= 'A' && *p <= 'Z') ||
2510                                     (*p >= '0' && *p <= '9') ||
2511                                     *p == '-' || *p == '_')
2512                                         continue;
2513                                 log_error("ignoring invalid tag name '%s'\n", tag);
2514                                 break;
2515                         }
2516                         udev_device_add_tag(event->dev, tag);
2517                         break;
2518                 }
2519                 case TK_A_NAME: {
2520                         const char *name  = &rules->buf[cur->key.value_off];
2521
2522                         char name_str[UTIL_PATH_SIZE];
2523                         int count;
2524
2525                         if (event->name_final)
2526                                 break;
2527                         if (cur->key.op == OP_ASSIGN_FINAL)
2528                                 event->name_final = true;
2529                         udev_event_apply_format(event, name, name_str, sizeof(name_str));
2530                         if (esc == ESCAPE_UNSET || esc == ESCAPE_REPLACE) {
2531                                 count = util_replace_chars(name_str, "/");
2532                                 if (count > 0)
2533                                         log_debug("%i character(s) replaced\n", count);
2534                         }
2535                         if (major(udev_device_get_devnum(event->dev)) &&
2536                             (!streq(name_str, udev_device_get_devnode(event->dev) + strlen("/dev/")))) {
2537                                 log_error("NAME=\"%s\" ignored, kernel device nodes "
2538                                     "can not be renamed; please fix it in %s:%u\n", name,
2539                                     &rules->buf[rule->rule.filename_off], rule->rule.filename_line);
2540                                 break;
2541                         }
2542                         free(event->name);
2543                         event->name = strdup(name_str);
2544                         log_debug("NAME '%s' %s:%u\n",
2545                                   event->name,
2546                                   &rules->buf[rule->rule.filename_off],
2547                                   rule->rule.filename_line);
2548                         break;
2549                 }
2550                 case TK_A_DEVLINK: {
2551                         char temp[UTIL_PATH_SIZE];
2552                         char filename[UTIL_PATH_SIZE];
2553                         char *pos, *next;
2554                         int count = 0;
2555
2556                         if (event->devlink_final)
2557                                 break;
2558                         if (major(udev_device_get_devnum(event->dev)) == 0)
2559                                 break;
2560                         if (cur->key.op == OP_ASSIGN_FINAL)
2561                                 event->devlink_final = true;
2562                         if (cur->key.op == OP_ASSIGN || cur->key.op == OP_ASSIGN_FINAL)
2563                                 udev_device_cleanup_devlinks_list(event->dev);
2564
2565                         /* allow  multiple symlinks separated by spaces */
2566                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], temp, sizeof(temp));
2567                         if (esc == ESCAPE_UNSET)
2568                                 count = util_replace_chars(temp, "/ ");
2569                         else if (esc == ESCAPE_REPLACE)
2570                                 count = util_replace_chars(temp, "/");
2571                         if (count > 0)
2572                                 log_debug("%i character(s) replaced\n" , count);
2573                         pos = temp;
2574                         while (isspace(pos[0]))
2575                                 pos++;
2576                         next = strchr(pos, ' ');
2577                         while (next != NULL) {
2578                                 next[0] = '\0';
2579                                 log_debug("LINK '%s' %s:%u\n", pos,
2580                                           &rules->buf[rule->rule.filename_off], rule->rule.filename_line);
2581                                 util_strscpyl(filename, sizeof(filename), "/dev/", pos, NULL);
2582                                 udev_device_add_devlink(event->dev, filename, cur->key.devlink_unique);
2583                                 while (isspace(next[1]))
2584                                         next++;
2585                                 pos = &next[1];
2586                                 next = strchr(pos, ' ');
2587                         }
2588                         if (pos[0] != '\0') {
2589                                 log_debug("LINK '%s' %s:%u\n", pos,
2590                                           &rules->buf[rule->rule.filename_off], rule->rule.filename_line);
2591                                 util_strscpyl(filename, sizeof(filename), "/dev/", pos, NULL);
2592                                 udev_device_add_devlink(event->dev, filename, cur->key.devlink_unique);
2593                         }
2594                         break;
2595                 }
2596                 case TK_A_ATTR: {
2597                         const char *key_name = &rules->buf[cur->key.attr_off];
2598                         char attr[UTIL_PATH_SIZE];
2599                         char value[UTIL_NAME_SIZE];
2600                         FILE *f;
2601
2602                         if (util_resolve_subsys_kernel(event->udev, key_name, attr, sizeof(attr), 0) != 0)
2603                                 util_strscpyl(attr, sizeof(attr), udev_device_get_syspath(event->dev), "/", key_name, NULL);
2604                         attr_subst_subdir(attr, sizeof(attr));
2605
2606                         udev_event_apply_format(event, &rules->buf[cur->key.value_off], value, sizeof(value));
2607                         log_debug("ATTR '%s' writing '%s' %s:%u\n", attr, value,
2608                                   &rules->buf[rule->rule.filename_off],
2609                                   rule->rule.filename_line);
2610                         f = fopen(attr, "we");
2611                         if (f != NULL) {
2612                                 if (fprintf(f, "%s", value) <= 0)
2613                                         log_error("error writing ATTR{%s}: %m\n", attr);
2614                                 fclose(f);
2615                         } else {
2616                                 log_error("error opening ATTR{%s} for writing: %m\n", attr);
2617                         }
2618                         break;
2619                 }
2620                 case TK_A_RUN_BUILTIN:
2621                 case TK_A_RUN_PROGRAM: {
2622                         struct udev_list_entry *entry;
2623
2624                         if (cur->key.op == OP_ASSIGN || cur->key.op == OP_ASSIGN_FINAL)
2625                                 udev_list_cleanup(&event->run_list);
2626                         log_debug("RUN '%s' %s:%u\n",
2627                                   &rules->buf[cur->key.value_off],
2628                                   &rules->buf[rule->rule.filename_off],
2629                                   rule->rule.filename_line);
2630                         entry = udev_list_entry_add(&event->run_list, &rules->buf[cur->key.value_off], NULL);
2631                         udev_list_entry_set_num(entry, cur->key.builtin_cmd);
2632                         break;
2633                 }
2634                 case TK_A_GOTO:
2635                         if (cur->key.rule_goto == 0)
2636                                 break;
2637                         cur = &rules->tokens[cur->key.rule_goto];
2638                         continue;
2639                 case TK_END:
2640                         return 0;
2641
2642                 case TK_M_PARENTS_MIN:
2643                 case TK_M_PARENTS_MAX:
2644                 case TK_M_MAX:
2645                 case TK_UNSET:
2646                         log_error("wrong type %u\n", cur->type);
2647                         goto nomatch;
2648                 }
2649
2650                 cur++;
2651                 continue;
2652         nomatch:
2653                 /* fast-forward to next rule */
2654                 cur = rule + rule->rule.token_count;
2655         }
2656 }
2657
2658 void udev_rules_apply_static_dev_perms(struct udev_rules *rules)
2659 {
2660         struct token *cur;
2661         struct token *rule;
2662         uid_t uid = 0;
2663         gid_t gid = 0;
2664         mode_t mode = 0;
2665
2666         if (rules->tokens == NULL)
2667                 return;
2668
2669         cur = &rules->tokens[0];
2670         rule = cur;
2671         for (;;) {
2672                 switch (cur->type) {
2673                 case TK_RULE:
2674                         /* current rule */
2675                         rule = cur;
2676
2677                         /* skip rules without a static_node tag */
2678                         if (!rule->rule.has_static_node)
2679                                 goto next;
2680
2681                         uid = 0;
2682                         gid = 0;
2683                         mode = 0;
2684                         break;
2685                 case TK_A_OWNER_ID:
2686                         uid = cur->key.uid;
2687                         break;
2688                 case TK_A_GROUP_ID:
2689                         gid = cur->key.gid;
2690                         break;
2691                 case TK_A_MODE_ID:
2692                         mode = cur->key.mode;
2693                         break;
2694                 case TK_A_STATIC_NODE: {
2695                         char filename[UTIL_PATH_SIZE];
2696                         struct stat stats;
2697
2698                         /* we assure, that the permissions tokens are sorted before the static token */
2699                         if (mode == 0 && uid == 0 && gid == 0)
2700                                 goto next;
2701                         util_strscpyl(filename, sizeof(filename), "/dev/",
2702                                       &rules->buf[cur->key.value_off], NULL);
2703                         if (stat(filename, &stats) != 0)
2704                                 goto next;
2705                         if (!S_ISBLK(stats.st_mode) && !S_ISCHR(stats.st_mode))
2706                                 goto next;
2707                         if (mode == 0) {
2708                                 if (gid > 0)
2709                                         mode = 0660;
2710                                 else
2711                                         mode = 0600;
2712                         }
2713                         if (mode != (stats.st_mode & 01777)) {
2714                                 chmod(filename, mode);
2715                                 log_debug("chmod '%s' %#o\n", filename, mode);
2716                         }
2717
2718                         if ((uid != 0 && uid != stats.st_uid) || (gid != 0 && gid != stats.st_gid)) {
2719                                 chown(filename, uid, gid);
2720                                 log_debug("chown '%s' %u %u\n", filename, uid, gid);
2721                         }
2722
2723                         utimensat(AT_FDCWD, filename, NULL, 0);
2724                         break;
2725                 }
2726                 case TK_END:
2727                         return;
2728                 }
2729
2730                 cur++;
2731                 continue;
2732 next:
2733                 /* fast-forward to next rule */
2734                 cur = rule + rule->rule.token_count;
2735                 continue;
2736         }
2737 }