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