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