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