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