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