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