chiark / gitweb /
9d9529a0fe38c316ba9d9eccd8ca0fba1a09ee79
[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
555         /* find key */
556         key = line;
557         while (isspace(key[0]))
558                 key++;
559
560         /* comment or empty line */
561         if (key[0] == '#' || key[0] == '\0')
562                 return -1;
563
564         /* split key/value */
565         val = strchr(key, '=');
566         if (val == NULL)
567                 return -1;
568         val[0] = '\0';
569         val++;
570
571         /* find value */
572         while (isspace(val[0]))
573                 val++;
574
575         /* terminate key */
576         len = strlen(key);
577         if (len == 0)
578                 return -1;
579         while (isspace(key[len-1]))
580                 len--;
581         key[len] = '\0';
582
583         /* terminate value */
584         len = strlen(val);
585         if (len == 0)
586                 return -1;
587         while (isspace(val[len-1]))
588                 len--;
589         val[len] = '\0';
590
591         if (len == 0)
592                 return -1;
593
594         /* unquote */
595         if (val[0] == '"' || val[0] == '\'') {
596                 if (val[len-1] != val[0]) {
597                         log_debug("inconsistent quoting: '%s', skip\n", line);
598                         return -1;
599                 }
600                 val[len-1] = '\0';
601                 val++;
602         }
603
604         /* handle device, renamed by external tool, returning new path */
605         if (streq(key, "DEVPATH")) {
606                 char syspath[UTIL_PATH_SIZE];
607
608                 log_debug("updating devpath from '%s' to '%s'\n",
609                           udev_device_get_devpath(dev), val);
610                 strscpyl(syspath, sizeof(syspath), "/sys", val, NULL);
611                 udev_device_set_syspath(dev, syspath);
612         } else {
613                 struct udev_list_entry *entry;
614
615                 entry = udev_device_add_property(dev, key, val);
616                 /* store in db, skip private keys */
617                 if (key[0] != '.')
618                         udev_list_entry_set_num(entry, true);
619         }
620         return 0;
621 }
622
623 static int import_file_into_properties(struct udev_device *dev, const char *filename)
624 {
625         FILE *f;
626         char line[UTIL_LINE_SIZE];
627
628         f = fopen(filename, "re");
629         if (f == NULL)
630                 return -1;
631         while (fgets(line, sizeof(line), f) != NULL)
632                 import_property_from_string(dev, line);
633         fclose(f);
634         return 0;
635 }
636
637 static int import_program_into_properties(struct udev_event *event, const char *program, const sigset_t *sigmask)
638 {
639         struct udev_device *dev = event->dev;
640         char **envp;
641         char result[UTIL_LINE_SIZE];
642         char *line;
643         int err;
644
645         envp = udev_device_get_properties_envp(dev);
646         err = udev_event_spawn(event, program, envp, sigmask, result, sizeof(result));
647         if (err < 0)
648                 return err;
649
650         line = result;
651         while (line != NULL) {
652                 char *pos;
653
654                 pos = strchr(line, '\n');
655                 if (pos != NULL) {
656                         pos[0] = '\0';
657                         pos = &pos[1];
658                 }
659                 import_property_from_string(dev, line);
660                 line = pos;
661         }
662         return 0;
663 }
664
665 static int import_parent_into_properties(struct udev_device *dev, const char *filter)
666 {
667         struct udev_device *dev_parent;
668         struct udev_list_entry *list_entry;
669
670         dev_parent = udev_device_get_parent(dev);
671         if (dev_parent == NULL)
672                 return -1;
673
674         udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(dev_parent)) {
675                 const char *key = udev_list_entry_get_name(list_entry);
676                 const char *val = udev_list_entry_get_value(list_entry);
677
678                 if (fnmatch(filter, key, 0) == 0) {
679                         struct udev_list_entry *entry;
680
681                         entry = udev_device_add_property(dev, key, val);
682                         /* store in db, skip private keys */
683                         if (key[0] != '.')
684                                 udev_list_entry_set_num(entry, true);
685                 }
686         }
687         return 0;
688 }
689
690 #define WAIT_LOOP_PER_SECOND                50
691 static int wait_for_file(struct udev_device *dev, const char *file, int timeout)
692 {
693         char filepath[UTIL_PATH_SIZE];
694         char devicepath[UTIL_PATH_SIZE];
695         struct stat stats;
696         int loop = timeout * WAIT_LOOP_PER_SECOND;
697
698         /* a relative path is a device attribute */
699         devicepath[0] = '\0';
700         if (file[0] != '/') {
701                 strscpyl(devicepath, sizeof(devicepath), udev_device_get_syspath(dev), NULL);
702                 strscpyl(filepath, sizeof(filepath), devicepath, "/", file, NULL);
703                 file = filepath;
704         }
705
706         while (--loop) {
707                 const struct timespec duration = { 0, 1000 * 1000 * 1000 / WAIT_LOOP_PER_SECOND };
708
709                 /* lookup file */
710                 if (stat(file, &stats) == 0) {
711                         log_debug("file '%s' appeared after %i loops\n", file, (timeout * WAIT_LOOP_PER_SECOND) - loop-1);
712                         return 0;
713                 }
714                 /* make sure, the device did not disappear in the meantime */
715                 if (devicepath[0] != '\0' && stat(devicepath, &stats) != 0) {
716                         log_debug("device disappeared while waiting for '%s'\n", file);
717                         return -2;
718                 }
719                 log_debug("wait for '%s' for %i mseconds\n", file, 1000 / WAIT_LOOP_PER_SECOND);
720                 nanosleep(&duration, NULL);
721         }
722         log_debug("waiting for '%s' failed\n", file);
723         return -1;
724 }
725
726 static int attr_subst_subdir(char *attr, size_t len)
727 {
728         bool found = false;
729
730         if (strstr(attr, "/*/")) {
731                 char *pos;
732                 char dirname[UTIL_PATH_SIZE];
733                 const char *tail;
734                 DIR *dir;
735
736                 strscpy(dirname, sizeof(dirname), attr);
737                 pos = strstr(dirname, "/*/");
738                 if (pos == NULL)
739                         return -1;
740                 pos[0] = '\0';
741                 tail = &pos[2];
742                 dir = opendir(dirname);
743                 if (dir != NULL) {
744                         struct dirent *dent;
745
746                         for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
747                                 struct stat stats;
748
749                                 if (dent->d_name[0] == '.')
750                                         continue;
751                                 strscpyl(attr, len, dirname, "/", dent->d_name, tail, NULL);
752                                 if (stat(attr, &stats) == 0) {
753                                         found = true;
754                                         break;
755                                 }
756                         }
757                         closedir(dir);
758                 }
759         }
760
761         return found;
762 }
763
764 static int get_key(struct udev *udev, char **line, char **key, enum operation_type *op, char **value)
765 {
766         char *linepos;
767         char *temp;
768
769         linepos = *line;
770         if (linepos == NULL || linepos[0] == '\0')
771                 return -1;
772
773         /* skip whitespace */
774         while (isspace(linepos[0]) || linepos[0] == ',')
775                 linepos++;
776
777         /* get the key */
778         if (linepos[0] == '\0')
779                 return -1;
780         *key = linepos;
781
782         for (;;) {
783                 linepos++;
784                 if (linepos[0] == '\0')
785                         return -1;
786                 if (isspace(linepos[0]))
787                         break;
788                 if (linepos[0] == '=')
789                         break;
790                 if ((linepos[0] == '+') || (linepos[0] == '!') || (linepos[0] == ':'))
791                         if (linepos[1] == '=')
792                                 break;
793         }
794
795         /* remember end of key */
796         temp = linepos;
797
798         /* skip whitespace after key */
799         while (isspace(linepos[0]))
800                 linepos++;
801         if (linepos[0] == '\0')
802                 return -1;
803
804         /* get operation type */
805         if (linepos[0] == '=' && linepos[1] == '=') {
806                 *op = OP_MATCH;
807                 linepos += 2;
808         } else if (linepos[0] == '!' && linepos[1] == '=') {
809                 *op = OP_NOMATCH;
810                 linepos += 2;
811         } else if (linepos[0] == '+' && linepos[1] == '=') {
812                 *op = OP_ADD;
813                 linepos += 2;
814         } else if (linepos[0] == '=') {
815                 *op = OP_ASSIGN;
816                 linepos++;
817         } else if (linepos[0] == ':' && linepos[1] == '=') {
818                 *op = OP_ASSIGN_FINAL;
819                 linepos += 2;
820         } else
821                 return -1;
822
823         /* terminate key */
824         temp[0] = '\0';
825
826         /* skip whitespace after operator */
827         while (isspace(linepos[0]))
828                 linepos++;
829         if (linepos[0] == '\0')
830                 return -1;
831
832         /* get the value */
833         if (linepos[0] == '"')
834                 linepos++;
835         else
836                 return -1;
837         *value = linepos;
838
839         /* terminate */
840         temp = strchr(linepos, '"');
841         if (!temp)
842                 return -1;
843         temp[0] = '\0';
844         temp++;
845
846         /* move line to next key */
847         *line = temp;
848         return 0;
849 }
850
851 /* extract possible KEY{attr} */
852 static const char *get_key_attribute(struct udev *udev, char *str)
853 {
854         char *pos;
855         char *attr;
856
857         attr = strchr(str, '{');
858         if (attr != NULL) {
859                 attr++;
860                 pos = strchr(attr, '}');
861                 if (pos == NULL) {
862                         log_error("missing closing brace for format\n");
863                         return NULL;
864                 }
865                 pos[0] = '\0';
866                 return attr;
867         }
868         return NULL;
869 }
870
871 static int rule_add_key(struct rule_tmp *rule_tmp, enum token_type type,
872                         enum operation_type op,
873                         const char *value, const void *data)
874 {
875         struct token *token = &rule_tmp->token[rule_tmp->token_cur];
876         const char *attr = NULL;
877
878         memset(token, 0x00, sizeof(struct token));
879
880         switch (type) {
881         case TK_M_ACTION:
882         case TK_M_DEVPATH:
883         case TK_M_KERNEL:
884         case TK_M_SUBSYSTEM:
885         case TK_M_DRIVER:
886         case TK_M_WAITFOR:
887         case TK_M_DEVLINK:
888         case TK_M_NAME:
889         case TK_M_KERNELS:
890         case TK_M_SUBSYSTEMS:
891         case TK_M_DRIVERS:
892         case TK_M_TAGS:
893         case TK_M_PROGRAM:
894         case TK_M_IMPORT_FILE:
895         case TK_M_IMPORT_PROG:
896         case TK_M_IMPORT_DB:
897         case TK_M_IMPORT_CMDLINE:
898         case TK_M_IMPORT_PARENT:
899         case TK_M_RESULT:
900         case TK_A_OWNER:
901         case TK_A_GROUP:
902         case TK_A_MODE:
903         case TK_A_DEVLINK:
904         case TK_A_NAME:
905         case TK_A_GOTO:
906         case TK_M_TAG:
907         case TK_A_TAG:
908                 token->key.value_off = rules_add_string(rule_tmp->rules, value);
909                 break;
910         case TK_M_IMPORT_BUILTIN:
911                 token->key.value_off = rules_add_string(rule_tmp->rules, value);
912                 token->key.builtin_cmd = *(enum udev_builtin_cmd *)data;
913                 break;
914         case TK_M_ENV:
915         case TK_M_ATTR:
916         case TK_M_ATTRS:
917         case TK_A_ATTR:
918         case TK_A_ENV:
919         case TK_A_SECLABEL:
920                 attr = data;
921                 token->key.value_off = rules_add_string(rule_tmp->rules, value);
922                 token->key.attr_off = rules_add_string(rule_tmp->rules, attr);
923                 break;
924         case TK_M_TEST:
925                 token->key.value_off = rules_add_string(rule_tmp->rules, value);
926                 if (data != NULL)
927                         token->key.mode = *(mode_t *)data;
928                 break;
929         case TK_A_STRING_ESCAPE_NONE:
930         case TK_A_STRING_ESCAPE_REPLACE:
931         case TK_A_DB_PERSIST:
932                 break;
933         case TK_A_RUN_BUILTIN:
934         case TK_A_RUN_PROGRAM:
935                 token->key.builtin_cmd = *(enum udev_builtin_cmd *)data;
936                 token->key.value_off = rules_add_string(rule_tmp->rules, value);
937                 break;
938         case TK_A_INOTIFY_WATCH:
939         case TK_A_DEVLINK_PRIO:
940                 token->key.devlink_prio = *(int *)data;
941                 break;
942         case TK_A_OWNER_ID:
943                 token->key.uid = *(uid_t *)data;
944                 break;
945         case TK_A_GROUP_ID:
946                 token->key.gid = *(gid_t *)data;
947                 break;
948         case TK_A_MODE_ID:
949                 token->key.mode = *(mode_t *)data;
950                 break;
951         case TK_A_STATIC_NODE:
952                 token->key.value_off = rules_add_string(rule_tmp->rules, value);
953                 break;
954         case TK_M_EVENT_TIMEOUT:
955                 token->key.event_timeout = *(int *)data;
956                 break;
957         case TK_RULE:
958         case TK_M_PARENTS_MIN:
959         case TK_M_PARENTS_MAX:
960         case TK_M_MAX:
961         case TK_END:
962         case TK_UNSET:
963                 log_error("wrong type %u\n", type);
964                 return -1;
965         }
966
967         if (value != NULL && type < TK_M_MAX) {
968                 /* check if we need to split or call fnmatch() while matching rules */
969                 enum string_glob_type glob;
970                 int has_split;
971                 int has_glob;
972
973                 has_split = (strchr(value, '|') != NULL);
974                 has_glob = (strchr(value, '*') != NULL || strchr(value, '?') != NULL || strchr(value, '[') != NULL);
975                 if (has_split && has_glob) {
976                         glob = GL_SPLIT_GLOB;
977                 } else if (has_split) {
978                         glob = GL_SPLIT;
979                 } else if (has_glob) {
980                         if (streq(value, "?*"))
981                                 glob = GL_SOMETHING;
982                         else
983                                 glob = GL_GLOB;
984                 } else {
985                         glob = GL_PLAIN;
986                 }
987                 token->key.glob = glob;
988         }
989
990         if (value != NULL && type > TK_M_MAX) {
991                 /* check if assigned value has substitution chars */
992                 if (value[0] == '[')
993                         token->key.subst = SB_SUBSYS;
994                 else if (strchr(value, '%') != NULL || strchr(value, '$') != NULL)
995                         token->key.subst = SB_FORMAT;
996                 else
997                         token->key.subst = SB_NONE;
998         }
999
1000         if (attr != NULL) {
1001                 /* check if property/attribut name has substitution chars */
1002                 if (attr[0] == '[')
1003                         token->key.attrsubst = SB_SUBSYS;
1004                 else if (strchr(attr, '%') != NULL || strchr(attr, '$') != NULL)
1005                         token->key.attrsubst = SB_FORMAT;
1006                 else
1007                         token->key.attrsubst = SB_NONE;
1008         }
1009
1010         token->key.type = type;
1011         token->key.op = op;
1012         rule_tmp->token_cur++;
1013         if (rule_tmp->token_cur >= ELEMENTSOF(rule_tmp->token)) {
1014                 log_error("temporary rule array too small\n");
1015                 return -1;
1016         }
1017         return 0;
1018 }
1019
1020 static int sort_token(struct udev_rules *rules, struct rule_tmp *rule_tmp)
1021 {
1022         unsigned int i;
1023         unsigned int start = 0;
1024         unsigned int end = rule_tmp->token_cur;
1025
1026         for (i = 0; i < rule_tmp->token_cur; i++) {
1027                 enum token_type next_val = TK_UNSET;
1028                 unsigned int next_idx = 0;
1029                 unsigned int j;
1030
1031                 /* find smallest value */
1032                 for (j = start; j < end; j++) {
1033                         if (rule_tmp->token[j].type == TK_UNSET)
1034                                 continue;
1035                         if (next_val == TK_UNSET || rule_tmp->token[j].type < next_val) {
1036                                 next_val = rule_tmp->token[j].type;
1037                                 next_idx = j;
1038                         }
1039                 }
1040
1041                 /* add token and mark done */
1042                 if (add_token(rules, &rule_tmp->token[next_idx]) != 0)
1043                         return -1;
1044                 rule_tmp->token[next_idx].type = TK_UNSET;
1045
1046                 /* shrink range */
1047                 if (next_idx == start)
1048                         start++;
1049                 if (next_idx+1 == end)
1050                         end--;
1051         }
1052         return 0;
1053 }
1054
1055 static int add_rule(struct udev_rules *rules, char *line,
1056                     const char *filename, unsigned int filename_off, unsigned int lineno)
1057 {
1058         char *linepos;
1059         const char *attr;
1060         struct rule_tmp rule_tmp;
1061
1062         memset(&rule_tmp, 0x00, sizeof(struct rule_tmp));
1063         rule_tmp.rules = rules;
1064         rule_tmp.rule.type = TK_RULE;
1065         /* the offset in the rule is limited to unsigned short */
1066         if (filename_off < USHRT_MAX)
1067                 rule_tmp.rule.rule.filename_off = filename_off;
1068         rule_tmp.rule.rule.filename_line = lineno;
1069
1070         linepos = line;
1071         for (;;) {
1072                 char *key;
1073                 char *value;
1074                 enum operation_type op;
1075
1076                 if (get_key(rules->udev, &linepos, &key, &op, &value) != 0) {
1077                         /* Avoid erroring on trailing whitespace. This is probably rare
1078                          * so save the work for the error case instead of always trying
1079                          * to strip the trailing whitespace with strstrip(). */
1080                         while (isblank(*linepos))
1081                                 linepos++;
1082
1083                         /* If we aren't at the end of the line, this is a parsing error.
1084                          * Make a best effort to describe where the problem is. */
1085                         if (*linepos != '\n') {
1086                                 char buf[2] = {linepos[1]};
1087                                 _cleanup_free_ char *tmp;
1088
1089                                 tmp = cescape(buf);
1090                                 log_error("invalid key/value pair in file %s on line %u,"
1091                                           "starting at character %tu ('%s')\n",
1092                                           filename, lineno, linepos - line + 1, tmp);
1093                                 if (linepos[1] == '#')
1094                                         log_info("hint: comments can only start at beginning of line");
1095                         }
1096                         break;
1097                 }
1098
1099                 if (streq(key, "ACTION")) {
1100                         if (op > OP_MATCH_MAX) {
1101                                 log_error("invalid ACTION operation\n");
1102                                 goto invalid;
1103                         }
1104                         rule_add_key(&rule_tmp, TK_M_ACTION, op, value, NULL);
1105                         continue;
1106                 }
1107
1108                 if (streq(key, "DEVPATH")) {
1109                         if (op > OP_MATCH_MAX) {
1110                                 log_error("invalid DEVPATH operation\n");
1111                                 goto invalid;
1112                         }
1113                         rule_add_key(&rule_tmp, TK_M_DEVPATH, op, value, NULL);
1114                         continue;
1115                 }
1116
1117                 if (streq(key, "KERNEL")) {
1118                         if (op > OP_MATCH_MAX) {
1119                                 log_error("invalid KERNEL operation\n");
1120                                 goto invalid;
1121                         }
1122                         rule_add_key(&rule_tmp, TK_M_KERNEL, op, value, NULL);
1123                         continue;
1124                 }
1125
1126                 if (streq(key, "SUBSYSTEM")) {
1127                         if (op > OP_MATCH_MAX) {
1128                                 log_error("invalid SUBSYSTEM operation\n");
1129                                 goto invalid;
1130                         }
1131                         /* bus, class, subsystem events should all be the same */
1132                         if (streq(value, "subsystem") ||
1133                             streq(value, "bus") ||
1134                             streq(value, "class")) {
1135                                 if (streq(value, "bus") || streq(value, "class"))
1136                                         log_error("'%s' must be specified as 'subsystem' \n"
1137                                             "please fix it in %s:%u", value, filename, lineno);
1138                                 rule_add_key(&rule_tmp, TK_M_SUBSYSTEM, op, "subsystem|class|bus", NULL);
1139                         } else
1140                                 rule_add_key(&rule_tmp, TK_M_SUBSYSTEM, op, value, NULL);
1141                         continue;
1142                 }
1143
1144                 if (streq(key, "DRIVER")) {
1145                         if (op > OP_MATCH_MAX) {
1146                                 log_error("invalid DRIVER operation\n");
1147                                 goto invalid;
1148                         }
1149                         rule_add_key(&rule_tmp, TK_M_DRIVER, op, value, NULL);
1150                         continue;
1151                 }
1152
1153                 if (startswith(key, "ATTR{")) {
1154                         attr = get_key_attribute(rules->udev, key + sizeof("ATTR")-1);
1155                         if (attr == NULL) {
1156                                 log_error("error parsing ATTR attribute\n");
1157                                 goto invalid;
1158                         }
1159                         if (op < OP_MATCH_MAX) {
1160                                 rule_add_key(&rule_tmp, TK_M_ATTR, op, value, attr);
1161                         } else {
1162                                 rule_add_key(&rule_tmp, TK_A_ATTR, op, value, attr);
1163                         }
1164                         continue;
1165                 }
1166
1167                 if (startswith(key, "SECLABEL{")) {
1168                         attr = get_key_attribute(rules->udev, key + sizeof("SECLABEL")-1);
1169                         if (!attr) {
1170                                 log_error("error parsing SECLABEL attribute\n");
1171                                 goto invalid;
1172                         }
1173
1174                         rule_add_key(&rule_tmp, TK_A_SECLABEL, op, value, attr);
1175                         continue;
1176                 }
1177
1178                 if (streq(key, "KERNELS")) {
1179                         if (op > OP_MATCH_MAX) {
1180                                 log_error("invalid KERNELS operation\n");
1181                                 goto invalid;
1182                         }
1183                         rule_add_key(&rule_tmp, TK_M_KERNELS, op, value, NULL);
1184                         continue;
1185                 }
1186
1187                 if (streq(key, "SUBSYSTEMS")) {
1188                         if (op > OP_MATCH_MAX) {
1189                                 log_error("invalid SUBSYSTEMS operation\n");
1190                                 goto invalid;
1191                         }
1192                         rule_add_key(&rule_tmp, TK_M_SUBSYSTEMS, op, value, NULL);
1193                         continue;
1194                 }
1195
1196                 if (streq(key, "DRIVERS")) {
1197                         if (op > OP_MATCH_MAX) {
1198                                 log_error("invalid DRIVERS operation\n");
1199                                 goto invalid;
1200                         }
1201                         rule_add_key(&rule_tmp, TK_M_DRIVERS, op, value, NULL);
1202                         continue;
1203                 }
1204
1205                 if (startswith(key, "ATTRS{")) {
1206                         if (op > OP_MATCH_MAX) {
1207                                 log_error("invalid ATTRS operation\n");
1208                                 goto invalid;
1209                         }
1210                         attr = get_key_attribute(rules->udev, key + sizeof("ATTRS")-1);
1211                         if (attr == NULL) {
1212                                 log_error("error parsing ATTRS attribute\n");
1213                                 goto invalid;
1214                         }
1215                         if (startswith(attr, "device/"))
1216                                 log_error("the 'device' link may not be available in a future kernel, "
1217                                     "please fix it in %s:%u", filename, lineno);
1218                         else if (strstr(attr, "../") != NULL)
1219                                 log_error("do not reference parent sysfs directories directly, "
1220                                     "it may break with a future kernel, please fix it in %s:%u", filename, lineno);
1221                         rule_add_key(&rule_tmp, TK_M_ATTRS, op, value, attr);
1222                         continue;
1223                 }
1224
1225                 if (streq(key, "TAGS")) {
1226                         if (op > OP_MATCH_MAX) {
1227                                 log_error("invalid TAGS operation\n");
1228                                 goto invalid;
1229                         }
1230                         rule_add_key(&rule_tmp, TK_M_TAGS, op, value, NULL);
1231                         continue;
1232                 }
1233
1234                 if (startswith(key, "ENV{")) {
1235                         attr = get_key_attribute(rules->udev, key + sizeof("ENV")-1);
1236                         if (attr == NULL) {
1237                                 log_error("error parsing ENV attribute\n");
1238                                 goto invalid;
1239                         }
1240                         if (op < OP_MATCH_MAX) {
1241                                 if (rule_add_key(&rule_tmp, TK_M_ENV, op, value, attr) != 0)
1242                                         goto invalid;
1243                         } else {
1244                                 static const char *blacklist[] = {
1245                                         "ACTION",
1246                                         "SUBSYSTEM",
1247                                         "DEVTYPE",
1248                                         "MAJOR",
1249                                         "MINOR",
1250                                         "DRIVER",
1251                                         "IFINDEX",
1252                                         "DEVNAME",
1253                                         "DEVLINKS",
1254                                         "DEVPATH",
1255                                         "TAGS",
1256                                 };
1257                                 unsigned int i;
1258
1259                                 for (i = 0; i < ELEMENTSOF(blacklist); i++) {
1260                                         if (!streq(attr, blacklist[i]))
1261                                                 continue;
1262                                         log_error("invalid ENV attribute, '%s' can not be set %s:%u\n", attr, filename, lineno);
1263                                         goto invalid;
1264                                 }
1265                                 if (rule_add_key(&rule_tmp, TK_A_ENV, op, value, attr) != 0)
1266                                         goto invalid;
1267                         }
1268                         continue;
1269                 }
1270
1271                 if (streq(key, "TAG")) {
1272                         if (op < OP_MATCH_MAX)
1273                                 rule_add_key(&rule_tmp, TK_M_TAG, op, value, NULL);
1274                         else
1275                                 rule_add_key(&rule_tmp, TK_A_TAG, op, value, NULL);
1276                         continue;
1277                 }
1278
1279                 if (streq(key, "PROGRAM")) {
1280                         rule_add_key(&rule_tmp, TK_M_PROGRAM, op, value, NULL);
1281                         continue;
1282                 }
1283
1284                 if (streq(key, "RESULT")) {
1285                         if (op > OP_MATCH_MAX) {
1286                                 log_error("invalid RESULT operation\n");
1287                                 goto invalid;
1288                         }
1289                         rule_add_key(&rule_tmp, TK_M_RESULT, op, value, NULL);
1290                         continue;
1291                 }
1292
1293                 if (startswith(key, "IMPORT")) {
1294                         attr = get_key_attribute(rules->udev, key + sizeof("IMPORT")-1);
1295                         if (attr == NULL) {
1296                                 log_error("IMPORT{} type missing, ignoring IMPORT %s:%u\n", filename, lineno);
1297                                 continue;
1298                         }
1299                         if (streq(attr, "program")) {
1300                                 /* find known built-in command */
1301                                 if (value[0] != '/') {
1302                                         enum udev_builtin_cmd cmd;
1303
1304                                         cmd = udev_builtin_lookup(value);
1305                                         if (cmd < UDEV_BUILTIN_MAX) {
1306                                                 log_debug("IMPORT found builtin '%s', replacing %s:%u\n",
1307                                                           value, filename, lineno);
1308                                                 rule_add_key(&rule_tmp, TK_M_IMPORT_BUILTIN, op, value, &cmd);
1309                                                 continue;
1310                                         }
1311                                 }
1312                                 rule_add_key(&rule_tmp, TK_M_IMPORT_PROG, op, value, NULL);
1313                         } else if (streq(attr, "builtin")) {
1314                                 enum udev_builtin_cmd cmd = udev_builtin_lookup(value);
1315
1316                                 if (cmd < UDEV_BUILTIN_MAX)
1317                                         rule_add_key(&rule_tmp, TK_M_IMPORT_BUILTIN, op, value, &cmd);
1318                                 else
1319                                         log_error("IMPORT{builtin}: '%s' unknown %s:%u\n", value, filename, lineno);
1320                         } else if (streq(attr, "file")) {
1321                                 rule_add_key(&rule_tmp, TK_M_IMPORT_FILE, op, value, NULL);
1322                         } else if (streq(attr, "db")) {
1323                                 rule_add_key(&rule_tmp, TK_M_IMPORT_DB, op, value, NULL);
1324                         } else if (streq(attr, "cmdline")) {
1325                                 rule_add_key(&rule_tmp, TK_M_IMPORT_CMDLINE, op, value, NULL);
1326                         } else if (streq(attr, "parent")) {
1327                                 rule_add_key(&rule_tmp, TK_M_IMPORT_PARENT, op, value, NULL);
1328                         } else
1329                                 log_error("IMPORT{} unknown type, ignoring IMPORT %s:%u\n", filename, lineno);
1330                         continue;
1331                 }
1332
1333                 if (startswith(key, "TEST")) {
1334                         mode_t mode = 0;
1335
1336                         if (op > OP_MATCH_MAX) {
1337                                 log_error("invalid TEST operation\n");
1338                                 goto invalid;
1339                         }
1340                         attr = get_key_attribute(rules->udev, key + sizeof("TEST")-1);
1341                         if (attr != NULL) {
1342                                 mode = strtol(attr, NULL, 8);
1343                                 rule_add_key(&rule_tmp, TK_M_TEST, op, value, &mode);
1344                         } else {
1345                                 rule_add_key(&rule_tmp, TK_M_TEST, op, value, NULL);
1346                         }
1347                         continue;
1348                 }
1349
1350                 if (startswith(key, "RUN")) {
1351                         attr = get_key_attribute(rules->udev, key + sizeof("RUN")-1);
1352                         if (attr == NULL)
1353                                 attr = "program";
1354
1355                         if (streq(attr, "builtin")) {
1356                                 enum udev_builtin_cmd cmd = udev_builtin_lookup(value);
1357
1358                                 if (cmd < UDEV_BUILTIN_MAX)
1359                                         rule_add_key(&rule_tmp, TK_A_RUN_BUILTIN, op, value, &cmd);
1360                                 else
1361                                         log_error("IMPORT{builtin}: '%s' unknown %s:%u\n", value, filename, lineno);
1362                         } else if (streq(attr, "program")) {
1363                                 enum udev_builtin_cmd cmd = UDEV_BUILTIN_MAX;
1364
1365                                 rule_add_key(&rule_tmp, TK_A_RUN_PROGRAM, op, value, &cmd);
1366                         } else {
1367                                 log_error("RUN{} unknown type, ignoring RUN %s:%u\n", filename, lineno);
1368                         }
1369
1370                         continue;
1371                 }
1372
1373                 if (streq(key, "WAIT_FOR") || streq(key, "WAIT_FOR_SYSFS")) {
1374                         rule_add_key(&rule_tmp, TK_M_WAITFOR, 0, value, NULL);
1375                         continue;
1376                 }
1377
1378                 if (streq(key, "LABEL")) {
1379                         rule_tmp.rule.rule.label_off = rules_add_string(rules, value);
1380                         continue;
1381                 }
1382
1383                 if (streq(key, "GOTO")) {
1384                         rule_add_key(&rule_tmp, TK_A_GOTO, 0, value, NULL);
1385                         continue;
1386                 }
1387
1388                 if (startswith(key, "NAME")) {
1389                         if (op < OP_MATCH_MAX) {
1390                                 rule_add_key(&rule_tmp, TK_M_NAME, op, value, NULL);
1391                         } else {
1392                                 if (streq(value, "%k")) {
1393                                         log_error("NAME=\"%%k\" is ignored, because it breaks kernel supplied names, "
1394                                             "please remove it from %s:%u\n", filename, lineno);
1395                                         continue;
1396                                 }
1397                                 if (value[0] == '\0') {
1398                                         log_debug("NAME=\"\" is ignored, because udev will not delete any device nodes, "
1399                                                   "please remove it from %s:%u\n", filename, lineno);
1400                                         continue;
1401                                 }
1402                                 rule_add_key(&rule_tmp, TK_A_NAME, op, value, NULL);
1403                         }
1404                         rule_tmp.rule.rule.can_set_name = true;
1405                         continue;
1406                 }
1407
1408                 if (streq(key, "SYMLINK")) {
1409                         if (op < OP_MATCH_MAX)
1410                                 rule_add_key(&rule_tmp, TK_M_DEVLINK, op, value, NULL);
1411                         else
1412                                 rule_add_key(&rule_tmp, TK_A_DEVLINK, op, value, NULL);
1413                         rule_tmp.rule.rule.can_set_name = true;
1414                         continue;
1415                 }
1416
1417                 if (streq(key, "OWNER")) {
1418                         uid_t uid;
1419                         char *endptr;
1420
1421                         uid = strtoul(value, &endptr, 10);
1422                         if (endptr[0] == '\0') {
1423                                 rule_add_key(&rule_tmp, TK_A_OWNER_ID, op, NULL, &uid);
1424                         } else if ((rules->resolve_names > 0) && strchr("$%", value[0]) == NULL) {
1425                                 uid = add_uid(rules, value);
1426                                 rule_add_key(&rule_tmp, TK_A_OWNER_ID, op, NULL, &uid);
1427                         } else if (rules->resolve_names >= 0) {
1428                                 rule_add_key(&rule_tmp, TK_A_OWNER, op, value, NULL);
1429                         }
1430                         rule_tmp.rule.rule.can_set_name = true;
1431                         continue;
1432                 }
1433
1434                 if (streq(key, "GROUP")) {
1435                         gid_t gid;
1436                         char *endptr;
1437
1438                         gid = strtoul(value, &endptr, 10);
1439                         if (endptr[0] == '\0') {
1440                                 rule_add_key(&rule_tmp, TK_A_GROUP_ID, op, NULL, &gid);
1441                         } else if ((rules->resolve_names > 0) && strchr("$%", value[0]) == NULL) {
1442                                 gid = add_gid(rules, value);
1443                                 rule_add_key(&rule_tmp, TK_A_GROUP_ID, op, NULL, &gid);
1444                         } else if (rules->resolve_names >= 0) {
1445                                 rule_add_key(&rule_tmp, TK_A_GROUP, op, value, NULL);
1446                         }
1447                         rule_tmp.rule.rule.can_set_name = true;
1448                         continue;
1449                 }
1450
1451                 if (streq(key, "MODE")) {
1452                         mode_t mode;
1453                         char *endptr;
1454
1455                         mode = strtol(value, &endptr, 8);
1456                         if (endptr[0] == '\0')
1457                                 rule_add_key(&rule_tmp, TK_A_MODE_ID, op, NULL, &mode);
1458                         else
1459                                 rule_add_key(&rule_tmp, TK_A_MODE, op, value, NULL);
1460                         rule_tmp.rule.rule.can_set_name = true;
1461                         continue;
1462                 }
1463
1464                 if (streq(key, "OPTIONS")) {
1465                         const char *pos;
1466
1467                         pos = strstr(value, "link_priority=");
1468                         if (pos != NULL) {
1469                                 int prio = atoi(&pos[strlen("link_priority=")]);
1470
1471                                 rule_add_key(&rule_tmp, TK_A_DEVLINK_PRIO, op, NULL, &prio);
1472                         }
1473
1474                         pos = strstr(value, "event_timeout=");
1475                         if (pos != NULL) {
1476                                 int tout = atoi(&pos[strlen("event_timeout=")]);
1477
1478                                 rule_add_key(&rule_tmp, TK_M_EVENT_TIMEOUT, op, NULL, &tout);
1479                         }
1480
1481                         pos = strstr(value, "string_escape=");
1482                         if (pos != NULL) {
1483                                 pos = &pos[strlen("string_escape=")];
1484                                 if (startswith(pos, "none"))
1485                                         rule_add_key(&rule_tmp, TK_A_STRING_ESCAPE_NONE, op, NULL, NULL);
1486                                 else if (startswith(pos, "replace"))
1487                                         rule_add_key(&rule_tmp, TK_A_STRING_ESCAPE_REPLACE, op, NULL, NULL);
1488                         }
1489
1490                         pos = strstr(value, "db_persist");
1491                         if (pos != NULL)
1492                                 rule_add_key(&rule_tmp, TK_A_DB_PERSIST, op, NULL, NULL);
1493
1494                         pos = strstr(value, "nowatch");
1495                         if (pos != NULL) {
1496                                 const int off = 0;
1497
1498                                 rule_add_key(&rule_tmp, TK_A_INOTIFY_WATCH, op, NULL, &off);
1499                         } else {
1500                                 pos = strstr(value, "watch");
1501                                 if (pos != NULL) {
1502                                         const int on = 1;
1503
1504                                         rule_add_key(&rule_tmp, TK_A_INOTIFY_WATCH, op, NULL, &on);
1505                                 }
1506                         }
1507
1508                         pos = strstr(value, "static_node=");
1509                         if (pos != NULL) {
1510                                 rule_add_key(&rule_tmp, TK_A_STATIC_NODE, op, &pos[strlen("static_node=")], NULL);
1511                                 rule_tmp.rule.rule.has_static_node = true;
1512                         }
1513
1514                         continue;
1515                 }
1516
1517                 log_error("unknown key '%s' in %s:%u\n", key, filename, lineno);
1518                 goto invalid;
1519         }
1520
1521         /* add rule token */
1522         rule_tmp.rule.rule.token_count = 1 + rule_tmp.token_cur;
1523         if (add_token(rules, &rule_tmp.rule) != 0)
1524                 goto invalid;
1525
1526         /* add tokens to list, sorted by type */
1527         if (sort_token(rules, &rule_tmp) != 0)
1528                 goto invalid;
1529
1530         return 0;
1531 invalid:
1532         log_error("invalid rule '%s:%u'\n", filename, lineno);
1533         return -1;
1534 }
1535
1536 static int parse_file(struct udev_rules *rules, const char *filename)
1537 {
1538         FILE *f;
1539         unsigned int first_token;
1540         unsigned int filename_off;
1541         char line[UTIL_LINE_SIZE];
1542         int line_nr = 0;
1543         unsigned int i;
1544
1545         if (null_or_empty_path(filename)) {
1546                 log_debug("skip empty file: %s\n", filename);
1547                 return 0;
1548         }
1549         log_debug("read rules file: %s\n", filename);
1550
1551         f = fopen(filename, "re");
1552         if (f == NULL)
1553                 return -1;
1554
1555         first_token = rules->token_cur;
1556         filename_off = rules_add_string(rules, filename);
1557
1558         while (fgets(line, sizeof(line), f) != NULL) {
1559                 char *key;
1560                 size_t len;
1561
1562                 /* skip whitespace */
1563                 line_nr++;
1564                 key = line;
1565                 while (isspace(key[0]))
1566                         key++;
1567
1568                 /* comment */
1569                 if (key[0] == '#')
1570                         continue;
1571
1572                 len = strlen(line);
1573                 if (len < 3)
1574                         continue;
1575
1576                 /* continue reading if backslash+newline is found */
1577                 while (line[len-2] == '\\') {
1578                         if (fgets(&line[len-2], (sizeof(line)-len)+2, f) == NULL)
1579                                 break;
1580                         if (strlen(&line[len-2]) < 2)
1581                                 break;
1582                         line_nr++;
1583                         len = strlen(line);
1584                 }
1585
1586                 if (len+1 >= sizeof(line)) {
1587                         log_error("line too long '%s':%u, ignored\n", filename, line_nr);
1588                         continue;
1589                 }
1590                 add_rule(rules, key, filename, filename_off, line_nr);
1591         }
1592         fclose(f);
1593
1594         /* link GOTOs to LABEL rules in this file to be able to fast-forward */
1595         for (i = first_token+1; i < rules->token_cur; i++) {
1596                 if (rules->tokens[i].type == TK_A_GOTO) {
1597                         char *label = rules_str(rules, rules->tokens[i].key.value_off);
1598                         unsigned int j;
1599
1600                         for (j = i+1; j < rules->token_cur; j++) {
1601                                 if (rules->tokens[j].type != TK_RULE)
1602                                         continue;
1603                                 if (rules->tokens[j].rule.label_off == 0)
1604                                         continue;
1605                                 if (!streq(label, rules_str(rules, rules->tokens[j].rule.label_off)))
1606                                         continue;
1607                                 rules->tokens[i].key.rule_goto = j;
1608                                 break;
1609                         }
1610                         if (rules->tokens[i].key.rule_goto == 0)
1611                                 log_error("GOTO '%s' has no matching label in: '%s'\n", label, filename);
1612                 }
1613         }
1614         return 0;
1615 }
1616
1617 struct udev_rules *udev_rules_new(struct udev *udev, int resolve_names)
1618 {
1619         struct udev_rules *rules;
1620         struct udev_list file_list;
1621         struct token end_token;
1622         char **files, **f;
1623         int r;
1624
1625         rules = calloc(1, sizeof(struct udev_rules));
1626         if (rules == NULL)
1627                 return NULL;
1628         rules->udev = udev;
1629         rules->resolve_names = resolve_names;
1630         udev_list_init(udev, &file_list, true);
1631
1632         /* init token array and string buffer */
1633         rules->tokens = malloc(PREALLOC_TOKEN * sizeof(struct token));
1634         if (rules->tokens == NULL)
1635                 return udev_rules_unref(rules);
1636         rules->token_max = PREALLOC_TOKEN;
1637
1638         rules->strbuf = strbuf_new();
1639         if (!rules->strbuf)
1640                 return udev_rules_unref(rules);
1641
1642         rules->dirs = strv_new("/etc/udev/rules.d",
1643                                "/run/udev/rules.d",
1644                                UDEVLIBEXECDIR "/rules.d",
1645                                NULL);
1646         if (!rules->dirs) {
1647                 log_error("failed to build config directory array");
1648                 return udev_rules_unref(rules);
1649         }
1650         if (!path_strv_canonicalize(rules->dirs)) {
1651                 log_error("failed to canonicalize config directories\n");
1652                 return udev_rules_unref(rules);
1653         }
1654         strv_uniq(rules->dirs);
1655
1656         rules->dirs_ts_usec = calloc(strv_length(rules->dirs), sizeof(usec_t));
1657         if(!rules->dirs_ts_usec)
1658                 return udev_rules_unref(rules);
1659         udev_rules_check_timestamp(rules);
1660
1661         r = conf_files_list_strv(&files, ".rules", NULL, (const char **)rules->dirs);
1662         if (r < 0) {
1663                 log_error("failed to enumerate rules files: %s\n", strerror(-r));
1664                 return udev_rules_unref(rules);
1665         }
1666
1667         /*
1668          * The offset value in the rules strct is limited; add all
1669          * rules file names to the beginning of the string buffer.
1670          */
1671         STRV_FOREACH(f, files)
1672                 rules_add_string(rules, *f);
1673
1674         STRV_FOREACH(f, files)
1675                 parse_file(rules, *f);
1676
1677         strv_free(files);
1678
1679         memset(&end_token, 0x00, sizeof(struct token));
1680         end_token.type = TK_END;
1681         add_token(rules, &end_token);
1682         log_debug("rules contain %zu bytes tokens (%u * %zu bytes), %zu bytes strings\n",
1683                   rules->token_max * sizeof(struct token), rules->token_max, sizeof(struct token), rules->strbuf->len);
1684
1685         /* cleanup temporary strbuf data */
1686         log_debug("%zu strings (%zu bytes), %zu de-duplicated (%zu bytes), %zu trie nodes used\n",
1687                   rules->strbuf->in_count, rules->strbuf->in_len,
1688                   rules->strbuf->dedup_count, rules->strbuf->dedup_len, rules->strbuf->nodes_count);
1689         strbuf_complete(rules->strbuf);
1690
1691         /* cleanup uid/gid cache */
1692         free(rules->uids);
1693         rules->uids = NULL;
1694         rules->uids_cur = 0;
1695         rules->uids_max = 0;
1696         free(rules->gids);
1697         rules->gids = NULL;
1698         rules->gids_cur = 0;
1699         rules->gids_max = 0;
1700
1701         dump_rules(rules);
1702         return rules;
1703 }
1704
1705 struct udev_rules *udev_rules_unref(struct udev_rules *rules)
1706 {
1707         if (rules == NULL)
1708                 return NULL;
1709         free(rules->tokens);
1710         strbuf_cleanup(rules->strbuf);
1711         free(rules->uids);
1712         free(rules->gids);
1713         strv_free(rules->dirs);
1714         free(rules->dirs_ts_usec);
1715         free(rules);
1716         return NULL;
1717 }
1718
1719 bool udev_rules_check_timestamp(struct udev_rules *rules)
1720 {
1721         unsigned int i;
1722         bool changed = false;
1723
1724         if (rules == NULL)
1725                 goto out;
1726
1727         for (i = 0; rules->dirs[i]; i++) {
1728                 struct stat stats;
1729
1730                 if (stat(rules->dirs[i], &stats) < 0)
1731                         continue;
1732
1733                 if (rules->dirs_ts_usec[i] == timespec_load(&stats.st_mtim))
1734                         continue;
1735
1736                 /* first check */
1737                 if (rules->dirs_ts_usec[i] != 0) {
1738                         log_debug("reload - timestamp of '%s' changed\n", rules->dirs[i]);
1739                         changed = true;
1740                 }
1741
1742                 /* update timestamp */
1743                 rules->dirs_ts_usec[i] = timespec_load(&stats.st_mtim);
1744         }
1745 out:
1746         return changed;
1747 }
1748
1749 static int match_key(struct udev_rules *rules, struct token *token, const char *val)
1750 {
1751         char *key_value = rules_str(rules, token->key.value_off);
1752         char *pos;
1753         bool match = false;
1754
1755         if (val == NULL)
1756                 val = "";
1757
1758         switch (token->key.glob) {
1759         case GL_PLAIN:
1760                 match = (streq(key_value, val));
1761                 break;
1762         case GL_GLOB:
1763                 match = (fnmatch(key_value, val, 0) == 0);
1764                 break;
1765         case GL_SPLIT:
1766                 {
1767                         const char *s;
1768                         size_t len;
1769
1770                         s = rules_str(rules, token->key.value_off);
1771                         len = strlen(val);
1772                         for (;;) {
1773                                 const char *next;
1774
1775                                 next = strchr(s, '|');
1776                                 if (next != NULL) {
1777                                         size_t matchlen = (size_t)(next - s);
1778
1779                                         match = (matchlen == len && strneq(s, val, matchlen));
1780                                         if (match)
1781                                                 break;
1782                                 } else {
1783                                         match = (streq(s, val));
1784                                         break;
1785                                 }
1786                                 s = &next[1];
1787                         }
1788                         break;
1789                 }
1790         case GL_SPLIT_GLOB:
1791                 {
1792                         char value[UTIL_PATH_SIZE];
1793
1794                         strscpy(value, sizeof(value), rules_str(rules, token->key.value_off));
1795                         key_value = value;
1796                         while (key_value != NULL) {
1797                                 pos = strchr(key_value, '|');
1798                                 if (pos != NULL) {
1799                                         pos[0] = '\0';
1800                                         pos = &pos[1];
1801                                 }
1802                                 match = (fnmatch(key_value, val, 0) == 0);
1803                                 if (match)
1804                                         break;
1805                                 key_value = pos;
1806                         }
1807                         break;
1808                 }
1809         case GL_SOMETHING:
1810                 match = (val[0] != '\0');
1811                 break;
1812         case GL_UNSET:
1813                 return -1;
1814         }
1815
1816         if (match && (token->key.op == OP_MATCH))
1817                 return 0;
1818         if (!match && (token->key.op == OP_NOMATCH))
1819                 return 0;
1820         return -1;
1821 }
1822
1823 static int match_attr(struct udev_rules *rules, struct udev_device *dev, struct udev_event *event, struct token *cur)
1824 {
1825         const char *name;
1826         char nbuf[UTIL_NAME_SIZE];
1827         const char *value;
1828         char vbuf[UTIL_NAME_SIZE];
1829         size_t len;
1830
1831         name = rules_str(rules, cur->key.attr_off);
1832         switch (cur->key.attrsubst) {
1833         case SB_FORMAT:
1834                 udev_event_apply_format(event, name, nbuf, sizeof(nbuf));
1835                 name = nbuf;
1836                 /* fall through */
1837         case SB_NONE:
1838                 value = udev_device_get_sysattr_value(dev, name);
1839                 if (value == NULL)
1840                         return -1;
1841                 break;
1842         case SB_SUBSYS:
1843                 if (util_resolve_subsys_kernel(event->udev, name, vbuf, sizeof(vbuf), 1) != 0)
1844                         return -1;
1845                 value = vbuf;
1846                 break;
1847         default:
1848                 return -1;
1849         }
1850
1851         /* remove trailing whitespace, if not asked to match for it */
1852         len = strlen(value);
1853         if (len > 0 && isspace(value[len-1])) {
1854                 const char *key_value;
1855                 size_t klen;
1856
1857                 key_value = rules_str(rules, cur->key.value_off);
1858                 klen = strlen(key_value);
1859                 if (klen > 0 && !isspace(key_value[klen-1])) {
1860                         if (value != vbuf) {
1861                                 strscpy(vbuf, sizeof(vbuf), value);
1862                                 value = vbuf;
1863                         }
1864                         while (len > 0 && isspace(vbuf[--len]))
1865                                 vbuf[len] = '\0';
1866                 }
1867         }
1868
1869         return match_key(rules, cur, value);
1870 }
1871
1872 enum escape_type {
1873         ESCAPE_UNSET,
1874         ESCAPE_NONE,
1875         ESCAPE_REPLACE,
1876 };
1877
1878 int udev_rules_apply_to_event(struct udev_rules *rules, struct udev_event *event, const sigset_t *sigmask)
1879 {
1880         struct token *cur;
1881         struct token *rule;
1882         enum escape_type esc = ESCAPE_UNSET;
1883         bool can_set_name;
1884
1885         if (rules->tokens == NULL)
1886                 return -1;
1887
1888         can_set_name = ((!streq(udev_device_get_action(event->dev), "remove")) &&
1889                         (major(udev_device_get_devnum(event->dev)) > 0 ||
1890                          udev_device_get_ifindex(event->dev) > 0));
1891
1892         /* loop through token list, match, run actions or forward to next rule */
1893         cur = &rules->tokens[0];
1894         rule = cur;
1895         for (;;) {
1896                 dump_token(rules, cur);
1897                 switch (cur->type) {
1898                 case TK_RULE:
1899                         /* current rule */
1900                         rule = cur;
1901                         /* possibly skip rules which want to set NAME, SYMLINK, OWNER, GROUP, MODE */
1902                         if (!can_set_name && rule->rule.can_set_name)
1903                                 goto nomatch;
1904                         esc = ESCAPE_UNSET;
1905                         break;
1906                 case TK_M_ACTION:
1907                         if (match_key(rules, cur, udev_device_get_action(event->dev)) != 0)
1908                                 goto nomatch;
1909                         break;
1910                 case TK_M_DEVPATH:
1911                         if (match_key(rules, cur, udev_device_get_devpath(event->dev)) != 0)
1912                                 goto nomatch;
1913                         break;
1914                 case TK_M_KERNEL:
1915                         if (match_key(rules, cur, udev_device_get_sysname(event->dev)) != 0)
1916                                 goto nomatch;
1917                         break;
1918                 case TK_M_DEVLINK: {
1919                         struct udev_list_entry *list_entry;
1920                         bool match = false;
1921
1922                         udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(event->dev)) {
1923                                 const char *devlink;
1924
1925                                 devlink =  udev_list_entry_get_name(list_entry) + strlen("/dev/");
1926                                 if (match_key(rules, cur, devlink) == 0) {
1927                                         match = true;
1928                                         break;
1929                                 }
1930                         }
1931                         if (!match)
1932                                 goto nomatch;
1933                         break;
1934                 }
1935                 case TK_M_NAME:
1936                         if (match_key(rules, cur, event->name) != 0)
1937                                 goto nomatch;
1938                         break;
1939                 case TK_M_ENV: {
1940                         const char *key_name = rules_str(rules, cur->key.attr_off);
1941                         const char *value;
1942
1943                         value = udev_device_get_property_value(event->dev, key_name);
1944                         if (value == NULL)
1945                                 value = "";
1946                         if (match_key(rules, cur, value))
1947                                 goto nomatch;
1948                         break;
1949                 }
1950                 case TK_M_TAG: {
1951                         struct udev_list_entry *list_entry;
1952                         bool match = false;
1953
1954                         udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(event->dev)) {
1955                                 if (streq(rules_str(rules, cur->key.value_off), udev_list_entry_get_name(list_entry))) {
1956                                         match = true;
1957                                         break;
1958                                 }
1959                         }
1960                         if (!match && (cur->key.op != OP_NOMATCH))
1961                                 goto nomatch;
1962                         break;
1963                 }
1964                 case TK_M_SUBSYSTEM:
1965                         if (match_key(rules, cur, udev_device_get_subsystem(event->dev)) != 0)
1966                                 goto nomatch;
1967                         break;
1968                 case TK_M_DRIVER:
1969                         if (match_key(rules, cur, udev_device_get_driver(event->dev)) != 0)
1970                                 goto nomatch;
1971                         break;
1972                 case TK_M_WAITFOR: {
1973                         char filename[UTIL_PATH_SIZE];
1974                         int found;
1975
1976                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), filename, sizeof(filename));
1977                         found = (wait_for_file(event->dev, filename, 10) == 0);
1978                         if (!found && (cur->key.op != OP_NOMATCH))
1979                                 goto nomatch;
1980                         break;
1981                 }
1982                 case TK_M_ATTR:
1983                         if (match_attr(rules, event->dev, event, cur) != 0)
1984                                 goto nomatch;
1985                         break;
1986                 case TK_M_KERNELS:
1987                 case TK_M_SUBSYSTEMS:
1988                 case TK_M_DRIVERS:
1989                 case TK_M_ATTRS:
1990                 case TK_M_TAGS: {
1991                         struct token *next;
1992
1993                         /* get whole sequence of parent matches */
1994                         next = cur;
1995                         while (next->type > TK_M_PARENTS_MIN && next->type < TK_M_PARENTS_MAX)
1996                                 next++;
1997
1998                         /* loop over parents */
1999                         event->dev_parent = event->dev;
2000                         for (;;) {
2001                                 struct token *key;
2002
2003                                 /* loop over sequence of parent match keys */
2004                                 for (key = cur; key < next; key++ ) {
2005                                         dump_token(rules, key);
2006                                         switch(key->type) {
2007                                         case TK_M_KERNELS:
2008                                                 if (match_key(rules, key, udev_device_get_sysname(event->dev_parent)) != 0)
2009                                                         goto try_parent;
2010                                                 break;
2011                                         case TK_M_SUBSYSTEMS:
2012                                                 if (match_key(rules, key, udev_device_get_subsystem(event->dev_parent)) != 0)
2013                                                         goto try_parent;
2014                                                 break;
2015                                         case TK_M_DRIVERS:
2016                                                 if (match_key(rules, key, udev_device_get_driver(event->dev_parent)) != 0)
2017                                                         goto try_parent;
2018                                                 break;
2019                                         case TK_M_ATTRS:
2020                                                 if (match_attr(rules, event->dev_parent, event, key) != 0)
2021                                                         goto try_parent;
2022                                                 break;
2023                                         case TK_M_TAGS: {
2024                                                 bool match = udev_device_has_tag(event->dev_parent, rules_str(rules, cur->key.value_off));
2025
2026                                                 if (match && key->key.op == OP_NOMATCH)
2027                                                         goto try_parent;
2028                                                 if (!match && key->key.op == OP_MATCH)
2029                                                         goto try_parent;
2030                                                 break;
2031                                         }
2032                                         default:
2033                                                 goto nomatch;
2034                                         }
2035                                 }
2036                                 break;
2037
2038                         try_parent:
2039                                 event->dev_parent = udev_device_get_parent(event->dev_parent);
2040                                 if (event->dev_parent == NULL)
2041                                         goto nomatch;
2042                         }
2043                         /* move behind our sequence of parent match keys */
2044                         cur = next;
2045                         continue;
2046                 }
2047                 case TK_M_TEST: {
2048                         char filename[UTIL_PATH_SIZE];
2049                         struct stat statbuf;
2050                         int match;
2051
2052                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), filename, sizeof(filename));
2053                         if (util_resolve_subsys_kernel(event->udev, filename, filename, sizeof(filename), 0) != 0) {
2054                                 if (filename[0] != '/') {
2055                                         char tmp[UTIL_PATH_SIZE];
2056
2057                                         strscpy(tmp, sizeof(tmp), filename);
2058                                         strscpyl(filename, sizeof(filename),
2059                                                       udev_device_get_syspath(event->dev), "/", tmp, NULL);
2060                                 }
2061                         }
2062                         attr_subst_subdir(filename, sizeof(filename));
2063
2064                         match = (stat(filename, &statbuf) == 0);
2065                         if (match && cur->key.mode > 0)
2066                                 match = ((statbuf.st_mode & cur->key.mode) > 0);
2067                         if (match && cur->key.op == OP_NOMATCH)
2068                                 goto nomatch;
2069                         if (!match && cur->key.op == OP_MATCH)
2070                                 goto nomatch;
2071                         break;
2072                 }
2073                 case TK_M_EVENT_TIMEOUT:
2074                         log_debug("OPTIONS event_timeout=%u\n", cur->key.event_timeout);
2075                         event->timeout_usec = cur->key.event_timeout * 1000 * 1000;
2076                         break;
2077                 case TK_M_PROGRAM: {
2078                         char program[UTIL_PATH_SIZE];
2079                         char **envp;
2080                         char result[UTIL_PATH_SIZE];
2081
2082                         free(event->program_result);
2083                         event->program_result = NULL;
2084                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), program, sizeof(program));
2085                         envp = udev_device_get_properties_envp(event->dev);
2086                         log_debug("PROGRAM '%s' %s:%u\n",
2087                                   program,
2088                                   rules_str(rules, rule->rule.filename_off),
2089                                   rule->rule.filename_line);
2090
2091                         if (udev_event_spawn(event, program, envp, sigmask, result, sizeof(result)) < 0) {
2092                                 if (cur->key.op != OP_NOMATCH)
2093                                         goto nomatch;
2094                         } else {
2095                                 int count;
2096
2097                                 util_remove_trailing_chars(result, '\n');
2098                                 if (esc == ESCAPE_UNSET || esc == ESCAPE_REPLACE) {
2099                                         count = util_replace_chars(result, UDEV_ALLOWED_CHARS_INPUT);
2100                                         if (count > 0)
2101                                                 log_debug("%i character(s) replaced\n" , count);
2102                                 }
2103                                 event->program_result = strdup(result);
2104                                 if (cur->key.op == OP_NOMATCH)
2105                                         goto nomatch;
2106                         }
2107                         break;
2108                 }
2109                 case TK_M_IMPORT_FILE: {
2110                         char import[UTIL_PATH_SIZE];
2111
2112                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), import, sizeof(import));
2113                         if (import_file_into_properties(event->dev, import) != 0)
2114                                 if (cur->key.op != OP_NOMATCH)
2115                                         goto nomatch;
2116                         break;
2117                 }
2118                 case TK_M_IMPORT_PROG: {
2119                         char import[UTIL_PATH_SIZE];
2120
2121                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), import, sizeof(import));
2122                         log_debug("IMPORT '%s' %s:%u\n",
2123                                   import,
2124                                   rules_str(rules, rule->rule.filename_off),
2125                                   rule->rule.filename_line);
2126
2127                         if (import_program_into_properties(event, import, sigmask) != 0)
2128                                 if (cur->key.op != OP_NOMATCH)
2129                                         goto nomatch;
2130                         break;
2131                 }
2132                 case TK_M_IMPORT_BUILTIN: {
2133                         char command[UTIL_PATH_SIZE];
2134
2135                         if (udev_builtin_run_once(cur->key.builtin_cmd)) {
2136                                 /* check if we ran already */
2137                                 if (event->builtin_run & (1 << cur->key.builtin_cmd)) {
2138                                         log_debug("IMPORT builtin skip '%s' %s:%u\n",
2139                                                   udev_builtin_name(cur->key.builtin_cmd),
2140                                                   rules_str(rules, rule->rule.filename_off),
2141                                                   rule->rule.filename_line);
2142                                         /* return the result from earlier run */
2143                                         if (event->builtin_ret & (1 << cur->key.builtin_cmd))
2144                                         if (cur->key.op != OP_NOMATCH)
2145                                                         goto nomatch;
2146                                         break;
2147                                 }
2148                                 /* mark as ran */
2149                                 event->builtin_run |= (1 << cur->key.builtin_cmd);
2150                         }
2151
2152                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), command, sizeof(command));
2153                         log_debug("IMPORT builtin '%s' %s:%u\n",
2154                                   udev_builtin_name(cur->key.builtin_cmd),
2155                                   rules_str(rules, rule->rule.filename_off),
2156                                   rule->rule.filename_line);
2157
2158                         if (udev_builtin_run(event->dev, cur->key.builtin_cmd, command, false) != 0) {
2159                                 /* remember failure */
2160                                 log_debug("IMPORT builtin '%s' returned non-zero\n",
2161                                           udev_builtin_name(cur->key.builtin_cmd));
2162                                 event->builtin_ret |= (1 << cur->key.builtin_cmd);
2163                                 if (cur->key.op != OP_NOMATCH)
2164                                         goto nomatch;
2165                         }
2166                         break;
2167                 }
2168                 case TK_M_IMPORT_DB: {
2169                         const char *key = rules_str(rules, cur->key.value_off);
2170                         const char *value;
2171
2172                         value = udev_device_get_property_value(event->dev_db, key);
2173                         if (value != NULL) {
2174                                 struct udev_list_entry *entry;
2175
2176                                 entry = udev_device_add_property(event->dev, key, value);
2177                                 udev_list_entry_set_num(entry, true);
2178                         } else {
2179                                 if (cur->key.op != OP_NOMATCH)
2180                                         goto nomatch;
2181                         }
2182                         break;
2183                 }
2184                 case TK_M_IMPORT_CMDLINE: {
2185                         FILE *f;
2186                         bool imported = false;
2187
2188                         f = fopen("/proc/cmdline", "re");
2189                         if (f != NULL) {
2190                                 char cmdline[4096];
2191
2192                                 if (fgets(cmdline, sizeof(cmdline), f) != NULL) {
2193                                         const char *key = rules_str(rules, cur->key.value_off);
2194                                         char *pos;
2195
2196                                         pos = strstr(cmdline, key);
2197                                         if (pos != NULL) {
2198                                                 struct udev_list_entry *entry;
2199
2200                                                 pos += strlen(key);
2201                                                 if (pos[0] == '\0' || isspace(pos[0])) {
2202                                                         /* we import simple flags as 'FLAG=1' */
2203                                                         entry = udev_device_add_property(event->dev, key, "1");
2204                                                         udev_list_entry_set_num(entry, true);
2205                                                         imported = true;
2206                                                 } else if (pos[0] == '=') {
2207                                                         const char *value;
2208
2209                                                         pos++;
2210                                                         value = pos;
2211                                                         while (pos[0] != '\0' && !isspace(pos[0]))
2212                                                                 pos++;
2213                                                         pos[0] = '\0';
2214                                                         entry = udev_device_add_property(event->dev, key, value);
2215                                                         udev_list_entry_set_num(entry, true);
2216                                                         imported = true;
2217                                                 }
2218                                         }
2219                                 }
2220                                 fclose(f);
2221                         }
2222                         if (!imported && cur->key.op != OP_NOMATCH)
2223                                 goto nomatch;
2224                         break;
2225                 }
2226                 case TK_M_IMPORT_PARENT: {
2227                         char import[UTIL_PATH_SIZE];
2228
2229                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), import, sizeof(import));
2230                         if (import_parent_into_properties(event->dev, import) != 0)
2231                                 if (cur->key.op != OP_NOMATCH)
2232                                         goto nomatch;
2233                         break;
2234                 }
2235                 case TK_M_RESULT:
2236                         if (match_key(rules, cur, event->program_result) != 0)
2237                                 goto nomatch;
2238                         break;
2239                 case TK_A_STRING_ESCAPE_NONE:
2240                         esc = ESCAPE_NONE;
2241                         break;
2242                 case TK_A_STRING_ESCAPE_REPLACE:
2243                         esc = ESCAPE_REPLACE;
2244                         break;
2245                 case TK_A_DB_PERSIST:
2246                         udev_device_set_db_persist(event->dev);
2247                         break;
2248                 case TK_A_INOTIFY_WATCH:
2249                         if (event->inotify_watch_final)
2250                                 break;
2251                         if (cur->key.op == OP_ASSIGN_FINAL)
2252                                 event->inotify_watch_final = true;
2253                         event->inotify_watch = cur->key.watch;
2254                         break;
2255                 case TK_A_DEVLINK_PRIO:
2256                         udev_device_set_devlink_priority(event->dev, cur->key.devlink_prio);
2257                         break;
2258                 case TK_A_OWNER: {
2259                         char owner[UTIL_NAME_SIZE];
2260
2261                         if (event->owner_final)
2262                                 break;
2263                         if (cur->key.op == OP_ASSIGN_FINAL)
2264                                 event->owner_final = true;
2265                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), owner, sizeof(owner));
2266                         event->owner_set = true;
2267                         event->uid = util_lookup_user(event->udev, owner);
2268                         log_debug("OWNER %u %s:%u\n",
2269                                   event->uid,
2270                                   rules_str(rules, rule->rule.filename_off),
2271                                   rule->rule.filename_line);
2272                         break;
2273                 }
2274                 case TK_A_GROUP: {
2275                         char group[UTIL_NAME_SIZE];
2276
2277                         if (event->group_final)
2278                                 break;
2279                         if (cur->key.op == OP_ASSIGN_FINAL)
2280                                 event->group_final = true;
2281                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), group, sizeof(group));
2282                         event->group_set = true;
2283                         event->gid = util_lookup_group(event->udev, group);
2284                         log_debug("GROUP %u %s:%u\n",
2285                                   event->gid,
2286                                   rules_str(rules, rule->rule.filename_off),
2287                                   rule->rule.filename_line);
2288                         break;
2289                 }
2290                 case TK_A_MODE: {
2291                         char mode_str[UTIL_NAME_SIZE];
2292                         mode_t mode;
2293                         char *endptr;
2294
2295                         if (event->mode_final)
2296                                 break;
2297                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), mode_str, sizeof(mode_str));
2298                         mode = strtol(mode_str, &endptr, 8);
2299                         if (endptr[0] != '\0') {
2300                                 log_error("ignoring invalid mode '%s'\n", mode_str);
2301                                 break;
2302                         }
2303                         if (cur->key.op == OP_ASSIGN_FINAL)
2304                                 event->mode_final = true;
2305                         event->mode_set = true;
2306                         event->mode = mode;
2307                         log_debug("MODE %#o %s:%u\n",
2308                                   event->mode,
2309                                   rules_str(rules, rule->rule.filename_off),
2310                                   rule->rule.filename_line);
2311                         break;
2312                 }
2313                 case TK_A_OWNER_ID:
2314                         if (event->owner_final)
2315                                 break;
2316                         if (cur->key.op == OP_ASSIGN_FINAL)
2317                                 event->owner_final = true;
2318                         event->owner_set = true;
2319                         event->uid = cur->key.uid;
2320                         log_debug("OWNER %u %s:%u\n",
2321                                   event->uid,
2322                                   rules_str(rules, rule->rule.filename_off),
2323                                   rule->rule.filename_line);
2324                         break;
2325                 case TK_A_GROUP_ID:
2326                         if (event->group_final)
2327                                 break;
2328                         if (cur->key.op == OP_ASSIGN_FINAL)
2329                                 event->group_final = true;
2330                         event->group_set = true;
2331                         event->gid = cur->key.gid;
2332                         log_debug("GROUP %u %s:%u\n",
2333                                   event->gid,
2334                                   rules_str(rules, rule->rule.filename_off),
2335                                   rule->rule.filename_line);
2336                         break;
2337                 case TK_A_MODE_ID:
2338                         if (event->mode_final)
2339                                 break;
2340                         if (cur->key.op == OP_ASSIGN_FINAL)
2341                                 event->mode_final = true;
2342                         event->mode_set = true;
2343                         event->mode = cur->key.mode;
2344                         log_debug("MODE %#o %s:%u\n",
2345                                   event->mode,
2346                                   rules_str(rules, rule->rule.filename_off),
2347                                   rule->rule.filename_line);
2348                         break;
2349                 case TK_A_SECLABEL: {
2350                         const char *name, *label;
2351
2352                         name = rules_str(rules, cur->key.attr_off);
2353                         label = rules_str(rules, cur->key.value_off);
2354                         if (cur->key.op == OP_ASSIGN || cur->key.op == OP_ASSIGN_FINAL)
2355                                 udev_list_cleanup(&event->seclabel_list);
2356                         udev_list_entry_add(&event->seclabel_list, name, label);
2357                         log_debug("SECLABEL{%s}='%s' %s:%u\n",
2358                                   name, label,
2359                                   rules_str(rules, rule->rule.filename_off),
2360                                   rule->rule.filename_line);
2361                         break;
2362                 }
2363                 case TK_A_ENV: {
2364                         const char *name = rules_str(rules, cur->key.attr_off);
2365                         char *value = rules_str(rules, cur->key.value_off);
2366                         char value_new[UTIL_NAME_SIZE];
2367                         const char *value_old = NULL;
2368                         struct udev_list_entry *entry;
2369
2370                         if (value[0] == '\0') {
2371                                 if (cur->key.op == OP_ADD)
2372                                         break;
2373                                 udev_device_add_property(event->dev, name, NULL);
2374                                 break;
2375                         }
2376
2377                         if (cur->key.op == OP_ADD)
2378                                 value_old = udev_device_get_property_value(event->dev, name);
2379                         if (value_old) {
2380                                 char temp[UTIL_NAME_SIZE];
2381
2382                                 /* append value separated by space */
2383                                 udev_event_apply_format(event, value, temp, sizeof(temp));
2384                                 strscpyl(value_new, sizeof(value_new), value_old, " ", temp, NULL);
2385                         } else
2386                                 udev_event_apply_format(event, value, value_new, sizeof(value_new));
2387
2388                         entry = udev_device_add_property(event->dev, name, value_new);
2389                         /* store in db, skip private keys */
2390                         if (name[0] != '.')
2391                                 udev_list_entry_set_num(entry, true);
2392                         break;
2393                 }
2394                 case TK_A_TAG: {
2395                         char tag[UTIL_PATH_SIZE];
2396                         const char *p;
2397
2398                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), tag, sizeof(tag));
2399                         if (cur->key.op == OP_ASSIGN || cur->key.op == OP_ASSIGN_FINAL)
2400                                 udev_device_cleanup_tags_list(event->dev);
2401                         for (p = tag; *p != '\0'; p++) {
2402                                 if ((*p >= 'a' && *p <= 'z') ||
2403                                     (*p >= 'A' && *p <= 'Z') ||
2404                                     (*p >= '0' && *p <= '9') ||
2405                                     *p == '-' || *p == '_')
2406                                         continue;
2407                                 log_error("ignoring invalid tag name '%s'\n", tag);
2408                                 break;
2409                         }
2410                         udev_device_add_tag(event->dev, tag);
2411                         break;
2412                 }
2413                 case TK_A_NAME: {
2414                         const char *name  = rules_str(rules, cur->key.value_off);
2415
2416                         char name_str[UTIL_PATH_SIZE];
2417                         int count;
2418
2419                         if (event->name_final)
2420                                 break;
2421                         if (cur->key.op == OP_ASSIGN_FINAL)
2422                                 event->name_final = true;
2423                         udev_event_apply_format(event, name, name_str, sizeof(name_str));
2424                         if (esc == ESCAPE_UNSET || esc == ESCAPE_REPLACE) {
2425                                 count = util_replace_chars(name_str, "/");
2426                                 if (count > 0)
2427                                         log_debug("%i character(s) replaced\n", count);
2428                         }
2429                         if (major(udev_device_get_devnum(event->dev)) &&
2430                             (!streq(name_str, udev_device_get_devnode(event->dev) + strlen("/dev/")))) {
2431                                 log_error("NAME=\"%s\" ignored, kernel device nodes "
2432                                     "can not be renamed; please fix it in %s:%u\n", name,
2433                                     rules_str(rules, rule->rule.filename_off), rule->rule.filename_line);
2434                                 break;
2435                         }
2436                         free(event->name);
2437                         event->name = strdup(name_str);
2438                         log_debug("NAME '%s' %s:%u\n",
2439                                   event->name,
2440                                   rules_str(rules, rule->rule.filename_off),
2441                                   rule->rule.filename_line);
2442                         break;
2443                 }
2444                 case TK_A_DEVLINK: {
2445                         char temp[UTIL_PATH_SIZE];
2446                         char filename[UTIL_PATH_SIZE];
2447                         char *pos, *next;
2448                         int count = 0;
2449
2450                         if (event->devlink_final)
2451                                 break;
2452                         if (major(udev_device_get_devnum(event->dev)) == 0)
2453                                 break;
2454                         if (cur->key.op == OP_ASSIGN_FINAL)
2455                                 event->devlink_final = true;
2456                         if (cur->key.op == OP_ASSIGN || cur->key.op == OP_ASSIGN_FINAL)
2457                                 udev_device_cleanup_devlinks_list(event->dev);
2458
2459                         /* allow  multiple symlinks separated by spaces */
2460                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), temp, sizeof(temp));
2461                         if (esc == ESCAPE_UNSET)
2462                                 count = util_replace_chars(temp, "/ ");
2463                         else if (esc == ESCAPE_REPLACE)
2464                                 count = util_replace_chars(temp, "/");
2465                         if (count > 0)
2466                                 log_debug("%i character(s) replaced\n" , count);
2467                         pos = temp;
2468                         while (isspace(pos[0]))
2469                                 pos++;
2470                         next = strchr(pos, ' ');
2471                         while (next != NULL) {
2472                                 next[0] = '\0';
2473                                 log_debug("LINK '%s' %s:%u\n", pos,
2474                                           rules_str(rules, rule->rule.filename_off), rule->rule.filename_line);
2475                                 strscpyl(filename, sizeof(filename), "/dev/", pos, NULL);
2476                                 udev_device_add_devlink(event->dev, filename);
2477                                 while (isspace(next[1]))
2478                                         next++;
2479                                 pos = &next[1];
2480                                 next = strchr(pos, ' ');
2481                         }
2482                         if (pos[0] != '\0') {
2483                                 log_debug("LINK '%s' %s:%u\n", pos,
2484                                           rules_str(rules, rule->rule.filename_off), rule->rule.filename_line);
2485                                 strscpyl(filename, sizeof(filename), "/dev/", pos, NULL);
2486                                 udev_device_add_devlink(event->dev, filename);
2487                         }
2488                         break;
2489                 }
2490                 case TK_A_ATTR: {
2491                         const char *key_name = rules_str(rules, cur->key.attr_off);
2492                         char attr[UTIL_PATH_SIZE];
2493                         char value[UTIL_NAME_SIZE];
2494                         FILE *f;
2495
2496                         if (util_resolve_subsys_kernel(event->udev, key_name, attr, sizeof(attr), 0) != 0)
2497                                 strscpyl(attr, sizeof(attr), udev_device_get_syspath(event->dev), "/", key_name, NULL);
2498                         attr_subst_subdir(attr, sizeof(attr));
2499
2500                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), value, sizeof(value));
2501                         log_debug("ATTR '%s' writing '%s' %s:%u\n", attr, value,
2502                                   rules_str(rules, rule->rule.filename_off),
2503                                   rule->rule.filename_line);
2504                         f = fopen(attr, "we");
2505                         if (f != NULL) {
2506                                 if (fprintf(f, "%s", value) <= 0)
2507                                         log_error("error writing ATTR{%s}: %m\n", attr);
2508                                 fclose(f);
2509                         } else {
2510                                 log_error("error opening ATTR{%s} for writing: %m\n", attr);
2511                         }
2512                         break;
2513                 }
2514                 case TK_A_RUN_BUILTIN:
2515                 case TK_A_RUN_PROGRAM: {
2516                         struct udev_list_entry *entry;
2517
2518                         if (cur->key.op == OP_ASSIGN || cur->key.op == OP_ASSIGN_FINAL)
2519                                 udev_list_cleanup(&event->run_list);
2520                         log_debug("RUN '%s' %s:%u\n",
2521                                   rules_str(rules, cur->key.value_off),
2522                                   rules_str(rules, rule->rule.filename_off),
2523                                   rule->rule.filename_line);
2524                         entry = udev_list_entry_add(&event->run_list, rules_str(rules, cur->key.value_off), NULL);
2525                         udev_list_entry_set_num(entry, cur->key.builtin_cmd);
2526                         break;
2527                 }
2528                 case TK_A_GOTO:
2529                         if (cur->key.rule_goto == 0)
2530                                 break;
2531                         cur = &rules->tokens[cur->key.rule_goto];
2532                         continue;
2533                 case TK_END:
2534                         return 0;
2535
2536                 case TK_M_PARENTS_MIN:
2537                 case TK_M_PARENTS_MAX:
2538                 case TK_M_MAX:
2539                 case TK_UNSET:
2540                         log_error("wrong type %u\n", cur->type);
2541                         goto nomatch;
2542                 }
2543
2544                 cur++;
2545                 continue;
2546         nomatch:
2547                 /* fast-forward to next rule */
2548                 cur = rule + rule->rule.token_count;
2549         }
2550 }
2551
2552 int udev_rules_apply_static_dev_perms(struct udev_rules *rules)
2553 {
2554         struct token *cur;
2555         struct token *rule;
2556         uid_t uid = 0;
2557         gid_t gid = 0;
2558         mode_t mode = 0;
2559         _cleanup_strv_free_ char **tags = NULL;
2560         char **t;
2561         FILE *f = NULL;
2562         _cleanup_free_ char *path = NULL;
2563         int r = 0;
2564
2565         if (rules->tokens == NULL)
2566                 return 0;
2567
2568         cur = &rules->tokens[0];
2569         rule = cur;
2570         for (;;) {
2571                 switch (cur->type) {
2572                 case TK_RULE:
2573                         /* current rule */
2574                         rule = cur;
2575
2576                         /* skip rules without a static_node tag */
2577                         if (!rule->rule.has_static_node)
2578                                 goto next;
2579
2580                         uid = 0;
2581                         gid = 0;
2582                         mode = 0;
2583                         strv_free(tags);
2584                         tags = NULL;
2585                         break;
2586                 case TK_A_OWNER_ID:
2587                         uid = cur->key.uid;
2588                         break;
2589                 case TK_A_GROUP_ID:
2590                         gid = cur->key.gid;
2591                         break;
2592                 case TK_A_MODE_ID:
2593                         mode = cur->key.mode;
2594                         break;
2595                 case TK_A_TAG:
2596                         r = strv_extend(&tags, rules_str(rules, cur->key.value_off));
2597                         if (r < 0)
2598                                 goto finish;
2599
2600                         break;
2601                 case TK_A_STATIC_NODE: {
2602                         char device_node[UTIL_PATH_SIZE];
2603                         char tags_dir[UTIL_PATH_SIZE];
2604                         char tag_symlink[UTIL_PATH_SIZE];
2605                         struct stat stats;
2606
2607                         /* we assure, that the permissions tokens are sorted before the static token */
2608                         if (mode == 0 && uid == 0 && gid == 0 && tags == NULL)
2609                                 goto next;
2610                         strscpyl(device_node, sizeof(device_node), "/dev/", rules_str(rules, cur->key.value_off), NULL);
2611                         if (stat(device_node, &stats) != 0)
2612                                 goto next;
2613                         if (!S_ISBLK(stats.st_mode) && !S_ISCHR(stats.st_mode))
2614                                 goto next;
2615
2616                         if (tags) {
2617                                 /* Export the tags to a directory as symlinks, allowing otherwise dead nodes to be tagged */
2618
2619                                 STRV_FOREACH(t, tags) {
2620                                         _cleanup_free_ char *unescaped_filename = NULL;
2621
2622                                         strscpyl(tags_dir, sizeof(tags_dir), "/run/udev/static_node-tags/", *t, "/", NULL);
2623                                         r = mkdir_p(tags_dir, 0755);
2624                                         if (r < 0) {
2625                                                 log_error("failed to create %s: %s\n", tags_dir, strerror(-r));
2626                                                 return r;
2627                                         }
2628
2629                                         unescaped_filename = xescape(rules_str(rules, cur->key.value_off), "/.");
2630
2631                                         strscpyl(tag_symlink, sizeof(tag_symlink), tags_dir, unescaped_filename, NULL);
2632                                         r = symlink(device_node, tag_symlink);
2633                                         if (r < 0 && errno != EEXIST) {
2634                                                 log_error("failed to create symlink %s -> %s: %s\n", tag_symlink, device_node, strerror(errno));
2635                                                 return -errno;
2636                                         } else
2637                                                 r = 0;
2638                                 }
2639                         }
2640
2641                         /* don't touch the permissions if only the tags were set */
2642                         if (mode == 0 && uid == 0 && gid == 0)
2643                                 goto next;
2644
2645                         if (mode == 0) {
2646                                 if (gid > 0)
2647                                         mode = 0660;
2648                                 else
2649                                         mode = 0600;
2650                         }
2651                         if (mode != (stats.st_mode & 01777)) {
2652                                 r = chmod(device_node, mode);
2653                                 if (r < 0) {
2654                                         log_error("failed to chmod '%s' %#o\n", device_node, mode);
2655                                         return -errno;
2656                                 } else
2657                                         log_debug("chmod '%s' %#o\n", device_node, mode);
2658                         }
2659
2660                         if ((uid != 0 && uid != stats.st_uid) || (gid != 0 && gid != stats.st_gid)) {
2661                                 r = chown(device_node, uid, gid);
2662                                 if (r < 0) {
2663                                         log_error("failed to chown '%s' %u %u \n", device_node, uid, gid);
2664                                         return -errno;
2665                                 } else
2666                                         log_debug("chown '%s' %u %u\n", device_node, uid, gid);
2667                         }
2668
2669                         utimensat(AT_FDCWD, device_node, NULL, 0);
2670                         break;
2671                 }
2672                 case TK_END:
2673                         goto finish;
2674                 }
2675
2676                 cur++;
2677                 continue;
2678 next:
2679                 /* fast-forward to next rule */
2680                 cur = rule + rule->rule.token_count;
2681                 continue;
2682         }
2683
2684 finish:
2685         if (f) {
2686                 fflush(f);
2687                 fchmod(fileno(f), 0644);
2688                 if (ferror(f) || rename(path, "/run/udev/static_node-tags") < 0) {
2689                         r = -errno;
2690                         unlink("/run/udev/static_node-tags");
2691                         unlink(path);
2692                 }
2693                 fclose(f);
2694         }
2695
2696         return r;
2697 }