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