]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/udev/udev-rules.c
Merge pull request #30513 from rpigott/resolved-ede
[thirdparty/systemd.git] / src / udev / udev-rules.c
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2
3 #include <ctype.h>
4
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 "escape.h"
15 #include "fd-util.h"
16 #include "fileio.h"
17 #include "format-util.h"
18 #include "fs-util.h"
19 #include "glob-util.h"
20 #include "list.h"
21 #include "mkdir.h"
22 #include "netif-naming-scheme.h"
23 #include "nulstr-util.h"
24 #include "parse-util.h"
25 #include "path-util.h"
26 #include "proc-cmdline.h"
27 #include "socket-util.h"
28 #include "stat-util.h"
29 #include "string-table.h"
30 #include "strv.h"
31 #include "strxcpyx.h"
32 #include "sysctl-util.h"
33 #include "syslog-util.h"
34 #include "udev-builtin.h"
35 #include "udev-event.h"
36 #include "udev-format.h"
37 #include "udev-node.h"
38 #include "udev-rules.h"
39 #include "udev-spawn.h"
40 #include "udev-trace.h"
41 #include "udev-util.h"
42 #include "user-util.h"
43 #include "virt.h"
44
45 #define RULES_DIRS ((const char* const*) CONF_PATHS_STRV("udev/rules.d"))
46
47 typedef enum {
48 OP_MATCH, /* == */
49 OP_NOMATCH, /* != */
50 OP_ADD, /* += */
51 OP_REMOVE, /* -= */
52 OP_ASSIGN, /* = */
53 OP_ASSIGN_FINAL, /* := */
54 _OP_TYPE_MAX,
55 _OP_TYPE_INVALID = -EINVAL,
56 } UdevRuleOperatorType;
57
58 typedef enum {
59 MATCH_TYPE_EMPTY, /* empty string */
60 MATCH_TYPE_PLAIN, /* no special characters */
61 MATCH_TYPE_PLAIN_WITH_EMPTY, /* no special characters with empty string, e.g., "|foo" */
62 MATCH_TYPE_GLOB, /* shell globs ?,*,[] */
63 MATCH_TYPE_GLOB_WITH_EMPTY, /* shell globs ?,*,[] with empty string, e.g., "|foo*" */
64 MATCH_TYPE_SUBSYSTEM, /* "subsystem", "bus", or "class" */
65 _MATCH_TYPE_MAX,
66 _MATCH_TYPE_INVALID = -EINVAL,
67 } UdevRuleMatchType;
68
69 typedef enum {
70 SUBST_TYPE_PLAIN, /* no substitution */
71 SUBST_TYPE_FORMAT, /* % or $ */
72 SUBST_TYPE_SUBSYS, /* "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
73 _SUBST_TYPE_MAX,
74 _SUBST_TYPE_INVALID = -EINVAL,
75 } UdevRuleSubstituteType;
76
77 typedef enum {
78 /* lvalues which take match or nomatch operator */
79 TK_M_ACTION, /* string, device_get_action() */
80 TK_M_DEVPATH, /* path, sd_device_get_devpath() */
81 TK_M_KERNEL, /* string, sd_device_get_sysname() */
82 TK_M_DEVLINK, /* strv, sd_device_get_devlink_first(), sd_device_get_devlink_next() */
83 TK_M_NAME, /* string, name of network interface */
84 TK_M_ENV, /* string, device property, takes key through attribute */
85 TK_M_CONST, /* string, system-specific hard-coded constant */
86 TK_M_TAG, /* strv, sd_device_get_tag_first(), sd_device_get_tag_next() */
87 TK_M_SUBSYSTEM, /* string, sd_device_get_subsystem() */
88 TK_M_DRIVER, /* string, sd_device_get_driver() */
89 TK_M_ATTR, /* string, takes filename through attribute, sd_device_get_sysattr_value(), udev_resolve_subsys_kernel(), etc. */
90 TK_M_SYSCTL, /* string, takes kernel parameter through attribute */
91
92 /* matches parent parameters */
93 TK_M_PARENTS_KERNEL, /* string */
94 TK_M_PARENTS_SUBSYSTEM, /* string */
95 TK_M_PARENTS_DRIVER, /* string */
96 TK_M_PARENTS_ATTR, /* string */
97 TK_M_PARENTS_TAG, /* strv */
98
99 TK_M_TEST, /* path, optionally mode_t can be specified by attribute, test the existence of a file */
100 TK_M_PROGRAM, /* string, execute a program */
101 TK_M_IMPORT_FILE, /* path */
102 TK_M_IMPORT_PROGRAM, /* string, import properties from the result of program */
103 TK_M_IMPORT_BUILTIN, /* string, import properties from the result of built-in command */
104 TK_M_IMPORT_DB, /* string, import properties from database */
105 TK_M_IMPORT_CMDLINE, /* string, kernel command line */
106 TK_M_IMPORT_PARENT, /* string, parent property */
107 TK_M_RESULT, /* string, result of TK_M_PROGRAM */
108
109 #define _TK_M_MAX (TK_M_RESULT + 1)
110 #define _TK_A_MIN _TK_M_MAX
111
112 /* lvalues which take one of assign operators */
113 TK_A_OPTIONS_STRING_ESCAPE_NONE, /* no argument */
114 TK_A_OPTIONS_STRING_ESCAPE_REPLACE, /* no argument */
115 TK_A_OPTIONS_DB_PERSIST, /* no argument */
116 TK_A_OPTIONS_INOTIFY_WATCH, /* boolean */
117 TK_A_OPTIONS_DEVLINK_PRIORITY, /* int */
118 TK_A_OPTIONS_LOG_LEVEL, /* string of log level or "reset" */
119 TK_A_OWNER, /* user name */
120 TK_A_GROUP, /* group name */
121 TK_A_MODE, /* mode string */
122 TK_A_OWNER_ID, /* uid_t */
123 TK_A_GROUP_ID, /* gid_t */
124 TK_A_MODE_ID, /* mode_t */
125 TK_A_TAG, /* string */
126 TK_A_OPTIONS_STATIC_NODE, /* device path, /dev/... */
127 TK_A_SECLABEL, /* string with attribute */
128 TK_A_ENV, /* string with attribute */
129 TK_A_NAME, /* ifname */
130 TK_A_DEVLINK, /* string */
131 TK_A_ATTR, /* string with attribute */
132 TK_A_SYSCTL, /* string with attribute */
133 TK_A_RUN_BUILTIN, /* string */
134 TK_A_RUN_PROGRAM, /* string */
135
136 _TK_TYPE_MAX,
137 _TK_TYPE_INVALID = -EINVAL,
138 } UdevRuleTokenType;
139
140 typedef enum {
141 LINE_HAS_NAME = 1 << 0, /* has NAME= */
142 LINE_HAS_DEVLINK = 1 << 1, /* has SYMLINK=, OWNER=, GROUP= or MODE= */
143 LINE_HAS_STATIC_NODE = 1 << 2, /* has OPTIONS=static_node */
144 LINE_HAS_GOTO = 1 << 3, /* has GOTO= */
145 LINE_HAS_LABEL = 1 << 4, /* has LABEL= */
146 LINE_UPDATE_SOMETHING = 1 << 5, /* has other TK_A_* or TK_M_IMPORT tokens */
147 LINE_IS_REFERENCED = 1 << 6, /* is referenced by GOTO */
148 } UdevRuleLineType;
149
150 typedef struct UdevRuleFile UdevRuleFile;
151 typedef struct UdevRuleLine UdevRuleLine;
152 typedef struct UdevRuleToken UdevRuleToken;
153
154 struct UdevRuleToken {
155 UdevRuleTokenType type:8;
156 UdevRuleOperatorType op:8;
157 UdevRuleMatchType match_type:8;
158 UdevRuleSubstituteType attr_subst_type:7;
159 bool attr_match_remove_trailing_whitespace:1;
160 const char *value;
161 void *data;
162
163 UdevRuleLine *rule_line;
164 LIST_FIELDS(UdevRuleToken, tokens);
165 };
166
167 struct UdevRuleLine {
168 char *line;
169 unsigned line_number;
170 UdevRuleLineType type;
171
172 const char *label;
173 const char *goto_label;
174 UdevRuleLine *goto_line;
175
176 UdevRuleFile *rule_file;
177 LIST_HEAD(UdevRuleToken, tokens);
178 LIST_FIELDS(UdevRuleLine, rule_lines);
179 };
180
181 struct UdevRuleFile {
182 char *filename;
183 unsigned issues; /* used by "udevadm verify" */
184
185 UdevRules *rules;
186 LIST_HEAD(UdevRuleLine, rule_lines);
187 LIST_FIELDS(UdevRuleFile, rule_files);
188 };
189
190 struct UdevRules {
191 ResolveNameTiming resolve_name_timing;
192 Hashmap *known_users;
193 Hashmap *known_groups;
194 Hashmap *stats_by_path;
195 LIST_HEAD(UdevRuleFile, rule_files);
196 };
197
198 #define LINE_GET_RULES(line) \
199 ASSERT_PTR(ASSERT_PTR(ASSERT_PTR(line)->rule_file)->rules)
200
201 /*** Logging helpers ***/
202
203 #define log_udev_rule_internal(device, file, line_nr, level, error, fmt, ...) \
204 ({ \
205 int _lv = (level); \
206 sd_device *_dev = (device); \
207 UdevRuleFile *_f = (file); \
208 const char *_n = _f ? _f->filename : NULL; \
209 \
210 if (!_dev && _f) \
211 _f->issues |= (1U << _lv); \
212 \
213 log_device_full_errno_zerook( \
214 _dev, _lv, error, "%s:%u " fmt, \
215 strna(_n), line_nr, \
216 ##__VA_ARGS__); \
217 })
218
219 /* Mainly used when applying tokens to the event device. */
220 #define log_event_full_errno_zerook(device, token, ...) \
221 ({ \
222 UdevRuleToken *_t = (token); \
223 UdevRuleLine *_l = _t ? _t->rule_line : NULL; \
224 \
225 log_udev_rule_internal( \
226 device, \
227 _l ? _l->rule_file : NULL, \
228 _l ? _l->line_number : 0, \
229 __VA_ARGS__); \
230 })
231
232 #define log_event_full_errno(device, token, level, error, ...) \
233 ({ \
234 int _error = (error); \
235 ASSERT_NON_ZERO(_error); \
236 log_event_full_errno_zerook( \
237 device, token, level, _error, ##__VA_ARGS__); \
238 })
239
240 #define log_event_full(device, token, level, ...) (void) log_event_full_errno_zerook(device, token, level, 0, __VA_ARGS__)
241
242 #define log_event_debug(device, token, ...) log_event_full(device, token, LOG_DEBUG, __VA_ARGS__)
243 #define log_event_info(device, token, ...) log_event_full(device, token, LOG_INFO, __VA_ARGS__)
244 #define log_event_notice(device, token, ...) log_event_full(device, token, LOG_NOTICE, __VA_ARGS__)
245 #define log_event_warning(device, token, ...) log_event_full(device, token, LOG_WARNING, __VA_ARGS__)
246 #define log_event_error(device, token, ...) log_event_full(device, token, LOG_ERR, __VA_ARGS__)
247
248 #define log_event_debug_errno(device, token, error, ...) log_event_full_errno(device, token, LOG_DEBUG, error, __VA_ARGS__)
249 #define log_event_info_errno(device, token, error, ...) log_event_full_errno(device, token, LOG_INFO, error, __VA_ARGS__)
250 #define log_event_notice_errno(device, token, error, ...) log_event_full_errno(device, token, LOG_NOTICE, error, __VA_ARGS__)
251 #define log_event_warning_errno(device, token, error, ...) log_event_full_errno(device, token, LOG_WARNING, error, __VA_ARGS__)
252 #define log_event_error_errno(device, token, error, ...) log_event_full_errno(device, token, LOG_ERR, error, __VA_ARGS__)
253
254 /* Mainly used when parsing .rules files. */
255 #define log_file_full_errno_zerook(...) \
256 log_udev_rule_internal(NULL, __VA_ARGS__)
257
258 #define log_file_error(file, line_nr, ...) \
259 log_file_full_errno_zerook(file, line_nr, LOG_ERR, 0, __VA_ARGS__)
260
261 #define log_line_full_errno_zerook(line, ...) \
262 ({ \
263 UdevRuleLine *_l = (line); \
264 log_file_full_errno_zerook( \
265 _l ? _l->rule_file : NULL, \
266 _l ? _l->line_number : 0, \
267 __VA_ARGS__); \
268 })
269
270 #define log_line_full_errno(line, level, error, ...) \
271 ({ \
272 int _error = (error); \
273 ASSERT_NON_ZERO(_error); \
274 log_line_full_errno_zerook( \
275 line, level, _error, ##__VA_ARGS__); \
276 })
277
278 #define log_line_full(line, level, ...) (void) log_line_full_errno_zerook(line, level, 0, __VA_ARGS__)
279
280 #define log_line_debug(line, ...) log_line_full(line, LOG_DEBUG, __VA_ARGS__)
281 #define log_line_info(line, ...) log_line_full(line, LOG_INFO, __VA_ARGS__)
282 #define log_line_notice(line, ...) log_line_full(line, LOG_NOTICE, __VA_ARGS__)
283 #define log_line_warning(line, ...) log_line_full(line, LOG_WARNING, __VA_ARGS__)
284 #define log_line_error(line, ...) log_line_full(line, LOG_ERR, __VA_ARGS__)
285
286 #define log_line_debug_errno(line, error, ...) log_line_full_errno(line, LOG_DEBUG, error, __VA_ARGS__)
287 #define log_line_info_errno(line, error, ...) log_line_full_errno(line, LOG_INFO, error, __VA_ARGS__)
288 #define log_line_notice_errno(line, error, ...) log_line_full_errno(line, LOG_NOTICE, error, __VA_ARGS__)
289 #define log_line_warning_errno(line, error, ...) log_line_full_errno(line, LOG_WARNING, error, __VA_ARGS__)
290 #define log_line_error_errno(line, error, ...) log_line_full_errno(line, LOG_ERR, error, __VA_ARGS__)
291
292 #define _log_line_invalid_token(line, key, type) \
293 log_line_error_errno(line, SYNTHETIC_ERRNO(EINVAL), \
294 "Invalid %s for %s.", type, key)
295
296 #define log_line_invalid_op(line, key) _log_line_invalid_token(line, key, "operator")
297 #define log_line_invalid_attr(line, key) _log_line_invalid_token(line, key, "attribute")
298
299 #define log_line_invalid_attr_format(line, key, attr, offset, hint) \
300 log_line_error_errno(line, SYNTHETIC_ERRNO(EINVAL), \
301 "Invalid attribute \"%s\" for %s (char %zu: %s), ignoring.", \
302 attr, key, offset, hint)
303 #define log_line_invalid_value(line, key, value, offset, hint) \
304 log_line_error_errno(line, SYNTHETIC_ERRNO(EINVAL), \
305 "Invalid value \"%s\" for %s (char %zu: %s), ignoring.", \
306 value, key, offset, hint)
307
308 static void log_unknown_owner(sd_device *dev, UdevRuleLine *line, int error, const char *entity, const char *name) {
309 assert(line);
310 ASSERT_NON_ZERO(error);
311
312 if (IN_SET(abs(error), ENOENT, ESRCH))
313 log_udev_rule_internal(dev, line->rule_file, line->line_number, LOG_ERR, error,
314 "Unknown %s '%s', ignoring.", entity, name);
315 else
316 log_udev_rule_internal(dev, line->rule_file, line->line_number, LOG_ERR, error,
317 "Failed to resolve %s '%s', ignoring: %m", entity, name);
318 }
319
320 static void log_event_truncated(
321 sd_device *dev,
322 UdevRuleToken *token,
323 const char *what,
324 const char *format,
325 const char *key,
326 bool is_match) {
327
328 if (is_match)
329 log_event_debug(dev, token,
330 "The %s is truncated while substituting into '%s', "
331 "assuming the %s key does not match.",
332 what, format, key);
333 else
334 log_event_warning(dev, token,
335 "The %s is truncated while substituting into '%s', "
336 "refusing to apply the %s key.",
337 what, format, key);
338 }
339
340 /*** Other functions ***/
341
342 static UdevRuleToken *udev_rule_token_free(UdevRuleToken *token) {
343 if (!token)
344 return NULL;
345
346 if (token->rule_line)
347 LIST_REMOVE(tokens, token->rule_line->tokens, token);
348
349 return mfree(token);
350 }
351
352 DEFINE_TRIVIAL_CLEANUP_FUNC(UdevRuleToken*, udev_rule_token_free);
353
354 static void udev_rule_line_clear_tokens(UdevRuleLine *rule_line) {
355 assert(rule_line);
356
357 LIST_FOREACH(tokens, i, rule_line->tokens)
358 udev_rule_token_free(i);
359 }
360
361 static UdevRuleLine *udev_rule_line_free(UdevRuleLine *rule_line) {
362 if (!rule_line)
363 return NULL;
364
365 udev_rule_line_clear_tokens(rule_line);
366
367 if (rule_line->rule_file)
368 LIST_REMOVE(rule_lines, rule_line->rule_file->rule_lines, rule_line);
369
370 free(rule_line->line);
371 return mfree(rule_line);
372 }
373
374 DEFINE_TRIVIAL_CLEANUP_FUNC(UdevRuleLine*, udev_rule_line_free);
375
376 static UdevRuleFile *udev_rule_file_free(UdevRuleFile *rule_file) {
377 if (!rule_file)
378 return NULL;
379
380 LIST_FOREACH(rule_lines, i, rule_file->rule_lines)
381 udev_rule_line_free(i);
382
383 if (rule_file->rules)
384 LIST_REMOVE(rule_files, rule_file->rules->rule_files, rule_file);
385
386 free(rule_file->filename);
387 return mfree(rule_file);
388 }
389
390 DEFINE_TRIVIAL_CLEANUP_FUNC(UdevRuleFile*, udev_rule_file_free);
391
392 UdevRules *udev_rules_free(UdevRules *rules) {
393 if (!rules)
394 return NULL;
395
396 LIST_FOREACH(rule_files, i, rules->rule_files)
397 udev_rule_file_free(i);
398
399 hashmap_free_free_key(rules->known_users);
400 hashmap_free_free_key(rules->known_groups);
401 hashmap_free(rules->stats_by_path);
402 return mfree(rules);
403 }
404
405 static int rule_resolve_user(UdevRuleLine *rule_line, const char *name, uid_t *ret) {
406 Hashmap **known_users = &LINE_GET_RULES(rule_line)->known_users;
407 _cleanup_free_ char *n = NULL;
408 uid_t uid;
409 void *val;
410 int r;
411
412 assert(name);
413 assert(ret);
414
415 val = hashmap_get(*known_users, name);
416 if (val) {
417 *ret = PTR_TO_UID(val);
418 return 0;
419 }
420
421 r = get_user_creds(&name, &uid, NULL, NULL, NULL, USER_CREDS_ALLOW_MISSING);
422 if (r < 0) {
423 log_unknown_owner(NULL, rule_line, r, "user", name);
424 *ret = UID_INVALID;
425 return 0;
426 }
427
428 n = strdup(name);
429 if (!n)
430 return -ENOMEM;
431
432 r = hashmap_ensure_put(known_users, &string_hash_ops, n, UID_TO_PTR(uid));
433 if (r < 0)
434 return r;
435
436 TAKE_PTR(n);
437 *ret = uid;
438 return 0;
439 }
440
441 static int rule_resolve_group(UdevRuleLine *rule_line, const char *name, gid_t *ret) {
442 Hashmap **known_groups = &LINE_GET_RULES(rule_line)->known_groups;
443 _cleanup_free_ char *n = NULL;
444 gid_t gid;
445 void *val;
446 int r;
447
448 assert(name);
449 assert(ret);
450
451 val = hashmap_get(*known_groups, name);
452 if (val) {
453 *ret = PTR_TO_GID(val);
454 return 0;
455 }
456
457 r = get_group_creds(&name, &gid, USER_CREDS_ALLOW_MISSING);
458 if (r < 0) {
459 log_unknown_owner(NULL, rule_line, r, "group", name);
460 *ret = GID_INVALID;
461 return 0;
462 }
463
464 n = strdup(name);
465 if (!n)
466 return -ENOMEM;
467
468 r = hashmap_ensure_put(known_groups, &string_hash_ops, n, GID_TO_PTR(gid));
469 if (r < 0)
470 return r;
471
472 TAKE_PTR(n);
473 *ret = gid;
474 return 0;
475 }
476
477 static UdevRuleSubstituteType rule_get_substitution_type(const char *str) {
478 assert(str);
479
480 if (str[0] == '[')
481 return SUBST_TYPE_SUBSYS;
482 if (strchr(str, '%') || strchr(str, '$'))
483 return SUBST_TYPE_FORMAT;
484 return SUBST_TYPE_PLAIN;
485 }
486
487 static bool type_has_nulstr_value(UdevRuleTokenType type) {
488 return type < TK_M_TEST || type == TK_M_RESULT;
489 }
490
491 static int rule_line_add_token(UdevRuleLine *rule_line, UdevRuleTokenType type, UdevRuleOperatorType op, char *value, void *data) {
492 _cleanup_(udev_rule_token_freep) UdevRuleToken *token = NULL;
493 UdevRuleMatchType match_type = _MATCH_TYPE_INVALID;
494 UdevRuleSubstituteType subst_type = _SUBST_TYPE_INVALID;
495 bool remove_trailing_whitespace = false;
496 size_t len;
497
498 assert(rule_line);
499 assert(type >= 0 && type < _TK_TYPE_MAX);
500 assert(op >= 0 && op < _OP_TYPE_MAX);
501
502 if (type < _TK_M_MAX) {
503 assert(value);
504 assert(IN_SET(op, OP_MATCH, OP_NOMATCH));
505
506 if (type == TK_M_SUBSYSTEM && STR_IN_SET(value, "subsystem", "bus", "class"))
507 match_type = MATCH_TYPE_SUBSYSTEM;
508 else if (isempty(value))
509 match_type = MATCH_TYPE_EMPTY;
510 else if (streq(value, "?*")) {
511 /* Convert KEY=="?*" -> KEY!="" */
512 match_type = MATCH_TYPE_EMPTY;
513 op = op == OP_MATCH ? OP_NOMATCH : OP_MATCH;
514 } else if (string_is_glob(value))
515 match_type = MATCH_TYPE_GLOB;
516 else
517 match_type = MATCH_TYPE_PLAIN;
518
519 if (type_has_nulstr_value(type)) {
520 /* Convert value string to nulstr. */
521 bool bar = true, empty = false;
522 char *a, *b;
523
524 for (a = b = value; *a != '\0'; a++) {
525 if (*a != '|') {
526 *b++ = *a;
527 bar = false;
528 } else {
529 if (bar)
530 empty = true;
531 else
532 *b++ = '\0';
533 bar = true;
534 }
535 }
536 *b = '\0';
537
538 /* Make sure the value is end, so NULSTR_FOREACH can read correct match */
539 if (b < a)
540 b[1] = '\0';
541
542 if (bar)
543 empty = true;
544
545 if (empty) {
546 if (match_type == MATCH_TYPE_GLOB)
547 match_type = MATCH_TYPE_GLOB_WITH_EMPTY;
548 if (match_type == MATCH_TYPE_PLAIN)
549 match_type = MATCH_TYPE_PLAIN_WITH_EMPTY;
550 }
551 }
552 }
553
554 if (IN_SET(type, TK_M_ATTR, TK_M_PARENTS_ATTR)) {
555 assert(value);
556 assert(data);
557
558 len = strlen(value);
559 if (len > 0 && !isspace(value[len - 1]))
560 remove_trailing_whitespace = true;
561
562 subst_type = rule_get_substitution_type(data);
563 }
564
565 token = new(UdevRuleToken, 1);
566 if (!token)
567 return -ENOMEM;
568
569 *token = (UdevRuleToken) {
570 .type = type,
571 .op = op,
572 .value = value,
573 .data = data,
574 .match_type = match_type,
575 .attr_subst_type = subst_type,
576 .attr_match_remove_trailing_whitespace = remove_trailing_whitespace,
577 .rule_line = rule_line,
578 };
579
580 LIST_APPEND(tokens, rule_line->tokens, token);
581
582 if (token->type == TK_A_NAME)
583 SET_FLAG(rule_line->type, LINE_HAS_NAME, true);
584
585 else if (IN_SET(token->type, TK_A_DEVLINK,
586 TK_A_OWNER, TK_A_GROUP, TK_A_MODE,
587 TK_A_OWNER_ID, TK_A_GROUP_ID, TK_A_MODE_ID))
588 SET_FLAG(rule_line->type, LINE_HAS_DEVLINK, true);
589
590 else if (token->type == TK_A_OPTIONS_STATIC_NODE)
591 SET_FLAG(rule_line->type, LINE_HAS_STATIC_NODE, true);
592
593 else if (token->type >= _TK_A_MIN ||
594 IN_SET(token->type, TK_M_PROGRAM,
595 TK_M_IMPORT_FILE, TK_M_IMPORT_PROGRAM, TK_M_IMPORT_BUILTIN,
596 TK_M_IMPORT_DB, TK_M_IMPORT_CMDLINE, TK_M_IMPORT_PARENT))
597 SET_FLAG(rule_line->type, LINE_UPDATE_SOMETHING, true);
598
599 TAKE_PTR(token);
600 return 0;
601 }
602
603 static void check_value_format_and_warn(UdevRuleLine *line, const char *key, const char *value, bool nonempty) {
604 size_t offset;
605 const char *hint;
606
607 if (nonempty && isempty(value))
608 log_line_invalid_value(line, key, value, (size_t) 0, "empty value");
609 else if (udev_check_format(value, &offset, &hint) < 0)
610 log_line_invalid_value(line, key, value, offset + 1, hint);
611 }
612
613 static int check_attr_format_and_warn(UdevRuleLine *line, const char *key, const char *value) {
614 size_t offset;
615 const char *hint;
616
617 if (isempty(value))
618 return log_line_invalid_attr(line, key);
619 if (udev_check_format(value, &offset, &hint) < 0)
620 log_line_invalid_attr_format(line, key, value, offset + 1, hint);
621 return 0;
622 }
623
624 static int parse_token(UdevRuleLine *rule_line, const char *key, char *attr, UdevRuleOperatorType op, char *value) {
625 ResolveNameTiming resolve_name_timing = LINE_GET_RULES(rule_line)->resolve_name_timing;
626 bool is_match = IN_SET(op, OP_MATCH, OP_NOMATCH);
627 int r;
628
629 assert(key);
630 assert(value);
631
632 if (streq(key, "ACTION")) {
633 if (attr)
634 return log_line_invalid_attr(rule_line, key);
635 if (!is_match)
636 return log_line_invalid_op(rule_line, key);
637
638 r = rule_line_add_token(rule_line, TK_M_ACTION, op, value, NULL);
639 } else if (streq(key, "DEVPATH")) {
640 if (attr)
641 return log_line_invalid_attr(rule_line, key);
642 if (!is_match)
643 return log_line_invalid_op(rule_line, key);
644
645 r = rule_line_add_token(rule_line, TK_M_DEVPATH, op, value, NULL);
646 } else if (streq(key, "KERNEL")) {
647 if (attr)
648 return log_line_invalid_attr(rule_line, key);
649 if (!is_match)
650 return log_line_invalid_op(rule_line, key);
651
652 r = rule_line_add_token(rule_line, TK_M_KERNEL, op, value, NULL);
653 } else if (streq(key, "SYMLINK")) {
654 if (attr)
655 return log_line_invalid_attr(rule_line, key);
656 if (!is_match) {
657 check_value_format_and_warn(rule_line, key, value, false);
658 r = rule_line_add_token(rule_line, TK_A_DEVLINK, op, value, NULL);
659 } else
660 r = rule_line_add_token(rule_line, TK_M_DEVLINK, op, value, NULL);
661 } else if (streq(key, "NAME")) {
662 if (attr)
663 return log_line_invalid_attr(rule_line, key);
664 if (op == OP_REMOVE)
665 return log_line_invalid_op(rule_line, key);
666 if (op == OP_ADD) {
667 log_line_warning(rule_line, "%s key takes '==', '!=', '=', or ':=' operator, assuming '='.", key);
668 op = OP_ASSIGN;
669 }
670
671 if (!is_match) {
672 if (streq(value, "%k"))
673 return log_line_error_errno(rule_line, SYNTHETIC_ERRNO(EINVAL),
674 "Ignoring NAME=\"%%k\", as it will take no effect.");
675 if (isempty(value))
676 return log_line_error_errno(rule_line, SYNTHETIC_ERRNO(EINVAL),
677 "Ignoring NAME=\"\", as udev will not delete any network interfaces.");
678 check_value_format_and_warn(rule_line, key, value, false);
679
680 r = rule_line_add_token(rule_line, TK_A_NAME, op, value, NULL);
681 } else
682 r = rule_line_add_token(rule_line, TK_M_NAME, op, value, NULL);
683 } else if (streq(key, "ENV")) {
684 if (isempty(attr))
685 return log_line_invalid_attr(rule_line, key);
686 if (op == OP_REMOVE)
687 return log_line_invalid_op(rule_line, key);
688 if (op == OP_ASSIGN_FINAL) {
689 log_line_warning(rule_line, "%s key takes '==', '!=', '=', or '+=' operator, assuming '='.", key);
690 op = OP_ASSIGN;
691 }
692
693 if (!is_match) {
694 if (STR_IN_SET(attr,
695 "ACTION", "DEVLINKS", "DEVNAME", "DEVPATH", "DEVTYPE", "DRIVER",
696 "IFINDEX", "MAJOR", "MINOR", "SEQNUM", "SUBSYSTEM", "TAGS"))
697 return log_line_error_errno(rule_line, SYNTHETIC_ERRNO(EINVAL),
698 "Invalid ENV attribute. '%s' cannot be set.", attr);
699
700 check_value_format_and_warn(rule_line, key, value, false);
701
702 r = rule_line_add_token(rule_line, TK_A_ENV, op, value, attr);
703 } else
704 r = rule_line_add_token(rule_line, TK_M_ENV, op, value, attr);
705 } else if (streq(key, "CONST")) {
706 if (isempty(attr) || !STR_IN_SET(attr, "arch", "virt"))
707 return log_line_invalid_attr(rule_line, key);
708 if (!is_match)
709 return log_line_invalid_op(rule_line, key);
710 r = rule_line_add_token(rule_line, TK_M_CONST, op, value, attr);
711 } else if (streq(key, "TAG")) {
712 if (attr)
713 return log_line_invalid_attr(rule_line, key);
714 if (op == OP_ASSIGN_FINAL) {
715 log_line_warning(rule_line, "%s key takes '==', '!=', '=', or '+=' operator, assuming '='.", key);
716 op = OP_ASSIGN;
717 }
718
719 if (!is_match) {
720 check_value_format_and_warn(rule_line, key, value, true);
721
722 r = rule_line_add_token(rule_line, TK_A_TAG, op, value, NULL);
723 } else
724 r = rule_line_add_token(rule_line, TK_M_TAG, op, value, NULL);
725 } else if (streq(key, "SUBSYSTEM")) {
726 if (attr)
727 return log_line_invalid_attr(rule_line, key);
728 if (!is_match)
729 return log_line_invalid_op(rule_line, key);
730
731 if (STR_IN_SET(value, "bus", "class"))
732 log_line_warning(rule_line, "\"%s\" must be specified as \"subsystem\".", value);
733
734 r = rule_line_add_token(rule_line, TK_M_SUBSYSTEM, op, value, NULL);
735 } else if (streq(key, "DRIVER")) {
736 if (attr)
737 return log_line_invalid_attr(rule_line, key);
738 if (!is_match)
739 return log_line_invalid_op(rule_line, key);
740
741 r = rule_line_add_token(rule_line, TK_M_DRIVER, op, value, NULL);
742 } else if (streq(key, "ATTR")) {
743 r = check_attr_format_and_warn(rule_line, key, attr);
744 if (r < 0)
745 return r;
746 if (op == OP_REMOVE)
747 return log_line_invalid_op(rule_line, key);
748 if (IN_SET(op, OP_ADD, OP_ASSIGN_FINAL)) {
749 log_line_warning(rule_line, "%s key takes '==', '!=', or '=' operator, assuming '='.", key);
750 op = OP_ASSIGN;
751 }
752
753 if (!is_match) {
754 check_value_format_and_warn(rule_line, key, value, false);
755 r = rule_line_add_token(rule_line, TK_A_ATTR, op, value, attr);
756 } else
757 r = rule_line_add_token(rule_line, TK_M_ATTR, op, value, attr);
758 } else if (streq(key, "SYSCTL")) {
759 r = check_attr_format_and_warn(rule_line, key, attr);
760 if (r < 0)
761 return r;
762 if (op == OP_REMOVE)
763 return log_line_invalid_op(rule_line, key);
764 if (IN_SET(op, OP_ADD, OP_ASSIGN_FINAL)) {
765 log_line_warning(rule_line, "%s key takes '==', '!=', or '=' operator, assuming '='.", key);
766 op = OP_ASSIGN;
767 }
768
769 if (!is_match) {
770 check_value_format_and_warn(rule_line, key, value, false);
771 r = rule_line_add_token(rule_line, TK_A_SYSCTL, op, value, attr);
772 } else
773 r = rule_line_add_token(rule_line, TK_M_SYSCTL, op, value, attr);
774 } else if (streq(key, "KERNELS")) {
775 if (attr)
776 return log_line_invalid_attr(rule_line, key);
777 if (!is_match)
778 return log_line_invalid_op(rule_line, key);
779
780 r = rule_line_add_token(rule_line, TK_M_PARENTS_KERNEL, op, value, NULL);
781 } else if (streq(key, "SUBSYSTEMS")) {
782 if (attr)
783 return log_line_invalid_attr(rule_line, key);
784 if (!is_match)
785 return log_line_invalid_op(rule_line, key);
786
787 r = rule_line_add_token(rule_line, TK_M_PARENTS_SUBSYSTEM, op, value, NULL);
788 } else if (streq(key, "DRIVERS")) {
789 if (attr)
790 return log_line_invalid_attr(rule_line, key);
791 if (!is_match)
792 return log_line_invalid_op(rule_line, key);
793
794 r = rule_line_add_token(rule_line, TK_M_PARENTS_DRIVER, op, value, NULL);
795 } else if (streq(key, "ATTRS")) {
796 r = check_attr_format_and_warn(rule_line, key, attr);
797 if (r < 0)
798 return r;
799 if (!is_match)
800 return log_line_invalid_op(rule_line, key);
801
802 if (startswith(attr, "device/"))
803 log_line_warning(rule_line, "'device' link may not be available in future kernels.");
804 if (strstr(attr, "../"))
805 log_line_warning(rule_line, "Direct reference to parent sysfs directory, may break in future kernels.");
806
807 r = rule_line_add_token(rule_line, TK_M_PARENTS_ATTR, op, value, attr);
808 } else if (streq(key, "TAGS")) {
809 if (attr)
810 return log_line_invalid_attr(rule_line, key);
811 if (!is_match)
812 return log_line_invalid_op(rule_line, key);
813
814 r = rule_line_add_token(rule_line, TK_M_PARENTS_TAG, op, value, NULL);
815 } else if (streq(key, "TEST")) {
816 mode_t mode = MODE_INVALID;
817
818 if (!isempty(attr)) {
819 r = parse_mode(attr, &mode);
820 if (r < 0)
821 return log_line_error_errno(rule_line, r, "Failed to parse mode '%s': %m", attr);
822 }
823 check_value_format_and_warn(rule_line, key, value, true);
824 if (!is_match)
825 return log_line_invalid_op(rule_line, key);
826
827 r = rule_line_add_token(rule_line, TK_M_TEST, op, value, MODE_TO_PTR(mode));
828 } else if (streq(key, "PROGRAM")) {
829 if (attr)
830 return log_line_invalid_attr(rule_line, key);
831 check_value_format_and_warn(rule_line, key, value, true);
832 if (op == OP_REMOVE)
833 return log_line_invalid_op(rule_line, key);
834 if (!is_match)
835 op = OP_MATCH;
836
837 r = rule_line_add_token(rule_line, TK_M_PROGRAM, op, value, NULL);
838 } else if (streq(key, "IMPORT")) {
839 if (isempty(attr))
840 return log_line_invalid_attr(rule_line, key);
841 check_value_format_and_warn(rule_line, key, value, true);
842 if (op == OP_REMOVE)
843 return log_line_invalid_op(rule_line, key);
844 if (!is_match)
845 op = OP_MATCH;
846
847 if (streq(attr, "file"))
848 r = rule_line_add_token(rule_line, TK_M_IMPORT_FILE, op, value, NULL);
849 else if (streq(attr, "program")) {
850 UdevBuiltinCommand cmd;
851
852 cmd = udev_builtin_lookup(value);
853 if (cmd >= 0) {
854 log_line_debug(rule_line, "Found builtin command '%s' for %s, replacing attribute.", value, key);
855 r = rule_line_add_token(rule_line, TK_M_IMPORT_BUILTIN, op, value, UDEV_BUILTIN_CMD_TO_PTR(cmd));
856 } else
857 r = rule_line_add_token(rule_line, TK_M_IMPORT_PROGRAM, op, value, NULL);
858 } else if (streq(attr, "builtin")) {
859 UdevBuiltinCommand cmd;
860
861 cmd = udev_builtin_lookup(value);
862 if (cmd < 0)
863 return log_line_error_errno(rule_line, SYNTHETIC_ERRNO(EINVAL),
864 "Unknown builtin command: %s", value);
865 r = rule_line_add_token(rule_line, TK_M_IMPORT_BUILTIN, op, value, UDEV_BUILTIN_CMD_TO_PTR(cmd));
866 } else if (streq(attr, "db"))
867 r = rule_line_add_token(rule_line, TK_M_IMPORT_DB, op, value, NULL);
868 else if (streq(attr, "cmdline"))
869 r = rule_line_add_token(rule_line, TK_M_IMPORT_CMDLINE, op, value, NULL);
870 else if (streq(attr, "parent"))
871 r = rule_line_add_token(rule_line, TK_M_IMPORT_PARENT, op, value, NULL);
872 else
873 return log_line_invalid_attr(rule_line, key);
874 } else if (streq(key, "RESULT")) {
875 if (attr)
876 return log_line_invalid_attr(rule_line, key);
877 if (!is_match)
878 return log_line_invalid_op(rule_line, key);
879
880 r = rule_line_add_token(rule_line, TK_M_RESULT, op, value, NULL);
881 } else if (streq(key, "OPTIONS")) {
882 char *tmp;
883
884 if (attr)
885 return log_line_invalid_attr(rule_line, key);
886 if (is_match || op == OP_REMOVE)
887 return log_line_invalid_op(rule_line, key);
888 if (op == OP_ADD)
889 op = OP_ASSIGN;
890
891 if (streq(value, "string_escape=none"))
892 r = rule_line_add_token(rule_line, TK_A_OPTIONS_STRING_ESCAPE_NONE, op, NULL, NULL);
893 else if (streq(value, "string_escape=replace"))
894 r = rule_line_add_token(rule_line, TK_A_OPTIONS_STRING_ESCAPE_REPLACE, op, NULL, NULL);
895 else if (streq(value, "db_persist"))
896 r = rule_line_add_token(rule_line, TK_A_OPTIONS_DB_PERSIST, op, NULL, NULL);
897 else if (streq(value, "watch"))
898 r = rule_line_add_token(rule_line, TK_A_OPTIONS_INOTIFY_WATCH, op, NULL, INT_TO_PTR(1));
899 else if (streq(value, "nowatch"))
900 r = rule_line_add_token(rule_line, TK_A_OPTIONS_INOTIFY_WATCH, op, NULL, INT_TO_PTR(0));
901 else if ((tmp = startswith(value, "static_node=")))
902 r = rule_line_add_token(rule_line, TK_A_OPTIONS_STATIC_NODE, op, tmp, NULL);
903 else if ((tmp = startswith(value, "link_priority="))) {
904 int prio;
905
906 r = safe_atoi(tmp, &prio);
907 if (r < 0)
908 return log_line_error_errno(rule_line, r, "Failed to parse link priority '%s': %m", tmp);
909 r = rule_line_add_token(rule_line, TK_A_OPTIONS_DEVLINK_PRIORITY, op, NULL, INT_TO_PTR(prio));
910 } else if ((tmp = startswith(value, "log_level="))) {
911 int level;
912
913 if (streq(tmp, "reset"))
914 level = -1;
915 else {
916 level = log_level_from_string(tmp);
917 if (level < 0)
918 return log_line_error_errno(rule_line, level, "Failed to parse log level '%s': %m", tmp);
919 }
920 r = rule_line_add_token(rule_line, TK_A_OPTIONS_LOG_LEVEL, op, NULL, INT_TO_PTR(level));
921 } else {
922 log_line_warning(rule_line, "Invalid value for OPTIONS key, ignoring: '%s'", value);
923 return 0;
924 }
925 } else if (streq(key, "OWNER")) {
926 uid_t uid;
927
928 if (attr)
929 return log_line_invalid_attr(rule_line, key);
930 if (is_match || op == OP_REMOVE)
931 return log_line_invalid_op(rule_line, key);
932 if (op == OP_ADD) {
933 log_line_warning(rule_line, "%s key takes '=' or ':=' operator, assuming '='.", key);
934 op = OP_ASSIGN;
935 }
936
937 if (parse_uid(value, &uid) >= 0)
938 r = rule_line_add_token(rule_line, TK_A_OWNER_ID, op, NULL, UID_TO_PTR(uid));
939 else if (resolve_name_timing == RESOLVE_NAME_EARLY &&
940 rule_get_substitution_type(value) == SUBST_TYPE_PLAIN) {
941 r = rule_resolve_user(rule_line, value, &uid);
942 if (r < 0)
943 return log_line_error_errno(rule_line, r, "Failed to resolve user name '%s': %m", value);
944
945 r = rule_line_add_token(rule_line, TK_A_OWNER_ID, op, NULL, UID_TO_PTR(uid));
946 } else if (resolve_name_timing != RESOLVE_NAME_NEVER) {
947 check_value_format_and_warn(rule_line, key, value, true);
948 r = rule_line_add_token(rule_line, TK_A_OWNER, op, value, NULL);
949 } else {
950 log_line_debug(rule_line, "User name resolution is disabled, ignoring %s=\"%s\".", key, value);
951 return 0;
952 }
953 } else if (streq(key, "GROUP")) {
954 gid_t gid;
955
956 if (attr)
957 return log_line_invalid_attr(rule_line, key);
958 if (is_match || op == OP_REMOVE)
959 return log_line_invalid_op(rule_line, key);
960 if (op == OP_ADD) {
961 log_line_warning(rule_line, "%s key takes '=' or ':=' operator, assuming '='.", key);
962 op = OP_ASSIGN;
963 }
964
965 if (parse_gid(value, &gid) >= 0)
966 r = rule_line_add_token(rule_line, TK_A_GROUP_ID, op, NULL, GID_TO_PTR(gid));
967 else if (resolve_name_timing == RESOLVE_NAME_EARLY &&
968 rule_get_substitution_type(value) == SUBST_TYPE_PLAIN) {
969 r = rule_resolve_group(rule_line, value, &gid);
970 if (r < 0)
971 return log_line_error_errno(rule_line, r, "Failed to resolve group name '%s': %m", value);
972
973 r = rule_line_add_token(rule_line, TK_A_GROUP_ID, op, NULL, GID_TO_PTR(gid));
974 } else if (resolve_name_timing != RESOLVE_NAME_NEVER) {
975 check_value_format_and_warn(rule_line, key, value, true);
976 r = rule_line_add_token(rule_line, TK_A_GROUP, op, value, NULL);
977 } else {
978 log_line_debug(rule_line, "Resolving group name is disabled, ignoring GROUP=\"%s\".", value);
979 return 0;
980 }
981 } else if (streq(key, "MODE")) {
982 mode_t mode;
983
984 if (attr)
985 return log_line_invalid_attr(rule_line, key);
986 if (is_match || op == OP_REMOVE)
987 return log_line_invalid_op(rule_line, key);
988 if (op == OP_ADD) {
989 log_line_warning(rule_line, "%s key takes '=' or ':=' operator, assuming '='.", key);
990 op = OP_ASSIGN;
991 }
992
993 if (parse_mode(value, &mode) >= 0)
994 r = rule_line_add_token(rule_line, TK_A_MODE_ID, op, NULL, MODE_TO_PTR(mode));
995 else {
996 check_value_format_and_warn(rule_line, key, value, true);
997 r = rule_line_add_token(rule_line, TK_A_MODE, op, value, NULL);
998 }
999 } else if (streq(key, "SECLABEL")) {
1000 if (isempty(attr))
1001 return log_line_invalid_attr(rule_line, key);
1002 check_value_format_and_warn(rule_line, key, value, true);
1003 if (is_match || op == OP_REMOVE)
1004 return log_line_invalid_op(rule_line, key);
1005 if (op == OP_ASSIGN_FINAL) {
1006 log_line_warning(rule_line, "%s key takes '=' or '+=' operator, assuming '='.", key);
1007 op = OP_ASSIGN;
1008 }
1009
1010 r = rule_line_add_token(rule_line, TK_A_SECLABEL, op, value, attr);
1011 } else if (streq(key, "RUN")) {
1012 if (is_match || op == OP_REMOVE)
1013 return log_line_invalid_op(rule_line, key);
1014 check_value_format_and_warn(rule_line, key, value, true);
1015 if (!attr || streq(attr, "program"))
1016 r = rule_line_add_token(rule_line, TK_A_RUN_PROGRAM, op, value, NULL);
1017 else if (streq(attr, "builtin")) {
1018 UdevBuiltinCommand cmd;
1019
1020 cmd = udev_builtin_lookup(value);
1021 if (cmd < 0)
1022 return log_line_error_errno(rule_line, SYNTHETIC_ERRNO(EINVAL),
1023 "Unknown builtin command '%s', ignoring.", value);
1024 r = rule_line_add_token(rule_line, TK_A_RUN_BUILTIN, op, value, UDEV_BUILTIN_CMD_TO_PTR(cmd));
1025 } else
1026 return log_line_invalid_attr(rule_line, key);
1027 } else if (streq(key, "GOTO")) {
1028 if (attr)
1029 return log_line_invalid_attr(rule_line, key);
1030 if (op != OP_ASSIGN)
1031 return log_line_invalid_op(rule_line, key);
1032 if (FLAGS_SET(rule_line->type, LINE_HAS_GOTO)) {
1033 log_line_warning(rule_line, "Contains multiple GOTO keys, ignoring GOTO=\"%s\".", value);
1034 return 0;
1035 }
1036
1037 rule_line->goto_label = value;
1038 SET_FLAG(rule_line->type, LINE_HAS_GOTO, true);
1039 return 1;
1040 } else if (streq(key, "LABEL")) {
1041 if (attr)
1042 return log_line_invalid_attr(rule_line, key);
1043 if (op != OP_ASSIGN)
1044 return log_line_invalid_op(rule_line, key);
1045 if (FLAGS_SET(rule_line->type, LINE_HAS_LABEL))
1046 log_line_warning(rule_line, "Contains multiple LABEL keys, ignoring LABEL=\"%s\".",
1047 rule_line->label);
1048
1049 rule_line->label = value;
1050 SET_FLAG(rule_line->type, LINE_HAS_LABEL, true);
1051 return 1;
1052 } else
1053 return log_line_error_errno(rule_line, SYNTHETIC_ERRNO(EINVAL), "Invalid key '%s'.", key);
1054 if (r < 0)
1055 return log_oom();
1056
1057 return 1;
1058 }
1059
1060 static UdevRuleOperatorType parse_operator(const char *op) {
1061 assert(op);
1062
1063 if (startswith(op, "=="))
1064 return OP_MATCH;
1065 if (startswith(op, "!="))
1066 return OP_NOMATCH;
1067 if (startswith(op, "+="))
1068 return OP_ADD;
1069 if (startswith(op, "-="))
1070 return OP_REMOVE;
1071 if (startswith(op, "="))
1072 return OP_ASSIGN;
1073 if (startswith(op, ":="))
1074 return OP_ASSIGN_FINAL;
1075
1076 return _OP_TYPE_INVALID;
1077 }
1078
1079 static void check_token_delimiters(UdevRuleLine *rule_line, const char *line) {
1080 assert(rule_line);
1081
1082 size_t n_comma = 0;
1083 bool ws_before_comma = false, ws_after_comma = false;
1084 const char *p;
1085
1086 for (p = line; !isempty(p); ++p) {
1087 if (*p == ',')
1088 ++n_comma;
1089 else if (strchr(WHITESPACE, *p)) {
1090 if (n_comma > 0)
1091 ws_after_comma = true;
1092 else
1093 ws_before_comma = true;
1094 } else
1095 break;
1096 }
1097
1098 if (line == rule_line->line) {
1099 /* this is the first token of the rule */
1100 if (n_comma > 0)
1101 log_line_notice(rule_line, "style: stray leading comma.");
1102 } else if (isempty(p)) {
1103 /* there are no more tokens in the rule */
1104 if (n_comma > 0)
1105 log_line_notice(rule_line, "style: stray trailing comma.");
1106 } else {
1107 /* single comma is expected */
1108 if (n_comma == 0)
1109 log_line_notice(rule_line, "style: a comma between tokens is expected.");
1110 else if (n_comma > 1)
1111 log_line_notice(rule_line, "style: more than one comma between tokens.");
1112
1113 /* whitespace after comma is expected */
1114 if (n_comma > 0) {
1115 if (ws_before_comma)
1116 log_line_notice(rule_line, "style: stray whitespace before comma.");
1117 if (!ws_after_comma)
1118 log_line_notice(rule_line, "style: whitespace after comma is expected.");
1119 } else if (!ws_before_comma && !ws_after_comma)
1120 log_line_notice(rule_line, "style: whitespace between tokens is expected.");
1121 }
1122 }
1123
1124 int udev_rule_parse_value(char *str, char **ret_value, char **ret_endpos) {
1125 char *i, *j;
1126 bool is_escaped;
1127
1128 /* value must be double quotated */
1129 is_escaped = str[0] == 'e';
1130 str += is_escaped;
1131 if (str[0] != '"')
1132 return -EINVAL;
1133
1134 if (!is_escaped) {
1135 /* unescape double quotation '\"'->'"' */
1136 for (j = str, i = str + 1; *i != '"'; i++, j++) {
1137 if (*i == '\0')
1138 return -EINVAL;
1139 if (i[0] == '\\' && i[1] == '"')
1140 i++;
1141 *j = *i;
1142 }
1143 j[0] = '\0';
1144 /*
1145 * The return value must be terminated by two subsequent NULs
1146 * so it could be safely interpreted as nulstr.
1147 */
1148 j[1] = '\0';
1149 } else {
1150 _cleanup_free_ char *unescaped = NULL;
1151 ssize_t l;
1152
1153 /* find the end position of value */
1154 for (i = str + 1; *i != '"'; i++) {
1155 if (i[0] == '\\')
1156 i++;
1157 if (*i == '\0')
1158 return -EINVAL;
1159 }
1160 i[0] = '\0';
1161
1162 l = cunescape_length(str + 1, i - (str + 1), 0, &unescaped);
1163 if (l < 0)
1164 return l;
1165
1166 assert(l <= i - (str + 1));
1167 memcpy(str, unescaped, l + 1);
1168 /*
1169 * The return value must be terminated by two subsequent NULs
1170 * so it could be safely interpreted as nulstr.
1171 */
1172 str[l + 1] = '\0';
1173 }
1174
1175 *ret_value = str;
1176 *ret_endpos = i + 1;
1177 return 0;
1178 }
1179
1180 static int parse_line(char **line, char **ret_key, char **ret_attr, UdevRuleOperatorType *ret_op, char **ret_value) {
1181 char *key_begin, *key_end, *attr, *tmp;
1182 UdevRuleOperatorType op;
1183 int r;
1184
1185 assert(line);
1186 assert(*line);
1187 assert(ret_key);
1188 assert(ret_op);
1189 assert(ret_value);
1190
1191 key_begin = skip_leading_chars(*line, WHITESPACE ",");
1192
1193 if (isempty(key_begin))
1194 return 0;
1195
1196 for (key_end = key_begin; ; key_end++) {
1197 if (key_end[0] == '\0')
1198 return -EINVAL;
1199 if (strchr(WHITESPACE "={", key_end[0]))
1200 break;
1201 if (strchr("+-!:", key_end[0]) && key_end[1] == '=')
1202 break;
1203 }
1204 if (key_end[0] == '{') {
1205 attr = key_end + 1;
1206 tmp = strchr(attr, '}');
1207 if (!tmp)
1208 return -EINVAL;
1209 *tmp++ = '\0';
1210 } else {
1211 attr = NULL;
1212 tmp = key_end;
1213 }
1214
1215 tmp = skip_leading_chars(tmp, NULL);
1216 op = parse_operator(tmp);
1217 if (op < 0)
1218 return -EINVAL;
1219
1220 key_end[0] = '\0';
1221
1222 tmp += op == OP_ASSIGN ? 1 : 2;
1223 tmp = skip_leading_chars(tmp, NULL);
1224 r = udev_rule_parse_value(tmp, ret_value, line);
1225 if (r < 0)
1226 return r;
1227
1228 *ret_key = key_begin;
1229 *ret_attr = attr;
1230 *ret_op = op;
1231 return 1;
1232 }
1233
1234 static void check_tokens_order(UdevRuleLine *rule_line) {
1235 bool has_result = false;
1236
1237 assert(rule_line);
1238
1239 LIST_FOREACH(tokens, t, rule_line->tokens)
1240 if (t->type == TK_M_RESULT)
1241 has_result = true;
1242 else if (has_result && t->type == TK_M_PROGRAM) {
1243 log_line_warning(rule_line, "Reordering RESULT check after PROGRAM assignment.");
1244 break;
1245 }
1246 }
1247
1248 static void sort_tokens(UdevRuleLine *rule_line) {
1249 assert(rule_line);
1250
1251 UdevRuleToken *old_tokens = TAKE_PTR(rule_line->tokens);
1252
1253 while (old_tokens) {
1254 UdevRuleToken *min_token = NULL;
1255
1256 LIST_FOREACH(tokens, t, old_tokens)
1257 if (!min_token || min_token->type > t->type)
1258 min_token = t;
1259
1260 LIST_REMOVE(tokens, old_tokens, min_token);
1261 LIST_APPEND(tokens, rule_line->tokens, min_token);
1262 }
1263 }
1264
1265 static int rule_add_line(UdevRuleFile *rule_file, const char *line_str, unsigned line_nr, bool extra_checks) {
1266 _cleanup_(udev_rule_line_freep) UdevRuleLine *rule_line = NULL;
1267 _cleanup_free_ char *line = NULL;
1268 char *p;
1269 int r;
1270
1271 assert(rule_file);
1272 assert(line_str);
1273
1274 if (isempty(line_str))
1275 return 0;
1276
1277 line = strdup(line_str);
1278 if (!line)
1279 return log_oom();
1280
1281 rule_line = new(UdevRuleLine, 1);
1282 if (!rule_line)
1283 return log_oom();
1284
1285 *rule_line = (UdevRuleLine) {
1286 .line = TAKE_PTR(line),
1287 .line_number = line_nr,
1288 .rule_file = rule_file,
1289 };
1290
1291 LIST_APPEND(rule_lines, rule_file->rule_lines, rule_line);
1292
1293 for (p = rule_line->line; !isempty(p); ) {
1294 char *key, *attr, *value;
1295 UdevRuleOperatorType op;
1296
1297 if (extra_checks)
1298 check_token_delimiters(rule_line, p);
1299
1300 r = parse_line(&p, &key, &attr, &op, &value);
1301 if (r < 0)
1302 return log_line_error_errno(rule_line, r, "Invalid key/value pair, ignoring.");
1303 if (r == 0)
1304 break;
1305
1306 r = parse_token(rule_line, key, attr, op, value);
1307 if (r < 0)
1308 return r;
1309 }
1310
1311 if (rule_line->type == 0) {
1312 log_line_warning(rule_line, "The line has no effect, ignoring.");
1313 return 0;
1314 }
1315
1316 if (extra_checks)
1317 check_tokens_order(rule_line);
1318
1319 sort_tokens(rule_line);
1320 TAKE_PTR(rule_line);
1321 return 0;
1322 }
1323
1324 static void rule_resolve_goto(UdevRuleFile *rule_file) {
1325 assert(rule_file);
1326
1327 /* link GOTOs to LABEL rules in this file to be able to fast-forward */
1328 LIST_FOREACH(rule_lines, line, rule_file->rule_lines) {
1329 if (!FLAGS_SET(line->type, LINE_HAS_GOTO))
1330 continue;
1331
1332 LIST_FOREACH(rule_lines, i, line->rule_lines_next)
1333 if (streq_ptr(i->label, line->goto_label)) {
1334 line->goto_line = i;
1335 SET_FLAG(i->type, LINE_IS_REFERENCED, true);
1336 break;
1337 }
1338
1339 if (!line->goto_line) {
1340 log_line_error(line, "GOTO=\"%s\" has no matching label, ignoring.",
1341 line->goto_label);
1342
1343 SET_FLAG(line->type, LINE_HAS_GOTO, false);
1344 line->goto_label = NULL;
1345
1346 if ((line->type & ~(LINE_HAS_LABEL|LINE_IS_REFERENCED)) == 0) {
1347 log_line_warning(line, "The line has no effect any more, dropping.");
1348 /* LINE_IS_REFERENCED implies LINE_HAS_LABEL */
1349 if (line->type & LINE_HAS_LABEL)
1350 udev_rule_line_clear_tokens(line);
1351 else
1352 udev_rule_line_free(line);
1353 }
1354 }
1355 }
1356 }
1357
1358 static bool token_data_is_string(UdevRuleTokenType type) {
1359 return IN_SET(type, TK_M_ENV,
1360 TK_M_CONST,
1361 TK_M_ATTR,
1362 TK_M_SYSCTL,
1363 TK_M_PARENTS_ATTR,
1364 TK_A_SECLABEL,
1365 TK_A_ENV,
1366 TK_A_ATTR,
1367 TK_A_SYSCTL);
1368 }
1369
1370 static bool token_type_and_data_eq(const UdevRuleToken *a, const UdevRuleToken *b) {
1371 assert(a);
1372 assert(b);
1373
1374 return a->type == b->type &&
1375 (token_data_is_string(a->type) ? streq_ptr(a->data, b->data) : (a->data == b->data));
1376 }
1377
1378 static bool nulstr_eq(const char *a, const char *b) {
1379 NULSTR_FOREACH(i, a)
1380 if (!nulstr_contains(b, i))
1381 return false;
1382
1383 NULSTR_FOREACH(i, b)
1384 if (!nulstr_contains(a, i))
1385 return false;
1386
1387 return true;
1388 }
1389
1390 static bool token_type_and_value_eq(const UdevRuleToken *a, const UdevRuleToken *b) {
1391 assert(a);
1392 assert(b);
1393
1394 if (a->type != b->type ||
1395 a->match_type != b->match_type)
1396 return false;
1397
1398 /* token value is ignored for certain match types */
1399 if (IN_SET(a->match_type, MATCH_TYPE_EMPTY, MATCH_TYPE_SUBSYSTEM))
1400 return true;
1401
1402 return type_has_nulstr_value(a->type) ? nulstr_eq(a->value, b->value) :
1403 streq_ptr(a->value, b->value);
1404 }
1405
1406 static bool conflicting_op(UdevRuleOperatorType a, UdevRuleOperatorType b) {
1407 return (a == OP_MATCH && b == OP_NOMATCH) ||
1408 (a == OP_NOMATCH && b == OP_MATCH);
1409 }
1410
1411 /* test whether all fields besides UdevRuleOperatorType of two tokens match */
1412 static bool tokens_eq(const UdevRuleToken *a, const UdevRuleToken *b) {
1413 assert(a);
1414 assert(b);
1415
1416 return a->attr_subst_type == b->attr_subst_type &&
1417 a->attr_match_remove_trailing_whitespace == b->attr_match_remove_trailing_whitespace &&
1418 token_type_and_value_eq(a, b) &&
1419 token_type_and_data_eq(a, b);
1420 }
1421
1422 static bool nulstr_tokens_conflict(const UdevRuleToken *a, const UdevRuleToken *b) {
1423 assert(a);
1424 assert(b);
1425
1426 if (!(a->type == b->type &&
1427 type_has_nulstr_value(a->type) &&
1428 a->op == b->op &&
1429 a->op == OP_MATCH &&
1430 a->match_type == b->match_type &&
1431 a->attr_subst_type == b->attr_subst_type &&
1432 a->attr_match_remove_trailing_whitespace == b->attr_match_remove_trailing_whitespace &&
1433 token_type_and_data_eq(a, b)))
1434 return false;
1435
1436 if (a->match_type == MATCH_TYPE_PLAIN) {
1437 NULSTR_FOREACH(i, a->value)
1438 if (nulstr_contains(b->value, i))
1439 return false;
1440 return true;
1441 }
1442
1443 if (a->match_type == MATCH_TYPE_GLOB) {
1444 NULSTR_FOREACH(i, a->value) {
1445 size_t i_n = strcspn(i, GLOB_CHARS);
1446 if (i_n == 0)
1447 return false;
1448 NULSTR_FOREACH(j, b->value) {
1449 size_t j_n = strcspn(j, GLOB_CHARS);
1450 if (j_n == 0 || strneq(i, j, MIN(i_n, j_n)))
1451 return false;
1452 }
1453
1454 }
1455 return true;
1456 }
1457
1458 return false;
1459 }
1460
1461 static void udev_check_unused_labels(UdevRuleLine *line) {
1462 assert(line);
1463
1464 if (FLAGS_SET(line->type, LINE_HAS_LABEL) &&
1465 !FLAGS_SET(line->type, LINE_IS_REFERENCED))
1466 log_line_notice(line, "style: LABEL=\"%s\" is unused.", line->label);
1467 }
1468
1469 static void udev_check_conflicts_duplicates(UdevRuleLine *line) {
1470 assert(line);
1471
1472 bool conflicts = false, duplicates = false;
1473
1474 LIST_FOREACH(tokens, token, line->tokens)
1475 LIST_FOREACH(tokens, i, token->tokens_next) {
1476 bool new_conflicts = false, new_duplicates = false;
1477
1478 if (tokens_eq(token, i)) {
1479 if (!duplicates && token->op == i->op)
1480 new_duplicates = true;
1481 if (!conflicts && conflicting_op(token->op, i->op))
1482 new_conflicts = true;
1483 } else if (!conflicts && nulstr_tokens_conflict(token, i))
1484 new_conflicts = true;
1485 else
1486 continue;
1487
1488 if (new_duplicates) {
1489 duplicates = new_duplicates;
1490 log_line_warning(line, "duplicate expressions.");
1491 }
1492 if (new_conflicts) {
1493 conflicts = new_conflicts;
1494 log_line_error(line, "conflicting match expressions, the line has no effect.");
1495 }
1496 if (conflicts && duplicates)
1497 return;
1498 }
1499 }
1500
1501 static void udev_check_rule_line(UdevRuleLine *line) {
1502 udev_check_unused_labels(line);
1503 udev_check_conflicts_duplicates(line);
1504 }
1505
1506 int udev_rules_parse_file(UdevRules *rules, const char *filename, bool extra_checks, UdevRuleFile **ret) {
1507 _cleanup_(udev_rule_file_freep) UdevRuleFile *rule_file = NULL;
1508 _cleanup_free_ char *continuation = NULL, *name = NULL;
1509 _cleanup_fclose_ FILE *f = NULL;
1510 bool ignore_line = false;
1511 unsigned line_nr = 0;
1512 struct stat st;
1513 int r;
1514
1515 assert(rules);
1516 assert(filename);
1517
1518 f = fopen(filename, "re");
1519 if (!f) {
1520 if (extra_checks)
1521 return -errno;
1522
1523 if (errno == ENOENT)
1524 return 0;
1525
1526 return log_warning_errno(errno, "Failed to open %s, ignoring: %m", filename);
1527 }
1528
1529 if (fstat(fileno(f), &st) < 0)
1530 return log_warning_errno(errno, "Failed to stat %s, ignoring: %m", filename);
1531
1532 if (null_or_empty(&st)) {
1533 log_debug("Skipping empty file: %s", filename);
1534 if (ret)
1535 *ret = NULL;
1536 return 0;
1537 }
1538
1539 r = hashmap_put_stats_by_path(&rules->stats_by_path, filename, &st);
1540 if (r < 0)
1541 return log_warning_errno(errno, "Failed to save stat for %s, ignoring: %m", filename);
1542
1543 (void) fd_warn_permissions(filename, fileno(f));
1544
1545 log_debug("Reading rules file: %s", filename);
1546
1547 name = strdup(filename);
1548 if (!name)
1549 return log_oom();
1550
1551 rule_file = new(UdevRuleFile, 1);
1552 if (!rule_file)
1553 return log_oom();
1554
1555 *rule_file = (UdevRuleFile) {
1556 .filename = TAKE_PTR(name),
1557 .rules = rules,
1558 };
1559
1560 LIST_APPEND(rule_files, rules->rule_files, rule_file);
1561
1562 for (;;) {
1563 _cleanup_free_ char *buf = NULL;
1564 size_t len;
1565 char *line;
1566
1567 r = read_line(f, UDEV_LINE_SIZE, &buf);
1568 if (r < 0)
1569 return r;
1570 if (r == 0)
1571 break;
1572
1573 line_nr++;
1574 line = skip_leading_chars(buf, NULL);
1575
1576 /* Lines beginning with '#' are ignored regardless of line continuation. */
1577 if (line[0] == '#')
1578 continue;
1579
1580 len = strlen(line);
1581
1582 if (continuation && !ignore_line) {
1583 if (strlen(continuation) + len >= UDEV_LINE_SIZE)
1584 ignore_line = true;
1585
1586 if (!strextend(&continuation, line))
1587 return log_oom();
1588
1589 if (!ignore_line) {
1590 line = continuation;
1591 len = strlen(line);
1592 }
1593 }
1594
1595 if (len > 0 && line[len - 1] == '\\') {
1596 if (ignore_line)
1597 continue;
1598
1599 line[len - 1] = '\0';
1600 if (!continuation) {
1601 continuation = strdup(line);
1602 if (!continuation)
1603 return log_oom();
1604 }
1605
1606 continue;
1607 }
1608
1609 if (ignore_line)
1610 log_file_error(rule_file, line_nr, "Line is too long, ignored.");
1611 else if (len > 0)
1612 (void) rule_add_line(rule_file, line, line_nr, extra_checks);
1613
1614 continuation = mfree(continuation);
1615 ignore_line = false;
1616 }
1617
1618 if (continuation)
1619 log_file_error(rule_file, line_nr,
1620 "Unexpected EOF after line continuation, line ignored.");
1621
1622 rule_resolve_goto(rule_file);
1623
1624 if (extra_checks)
1625 LIST_FOREACH(rule_lines, line, rule_file->rule_lines)
1626 udev_check_rule_line(line);
1627
1628 if (ret)
1629 *ret = rule_file;
1630
1631 TAKE_PTR(rule_file);
1632 return 1;
1633 }
1634
1635 unsigned udev_rule_file_get_issues(UdevRuleFile *rule_file) {
1636 assert(rule_file);
1637
1638 return rule_file->issues;
1639 }
1640
1641 UdevRules* udev_rules_new(ResolveNameTiming resolve_name_timing) {
1642 assert(resolve_name_timing >= 0 && resolve_name_timing < _RESOLVE_NAME_TIMING_MAX);
1643
1644 UdevRules *rules = new(UdevRules, 1);
1645 if (!rules)
1646 return NULL;
1647
1648 *rules = (UdevRules) {
1649 .resolve_name_timing = resolve_name_timing,
1650 };
1651
1652 return rules;
1653 }
1654
1655 int udev_rules_load(UdevRules **ret_rules, ResolveNameTiming resolve_name_timing) {
1656 _cleanup_(udev_rules_freep) UdevRules *rules = NULL;
1657 _cleanup_strv_free_ char **files = NULL;
1658 int r;
1659
1660 rules = udev_rules_new(resolve_name_timing);
1661 if (!rules)
1662 return -ENOMEM;
1663
1664 r = conf_files_list_strv(&files, ".rules", NULL, 0, RULES_DIRS);
1665 if (r < 0)
1666 return log_debug_errno(r, "Failed to enumerate rules files: %m");
1667
1668 STRV_FOREACH(f, files) {
1669 r = udev_rules_parse_file(rules, *f, /* extra_checks = */ false, NULL);
1670 if (r < 0)
1671 log_debug_errno(r, "Failed to read rules file %s, ignoring: %m", *f);
1672 }
1673
1674 *ret_rules = TAKE_PTR(rules);
1675 return 0;
1676 }
1677
1678 bool udev_rules_should_reload(UdevRules *rules) {
1679 _cleanup_hashmap_free_ Hashmap *stats_by_path = NULL;
1680 int r;
1681
1682 if (!rules)
1683 return true;
1684
1685 r = config_get_stats_by_path(".rules", NULL, 0, RULES_DIRS, /* check_dropins = */ false, &stats_by_path);
1686 if (r < 0) {
1687 log_warning_errno(r, "Failed to get stats of udev rules, ignoring: %m");
1688 return true;
1689 }
1690
1691 if (!stats_by_path_equal(rules->stats_by_path, stats_by_path)) {
1692 log_debug("Udev rules need reloading");
1693 return true;
1694 }
1695
1696 return false;
1697 }
1698
1699 static bool token_match_string(UdevRuleToken *token, const char *str) {
1700 const char *value;
1701 bool match = false;
1702
1703 assert(token);
1704 assert(token->value);
1705 assert(token->type < _TK_M_MAX);
1706
1707 str = strempty(str);
1708 value = token->value;
1709
1710 switch (token->match_type) {
1711 case MATCH_TYPE_EMPTY:
1712 match = isempty(str);
1713 break;
1714 case MATCH_TYPE_SUBSYSTEM:
1715 match = STR_IN_SET(str, "subsystem", "class", "bus");
1716 break;
1717 case MATCH_TYPE_PLAIN_WITH_EMPTY:
1718 if (isempty(str)) {
1719 match = true;
1720 break;
1721 }
1722 _fallthrough_;
1723 case MATCH_TYPE_PLAIN:
1724 NULSTR_FOREACH(i, value)
1725 if (streq(i, str)) {
1726 match = true;
1727 break;
1728 }
1729 break;
1730 case MATCH_TYPE_GLOB_WITH_EMPTY:
1731 if (isempty(str)) {
1732 match = true;
1733 break;
1734 }
1735 _fallthrough_;
1736 case MATCH_TYPE_GLOB:
1737 NULSTR_FOREACH(i, value)
1738 if ((fnmatch(i, str, 0) == 0)) {
1739 match = true;
1740 break;
1741 }
1742 break;
1743 default:
1744 assert_not_reached();
1745 }
1746
1747 return token->op == (match ? OP_MATCH : OP_NOMATCH);
1748 }
1749
1750 static bool token_match_attr(UdevRuleToken *token, sd_device *dev, UdevEvent *event) {
1751 char nbuf[UDEV_NAME_SIZE], vbuf[UDEV_NAME_SIZE];
1752 const char *name, *value;
1753 bool truncated;
1754
1755 assert(token);
1756 assert(IN_SET(token->type, TK_M_ATTR, TK_M_PARENTS_ATTR));
1757 assert(dev);
1758 assert(event);
1759
1760 name = token->data;
1761
1762 switch (token->attr_subst_type) {
1763 case SUBST_TYPE_FORMAT:
1764 (void) udev_event_apply_format(event, name, nbuf, sizeof(nbuf), false, &truncated);
1765 if (truncated) {
1766 log_event_truncated(dev, token, "sysfs attribute name", name,
1767 token->type == TK_M_ATTR ? "ATTR" : "ATTRS", /* is_match = */ true);
1768 return false;
1769 }
1770
1771 name = nbuf;
1772 _fallthrough_;
1773 case SUBST_TYPE_PLAIN:
1774 if (sd_device_get_sysattr_value(dev, name, &value) < 0)
1775 return false;
1776 break;
1777 case SUBST_TYPE_SUBSYS:
1778 if (udev_resolve_subsys_kernel(name, vbuf, sizeof(vbuf), true) < 0)
1779 return false;
1780 value = vbuf;
1781 break;
1782 default:
1783 assert_not_reached();
1784 }
1785
1786 /* remove trailing whitespace, if not asked to match for it */
1787 if (token->attr_match_remove_trailing_whitespace) {
1788 if (value != vbuf) {
1789 strscpy(vbuf, sizeof(vbuf), value);
1790 value = vbuf;
1791 }
1792
1793 delete_trailing_chars(vbuf, NULL);
1794 }
1795
1796 return token_match_string(token, value);
1797 }
1798
1799 static int get_property_from_string(char *line, char **ret_key, char **ret_value) {
1800 char *key, *val;
1801 size_t len;
1802
1803 assert(line);
1804 assert(ret_key);
1805 assert(ret_value);
1806
1807 /* find key */
1808 key = skip_leading_chars(line, NULL);
1809
1810 /* comment or empty line */
1811 if (IN_SET(key[0], '#', '\0')) {
1812 *ret_key = *ret_value = NULL;
1813 return 0;
1814 }
1815
1816 /* split key/value */
1817 val = strchr(key, '=');
1818 if (!val)
1819 return -EINVAL;
1820 *val++ = '\0';
1821
1822 key = strstrip(key);
1823 if (isempty(key))
1824 return -EINVAL;
1825
1826 val = strstrip(val);
1827 if (isempty(val))
1828 return -EINVAL;
1829
1830 /* unquote */
1831 if (IN_SET(val[0], '"', '\'')) {
1832 len = strlen(val);
1833 if (len == 1 || val[len-1] != val[0])
1834 return -EINVAL;
1835 val[len-1] = '\0';
1836 val++;
1837 }
1838
1839 *ret_key = key;
1840 *ret_value = val;
1841 return 1;
1842 }
1843
1844 static int import_parent_into_properties(sd_device *dev, const char *filter) {
1845 sd_device *parent;
1846 int r;
1847
1848 assert(dev);
1849 assert(filter);
1850
1851 r = sd_device_get_parent(dev, &parent);
1852 if (r == -ENOENT)
1853 return 0;
1854 if (r < 0)
1855 return r;
1856
1857 FOREACH_DEVICE_PROPERTY(parent, key, val) {
1858 if (fnmatch(filter, key, 0) != 0)
1859 continue;
1860 r = device_add_property(dev, key, val);
1861 if (r < 0)
1862 return r;
1863 }
1864
1865 return 1;
1866 }
1867
1868 static int attr_subst_subdir(char attr[static UDEV_PATH_SIZE]) {
1869 _cleanup_closedir_ DIR *dir = NULL;
1870 char buf[UDEV_PATH_SIZE], *p;
1871 const char *tail;
1872 size_t len, size;
1873 bool truncated;
1874
1875 assert(attr);
1876
1877 tail = strstr(attr, "/*/");
1878 if (!tail)
1879 return 0;
1880
1881 len = tail - attr + 1; /* include slash at the end */
1882 tail += 2; /* include slash at the beginning */
1883
1884 p = buf;
1885 size = sizeof(buf);
1886 size -= strnpcpy_full(&p, size, attr, len, &truncated);
1887 if (truncated)
1888 return -ENOENT;
1889
1890 dir = opendir(buf);
1891 if (!dir)
1892 return -errno;
1893
1894 FOREACH_DIRENT_ALL(de, dir, break) {
1895 if (de->d_name[0] == '.')
1896 continue;
1897
1898 strscpyl_full(p, size, &truncated, de->d_name, tail, NULL);
1899 if (truncated)
1900 continue;
1901
1902 if (faccessat(dirfd(dir), p, F_OK, 0) < 0)
1903 continue;
1904
1905 strcpy(attr, buf);
1906 return 0;
1907 }
1908
1909 return -ENOENT;
1910 }
1911
1912 static size_t udev_replace_ifname(char *str) {
1913 size_t replaced = 0;
1914
1915 assert(str);
1916
1917 /* See ifname_valid_full(). */
1918
1919 for (char *p = str; *p != '\0'; p++)
1920 if (!ifname_valid_char(*p)) {
1921 *p = '_';
1922 replaced++;
1923 }
1924
1925 return replaced;
1926 }
1927
1928 static int udev_rule_apply_token_to_event(
1929 UdevRuleToken *token,
1930 sd_device *dev,
1931 UdevEvent *event) {
1932
1933 int r;
1934
1935 assert(token);
1936 assert(dev);
1937 assert(event);
1938
1939 /* This returns the following values:
1940 * 0 on the current token does not match the event,
1941 * 1 on the current token matches the event, and
1942 * negative errno on some critical errors. */
1943
1944 switch (token->type) {
1945 case TK_M_ACTION: {
1946 sd_device_action_t a;
1947
1948 r = sd_device_get_action(dev, &a);
1949 if (r < 0)
1950 return log_event_error_errno(dev, token, r, "Failed to get uevent action type: %m");
1951
1952 return token_match_string(token, device_action_to_string(a));
1953 }
1954 case TK_M_DEVPATH: {
1955 const char *val;
1956
1957 r = sd_device_get_devpath(dev, &val);
1958 if (r < 0)
1959 return log_event_error_errno(dev, token, r, "Failed to get devpath: %m");
1960
1961 return token_match_string(token, val);
1962 }
1963 case TK_M_KERNEL:
1964 case TK_M_PARENTS_KERNEL: {
1965 const char *val;
1966
1967 r = sd_device_get_sysname(dev, &val);
1968 if (r < 0)
1969 return log_event_error_errno(dev, token, r, "Failed to get sysname: %m");
1970
1971 return token_match_string(token, val);
1972 }
1973 case TK_M_DEVLINK:
1974 FOREACH_DEVICE_DEVLINK(dev, val)
1975 if (token_match_string(token, strempty(startswith(val, "/dev/"))) == (token->op == OP_MATCH))
1976 return token->op == OP_MATCH;
1977 return token->op == OP_NOMATCH;
1978 case TK_M_NAME:
1979 return token_match_string(token, event->name);
1980 case TK_M_ENV: {
1981 const char *val = NULL;
1982
1983 (void) device_get_property_value_with_fallback(dev, token->data, event->worker ? event->worker->properties : NULL, &val);
1984
1985 return token_match_string(token, val);
1986 }
1987 case TK_M_CONST: {
1988 const char *val, *k = token->data;
1989
1990 if (streq(k, "arch"))
1991 val = architecture_to_string(uname_architecture());
1992 else if (streq(k, "virt"))
1993 val = virtualization_to_string(detect_virtualization());
1994 else if (streq(k, "cvm"))
1995 val = confidential_virtualization_to_string(detect_confidential_virtualization());
1996 else
1997 assert_not_reached();
1998 return token_match_string(token, val);
1999 }
2000 case TK_M_TAG:
2001 case TK_M_PARENTS_TAG:
2002 FOREACH_DEVICE_CURRENT_TAG(dev, val)
2003 if (token_match_string(token, val) == (token->op == OP_MATCH))
2004 return token->op == OP_MATCH;
2005 return token->op == OP_NOMATCH;
2006 case TK_M_SUBSYSTEM:
2007 case TK_M_PARENTS_SUBSYSTEM: {
2008 const char *val;
2009
2010 r = sd_device_get_subsystem(dev, &val);
2011 if (r == -ENOENT)
2012 val = NULL;
2013 else if (r < 0)
2014 return log_event_error_errno(dev, token, r, "Failed to get subsystem: %m");
2015
2016 return token_match_string(token, val);
2017 }
2018 case TK_M_DRIVER:
2019 case TK_M_PARENTS_DRIVER: {
2020 const char *val;
2021
2022 r = sd_device_get_driver(dev, &val);
2023 if (r == -ENOENT)
2024 val = NULL;
2025 else if (r < 0)
2026 return log_event_error_errno(dev, token, r, "Failed to get driver: %m");
2027
2028 return token_match_string(token, val);
2029 }
2030 case TK_M_ATTR:
2031 case TK_M_PARENTS_ATTR:
2032 return token_match_attr(token, dev, event);
2033 case TK_M_SYSCTL: {
2034 _cleanup_free_ char *value = NULL;
2035 char buf[UDEV_PATH_SIZE];
2036 bool truncated;
2037
2038 (void) udev_event_apply_format(event, token->data, buf, sizeof(buf), false, &truncated);
2039 if (truncated) {
2040 log_event_truncated(dev, token, "sysctl entry name", token->data, "SYSCTL", /* is_match = */ true);
2041 return false;
2042 }
2043
2044 r = sysctl_read(sysctl_normalize(buf), &value);
2045 if (r < 0 && r != -ENOENT)
2046 return log_event_error_errno(dev, token, r, "Failed to read sysctl '%s': %m", buf);
2047
2048 return token_match_string(token, strstrip(value));
2049 }
2050 case TK_M_TEST: {
2051 mode_t mode = PTR_TO_MODE(token->data);
2052 char buf[UDEV_PATH_SIZE];
2053 struct stat statbuf;
2054 bool match, truncated;
2055
2056 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2057 if (truncated) {
2058 log_event_truncated(dev, token, "file name", token->value, "TEST", /* is_match = */ true);
2059 return false;
2060 }
2061
2062 if (!path_is_absolute(buf) &&
2063 udev_resolve_subsys_kernel(buf, buf, sizeof(buf), false) < 0) {
2064 char tmp[UDEV_PATH_SIZE];
2065 const char *val;
2066
2067 r = sd_device_get_syspath(dev, &val);
2068 if (r < 0)
2069 return log_event_error_errno(dev, token, r, "Failed to get syspath: %m");
2070
2071 strscpy_full(tmp, sizeof(tmp), buf, &truncated);
2072 assert(!truncated);
2073 strscpyl_full(buf, sizeof(buf), &truncated, val, "/", tmp, NULL);
2074 if (truncated)
2075 return false;
2076 }
2077
2078 r = attr_subst_subdir(buf);
2079 if (r == -ENOENT)
2080 return token->op == OP_NOMATCH;
2081 if (r < 0)
2082 return log_event_error_errno(dev, token, r, "Failed to test for the existence of '%s': %m", buf);
2083
2084 if (stat(buf, &statbuf) < 0)
2085 return token->op == OP_NOMATCH;
2086
2087 if (mode == MODE_INVALID)
2088 return token->op == OP_MATCH;
2089
2090 match = (statbuf.st_mode & mode) > 0;
2091 return token->op == (match ? OP_MATCH : OP_NOMATCH);
2092 }
2093 case TK_M_PROGRAM: {
2094 char buf[UDEV_LINE_SIZE], result[UDEV_LINE_SIZE];
2095 bool truncated;
2096 size_t count;
2097
2098 event->program_result = mfree(event->program_result);
2099 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2100 if (truncated) {
2101 log_event_truncated(dev, token, "command", token->value, "PROGRAM", /* is_match = */ true);
2102 return false;
2103 }
2104
2105 log_event_debug(dev, token, "Running PROGRAM '%s'", buf);
2106
2107 r = udev_event_spawn(event, /* accept_failure = */ true, buf, result, sizeof(result), NULL);
2108 if (r != 0) {
2109 if (r < 0)
2110 log_event_warning_errno(dev, token, r, "Failed to execute \"%s\": %m", buf);
2111 else /* returned value is positive when program fails */
2112 log_event_debug(dev, token, "Command \"%s\" returned %d (error)", buf, r);
2113 return token->op == OP_NOMATCH;
2114 }
2115
2116 delete_trailing_chars(result, "\n");
2117 count = udev_replace_chars(result, UDEV_ALLOWED_CHARS_INPUT);
2118 if (count > 0)
2119 log_event_debug(dev, token,
2120 "Replaced %zu character(s) in result of \"%s\"",
2121 count, buf);
2122
2123 event->program_result = strdup(result);
2124 return token->op == OP_MATCH;
2125 }
2126 case TK_M_IMPORT_FILE: {
2127 _cleanup_fclose_ FILE *f = NULL;
2128 char buf[UDEV_PATH_SIZE];
2129 bool truncated;
2130
2131 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2132 if (truncated) {
2133 log_event_truncated(dev, token, "file name to be imported", token->value, "IMPORT", /* is_match = */ true);
2134 return false;
2135 }
2136
2137 log_event_debug(dev, token, "Importing properties from '%s'", buf);
2138
2139 f = fopen(buf, "re");
2140 if (!f) {
2141 if (errno != ENOENT)
2142 return log_event_error_errno(dev, token, errno, "Failed to open '%s': %m", buf);
2143 return token->op == OP_NOMATCH;
2144 }
2145
2146 for (;;) {
2147 _cleanup_free_ char *line = NULL;
2148 char *key, *value;
2149
2150 r = read_line(f, LONG_LINE_MAX, &line);
2151 if (r < 0) {
2152 log_event_debug_errno(dev, token, r, "Failed to read '%s', ignoring: %m", buf);
2153 return token->op == OP_NOMATCH;
2154 }
2155 if (r == 0)
2156 break;
2157
2158 r = get_property_from_string(line, &key, &value);
2159 if (r < 0) {
2160 log_event_debug_errno(dev, token, r,
2161 "Failed to parse key and value from '%s', ignoring: %m",
2162 line);
2163 continue;
2164 }
2165 if (r == 0)
2166 continue;
2167
2168 r = device_add_property(dev, key, value);
2169 if (r < 0)
2170 return log_event_error_errno(dev, token, r,
2171 "Failed to add property %s=%s: %m",
2172 key, value);
2173 }
2174
2175 return token->op == OP_MATCH;
2176 }
2177 case TK_M_IMPORT_PROGRAM: {
2178 _cleanup_strv_free_ char **lines = NULL;
2179 char buf[UDEV_LINE_SIZE], result[UDEV_LINE_SIZE];
2180 bool truncated;
2181
2182 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2183 if (truncated) {
2184 log_event_truncated(dev, token, "command", token->value, "IMPORT", /* is_match = */ true);
2185 return false;
2186 }
2187
2188 log_event_debug(dev, token, "Importing properties from results of '%s'", buf);
2189
2190 r = udev_event_spawn(event, /* accept_failure = */ true, buf, result, sizeof result, &truncated);
2191 if (r != 0) {
2192 if (r < 0)
2193 log_event_warning_errno(dev, token, r, "Failed to execute '%s', ignoring: %m", buf);
2194 else /* returned value is positive when program fails */
2195 log_event_debug(dev, token, "Command \"%s\" returned %d (error), ignoring", buf, r);
2196 return token->op == OP_NOMATCH;
2197 }
2198
2199 if (truncated) {
2200 bool found = false;
2201
2202 /* Drop the last line. */
2203 for (char *p = PTR_SUB1(buf + strlen(buf), buf); p; p = PTR_SUB1(p, buf))
2204 if (strchr(NEWLINE, *p)) {
2205 *p = '\0';
2206 found = true;
2207 } else if (found)
2208 break;
2209 }
2210
2211 r = strv_split_newlines_full(&lines, result, EXTRACT_RETAIN_ESCAPE);
2212 if (r == -ENOMEM)
2213 return log_oom();
2214 if (r < 0) {
2215 log_event_warning_errno(dev, token, r,
2216 "Failed to extract lines from result of command \"%s\", ignoring: %m", buf);
2217 return false;
2218 }
2219
2220 STRV_FOREACH(line, lines) {
2221 char *key, *value;
2222
2223 r = get_property_from_string(*line, &key, &value);
2224 if (r < 0) {
2225 log_event_debug_errno(dev, token, r,
2226 "Failed to parse key and value from '%s', ignoring: %m",
2227 *line);
2228 continue;
2229 }
2230 if (r == 0)
2231 continue;
2232
2233 r = device_add_property(dev, key, value);
2234 if (r < 0)
2235 return log_event_error_errno(dev, token, r,
2236 "Failed to add property %s=%s: %m",
2237 key, value);
2238 }
2239
2240 return token->op == OP_MATCH;
2241 }
2242 case TK_M_IMPORT_BUILTIN: {
2243 UdevBuiltinCommand cmd = PTR_TO_UDEV_BUILTIN_CMD(token->data);
2244 assert(cmd >= 0 && cmd < _UDEV_BUILTIN_MAX);
2245 unsigned mask = 1U << (int) cmd;
2246 char buf[UDEV_LINE_SIZE];
2247 bool truncated;
2248
2249 if (udev_builtin_run_once(cmd)) {
2250 /* check if we ran already */
2251 if (event->builtin_run & mask) {
2252 log_event_debug(dev, token, "Skipping builtin '%s' in IMPORT key",
2253 udev_builtin_name(cmd));
2254 /* return the result from earlier run */
2255 return token->op == (event->builtin_ret & mask ? OP_NOMATCH : OP_MATCH);
2256 }
2257 /* mark as ran */
2258 event->builtin_run |= mask;
2259 }
2260
2261 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2262 if (truncated) {
2263 log_event_truncated(dev, token, "builtin command", token->value, "IMPORT", /* is_match = */ true);
2264 return false;
2265 }
2266
2267 log_event_debug(dev, token, "Importing properties from results of builtin command '%s'", buf);
2268
2269 r = udev_builtin_run(event, cmd, buf, false);
2270 if (r < 0) {
2271 /* remember failure */
2272 log_event_debug_errno(dev, token, r, "Failed to run builtin '%s': %m", buf);
2273 event->builtin_ret |= mask;
2274 }
2275 return token->op == (r >= 0 ? OP_MATCH : OP_NOMATCH);
2276 }
2277 case TK_M_IMPORT_DB: {
2278 const char *val;
2279
2280 if (!event->dev_db_clone)
2281 return token->op == OP_NOMATCH;
2282 r = sd_device_get_property_value(event->dev_db_clone, token->value, &val);
2283 if (r == -ENOENT)
2284 return token->op == OP_NOMATCH;
2285 if (r < 0)
2286 return log_event_error_errno(dev, token, r,
2287 "Failed to get property '%s' from database: %m",
2288 token->value);
2289
2290 r = device_add_property(dev, token->value, val);
2291 if (r < 0)
2292 return log_event_error_errno(dev, token, r, "Failed to add property '%s=%s': %m",
2293 token->value, val);
2294 return token->op == OP_MATCH;
2295 }
2296 case TK_M_IMPORT_CMDLINE: {
2297 _cleanup_free_ char *value = NULL;
2298
2299 r = proc_cmdline_get_key(token->value, PROC_CMDLINE_VALUE_OPTIONAL|PROC_CMDLINE_IGNORE_EFI_OPTIONS, &value);
2300 if (r < 0)
2301 return log_event_error_errno(dev, token, r,
2302 "Failed to read '%s' option from /proc/cmdline: %m",
2303 token->value);
2304 if (r == 0)
2305 return token->op == OP_NOMATCH;
2306
2307 r = device_add_property(dev, token->value, value ?: "1");
2308 if (r < 0)
2309 return log_event_error_errno(dev, token, r, "Failed to add property '%s=%s': %m",
2310 token->value, value ?: "1");
2311 return token->op == OP_MATCH;
2312 }
2313 case TK_M_IMPORT_PARENT: {
2314 char buf[UDEV_PATH_SIZE];
2315 bool truncated;
2316
2317 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2318 if (truncated) {
2319 log_event_truncated(dev, token, "property name", token->value, "IMPORT", /* is_match = */ true);
2320 return false;
2321 }
2322
2323 r = import_parent_into_properties(dev, buf);
2324 if (r < 0)
2325 return log_event_error_errno(dev, token, r,
2326 "Failed to import properties '%s' from parent: %m",
2327 buf);
2328 return token->op == (r > 0 ? OP_MATCH : OP_NOMATCH);
2329 }
2330 case TK_M_RESULT:
2331 return token_match_string(token, event->program_result);
2332 case TK_A_OPTIONS_STRING_ESCAPE_NONE:
2333 event->esc = ESCAPE_NONE;
2334 break;
2335 case TK_A_OPTIONS_STRING_ESCAPE_REPLACE:
2336 event->esc = ESCAPE_REPLACE;
2337 break;
2338 case TK_A_OPTIONS_DB_PERSIST:
2339 device_set_db_persist(dev);
2340 break;
2341 case TK_A_OPTIONS_INOTIFY_WATCH:
2342 if (event->inotify_watch_final)
2343 break;
2344 if (token->op == OP_ASSIGN_FINAL)
2345 event->inotify_watch_final = true;
2346
2347 event->inotify_watch = token->data;
2348 break;
2349 case TK_A_OPTIONS_DEVLINK_PRIORITY:
2350 device_set_devlink_priority(dev, PTR_TO_INT(token->data));
2351 break;
2352 case TK_A_OPTIONS_LOG_LEVEL: {
2353 int level = PTR_TO_INT(token->data);
2354
2355 if (level < 0)
2356 level = event->default_log_level;
2357
2358 log_set_max_level(level);
2359
2360 if (level == LOG_DEBUG && !event->log_level_was_debug) {
2361 /* The log level becomes LOG_DEBUG at first time. Let's log basic information. */
2362 log_device_uevent(dev, "The log level is changed to 'debug' while processing device");
2363 event->log_level_was_debug = true;
2364 }
2365
2366 break;
2367 }
2368 case TK_A_OWNER: {
2369 char owner[UDEV_NAME_SIZE];
2370 const char *ow = owner;
2371 bool truncated;
2372
2373 if (event->owner_final)
2374 break;
2375 if (token->op == OP_ASSIGN_FINAL)
2376 event->owner_final = true;
2377
2378 (void) udev_event_apply_format(event, token->value, owner, sizeof(owner), false, &truncated);
2379 if (truncated) {
2380 log_event_truncated(dev, token, "user name", token->value, "OWNER", /* is_match = */ false);
2381 break;
2382 }
2383
2384 r = get_user_creds(&ow, &event->uid, NULL, NULL, NULL, USER_CREDS_ALLOW_MISSING);
2385 if (r < 0)
2386 log_unknown_owner(dev, token->rule_line, r, "user", owner);
2387 else
2388 log_event_debug(dev, token, "OWNER %s(%u)", owner, event->uid);
2389 break;
2390 }
2391 case TK_A_GROUP: {
2392 char group[UDEV_NAME_SIZE];
2393 const char *gr = group;
2394 bool truncated;
2395
2396 if (event->group_final)
2397 break;
2398 if (token->op == OP_ASSIGN_FINAL)
2399 event->group_final = true;
2400
2401 (void) udev_event_apply_format(event, token->value, group, sizeof(group), false, &truncated);
2402 if (truncated) {
2403 log_event_truncated(dev, token, "group name", token->value, "GROUP", /* is_match = */ false);
2404 break;
2405 }
2406
2407 r = get_group_creds(&gr, &event->gid, USER_CREDS_ALLOW_MISSING);
2408 if (r < 0)
2409 log_unknown_owner(dev, token->rule_line, r, "group", group);
2410 else
2411 log_event_debug(dev, token, "GROUP %s(%u)", group, event->gid);
2412 break;
2413 }
2414 case TK_A_MODE: {
2415 char mode_str[UDEV_NAME_SIZE];
2416 bool truncated;
2417
2418 if (event->mode_final)
2419 break;
2420 if (token->op == OP_ASSIGN_FINAL)
2421 event->mode_final = true;
2422
2423 (void) udev_event_apply_format(event, token->value, mode_str, sizeof(mode_str), false, &truncated);
2424 if (truncated) {
2425 log_event_truncated(dev, token, "mode", token->value, "MODE", /* is_match = */ false);
2426 break;
2427 }
2428
2429 r = parse_mode(mode_str, &event->mode);
2430 if (r < 0)
2431 log_event_error_errno(dev, token, r, "Failed to parse mode '%s', ignoring: %m", mode_str);
2432 else
2433 log_event_debug(dev, token, "MODE %#o", event->mode);
2434 break;
2435 }
2436 case TK_A_OWNER_ID:
2437 if (event->owner_final)
2438 break;
2439 if (token->op == OP_ASSIGN_FINAL)
2440 event->owner_final = true;
2441 if (!token->data)
2442 break;
2443 event->uid = PTR_TO_UID(token->data);
2444 log_event_debug(dev, token, "OWNER %u", event->uid);
2445 break;
2446 case TK_A_GROUP_ID:
2447 if (event->group_final)
2448 break;
2449 if (token->op == OP_ASSIGN_FINAL)
2450 event->group_final = true;
2451 if (!token->data)
2452 break;
2453 event->gid = PTR_TO_GID(token->data);
2454 log_event_debug(dev, token, "GROUP %u", event->gid);
2455 break;
2456 case TK_A_MODE_ID:
2457 if (event->mode_final)
2458 break;
2459 if (token->op == OP_ASSIGN_FINAL)
2460 event->mode_final = true;
2461 if (!token->data)
2462 break;
2463 event->mode = PTR_TO_MODE(token->data);
2464 log_event_debug(dev, token, "MODE %#o", event->mode);
2465 break;
2466 case TK_A_SECLABEL: {
2467 _cleanup_free_ char *name = NULL, *label = NULL;
2468 char label_str[UDEV_LINE_SIZE] = {};
2469 bool truncated;
2470
2471 name = strdup(token->data);
2472 if (!name)
2473 return log_oom();
2474
2475 (void) udev_event_apply_format(event, token->value, label_str, sizeof(label_str), false, &truncated);
2476 if (truncated) {
2477 log_event_truncated(dev, token, "security label", token->value, "SECLABEL", /* is_match = */ false);
2478 break;
2479 }
2480
2481 if (!isempty(label_str))
2482 label = strdup(label_str);
2483 else
2484 label = strdup(token->value);
2485 if (!label)
2486 return log_oom();
2487
2488 if (token->op == OP_ASSIGN)
2489 ordered_hashmap_clear_free_free(event->seclabel_list);
2490
2491 r = ordered_hashmap_ensure_put(&event->seclabel_list, NULL, name, label);
2492 if (r == -ENOMEM)
2493 return log_oom();
2494 if (r < 0)
2495 return log_event_error_errno(dev, token, r, "Failed to store SECLABEL{%s}='%s': %m", name, label);
2496
2497 log_event_debug(dev, token, "SECLABEL{%s}='%s'", name, label);
2498
2499 TAKE_PTR(name);
2500 TAKE_PTR(label);
2501 break;
2502 }
2503 case TK_A_ENV: {
2504 const char *val, *name = token->data;
2505 char value_new[UDEV_NAME_SIZE], *p = value_new;
2506 size_t count, l = sizeof(value_new);
2507 bool truncated;
2508
2509 if (isempty(token->value)) {
2510 if (token->op == OP_ADD)
2511 break;
2512 r = device_add_property(dev, name, NULL);
2513 if (r < 0)
2514 return log_event_error_errno(dev, token, r, "Failed to remove property '%s': %m", name);
2515 break;
2516 }
2517
2518 if (token->op == OP_ADD &&
2519 device_get_property_value_with_fallback(dev, name, event->worker ? event->worker->properties : NULL, &val) >= 0) {
2520 l = strpcpyl_full(&p, l, &truncated, val, " ", NULL);
2521 if (truncated) {
2522 log_event_warning(dev, token,
2523 "The buffer for the property '%s' is full, "
2524 "refusing to append the new value '%s'.", name, token->value);
2525 break;
2526 }
2527 }
2528
2529 (void) udev_event_apply_format(event, token->value, p, l, false, &truncated);
2530 if (truncated) {
2531 _cleanup_free_ char *key_with_name = strjoin("ENV{", name, "}");
2532 log_event_truncated(dev, token, "property value", token->value,
2533 key_with_name ?: "ENV", /* is_match = */ false);
2534 break;
2535 }
2536
2537 if (event->esc == ESCAPE_REPLACE) {
2538 count = udev_replace_chars(p, NULL);
2539 if (count > 0)
2540 log_event_debug(dev, token,
2541 "Replaced %zu slash(es) from result of ENV{%s}%s=\"%s\"",
2542 count, name, token->op == OP_ADD ? "+" : "", token->value);
2543 }
2544
2545 r = device_add_property(dev, name, value_new);
2546 if (r < 0)
2547 return log_event_error_errno(dev, token, r, "Failed to add property '%s=%s': %m", name, value_new);
2548 break;
2549 }
2550 case TK_A_TAG: {
2551 char buf[UDEV_PATH_SIZE];
2552 bool truncated;
2553
2554 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2555 if (truncated) {
2556 log_event_truncated(dev, token, "tag name", token->value, "TAG", /* is_match = */ false);
2557 break;
2558 }
2559
2560 if (token->op == OP_ASSIGN)
2561 device_cleanup_tags(dev);
2562
2563 if (token->op == OP_REMOVE)
2564 device_remove_tag(dev, buf);
2565 else {
2566 r = device_add_tag(dev, buf, true);
2567 if (r == -ENOMEM)
2568 return log_oom();
2569 if (r < 0)
2570 log_event_warning_errno(dev, token, r, "Failed to add tag '%s', ignoring: %m", buf);
2571 }
2572 break;
2573 }
2574 case TK_A_NAME: {
2575 char buf[UDEV_PATH_SIZE];
2576 bool truncated;
2577 size_t count;
2578
2579 if (event->name_final)
2580 break;
2581 if (token->op == OP_ASSIGN_FINAL)
2582 event->name_final = true;
2583
2584 if (sd_device_get_ifindex(dev, NULL) < 0) {
2585 log_event_error(dev, token,
2586 "Only network interfaces can be renamed, ignoring NAME=\"%s\".",
2587 token->value);
2588 break;
2589 }
2590
2591 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2592 if (truncated) {
2593 log_event_truncated(dev, token, "network interface name", token->value, "NAME", /* is_match = */ false);
2594 break;
2595 }
2596
2597 if (IN_SET(event->esc, ESCAPE_UNSET, ESCAPE_REPLACE)) {
2598 if (naming_scheme_has(NAMING_REPLACE_STRICTLY))
2599 count = udev_replace_ifname(buf);
2600 else
2601 count = udev_replace_chars(buf, "/");
2602 if (count > 0)
2603 log_event_debug(dev, token,
2604 "Replaced %zu character(s) from result of NAME=\"%s\"",
2605 count, token->value);
2606 }
2607 r = free_and_strdup_warn(&event->name, buf);
2608 if (r < 0)
2609 return r;
2610
2611 log_event_debug(dev, token, "NAME '%s'", event->name);
2612 break;
2613 }
2614 case TK_A_DEVLINK: {
2615 char buf[UDEV_PATH_SIZE];
2616 bool truncated;
2617 size_t count;
2618
2619 if (event->devlink_final)
2620 break;
2621 if (sd_device_get_devnum(dev, NULL) < 0)
2622 break;
2623 if (token->op == OP_ASSIGN_FINAL)
2624 event->devlink_final = true;
2625 if (IN_SET(token->op, OP_ASSIGN, OP_ASSIGN_FINAL))
2626 device_cleanup_devlinks(dev);
2627
2628 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf),
2629 /* replace_whitespace = */ event->esc != ESCAPE_NONE, &truncated);
2630 if (truncated) {
2631 log_event_truncated(dev, token, "symbolic link path", token->value, "SYMLINK", /* is_match = */ false);
2632 break;
2633 }
2634
2635 /* By default or string_escape=none, allow multiple symlinks separated by spaces. */
2636 if (event->esc == ESCAPE_UNSET)
2637 count = udev_replace_chars(buf, /* allow = */ "/ ");
2638 else if (event->esc == ESCAPE_REPLACE)
2639 count = udev_replace_chars(buf, /* allow = */ "/");
2640 else
2641 count = 0;
2642 if (count > 0)
2643 log_event_debug(dev, token,
2644 "Replaced %zu character(s) from result of SYMLINK=\"%s\"",
2645 count, token->value);
2646
2647 for (const char *p = buf;;) {
2648 _cleanup_free_ char *path = NULL;
2649
2650 r = extract_first_word(&p, &path, NULL, EXTRACT_RETAIN_ESCAPE);
2651 if (r == -ENOMEM)
2652 return log_oom();
2653 if (r < 0) {
2654 log_warning_errno(r, "Failed to extract first path in SYMLINK=, ignoring: %m");
2655 break;
2656 }
2657 if (r == 0)
2658 break;
2659
2660 if (token->op == OP_REMOVE) {
2661 r = device_remove_devlink(dev, path);
2662 if (r == -ENOMEM)
2663 return log_oom();
2664 if (r < 0)
2665 log_event_warning_errno(dev, token, r, "Failed to remove devlink '%s', ignoring: %m", path);
2666 else if (r > 0)
2667 log_event_debug(dev, token, "Dropped SYMLINK '%s'", path);
2668 } else {
2669 r = device_add_devlink(dev, path);
2670 if (r == -ENOMEM)
2671 return log_oom();
2672 if (r < 0)
2673 log_event_warning_errno(dev, token, r, "Failed to add devlink '%s', ignoring: %m", path);
2674 else if (r > 0)
2675 log_event_debug(dev, token, "Added SYMLINK '%s'", path);
2676 }
2677 }
2678 break;
2679 }
2680 case TK_A_ATTR: {
2681 char buf[UDEV_PATH_SIZE], value[UDEV_NAME_SIZE];
2682 const char *val, *key_name = token->data;
2683 bool truncated;
2684
2685 if (udev_resolve_subsys_kernel(key_name, buf, sizeof(buf), false) < 0 &&
2686 sd_device_get_syspath(dev, &val) >= 0) {
2687 strscpyl_full(buf, sizeof(buf), &truncated, val, "/", key_name, NULL);
2688 if (truncated) {
2689 log_event_warning(dev, token,
2690 "The path to the attribute '%s/%s' is too long, refusing to set the attribute.",
2691 val, key_name);
2692 break;
2693 }
2694 }
2695
2696 r = attr_subst_subdir(buf);
2697 if (r < 0) {
2698 log_event_error_errno(dev, token, r, "Could not find file matches '%s', ignoring: %m", buf);
2699 break;
2700 }
2701 (void) udev_event_apply_format(event, token->value, value, sizeof(value), false, &truncated);
2702 if (truncated) {
2703 log_event_truncated(dev, token, "attribute value", token->value, "ATTR", /* is_match = */ false);
2704 break;
2705 }
2706
2707 log_event_debug(dev, token, "ATTR '%s' writing '%s'", buf, value);
2708 r = write_string_file(buf, value,
2709 WRITE_STRING_FILE_VERIFY_ON_FAILURE |
2710 WRITE_STRING_FILE_DISABLE_BUFFER |
2711 WRITE_STRING_FILE_AVOID_NEWLINE |
2712 WRITE_STRING_FILE_VERIFY_IGNORE_NEWLINE);
2713 if (r < 0)
2714 log_event_error_errno(dev, token, r, "Failed to write ATTR{%s}, ignoring: %m", buf);
2715 break;
2716 }
2717 case TK_A_SYSCTL: {
2718 char buf[UDEV_PATH_SIZE], value[UDEV_NAME_SIZE];
2719 bool truncated;
2720
2721 (void) udev_event_apply_format(event, token->data, buf, sizeof(buf), false, &truncated);
2722 if (truncated) {
2723 log_event_truncated(dev, token, "sysctl entry name", token->data, "SYSCTL", /* is_match = */ false);
2724 break;
2725 }
2726
2727 (void) udev_event_apply_format(event, token->value, value, sizeof(value), false, &truncated);
2728 if (truncated) {
2729 _cleanup_free_ char *key_with_name = strjoin("SYSCTL{", buf, "}");
2730 log_event_truncated(dev, token, "sysctl value", token->value,
2731 key_with_name ?: "SYSCTL", /* is_match = */ false);
2732 break;
2733 }
2734
2735 sysctl_normalize(buf);
2736 log_event_debug(dev, token, "SYSCTL '%s' writing '%s'", buf, value);
2737 r = sysctl_write(buf, value);
2738 if (r < 0)
2739 log_event_error_errno(dev, token, r, "Failed to write SYSCTL{%s}='%s', ignoring: %m", buf, value);
2740 break;
2741 }
2742 case TK_A_RUN_BUILTIN:
2743 case TK_A_RUN_PROGRAM: {
2744 _cleanup_free_ char *cmd = NULL;
2745 char buf[UDEV_LINE_SIZE];
2746 bool truncated;
2747
2748 if (event->run_final)
2749 break;
2750 if (token->op == OP_ASSIGN_FINAL)
2751 event->run_final = true;
2752
2753 if (IN_SET(token->op, OP_ASSIGN, OP_ASSIGN_FINAL))
2754 ordered_hashmap_clear_free_key(event->run_list);
2755
2756 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2757 if (truncated) {
2758 log_event_truncated(dev, token, "command", token->value,
2759 token->type == TK_A_RUN_BUILTIN ? "RUN{builtin}" : "RUN{program}",
2760 /* is_match = */ false);
2761 break;
2762 }
2763
2764 cmd = strdup(buf);
2765 if (!cmd)
2766 return log_oom();
2767
2768 r = ordered_hashmap_ensure_put(&event->run_list, NULL, cmd, token->data);
2769 if (r == -ENOMEM)
2770 return log_oom();
2771 if (r < 0)
2772 return log_event_error_errno(dev, token, r, "Failed to store command '%s': %m", cmd);
2773
2774 TAKE_PTR(cmd);
2775
2776 log_event_debug(dev, token, "RUN '%s'", token->value);
2777 break;
2778 }
2779 case TK_A_OPTIONS_STATIC_NODE:
2780 /* do nothing for events. */
2781 break;
2782 default:
2783 assert_not_reached();
2784 }
2785
2786 return true;
2787 }
2788
2789 static bool token_is_for_parents(UdevRuleToken *token) {
2790 return token->type >= TK_M_PARENTS_KERNEL && token->type <= TK_M_PARENTS_TAG;
2791 }
2792
2793 static int udev_rule_apply_parent_token_to_event(UdevRuleToken *head_token, UdevEvent *event) {
2794 int r;
2795
2796 assert(head_token);
2797 assert(event);
2798
2799 event->dev_parent = ASSERT_PTR(event->dev);
2800
2801 for (;;) {
2802 LIST_FOREACH(tokens, token, head_token) {
2803 if (!token_is_for_parents(token))
2804 return true; /* All parent tokens match. */
2805
2806 r = udev_rule_apply_token_to_event(token, event->dev_parent, event);
2807 if (r < 0)
2808 return r;
2809 if (r == 0)
2810 break;
2811 }
2812 if (r > 0)
2813 /* All parent tokens match, and no more token (except for GOTO) in the line. */
2814 return true;
2815
2816 if (sd_device_get_parent(event->dev_parent, &event->dev_parent) < 0) {
2817 event->dev_parent = NULL;
2818 return false;
2819 }
2820 }
2821 }
2822
2823 static int udev_rule_apply_line_to_event(
2824 UdevRuleLine *line,
2825 UdevEvent *event,
2826 UdevRuleLine **next_line) {
2827
2828 UdevRuleLineType mask = LINE_HAS_GOTO | LINE_UPDATE_SOMETHING;
2829 bool parents_done = false;
2830 sd_device_action_t action;
2831 int r;
2832
2833 assert(line);
2834 assert(event);
2835 assert(next_line);
2836
2837 r = sd_device_get_action(event->dev, &action);
2838 if (r < 0)
2839 return r;
2840
2841 if (action != SD_DEVICE_REMOVE) {
2842 if (sd_device_get_devnum(event->dev, NULL) >= 0)
2843 mask |= LINE_HAS_DEVLINK;
2844
2845 if (sd_device_get_ifindex(event->dev, NULL) >= 0)
2846 mask |= LINE_HAS_NAME;
2847 }
2848
2849 if ((line->type & mask) == 0)
2850 return 0;
2851
2852 event->esc = ESCAPE_UNSET;
2853
2854 DEVICE_TRACE_POINT(rules_apply_line, event->dev, line->rule_file->filename, line->line_number);
2855
2856 LIST_FOREACH(tokens, token, line->tokens) {
2857 if (token_is_for_parents(token)) {
2858 if (parents_done)
2859 continue;
2860
2861 r = udev_rule_apply_parent_token_to_event(token, event);
2862 if (r <= 0)
2863 return r;
2864
2865 parents_done = true;
2866 continue;
2867 }
2868
2869 r = udev_rule_apply_token_to_event(token, event->dev, event);
2870 if (r <= 0)
2871 return r;
2872 }
2873
2874 if (line->goto_line)
2875 *next_line = line->goto_line; /* update next_line only when the line has GOTO token. */
2876
2877 return 0;
2878 }
2879
2880 int udev_rules_apply_to_event(UdevRules *rules, UdevEvent *event) {
2881 int r;
2882
2883 assert(rules);
2884 assert(event);
2885
2886 LIST_FOREACH(rule_files, file, rules->rule_files)
2887 LIST_FOREACH_WITH_NEXT(rule_lines, line, next_line, file->rule_lines) {
2888 r = udev_rule_apply_line_to_event(line, event, &next_line);
2889 if (r < 0)
2890 return r;
2891 }
2892
2893 return 0;
2894 }
2895
2896 static int udev_rule_line_apply_static_dev_perms(UdevRuleLine *rule_line) {
2897 _cleanup_strv_free_ char **tags = NULL;
2898 uid_t uid = UID_INVALID;
2899 gid_t gid = GID_INVALID;
2900 mode_t mode = MODE_INVALID;
2901 int r;
2902
2903 assert(rule_line);
2904
2905 if (!FLAGS_SET(rule_line->type, LINE_HAS_STATIC_NODE))
2906 return 0;
2907
2908 LIST_FOREACH(tokens, token, rule_line->tokens)
2909 if (token->type == TK_A_OWNER_ID)
2910 uid = PTR_TO_UID(token->data);
2911 else if (token->type == TK_A_GROUP_ID)
2912 gid = PTR_TO_GID(token->data);
2913 else if (token->type == TK_A_MODE_ID)
2914 mode = PTR_TO_MODE(token->data);
2915 else if (token->type == TK_A_TAG) {
2916 r = strv_extend(&tags, token->value);
2917 if (r < 0)
2918 return log_oom();
2919 } else if (token->type == TK_A_OPTIONS_STATIC_NODE) {
2920 r = static_node_apply_permissions(token->value, mode, uid, gid, tags);
2921 if (r < 0)
2922 return r;
2923 }
2924
2925 return 0;
2926 }
2927
2928 int udev_rules_apply_static_dev_perms(UdevRules *rules) {
2929 int r;
2930
2931 assert(rules);
2932
2933 LIST_FOREACH(rule_files, file, rules->rule_files)
2934 LIST_FOREACH(rule_lines, line, file->rule_lines) {
2935 r = udev_rule_line_apply_static_dev_perms(line);
2936 if (r < 0)
2937 return r;
2938 }
2939
2940 return 0;
2941 }
2942
2943 static const char* const resolve_name_timing_table[_RESOLVE_NAME_TIMING_MAX] = {
2944 [RESOLVE_NAME_NEVER] = "never",
2945 [RESOLVE_NAME_LATE] = "late",
2946 [RESOLVE_NAME_EARLY] = "early",
2947 };
2948
2949 DEFINE_STRING_TABLE_LOOKUP(resolve_name_timing, ResolveNameTiming);