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