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