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