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