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