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