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