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