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