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