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