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