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