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