udev: String substitutions can be done in ENV, too
[systemd_ALT.git] / src / udev / udev-rules.c
blob88846ae275a056e9ef7d955289024d03dd393f94
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
3 #include <ctype.h>
5 #include "alloc-util.h"
6 #include "architecture.h"
7 #include "conf-files.h"
8 #include "conf-parser.h"
9 #include "confidential-virt.h"
10 #include "constants.h"
11 #include "device-private.h"
12 #include "device-util.h"
13 #include "dirent-util.h"
14 #include "fd-util.h"
15 #include "fileio.h"
16 #include "format-util.h"
17 #include "fs-util.h"
18 #include "glob-util.h"
19 #include "list.h"
20 #include "mkdir.h"
21 #include "netif-naming-scheme.h"
22 #include "nulstr-util.h"
23 #include "parse-util.h"
24 #include "path-util.h"
25 #include "proc-cmdline.h"
26 #include "stat-util.h"
27 #include "strv.h"
28 #include "strxcpyx.h"
29 #include "sysctl-util.h"
30 #include "syslog-util.h"
31 #include "udev-builtin.h"
32 #include "udev-event.h"
33 #include "udev-node.h"
34 #include "udev-rules.h"
35 #include "udev-util.h"
36 #include "user-util.h"
37 #include "virt.h"
39 #define RULES_DIRS ((const char* const*) CONF_PATHS_STRV("udev/rules.d"))
41 typedef enum {
42 OP_MATCH, /* == */
43 OP_NOMATCH, /* != */
44 OP_ADD, /* += */
45 OP_REMOVE, /* -= */
46 OP_ASSIGN, /* = */
47 OP_ASSIGN_FINAL, /* := */
48 _OP_TYPE_MAX,
49 _OP_TYPE_INVALID = -EINVAL,
50 } UdevRuleOperatorType;
52 typedef enum {
53 MATCH_TYPE_EMPTY, /* empty string */
54 MATCH_TYPE_PLAIN, /* no special characters */
55 MATCH_TYPE_PLAIN_WITH_EMPTY, /* no special characters with empty string, e.g., "|foo" */
56 MATCH_TYPE_GLOB, /* shell globs ?,*,[] */
57 MATCH_TYPE_GLOB_WITH_EMPTY, /* shell globs ?,*,[] with empty string, e.g., "|foo*" */
58 MATCH_TYPE_SUBSYSTEM, /* "subsystem", "bus", or "class" */
59 _MATCH_TYPE_MAX,
60 _MATCH_TYPE_INVALID = -EINVAL,
61 } UdevRuleMatchType;
63 typedef enum {
64 SUBST_TYPE_PLAIN, /* no substitution */
65 SUBST_TYPE_FORMAT, /* % or $ */
66 SUBST_TYPE_SUBSYS, /* "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
67 _SUBST_TYPE_MAX,
68 _SUBST_TYPE_INVALID = -EINVAL,
69 } UdevRuleSubstituteType;
71 typedef enum {
72 /* lvalues which take match or nomatch operator */
73 TK_M_ACTION, /* string, device_get_action() */
74 TK_M_DEVPATH, /* path, sd_device_get_devpath() */
75 TK_M_KERNEL, /* string, sd_device_get_sysname() */
76 TK_M_DEVLINK, /* strv, sd_device_get_devlink_first(), sd_device_get_devlink_next() */
77 TK_M_NAME, /* string, name of network interface */
78 TK_M_ENV, /* string, device property, takes key through attribute */
79 TK_M_CONST, /* string, system-specific hard-coded constant */
80 TK_M_TAG, /* strv, sd_device_get_tag_first(), sd_device_get_tag_next() */
81 TK_M_SUBSYSTEM, /* string, sd_device_get_subsystem() */
82 TK_M_DRIVER, /* string, sd_device_get_driver() */
83 TK_M_ATTR, /* string, takes filename through attribute, sd_device_get_sysattr_value(), udev_resolve_subsys_kernel(), etc. */
84 TK_M_SYSCTL, /* string, takes kernel parameter through attribute */
86 /* matches parent parameters */
87 TK_M_PARENTS_KERNEL, /* string */
88 TK_M_PARENTS_SUBSYSTEM, /* string */
89 TK_M_PARENTS_DRIVER, /* string */
90 TK_M_PARENTS_ATTR, /* string */
91 TK_M_PARENTS_TAG, /* strv */
93 TK_M_TEST, /* path, optionally mode_t can be specified by attribute, test the existence of a file */
94 TK_M_PROGRAM, /* string, execute a program */
95 TK_M_IMPORT_FILE, /* path */
96 TK_M_IMPORT_PROGRAM, /* string, import properties from the result of program */
97 TK_M_IMPORT_BUILTIN, /* string, import properties from the result of built-in command */
98 TK_M_IMPORT_DB, /* string, import properties from database */
99 TK_M_IMPORT_CMDLINE, /* string, kernel command line */
100 TK_M_IMPORT_PARENT, /* string, parent property */
101 TK_M_RESULT, /* string, result of TK_M_PROGRAM */
103 #define _TK_M_MAX (TK_M_RESULT + 1)
104 #define _TK_A_MIN _TK_M_MAX
106 /* lvalues which take one of assign operators */
107 TK_A_OPTIONS_STRING_ESCAPE_NONE, /* no argument */
108 TK_A_OPTIONS_STRING_ESCAPE_REPLACE, /* no argument */
109 TK_A_OPTIONS_DB_PERSIST, /* no argument */
110 TK_A_OPTIONS_INOTIFY_WATCH, /* boolean */
111 TK_A_OPTIONS_DEVLINK_PRIORITY, /* int */
112 TK_A_OPTIONS_LOG_LEVEL, /* string of log level or "reset" */
113 TK_A_OWNER, /* user name */
114 TK_A_GROUP, /* group name */
115 TK_A_MODE, /* mode string */
116 TK_A_OWNER_ID, /* uid_t */
117 TK_A_GROUP_ID, /* gid_t */
118 TK_A_MODE_ID, /* mode_t */
119 TK_A_TAG, /* string */
120 TK_A_OPTIONS_STATIC_NODE, /* device path, /dev/... */
121 TK_A_SECLABEL, /* string with attribute */
122 TK_A_ENV, /* string with attribute */
123 TK_A_NAME, /* ifname */
124 TK_A_DEVLINK, /* string */
125 TK_A_ATTR, /* string with attribute */
126 TK_A_SYSCTL, /* string with attribute */
127 TK_A_RUN_BUILTIN, /* string */
128 TK_A_RUN_PROGRAM, /* string */
130 _TK_TYPE_MAX,
131 _TK_TYPE_INVALID = -EINVAL,
132 } UdevRuleTokenType;
134 typedef enum {
135 LINE_HAS_NAME = 1 << 0, /* has NAME= */
136 LINE_HAS_DEVLINK = 1 << 1, /* has SYMLINK=, OWNER=, GROUP= or MODE= */
137 LINE_HAS_STATIC_NODE = 1 << 2, /* has OPTIONS=static_node */
138 LINE_HAS_GOTO = 1 << 3, /* has GOTO= */
139 LINE_HAS_LABEL = 1 << 4, /* has LABEL= */
140 LINE_UPDATE_SOMETHING = 1 << 5, /* has other TK_A_* or TK_M_IMPORT tokens */
141 LINE_IS_REFERENCED = 1 << 6, /* is referenced by GOTO */
142 } UdevRuleLineType;
144 typedef struct UdevRuleFile UdevRuleFile;
145 typedef struct UdevRuleLine UdevRuleLine;
146 typedef struct UdevRuleToken UdevRuleToken;
148 struct UdevRuleToken {
149 UdevRuleTokenType type:8;
150 UdevRuleOperatorType op:8;
151 UdevRuleMatchType match_type:8;
152 UdevRuleSubstituteType attr_subst_type:7;
153 bool attr_match_remove_trailing_whitespace:1;
154 const char *value;
155 void *data;
157 UdevRuleLine *rule_line;
158 LIST_FIELDS(UdevRuleToken, tokens);
161 struct UdevRuleLine {
162 char *line;
163 unsigned line_number;
164 UdevRuleLineType type;
166 const char *label;
167 const char *goto_label;
168 UdevRuleLine *goto_line;
170 UdevRuleFile *rule_file;
171 LIST_HEAD(UdevRuleToken, tokens);
172 LIST_FIELDS(UdevRuleLine, rule_lines);
175 struct UdevRuleFile {
176 char *filename;
177 unsigned issues; /* used by "udevadm verify" */
179 UdevRules *rules;
180 LIST_HEAD(UdevRuleLine, rule_lines);
181 LIST_FIELDS(UdevRuleFile, rule_files);
184 struct UdevRules {
185 ResolveNameTiming resolve_name_timing;
186 Hashmap *known_users;
187 Hashmap *known_groups;
188 Hashmap *stats_by_path;
189 LIST_HEAD(UdevRuleFile, rule_files);
192 #define LINE_GET_RULES(line) \
193 ASSERT_PTR(ASSERT_PTR(ASSERT_PTR(line)->rule_file)->rules)
195 /*** Logging helpers ***/
197 #define log_udev_rule_internal(device, file, line_nr, level, error, fmt, ...) \
198 ({ \
199 int _lv = (level); \
200 sd_device *_dev = (device); \
201 UdevRuleFile *_f = (file); \
202 const char *_n = _f ? _f->filename : NULL; \
204 if (!_dev && _f) \
205 _f->issues |= (1U << _lv); \
207 log_device_full_errno_zerook( \
208 _dev, _lv, error, "%s:%u " fmt, \
209 strna(_n), line_nr, \
210 ##__VA_ARGS__); \
213 /* Mainly used when applying tokens to the event device. */
214 #define log_event_full_errno_zerook(device, token, ...) \
215 ({ \
216 UdevRuleToken *_t = (token); \
217 UdevRuleLine *_l = _t ? _t->rule_line : NULL; \
219 log_udev_rule_internal( \
220 device, \
221 _l ? _l->rule_file : NULL, \
222 _l ? _l->line_number : 0, \
223 __VA_ARGS__); \
226 #define log_event_full_errno(device, token, level, error, ...) \
227 ({ \
228 int _error = (error); \
229 ASSERT_NON_ZERO(_error); \
230 log_event_full_errno_zerook( \
231 device, token, level, _error, ##__VA_ARGS__); \
234 #define log_event_full(device, token, level, ...) (void) log_event_full_errno_zerook(device, token, level, 0, __VA_ARGS__)
236 #define log_event_debug(device, token, ...) log_event_full(device, token, LOG_DEBUG, __VA_ARGS__)
237 #define log_event_info(device, token, ...) log_event_full(device, token, LOG_INFO, __VA_ARGS__)
238 #define log_event_notice(device, token, ...) log_event_full(device, token, LOG_NOTICE, __VA_ARGS__)
239 #define log_event_warning(device, token, ...) log_event_full(device, token, LOG_WARNING, __VA_ARGS__)
240 #define log_event_error(device, token, ...) log_event_full(device, token, LOG_ERR, __VA_ARGS__)
242 #define log_event_debug_errno(device, token, error, ...) log_event_full_errno(device, token, LOG_DEBUG, error, __VA_ARGS__)
243 #define log_event_info_errno(device, token, error, ...) log_event_full_errno(device, token, LOG_INFO, error, __VA_ARGS__)
244 #define log_event_notice_errno(device, token, error, ...) log_event_full_errno(device, token, LOG_NOTICE, error, __VA_ARGS__)
245 #define log_event_warning_errno(device, token, error, ...) log_event_full_errno(device, token, LOG_WARNING, error, __VA_ARGS__)
246 #define log_event_error_errno(device, token, error, ...) log_event_full_errno(device, token, LOG_ERR, error, __VA_ARGS__)
248 /* Mainly used when parsing .rules files. */
249 #define log_file_full_errno_zerook(...) \
250 log_udev_rule_internal(NULL, __VA_ARGS__)
252 #define log_file_error(file, line_nr, ...) \
253 log_file_full_errno_zerook(file, line_nr, LOG_ERR, 0, __VA_ARGS__)
255 #define log_line_full_errno_zerook(line, ...) \
256 ({ \
257 UdevRuleLine *_l = (line); \
258 log_file_full_errno_zerook( \
259 _l ? _l->rule_file : NULL, \
260 _l ? _l->line_number : 0, \
261 __VA_ARGS__); \
264 #define log_line_full_errno(line, level, error, ...) \
265 ({ \
266 int _error = (error); \
267 ASSERT_NON_ZERO(_error); \
268 log_line_full_errno_zerook( \
269 line, level, _error, ##__VA_ARGS__); \
272 #define log_line_full(line, level, ...) (void) log_line_full_errno_zerook(line, level, 0, __VA_ARGS__)
274 #define log_line_debug(line, ...) log_line_full(line, LOG_DEBUG, __VA_ARGS__)
275 #define log_line_info(line, ...) log_line_full(line, LOG_INFO, __VA_ARGS__)
276 #define log_line_notice(line, ...) log_line_full(line, LOG_NOTICE, __VA_ARGS__)
277 #define log_line_warning(line, ...) log_line_full(line, LOG_WARNING, __VA_ARGS__)
278 #define log_line_error(line, ...) log_line_full(line, LOG_ERR, __VA_ARGS__)
280 #define log_line_debug_errno(line, error, ...) log_line_full_errno(line, LOG_DEBUG, error, __VA_ARGS__)
281 #define log_line_info_errno(line, error, ...) log_line_full_errno(line, LOG_INFO, error, __VA_ARGS__)
282 #define log_line_notice_errno(line, error, ...) log_line_full_errno(line, LOG_NOTICE, error, __VA_ARGS__)
283 #define log_line_warning_errno(line, error, ...) log_line_full_errno(line, LOG_WARNING, error, __VA_ARGS__)
284 #define log_line_error_errno(line, error, ...) log_line_full_errno(line, LOG_ERR, error, __VA_ARGS__)
286 #define _log_line_invalid_token(line, key, type) \
287 log_line_error_errno(line, SYNTHETIC_ERRNO(EINVAL), \
288 "Invalid %s for %s.", type, key)
290 #define log_line_invalid_op(line, key) _log_line_invalid_token(line, key, "operator")
291 #define log_line_invalid_attr(line, key) _log_line_invalid_token(line, key, "attribute")
293 #define log_line_invalid_attr_format(line, key, attr, offset, hint) \
294 log_line_error_errno(line, SYNTHETIC_ERRNO(EINVAL), \
295 "Invalid attribute \"%s\" for %s (char %zu: %s), ignoring.", \
296 attr, key, offset, hint)
297 #define log_line_invalid_value(line, key, value, offset, hint) \
298 log_line_error_errno(line, SYNTHETIC_ERRNO(EINVAL), \
299 "Invalid value \"%s\" for %s (char %zu: %s), ignoring.", \
300 value, key, offset, hint)
302 static void log_unknown_owner(sd_device *dev, UdevRuleLine *line, int error, const char *entity, const char *name) {
303 assert(line);
304 ASSERT_NON_ZERO(error);
306 if (IN_SET(abs(error), ENOENT, ESRCH))
307 log_udev_rule_internal(dev, line->rule_file, line->line_number, LOG_ERR, error,
308 "Unknown %s '%s', ignoring.", entity, name);
309 else
310 log_udev_rule_internal(dev, line->rule_file, line->line_number, LOG_ERR, error,
311 "Failed to resolve %s '%s', ignoring: %m", entity, name);
314 static void log_event_truncated(
315 sd_device *dev,
316 UdevRuleToken *token,
317 const char *what,
318 const char *format,
319 const char *key,
320 bool is_match) {
322 if (is_match)
323 log_event_debug(dev, token,
324 "The %s is truncated while substituting into '%s', "
325 "assuming the %s key does not match.",
326 what, format, key);
327 else
328 log_event_warning(dev, token,
329 "The %s is truncated while substituting into '%s', "
330 "refusing to apply the %s key.",
331 what, format, key);
334 /*** Other functions ***/
336 static UdevRuleToken *udev_rule_token_free(UdevRuleToken *token) {
337 if (!token)
338 return NULL;
340 if (token->rule_line)
341 LIST_REMOVE(tokens, token->rule_line->tokens, token);
343 return mfree(token);
346 DEFINE_TRIVIAL_CLEANUP_FUNC(UdevRuleToken*, udev_rule_token_free);
348 static void udev_rule_line_clear_tokens(UdevRuleLine *rule_line) {
349 assert(rule_line);
351 LIST_FOREACH(tokens, i, rule_line->tokens)
352 udev_rule_token_free(i);
355 static UdevRuleLine *udev_rule_line_free(UdevRuleLine *rule_line) {
356 if (!rule_line)
357 return NULL;
359 udev_rule_line_clear_tokens(rule_line);
361 if (rule_line->rule_file)
362 LIST_REMOVE(rule_lines, rule_line->rule_file->rule_lines, rule_line);
364 free(rule_line->line);
365 return mfree(rule_line);
368 DEFINE_TRIVIAL_CLEANUP_FUNC(UdevRuleLine*, udev_rule_line_free);
370 static UdevRuleFile *udev_rule_file_free(UdevRuleFile *rule_file) {
371 if (!rule_file)
372 return NULL;
374 LIST_FOREACH(rule_lines, i, rule_file->rule_lines)
375 udev_rule_line_free(i);
377 if (rule_file->rules)
378 LIST_REMOVE(rule_files, rule_file->rules->rule_files, rule_file);
380 free(rule_file->filename);
381 return mfree(rule_file);
384 DEFINE_TRIVIAL_CLEANUP_FUNC(UdevRuleFile*, udev_rule_file_free);
386 UdevRules *udev_rules_free(UdevRules *rules) {
387 if (!rules)
388 return NULL;
390 LIST_FOREACH(rule_files, i, rules->rule_files)
391 udev_rule_file_free(i);
393 hashmap_free_free_key(rules->known_users);
394 hashmap_free_free_key(rules->known_groups);
395 hashmap_free(rules->stats_by_path);
396 return mfree(rules);
399 static int rule_resolve_user(UdevRuleLine *rule_line, const char *name, uid_t *ret) {
400 Hashmap **known_users = &LINE_GET_RULES(rule_line)->known_users;
401 _cleanup_free_ char *n = NULL;
402 uid_t uid;
403 void *val;
404 int r;
406 assert(name);
407 assert(ret);
409 val = hashmap_get(*known_users, name);
410 if (val) {
411 *ret = PTR_TO_UID(val);
412 return 0;
415 r = get_user_creds(&name, &uid, NULL, NULL, NULL, USER_CREDS_ALLOW_MISSING);
416 if (r < 0) {
417 log_unknown_owner(NULL, rule_line, r, "user", name);
418 *ret = UID_INVALID;
419 return 0;
422 n = strdup(name);
423 if (!n)
424 return -ENOMEM;
426 r = hashmap_ensure_put(known_users, &string_hash_ops, n, UID_TO_PTR(uid));
427 if (r < 0)
428 return r;
430 TAKE_PTR(n);
431 *ret = uid;
432 return 0;
435 static int rule_resolve_group(UdevRuleLine *rule_line, const char *name, gid_t *ret) {
436 Hashmap **known_groups = &LINE_GET_RULES(rule_line)->known_groups;
437 _cleanup_free_ char *n = NULL;
438 gid_t gid;
439 void *val;
440 int r;
442 assert(name);
443 assert(ret);
445 val = hashmap_get(*known_groups, name);
446 if (val) {
447 *ret = PTR_TO_GID(val);
448 return 0;
451 r = get_group_creds(&name, &gid, USER_CREDS_ALLOW_MISSING);
452 if (r < 0) {
453 log_unknown_owner(NULL, rule_line, r, "group", name);
454 *ret = GID_INVALID;
455 return 0;
458 n = strdup(name);
459 if (!n)
460 return -ENOMEM;
462 r = hashmap_ensure_put(known_groups, &string_hash_ops, n, GID_TO_PTR(gid));
463 if (r < 0)
464 return r;
466 TAKE_PTR(n);
467 *ret = gid;
468 return 0;
471 static UdevRuleSubstituteType rule_get_substitution_type(const char *str) {
472 assert(str);
474 if (str[0] == '[')
475 return SUBST_TYPE_SUBSYS;
476 if (strchr(str, '%') || strchr(str, '$'))
477 return SUBST_TYPE_FORMAT;
478 return SUBST_TYPE_PLAIN;
481 static bool type_has_nulstr_value(UdevRuleTokenType type) {
482 return type < TK_M_TEST || type == TK_M_RESULT;
485 static int rule_line_add_token(UdevRuleLine *rule_line, UdevRuleTokenType type, UdevRuleOperatorType op, char *value, void *data) {
486 _cleanup_(udev_rule_token_freep) UdevRuleToken *token = NULL;
487 UdevRuleMatchType match_type = _MATCH_TYPE_INVALID;
488 UdevRuleSubstituteType subst_type = _SUBST_TYPE_INVALID;
489 bool remove_trailing_whitespace = false;
490 size_t len;
492 assert(rule_line);
493 assert(type >= 0 && type < _TK_TYPE_MAX);
494 assert(op >= 0 && op < _OP_TYPE_MAX);
496 if (type < _TK_M_MAX) {
497 assert(value);
498 assert(IN_SET(op, OP_MATCH, OP_NOMATCH));
500 if (type == TK_M_SUBSYSTEM && STR_IN_SET(value, "subsystem", "bus", "class"))
501 match_type = MATCH_TYPE_SUBSYSTEM;
502 else if (isempty(value))
503 match_type = MATCH_TYPE_EMPTY;
504 else if (streq(value, "?*")) {
505 /* Convert KEY=="?*" -> KEY!="" */
506 match_type = MATCH_TYPE_EMPTY;
507 op = op == OP_MATCH ? OP_NOMATCH : OP_MATCH;
508 } else if (string_is_glob(value))
509 match_type = MATCH_TYPE_GLOB;
510 else
511 match_type = MATCH_TYPE_PLAIN;
513 if (type_has_nulstr_value(type)) {
514 /* Convert value string to nulstr. */
515 bool bar = true, empty = false;
516 char *a, *b;
518 for (a = b = value; *a != '\0'; a++) {
519 if (*a != '|') {
520 *b++ = *a;
521 bar = false;
522 } else {
523 if (bar)
524 empty = true;
525 else
526 *b++ = '\0';
527 bar = true;
530 *b = '\0';
532 /* Make sure the value is end, so NULSTR_FOREACH can read correct match */
533 if (b < a)
534 b[1] = '\0';
536 if (bar)
537 empty = true;
539 if (empty) {
540 if (match_type == MATCH_TYPE_GLOB)
541 match_type = MATCH_TYPE_GLOB_WITH_EMPTY;
542 if (match_type == MATCH_TYPE_PLAIN)
543 match_type = MATCH_TYPE_PLAIN_WITH_EMPTY;
548 if (IN_SET(type, TK_M_ATTR, TK_M_PARENTS_ATTR)) {
549 assert(value);
550 assert(data);
552 len = strlen(value);
553 if (len > 0 && !isspace(value[len - 1]))
554 remove_trailing_whitespace = true;
556 subst_type = rule_get_substitution_type(data);
559 token = new(UdevRuleToken, 1);
560 if (!token)
561 return -ENOMEM;
563 *token = (UdevRuleToken) {
564 .type = type,
565 .op = op,
566 .value = value,
567 .data = data,
568 .match_type = match_type,
569 .attr_subst_type = subst_type,
570 .attr_match_remove_trailing_whitespace = remove_trailing_whitespace,
571 .rule_line = rule_line,
574 LIST_APPEND(tokens, rule_line->tokens, token);
576 if (token->type == TK_A_NAME)
577 SET_FLAG(rule_line->type, LINE_HAS_NAME, true);
579 else if (IN_SET(token->type, TK_A_DEVLINK,
580 TK_A_OWNER, TK_A_GROUP, TK_A_MODE,
581 TK_A_OWNER_ID, TK_A_GROUP_ID, TK_A_MODE_ID))
582 SET_FLAG(rule_line->type, LINE_HAS_DEVLINK, true);
584 else if (token->type == TK_A_OPTIONS_STATIC_NODE)
585 SET_FLAG(rule_line->type, LINE_HAS_STATIC_NODE, true);
587 else if (token->type >= _TK_A_MIN ||
588 IN_SET(token->type, TK_M_PROGRAM,
589 TK_M_IMPORT_FILE, TK_M_IMPORT_PROGRAM, TK_M_IMPORT_BUILTIN,
590 TK_M_IMPORT_DB, TK_M_IMPORT_CMDLINE, TK_M_IMPORT_PARENT))
591 SET_FLAG(rule_line->type, LINE_UPDATE_SOMETHING, true);
593 TAKE_PTR(token);
594 return 0;
597 static void check_value_format_and_warn(UdevRuleLine *line, const char *key, const char *value, bool nonempty) {
598 size_t offset;
599 const char *hint;
601 if (nonempty && isempty(value))
602 log_line_invalid_value(line, key, value, (size_t) 0, "empty value");
603 else if (udev_check_format(value, &offset, &hint) < 0)
604 log_line_invalid_value(line, key, value, offset + 1, hint);
607 static int check_attr_format_and_warn(UdevRuleLine *line, const char *key, const char *value) {
608 size_t offset;
609 const char *hint;
611 if (isempty(value))
612 return log_line_invalid_attr(line, key);
613 if (udev_check_format(value, &offset, &hint) < 0)
614 log_line_invalid_attr_format(line, key, value, offset + 1, hint);
615 return 0;
618 static int parse_token(UdevRuleLine *rule_line, const char *key, char *attr, UdevRuleOperatorType op, char *value) {
619 ResolveNameTiming resolve_name_timing = LINE_GET_RULES(rule_line)->resolve_name_timing;
620 bool is_match = IN_SET(op, OP_MATCH, OP_NOMATCH);
621 int r;
623 assert(key);
624 assert(value);
626 if (streq(key, "ACTION")) {
627 if (attr)
628 return log_line_invalid_attr(rule_line, key);
629 if (!is_match)
630 return log_line_invalid_op(rule_line, key);
632 r = rule_line_add_token(rule_line, TK_M_ACTION, op, value, NULL);
633 } else if (streq(key, "DEVPATH")) {
634 if (attr)
635 return log_line_invalid_attr(rule_line, key);
636 if (!is_match)
637 return log_line_invalid_op(rule_line, key);
639 r = rule_line_add_token(rule_line, TK_M_DEVPATH, op, value, NULL);
640 } else if (streq(key, "KERNEL")) {
641 if (attr)
642 return log_line_invalid_attr(rule_line, key);
643 if (!is_match)
644 return log_line_invalid_op(rule_line, key);
646 r = rule_line_add_token(rule_line, TK_M_KERNEL, op, value, NULL);
647 } else if (streq(key, "SYMLINK")) {
648 if (attr)
649 return log_line_invalid_attr(rule_line, key);
650 if (!is_match) {
651 check_value_format_and_warn(rule_line, key, value, false);
652 r = rule_line_add_token(rule_line, TK_A_DEVLINK, op, value, NULL);
653 } else
654 r = rule_line_add_token(rule_line, TK_M_DEVLINK, op, value, NULL);
655 } else if (streq(key, "NAME")) {
656 if (attr)
657 return log_line_invalid_attr(rule_line, key);
658 if (op == OP_REMOVE)
659 return log_line_invalid_op(rule_line, key);
660 if (op == OP_ADD) {
661 log_line_warning(rule_line, "%s key takes '==', '!=', '=', or ':=' operator, assuming '='.", key);
662 op = OP_ASSIGN;
665 if (!is_match) {
666 if (streq(value, "%k"))
667 return log_line_error_errno(rule_line, SYNTHETIC_ERRNO(EINVAL),
668 "Ignoring NAME=\"%%k\", as it will take no effect.");
669 if (isempty(value))
670 return log_line_error_errno(rule_line, SYNTHETIC_ERRNO(EINVAL),
671 "Ignoring NAME=\"\", as udev will not delete any network interfaces.");
672 check_value_format_and_warn(rule_line, key, value, false);
674 r = rule_line_add_token(rule_line, TK_A_NAME, op, value, NULL);
675 } else
676 r = rule_line_add_token(rule_line, TK_M_NAME, op, value, NULL);
677 } else if (streq(key, "ENV")) {
678 if (isempty(attr))
679 return log_line_invalid_attr(rule_line, key);
680 if (op == OP_REMOVE)
681 return log_line_invalid_op(rule_line, key);
682 if (op == OP_ASSIGN_FINAL) {
683 log_line_warning(rule_line, "%s key takes '==', '!=', '=', or '+=' operator, assuming '='.", key);
684 op = OP_ASSIGN;
687 if (!is_match) {
688 if (STR_IN_SET(attr,
689 "ACTION", "DEVLINKS", "DEVNAME", "DEVPATH", "DEVTYPE", "DRIVER",
690 "IFINDEX", "MAJOR", "MINOR", "SEQNUM", "SUBSYSTEM", "TAGS"))
691 return log_line_error_errno(rule_line, SYNTHETIC_ERRNO(EINVAL),
692 "Invalid ENV attribute. '%s' cannot be set.", attr);
694 check_value_format_and_warn(rule_line, key, value, false);
696 r = rule_line_add_token(rule_line, TK_A_ENV, op, value, attr);
697 } else
698 r = rule_line_add_token(rule_line, TK_M_ENV, op, value, attr);
699 } else if (streq(key, "CONST")) {
700 if (isempty(attr) || !STR_IN_SET(attr, "arch", "virt"))
701 return log_line_invalid_attr(rule_line, key);
702 if (!is_match)
703 return log_line_invalid_op(rule_line, key);
704 r = rule_line_add_token(rule_line, TK_M_CONST, op, value, attr);
705 } else if (streq(key, "TAG")) {
706 if (attr)
707 return log_line_invalid_attr(rule_line, key);
708 if (op == OP_ASSIGN_FINAL) {
709 log_line_warning(rule_line, "%s key takes '==', '!=', '=', or '+=' operator, assuming '='.", key);
710 op = OP_ASSIGN;
713 if (!is_match) {
714 check_value_format_and_warn(rule_line, key, value, true);
716 r = rule_line_add_token(rule_line, TK_A_TAG, op, value, NULL);
717 } else
718 r = rule_line_add_token(rule_line, TK_M_TAG, op, value, NULL);
719 } else if (streq(key, "SUBSYSTEM")) {
720 if (attr)
721 return log_line_invalid_attr(rule_line, key);
722 if (!is_match)
723 return log_line_invalid_op(rule_line, key);
725 if (STR_IN_SET(value, "bus", "class"))
726 log_line_warning(rule_line, "\"%s\" must be specified as \"subsystem\".", value);
728 r = rule_line_add_token(rule_line, TK_M_SUBSYSTEM, op, value, NULL);
729 } else if (streq(key, "DRIVER")) {
730 if (attr)
731 return log_line_invalid_attr(rule_line, key);
732 if (!is_match)
733 return log_line_invalid_op(rule_line, key);
735 r = rule_line_add_token(rule_line, TK_M_DRIVER, op, value, NULL);
736 } else if (streq(key, "ATTR")) {
737 r = check_attr_format_and_warn(rule_line, key, attr);
738 if (r < 0)
739 return r;
740 if (op == OP_REMOVE)
741 return log_line_invalid_op(rule_line, key);
742 if (IN_SET(op, OP_ADD, OP_ASSIGN_FINAL)) {
743 log_line_warning(rule_line, "%s key takes '==', '!=', or '=' operator, assuming '='.", key);
744 op = OP_ASSIGN;
747 if (!is_match) {
748 check_value_format_and_warn(rule_line, key, value, false);
749 r = rule_line_add_token(rule_line, TK_A_ATTR, op, value, attr);
750 } else
751 r = rule_line_add_token(rule_line, TK_M_ATTR, op, value, attr);
752 } else if (streq(key, "SYSCTL")) {
753 r = check_attr_format_and_warn(rule_line, key, attr);
754 if (r < 0)
755 return r;
756 if (op == OP_REMOVE)
757 return log_line_invalid_op(rule_line, key);
758 if (IN_SET(op, OP_ADD, OP_ASSIGN_FINAL)) {
759 log_line_warning(rule_line, "%s key takes '==', '!=', or '=' operator, assuming '='.", key);
760 op = OP_ASSIGN;
763 if (!is_match) {
764 check_value_format_and_warn(rule_line, key, value, false);
765 r = rule_line_add_token(rule_line, TK_A_SYSCTL, op, value, attr);
766 } else
767 r = rule_line_add_token(rule_line, TK_M_SYSCTL, op, value, attr);
768 } else if (streq(key, "KERNELS")) {
769 if (attr)
770 return log_line_invalid_attr(rule_line, key);
771 if (!is_match)
772 return log_line_invalid_op(rule_line, key);
774 r = rule_line_add_token(rule_line, TK_M_PARENTS_KERNEL, op, value, NULL);
775 } else if (streq(key, "SUBSYSTEMS")) {
776 if (attr)
777 return log_line_invalid_attr(rule_line, key);
778 if (!is_match)
779 return log_line_invalid_op(rule_line, key);
781 r = rule_line_add_token(rule_line, TK_M_PARENTS_SUBSYSTEM, op, value, NULL);
782 } else if (streq(key, "DRIVERS")) {
783 if (attr)
784 return log_line_invalid_attr(rule_line, key);
785 if (!is_match)
786 return log_line_invalid_op(rule_line, key);
788 r = rule_line_add_token(rule_line, TK_M_PARENTS_DRIVER, op, value, NULL);
789 } else if (streq(key, "ATTRS")) {
790 r = check_attr_format_and_warn(rule_line, key, attr);
791 if (r < 0)
792 return r;
793 if (!is_match)
794 return log_line_invalid_op(rule_line, key);
796 if (startswith(attr, "device/"))
797 log_line_warning(rule_line, "'device' link may not be available in future kernels.");
798 if (strstr(attr, "../"))
799 log_line_warning(rule_line, "Direct reference to parent sysfs directory, may break in future kernels.");
801 r = rule_line_add_token(rule_line, TK_M_PARENTS_ATTR, op, value, attr);
802 } else if (streq(key, "TAGS")) {
803 if (attr)
804 return log_line_invalid_attr(rule_line, key);
805 if (!is_match)
806 return log_line_invalid_op(rule_line, key);
808 r = rule_line_add_token(rule_line, TK_M_PARENTS_TAG, op, value, NULL);
809 } else if (streq(key, "TEST")) {
810 mode_t mode = MODE_INVALID;
812 if (!isempty(attr)) {
813 r = parse_mode(attr, &mode);
814 if (r < 0)
815 return log_line_error_errno(rule_line, r, "Failed to parse mode '%s': %m", attr);
817 check_value_format_and_warn(rule_line, key, value, true);
818 if (!is_match)
819 return log_line_invalid_op(rule_line, key);
821 r = rule_line_add_token(rule_line, TK_M_TEST, op, value, MODE_TO_PTR(mode));
822 } else if (streq(key, "PROGRAM")) {
823 if (attr)
824 return log_line_invalid_attr(rule_line, key);
825 check_value_format_and_warn(rule_line, key, value, true);
826 if (op == OP_REMOVE)
827 return log_line_invalid_op(rule_line, key);
828 if (!is_match)
829 op = OP_MATCH;
831 r = rule_line_add_token(rule_line, TK_M_PROGRAM, op, value, NULL);
832 } else if (streq(key, "IMPORT")) {
833 if (isempty(attr))
834 return log_line_invalid_attr(rule_line, key);
835 check_value_format_and_warn(rule_line, key, value, true);
836 if (op == OP_REMOVE)
837 return log_line_invalid_op(rule_line, key);
838 if (!is_match)
839 op = OP_MATCH;
841 if (streq(attr, "file"))
842 r = rule_line_add_token(rule_line, TK_M_IMPORT_FILE, op, value, NULL);
843 else if (streq(attr, "program")) {
844 UdevBuiltinCommand cmd;
846 cmd = udev_builtin_lookup(value);
847 if (cmd >= 0) {
848 log_line_debug(rule_line, "Found builtin command '%s' for %s, replacing attribute.", value, key);
849 r = rule_line_add_token(rule_line, TK_M_IMPORT_BUILTIN, op, value, UDEV_BUILTIN_CMD_TO_PTR(cmd));
850 } else
851 r = rule_line_add_token(rule_line, TK_M_IMPORT_PROGRAM, op, value, NULL);
852 } else if (streq(attr, "builtin")) {
853 UdevBuiltinCommand cmd;
855 cmd = udev_builtin_lookup(value);
856 if (cmd < 0)
857 return log_line_error_errno(rule_line, SYNTHETIC_ERRNO(EINVAL),
858 "Unknown builtin command: %s", value);
859 r = rule_line_add_token(rule_line, TK_M_IMPORT_BUILTIN, op, value, UDEV_BUILTIN_CMD_TO_PTR(cmd));
860 } else if (streq(attr, "db"))
861 r = rule_line_add_token(rule_line, TK_M_IMPORT_DB, op, value, NULL);
862 else if (streq(attr, "cmdline"))
863 r = rule_line_add_token(rule_line, TK_M_IMPORT_CMDLINE, op, value, NULL);
864 else if (streq(attr, "parent"))
865 r = rule_line_add_token(rule_line, TK_M_IMPORT_PARENT, op, value, NULL);
866 else
867 return log_line_invalid_attr(rule_line, key);
868 } else if (streq(key, "RESULT")) {
869 if (attr)
870 return log_line_invalid_attr(rule_line, key);
871 if (!is_match)
872 return log_line_invalid_op(rule_line, key);
874 r = rule_line_add_token(rule_line, TK_M_RESULT, op, value, NULL);
875 } else if (streq(key, "OPTIONS")) {
876 char *tmp;
878 if (attr)
879 return log_line_invalid_attr(rule_line, key);
880 if (is_match || op == OP_REMOVE)
881 return log_line_invalid_op(rule_line, key);
882 if (op == OP_ADD)
883 op = OP_ASSIGN;
885 if (streq(value, "string_escape=none"))
886 r = rule_line_add_token(rule_line, TK_A_OPTIONS_STRING_ESCAPE_NONE, op, NULL, NULL);
887 else if (streq(value, "string_escape=replace"))
888 r = rule_line_add_token(rule_line, TK_A_OPTIONS_STRING_ESCAPE_REPLACE, op, NULL, NULL);
889 else if (streq(value, "db_persist"))
890 r = rule_line_add_token(rule_line, TK_A_OPTIONS_DB_PERSIST, op, NULL, NULL);
891 else if (streq(value, "watch"))
892 r = rule_line_add_token(rule_line, TK_A_OPTIONS_INOTIFY_WATCH, op, NULL, INT_TO_PTR(1));
893 else if (streq(value, "nowatch"))
894 r = rule_line_add_token(rule_line, TK_A_OPTIONS_INOTIFY_WATCH, op, NULL, INT_TO_PTR(0));
895 else if ((tmp = startswith(value, "static_node=")))
896 r = rule_line_add_token(rule_line, TK_A_OPTIONS_STATIC_NODE, op, tmp, NULL);
897 else if ((tmp = startswith(value, "link_priority="))) {
898 int prio;
900 r = safe_atoi(tmp, &prio);
901 if (r < 0)
902 return log_line_error_errno(rule_line, r, "Failed to parse link priority '%s': %m", tmp);
903 r = rule_line_add_token(rule_line, TK_A_OPTIONS_DEVLINK_PRIORITY, op, NULL, INT_TO_PTR(prio));
904 } else if ((tmp = startswith(value, "log_level="))) {
905 int level;
907 if (streq(tmp, "reset"))
908 level = -1;
909 else {
910 level = log_level_from_string(tmp);
911 if (level < 0)
912 return log_line_error_errno(rule_line, level, "Failed to parse log level '%s': %m", tmp);
914 r = rule_line_add_token(rule_line, TK_A_OPTIONS_LOG_LEVEL, op, NULL, INT_TO_PTR(level));
915 } else {
916 log_line_warning(rule_line, "Invalid value for OPTIONS key, ignoring: '%s'", value);
917 return 0;
919 } else if (streq(key, "OWNER")) {
920 uid_t uid;
922 if (attr)
923 return log_line_invalid_attr(rule_line, key);
924 if (is_match || op == OP_REMOVE)
925 return log_line_invalid_op(rule_line, key);
926 if (op == OP_ADD) {
927 log_line_warning(rule_line, "%s key takes '=' or ':=' operator, assuming '='.", key);
928 op = OP_ASSIGN;
931 if (parse_uid(value, &uid) >= 0)
932 r = rule_line_add_token(rule_line, TK_A_OWNER_ID, op, NULL, UID_TO_PTR(uid));
933 else if (resolve_name_timing == RESOLVE_NAME_EARLY &&
934 rule_get_substitution_type(value) == SUBST_TYPE_PLAIN) {
935 r = rule_resolve_user(rule_line, value, &uid);
936 if (r < 0)
937 return log_line_error_errno(rule_line, r, "Failed to resolve user name '%s': %m", value);
939 r = rule_line_add_token(rule_line, TK_A_OWNER_ID, op, NULL, UID_TO_PTR(uid));
940 } else if (resolve_name_timing != RESOLVE_NAME_NEVER) {
941 check_value_format_and_warn(rule_line, key, value, true);
942 r = rule_line_add_token(rule_line, TK_A_OWNER, op, value, NULL);
943 } else {
944 log_line_debug(rule_line, "User name resolution is disabled, ignoring %s=\"%s\".", key, value);
945 return 0;
947 } else if (streq(key, "GROUP")) {
948 gid_t gid;
950 if (attr)
951 return log_line_invalid_attr(rule_line, key);
952 if (is_match || op == OP_REMOVE)
953 return log_line_invalid_op(rule_line, key);
954 if (op == OP_ADD) {
955 log_line_warning(rule_line, "%s key takes '=' or ':=' operator, assuming '='.", key);
956 op = OP_ASSIGN;
959 if (parse_gid(value, &gid) >= 0)
960 r = rule_line_add_token(rule_line, TK_A_GROUP_ID, op, NULL, GID_TO_PTR(gid));
961 else if (resolve_name_timing == RESOLVE_NAME_EARLY &&
962 rule_get_substitution_type(value) == SUBST_TYPE_PLAIN) {
963 r = rule_resolve_group(rule_line, value, &gid);
964 if (r < 0)
965 return log_line_error_errno(rule_line, r, "Failed to resolve group name '%s': %m", value);
967 r = rule_line_add_token(rule_line, TK_A_GROUP_ID, op, NULL, GID_TO_PTR(gid));
968 } else if (resolve_name_timing != RESOLVE_NAME_NEVER) {
969 check_value_format_and_warn(rule_line, key, value, true);
970 r = rule_line_add_token(rule_line, TK_A_GROUP, op, value, NULL);
971 } else {
972 log_line_debug(rule_line, "Resolving group name is disabled, ignoring GROUP=\"%s\".", value);
973 return 0;
975 } else if (streq(key, "MODE")) {
976 mode_t mode;
978 if (attr)
979 return log_line_invalid_attr(rule_line, key);
980 if (is_match || op == OP_REMOVE)
981 return log_line_invalid_op(rule_line, key);
982 if (op == OP_ADD) {
983 log_line_warning(rule_line, "%s key takes '=' or ':=' operator, assuming '='.", key);
984 op = OP_ASSIGN;
987 if (parse_mode(value, &mode) >= 0)
988 r = rule_line_add_token(rule_line, TK_A_MODE_ID, op, NULL, MODE_TO_PTR(mode));
989 else {
990 check_value_format_and_warn(rule_line, key, value, true);
991 r = rule_line_add_token(rule_line, TK_A_MODE, op, value, NULL);
993 } else if (streq(key, "SECLABEL")) {
994 if (isempty(attr))
995 return log_line_invalid_attr(rule_line, key);
996 check_value_format_and_warn(rule_line, key, value, true);
997 if (is_match || op == OP_REMOVE)
998 return log_line_invalid_op(rule_line, key);
999 if (op == OP_ASSIGN_FINAL) {
1000 log_line_warning(rule_line, "%s key takes '=' or '+=' operator, assuming '='.", key);
1001 op = OP_ASSIGN;
1004 r = rule_line_add_token(rule_line, TK_A_SECLABEL, op, value, attr);
1005 } else if (streq(key, "RUN")) {
1006 if (is_match || op == OP_REMOVE)
1007 return log_line_invalid_op(rule_line, key);
1008 check_value_format_and_warn(rule_line, key, value, true);
1009 if (!attr || streq(attr, "program"))
1010 r = rule_line_add_token(rule_line, TK_A_RUN_PROGRAM, op, value, NULL);
1011 else if (streq(attr, "builtin")) {
1012 UdevBuiltinCommand cmd;
1014 cmd = udev_builtin_lookup(value);
1015 if (cmd < 0)
1016 return log_line_error_errno(rule_line, SYNTHETIC_ERRNO(EINVAL),
1017 "Unknown builtin command '%s', ignoring.", value);
1018 r = rule_line_add_token(rule_line, TK_A_RUN_BUILTIN, op, value, UDEV_BUILTIN_CMD_TO_PTR(cmd));
1019 } else
1020 return log_line_invalid_attr(rule_line, key);
1021 } else if (streq(key, "GOTO")) {
1022 if (attr)
1023 return log_line_invalid_attr(rule_line, key);
1024 if (op != OP_ASSIGN)
1025 return log_line_invalid_op(rule_line, key);
1026 if (FLAGS_SET(rule_line->type, LINE_HAS_GOTO)) {
1027 log_line_warning(rule_line, "Contains multiple GOTO keys, ignoring GOTO=\"%s\".", value);
1028 return 0;
1031 rule_line->goto_label = value;
1032 SET_FLAG(rule_line->type, LINE_HAS_GOTO, true);
1033 return 1;
1034 } else if (streq(key, "LABEL")) {
1035 if (attr)
1036 return log_line_invalid_attr(rule_line, key);
1037 if (op != OP_ASSIGN)
1038 return log_line_invalid_op(rule_line, key);
1039 if (FLAGS_SET(rule_line->type, LINE_HAS_LABEL))
1040 log_line_warning(rule_line, "Contains multiple LABEL keys, ignoring LABEL=\"%s\".",
1041 rule_line->label);
1043 rule_line->label = value;
1044 SET_FLAG(rule_line->type, LINE_HAS_LABEL, true);
1045 return 1;
1046 } else
1047 return log_line_error_errno(rule_line, SYNTHETIC_ERRNO(EINVAL), "Invalid key '%s'.", key);
1048 if (r < 0)
1049 return log_oom();
1051 return 1;
1054 static UdevRuleOperatorType parse_operator(const char *op) {
1055 assert(op);
1057 if (startswith(op, "=="))
1058 return OP_MATCH;
1059 if (startswith(op, "!="))
1060 return OP_NOMATCH;
1061 if (startswith(op, "+="))
1062 return OP_ADD;
1063 if (startswith(op, "-="))
1064 return OP_REMOVE;
1065 if (startswith(op, "="))
1066 return OP_ASSIGN;
1067 if (startswith(op, ":="))
1068 return OP_ASSIGN_FINAL;
1070 return _OP_TYPE_INVALID;
1073 static void check_token_delimiters(UdevRuleLine *rule_line, const char *line) {
1074 assert(rule_line);
1076 size_t n_comma = 0;
1077 bool ws_before_comma = false, ws_after_comma = false;
1078 const char *p;
1080 for (p = line; !isempty(p); ++p) {
1081 if (*p == ',')
1082 ++n_comma;
1083 else if (strchr(WHITESPACE, *p)) {
1084 if (n_comma > 0)
1085 ws_after_comma = true;
1086 else
1087 ws_before_comma = true;
1088 } else
1089 break;
1092 if (line == rule_line->line) {
1093 /* this is the first token of the rule */
1094 if (n_comma > 0)
1095 log_line_notice(rule_line, "style: stray leading comma.");
1096 } else if (isempty(p)) {
1097 /* there are no more tokens in the rule */
1098 if (n_comma > 0)
1099 log_line_notice(rule_line, "style: stray trailing comma.");
1100 } else {
1101 /* single comma is expected */
1102 if (n_comma == 0)
1103 log_line_notice(rule_line, "style: a comma between tokens is expected.");
1104 else if (n_comma > 1)
1105 log_line_notice(rule_line, "style: more than one comma between tokens.");
1107 /* whitespace after comma is expected */
1108 if (n_comma > 0) {
1109 if (ws_before_comma)
1110 log_line_notice(rule_line, "style: stray whitespace before comma.");
1111 if (!ws_after_comma)
1112 log_line_notice(rule_line, "style: whitespace after comma is expected.");
1113 } else if (!ws_before_comma && !ws_after_comma)
1114 log_line_notice(rule_line, "style: whitespace between tokens is expected.");
1118 static int parse_line(char **line, char **ret_key, char **ret_attr, UdevRuleOperatorType *ret_op, char **ret_value) {
1119 char *key_begin, *key_end, *attr, *tmp;
1120 UdevRuleOperatorType op;
1121 int r;
1123 assert(line);
1124 assert(*line);
1125 assert(ret_key);
1126 assert(ret_op);
1127 assert(ret_value);
1129 key_begin = skip_leading_chars(*line, WHITESPACE ",");
1131 if (isempty(key_begin))
1132 return 0;
1134 for (key_end = key_begin; ; key_end++) {
1135 if (key_end[0] == '\0')
1136 return -EINVAL;
1137 if (strchr(WHITESPACE "={", key_end[0]))
1138 break;
1139 if (strchr("+-!:", key_end[0]) && key_end[1] == '=')
1140 break;
1142 if (key_end[0] == '{') {
1143 attr = key_end + 1;
1144 tmp = strchr(attr, '}');
1145 if (!tmp)
1146 return -EINVAL;
1147 *tmp++ = '\0';
1148 } else {
1149 attr = NULL;
1150 tmp = key_end;
1153 tmp = skip_leading_chars(tmp, NULL);
1154 op = parse_operator(tmp);
1155 if (op < 0)
1156 return -EINVAL;
1158 key_end[0] = '\0';
1160 tmp += op == OP_ASSIGN ? 1 : 2;
1161 tmp = skip_leading_chars(tmp, NULL);
1162 r = udev_rule_parse_value(tmp, ret_value, line);
1163 if (r < 0)
1164 return r;
1166 *ret_key = key_begin;
1167 *ret_attr = attr;
1168 *ret_op = op;
1169 return 1;
1172 static void check_tokens_order(UdevRuleLine *rule_line) {
1173 bool has_result = false;
1175 assert(rule_line);
1177 LIST_FOREACH(tokens, t, rule_line->tokens)
1178 if (t->type == TK_M_RESULT)
1179 has_result = true;
1180 else if (has_result && t->type == TK_M_PROGRAM) {
1181 log_line_warning(rule_line, "Reordering RESULT check after PROGRAM assignment.");
1182 break;
1186 static void sort_tokens(UdevRuleLine *rule_line) {
1187 assert(rule_line);
1189 UdevRuleToken *old_tokens = TAKE_PTR(rule_line->tokens);
1191 while (old_tokens) {
1192 UdevRuleToken *min_token = NULL;
1194 LIST_FOREACH(tokens, t, old_tokens)
1195 if (!min_token || min_token->type > t->type)
1196 min_token = t;
1198 LIST_REMOVE(tokens, old_tokens, min_token);
1199 LIST_APPEND(tokens, rule_line->tokens, min_token);
1203 static int rule_add_line(UdevRuleFile *rule_file, const char *line_str, unsigned line_nr, bool extra_checks) {
1204 _cleanup_(udev_rule_line_freep) UdevRuleLine *rule_line = NULL;
1205 _cleanup_free_ char *line = NULL;
1206 char *p;
1207 int r;
1209 assert(rule_file);
1210 assert(line_str);
1212 if (isempty(line_str))
1213 return 0;
1215 line = strdup(line_str);
1216 if (!line)
1217 return log_oom();
1219 rule_line = new(UdevRuleLine, 1);
1220 if (!rule_line)
1221 return log_oom();
1223 *rule_line = (UdevRuleLine) {
1224 .line = TAKE_PTR(line),
1225 .line_number = line_nr,
1226 .rule_file = rule_file,
1229 LIST_APPEND(rule_lines, rule_file->rule_lines, rule_line);
1231 for (p = rule_line->line; !isempty(p); ) {
1232 char *key, *attr, *value;
1233 UdevRuleOperatorType op;
1235 if (extra_checks)
1236 check_token_delimiters(rule_line, p);
1238 r = parse_line(&p, &key, &attr, &op, &value);
1239 if (r < 0)
1240 return log_line_error_errno(rule_line, r, "Invalid key/value pair, ignoring.");
1241 if (r == 0)
1242 break;
1244 r = parse_token(rule_line, key, attr, op, value);
1245 if (r < 0)
1246 return r;
1249 if (rule_line->type == 0) {
1250 log_line_warning(rule_line, "The line has no effect, ignoring.");
1251 return 0;
1254 if (extra_checks)
1255 check_tokens_order(rule_line);
1257 sort_tokens(rule_line);
1258 TAKE_PTR(rule_line);
1259 return 0;
1262 static void rule_resolve_goto(UdevRuleFile *rule_file) {
1263 assert(rule_file);
1265 /* link GOTOs to LABEL rules in this file to be able to fast-forward */
1266 LIST_FOREACH(rule_lines, line, rule_file->rule_lines) {
1267 if (!FLAGS_SET(line->type, LINE_HAS_GOTO))
1268 continue;
1270 LIST_FOREACH(rule_lines, i, line->rule_lines_next)
1271 if (streq_ptr(i->label, line->goto_label)) {
1272 line->goto_line = i;
1273 SET_FLAG(i->type, LINE_IS_REFERENCED, true);
1274 break;
1277 if (!line->goto_line) {
1278 log_line_error(line, "GOTO=\"%s\" has no matching label, ignoring.",
1279 line->goto_label);
1281 SET_FLAG(line->type, LINE_HAS_GOTO, false);
1282 line->goto_label = NULL;
1284 if ((line->type & ~(LINE_HAS_LABEL|LINE_IS_REFERENCED)) == 0) {
1285 log_line_warning(line, "The line has no effect any more, dropping.");
1286 /* LINE_IS_REFERENCED implies LINE_HAS_LABEL */
1287 if (line->type & LINE_HAS_LABEL)
1288 udev_rule_line_clear_tokens(line);
1289 else
1290 udev_rule_line_free(line);
1296 static bool token_data_is_string(UdevRuleTokenType type) {
1297 return IN_SET(type, TK_M_ENV,
1298 TK_M_CONST,
1299 TK_M_ATTR,
1300 TK_M_SYSCTL,
1301 TK_M_PARENTS_ATTR,
1302 TK_A_SECLABEL,
1303 TK_A_ENV,
1304 TK_A_ATTR,
1305 TK_A_SYSCTL);
1308 static bool token_type_and_data_eq(const UdevRuleToken *a, const UdevRuleToken *b) {
1309 assert(a);
1310 assert(b);
1312 return a->type == b->type &&
1313 (token_data_is_string(a->type) ? streq_ptr(a->data, b->data) : (a->data == b->data));
1316 static bool nulstr_eq(const char *a, const char *b) {
1317 NULSTR_FOREACH(i, a)
1318 if (!nulstr_contains(b, i))
1319 return false;
1321 NULSTR_FOREACH(i, b)
1322 if (!nulstr_contains(a, i))
1323 return false;
1325 return true;
1328 static bool token_type_and_value_eq(const UdevRuleToken *a, const UdevRuleToken *b) {
1329 assert(a);
1330 assert(b);
1332 if (a->type != b->type ||
1333 a->match_type != b->match_type)
1334 return false;
1336 /* token value is ignored for certain match types */
1337 if (IN_SET(a->match_type, MATCH_TYPE_EMPTY, MATCH_TYPE_SUBSYSTEM))
1338 return true;
1340 return type_has_nulstr_value(a->type) ? nulstr_eq(a->value, b->value) :
1341 streq_ptr(a->value, b->value);
1344 static bool conflicting_op(UdevRuleOperatorType a, UdevRuleOperatorType b) {
1345 return (a == OP_MATCH && b == OP_NOMATCH) ||
1346 (a == OP_NOMATCH && b == OP_MATCH);
1349 /* test whether all fields besides UdevRuleOperatorType of two tokens match */
1350 static bool tokens_eq(const UdevRuleToken *a, const UdevRuleToken *b) {
1351 assert(a);
1352 assert(b);
1354 return a->attr_subst_type == b->attr_subst_type &&
1355 a->attr_match_remove_trailing_whitespace == b->attr_match_remove_trailing_whitespace &&
1356 token_type_and_value_eq(a, b) &&
1357 token_type_and_data_eq(a, b);
1360 static bool nulstr_tokens_conflict(const UdevRuleToken *a, const UdevRuleToken *b) {
1361 assert(a);
1362 assert(b);
1364 if (!(a->type == b->type &&
1365 type_has_nulstr_value(a->type) &&
1366 a->op == b->op &&
1367 a->op == OP_MATCH &&
1368 a->match_type == b->match_type &&
1369 a->attr_subst_type == b->attr_subst_type &&
1370 a->attr_match_remove_trailing_whitespace == b->attr_match_remove_trailing_whitespace &&
1371 token_type_and_data_eq(a, b)))
1372 return false;
1374 if (a->match_type == MATCH_TYPE_PLAIN) {
1375 NULSTR_FOREACH(i, a->value)
1376 if (nulstr_contains(b->value, i))
1377 return false;
1378 return true;
1381 if (a->match_type == MATCH_TYPE_GLOB) {
1382 NULSTR_FOREACH(i, a->value) {
1383 size_t i_n = strcspn(i, GLOB_CHARS);
1384 if (i_n == 0)
1385 return false;
1386 NULSTR_FOREACH(j, b->value) {
1387 size_t j_n = strcspn(j, GLOB_CHARS);
1388 if (j_n == 0 || strneq(i, j, MIN(i_n, j_n)))
1389 return false;
1393 return true;
1396 return false;
1399 static void udev_check_unused_labels(UdevRuleLine *line) {
1400 assert(line);
1402 if (FLAGS_SET(line->type, LINE_HAS_LABEL) &&
1403 !FLAGS_SET(line->type, LINE_IS_REFERENCED))
1404 log_line_notice(line, "style: LABEL=\"%s\" is unused.", line->label);
1407 static void udev_check_conflicts_duplicates(UdevRuleLine *line) {
1408 assert(line);
1410 bool conflicts = false, duplicates = false;
1412 LIST_FOREACH(tokens, token, line->tokens)
1413 LIST_FOREACH(tokens, i, token->tokens_next) {
1414 bool new_conflicts = false, new_duplicates = false;
1416 if (tokens_eq(token, i)) {
1417 if (!duplicates && token->op == i->op)
1418 new_duplicates = true;
1419 if (!conflicts && conflicting_op(token->op, i->op))
1420 new_conflicts = true;
1421 } else if (!conflicts && nulstr_tokens_conflict(token, i))
1422 new_conflicts = true;
1423 else
1424 continue;
1426 if (new_duplicates) {
1427 duplicates = new_duplicates;
1428 log_line_warning(line, "duplicate expressions.");
1430 if (new_conflicts) {
1431 conflicts = new_conflicts;
1432 log_line_error(line, "conflicting match expressions, the line has no effect.");
1434 if (conflicts && duplicates)
1435 return;
1439 static void udev_check_rule_line(UdevRuleLine *line) {
1440 udev_check_unused_labels(line);
1441 udev_check_conflicts_duplicates(line);
1444 int udev_rules_parse_file(UdevRules *rules, const char *filename, bool extra_checks, UdevRuleFile **ret) {
1445 _cleanup_(udev_rule_file_freep) UdevRuleFile *rule_file = NULL;
1446 _cleanup_free_ char *continuation = NULL, *name = NULL;
1447 _cleanup_fclose_ FILE *f = NULL;
1448 bool ignore_line = false;
1449 unsigned line_nr = 0;
1450 struct stat st;
1451 int r;
1453 assert(rules);
1454 assert(filename);
1456 f = fopen(filename, "re");
1457 if (!f) {
1458 if (extra_checks)
1459 return -errno;
1461 if (errno == ENOENT)
1462 return 0;
1464 return log_warning_errno(errno, "Failed to open %s, ignoring: %m", filename);
1467 if (fstat(fileno(f), &st) < 0)
1468 return log_warning_errno(errno, "Failed to stat %s, ignoring: %m", filename);
1470 if (null_or_empty(&st)) {
1471 log_debug("Skipping empty file: %s", filename);
1472 if (ret)
1473 *ret = NULL;
1474 return 0;
1477 r = hashmap_put_stats_by_path(&rules->stats_by_path, filename, &st);
1478 if (r < 0)
1479 return log_warning_errno(errno, "Failed to save stat for %s, ignoring: %m", filename);
1481 (void) fd_warn_permissions(filename, fileno(f));
1483 log_debug("Reading rules file: %s", filename);
1485 name = strdup(filename);
1486 if (!name)
1487 return log_oom();
1489 rule_file = new(UdevRuleFile, 1);
1490 if (!rule_file)
1491 return log_oom();
1493 *rule_file = (UdevRuleFile) {
1494 .filename = TAKE_PTR(name),
1495 .rules = rules,
1498 LIST_APPEND(rule_files, rules->rule_files, rule_file);
1500 for (;;) {
1501 _cleanup_free_ char *buf = NULL;
1502 size_t len;
1503 char *line;
1505 r = read_line(f, UDEV_LINE_SIZE, &buf);
1506 if (r < 0)
1507 return r;
1508 if (r == 0)
1509 break;
1511 line_nr++;
1512 line = skip_leading_chars(buf, NULL);
1514 /* Lines beginning with '#' are ignored regardless of line continuation. */
1515 if (line[0] == '#')
1516 continue;
1518 len = strlen(line);
1520 if (continuation && !ignore_line) {
1521 if (strlen(continuation) + len >= UDEV_LINE_SIZE)
1522 ignore_line = true;
1524 if (!strextend(&continuation, line))
1525 return log_oom();
1527 if (!ignore_line) {
1528 line = continuation;
1529 len = strlen(line);
1533 if (len > 0 && line[len - 1] == '\\') {
1534 if (ignore_line)
1535 continue;
1537 line[len - 1] = '\0';
1538 if (!continuation) {
1539 continuation = strdup(line);
1540 if (!continuation)
1541 return log_oom();
1544 continue;
1547 if (ignore_line)
1548 log_file_error(rule_file, line_nr, "Line is too long, ignored.");
1549 else if (len > 0)
1550 (void) rule_add_line(rule_file, line, line_nr, extra_checks);
1552 continuation = mfree(continuation);
1553 ignore_line = false;
1556 if (continuation)
1557 log_file_error(rule_file, line_nr,
1558 "Unexpected EOF after line continuation, line ignored.");
1560 rule_resolve_goto(rule_file);
1562 if (extra_checks)
1563 LIST_FOREACH(rule_lines, line, rule_file->rule_lines)
1564 udev_check_rule_line(line);
1566 if (ret)
1567 *ret = rule_file;
1569 TAKE_PTR(rule_file);
1570 return 1;
1573 unsigned udev_rule_file_get_issues(UdevRuleFile *rule_file) {
1574 assert(rule_file);
1576 return rule_file->issues;
1579 UdevRules* udev_rules_new(ResolveNameTiming resolve_name_timing) {
1580 assert(resolve_name_timing >= 0 && resolve_name_timing < _RESOLVE_NAME_TIMING_MAX);
1582 UdevRules *rules = new(UdevRules, 1);
1583 if (!rules)
1584 return NULL;
1586 *rules = (UdevRules) {
1587 .resolve_name_timing = resolve_name_timing,
1590 return rules;
1593 int udev_rules_load(UdevRules **ret_rules, ResolveNameTiming resolve_name_timing) {
1594 _cleanup_(udev_rules_freep) UdevRules *rules = NULL;
1595 _cleanup_strv_free_ char **files = NULL;
1596 int r;
1598 rules = udev_rules_new(resolve_name_timing);
1599 if (!rules)
1600 return -ENOMEM;
1602 r = conf_files_list_strv(&files, ".rules", NULL, 0, RULES_DIRS);
1603 if (r < 0)
1604 return log_debug_errno(r, "Failed to enumerate rules files: %m");
1606 STRV_FOREACH(f, files) {
1607 r = udev_rules_parse_file(rules, *f, /* extra_checks = */ false, NULL);
1608 if (r < 0)
1609 log_debug_errno(r, "Failed to read rules file %s, ignoring: %m", *f);
1612 *ret_rules = TAKE_PTR(rules);
1613 return 0;
1616 bool udev_rules_should_reload(UdevRules *rules) {
1617 _cleanup_hashmap_free_ Hashmap *stats_by_path = NULL;
1618 int r;
1620 if (!rules)
1621 return true;
1623 r = config_get_stats_by_path(".rules", NULL, 0, RULES_DIRS, /* check_dropins = */ false, &stats_by_path);
1624 if (r < 0) {
1625 log_warning_errno(r, "Failed to get stats of udev rules, ignoring: %m");
1626 return true;
1629 if (!stats_by_path_equal(rules->stats_by_path, stats_by_path)) {
1630 log_debug("Udev rules need reloading");
1631 return true;
1634 return false;
1637 static bool token_match_string(UdevRuleToken *token, const char *str) {
1638 const char *value;
1639 bool match = false;
1641 assert(token);
1642 assert(token->value);
1643 assert(token->type < _TK_M_MAX);
1645 str = strempty(str);
1646 value = token->value;
1648 switch (token->match_type) {
1649 case MATCH_TYPE_EMPTY:
1650 match = isempty(str);
1651 break;
1652 case MATCH_TYPE_SUBSYSTEM:
1653 match = STR_IN_SET(str, "subsystem", "class", "bus");
1654 break;
1655 case MATCH_TYPE_PLAIN_WITH_EMPTY:
1656 if (isempty(str)) {
1657 match = true;
1658 break;
1660 _fallthrough_;
1661 case MATCH_TYPE_PLAIN:
1662 NULSTR_FOREACH(i, value)
1663 if (streq(i, str)) {
1664 match = true;
1665 break;
1667 break;
1668 case MATCH_TYPE_GLOB_WITH_EMPTY:
1669 if (isempty(str)) {
1670 match = true;
1671 break;
1673 _fallthrough_;
1674 case MATCH_TYPE_GLOB:
1675 NULSTR_FOREACH(i, value)
1676 if ((fnmatch(i, str, 0) == 0)) {
1677 match = true;
1678 break;
1680 break;
1681 default:
1682 assert_not_reached();
1685 return token->op == (match ? OP_MATCH : OP_NOMATCH);
1688 static bool token_match_attr(UdevRuleToken *token, sd_device *dev, UdevEvent *event) {
1689 char nbuf[UDEV_NAME_SIZE], vbuf[UDEV_NAME_SIZE];
1690 const char *name, *value;
1691 bool truncated;
1693 assert(token);
1694 assert(IN_SET(token->type, TK_M_ATTR, TK_M_PARENTS_ATTR));
1695 assert(dev);
1696 assert(event);
1698 name = token->data;
1700 switch (token->attr_subst_type) {
1701 case SUBST_TYPE_FORMAT:
1702 (void) udev_event_apply_format(event, name, nbuf, sizeof(nbuf), false, &truncated);
1703 if (truncated) {
1704 log_event_truncated(dev, token, "sysfs attribute name", name,
1705 token->type == TK_M_ATTR ? "ATTR" : "ATTRS", /* is_match = */ true);
1706 return false;
1709 name = nbuf;
1710 _fallthrough_;
1711 case SUBST_TYPE_PLAIN:
1712 if (sd_device_get_sysattr_value(dev, name, &value) < 0)
1713 return false;
1714 break;
1715 case SUBST_TYPE_SUBSYS:
1716 if (udev_resolve_subsys_kernel(name, vbuf, sizeof(vbuf), true) < 0)
1717 return false;
1718 value = vbuf;
1719 break;
1720 default:
1721 assert_not_reached();
1724 /* remove trailing whitespace, if not asked to match for it */
1725 if (token->attr_match_remove_trailing_whitespace) {
1726 if (value != vbuf) {
1727 strscpy(vbuf, sizeof(vbuf), value);
1728 value = vbuf;
1731 delete_trailing_chars(vbuf, NULL);
1734 return token_match_string(token, value);
1737 static int get_property_from_string(char *line, char **ret_key, char **ret_value) {
1738 char *key, *val;
1739 size_t len;
1741 assert(line);
1742 assert(ret_key);
1743 assert(ret_value);
1745 /* find key */
1746 key = skip_leading_chars(line, NULL);
1748 /* comment or empty line */
1749 if (IN_SET(key[0], '#', '\0')) {
1750 *ret_key = *ret_value = NULL;
1751 return 0;
1754 /* split key/value */
1755 val = strchr(key, '=');
1756 if (!val)
1757 return -EINVAL;
1758 *val++ = '\0';
1760 key = strstrip(key);
1761 if (isempty(key))
1762 return -EINVAL;
1764 val = strstrip(val);
1765 if (isempty(val))
1766 return -EINVAL;
1768 /* unquote */
1769 if (IN_SET(val[0], '"', '\'')) {
1770 len = strlen(val);
1771 if (len == 1 || val[len-1] != val[0])
1772 return -EINVAL;
1773 val[len-1] = '\0';
1774 val++;
1777 *ret_key = key;
1778 *ret_value = val;
1779 return 1;
1782 static int import_parent_into_properties(sd_device *dev, const char *filter) {
1783 sd_device *parent;
1784 int r;
1786 assert(dev);
1787 assert(filter);
1789 r = sd_device_get_parent(dev, &parent);
1790 if (r == -ENOENT)
1791 return 0;
1792 if (r < 0)
1793 return r;
1795 FOREACH_DEVICE_PROPERTY(parent, key, val) {
1796 if (fnmatch(filter, key, 0) != 0)
1797 continue;
1798 r = device_add_property(dev, key, val);
1799 if (r < 0)
1800 return r;
1803 return 1;
1806 static int attr_subst_subdir(char attr[static UDEV_PATH_SIZE]) {
1807 _cleanup_closedir_ DIR *dir = NULL;
1808 char buf[UDEV_PATH_SIZE], *p;
1809 const char *tail;
1810 size_t len, size;
1811 bool truncated;
1813 assert(attr);
1815 tail = strstr(attr, "/*/");
1816 if (!tail)
1817 return 0;
1819 len = tail - attr + 1; /* include slash at the end */
1820 tail += 2; /* include slash at the beginning */
1822 p = buf;
1823 size = sizeof(buf);
1824 size -= strnpcpy_full(&p, size, attr, len, &truncated);
1825 if (truncated)
1826 return -ENOENT;
1828 dir = opendir(buf);
1829 if (!dir)
1830 return -errno;
1832 FOREACH_DIRENT_ALL(de, dir, break) {
1833 if (de->d_name[0] == '.')
1834 continue;
1836 strscpyl_full(p, size, &truncated, de->d_name, tail, NULL);
1837 if (truncated)
1838 continue;
1840 if (faccessat(dirfd(dir), p, F_OK, 0) < 0)
1841 continue;
1843 strcpy(attr, buf);
1844 return 0;
1847 return -ENOENT;
1850 static int udev_rule_apply_token_to_event(
1851 UdevRuleToken *token,
1852 sd_device *dev,
1853 UdevEvent *event,
1854 usec_t timeout_usec,
1855 int timeout_signal,
1856 Hashmap *properties_list) {
1858 int r;
1860 assert(token);
1861 assert(dev);
1862 assert(event);
1864 /* This returns the following values:
1865 * 0 on the current token does not match the event,
1866 * 1 on the current token matches the event, and
1867 * negative errno on some critical errors. */
1869 switch (token->type) {
1870 case TK_M_ACTION: {
1871 sd_device_action_t a;
1873 r = sd_device_get_action(dev, &a);
1874 if (r < 0)
1875 return log_event_error_errno(dev, token, r, "Failed to get uevent action type: %m");
1877 return token_match_string(token, device_action_to_string(a));
1879 case TK_M_DEVPATH: {
1880 const char *val;
1882 r = sd_device_get_devpath(dev, &val);
1883 if (r < 0)
1884 return log_event_error_errno(dev, token, r, "Failed to get devpath: %m");
1886 return token_match_string(token, val);
1888 case TK_M_KERNEL:
1889 case TK_M_PARENTS_KERNEL: {
1890 const char *val;
1892 r = sd_device_get_sysname(dev, &val);
1893 if (r < 0)
1894 return log_event_error_errno(dev, token, r, "Failed to get sysname: %m");
1896 return token_match_string(token, val);
1898 case TK_M_DEVLINK:
1899 FOREACH_DEVICE_DEVLINK(dev, val)
1900 if (token_match_string(token, strempty(startswith(val, "/dev/"))) == (token->op == OP_MATCH))
1901 return token->op == OP_MATCH;
1902 return token->op == OP_NOMATCH;
1903 case TK_M_NAME:
1904 return token_match_string(token, event->name);
1905 case TK_M_ENV: {
1906 const char *val;
1908 if (sd_device_get_property_value(dev, token->data, &val) < 0)
1909 val = hashmap_get(properties_list, token->data);
1911 return token_match_string(token, val);
1913 case TK_M_CONST: {
1914 const char *val, *k = token->data;
1916 if (streq(k, "arch"))
1917 val = architecture_to_string(uname_architecture());
1918 else if (streq(k, "virt"))
1919 val = virtualization_to_string(detect_virtualization());
1920 else if (streq(k, "cvm"))
1921 val = confidential_virtualization_to_string(detect_confidential_virtualization());
1922 else
1923 assert_not_reached();
1924 return token_match_string(token, val);
1926 case TK_M_TAG:
1927 case TK_M_PARENTS_TAG:
1928 FOREACH_DEVICE_CURRENT_TAG(dev, val)
1929 if (token_match_string(token, val) == (token->op == OP_MATCH))
1930 return token->op == OP_MATCH;
1931 return token->op == OP_NOMATCH;
1932 case TK_M_SUBSYSTEM:
1933 case TK_M_PARENTS_SUBSYSTEM: {
1934 const char *val;
1936 r = sd_device_get_subsystem(dev, &val);
1937 if (r == -ENOENT)
1938 val = NULL;
1939 else if (r < 0)
1940 return log_event_error_errno(dev, token, r, "Failed to get subsystem: %m");
1942 return token_match_string(token, val);
1944 case TK_M_DRIVER:
1945 case TK_M_PARENTS_DRIVER: {
1946 const char *val;
1948 r = sd_device_get_driver(dev, &val);
1949 if (r == -ENOENT)
1950 val = NULL;
1951 else if (r < 0)
1952 return log_event_error_errno(dev, token, r, "Failed to get driver: %m");
1954 return token_match_string(token, val);
1956 case TK_M_ATTR:
1957 case TK_M_PARENTS_ATTR:
1958 return token_match_attr(token, dev, event);
1959 case TK_M_SYSCTL: {
1960 _cleanup_free_ char *value = NULL;
1961 char buf[UDEV_PATH_SIZE];
1962 bool truncated;
1964 (void) udev_event_apply_format(event, token->data, buf, sizeof(buf), false, &truncated);
1965 if (truncated) {
1966 log_event_truncated(dev, token, "sysctl entry name", token->data, "SYSCTL", /* is_match = */ true);
1967 return false;
1970 r = sysctl_read(sysctl_normalize(buf), &value);
1971 if (r < 0 && r != -ENOENT)
1972 return log_event_error_errno(dev, token, r, "Failed to read sysctl '%s': %m", buf);
1974 return token_match_string(token, strstrip(value));
1976 case TK_M_TEST: {
1977 mode_t mode = PTR_TO_MODE(token->data);
1978 char buf[UDEV_PATH_SIZE];
1979 struct stat statbuf;
1980 bool match, truncated;
1982 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
1983 if (truncated) {
1984 log_event_truncated(dev, token, "file name", token->value, "TEST", /* is_match = */ true);
1985 return false;
1988 if (!path_is_absolute(buf) &&
1989 udev_resolve_subsys_kernel(buf, buf, sizeof(buf), false) < 0) {
1990 char tmp[UDEV_PATH_SIZE];
1991 const char *val;
1993 r = sd_device_get_syspath(dev, &val);
1994 if (r < 0)
1995 return log_event_error_errno(dev, token, r, "Failed to get syspath: %m");
1997 strscpy_full(tmp, sizeof(tmp), buf, &truncated);
1998 assert(!truncated);
1999 strscpyl_full(buf, sizeof(buf), &truncated, val, "/", tmp, NULL);
2000 if (truncated)
2001 return false;
2004 r = attr_subst_subdir(buf);
2005 if (r == -ENOENT)
2006 return token->op == OP_NOMATCH;
2007 if (r < 0)
2008 return log_event_error_errno(dev, token, r, "Failed to test for the existence of '%s': %m", buf);
2010 if (stat(buf, &statbuf) < 0)
2011 return token->op == OP_NOMATCH;
2013 if (mode == MODE_INVALID)
2014 return token->op == OP_MATCH;
2016 match = (statbuf.st_mode & mode) > 0;
2017 return token->op == (match ? OP_MATCH : OP_NOMATCH);
2019 case TK_M_PROGRAM: {
2020 char buf[UDEV_LINE_SIZE], result[UDEV_LINE_SIZE];
2021 bool truncated;
2022 size_t count;
2024 event->program_result = mfree(event->program_result);
2025 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2026 if (truncated) {
2027 log_event_truncated(dev, token, "command", token->value, "PROGRAM", /* is_match = */ true);
2028 return false;
2031 log_event_debug(dev, token, "Running PROGRAM '%s'", buf);
2033 r = udev_event_spawn(event, timeout_usec, timeout_signal, true, buf, result, sizeof(result), NULL);
2034 if (r != 0) {
2035 if (r < 0)
2036 log_event_warning_errno(dev, token, r, "Failed to execute \"%s\": %m", buf);
2037 else /* returned value is positive when program fails */
2038 log_event_debug(dev, token, "Command \"%s\" returned %d (error)", buf, r);
2039 return token->op == OP_NOMATCH;
2042 delete_trailing_chars(result, "\n");
2043 count = udev_replace_chars(result, UDEV_ALLOWED_CHARS_INPUT);
2044 if (count > 0)
2045 log_event_debug(dev, token,
2046 "Replaced %zu character(s) in result of \"%s\"",
2047 count, buf);
2049 event->program_result = strdup(result);
2050 return token->op == OP_MATCH;
2052 case TK_M_IMPORT_FILE: {
2053 _cleanup_fclose_ FILE *f = NULL;
2054 char buf[UDEV_PATH_SIZE];
2055 bool truncated;
2057 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2058 if (truncated) {
2059 log_event_truncated(dev, token, "file name to be imported", token->value, "IMPORT", /* is_match = */ true);
2060 return false;
2063 log_event_debug(dev, token, "Importing properties from '%s'", buf);
2065 f = fopen(buf, "re");
2066 if (!f) {
2067 if (errno != ENOENT)
2068 return log_event_error_errno(dev, token, errno, "Failed to open '%s': %m", buf);
2069 return token->op == OP_NOMATCH;
2072 for (;;) {
2073 _cleanup_free_ char *line = NULL;
2074 char *key, *value;
2076 r = read_line(f, LONG_LINE_MAX, &line);
2077 if (r < 0) {
2078 log_event_debug_errno(dev, token, r, "Failed to read '%s', ignoring: %m", buf);
2079 return token->op == OP_NOMATCH;
2081 if (r == 0)
2082 break;
2084 r = get_property_from_string(line, &key, &value);
2085 if (r < 0) {
2086 log_event_debug_errno(dev, token, r,
2087 "Failed to parse key and value from '%s', ignoring: %m",
2088 line);
2089 continue;
2091 if (r == 0)
2092 continue;
2094 r = device_add_property(dev, key, value);
2095 if (r < 0)
2096 return log_event_error_errno(dev, token, r,
2097 "Failed to add property %s=%s: %m",
2098 key, value);
2101 return token->op == OP_MATCH;
2103 case TK_M_IMPORT_PROGRAM: {
2104 _cleanup_strv_free_ char **lines = NULL;
2105 char buf[UDEV_LINE_SIZE], result[UDEV_LINE_SIZE];
2106 bool truncated;
2108 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2109 if (truncated) {
2110 log_event_truncated(dev, token, "command", token->value, "IMPORT", /* is_match = */ true);
2111 return false;
2114 log_event_debug(dev, token, "Importing properties from results of '%s'", buf);
2116 r = udev_event_spawn(event, timeout_usec, timeout_signal, true, buf, result, sizeof result, &truncated);
2117 if (r != 0) {
2118 if (r < 0)
2119 log_event_warning_errno(dev, token, r, "Failed to execute '%s', ignoring: %m", buf);
2120 else /* returned value is positive when program fails */
2121 log_event_debug(dev, token, "Command \"%s\" returned %d (error), ignoring", buf, r);
2122 return token->op == OP_NOMATCH;
2125 if (truncated) {
2126 bool found = false;
2128 /* Drop the last line. */
2129 for (char *p = PTR_SUB1(buf + strlen(buf), buf); p; p = PTR_SUB1(p, buf))
2130 if (strchr(NEWLINE, *p)) {
2131 *p = '\0';
2132 found = true;
2133 } else if (found)
2134 break;
2137 r = strv_split_newlines_full(&lines, result, EXTRACT_RETAIN_ESCAPE);
2138 if (r == -ENOMEM)
2139 return log_oom();
2140 if (r < 0) {
2141 log_event_warning_errno(dev, token, r,
2142 "Failed to extract lines from result of command \"%s\", ignoring: %m", buf);
2143 return false;
2146 STRV_FOREACH(line, lines) {
2147 char *key, *value;
2149 r = get_property_from_string(*line, &key, &value);
2150 if (r < 0) {
2151 log_event_debug_errno(dev, token, r,
2152 "Failed to parse key and value from '%s', ignoring: %m",
2153 *line);
2154 continue;
2156 if (r == 0)
2157 continue;
2159 r = device_add_property(dev, key, value);
2160 if (r < 0)
2161 return log_event_error_errno(dev, token, r,
2162 "Failed to add property %s=%s: %m",
2163 key, value);
2166 return token->op == OP_MATCH;
2168 case TK_M_IMPORT_BUILTIN: {
2169 UdevBuiltinCommand cmd = PTR_TO_UDEV_BUILTIN_CMD(token->data);
2170 assert(cmd >= 0 && cmd < _UDEV_BUILTIN_MAX);
2171 unsigned mask = 1U << (int) cmd;
2172 char buf[UDEV_LINE_SIZE];
2173 bool truncated;
2175 if (udev_builtin_run_once(cmd)) {
2176 /* check if we ran already */
2177 if (event->builtin_run & mask) {
2178 log_event_debug(dev, token, "Skipping builtin '%s' in IMPORT key",
2179 udev_builtin_name(cmd));
2180 /* return the result from earlier run */
2181 return token->op == (event->builtin_ret & mask ? OP_NOMATCH : OP_MATCH);
2183 /* mark as ran */
2184 event->builtin_run |= mask;
2187 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2188 if (truncated) {
2189 log_event_truncated(dev, token, "builtin command", token->value, "IMPORT", /* is_match = */ true);
2190 return false;
2193 log_event_debug(dev, token, "Importing properties from results of builtin command '%s'", buf);
2195 r = udev_builtin_run(event, cmd, buf, false);
2196 if (r < 0) {
2197 /* remember failure */
2198 log_event_debug_errno(dev, token, r, "Failed to run builtin '%s': %m", buf);
2199 event->builtin_ret |= mask;
2201 return token->op == (r >= 0 ? OP_MATCH : OP_NOMATCH);
2203 case TK_M_IMPORT_DB: {
2204 const char *val;
2206 if (!event->dev_db_clone)
2207 return token->op == OP_NOMATCH;
2208 r = sd_device_get_property_value(event->dev_db_clone, token->value, &val);
2209 if (r == -ENOENT)
2210 return token->op == OP_NOMATCH;
2211 if (r < 0)
2212 return log_event_error_errno(dev, token, r,
2213 "Failed to get property '%s' from database: %m",
2214 token->value);
2216 r = device_add_property(dev, token->value, val);
2217 if (r < 0)
2218 return log_event_error_errno(dev, token, r, "Failed to add property '%s=%s': %m",
2219 token->value, val);
2220 return token->op == OP_MATCH;
2222 case TK_M_IMPORT_CMDLINE: {
2223 _cleanup_free_ char *value = NULL;
2225 r = proc_cmdline_get_key(token->value, PROC_CMDLINE_VALUE_OPTIONAL|PROC_CMDLINE_IGNORE_EFI_OPTIONS, &value);
2226 if (r < 0)
2227 return log_event_error_errno(dev, token, r,
2228 "Failed to read '%s' option from /proc/cmdline: %m",
2229 token->value);
2230 if (r == 0)
2231 return token->op == OP_NOMATCH;
2233 r = device_add_property(dev, token->value, value ?: "1");
2234 if (r < 0)
2235 return log_event_error_errno(dev, token, r, "Failed to add property '%s=%s': %m",
2236 token->value, value ?: "1");
2237 return token->op == OP_MATCH;
2239 case TK_M_IMPORT_PARENT: {
2240 char buf[UDEV_PATH_SIZE];
2241 bool truncated;
2243 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2244 if (truncated) {
2245 log_event_truncated(dev, token, "property name", token->value, "IMPORT", /* is_match = */ true);
2246 return false;
2249 r = import_parent_into_properties(dev, buf);
2250 if (r < 0)
2251 return log_event_error_errno(dev, token, r,
2252 "Failed to import properties '%s' from parent: %m",
2253 buf);
2254 return token->op == (r > 0 ? OP_MATCH : OP_NOMATCH);
2256 case TK_M_RESULT:
2257 return token_match_string(token, event->program_result);
2258 case TK_A_OPTIONS_STRING_ESCAPE_NONE:
2259 event->esc = ESCAPE_NONE;
2260 break;
2261 case TK_A_OPTIONS_STRING_ESCAPE_REPLACE:
2262 event->esc = ESCAPE_REPLACE;
2263 break;
2264 case TK_A_OPTIONS_DB_PERSIST:
2265 device_set_db_persist(dev);
2266 break;
2267 case TK_A_OPTIONS_INOTIFY_WATCH:
2268 if (event->inotify_watch_final)
2269 break;
2270 if (token->op == OP_ASSIGN_FINAL)
2271 event->inotify_watch_final = true;
2273 event->inotify_watch = token->data;
2274 break;
2275 case TK_A_OPTIONS_DEVLINK_PRIORITY:
2276 device_set_devlink_priority(dev, PTR_TO_INT(token->data));
2277 break;
2278 case TK_A_OPTIONS_LOG_LEVEL: {
2279 int level = PTR_TO_INT(token->data);
2281 if (level < 0)
2282 level = event->default_log_level;
2284 log_set_max_level(level);
2286 if (level == LOG_DEBUG && !event->log_level_was_debug) {
2287 /* The log level becomes LOG_DEBUG at first time. Let's log basic information. */
2288 log_device_uevent(dev, "The log level is changed to 'debug' while processing device");
2289 event->log_level_was_debug = true;
2292 break;
2294 case TK_A_OWNER: {
2295 char owner[UDEV_NAME_SIZE];
2296 const char *ow = owner;
2297 bool truncated;
2299 if (event->owner_final)
2300 break;
2301 if (token->op == OP_ASSIGN_FINAL)
2302 event->owner_final = true;
2304 (void) udev_event_apply_format(event, token->value, owner, sizeof(owner), false, &truncated);
2305 if (truncated) {
2306 log_event_truncated(dev, token, "user name", token->value, "OWNER", /* is_match = */ false);
2307 break;
2310 r = get_user_creds(&ow, &event->uid, NULL, NULL, NULL, USER_CREDS_ALLOW_MISSING);
2311 if (r < 0)
2312 log_unknown_owner(dev, token->rule_line, r, "user", owner);
2313 else
2314 log_event_debug(dev, token, "OWNER %s(%u)", owner, event->uid);
2315 break;
2317 case TK_A_GROUP: {
2318 char group[UDEV_NAME_SIZE];
2319 const char *gr = group;
2320 bool truncated;
2322 if (event->group_final)
2323 break;
2324 if (token->op == OP_ASSIGN_FINAL)
2325 event->group_final = true;
2327 (void) udev_event_apply_format(event, token->value, group, sizeof(group), false, &truncated);
2328 if (truncated) {
2329 log_event_truncated(dev, token, "group name", token->value, "GROUP", /* is_match = */ false);
2330 break;
2333 r = get_group_creds(&gr, &event->gid, USER_CREDS_ALLOW_MISSING);
2334 if (r < 0)
2335 log_unknown_owner(dev, token->rule_line, r, "group", group);
2336 else
2337 log_event_debug(dev, token, "GROUP %s(%u)", group, event->gid);
2338 break;
2340 case TK_A_MODE: {
2341 char mode_str[UDEV_NAME_SIZE];
2342 bool truncated;
2344 if (event->mode_final)
2345 break;
2346 if (token->op == OP_ASSIGN_FINAL)
2347 event->mode_final = true;
2349 (void) udev_event_apply_format(event, token->value, mode_str, sizeof(mode_str), false, &truncated);
2350 if (truncated) {
2351 log_event_truncated(dev, token, "mode", token->value, "MODE", /* is_match = */ false);
2352 break;
2355 r = parse_mode(mode_str, &event->mode);
2356 if (r < 0)
2357 log_event_error_errno(dev, token, r, "Failed to parse mode '%s', ignoring: %m", mode_str);
2358 else
2359 log_event_debug(dev, token, "MODE %#o", event->mode);
2360 break;
2362 case TK_A_OWNER_ID:
2363 if (event->owner_final)
2364 break;
2365 if (token->op == OP_ASSIGN_FINAL)
2366 event->owner_final = true;
2367 if (!token->data)
2368 break;
2369 event->uid = PTR_TO_UID(token->data);
2370 log_event_debug(dev, token, "OWNER %u", event->uid);
2371 break;
2372 case TK_A_GROUP_ID:
2373 if (event->group_final)
2374 break;
2375 if (token->op == OP_ASSIGN_FINAL)
2376 event->group_final = true;
2377 if (!token->data)
2378 break;
2379 event->gid = PTR_TO_GID(token->data);
2380 log_event_debug(dev, token, "GROUP %u", event->gid);
2381 break;
2382 case TK_A_MODE_ID:
2383 if (event->mode_final)
2384 break;
2385 if (token->op == OP_ASSIGN_FINAL)
2386 event->mode_final = true;
2387 if (!token->data)
2388 break;
2389 event->mode = PTR_TO_MODE(token->data);
2390 log_event_debug(dev, token, "MODE %#o", event->mode);
2391 break;
2392 case TK_A_SECLABEL: {
2393 _cleanup_free_ char *name = NULL, *label = NULL;
2394 char label_str[UDEV_LINE_SIZE] = {};
2395 bool truncated;
2397 name = strdup(token->data);
2398 if (!name)
2399 return log_oom();
2401 (void) udev_event_apply_format(event, token->value, label_str, sizeof(label_str), false, &truncated);
2402 if (truncated) {
2403 log_event_truncated(dev, token, "security label", token->value, "SECLABEL", /* is_match = */ false);
2404 break;
2407 if (!isempty(label_str))
2408 label = strdup(label_str);
2409 else
2410 label = strdup(token->value);
2411 if (!label)
2412 return log_oom();
2414 if (token->op == OP_ASSIGN)
2415 ordered_hashmap_clear_free_free(event->seclabel_list);
2417 r = ordered_hashmap_ensure_put(&event->seclabel_list, NULL, name, label);
2418 if (r == -ENOMEM)
2419 return log_oom();
2420 if (r < 0)
2421 return log_event_error_errno(dev, token, r, "Failed to store SECLABEL{%s}='%s': %m", name, label);
2423 log_event_debug(dev, token, "SECLABEL{%s}='%s'", name, label);
2425 TAKE_PTR(name);
2426 TAKE_PTR(label);
2427 break;
2429 case TK_A_ENV: {
2430 const char *val, *name = token->data;
2431 char value_new[UDEV_NAME_SIZE], *p = value_new;
2432 size_t count, l = sizeof(value_new);
2433 bool truncated;
2435 if (isempty(token->value)) {
2436 if (token->op == OP_ADD)
2437 break;
2438 r = device_add_property(dev, name, NULL);
2439 if (r < 0)
2440 return log_event_error_errno(dev, token, r, "Failed to remove property '%s': %m", name);
2441 break;
2444 if (token->op == OP_ADD &&
2445 sd_device_get_property_value(dev, name, &val) >= 0) {
2446 l = strpcpyl_full(&p, l, &truncated, val, " ", NULL);
2447 if (truncated) {
2448 log_event_warning(dev, token,
2449 "The buffer for the property '%s' is full, "
2450 "refusing to append the new value '%s'.", name, token->value);
2451 break;
2455 (void) udev_event_apply_format(event, token->value, p, l, false, &truncated);
2456 if (truncated) {
2457 _cleanup_free_ char *key_with_name = strjoin("ENV{", name, "}");
2458 log_event_truncated(dev, token, "property value", token->value,
2459 key_with_name ?: "ENV", /* is_match = */ false);
2460 break;
2463 if (event->esc == ESCAPE_REPLACE) {
2464 count = udev_replace_chars(p, NULL);
2465 if (count > 0)
2466 log_event_debug(dev, token,
2467 "Replaced %zu slash(es) from result of ENV{%s}%s=\"%s\"",
2468 count, name, token->op == OP_ADD ? "+" : "", token->value);
2471 r = device_add_property(dev, name, value_new);
2472 if (r < 0)
2473 return log_event_error_errno(dev, token, r, "Failed to add property '%s=%s': %m", name, value_new);
2474 break;
2476 case TK_A_TAG: {
2477 char buf[UDEV_PATH_SIZE];
2478 bool truncated;
2480 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2481 if (truncated) {
2482 log_event_truncated(dev, token, "tag name", token->value, "TAG", /* is_match = */ false);
2483 break;
2486 if (token->op == OP_ASSIGN)
2487 device_cleanup_tags(dev);
2489 if (token->op == OP_REMOVE)
2490 device_remove_tag(dev, buf);
2491 else {
2492 r = device_add_tag(dev, buf, true);
2493 if (r == -ENOMEM)
2494 return log_oom();
2495 if (r < 0)
2496 log_event_warning_errno(dev, token, r, "Failed to add tag '%s', ignoring: %m", buf);
2498 break;
2500 case TK_A_NAME: {
2501 char buf[UDEV_PATH_SIZE];
2502 bool truncated;
2503 size_t count;
2505 if (event->name_final)
2506 break;
2507 if (token->op == OP_ASSIGN_FINAL)
2508 event->name_final = true;
2510 if (sd_device_get_ifindex(dev, NULL) < 0) {
2511 log_event_error(dev, token,
2512 "Only network interfaces can be renamed, ignoring NAME=\"%s\".",
2513 token->value);
2514 break;
2517 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2518 if (truncated) {
2519 log_event_truncated(dev, token, "network interface name", token->value, "NAME", /* is_match = */ false);
2520 break;
2523 if (IN_SET(event->esc, ESCAPE_UNSET, ESCAPE_REPLACE)) {
2524 if (naming_scheme_has(NAMING_REPLACE_STRICTLY))
2525 count = udev_replace_ifname(buf);
2526 else
2527 count = udev_replace_chars(buf, "/");
2528 if (count > 0)
2529 log_event_debug(dev, token,
2530 "Replaced %zu character(s) from result of NAME=\"%s\"",
2531 count, token->value);
2533 r = free_and_strdup_warn(&event->name, buf);
2534 if (r < 0)
2535 return r;
2537 log_event_debug(dev, token, "NAME '%s'", event->name);
2538 break;
2540 case TK_A_DEVLINK: {
2541 char buf[UDEV_PATH_SIZE];
2542 bool truncated;
2543 size_t count;
2545 if (event->devlink_final)
2546 break;
2547 if (sd_device_get_devnum(dev, NULL) < 0)
2548 break;
2549 if (token->op == OP_ASSIGN_FINAL)
2550 event->devlink_final = true;
2551 if (IN_SET(token->op, OP_ASSIGN, OP_ASSIGN_FINAL))
2552 device_cleanup_devlinks(dev);
2554 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf),
2555 /* replace_whitespace = */ event->esc != ESCAPE_NONE, &truncated);
2556 if (truncated) {
2557 log_event_truncated(dev, token, "symbolic link path", token->value, "SYMLINK", /* is_match = */ false);
2558 break;
2561 /* By default or string_escape=none, allow multiple symlinks separated by spaces. */
2562 if (event->esc == ESCAPE_UNSET)
2563 count = udev_replace_chars(buf, /* allow = */ "/ ");
2564 else if (event->esc == ESCAPE_REPLACE)
2565 count = udev_replace_chars(buf, /* allow = */ "/");
2566 else
2567 count = 0;
2568 if (count > 0)
2569 log_event_debug(dev, token,
2570 "Replaced %zu character(s) from result of SYMLINK=\"%s\"",
2571 count, token->value);
2573 for (const char *p = buf;;) {
2574 _cleanup_free_ char *path = NULL;
2576 r = extract_first_word(&p, &path, NULL, EXTRACT_RETAIN_ESCAPE);
2577 if (r == -ENOMEM)
2578 return log_oom();
2579 if (r < 0) {
2580 log_warning_errno(r, "Failed to extract first path in SYMLINK=, ignoring: %m");
2581 break;
2583 if (r == 0)
2584 break;
2586 if (token->op == OP_REMOVE) {
2587 r = device_remove_devlink(dev, path);
2588 if (r == -ENOMEM)
2589 return log_oom();
2590 if (r < 0)
2591 log_event_warning_errno(dev, token, r, "Failed to remove devlink '%s', ignoring: %m", path);
2592 else if (r > 0)
2593 log_event_debug(dev, token, "Dropped SYMLINK '%s'", path);
2594 } else {
2595 r = device_add_devlink(dev, path);
2596 if (r == -ENOMEM)
2597 return log_oom();
2598 if (r < 0)
2599 log_event_warning_errno(dev, token, r, "Failed to add devlink '%s', ignoring: %m", path);
2600 else if (r > 0)
2601 log_event_debug(dev, token, "Added SYMLINK '%s'", path);
2604 break;
2606 case TK_A_ATTR: {
2607 char buf[UDEV_PATH_SIZE], value[UDEV_NAME_SIZE];
2608 const char *val, *key_name = token->data;
2609 bool truncated;
2611 if (udev_resolve_subsys_kernel(key_name, buf, sizeof(buf), false) < 0 &&
2612 sd_device_get_syspath(dev, &val) >= 0) {
2613 strscpyl_full(buf, sizeof(buf), &truncated, val, "/", key_name, NULL);
2614 if (truncated) {
2615 log_event_warning(dev, token,
2616 "The path to the attribute '%s/%s' is too long, refusing to set the attribute.",
2617 val, key_name);
2618 break;
2622 r = attr_subst_subdir(buf);
2623 if (r < 0) {
2624 log_event_error_errno(dev, token, r, "Could not find file matches '%s', ignoring: %m", buf);
2625 break;
2627 (void) udev_event_apply_format(event, token->value, value, sizeof(value), false, &truncated);
2628 if (truncated) {
2629 log_event_truncated(dev, token, "attribute value", token->value, "ATTR", /* is_match = */ false);
2630 break;
2633 log_event_debug(dev, token, "ATTR '%s' writing '%s'", buf, value);
2634 r = write_string_file(buf, value,
2635 WRITE_STRING_FILE_VERIFY_ON_FAILURE |
2636 WRITE_STRING_FILE_DISABLE_BUFFER |
2637 WRITE_STRING_FILE_AVOID_NEWLINE |
2638 WRITE_STRING_FILE_VERIFY_IGNORE_NEWLINE);
2639 if (r < 0)
2640 log_event_error_errno(dev, token, r, "Failed to write ATTR{%s}, ignoring: %m", buf);
2641 break;
2643 case TK_A_SYSCTL: {
2644 char buf[UDEV_PATH_SIZE], value[UDEV_NAME_SIZE];
2645 bool truncated;
2647 (void) udev_event_apply_format(event, token->data, buf, sizeof(buf), false, &truncated);
2648 if (truncated) {
2649 log_event_truncated(dev, token, "sysctl entry name", token->data, "SYSCTL", /* is_match = */ false);
2650 break;
2653 (void) udev_event_apply_format(event, token->value, value, sizeof(value), false, &truncated);
2654 if (truncated) {
2655 _cleanup_free_ char *key_with_name = strjoin("SYSCTL{", buf, "}");
2656 log_event_truncated(dev, token, "sysctl value", token->value,
2657 key_with_name ?: "SYSCTL", /* is_match = */ false);
2658 break;
2661 sysctl_normalize(buf);
2662 log_event_debug(dev, token, "SYSCTL '%s' writing '%s'", buf, value);
2663 r = sysctl_write(buf, value);
2664 if (r < 0)
2665 log_event_error_errno(dev, token, r, "Failed to write SYSCTL{%s}='%s', ignoring: %m", buf, value);
2666 break;
2668 case TK_A_RUN_BUILTIN:
2669 case TK_A_RUN_PROGRAM: {
2670 _cleanup_free_ char *cmd = NULL;
2671 char buf[UDEV_LINE_SIZE];
2672 bool truncated;
2674 if (event->run_final)
2675 break;
2676 if (token->op == OP_ASSIGN_FINAL)
2677 event->run_final = true;
2679 if (IN_SET(token->op, OP_ASSIGN, OP_ASSIGN_FINAL))
2680 ordered_hashmap_clear_free_key(event->run_list);
2682 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2683 if (truncated) {
2684 log_event_truncated(dev, token, "command", token->value,
2685 token->type == TK_A_RUN_BUILTIN ? "RUN{builtin}" : "RUN{program}",
2686 /* is_match = */ false);
2687 break;
2690 cmd = strdup(buf);
2691 if (!cmd)
2692 return log_oom();
2694 r = ordered_hashmap_ensure_put(&event->run_list, NULL, cmd, token->data);
2695 if (r == -ENOMEM)
2696 return log_oom();
2697 if (r < 0)
2698 return log_event_error_errno(dev, token, r, "Failed to store command '%s': %m", cmd);
2700 TAKE_PTR(cmd);
2702 log_event_debug(dev, token, "RUN '%s'", token->value);
2703 break;
2705 case TK_A_OPTIONS_STATIC_NODE:
2706 /* do nothing for events. */
2707 break;
2708 default:
2709 assert_not_reached();
2712 return true;
2715 static bool token_is_for_parents(UdevRuleToken *token) {
2716 return token->type >= TK_M_PARENTS_KERNEL && token->type <= TK_M_PARENTS_TAG;
2719 static int udev_rule_apply_parent_token_to_event(
2720 UdevRuleToken *head_token,
2721 UdevEvent *event,
2722 int timeout_signal) {
2724 int r;
2726 assert(head_token);
2727 assert(event);
2729 event->dev_parent = ASSERT_PTR(event->dev);
2731 for (;;) {
2732 LIST_FOREACH(tokens, token, head_token) {
2733 if (!token_is_for_parents(token))
2734 return true; /* All parent tokens match. */
2736 r = udev_rule_apply_token_to_event(token, event->dev_parent, event, 0, timeout_signal, NULL);
2737 if (r < 0)
2738 return r;
2739 if (r == 0)
2740 break;
2742 if (r > 0)
2743 /* All parent tokens match, and no more token (except for GOTO) in the line. */
2744 return true;
2746 if (sd_device_get_parent(event->dev_parent, &event->dev_parent) < 0) {
2747 event->dev_parent = NULL;
2748 return false;
2753 static int udev_rule_apply_line_to_event(
2754 UdevRuleLine *line,
2755 UdevEvent *event,
2756 usec_t timeout_usec,
2757 int timeout_signal,
2758 Hashmap *properties_list,
2759 UdevRuleLine **next_line) {
2761 UdevRuleLineType mask = LINE_HAS_GOTO | LINE_UPDATE_SOMETHING;
2762 bool parents_done = false;
2763 sd_device_action_t action;
2764 int r;
2766 assert(line);
2767 assert(event);
2768 assert(next_line);
2770 r = sd_device_get_action(event->dev, &action);
2771 if (r < 0)
2772 return r;
2774 if (action != SD_DEVICE_REMOVE) {
2775 if (sd_device_get_devnum(event->dev, NULL) >= 0)
2776 mask |= LINE_HAS_DEVLINK;
2778 if (sd_device_get_ifindex(event->dev, NULL) >= 0)
2779 mask |= LINE_HAS_NAME;
2782 if ((line->type & mask) == 0)
2783 return 0;
2785 event->esc = ESCAPE_UNSET;
2787 DEVICE_TRACE_POINT(rules_apply_line, event->dev, line->rule_file->filename, line->line_number);
2789 LIST_FOREACH(tokens, token, line->tokens) {
2790 if (token_is_for_parents(token)) {
2791 if (parents_done)
2792 continue;
2794 r = udev_rule_apply_parent_token_to_event(token, event, timeout_signal);
2795 if (r <= 0)
2796 return r;
2798 parents_done = true;
2799 continue;
2802 r = udev_rule_apply_token_to_event(token, event->dev, event, timeout_usec, timeout_signal, properties_list);
2803 if (r <= 0)
2804 return r;
2807 if (line->goto_line)
2808 *next_line = line->goto_line; /* update next_line only when the line has GOTO token. */
2810 return 0;
2813 int udev_rules_apply_to_event(
2814 UdevRules *rules,
2815 UdevEvent *event,
2816 usec_t timeout_usec,
2817 int timeout_signal,
2818 Hashmap *properties_list) {
2820 int r;
2822 assert(rules);
2823 assert(event);
2825 LIST_FOREACH(rule_files, file, rules->rule_files)
2826 LIST_FOREACH_WITH_NEXT(rule_lines, line, next_line, file->rule_lines) {
2827 r = udev_rule_apply_line_to_event(line, event, timeout_usec, timeout_signal, properties_list, &next_line);
2828 if (r < 0)
2829 return r;
2832 return 0;
2835 static int udev_rule_line_apply_static_dev_perms(UdevRuleLine *rule_line) {
2836 _cleanup_strv_free_ char **tags = NULL;
2837 uid_t uid = UID_INVALID;
2838 gid_t gid = GID_INVALID;
2839 mode_t mode = MODE_INVALID;
2840 int r;
2842 assert(rule_line);
2844 if (!FLAGS_SET(rule_line->type, LINE_HAS_STATIC_NODE))
2845 return 0;
2847 LIST_FOREACH(tokens, token, rule_line->tokens)
2848 if (token->type == TK_A_OWNER_ID)
2849 uid = PTR_TO_UID(token->data);
2850 else if (token->type == TK_A_GROUP_ID)
2851 gid = PTR_TO_GID(token->data);
2852 else if (token->type == TK_A_MODE_ID)
2853 mode = PTR_TO_MODE(token->data);
2854 else if (token->type == TK_A_TAG) {
2855 r = strv_extend(&tags, token->value);
2856 if (r < 0)
2857 return log_oom();
2858 } else if (token->type == TK_A_OPTIONS_STATIC_NODE) {
2859 r = static_node_apply_permissions(token->value, mode, uid, gid, tags);
2860 if (r < 0)
2861 return r;
2864 return 0;
2867 int udev_rules_apply_static_dev_perms(UdevRules *rules) {
2868 int r;
2870 assert(rules);
2872 LIST_FOREACH(rule_files, file, rules->rule_files)
2873 LIST_FOREACH(rule_lines, line, file->rule_lines) {
2874 r = udev_rule_line_apply_static_dev_perms(line);
2875 if (r < 0)
2876 return r;
2879 return 0;