chiark / gitweb /
fe4965feb9f38ee1301a6c3facf3773c7b25a2f4
[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                         break;
1071
1072                 if (streq(key, "ACTION")) {
1073                         if (op > OP_MATCH_MAX) {
1074                                 log_error("invalid ACTION operation\n");
1075                                 goto invalid;
1076                         }
1077                         rule_add_key(&rule_tmp, TK_M_ACTION, op, value, NULL);
1078                         continue;
1079                 }
1080
1081                 if (streq(key, "DEVPATH")) {
1082                         if (op > OP_MATCH_MAX) {
1083                                 log_error("invalid DEVPATH operation\n");
1084                                 goto invalid;
1085                         }
1086                         rule_add_key(&rule_tmp, TK_M_DEVPATH, op, value, NULL);
1087                         continue;
1088                 }
1089
1090                 if (streq(key, "KERNEL")) {
1091                         if (op > OP_MATCH_MAX) {
1092                                 log_error("invalid KERNEL operation\n");
1093                                 goto invalid;
1094                         }
1095                         rule_add_key(&rule_tmp, TK_M_KERNEL, op, value, NULL);
1096                         continue;
1097                 }
1098
1099                 if (streq(key, "SUBSYSTEM")) {
1100                         if (op > OP_MATCH_MAX) {
1101                                 log_error("invalid SUBSYSTEM operation\n");
1102                                 goto invalid;
1103                         }
1104                         /* bus, class, subsystem events should all be the same */
1105                         if (streq(value, "subsystem") ||
1106                             streq(value, "bus") ||
1107                             streq(value, "class")) {
1108                                 if (streq(value, "bus") || streq(value, "class"))
1109                                         log_error("'%s' must be specified as 'subsystem' \n"
1110                                             "please fix it in %s:%u", value, filename, lineno);
1111                                 rule_add_key(&rule_tmp, TK_M_SUBSYSTEM, op, "subsystem|class|bus", NULL);
1112                         } else
1113                                 rule_add_key(&rule_tmp, TK_M_SUBSYSTEM, op, value, NULL);
1114                         continue;
1115                 }
1116
1117                 if (streq(key, "DRIVER")) {
1118                         if (op > OP_MATCH_MAX) {
1119                                 log_error("invalid DRIVER operation\n");
1120                                 goto invalid;
1121                         }
1122                         rule_add_key(&rule_tmp, TK_M_DRIVER, op, value, NULL);
1123                         continue;
1124                 }
1125
1126                 if (startswith(key, "ATTR{")) {
1127                         attr = get_key_attribute(rules->udev, key + sizeof("ATTR")-1);
1128                         if (attr == NULL) {
1129                                 log_error("error parsing ATTR attribute\n");
1130                                 goto invalid;
1131                         }
1132                         if (op < OP_MATCH_MAX) {
1133                                 rule_add_key(&rule_tmp, TK_M_ATTR, op, value, attr);
1134                         } else {
1135                                 rule_add_key(&rule_tmp, TK_A_ATTR, op, value, attr);
1136                         }
1137                         continue;
1138                 }
1139
1140                 if (streq(key, "KERNELS")) {
1141                         if (op > OP_MATCH_MAX) {
1142                                 log_error("invalid KERNELS operation\n");
1143                                 goto invalid;
1144                         }
1145                         rule_add_key(&rule_tmp, TK_M_KERNELS, op, value, NULL);
1146                         continue;
1147                 }
1148
1149                 if (streq(key, "SUBSYSTEMS")) {
1150                         if (op > OP_MATCH_MAX) {
1151                                 log_error("invalid SUBSYSTEMS operation\n");
1152                                 goto invalid;
1153                         }
1154                         rule_add_key(&rule_tmp, TK_M_SUBSYSTEMS, op, value, NULL);
1155                         continue;
1156                 }
1157
1158                 if (streq(key, "DRIVERS")) {
1159                         if (op > OP_MATCH_MAX) {
1160                                 log_error("invalid DRIVERS operation\n");
1161                                 goto invalid;
1162                         }
1163                         rule_add_key(&rule_tmp, TK_M_DRIVERS, op, value, NULL);
1164                         continue;
1165                 }
1166
1167                 if (startswith(key, "ATTRS{")) {
1168                         if (op > OP_MATCH_MAX) {
1169                                 log_error("invalid ATTRS operation\n");
1170                                 goto invalid;
1171                         }
1172                         attr = get_key_attribute(rules->udev, key + sizeof("ATTRS")-1);
1173                         if (attr == NULL) {
1174                                 log_error("error parsing ATTRS attribute\n");
1175                                 goto invalid;
1176                         }
1177                         if (startswith(attr, "device/"))
1178                                 log_error("the 'device' link may not be available in a future kernel, "
1179                                     "please fix it in %s:%u", filename, lineno);
1180                         else if (strstr(attr, "../") != NULL)
1181                                 log_error("do not reference parent sysfs directories directly, "
1182                                     "it may break with a future kernel, please fix it in %s:%u", filename, lineno);
1183                         rule_add_key(&rule_tmp, TK_M_ATTRS, op, value, attr);
1184                         continue;
1185                 }
1186
1187                 if (streq(key, "TAGS")) {
1188                         if (op > OP_MATCH_MAX) {
1189                                 log_error("invalid TAGS operation\n");
1190                                 goto invalid;
1191                         }
1192                         rule_add_key(&rule_tmp, TK_M_TAGS, op, value, NULL);
1193                         continue;
1194                 }
1195
1196                 if (startswith(key, "ENV{")) {
1197                         attr = get_key_attribute(rules->udev, key + sizeof("ENV")-1);
1198                         if (attr == NULL) {
1199                                 log_error("error parsing ENV attribute\n");
1200                                 goto invalid;
1201                         }
1202                         if (op < OP_MATCH_MAX) {
1203                                 if (rule_add_key(&rule_tmp, TK_M_ENV, op, value, attr) != 0)
1204                                         goto invalid;
1205                         } else {
1206                                 static const char *blacklist[] = {
1207                                         "ACTION",
1208                                         "SUBSYSTEM",
1209                                         "DEVTYPE",
1210                                         "MAJOR",
1211                                         "MINOR",
1212                                         "DRIVER",
1213                                         "IFINDEX",
1214                                         "DEVNAME",
1215                                         "DEVLINKS",
1216                                         "DEVPATH",
1217                                         "TAGS",
1218                                 };
1219                                 unsigned int i;
1220
1221                                 for (i = 0; i < ELEMENTSOF(blacklist); i++) {
1222                                         if (!streq(attr, blacklist[i]))
1223                                                 continue;
1224                                         log_error("invalid ENV attribute, '%s' can not be set %s:%u\n", attr, filename, lineno);
1225                                         goto invalid;
1226                                 }
1227                                 if (rule_add_key(&rule_tmp, TK_A_ENV, op, value, attr) != 0)
1228                                         goto invalid;
1229                         }
1230                         continue;
1231                 }
1232
1233                 if (streq(key, "TAG")) {
1234                         if (op < OP_MATCH_MAX)
1235                                 rule_add_key(&rule_tmp, TK_M_TAG, op, value, NULL);
1236                         else
1237                                 rule_add_key(&rule_tmp, TK_A_TAG, op, value, NULL);
1238                         continue;
1239                 }
1240
1241                 if (streq(key, "PROGRAM")) {
1242                         rule_add_key(&rule_tmp, TK_M_PROGRAM, op, value, NULL);
1243                         continue;
1244                 }
1245
1246                 if (streq(key, "RESULT")) {
1247                         if (op > OP_MATCH_MAX) {
1248                                 log_error("invalid RESULT operation\n");
1249                                 goto invalid;
1250                         }
1251                         rule_add_key(&rule_tmp, TK_M_RESULT, op, value, NULL);
1252                         continue;
1253                 }
1254
1255                 if (startswith(key, "IMPORT")) {
1256                         attr = get_key_attribute(rules->udev, key + sizeof("IMPORT")-1);
1257                         if (attr == NULL) {
1258                                 log_error("IMPORT{} type missing, ignoring IMPORT %s:%u\n", filename, lineno);
1259                                 continue;
1260                         }
1261                         if (streq(attr, "program")) {
1262                                 /* find known built-in command */
1263                                 if (value[0] != '/') {
1264                                         enum udev_builtin_cmd cmd;
1265
1266                                         cmd = udev_builtin_lookup(value);
1267                                         if (cmd < UDEV_BUILTIN_MAX) {
1268                                                 log_debug("IMPORT found builtin '%s', replacing %s:%u\n",
1269                                                           value, filename, lineno);
1270                                                 rule_add_key(&rule_tmp, TK_M_IMPORT_BUILTIN, op, value, &cmd);
1271                                                 continue;
1272                                         }
1273                                 }
1274                                 rule_add_key(&rule_tmp, TK_M_IMPORT_PROG, op, value, NULL);
1275                         } else if (streq(attr, "builtin")) {
1276                                 enum udev_builtin_cmd cmd = udev_builtin_lookup(value);
1277
1278                                 if (cmd < UDEV_BUILTIN_MAX)
1279                                         rule_add_key(&rule_tmp, TK_M_IMPORT_BUILTIN, op, value, &cmd);
1280                                 else
1281                                         log_error("IMPORT{builtin}: '%s' unknown %s:%u\n", value, filename, lineno);
1282                         } else if (streq(attr, "file")) {
1283                                 rule_add_key(&rule_tmp, TK_M_IMPORT_FILE, op, value, NULL);
1284                         } else if (streq(attr, "db")) {
1285                                 rule_add_key(&rule_tmp, TK_M_IMPORT_DB, op, value, NULL);
1286                         } else if (streq(attr, "cmdline")) {
1287                                 rule_add_key(&rule_tmp, TK_M_IMPORT_CMDLINE, op, value, NULL);
1288                         } else if (streq(attr, "parent")) {
1289                                 rule_add_key(&rule_tmp, TK_M_IMPORT_PARENT, op, value, NULL);
1290                         } else
1291                                 log_error("IMPORT{} unknown type, ignoring IMPORT %s:%u\n", filename, lineno);
1292                         continue;
1293                 }
1294
1295                 if (startswith(key, "TEST")) {
1296                         mode_t mode = 0;
1297
1298                         if (op > OP_MATCH_MAX) {
1299                                 log_error("invalid TEST operation\n");
1300                                 goto invalid;
1301                         }
1302                         attr = get_key_attribute(rules->udev, key + sizeof("TEST")-1);
1303                         if (attr != NULL) {
1304                                 mode = strtol(attr, NULL, 8);
1305                                 rule_add_key(&rule_tmp, TK_M_TEST, op, value, &mode);
1306                         } else {
1307                                 rule_add_key(&rule_tmp, TK_M_TEST, op, value, NULL);
1308                         }
1309                         continue;
1310                 }
1311
1312                 if (startswith(key, "RUN")) {
1313                         attr = get_key_attribute(rules->udev, key + sizeof("RUN")-1);
1314                         if (attr == NULL)
1315                                 attr = "program";
1316
1317                         if (streq(attr, "builtin")) {
1318                                 enum udev_builtin_cmd cmd = udev_builtin_lookup(value);
1319
1320                                 if (cmd < UDEV_BUILTIN_MAX)
1321                                         rule_add_key(&rule_tmp, TK_A_RUN_BUILTIN, op, value, &cmd);
1322                                 else
1323                                         log_error("IMPORT{builtin}: '%s' unknown %s:%u\n", value, filename, lineno);
1324                         } else if (streq(attr, "program")) {
1325                                 enum udev_builtin_cmd cmd = UDEV_BUILTIN_MAX;
1326
1327                                 rule_add_key(&rule_tmp, TK_A_RUN_PROGRAM, op, value, &cmd);
1328                         } else {
1329                                 log_error("RUN{} unknown type, ignoring RUN %s:%u\n", filename, lineno);
1330                         }
1331
1332                         continue;
1333                 }
1334
1335                 if (streq(key, "WAIT_FOR") || streq(key, "WAIT_FOR_SYSFS")) {
1336                         rule_add_key(&rule_tmp, TK_M_WAITFOR, 0, value, NULL);
1337                         continue;
1338                 }
1339
1340                 if (streq(key, "LABEL")) {
1341                         rule_tmp.rule.rule.label_off = rules_add_string(rules, value);
1342                         continue;
1343                 }
1344
1345                 if (streq(key, "GOTO")) {
1346                         rule_add_key(&rule_tmp, TK_A_GOTO, 0, value, NULL);
1347                         continue;
1348                 }
1349
1350                 if (startswith(key, "NAME")) {
1351                         if (op < OP_MATCH_MAX) {
1352                                 rule_add_key(&rule_tmp, TK_M_NAME, op, value, NULL);
1353                         } else {
1354                                 if (streq(value, "%k")) {
1355                                         log_error("NAME=\"%%k\" is ignored, because it breaks kernel supplied names, "
1356                                             "please remove it from %s:%u\n", filename, lineno);
1357                                         continue;
1358                                 }
1359                                 if (value[0] == '\0') {
1360                                         log_debug("NAME=\"\" is ignored, because udev will not delete any device nodes, "
1361                                                   "please remove it from %s:%u\n", filename, lineno);
1362                                         continue;
1363                                 }
1364                                 rule_add_key(&rule_tmp, TK_A_NAME, op, value, NULL);
1365                         }
1366                         rule_tmp.rule.rule.can_set_name = true;
1367                         continue;
1368                 }
1369
1370                 if (streq(key, "SYMLINK")) {
1371                         if (op < OP_MATCH_MAX)
1372                                 rule_add_key(&rule_tmp, TK_M_DEVLINK, op, value, NULL);
1373                         else
1374                                 rule_add_key(&rule_tmp, TK_A_DEVLINK, op, value, NULL);
1375                         rule_tmp.rule.rule.can_set_name = true;
1376                         continue;
1377                 }
1378
1379                 if (streq(key, "OWNER")) {
1380                         uid_t uid;
1381                         char *endptr;
1382
1383                         uid = strtoul(value, &endptr, 10);
1384                         if (endptr[0] == '\0') {
1385                                 rule_add_key(&rule_tmp, TK_A_OWNER_ID, op, NULL, &uid);
1386                         } else if ((rules->resolve_names > 0) && strchr("$%", value[0]) == NULL) {
1387                                 uid = add_uid(rules, value);
1388                                 rule_add_key(&rule_tmp, TK_A_OWNER_ID, op, NULL, &uid);
1389                         } else if (rules->resolve_names >= 0) {
1390                                 rule_add_key(&rule_tmp, TK_A_OWNER, op, value, NULL);
1391                         }
1392                         rule_tmp.rule.rule.can_set_name = true;
1393                         continue;
1394                 }
1395
1396                 if (streq(key, "GROUP")) {
1397                         gid_t gid;
1398                         char *endptr;
1399
1400                         gid = strtoul(value, &endptr, 10);
1401                         if (endptr[0] == '\0') {
1402                                 rule_add_key(&rule_tmp, TK_A_GROUP_ID, op, NULL, &gid);
1403                         } else if ((rules->resolve_names > 0) && strchr("$%", value[0]) == NULL) {
1404                                 gid = add_gid(rules, value);
1405                                 rule_add_key(&rule_tmp, TK_A_GROUP_ID, op, NULL, &gid);
1406                         } else if (rules->resolve_names >= 0) {
1407                                 rule_add_key(&rule_tmp, TK_A_GROUP, op, value, NULL);
1408                         }
1409                         rule_tmp.rule.rule.can_set_name = true;
1410                         continue;
1411                 }
1412
1413                 if (streq(key, "MODE")) {
1414                         mode_t mode;
1415                         char *endptr;
1416
1417                         mode = strtol(value, &endptr, 8);
1418                         if (endptr[0] == '\0')
1419                                 rule_add_key(&rule_tmp, TK_A_MODE_ID, op, NULL, &mode);
1420                         else
1421                                 rule_add_key(&rule_tmp, TK_A_MODE, op, value, NULL);
1422                         rule_tmp.rule.rule.can_set_name = true;
1423                         continue;
1424                 }
1425
1426                 if (streq(key, "OPTIONS")) {
1427                         const char *pos;
1428
1429                         pos = strstr(value, "link_priority=");
1430                         if (pos != NULL) {
1431                                 int prio = atoi(&pos[strlen("link_priority=")]);
1432
1433                                 rule_add_key(&rule_tmp, TK_A_DEVLINK_PRIO, op, NULL, &prio);
1434                         }
1435
1436                         pos = strstr(value, "event_timeout=");
1437                         if (pos != NULL) {
1438                                 int tout = atoi(&pos[strlen("event_timeout=")]);
1439
1440                                 rule_add_key(&rule_tmp, TK_M_EVENT_TIMEOUT, op, NULL, &tout);
1441                         }
1442
1443                         pos = strstr(value, "string_escape=");
1444                         if (pos != NULL) {
1445                                 pos = &pos[strlen("string_escape=")];
1446                                 if (startswith(pos, "none"))
1447                                         rule_add_key(&rule_tmp, TK_A_STRING_ESCAPE_NONE, op, NULL, NULL);
1448                                 else if (startswith(pos, "replace"))
1449                                         rule_add_key(&rule_tmp, TK_A_STRING_ESCAPE_REPLACE, op, NULL, NULL);
1450                         }
1451
1452                         pos = strstr(value, "db_persist");
1453                         if (pos != NULL)
1454                                 rule_add_key(&rule_tmp, TK_A_DB_PERSIST, op, NULL, NULL);
1455
1456                         pos = strstr(value, "nowatch");
1457                         if (pos != NULL) {
1458                                 const int off = 0;
1459
1460                                 rule_add_key(&rule_tmp, TK_A_INOTIFY_WATCH, op, NULL, &off);
1461                         } else {
1462                                 pos = strstr(value, "watch");
1463                                 if (pos != NULL) {
1464                                         const int on = 1;
1465
1466                                         rule_add_key(&rule_tmp, TK_A_INOTIFY_WATCH, op, NULL, &on);
1467                                 }
1468                         }
1469
1470                         pos = strstr(value, "static_node=");
1471                         if (pos != NULL) {
1472                                 rule_add_key(&rule_tmp, TK_A_STATIC_NODE, op, &pos[strlen("static_node=")], NULL);
1473                                 rule_tmp.rule.rule.has_static_node = true;
1474                         }
1475
1476                         continue;
1477                 }
1478
1479                 log_error("unknown key '%s' in %s:%u\n", key, filename, lineno);
1480                 goto invalid;
1481         }
1482
1483         /* add rule token */
1484         rule_tmp.rule.rule.token_count = 1 + rule_tmp.token_cur;
1485         if (add_token(rules, &rule_tmp.rule) != 0)
1486                 goto invalid;
1487
1488         /* add tokens to list, sorted by type */
1489         if (sort_token(rules, &rule_tmp) != 0)
1490                 goto invalid;
1491
1492         return 0;
1493 invalid:
1494         log_error("invalid rule '%s:%u'\n", filename, lineno);
1495         return -1;
1496 }
1497
1498 static int parse_file(struct udev_rules *rules, const char *filename)
1499 {
1500         FILE *f;
1501         unsigned int first_token;
1502         unsigned int filename_off;
1503         char line[UTIL_LINE_SIZE];
1504         int line_nr = 0;
1505         unsigned int i;
1506
1507         if (null_or_empty_path(filename)) {
1508                 log_debug("skip empty file: %s\n", filename);
1509                 return 0;
1510         }
1511         log_debug("read rules file: %s\n", filename);
1512
1513         f = fopen(filename, "re");
1514         if (f == NULL)
1515                 return -1;
1516
1517         first_token = rules->token_cur;
1518         filename_off = rules_add_string(rules, filename);
1519
1520         while (fgets(line, sizeof(line), f) != NULL) {
1521                 char *key;
1522                 size_t len;
1523
1524                 /* skip whitespace */
1525                 line_nr++;
1526                 key = line;
1527                 while (isspace(key[0]))
1528                         key++;
1529
1530                 /* comment */
1531                 if (key[0] == '#')
1532                         continue;
1533
1534                 len = strlen(line);
1535                 if (len < 3)
1536                         continue;
1537
1538                 /* continue reading if backslash+newline is found */
1539                 while (line[len-2] == '\\') {
1540                         if (fgets(&line[len-2], (sizeof(line)-len)+2, f) == NULL)
1541                                 break;
1542                         if (strlen(&line[len-2]) < 2)
1543                                 break;
1544                         line_nr++;
1545                         len = strlen(line);
1546                 }
1547
1548                 if (len+1 >= sizeof(line)) {
1549                         log_error("line too long '%s':%u, ignored\n", filename, line_nr);
1550                         continue;
1551                 }
1552                 add_rule(rules, key, filename, filename_off, line_nr);
1553         }
1554         fclose(f);
1555
1556         /* link GOTOs to LABEL rules in this file to be able to fast-forward */
1557         for (i = first_token+1; i < rules->token_cur; i++) {
1558                 if (rules->tokens[i].type == TK_A_GOTO) {
1559                         char *label = rules_str(rules, rules->tokens[i].key.value_off);
1560                         unsigned int j;
1561
1562                         for (j = i+1; j < rules->token_cur; j++) {
1563                                 if (rules->tokens[j].type != TK_RULE)
1564                                         continue;
1565                                 if (rules->tokens[j].rule.label_off == 0)
1566                                         continue;
1567                                 if (!streq(label, rules_str(rules, rules->tokens[j].rule.label_off)))
1568                                         continue;
1569                                 rules->tokens[i].key.rule_goto = j;
1570                                 break;
1571                         }
1572                         if (rules->tokens[i].key.rule_goto == 0)
1573                                 log_error("GOTO '%s' has no matching label in: '%s'\n", label, filename);
1574                 }
1575         }
1576         return 0;
1577 }
1578
1579 struct udev_rules *udev_rules_new(struct udev *udev, int resolve_names)
1580 {
1581         struct udev_rules *rules;
1582         struct udev_list file_list;
1583         struct token end_token;
1584         char **files, **f;
1585         int r;
1586
1587         rules = calloc(1, sizeof(struct udev_rules));
1588         if (rules == NULL)
1589                 return NULL;
1590         rules->udev = udev;
1591         rules->resolve_names = resolve_names;
1592         udev_list_init(udev, &file_list, true);
1593
1594         /* init token array and string buffer */
1595         rules->tokens = malloc(PREALLOC_TOKEN * sizeof(struct token));
1596         if (rules->tokens == NULL)
1597                 return udev_rules_unref(rules);
1598         rules->token_max = PREALLOC_TOKEN;
1599
1600         rules->strbuf = strbuf_new();
1601         if (!rules->strbuf)
1602                 return udev_rules_unref(rules);
1603
1604         rules->dirs = strv_new("/etc/udev/rules.d",
1605                                "/run/udev/rules.d",
1606                                UDEVLIBEXECDIR "/rules.d",
1607                                NULL);
1608         if (!rules->dirs) {
1609                 log_error("failed to build config directory array");
1610                 return udev_rules_unref(rules);
1611         }
1612         if (!path_strv_canonicalize(rules->dirs)) {
1613                 log_error("failed to canonicalize config directories\n");
1614                 return udev_rules_unref(rules);
1615         }
1616         strv_uniq(rules->dirs);
1617
1618         rules->dirs_ts_usec = calloc(strv_length(rules->dirs), sizeof(usec_t));
1619         if(!rules->dirs_ts_usec)
1620                 return udev_rules_unref(rules);
1621         udev_rules_check_timestamp(rules);
1622
1623         r = conf_files_list_strv(&files, ".rules", NULL, (const char **)rules->dirs);
1624         if (r < 0) {
1625                 log_error("failed to enumerate rules files: %s\n", strerror(-r));
1626                 return udev_rules_unref(rules);
1627         }
1628
1629         /*
1630          * The offset value in the rules strct is limited; add all
1631          * rules file names to the beginning of the string buffer.
1632          */
1633         STRV_FOREACH(f, files)
1634                 rules_add_string(rules, *f);
1635
1636         STRV_FOREACH(f, files)
1637                 parse_file(rules, *f);
1638
1639         strv_free(files);
1640
1641         memset(&end_token, 0x00, sizeof(struct token));
1642         end_token.type = TK_END;
1643         add_token(rules, &end_token);
1644         log_debug("rules contain %zu bytes tokens (%u * %zu bytes), %zu bytes strings\n",
1645                   rules->token_max * sizeof(struct token), rules->token_max, sizeof(struct token), rules->strbuf->len);
1646
1647         /* cleanup temporary strbuf data */
1648         log_debug("%zu strings (%zu bytes), %zu de-duplicated (%zu bytes), %zu trie nodes used\n",
1649                   rules->strbuf->in_count, rules->strbuf->in_len,
1650                   rules->strbuf->dedup_count, rules->strbuf->dedup_len, rules->strbuf->nodes_count);
1651         strbuf_complete(rules->strbuf);
1652
1653         /* cleanup uid/gid cache */
1654         free(rules->uids);
1655         rules->uids = NULL;
1656         rules->uids_cur = 0;
1657         rules->uids_max = 0;
1658         free(rules->gids);
1659         rules->gids = NULL;
1660         rules->gids_cur = 0;
1661         rules->gids_max = 0;
1662
1663         dump_rules(rules);
1664         return rules;
1665 }
1666
1667 struct udev_rules *udev_rules_unref(struct udev_rules *rules)
1668 {
1669         if (rules == NULL)
1670                 return NULL;
1671         free(rules->tokens);
1672         strbuf_cleanup(rules->strbuf);
1673         free(rules->uids);
1674         free(rules->gids);
1675         strv_free(rules->dirs);
1676         free(rules->dirs_ts_usec);
1677         free(rules);
1678         return NULL;
1679 }
1680
1681 bool udev_rules_check_timestamp(struct udev_rules *rules)
1682 {
1683         unsigned int i;
1684         bool changed = false;
1685
1686         if (rules == NULL)
1687                 goto out;
1688
1689         for (i = 0; rules->dirs[i]; i++) {
1690                 struct stat stats;
1691
1692                 if (stat(rules->dirs[i], &stats) < 0)
1693                         continue;
1694
1695                 if (rules->dirs_ts_usec[i] == timespec_load(&stats.st_mtim))
1696                         continue;
1697
1698                 /* first check */
1699                 if (rules->dirs_ts_usec[i] != 0) {
1700                         log_debug("reload - timestamp of '%s' changed\n", rules->dirs[i]);
1701                         changed = true;
1702                 }
1703
1704                 /* update timestamp */
1705                 rules->dirs_ts_usec[i] = timespec_load(&stats.st_mtim);
1706         }
1707 out:
1708         return changed;
1709 }
1710
1711 static int match_key(struct udev_rules *rules, struct token *token, const char *val)
1712 {
1713         char *key_value = rules_str(rules, token->key.value_off);
1714         char *pos;
1715         bool match = false;
1716
1717         if (val == NULL)
1718                 val = "";
1719
1720         switch (token->key.glob) {
1721         case GL_PLAIN:
1722                 match = (streq(key_value, val));
1723                 break;
1724         case GL_GLOB:
1725                 match = (fnmatch(key_value, val, 0) == 0);
1726                 break;
1727         case GL_SPLIT:
1728                 {
1729                         const char *s;
1730                         size_t len;
1731
1732                         s = rules_str(rules, token->key.value_off);
1733                         len = strlen(val);
1734                         for (;;) {
1735                                 const char *next;
1736
1737                                 next = strchr(s, '|');
1738                                 if (next != NULL) {
1739                                         size_t matchlen = (size_t)(next - s);
1740
1741                                         match = (matchlen == len && strneq(s, val, matchlen));
1742                                         if (match)
1743                                                 break;
1744                                 } else {
1745                                         match = (streq(s, val));
1746                                         break;
1747                                 }
1748                                 s = &next[1];
1749                         }
1750                         break;
1751                 }
1752         case GL_SPLIT_GLOB:
1753                 {
1754                         char value[UTIL_PATH_SIZE];
1755
1756                         strscpy(value, sizeof(value), rules_str(rules, token->key.value_off));
1757                         key_value = value;
1758                         while (key_value != NULL) {
1759                                 pos = strchr(key_value, '|');
1760                                 if (pos != NULL) {
1761                                         pos[0] = '\0';
1762                                         pos = &pos[1];
1763                                 }
1764                                 match = (fnmatch(key_value, val, 0) == 0);
1765                                 if (match)
1766                                         break;
1767                                 key_value = pos;
1768                         }
1769                         break;
1770                 }
1771         case GL_SOMETHING:
1772                 match = (val[0] != '\0');
1773                 break;
1774         case GL_UNSET:
1775                 return -1;
1776         }
1777
1778         if (match && (token->key.op == OP_MATCH))
1779                 return 0;
1780         if (!match && (token->key.op == OP_NOMATCH))
1781                 return 0;
1782         return -1;
1783 }
1784
1785 static int match_attr(struct udev_rules *rules, struct udev_device *dev, struct udev_event *event, struct token *cur)
1786 {
1787         const char *name;
1788         char nbuf[UTIL_NAME_SIZE];
1789         const char *value;
1790         char vbuf[UTIL_NAME_SIZE];
1791         size_t len;
1792
1793         name = rules_str(rules, cur->key.attr_off);
1794         switch (cur->key.attrsubst) {
1795         case SB_FORMAT:
1796                 udev_event_apply_format(event, name, nbuf, sizeof(nbuf));
1797                 name = nbuf;
1798                 /* fall through */
1799         case SB_NONE:
1800                 value = udev_device_get_sysattr_value(dev, name);
1801                 if (value == NULL)
1802                         return -1;
1803                 break;
1804         case SB_SUBSYS:
1805                 if (util_resolve_subsys_kernel(event->udev, name, vbuf, sizeof(vbuf), 1) != 0)
1806                         return -1;
1807                 value = vbuf;
1808                 break;
1809         default:
1810                 return -1;
1811         }
1812
1813         /* remove trailing whitespace, if not asked to match for it */
1814         len = strlen(value);
1815         if (len > 0 && isspace(value[len-1])) {
1816                 const char *key_value;
1817                 size_t klen;
1818
1819                 key_value = rules_str(rules, cur->key.value_off);
1820                 klen = strlen(key_value);
1821                 if (klen > 0 && !isspace(key_value[klen-1])) {
1822                         if (value != vbuf) {
1823                                 strscpy(vbuf, sizeof(vbuf), value);
1824                                 value = vbuf;
1825                         }
1826                         while (len > 0 && isspace(vbuf[--len]))
1827                                 vbuf[len] = '\0';
1828                 }
1829         }
1830
1831         return match_key(rules, cur, value);
1832 }
1833
1834 enum escape_type {
1835         ESCAPE_UNSET,
1836         ESCAPE_NONE,
1837         ESCAPE_REPLACE,
1838 };
1839
1840 int udev_rules_apply_to_event(struct udev_rules *rules, struct udev_event *event, const sigset_t *sigmask)
1841 {
1842         struct token *cur;
1843         struct token *rule;
1844         enum escape_type esc = ESCAPE_UNSET;
1845         bool can_set_name;
1846
1847         if (rules->tokens == NULL)
1848                 return -1;
1849
1850         can_set_name = ((!streq(udev_device_get_action(event->dev), "remove")) &&
1851                         (major(udev_device_get_devnum(event->dev)) > 0 ||
1852                          udev_device_get_ifindex(event->dev) > 0));
1853
1854         /* loop through token list, match, run actions or forward to next rule */
1855         cur = &rules->tokens[0];
1856         rule = cur;
1857         for (;;) {
1858                 dump_token(rules, cur);
1859                 switch (cur->type) {
1860                 case TK_RULE:
1861                         /* current rule */
1862                         rule = cur;
1863                         /* possibly skip rules which want to set NAME, SYMLINK, OWNER, GROUP, MODE */
1864                         if (!can_set_name && rule->rule.can_set_name)
1865                                 goto nomatch;
1866                         esc = ESCAPE_UNSET;
1867                         break;
1868                 case TK_M_ACTION:
1869                         if (match_key(rules, cur, udev_device_get_action(event->dev)) != 0)
1870                                 goto nomatch;
1871                         break;
1872                 case TK_M_DEVPATH:
1873                         if (match_key(rules, cur, udev_device_get_devpath(event->dev)) != 0)
1874                                 goto nomatch;
1875                         break;
1876                 case TK_M_KERNEL:
1877                         if (match_key(rules, cur, udev_device_get_sysname(event->dev)) != 0)
1878                                 goto nomatch;
1879                         break;
1880                 case TK_M_DEVLINK: {
1881                         struct udev_list_entry *list_entry;
1882                         bool match = false;
1883
1884                         udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(event->dev)) {
1885                                 const char *devlink;
1886
1887                                 devlink =  udev_list_entry_get_name(list_entry) + strlen("/dev/");
1888                                 if (match_key(rules, cur, devlink) == 0) {
1889                                         match = true;
1890                                         break;
1891                                 }
1892                         }
1893                         if (!match)
1894                                 goto nomatch;
1895                         break;
1896                 }
1897                 case TK_M_NAME:
1898                         if (match_key(rules, cur, event->name) != 0)
1899                                 goto nomatch;
1900                         break;
1901                 case TK_M_ENV: {
1902                         const char *key_name = rules_str(rules, cur->key.attr_off);
1903                         const char *value;
1904
1905                         value = udev_device_get_property_value(event->dev, key_name);
1906                         if (value == NULL)
1907                                 value = "";
1908                         if (match_key(rules, cur, value))
1909                                 goto nomatch;
1910                         break;
1911                 }
1912                 case TK_M_TAG: {
1913                         struct udev_list_entry *list_entry;
1914                         bool match = false;
1915
1916                         udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(event->dev)) {
1917                                 if (streq(rules_str(rules, cur->key.value_off), udev_list_entry_get_name(list_entry))) {
1918                                         match = true;
1919                                         break;
1920                                 }
1921                         }
1922                         if (!match && (cur->key.op != OP_NOMATCH))
1923                                 goto nomatch;
1924                         break;
1925                 }
1926                 case TK_M_SUBSYSTEM:
1927                         if (match_key(rules, cur, udev_device_get_subsystem(event->dev)) != 0)
1928                                 goto nomatch;
1929                         break;
1930                 case TK_M_DRIVER:
1931                         if (match_key(rules, cur, udev_device_get_driver(event->dev)) != 0)
1932                                 goto nomatch;
1933                         break;
1934                 case TK_M_WAITFOR: {
1935                         char filename[UTIL_PATH_SIZE];
1936                         int found;
1937
1938                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), filename, sizeof(filename));
1939                         found = (wait_for_file(event->dev, filename, 10) == 0);
1940                         if (!found && (cur->key.op != OP_NOMATCH))
1941                                 goto nomatch;
1942                         break;
1943                 }
1944                 case TK_M_ATTR:
1945                         if (match_attr(rules, event->dev, event, cur) != 0)
1946                                 goto nomatch;
1947                         break;
1948                 case TK_M_KERNELS:
1949                 case TK_M_SUBSYSTEMS:
1950                 case TK_M_DRIVERS:
1951                 case TK_M_ATTRS:
1952                 case TK_M_TAGS: {
1953                         struct token *next;
1954
1955                         /* get whole sequence of parent matches */
1956                         next = cur;
1957                         while (next->type > TK_M_PARENTS_MIN && next->type < TK_M_PARENTS_MAX)
1958                                 next++;
1959
1960                         /* loop over parents */
1961                         event->dev_parent = event->dev;
1962                         for (;;) {
1963                                 struct token *key;
1964
1965                                 /* loop over sequence of parent match keys */
1966                                 for (key = cur; key < next; key++ ) {
1967                                         dump_token(rules, key);
1968                                         switch(key->type) {
1969                                         case TK_M_KERNELS:
1970                                                 if (match_key(rules, key, udev_device_get_sysname(event->dev_parent)) != 0)
1971                                                         goto try_parent;
1972                                                 break;
1973                                         case TK_M_SUBSYSTEMS:
1974                                                 if (match_key(rules, key, udev_device_get_subsystem(event->dev_parent)) != 0)
1975                                                         goto try_parent;
1976                                                 break;
1977                                         case TK_M_DRIVERS:
1978                                                 if (match_key(rules, key, udev_device_get_driver(event->dev_parent)) != 0)
1979                                                         goto try_parent;
1980                                                 break;
1981                                         case TK_M_ATTRS:
1982                                                 if (match_attr(rules, event->dev_parent, event, key) != 0)
1983                                                         goto try_parent;
1984                                                 break;
1985                                         case TK_M_TAGS: {
1986                                                 bool match = udev_device_has_tag(event->dev_parent, rules_str(rules, cur->key.value_off));
1987
1988                                                 if (match && key->key.op == OP_NOMATCH)
1989                                                         goto try_parent;
1990                                                 if (!match && key->key.op == OP_MATCH)
1991                                                         goto try_parent;
1992                                                 break;
1993                                         }
1994                                         default:
1995                                                 goto nomatch;
1996                                         }
1997                                 }
1998                                 break;
1999
2000                         try_parent:
2001                                 event->dev_parent = udev_device_get_parent(event->dev_parent);
2002                                 if (event->dev_parent == NULL)
2003                                         goto nomatch;
2004                         }
2005                         /* move behind our sequence of parent match keys */
2006                         cur = next;
2007                         continue;
2008                 }
2009                 case TK_M_TEST: {
2010                         char filename[UTIL_PATH_SIZE];
2011                         struct stat statbuf;
2012                         int match;
2013
2014                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), filename, sizeof(filename));
2015                         if (util_resolve_subsys_kernel(event->udev, filename, filename, sizeof(filename), 0) != 0) {
2016                                 if (filename[0] != '/') {
2017                                         char tmp[UTIL_PATH_SIZE];
2018
2019                                         strscpy(tmp, sizeof(tmp), filename);
2020                                         strscpyl(filename, sizeof(filename),
2021                                                       udev_device_get_syspath(event->dev), "/", tmp, NULL);
2022                                 }
2023                         }
2024                         attr_subst_subdir(filename, sizeof(filename));
2025
2026                         match = (stat(filename, &statbuf) == 0);
2027                         if (match && cur->key.mode > 0)
2028                                 match = ((statbuf.st_mode & cur->key.mode) > 0);
2029                         if (match && cur->key.op == OP_NOMATCH)
2030                                 goto nomatch;
2031                         if (!match && cur->key.op == OP_MATCH)
2032                                 goto nomatch;
2033                         break;
2034                 }
2035                 case TK_M_EVENT_TIMEOUT:
2036                         log_debug("OPTIONS event_timeout=%u\n", cur->key.event_timeout);
2037                         event->timeout_usec = cur->key.event_timeout * 1000 * 1000;
2038                         break;
2039                 case TK_M_PROGRAM: {
2040                         char program[UTIL_PATH_SIZE];
2041                         char **envp;
2042                         char result[UTIL_PATH_SIZE];
2043
2044                         free(event->program_result);
2045                         event->program_result = NULL;
2046                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), program, sizeof(program));
2047                         envp = udev_device_get_properties_envp(event->dev);
2048                         log_debug("PROGRAM '%s' %s:%u\n",
2049                                   program,
2050                                   rules_str(rules, rule->rule.filename_off),
2051                                   rule->rule.filename_line);
2052
2053                         if (udev_event_spawn(event, program, envp, sigmask, result, sizeof(result)) < 0) {
2054                                 if (cur->key.op != OP_NOMATCH)
2055                                         goto nomatch;
2056                         } else {
2057                                 int count;
2058
2059                                 util_remove_trailing_chars(result, '\n');
2060                                 if (esc == ESCAPE_UNSET || esc == ESCAPE_REPLACE) {
2061                                         count = util_replace_chars(result, UDEV_ALLOWED_CHARS_INPUT);
2062                                         if (count > 0)
2063                                                 log_debug("%i character(s) replaced\n" , count);
2064                                 }
2065                                 event->program_result = strdup(result);
2066                                 if (cur->key.op == OP_NOMATCH)
2067                                         goto nomatch;
2068                         }
2069                         break;
2070                 }
2071                 case TK_M_IMPORT_FILE: {
2072                         char import[UTIL_PATH_SIZE];
2073
2074                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), import, sizeof(import));
2075                         if (import_file_into_properties(event->dev, import) != 0)
2076                                 if (cur->key.op != OP_NOMATCH)
2077                                         goto nomatch;
2078                         break;
2079                 }
2080                 case TK_M_IMPORT_PROG: {
2081                         char import[UTIL_PATH_SIZE];
2082
2083                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), import, sizeof(import));
2084                         log_debug("IMPORT '%s' %s:%u\n",
2085                                   import,
2086                                   rules_str(rules, rule->rule.filename_off),
2087                                   rule->rule.filename_line);
2088
2089                         if (import_program_into_properties(event, import, sigmask) != 0)
2090                                 if (cur->key.op != OP_NOMATCH)
2091                                         goto nomatch;
2092                         break;
2093                 }
2094                 case TK_M_IMPORT_BUILTIN: {
2095                         char command[UTIL_PATH_SIZE];
2096
2097                         if (udev_builtin_run_once(cur->key.builtin_cmd)) {
2098                                 /* check if we ran already */
2099                                 if (event->builtin_run & (1 << cur->key.builtin_cmd)) {
2100                                         log_debug("IMPORT builtin skip '%s' %s:%u\n",
2101                                                   udev_builtin_name(cur->key.builtin_cmd),
2102                                                   rules_str(rules, rule->rule.filename_off),
2103                                                   rule->rule.filename_line);
2104                                         /* return the result from earlier run */
2105                                         if (event->builtin_ret & (1 << cur->key.builtin_cmd))
2106                                         if (cur->key.op != OP_NOMATCH)
2107                                                         goto nomatch;
2108                                         break;
2109                                 }
2110                                 /* mark as ran */
2111                                 event->builtin_run |= (1 << cur->key.builtin_cmd);
2112                         }
2113
2114                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), command, sizeof(command));
2115                         log_debug("IMPORT builtin '%s' %s:%u\n",
2116                                   udev_builtin_name(cur->key.builtin_cmd),
2117                                   rules_str(rules, rule->rule.filename_off),
2118                                   rule->rule.filename_line);
2119
2120                         if (udev_builtin_run(event->dev, cur->key.builtin_cmd, command, false) != 0) {
2121                                 /* remember failure */
2122                                 log_debug("IMPORT builtin '%s' returned non-zero\n",
2123                                           udev_builtin_name(cur->key.builtin_cmd));
2124                                 event->builtin_ret |= (1 << cur->key.builtin_cmd);
2125                                 if (cur->key.op != OP_NOMATCH)
2126                                         goto nomatch;
2127                         }
2128                         break;
2129                 }
2130                 case TK_M_IMPORT_DB: {
2131                         const char *key = rules_str(rules, cur->key.value_off);
2132                         const char *value;
2133
2134                         value = udev_device_get_property_value(event->dev_db, key);
2135                         if (value != NULL) {
2136                                 struct udev_list_entry *entry;
2137
2138                                 entry = udev_device_add_property(event->dev, key, value);
2139                                 udev_list_entry_set_num(entry, true);
2140                         } else {
2141                                 if (cur->key.op != OP_NOMATCH)
2142                                         goto nomatch;
2143                         }
2144                         break;
2145                 }
2146                 case TK_M_IMPORT_CMDLINE: {
2147                         FILE *f;
2148                         bool imported = false;
2149
2150                         f = fopen("/proc/cmdline", "re");
2151                         if (f != NULL) {
2152                                 char cmdline[4096];
2153
2154                                 if (fgets(cmdline, sizeof(cmdline), f) != NULL) {
2155                                         const char *key = rules_str(rules, cur->key.value_off);
2156                                         char *pos;
2157
2158                                         pos = strstr(cmdline, key);
2159                                         if (pos != NULL) {
2160                                                 struct udev_list_entry *entry;
2161
2162                                                 pos += strlen(key);
2163                                                 if (pos[0] == '\0' || isspace(pos[0])) {
2164                                                         /* we import simple flags as 'FLAG=1' */
2165                                                         entry = udev_device_add_property(event->dev, key, "1");
2166                                                         udev_list_entry_set_num(entry, true);
2167                                                         imported = true;
2168                                                 } else if (pos[0] == '=') {
2169                                                         const char *value;
2170
2171                                                         pos++;
2172                                                         value = pos;
2173                                                         while (pos[0] != '\0' && !isspace(pos[0]))
2174                                                                 pos++;
2175                                                         pos[0] = '\0';
2176                                                         entry = udev_device_add_property(event->dev, key, value);
2177                                                         udev_list_entry_set_num(entry, true);
2178                                                         imported = true;
2179                                                 }
2180                                         }
2181                                 }
2182                                 fclose(f);
2183                         }
2184                         if (!imported && cur->key.op != OP_NOMATCH)
2185                                 goto nomatch;
2186                         break;
2187                 }
2188                 case TK_M_IMPORT_PARENT: {
2189                         char import[UTIL_PATH_SIZE];
2190
2191                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), import, sizeof(import));
2192                         if (import_parent_into_properties(event->dev, import) != 0)
2193                                 if (cur->key.op != OP_NOMATCH)
2194                                         goto nomatch;
2195                         break;
2196                 }
2197                 case TK_M_RESULT:
2198                         if (match_key(rules, cur, event->program_result) != 0)
2199                                 goto nomatch;
2200                         break;
2201                 case TK_A_STRING_ESCAPE_NONE:
2202                         esc = ESCAPE_NONE;
2203                         break;
2204                 case TK_A_STRING_ESCAPE_REPLACE:
2205                         esc = ESCAPE_REPLACE;
2206                         break;
2207                 case TK_A_DB_PERSIST:
2208                         udev_device_set_db_persist(event->dev);
2209                         break;
2210                 case TK_A_INOTIFY_WATCH:
2211                         if (event->inotify_watch_final)
2212                                 break;
2213                         if (cur->key.op == OP_ASSIGN_FINAL)
2214                                 event->inotify_watch_final = true;
2215                         event->inotify_watch = cur->key.watch;
2216                         break;
2217                 case TK_A_DEVLINK_PRIO:
2218                         udev_device_set_devlink_priority(event->dev, cur->key.devlink_prio);
2219                         break;
2220                 case TK_A_OWNER: {
2221                         char owner[UTIL_NAME_SIZE];
2222
2223                         if (event->owner_final)
2224                                 break;
2225                         if (cur->key.op == OP_ASSIGN_FINAL)
2226                                 event->owner_final = true;
2227                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), owner, sizeof(owner));
2228                         event->owner_set = true;
2229                         event->uid = util_lookup_user(event->udev, owner);
2230                         log_debug("OWNER %u %s:%u\n",
2231                                   event->uid,
2232                                   rules_str(rules, rule->rule.filename_off),
2233                                   rule->rule.filename_line);
2234                         break;
2235                 }
2236                 case TK_A_GROUP: {
2237                         char group[UTIL_NAME_SIZE];
2238
2239                         if (event->group_final)
2240                                 break;
2241                         if (cur->key.op == OP_ASSIGN_FINAL)
2242                                 event->group_final = true;
2243                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), group, sizeof(group));
2244                         event->group_set = true;
2245                         event->gid = util_lookup_group(event->udev, group);
2246                         log_debug("GROUP %u %s:%u\n",
2247                                   event->gid,
2248                                   rules_str(rules, rule->rule.filename_off),
2249                                   rule->rule.filename_line);
2250                         break;
2251                 }
2252                 case TK_A_MODE: {
2253                         char mode_str[UTIL_NAME_SIZE];
2254                         mode_t mode;
2255                         char *endptr;
2256
2257                         if (event->mode_final)
2258                                 break;
2259                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), mode_str, sizeof(mode_str));
2260                         mode = strtol(mode_str, &endptr, 8);
2261                         if (endptr[0] != '\0') {
2262                                 log_error("ignoring invalid mode '%s'\n", mode_str);
2263                                 break;
2264                         }
2265                         if (cur->key.op == OP_ASSIGN_FINAL)
2266                                 event->mode_final = true;
2267                         event->mode_set = true;
2268                         event->mode = mode;
2269                         log_debug("MODE %#o %s:%u\n",
2270                                   event->mode,
2271                                   rules_str(rules, rule->rule.filename_off),
2272                                   rule->rule.filename_line);
2273                         break;
2274                 }
2275                 case TK_A_OWNER_ID:
2276                         if (event->owner_final)
2277                                 break;
2278                         if (cur->key.op == OP_ASSIGN_FINAL)
2279                                 event->owner_final = true;
2280                         event->owner_set = true;
2281                         event->uid = cur->key.uid;
2282                         log_debug("OWNER %u %s:%u\n",
2283                                   event->uid,
2284                                   rules_str(rules, rule->rule.filename_off),
2285                                   rule->rule.filename_line);
2286                         break;
2287                 case TK_A_GROUP_ID:
2288                         if (event->group_final)
2289                                 break;
2290                         if (cur->key.op == OP_ASSIGN_FINAL)
2291                                 event->group_final = true;
2292                         event->group_set = true;
2293                         event->gid = cur->key.gid;
2294                         log_debug("GROUP %u %s:%u\n",
2295                                   event->gid,
2296                                   rules_str(rules, rule->rule.filename_off),
2297                                   rule->rule.filename_line);
2298                         break;
2299                 case TK_A_MODE_ID:
2300                         if (event->mode_final)
2301                                 break;
2302                         if (cur->key.op == OP_ASSIGN_FINAL)
2303                                 event->mode_final = true;
2304                         event->mode_set = true;
2305                         event->mode = cur->key.mode;
2306                         log_debug("MODE %#o %s:%u\n",
2307                                   event->mode,
2308                                   rules_str(rules, rule->rule.filename_off),
2309                                   rule->rule.filename_line);
2310                         break;
2311                 case TK_A_ENV: {
2312                         const char *name = rules_str(rules, cur->key.attr_off);
2313                         char *value = rules_str(rules, cur->key.value_off);
2314                         char value_new[UTIL_NAME_SIZE];
2315                         const char *value_old = NULL;
2316                         struct udev_list_entry *entry;
2317
2318                         if (value[0] == '\0') {
2319                                 if (cur->key.op == OP_ADD)
2320                                         break;
2321                                 udev_device_add_property(event->dev, name, NULL);
2322                                 break;
2323                         }
2324
2325                         if (cur->key.op == OP_ADD)
2326                                 value_old = udev_device_get_property_value(event->dev, name);
2327                         if (value_old) {
2328                                 char temp[UTIL_NAME_SIZE];
2329
2330                                 /* append value separated by space */
2331                                 udev_event_apply_format(event, value, temp, sizeof(temp));
2332                                 strscpyl(value_new, sizeof(value_new), value_old, " ", temp, NULL);
2333                         } else
2334                                 udev_event_apply_format(event, value, value_new, sizeof(value_new));
2335
2336                         entry = udev_device_add_property(event->dev, name, value_new);
2337                         /* store in db, skip private keys */
2338                         if (name[0] != '.')
2339                                 udev_list_entry_set_num(entry, true);
2340                         break;
2341                 }
2342                 case TK_A_TAG: {
2343                         char tag[UTIL_PATH_SIZE];
2344                         const char *p;
2345
2346                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), tag, sizeof(tag));
2347                         if (cur->key.op == OP_ASSIGN || cur->key.op == OP_ASSIGN_FINAL)
2348                                 udev_device_cleanup_tags_list(event->dev);
2349                         for (p = tag; *p != '\0'; p++) {
2350                                 if ((*p >= 'a' && *p <= 'z') ||
2351                                     (*p >= 'A' && *p <= 'Z') ||
2352                                     (*p >= '0' && *p <= '9') ||
2353                                     *p == '-' || *p == '_')
2354                                         continue;
2355                                 log_error("ignoring invalid tag name '%s'\n", tag);
2356                                 break;
2357                         }
2358                         udev_device_add_tag(event->dev, tag);
2359                         break;
2360                 }
2361                 case TK_A_NAME: {
2362                         const char *name  = rules_str(rules, cur->key.value_off);
2363
2364                         char name_str[UTIL_PATH_SIZE];
2365                         int count;
2366
2367                         if (event->name_final)
2368                                 break;
2369                         if (cur->key.op == OP_ASSIGN_FINAL)
2370                                 event->name_final = true;
2371                         udev_event_apply_format(event, name, name_str, sizeof(name_str));
2372                         if (esc == ESCAPE_UNSET || esc == ESCAPE_REPLACE) {
2373                                 count = util_replace_chars(name_str, "/");
2374                                 if (count > 0)
2375                                         log_debug("%i character(s) replaced\n", count);
2376                         }
2377                         if (major(udev_device_get_devnum(event->dev)) &&
2378                             (!streq(name_str, udev_device_get_devnode(event->dev) + strlen("/dev/")))) {
2379                                 log_error("NAME=\"%s\" ignored, kernel device nodes "
2380                                     "can not be renamed; please fix it in %s:%u\n", name,
2381                                     rules_str(rules, rule->rule.filename_off), rule->rule.filename_line);
2382                                 break;
2383                         }
2384                         free(event->name);
2385                         event->name = strdup(name_str);
2386                         log_debug("NAME '%s' %s:%u\n",
2387                                   event->name,
2388                                   rules_str(rules, rule->rule.filename_off),
2389                                   rule->rule.filename_line);
2390                         break;
2391                 }
2392                 case TK_A_DEVLINK: {
2393                         char temp[UTIL_PATH_SIZE];
2394                         char filename[UTIL_PATH_SIZE];
2395                         char *pos, *next;
2396                         int count = 0;
2397
2398                         if (event->devlink_final)
2399                                 break;
2400                         if (major(udev_device_get_devnum(event->dev)) == 0)
2401                                 break;
2402                         if (cur->key.op == OP_ASSIGN_FINAL)
2403                                 event->devlink_final = true;
2404                         if (cur->key.op == OP_ASSIGN || cur->key.op == OP_ASSIGN_FINAL)
2405                                 udev_device_cleanup_devlinks_list(event->dev);
2406
2407                         /* allow  multiple symlinks separated by spaces */
2408                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), temp, sizeof(temp));
2409                         if (esc == ESCAPE_UNSET)
2410                                 count = util_replace_chars(temp, "/ ");
2411                         else if (esc == ESCAPE_REPLACE)
2412                                 count = util_replace_chars(temp, "/");
2413                         if (count > 0)
2414                                 log_debug("%i character(s) replaced\n" , count);
2415                         pos = temp;
2416                         while (isspace(pos[0]))
2417                                 pos++;
2418                         next = strchr(pos, ' ');
2419                         while (next != NULL) {
2420                                 next[0] = '\0';
2421                                 log_debug("LINK '%s' %s:%u\n", pos,
2422                                           rules_str(rules, rule->rule.filename_off), rule->rule.filename_line);
2423                                 strscpyl(filename, sizeof(filename), "/dev/", pos, NULL);
2424                                 udev_device_add_devlink(event->dev, filename);
2425                                 while (isspace(next[1]))
2426                                         next++;
2427                                 pos = &next[1];
2428                                 next = strchr(pos, ' ');
2429                         }
2430                         if (pos[0] != '\0') {
2431                                 log_debug("LINK '%s' %s:%u\n", pos,
2432                                           rules_str(rules, rule->rule.filename_off), rule->rule.filename_line);
2433                                 strscpyl(filename, sizeof(filename), "/dev/", pos, NULL);
2434                                 udev_device_add_devlink(event->dev, filename);
2435                         }
2436                         break;
2437                 }
2438                 case TK_A_ATTR: {
2439                         const char *key_name = rules_str(rules, cur->key.attr_off);
2440                         char attr[UTIL_PATH_SIZE];
2441                         char value[UTIL_NAME_SIZE];
2442                         FILE *f;
2443
2444                         if (util_resolve_subsys_kernel(event->udev, key_name, attr, sizeof(attr), 0) != 0)
2445                                 strscpyl(attr, sizeof(attr), udev_device_get_syspath(event->dev), "/", key_name, NULL);
2446                         attr_subst_subdir(attr, sizeof(attr));
2447
2448                         udev_event_apply_format(event, rules_str(rules, cur->key.value_off), value, sizeof(value));
2449                         log_debug("ATTR '%s' writing '%s' %s:%u\n", attr, value,
2450                                   rules_str(rules, rule->rule.filename_off),
2451                                   rule->rule.filename_line);
2452                         f = fopen(attr, "we");
2453                         if (f != NULL) {
2454                                 if (fprintf(f, "%s", value) <= 0)
2455                                         log_error("error writing ATTR{%s}: %m\n", attr);
2456                                 fclose(f);
2457                         } else {
2458                                 log_error("error opening ATTR{%s} for writing: %m\n", attr);
2459                         }
2460                         break;
2461                 }
2462                 case TK_A_RUN_BUILTIN:
2463                 case TK_A_RUN_PROGRAM: {
2464                         struct udev_list_entry *entry;
2465
2466                         if (cur->key.op == OP_ASSIGN || cur->key.op == OP_ASSIGN_FINAL)
2467                                 udev_list_cleanup(&event->run_list);
2468                         log_debug("RUN '%s' %s:%u\n",
2469                                   rules_str(rules, cur->key.value_off),
2470                                   rules_str(rules, rule->rule.filename_off),
2471                                   rule->rule.filename_line);
2472                         entry = udev_list_entry_add(&event->run_list, rules_str(rules, cur->key.value_off), NULL);
2473                         udev_list_entry_set_num(entry, cur->key.builtin_cmd);
2474                         break;
2475                 }
2476                 case TK_A_GOTO:
2477                         if (cur->key.rule_goto == 0)
2478                                 break;
2479                         cur = &rules->tokens[cur->key.rule_goto];
2480                         continue;
2481                 case TK_END:
2482                         return 0;
2483
2484                 case TK_M_PARENTS_MIN:
2485                 case TK_M_PARENTS_MAX:
2486                 case TK_M_MAX:
2487                 case TK_UNSET:
2488                         log_error("wrong type %u\n", cur->type);
2489                         goto nomatch;
2490                 }
2491
2492                 cur++;
2493                 continue;
2494         nomatch:
2495                 /* fast-forward to next rule */
2496                 cur = rule + rule->rule.token_count;
2497         }
2498 }
2499
2500 int udev_rules_apply_static_dev_perms(struct udev_rules *rules)
2501 {
2502         struct token *cur;
2503         struct token *rule;
2504         uid_t uid = 0;
2505         gid_t gid = 0;
2506         mode_t mode = 0;
2507         _cleanup_strv_free_ char **tags = NULL;
2508         char **t;
2509         FILE *f = NULL;
2510         _cleanup_free_ char *path = NULL;
2511         int r = 0;
2512
2513         if (rules->tokens == NULL)
2514                 return 0;
2515
2516         cur = &rules->tokens[0];
2517         rule = cur;
2518         for (;;) {
2519                 switch (cur->type) {
2520                 case TK_RULE:
2521                         /* current rule */
2522                         rule = cur;
2523
2524                         /* skip rules without a static_node tag */
2525                         if (!rule->rule.has_static_node)
2526                                 goto next;
2527
2528                         uid = 0;
2529                         gid = 0;
2530                         mode = 0;
2531                         strv_free(tags);
2532                         tags = NULL;
2533                         break;
2534                 case TK_A_OWNER_ID:
2535                         uid = cur->key.uid;
2536                         break;
2537                 case TK_A_GROUP_ID:
2538                         gid = cur->key.gid;
2539                         break;
2540                 case TK_A_MODE_ID:
2541                         mode = cur->key.mode;
2542                         break;
2543                 case TK_A_TAG:
2544                         r = strv_extend(&tags, rules_str(rules, cur->key.value_off));
2545                         if (r < 0)
2546                                 goto finish;
2547
2548                         break;
2549                 case TK_A_STATIC_NODE: {
2550                         char device_node[UTIL_PATH_SIZE];
2551                         char tags_dir[UTIL_PATH_SIZE];
2552                         char tag_symlink[UTIL_PATH_SIZE];
2553                         struct stat stats;
2554
2555                         /* we assure, that the permissions tokens are sorted before the static token */
2556                         if (mode == 0 && uid == 0 && gid == 0 && tags == NULL)
2557                                 goto next;
2558                         strscpyl(device_node, sizeof(device_node), "/dev/", rules_str(rules, cur->key.value_off), NULL);
2559                         if (stat(device_node, &stats) != 0)
2560                                 goto next;
2561                         if (!S_ISBLK(stats.st_mode) && !S_ISCHR(stats.st_mode))
2562                                 goto next;
2563
2564                         if (tags) {
2565                                 /* Export the tags to a directory as symlinks, allowing otherwise dead nodes to be tagged */
2566
2567                                 STRV_FOREACH(t, tags) {
2568                                         _cleanup_free_ char *unescaped_filename = NULL;
2569
2570                                         strscpyl(tags_dir, sizeof(tags_dir), "/run/udev/static_node-tags/", *t, "/", NULL);
2571                                         r = mkdir_p(tags_dir, 0755);
2572                                         if (r < 0) {
2573                                                 log_error("failed to create %s: %s\n", tags_dir, strerror(-r));
2574                                                 return r;
2575                                         }
2576
2577                                         unescaped_filename = xescape(rules_str(rules, cur->key.value_off), "/.");
2578
2579                                         strscpyl(tag_symlink, sizeof(tag_symlink), tags_dir, unescaped_filename, NULL);
2580                                         r = symlink(device_node, tag_symlink);
2581                                         if (r < 0 && errno != EEXIST) {
2582                                                 log_error("failed to create symlink %s -> %s: %s\n", tag_symlink, device_node, strerror(errno));
2583                                                 return -errno;
2584                                         } else
2585                                                 r = 0;
2586                                 }
2587                         }
2588
2589                         if (mode == 0) {
2590                                 if (gid > 0)
2591                                         mode = 0660;
2592                                 else
2593                                         mode = 0600;
2594                         }
2595                         if (mode != (stats.st_mode & 01777)) {
2596                                 r = chmod(device_node, mode);
2597                                 if (r < 0) {
2598                                         log_error("failed to chmod '%s' %#o\n", device_node, mode);
2599                                         return -errno;
2600                                 } else
2601                                         log_debug("chmod '%s' %#o\n", device_node, mode);
2602                         }
2603
2604                         if ((uid != 0 && uid != stats.st_uid) || (gid != 0 && gid != stats.st_gid)) {
2605                                 r = chown(device_node, uid, gid);
2606                                 if (r < 0) {
2607                                         log_error("failed to chown '%s' %u %u \n", device_node, uid, gid);
2608                                         return -errno;
2609                                 } else
2610                                         log_debug("chown '%s' %u %u\n", device_node, uid, gid);
2611                         }
2612
2613                         utimensat(AT_FDCWD, device_node, NULL, 0);
2614                         break;
2615                 }
2616                 case TK_END:
2617                         goto finish;
2618                 }
2619
2620                 cur++;
2621                 continue;
2622 next:
2623                 /* fast-forward to next rule */
2624                 cur = rule + rule->rule.token_count;
2625                 continue;
2626         }
2627
2628 finish:
2629         if (f) {
2630                 fflush(f);
2631                 fchmod(fileno(f), 0644);
2632                 if (ferror(f) || rename(path, "/run/udev/static_node-tags") < 0) {
2633                         r = -errno;
2634                         unlink("/run/udev/static_node-tags");
2635                         unlink(path);
2636                 }
2637                 fclose(f);
2638         }
2639
2640         return r;
2641 }