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