]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/udev/udev-rules.c
a6da5074ac647f11360d9442fabb28952fc9610f
[thirdparty/systemd.git] / src / udev / udev-rules.c
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
60 typedef 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
71 typedef 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
86 assert_cc(_MATCH_TYPE_MAX <= _MATCH_TYPE_MASK);
87
88 typedef 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
96 typedef 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
160 typedef 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
170 typedef struct UdevRuleFile UdevRuleFile;
171 typedef struct UdevRuleLine UdevRuleLine;
172 typedef struct UdevRuleToken UdevRuleToken;
173
174 struct 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
188 struct 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
203 struct 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
212 struct 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
223 static 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
434 static 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
444 DEFINE_TRIVIAL_CLEANUP_FUNC(UdevRuleToken*, udev_rule_token_free);
445
446 static 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
453 static 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
467 DEFINE_TRIVIAL_CLEANUP_FUNC(UdevRuleLine*, udev_rule_line_free);
468
469 static 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
483 DEFINE_TRIVIAL_CLEANUP_FUNC(UdevRuleFile*, udev_rule_file_free);
484
485 UdevRules* 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
498 static 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
535 static 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
572 static 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
582 static bool type_has_nulstr_value(UdevRuleTokenType type) {
583 return type < TK_M_TEST || type == TK_M_RESULT;
584 }
585
586 static 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
709 static 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
719 static 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
730 static 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
1184 static 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
1203 static 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
1248 int 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
1322 static 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
1377 static 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
1391 static 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
1408 static 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
1468 static 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
1502 static 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
1514 static 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
1522 static 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
1534 static 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
1550 static 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 */
1556 static 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
1565 static 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
1603 static 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
1611 static 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
1643 static void udev_check_rule_line(UdevRuleLine *line) {
1644 udev_check_unused_labels(line);
1645 udev_check_conflicts_duplicates(line);
1646 }
1647
1648 int udev_rules_parse_file(UdevRules *rules, const char *filename, 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 struct stat st;
1653 int r;
1654
1655 assert(rules);
1656 assert(filename);
1657
1658 f = fopen(filename, "re");
1659 if (!f) {
1660 if (extra_checks)
1661 return -errno;
1662
1663 if (errno == ENOENT)
1664 return 0;
1665
1666 return log_warning_errno(errno, "Failed to open %s, ignoring: %m", filename);
1667 }
1668
1669 if (fstat(fileno(f), &st) < 0)
1670 return log_warning_errno(errno, "Failed to stat %s, ignoring: %m", filename);
1671
1672 if (null_or_empty(&st)) {
1673 log_debug("Skipping empty file: %s", filename);
1674 if (ret)
1675 *ret = NULL;
1676 return 0;
1677 }
1678
1679 r = hashmap_put_stats_by_path(&rules->stats_by_path, filename, &st);
1680 if (r < 0)
1681 return log_warning_errno(r, "Failed to save stat for %s, ignoring: %m", filename);
1682
1683 (void) fd_warn_permissions(filename, fileno(f));
1684
1685 log_debug("Reading rules file: %s", filename);
1686
1687 name = strdup(filename);
1688 if (!name)
1689 return log_oom();
1690
1691 rule_file = new(UdevRuleFile, 1);
1692 if (!rule_file)
1693 return log_oom();
1694
1695 *rule_file = (UdevRuleFile) {
1696 .filename = TAKE_PTR(name),
1697 .rules = rules,
1698 };
1699
1700 LIST_APPEND(rule_files, rules->rule_files, rule_file);
1701
1702 _cleanup_free_ char *continuation = NULL;
1703 unsigned line_nr = 0, current_line_nr = 0;
1704 bool ignore_line = false;
1705 for (;;) {
1706 _cleanup_free_ char *buf = NULL;
1707 size_t len;
1708 char *line;
1709
1710 r = read_line(f, UDEV_LINE_SIZE, &buf);
1711 if (r < 0)
1712 return r;
1713 if (r == 0)
1714 break;
1715
1716 current_line_nr++;
1717 if (!continuation)
1718 line_nr = current_line_nr;
1719
1720 line = skip_leading_chars(buf, NULL);
1721
1722 /* Lines beginning with '#' are ignored regardless of line continuation. */
1723 if (line[0] == '#')
1724 continue;
1725
1726 len = strlen(line);
1727
1728 if (continuation && !ignore_line) {
1729 if (strlen(continuation) + len >= UDEV_LINE_SIZE)
1730 ignore_line = true;
1731
1732 if (!strextend(&continuation, line))
1733 return log_oom();
1734
1735 if (!ignore_line) {
1736 line = continuation;
1737 len = strlen(line);
1738 }
1739 }
1740
1741 if (len > 0 && line[len - 1] == '\\') {
1742 if (ignore_line)
1743 continue;
1744
1745 line[len - 1] = '\0';
1746 if (!continuation) {
1747 continuation = strdup(line);
1748 if (!continuation)
1749 return log_oom();
1750 }
1751
1752 continue;
1753 }
1754
1755 if (ignore_line)
1756 log_file_error(rule_file, line_nr, "Line is too long, ignored.");
1757 else if (len > 0)
1758 (void) rule_add_line(rule_file, line, line_nr, extra_checks);
1759
1760 continuation = mfree(continuation);
1761 ignore_line = false;
1762 }
1763
1764 if (continuation)
1765 log_file_error(rule_file, line_nr,
1766 "Unexpected EOF after line continuation, line ignored.");
1767
1768 rule_resolve_goto(rule_file);
1769
1770 if (extra_checks)
1771 LIST_FOREACH(rule_lines, line, rule_file->rule_lines)
1772 udev_check_rule_line(line);
1773
1774 if (ret)
1775 *ret = rule_file;
1776
1777 TAKE_PTR(rule_file);
1778 return 1;
1779 }
1780
1781 unsigned udev_rule_file_get_issues(UdevRuleFile *rule_file) {
1782 assert(rule_file);
1783
1784 return rule_file->issues;
1785 }
1786
1787 UdevRules* udev_rules_new(ResolveNameTiming resolve_name_timing) {
1788 assert(resolve_name_timing >= 0 && resolve_name_timing < _RESOLVE_NAME_TIMING_MAX);
1789
1790 UdevRules *rules = new(UdevRules, 1);
1791 if (!rules)
1792 return NULL;
1793
1794 *rules = (UdevRules) {
1795 .resolve_name_timing = resolve_name_timing,
1796 };
1797
1798 return rules;
1799 }
1800
1801 int udev_rules_load(UdevRules **ret_rules, ResolveNameTiming resolve_name_timing, char * const *extra) {
1802 _cleanup_(udev_rules_freep) UdevRules *rules = NULL;
1803 _cleanup_strv_free_ char **files = NULL, **directories = NULL;
1804 int r;
1805
1806 rules = udev_rules_new(resolve_name_timing);
1807 if (!rules)
1808 return -ENOMEM;
1809
1810 if (!strv_isempty(extra)) {
1811 directories = strv_copy(extra);
1812 if (!directories)
1813 return -ENOMEM;
1814 }
1815
1816 r = strv_extend_strv(&directories, CONF_PATHS_STRV("udev/rules.d"), /* filter_duplicates = */ false);
1817 if (r < 0)
1818 return r;
1819
1820 r = conf_files_list_strv(&files, ".rules", NULL, 0, (const char* const*) directories);
1821 if (r < 0)
1822 return log_debug_errno(r, "Failed to enumerate rules files: %m");
1823
1824 STRV_FOREACH(f, files) {
1825 r = udev_rules_parse_file(rules, *f, /* extra_checks = */ false, NULL);
1826 if (r < 0)
1827 log_debug_errno(r, "Failed to read rules file %s, ignoring: %m", *f);
1828 }
1829
1830 *ret_rules = TAKE_PTR(rules);
1831 return 0;
1832 }
1833
1834 bool udev_rules_should_reload(UdevRules *rules) {
1835 _cleanup_hashmap_free_ Hashmap *stats_by_path = NULL;
1836 int r;
1837
1838 if (!rules)
1839 return true;
1840
1841 r = config_get_stats_by_path(".rules", NULL, 0, RULES_DIRS, /* check_dropins = */ false, &stats_by_path);
1842 if (r < 0) {
1843 log_warning_errno(r, "Failed to get stats of udev rules, ignoring: %m");
1844 return true;
1845 }
1846
1847 if (!stats_by_path_equal(rules->stats_by_path, stats_by_path)) {
1848 log_debug("Udev rules need reloading");
1849 return true;
1850 }
1851
1852 return false;
1853 }
1854
1855 static bool apply_format_full(
1856 UdevEvent *event,
1857 UdevRuleToken *token,
1858 const char *format,
1859 char *result,
1860 size_t result_size,
1861 bool replace_whitespace,
1862 const char *what) {
1863
1864 assert(event);
1865 assert(token);
1866 assert(format);
1867 assert(result);
1868 assert(what);
1869
1870 bool truncated = false;
1871 (void) udev_event_apply_format(event, format, result, result_size, replace_whitespace, &truncated);
1872 if (truncated) {
1873 log_event_truncated(event, token, what, format);
1874 return false;
1875 }
1876
1877 if (event->trace && !streq(format, result))
1878 log_event_trace(event, token, "Format substitution: \"%s\" -> \"%s\"", format, result);
1879
1880 return true;
1881 }
1882
1883 static bool apply_format_value(
1884 UdevEvent *event,
1885 UdevRuleToken *token,
1886 char *result,
1887 size_t result_size,
1888 const char *what) {
1889
1890 return apply_format_full(event, token, token->value, result, result_size, /* replace_whitespace = */ false, what);
1891 }
1892
1893 static bool apply_format_attr(
1894 UdevEvent *event,
1895 UdevRuleToken *token,
1896 char *result,
1897 size_t result_size,
1898 const char *what) {
1899
1900 return apply_format_full(event, token, token->data, result, result_size, /* replace_whitespace = */ false, what);
1901 }
1902
1903 static bool token_match_string(UdevEvent *event, UdevRuleToken *token, const char *str, bool log_result) {
1904 const char *value;
1905 bool match = false, case_insensitive;
1906
1907 assert(event);
1908 assert(token);
1909 assert(token->value);
1910 assert(token->type < _TK_M_MAX);
1911
1912 str = strempty(str);
1913 value = token->value;
1914 case_insensitive = FLAGS_SET(token->match_type, MATCH_CASE_INSENSITIVE);
1915
1916 switch (token->match_type & _MATCH_TYPE_MASK) {
1917 case MATCH_TYPE_EMPTY:
1918 match = isempty(str);
1919 break;
1920 case MATCH_TYPE_SUBSYSTEM:
1921 if (case_insensitive)
1922 match = STRCASE_IN_SET(str, "subsystem", "class", "bus");
1923 else
1924 match = STR_IN_SET(str, "subsystem", "class", "bus");
1925 break;
1926 case MATCH_TYPE_PLAIN_WITH_EMPTY:
1927 if (isempty(str)) {
1928 match = true;
1929 break;
1930 }
1931 _fallthrough_;
1932 case MATCH_TYPE_PLAIN:
1933 NULSTR_FOREACH(i, value)
1934 if (case_insensitive ? strcaseeq(i, str) : streq(i, str)) {
1935 match = true;
1936 break;
1937 }
1938 break;
1939 case MATCH_TYPE_GLOB_WITH_EMPTY:
1940 if (isempty(str)) {
1941 match = true;
1942 break;
1943 }
1944 _fallthrough_;
1945 case MATCH_TYPE_GLOB:
1946 NULSTR_FOREACH(i, value)
1947 if ((fnmatch(i, str, case_insensitive ? FNM_CASEFOLD : 0) == 0)) {
1948 match = true;
1949 break;
1950 }
1951 break;
1952 default:
1953 assert_not_reached();
1954 }
1955
1956 bool result = token->op == (match ? OP_MATCH : OP_NOMATCH);
1957
1958 if (event->trace)
1959 switch (token->match_type & _MATCH_TYPE_MASK) {
1960 case MATCH_TYPE_EMPTY:
1961 log_event_trace(event, token, "String \"%s\" is%s empty%s",
1962 strempty(str), match ? "" : " not",
1963 log_result ? result ? ": PASS" : ": FAIL" : ".");
1964 break;
1965 case MATCH_TYPE_SUBSYSTEM:
1966 log_event_trace(event, token,
1967 "String \"%s\" matches %s of \"subsystem\", \"class\", or \"bus\"%s",
1968 strempty(str), match ? "one" : "neither",
1969 log_result ? result ? ": PASS" : ": FAIL" : ".");
1970 break;
1971 case MATCH_TYPE_PLAIN_WITH_EMPTY:
1972 case MATCH_TYPE_PLAIN:
1973 case MATCH_TYPE_GLOB_WITH_EMPTY:
1974 case MATCH_TYPE_GLOB: {
1975 _cleanup_free_ char *joined = NULL;
1976 unsigned c = 0;
1977
1978 if (IN_SET(token->match_type & _MATCH_TYPE_MASK, MATCH_TYPE_PLAIN_WITH_EMPTY, MATCH_TYPE_GLOB_WITH_EMPTY)) {
1979 (void) strextend_with_separator(&joined, ", ", "\"\"");
1980 c++;
1981 }
1982
1983 NULSTR_FOREACH(i, value) {
1984 (void) strextendf_with_separator(&joined, ", ", "\"%s\"", i);
1985 c++;
1986 }
1987
1988 assert(c > 0);
1989 log_event_trace(event, token, "String \"%s\" %s %s%s",
1990 strempty(str),
1991 match ? (c > 1 ? "matches one of" : "matches") : (c > 1 ? "matches neither of" : "does not match"),
1992 strempty(joined),
1993 log_result ? result ? ": PASS" : ": FAIL" : ".");
1994 break;
1995 }
1996 default:
1997 assert_not_reached();
1998 }
1999
2000 return result;
2001 }
2002
2003 static bool token_match_attr(UdevRuleToken *token, sd_device *dev, UdevEvent *event) {
2004 char nbuf[UDEV_NAME_SIZE], vbuf[UDEV_NAME_SIZE];
2005 const char *name, *value;
2006 int r;
2007
2008 assert(token);
2009 assert(IN_SET(token->type, TK_M_ATTR, TK_M_PARENTS_ATTR));
2010 assert(dev);
2011 assert(event);
2012
2013 name = token->data;
2014
2015 switch (token->attr_subst_type) {
2016 case SUBST_TYPE_FORMAT:
2017 if (!apply_format_attr(event, token, nbuf, sizeof(nbuf), "sysfs attribute name"))
2018 return false;
2019
2020 name = nbuf;
2021 _fallthrough_;
2022 case SUBST_TYPE_PLAIN:
2023 r = sd_device_get_sysattr_value(dev, name, &value);
2024 if (r < 0) {
2025 log_event_trace_errno(event, token, r, "Cannot read sysfs attribute%s%s%s: %m",
2026 name != token->data ? " \"" : "",
2027 name != token->data ? name : "",
2028 name != token->data ? "\"" : "");
2029 return false;
2030 }
2031
2032 /* remove trailing whitespace, if not asked to match for it */
2033 if (FLAGS_SET(token->match_type, MATCH_REMOVE_TRAILING_WHITESPACE)) {
2034 strscpy(vbuf, sizeof(vbuf), value);
2035 value = delete_trailing_chars(vbuf, NULL);
2036 }
2037
2038 return token_match_string(event, token, value, /* log_result = */ true);
2039
2040 case SUBST_TYPE_SUBSYS:
2041 r = udev_resolve_subsys_kernel(name, vbuf, sizeof(vbuf), true);
2042 if (r < 0) {
2043 log_event_trace_errno(event, token, r, "Cannot read sysfs attribute: %m");
2044 return false;
2045 }
2046
2047 /* remove trailing whitespace, if not asked to match for it */
2048 if (FLAGS_SET(token->match_type, MATCH_REMOVE_TRAILING_WHITESPACE))
2049 delete_trailing_chars(vbuf, NULL);
2050
2051 return token_match_string(event, token, vbuf, /* log_result = */ true);
2052
2053 default:
2054 assert_not_reached();
2055 }
2056 }
2057
2058 static int get_property_from_string(char *line, char **ret_key, char **ret_value) {
2059 char *key, *val;
2060 size_t len;
2061
2062 assert(line);
2063 assert(ret_key);
2064 assert(ret_value);
2065
2066 /* find key */
2067 key = skip_leading_chars(line, NULL);
2068
2069 /* comment or empty line */
2070 if (IN_SET(key[0], '#', '\0')) {
2071 *ret_key = *ret_value = NULL;
2072 return 0;
2073 }
2074
2075 /* split key/value */
2076 val = strchr(key, '=');
2077 if (!val)
2078 return -EINVAL;
2079 *val++ = '\0';
2080
2081 key = strstrip(key);
2082 if (isempty(key))
2083 return -EINVAL;
2084
2085 val = strstrip(val);
2086 if (isempty(val))
2087 return -EINVAL;
2088
2089 /* unquote */
2090 if (IN_SET(val[0], '"', '\'')) {
2091 len = strlen(val);
2092 if (len == 1 || val[len-1] != val[0])
2093 return -EINVAL;
2094 val[len-1] = '\0';
2095 val++;
2096 }
2097
2098 *ret_key = key;
2099 *ret_value = val;
2100 return 1;
2101 }
2102
2103 static int attr_subst_subdir(char attr[static UDEV_PATH_SIZE]) {
2104 _cleanup_closedir_ DIR *dir = NULL;
2105 char buf[UDEV_PATH_SIZE], *p;
2106 const char *tail;
2107 size_t len, size;
2108 bool truncated;
2109
2110 assert(attr);
2111
2112 tail = strstr(attr, "/*/");
2113 if (!tail)
2114 return 0;
2115
2116 len = tail - attr + 1; /* include slash at the end */
2117 tail += 2; /* include slash at the beginning */
2118
2119 p = buf;
2120 size = sizeof(buf);
2121 size -= strnpcpy_full(&p, size, attr, len, &truncated);
2122 if (truncated)
2123 return -ENOENT;
2124
2125 dir = opendir(buf);
2126 if (!dir)
2127 return -errno;
2128
2129 FOREACH_DIRENT_ALL(de, dir, break) {
2130 if (de->d_name[0] == '.')
2131 continue;
2132
2133 strscpyl_full(p, size, &truncated, de->d_name, tail, NULL);
2134 if (truncated)
2135 continue;
2136
2137 if (faccessat(dirfd(dir), p, F_OK, 0) < 0)
2138 continue;
2139
2140 strcpy(attr, buf);
2141 return 0;
2142 }
2143
2144 return -ENOENT;
2145 }
2146
2147 static size_t udev_replace_ifname_strict(char *str) {
2148 size_t replaced = 0;
2149
2150 assert(str);
2151
2152 /* See ifname_valid_full(). */
2153
2154 for (char *p = str; *p != '\0'; p++)
2155 if (!ifname_valid_char(*p)) {
2156 *p = '_';
2157 replaced++;
2158 }
2159
2160 return replaced;
2161 }
2162
2163 static void udev_replace_ifname(UdevEvent *event, UdevRuleToken *token, char *buf) {
2164 assert(event);
2165 assert(token);
2166 assert(buf);
2167
2168 size_t count;
2169 if (naming_scheme_has(NAMING_REPLACE_STRICTLY))
2170 count = udev_replace_ifname_strict(buf);
2171 else
2172 count = udev_replace_chars(buf, "/");
2173 if (count > 0)
2174 log_event_trace(event, token,
2175 "Replaced %zu character(s) from network interface name, results to \"%s\"",
2176 count, buf);
2177 }
2178
2179 static void udev_replace_chars_and_log(UdevEvent *event, UdevRuleToken *token, char *buf, const char *allow, const char *what) {
2180 assert(event);
2181 assert(token);
2182 assert(buf);
2183 assert(what);
2184
2185 size_t count = udev_replace_chars(buf, allow);
2186 if (count > 0)
2187 log_event_trace(event, token,
2188 "Replaced %zu character(s) from %s, results to \"%s\"",
2189 count, what, buf);
2190 }
2191
2192 static int udev_rule_apply_token_to_event(
2193 UdevRuleToken *token,
2194 sd_device *dev,
2195 UdevEvent *event) {
2196
2197 int r;
2198
2199 assert(token);
2200 assert(dev);
2201 assert(event);
2202
2203 /* This returns the following values:
2204 * 0 on the current token does not match the event,
2205 * 1 on the current token matches the event, and
2206 * negative errno on some critical errors. */
2207
2208 switch (token->type) {
2209 case TK_M_ACTION: {
2210 sd_device_action_t a;
2211
2212 r = sd_device_get_action(dev, &a);
2213 if (r < 0)
2214 return log_event_error_errno(event, token, r, "Failed to get uevent action type: %m");
2215
2216 return token_match_string(event, token, device_action_to_string(a), /* log_result = */ true);
2217 }
2218 case TK_M_DEVPATH: {
2219 const char *val;
2220
2221 r = sd_device_get_devpath(dev, &val);
2222 if (r < 0)
2223 return log_event_error_errno(event, token, r, "Failed to get devpath: %m");
2224
2225 return token_match_string(event, token, val, /* log_result = */ true);
2226 }
2227 case TK_M_KERNEL:
2228 case TK_M_PARENTS_KERNEL: {
2229 const char *val;
2230
2231 r = sd_device_get_sysname(dev, &val);
2232 if (r < 0)
2233 return log_event_error_errno(event, token, r, "Failed to get sysname: %m");
2234
2235 return token_match_string(event, token, val, /* log_result = */ true);
2236 }
2237 case TK_M_DEVLINK:
2238 FOREACH_DEVICE_DEVLINK(dev, val)
2239 if (token_match_string(event, token, strempty(startswith(val, "/dev/")), /* log_result = */ false) == (token->op == OP_MATCH))
2240 return log_event_result(event, token, token->op == OP_MATCH);
2241 return log_event_result(event, token, token->op == OP_NOMATCH);
2242
2243 case TK_M_NAME:
2244 return token_match_string(event, token, event->name, /* log_result = */ true);
2245
2246 case TK_M_ENV: {
2247 const char *val = NULL;
2248
2249 (void) device_get_property_value_with_fallback(dev, token->data, event->worker ? event->worker->properties : NULL, &val);
2250
2251 return token_match_string(event, token, val, /* log_result = */ true);
2252 }
2253 case TK_M_CONST: {
2254 const char *val, *k = token->data;
2255
2256 if (streq(k, "arch"))
2257 val = architecture_to_string(uname_architecture());
2258 else if (streq(k, "virt"))
2259 val = virtualization_to_string(detect_virtualization());
2260 else if (streq(k, "cvm"))
2261 val = confidential_virtualization_to_string(detect_confidential_virtualization());
2262 else
2263 assert_not_reached();
2264 return token_match_string(event, token, val, /* log_result = */ true);
2265 }
2266 case TK_M_TAG:
2267 case TK_M_PARENTS_TAG:
2268 FOREACH_DEVICE_CURRENT_TAG(dev, val)
2269 if (token_match_string(event, token, val, /* log_result = */ false) == (token->op == OP_MATCH))
2270 return log_event_result(event, token, token->op == OP_MATCH);
2271 return log_event_result(event, token, token->op == OP_NOMATCH);
2272
2273 case TK_M_SUBSYSTEM:
2274 case TK_M_PARENTS_SUBSYSTEM: {
2275 const char *val;
2276
2277 r = sd_device_get_subsystem(dev, &val);
2278 if (r == -ENOENT)
2279 val = NULL;
2280 else if (r < 0)
2281 return log_event_error_errno(event, token, r, "Failed to get subsystem: %m");
2282
2283 return token_match_string(event, token, val, /* log_result = */ true);
2284 }
2285 case TK_M_DRIVER:
2286 case TK_M_PARENTS_DRIVER: {
2287 const char *val;
2288
2289 r = sd_device_get_driver(dev, &val);
2290 if (r == -ENOENT)
2291 val = NULL;
2292 else if (r < 0)
2293 return log_event_error_errno(event, token, r, "Failed to get driver: %m");
2294
2295 return token_match_string(event, token, val, /* log_result = */ true);
2296 }
2297 case TK_M_ATTR:
2298 case TK_M_PARENTS_ATTR:
2299 return token_match_attr(token, dev, event);
2300
2301 case TK_M_SYSCTL: {
2302 _cleanup_free_ char *value = NULL;
2303 char buf[UDEV_PATH_SIZE];
2304
2305 if (!apply_format_attr(event, token, buf, sizeof(buf), "sysctl entry name"))
2306 return false;
2307
2308 r = sysctl_read(sysctl_normalize(buf), &value);
2309 if (r < 0 && r != -ENOENT)
2310 return log_event_error_errno(event, token, r, "Failed to read sysctl \"%s\": %m", buf);
2311
2312 return token_match_string(event, token, strstrip(value), /* log_result = */ true);
2313 }
2314 case TK_M_TEST: {
2315 mode_t mode = PTR_TO_MODE(token->data);
2316 char buf[UDEV_PATH_SIZE];
2317 struct stat statbuf;
2318 bool match;
2319
2320 if (!apply_format_value(event, token, buf, sizeof(buf), "file name"))
2321 return false;
2322
2323 if (!path_is_absolute(buf) &&
2324 udev_resolve_subsys_kernel(buf, buf, sizeof(buf), false) < 0) {
2325 char tmp[UDEV_PATH_SIZE];
2326 const char *val;
2327
2328 r = sd_device_get_syspath(dev, &val);
2329 if (r < 0)
2330 return log_event_error_errno(event, token, r, "Failed to get syspath: %m");
2331
2332 bool truncated;
2333 strscpy_full(tmp, sizeof(tmp), buf, &truncated);
2334 assert(!truncated);
2335 strscpyl_full(buf, sizeof(buf), &truncated, val, "/", tmp, NULL);
2336 if (truncated)
2337 return log_event_result(event, token, false);
2338 }
2339
2340 r = attr_subst_subdir(buf);
2341 if (r == -ENOENT)
2342 return log_event_result(event, token, token->op == OP_NOMATCH);
2343 if (r < 0)
2344 return log_event_error_errno(event, token, r, "Failed to test for the existence of \"%s\": %m", buf);
2345
2346 if (stat(buf, &statbuf) < 0) {
2347 if (errno != ENOENT)
2348 log_event_warning_errno(event, token, errno, "Failed to stat \"%s\", ignoring: %m", buf);
2349 return log_event_result(event, token, token->op == OP_NOMATCH);
2350 }
2351
2352 if (mode == MODE_INVALID)
2353 return log_event_result(event, token, token->op == OP_MATCH);
2354
2355 match = (statbuf.st_mode & mode) > 0;
2356 return log_event_result(event, token, token->op == (match ? OP_MATCH : OP_NOMATCH));
2357 }
2358 case TK_M_PROGRAM: {
2359 char buf[UDEV_LINE_SIZE], result[UDEV_LINE_SIZE];
2360
2361 event->program_result = mfree(event->program_result);
2362
2363 if (!apply_format_value(event, token, buf, sizeof(buf), "command"))
2364 return false;
2365
2366 log_event_debug(event, token, "Running command \"%s\"", buf);
2367
2368 r = udev_event_spawn(event, /* accept_failure = */ true, buf, result, sizeof(result), NULL);
2369 if (r != 0) {
2370 if (r < 0)
2371 log_event_warning_errno(event, token, r, "Failed to execute \"%s\": %m", buf);
2372 else /* returned value is positive when program fails */
2373 log_event_debug(event, token, "Command \"%s\" returned %d (error)", buf, r);
2374 return log_event_result(event, token, token->op == OP_NOMATCH);
2375 }
2376
2377 delete_trailing_chars(result, "\n");
2378 udev_replace_chars_and_log(event, token, result, UDEV_ALLOWED_CHARS_INPUT, "command output");
2379
2380 event->program_result = strdup(result);
2381 return log_event_result(event, token, token->op == OP_MATCH);
2382 }
2383 case TK_M_IMPORT_FILE: {
2384 _cleanup_fclose_ FILE *f = NULL;
2385 char buf[UDEV_PATH_SIZE];
2386
2387 if (!apply_format_value(event, token, buf, sizeof(buf), "file name to be imported"))
2388 return false;
2389
2390 log_event_debug(event, token, "Importing properties from \"%s\"", buf);
2391
2392 f = fopen(buf, "re");
2393 if (!f) {
2394 if (errno != ENOENT)
2395 return log_event_error_errno(event, token, errno, "Failed to open \"%s\": %m", buf);
2396 return log_event_result(event, token, token->op == OP_NOMATCH);
2397 }
2398
2399 for (;;) {
2400 _cleanup_free_ char *line = NULL;
2401 char *key, *value;
2402
2403 r = read_line(f, LONG_LINE_MAX, &line);
2404 if (r < 0) {
2405 log_event_debug_errno(event, token, r, "Failed to read \"%s\", ignoring: %m", buf);
2406 return log_event_result(event, token, token->op == OP_NOMATCH);
2407 }
2408 if (r == 0)
2409 return log_event_result(event, token, token->op == OP_MATCH);
2410
2411 r = get_property_from_string(line, &key, &value);
2412 if (r < 0) {
2413 log_event_debug_errno(event, token, r,
2414 "Failed to parse key and value from \"%s\", ignoring: %m",
2415 line);
2416 continue;
2417 }
2418 if (r == 0)
2419 continue;
2420
2421 r = device_add_property(dev, key, value);
2422 if (r < 0)
2423 return log_event_error_errno(event, token, r,
2424 "Failed to add property %s=%s: %m",
2425 key, value);
2426 log_event_trace(event, token, "Imported property \"%s=%s\".", key, value);
2427 }
2428
2429 assert_not_reached();
2430 }
2431 case TK_M_IMPORT_PROGRAM: {
2432 _cleanup_strv_free_ char **lines = NULL;
2433 char buf[UDEV_LINE_SIZE], result[UDEV_LINE_SIZE];
2434 bool truncated;
2435
2436 if (!apply_format_value(event, token, buf, sizeof(buf), "command"))
2437 return false;
2438
2439 log_event_debug(event, token, "Importing properties from results of \"%s\"", buf);
2440
2441 r = udev_event_spawn(event, /* accept_failure = */ true, buf, result, sizeof result, &truncated);
2442 if (r != 0) {
2443 if (r < 0)
2444 log_event_warning_errno(event, token, r, "Failed to execute \"%s\", ignoring: %m", buf);
2445 else /* returned value is positive when program fails */
2446 log_event_debug(event, token, "Command \"%s\" returned %d (error), ignoring", buf, r);
2447 return log_event_result(event, token, token->op == OP_NOMATCH);
2448 }
2449
2450 if (truncated) {
2451 log_event_debug(event, token, "Result of \"%s\" is too long and truncated, ignoring the last line of the result.", buf);
2452
2453 /* Drop the last line. */
2454 bool found = false;
2455 for (char *p = PTR_SUB1(buf + strlen(buf), buf); p; p = PTR_SUB1(p, buf))
2456 if (strchr(NEWLINE, *p)) {
2457 *p = '\0';
2458 found = true;
2459 break;
2460 }
2461 if (!found)
2462 buf[0] = '\0';
2463 }
2464
2465 r = strv_split_newlines_full(&lines, result, EXTRACT_RETAIN_ESCAPE);
2466 if (r == -ENOMEM)
2467 return log_oom();
2468 if (r < 0) {
2469 log_event_warning_errno(event, token, r,
2470 "Failed to extract lines from result of command \"%s\", ignoring: %m", buf);
2471 return log_event_result(event, token, false);
2472 }
2473
2474 STRV_FOREACH(line, lines) {
2475 char *key, *value;
2476
2477 r = get_property_from_string(*line, &key, &value);
2478 if (r < 0) {
2479 log_event_debug_errno(event, token, r,
2480 "Failed to parse key and value from \"%s\", ignoring: %m",
2481 *line);
2482 continue;
2483 }
2484 if (r == 0)
2485 continue;
2486
2487 r = device_add_property(dev, key, value);
2488 if (r < 0)
2489 return log_event_error_errno(event, token, r,
2490 "Failed to add property %s=%s: %m",
2491 key, value);
2492 log_event_trace(event, token, "Imported property \"%s=%s\".", key, value);
2493 }
2494
2495 return log_event_result(event, token, token->op == OP_MATCH);
2496 }
2497 case TK_M_IMPORT_BUILTIN: {
2498 UdevBuiltinCommand cmd = PTR_TO_UDEV_BUILTIN_CMD(token->data);
2499 assert(cmd >= 0 && cmd < _UDEV_BUILTIN_MAX);
2500 unsigned mask = 1U << (int) cmd;
2501 char buf[UDEV_LINE_SIZE];
2502
2503 if (udev_builtin_run_once(cmd)) {
2504 /* check if we ran already */
2505 if (event->builtin_run & mask) {
2506 log_event_debug(event, token, "Builtin command \"%s\" has already run, skipping.",
2507 udev_builtin_name(cmd));
2508 /* return the result from earlier run */
2509 return log_event_result(event, token, token->op == (event->builtin_ret & mask ? OP_NOMATCH : OP_MATCH));
2510 }
2511 /* mark as ran */
2512 event->builtin_run |= mask;
2513 }
2514
2515 if (!apply_format_value(event, token, buf, sizeof(buf), "builtin command"))
2516 return false;
2517
2518 log_event_debug(event, token, "Importing properties from results of builtin command \"%s\".", buf);
2519
2520 r = udev_builtin_run(event, cmd, buf);
2521 if (r < 0) {
2522 /* remember failure */
2523 log_event_debug_errno(event, token, r, "Failed to run builtin \"%s\": %m", buf);
2524 event->builtin_ret |= mask;
2525 }
2526 return log_event_result(event, token, token->op == (r >= 0 ? OP_MATCH : OP_NOMATCH));
2527 }
2528 case TK_M_IMPORT_DB: {
2529 const char *val;
2530
2531 if (!event->dev_db_clone)
2532 return log_event_result(event, token, token->op == OP_NOMATCH);
2533 r = sd_device_get_property_value(event->dev_db_clone, token->value, &val);
2534 if (r == -ENOENT)
2535 return log_event_result(event, token, token->op == OP_NOMATCH);
2536 if (r < 0)
2537 return log_event_error_errno(event, token, r,
2538 "Failed to get property \"%s\" from database: %m",
2539 token->value);
2540
2541 r = device_add_property(dev, token->value, val);
2542 if (r < 0)
2543 return log_event_error_errno(event, token, r, "Failed to add property \"%s=%s\": %m",
2544 token->value, val);
2545 log_event_trace(event, token, "Imported property \"%s=%s\".", token->value, val);
2546
2547 return log_event_result(event, token, token->op == OP_MATCH);
2548 }
2549 case TK_M_IMPORT_CMDLINE: {
2550 _cleanup_free_ char *value = NULL;
2551
2552 r = proc_cmdline_get_key(token->value, PROC_CMDLINE_VALUE_OPTIONAL, &value);
2553 if (r < 0)
2554 return log_event_error_errno(event, token, r,
2555 "Failed to read \"%s\" option from /proc/cmdline: %m",
2556 token->value);
2557 if (r == 0)
2558 return log_event_result(event, token, token->op == OP_NOMATCH);
2559
2560 const char *val = value ?: "1";
2561 r = device_add_property(dev, token->value, val);
2562 if (r < 0)
2563 return log_event_error_errno(event, token, r, "Failed to add property \"%s=%s\": %m",
2564 token->value, val);
2565 log_event_trace(event, token, "Imported property \"%s=%s\".", token->value, val);
2566
2567 return log_event_result(event, token, token->op == OP_MATCH);
2568 }
2569 case TK_M_IMPORT_PARENT: {
2570 char buf[UDEV_PATH_SIZE];
2571
2572 if (!apply_format_value(event, token, buf, sizeof(buf), "property name"))
2573 return false;
2574
2575 sd_device *parent;
2576 r = sd_device_get_parent(dev, &parent);
2577 if (ERRNO_IS_NEG_DEVICE_ABSENT(r))
2578 return log_event_result(event, token, token->op == OP_NOMATCH);
2579 if (r < 0)
2580 return log_event_error_errno(event, token, r, "Failed to get parent device: %m");
2581
2582 bool have = false;
2583 FOREACH_DEVICE_PROPERTY(parent, key, val) {
2584 if (fnmatch(buf, key, 0) != 0)
2585 continue;
2586
2587 r = device_add_property(dev, key, val);
2588 if (r < 0)
2589 return log_event_error_errno(event, token, r, "Failed to add property \"%s=%s\": %m", key, val);
2590 log_event_trace(event, token, "Imported property \"%s=%s\".", key, val);
2591 have = true;
2592 }
2593
2594 return log_event_result(event, token, token->op == (have ? OP_MATCH : OP_NOMATCH));
2595 }
2596 case TK_M_RESULT:
2597 return token_match_string(event, token, event->program_result, /* log_result = */ true);
2598
2599 case TK_A_OPTIONS_DUMP: {
2600 log_event_info(event, token, "Dumping current state:");
2601
2602 _cleanup_(memstream_done) MemStream m = {};
2603 FILE *f = memstream_init(&m);
2604 if (!f)
2605 return log_oom();
2606
2607 (void) dump_event(event, SD_JSON_FORMAT_OFF, f);
2608
2609 _cleanup_free_ char *buf = NULL;
2610 r = memstream_finalize(&m, &buf, NULL);
2611 if (r < 0)
2612 log_event_warning_errno(event, token, r, "Failed to finalize memory stream, ignoring: %m");
2613 else
2614 log_info("%s", buf);
2615
2616 log_event_info(event, token, "DONE");
2617 return true;
2618 }
2619 case TK_A_OPTIONS_STRING_ESCAPE_NONE:
2620 event->esc = ESCAPE_NONE;
2621 return log_event_done(event, token);
2622
2623 case TK_A_OPTIONS_STRING_ESCAPE_REPLACE:
2624 event->esc = ESCAPE_REPLACE;
2625 return log_event_done(event, token);
2626
2627 case TK_A_OPTIONS_DB_PERSIST:
2628 device_set_db_persist(dev);
2629 return log_event_done(event, token);
2630
2631 case TK_A_OPTIONS_INOTIFY_WATCH:
2632 if (event->inotify_watch_final)
2633 return log_event_final_set(event, token);
2634
2635 if (token->op == OP_ASSIGN_FINAL)
2636 event->inotify_watch_final = true;
2637
2638 event->inotify_watch = token->data;
2639 return log_event_done(event, token);
2640
2641 case TK_A_OPTIONS_DEVLINK_PRIORITY:
2642 device_set_devlink_priority(dev, PTR_TO_INT(token->data));
2643 return log_event_done(event, token);
2644
2645 case TK_A_OPTIONS_LOG_LEVEL: {
2646 int level = PTR_TO_INT(token->data);
2647
2648 if (level < 0)
2649 level = event->default_log_level;
2650
2651 if (event->event_mode == EVENT_UDEV_WORKER)
2652 log_set_max_level(level);
2653 else {
2654 _cleanup_free_ char *level_str = NULL;
2655 (void) log_level_to_string_alloc(level, &level_str);
2656 log_event_debug(event, token, "Running in test mode, skipping changing maximum log level to %s.", strna(level_str));
2657 }
2658
2659 if (level == LOG_DEBUG && !event->log_level_was_debug) {
2660 /* The log level becomes LOG_DEBUG at first time. Let's log basic information. */
2661 if (event->event_mode == EVENT_UDEV_WORKER)
2662 log_device_uevent(dev, "The log level is changed to 'debug' while processing device");
2663 event->log_level_was_debug = true;
2664 }
2665
2666 return log_event_done(event, token);
2667 }
2668 case TK_A_OWNER: {
2669 char owner[UDEV_NAME_SIZE];
2670
2671 if (event->owner_final)
2672 return log_event_final_set(event, token);
2673
2674 if (token->op == OP_ASSIGN_FINAL)
2675 event->owner_final = true;
2676
2677 if (!apply_format_value(event, token, owner, sizeof(owner), "user name"))
2678 return true;
2679
2680 _cleanup_(user_record_unrefp) UserRecord *ur = NULL;
2681 r = userdb_by_name(owner, &USERDB_MATCH_ROOT_AND_SYSTEM,
2682 USERDB_SUPPRESS_SHADOW | USERDB_PARSE_NUMERIC | USERDB_SYNTHESIZE_NUMERIC,
2683 &ur);
2684 if (r == -ESRCH)
2685 log_event_error_errno(event, token, r, "Unknown user \"%s\", ignoring.", owner);
2686 else if (r == -ENOEXEC)
2687 log_event_error(event, token, "User \"%s\" is not a system user, ignoring.", owner);
2688 else if (r < 0)
2689 log_event_error_errno(event, token, r, "Failed to resolve user \"%s\", ignoring: %m", owner);
2690 else {
2691 event->uid = ur->uid;
2692 log_event_debug(event, token, "Set owner: %s("UID_FMT")", owner, event->uid);
2693 }
2694 return true;
2695 }
2696 case TK_A_GROUP: {
2697 char group[UDEV_NAME_SIZE];
2698
2699 if (event->group_final)
2700 return log_event_final_set(event, token);
2701
2702 if (token->op == OP_ASSIGN_FINAL)
2703 event->group_final = true;
2704
2705 if (!apply_format_value(event, token, group, sizeof(group), "group name"))
2706 return true;
2707
2708 _cleanup_(group_record_unrefp) GroupRecord *gr = NULL;
2709 r = groupdb_by_name(group, &USERDB_MATCH_ROOT_AND_SYSTEM,
2710 USERDB_SUPPRESS_SHADOW | USERDB_PARSE_NUMERIC | USERDB_SYNTHESIZE_NUMERIC,
2711 &gr);
2712 if (r == -ESRCH)
2713 log_event_error_errno(event, token, r, "Unknown group \"%s\", ignoring.", group);
2714 else if (r == -ENOEXEC)
2715 log_event_error(event, token, "Group \"%s\" is not a system group, ignoring.", group);
2716 else if (r < 0)
2717 log_event_error_errno(event, token, r, "Failed to resolve group \"%s\", ignoring: %m", group);
2718 else {
2719 event->gid = gr->gid;
2720 log_event_debug(event, token, "Set group: %s("GID_FMT")", group, event->gid);
2721 }
2722 return true;
2723 }
2724 case TK_A_MODE: {
2725 char mode_str[UDEV_NAME_SIZE];
2726
2727 if (event->mode_final)
2728 return log_event_final_set(event, token);
2729
2730 if (token->op == OP_ASSIGN_FINAL)
2731 event->mode_final = true;
2732
2733 if (!apply_format_value(event, token, mode_str, sizeof(mode_str), "mode"))
2734 return true;
2735
2736 r = parse_mode(mode_str, &event->mode);
2737 if (r < 0)
2738 log_event_error_errno(event, token, r, "Failed to parse mode \"%s\", ignoring: %m", mode_str);
2739 else
2740 log_event_debug(event, token, "Set mode: %#o", event->mode);
2741 return true;
2742 }
2743 case TK_A_OWNER_ID:
2744 if (event->owner_final)
2745 return log_event_final_set(event, token);
2746
2747 if (token->op == OP_ASSIGN_FINAL)
2748 event->owner_final = true;
2749
2750 event->uid = PTR_TO_UID(ASSERT_PTR(token->data));
2751 log_event_debug(event, token, "Set owner ID: %u", event->uid);
2752 return true;
2753
2754 case TK_A_GROUP_ID:
2755 if (event->group_final)
2756 return log_event_final_set(event, token);
2757
2758 if (token->op == OP_ASSIGN_FINAL)
2759 event->group_final = true;
2760
2761 event->gid = PTR_TO_GID(ASSERT_PTR(token->data));
2762 log_event_debug(event, token, "Set group ID: %u", event->gid);
2763 return true;
2764
2765 case TK_A_MODE_ID:
2766 if (event->mode_final)
2767 return log_event_final_set(event, token);
2768
2769 if (token->op == OP_ASSIGN_FINAL)
2770 event->mode_final = true;
2771
2772 event->mode = PTR_TO_MODE(ASSERT_PTR(token->data));
2773 log_event_debug(event, token, "Set mode: %#o", event->mode);
2774 return true;
2775
2776 case TK_A_SECLABEL: {
2777 _cleanup_free_ char *name = NULL, *label = NULL;
2778 char label_str[UDEV_LINE_SIZE] = {};
2779
2780 name = strdup(token->data);
2781 if (!name)
2782 return log_oom();
2783
2784 if (!apply_format_value(event, token, label_str, sizeof(label_str), "security label"))
2785 return true;
2786
2787 if (!isempty(label_str))
2788 label = strdup(label_str);
2789 else
2790 label = strdup(token->value);
2791 if (!label)
2792 return log_oom();
2793
2794 if (token->op == OP_ASSIGN)
2795 ordered_hashmap_clear(event->seclabel_list);
2796
2797 r = ordered_hashmap_ensure_put(&event->seclabel_list, &trivial_hash_ops_free_free, name, label);
2798 if (r == -ENOMEM)
2799 return log_oom();
2800 if (r < 0)
2801 return log_event_error_errno(event, token, r, "Failed to store security label \"%s=%s\": %m", name, label);
2802
2803 log_event_debug(event, token, "Set security label: %s=%s", name, label);
2804
2805 TAKE_PTR(name);
2806 TAKE_PTR(label);
2807 return true;
2808 }
2809 case TK_A_ENV: {
2810 const char *val, *name = token->data;
2811 char value_new[UDEV_NAME_SIZE], *p = value_new;
2812 size_t l = sizeof(value_new);
2813
2814 if (isempty(token->value)) {
2815 if (token->op == OP_ADD)
2816 return log_event_done(event, token);
2817
2818 r = device_add_property(dev, name, NULL);
2819 if (r < 0)
2820 return log_event_error_errno(event, token, r, "Failed to remove property \"%s\": %m", name);
2821 log_event_trace(event, token, "Removed property \"%s\".", name);
2822 return true;
2823 }
2824
2825 if (token->op == OP_ADD &&
2826 device_get_property_value_with_fallback(dev, name, event->worker ? event->worker->properties : NULL, &val) >= 0) {
2827 bool truncated;
2828 l = strpcpyl_full(&p, l, &truncated, val, " ", NULL);
2829 if (truncated) {
2830 log_event_warning(event, token,
2831 "The buffer for the property is full, refusing to append new property \"%s=%s\".",
2832 name, token->value);
2833 return true;
2834 }
2835 }
2836
2837 if (!apply_format_value(event, token, p, l, "property value"))
2838 return true;
2839
2840 if (event->esc == ESCAPE_REPLACE)
2841 udev_replace_chars_and_log(event, token, p, /* allow = */ NULL, "property value");
2842
2843 r = device_add_property(dev, name, value_new);
2844 if (r < 0)
2845 return log_event_error_errno(event, token, r, "Failed to set property \"%s=%s\": %m", name, value_new);
2846 log_event_trace(event, token, "Set property \"%s=%s\".", name, value_new);
2847 return true;
2848 }
2849 case TK_A_TAG: {
2850 char buf[UDEV_PATH_SIZE];
2851
2852 if (!apply_format_value(event, token, buf, sizeof(buf), "tag name"))
2853 return true;
2854
2855 if (token->op == OP_REMOVE) {
2856 device_remove_tag(dev, buf);
2857 log_event_trace(event, token, "Removed tag \"%s\".", buf);
2858 return true;
2859 }
2860
2861 assert(IN_SET(token->op, OP_ASSIGN, OP_ADD));
2862
2863 if (token->op == OP_ASSIGN)
2864 device_cleanup_tags(dev);
2865
2866 r = device_add_tag(dev, buf, /* both = */ true);
2867 if (r == -ENOMEM)
2868 return log_oom();
2869 if (r < 0)
2870 log_event_warning_errno(event, token, r, "Failed to %s tag \"%s\", ignoring: %m",
2871 token->op == OP_ASSIGN ? "set" : "add", buf);
2872 else
2873 log_event_trace(event, token, "%s tag \"%s\".", token->op == OP_ASSIGN ? "Set" : "Added", buf);
2874 return true;
2875 }
2876 case TK_A_NAME: {
2877 char buf[UDEV_PATH_SIZE];
2878
2879 if (event->name_final)
2880 return log_event_final_set(event, token);
2881
2882 if (token->op == OP_ASSIGN_FINAL)
2883 event->name_final = true;
2884
2885 if (sd_device_get_ifindex(dev, NULL) < 0) {
2886 log_event_warning(event, token, "Only network interfaces can be renamed, ignoring.");
2887 return true;
2888 }
2889
2890 if (!apply_format_value(event, token, buf, sizeof(buf), "network interface name"))
2891 return true;
2892
2893 if (IN_SET(event->esc, ESCAPE_UNSET, ESCAPE_REPLACE))
2894 udev_replace_ifname(event, token, buf);
2895
2896 r = free_and_strdup_warn(&event->name, buf);
2897 if (r < 0)
2898 return r;
2899
2900 log_event_debug(event, token, "Set network interface name: %s", event->name);
2901 return true;
2902 }
2903 case TK_A_DEVLINK: {
2904 char buf[UDEV_PATH_SIZE];
2905
2906 if (event->devlink_final)
2907 return log_event_final_set(event, token);
2908
2909 if (sd_device_get_devnum(dev, NULL) < 0) {
2910 log_event_debug(event, token, "Device does not have device node, ignoring to manage device node symlink.");
2911 return true;
2912 }
2913
2914 if (token->op == OP_ASSIGN_FINAL)
2915 event->devlink_final = true;
2916
2917 if (IN_SET(token->op, OP_ASSIGN, OP_ASSIGN_FINAL))
2918 device_cleanup_devlinks(dev);
2919
2920 if (!apply_format_full(event, token, token->value, buf, sizeof(buf),
2921 /* replace_whitespace = */ event->esc != ESCAPE_NONE,
2922 "symbolic link path"))
2923 return true;
2924
2925 /* By default or string_escape=none, allow multiple symlinks separated by spaces. */
2926 if (event->esc == ESCAPE_UNSET)
2927 udev_replace_chars_and_log(event, token, buf, /* allow = */ "/ ", "device node symlink");
2928 else if (event->esc == ESCAPE_REPLACE)
2929 udev_replace_chars_and_log(event, token, buf, /* allow = */ "/", "device node symlink");
2930
2931 for (const char *p = buf;;) {
2932 _cleanup_free_ char *path = NULL;
2933
2934 r = extract_first_word(&p, &path, NULL, EXTRACT_RETAIN_ESCAPE);
2935 if (r == -ENOMEM)
2936 return log_oom();
2937 if (r < 0) {
2938 log_warning_errno(r, "Failed to extract first path in device node symlinks, ignoring: %m");
2939 return true;
2940 }
2941 if (r == 0)
2942 return true;
2943
2944 if (token->op == OP_REMOVE) {
2945 r = device_remove_devlink(dev, path);
2946 if (r == -ENOMEM)
2947 return log_oom();
2948 if (r < 0)
2949 log_event_warning_errno(event, token, r, "Failed to remove device node symlink \"%s\", ignoring: %m", path);
2950 else if (r > 0)
2951 log_event_debug(event, token, "Removed device node symlink \"%s\"", path);
2952 } else {
2953 r = device_add_devlink(dev, path);
2954 if (r == -ENOMEM)
2955 return log_oom();
2956 if (r < 0)
2957 log_event_warning_errno(event, token, r, "Failed to add device node symlink \"%s\", ignoring: %m", path);
2958 else if (r > 0)
2959 log_event_debug(event, token, "Added device node symlink \"%s\".", path);
2960 }
2961 }
2962 assert_not_reached();
2963 }
2964 case TK_A_ATTR: {
2965 char buf[UDEV_PATH_SIZE], value[UDEV_NAME_SIZE];
2966 const char *key = token->data;
2967
2968 /* First, try to resolve "[<SUBSYSTEM>/<KERNEL>]<attribute>" format. */
2969 r = udev_resolve_subsys_kernel(key, buf, sizeof(buf), false);
2970 if (r == -ENOMEM)
2971 return log_oom();
2972 if (ERRNO_IS_NEG_DEVICE_ABSENT(r)) {
2973 log_event_warning_errno(event, token, r, "Failed to resolve sysfs attribute \"%s\", ignoring: %m", key);
2974 return true;
2975 }
2976 if (r < 0) {
2977 /* If not, make the path to sysfs attribute absolute, to make '*' resolvable by attr_subst_subdir(). */
2978 const char *syspath;
2979 r = sd_device_get_syspath(dev, &syspath);
2980 if (r < 0)
2981 return log_event_error_errno(event, token, r, "Failed to get syspath: %m");
2982
2983 bool truncated;
2984 strscpyl_full(buf, sizeof(buf), &truncated, syspath, "/", key, NULL);
2985 if (truncated) {
2986 log_event_warning(event, token,
2987 "The path to the attribute \"%s/%s\" is too long, refusing to set the attribute.",
2988 syspath, key);
2989 return true;
2990 }
2991
2992 /* Resolve '*' in the path. */
2993 r = attr_subst_subdir(buf);
2994 if (r < 0) {
2995 log_event_error_errno(event, token, r, "Could not find file matches \"%s\", ignoring: %m", buf);
2996 return true;
2997 }
2998 }
2999
3000 /* Then, make the path relative again. This also checks if the path being inside of the sysfs. */
3001 _cleanup_free_ char *resolved = NULL;
3002 _cleanup_close_ int fd = -EBADF;
3003 r = device_chase(dev, buf, /* flags = */ 0, &resolved, &fd);
3004 if (r < 0) {
3005 log_event_error_errno(event, token, r, "Could not chase sysfs attribute \"%s\", ignoring: %m", buf);
3006 return true;
3007 }
3008
3009 /* Apply formatting to the value. */
3010 if (!apply_format_value(event, token, value, sizeof(value), "attribute value"))
3011 return true;
3012
3013 if (EVENT_MODE_DESTRUCTIVE(event)) {
3014 log_event_debug(event, token, "Writing \"%s\" to sysfs attribute \"%s\".", value, resolved);
3015 r = sd_device_set_sysattr_value(dev, resolved, value);
3016 if (r < 0)
3017 log_event_error_errno(event, token, r, "Failed to write \"%s\" to sysfs attribute \"%s\", ignoring: %m", value, resolved);
3018 else {
3019 event_cache_written_sysattr(event, resolved, value);
3020 log_event_done(event, token);
3021 }
3022 } else {
3023 log_event_debug(event, token, "Running in test mode, skipping writing \"%s\" to sysfs attribute \"%s\".", value, resolved);
3024
3025 /* We assume the attribute is writable if the path points to a regular file, and cache
3026 * the value to make it shown by OPTIONS="dump" or obtained by later ATTR match token. */
3027 r = fd_verify_regular(fd);
3028 if (r < 0 && !ERRNO_IS_NEG_PRIVILEGE(r))
3029 log_event_error_errno(event, token, r, "Failed to verify sysfs attribute \"%s\" is a regular file: %m", resolved);
3030 else {
3031 event_cache_written_sysattr(event, resolved, value);
3032
3033 _cleanup_free_ char *copied = strdup(value);
3034 if (!copied)
3035 return log_oom();
3036
3037 r = device_cache_sysattr_value(dev, resolved, value, /* error = */ 0);
3038 if (r < 0)
3039 log_event_warning_errno(event, token, r, "Failed to cache sysfs attribute \"%s\", ignoring: %m", resolved);
3040 else if (r > 0) {
3041 TAKE_PTR(resolved);
3042 TAKE_PTR(copied);
3043 }
3044 }
3045 }
3046 return true;
3047 }
3048 case TK_A_SYSCTL: {
3049 char buf[UDEV_PATH_SIZE], value[UDEV_NAME_SIZE];
3050
3051 if (!apply_format_attr(event, token, buf, sizeof(buf), "sysctl entry name"))
3052 return true;
3053
3054 if (!apply_format_value(event, token, value, sizeof(value), "sysctl value"))
3055 return true;
3056
3057 sysctl_normalize(buf);
3058
3059 if (EVENT_MODE_DESTRUCTIVE(event)) {
3060 log_event_debug(event, token, "Writing \"%s\" to sysctl entry \"%s\".", value, buf);
3061 r = sysctl_write(buf, value);
3062 if (r < 0)
3063 log_event_error_errno(event, token, r, "Failed to write \"%s\" to sysctl entry \"%s\", ignoring: %m", value, buf);
3064 else {
3065 event_cache_written_sysctl(event, buf, value);
3066 log_event_done(event, token);
3067 }
3068 } else {
3069 log_event_debug(event, token, "Running in test mode, skipping writing \"%s\" to sysctl entry \"%s\".", value, buf);
3070
3071 _cleanup_free_ char *path = path_join("/proc/sys/", buf);
3072 if (!path)
3073 return log_oom();
3074
3075 r = verify_regular_at(AT_FDCWD, path, /* follow = */ true);
3076 if (r < 0 && !ERRNO_IS_NEG_PRIVILEGE(r))
3077 log_event_error_errno(event, token, r, "Failed to verify sysctl entry \"%s\" is a regular file: %m", buf);
3078 else
3079 event_cache_written_sysctl(event, buf, value);
3080 }
3081 return true;
3082 }
3083 case TK_A_RUN_BUILTIN:
3084 case TK_A_RUN_PROGRAM: {
3085 _cleanup_free_ char *cmd = NULL;
3086 char buf[UDEV_LINE_SIZE];
3087
3088 if (event->run_final)
3089 return log_event_final_set(event, token);
3090
3091 if (token->op == OP_ASSIGN_FINAL)
3092 event->run_final = true;
3093
3094 if (IN_SET(token->op, OP_ASSIGN, OP_ASSIGN_FINAL))
3095 ordered_hashmap_clear(event->run_list);
3096
3097 if (!apply_format_value(event, token, buf, sizeof(buf), "command"))
3098 return true;
3099
3100 cmd = strdup(buf);
3101 if (!cmd)
3102 return log_oom();
3103
3104 r = ordered_hashmap_ensure_put(&event->run_list, &trivial_hash_ops_free, cmd, token->data);
3105 if (r < 0)
3106 return log_event_error_errno(event, token, r, "Failed to store command \"%s\": %m", cmd);
3107
3108 log_event_debug(event, token, "Set command: %s", cmd);
3109 TAKE_PTR(cmd);
3110 return true;
3111 }
3112 case TK_A_OPTIONS_STATIC_NODE:
3113 /* do nothing for events. */
3114 return true;
3115
3116 default:
3117 assert_not_reached();
3118 }
3119
3120 assert_not_reached();
3121 }
3122
3123 static int udev_rule_apply_parent_token_to_event(UdevRuleToken *head_token, UdevEvent *event) {
3124 int r;
3125
3126 assert(head_token);
3127 assert(token_is_for_parents(head_token));
3128 assert(event);
3129
3130 UdevRuleLine *line = head_token->rule_line;
3131 if (event->trace) {
3132 _cleanup_free_ char *joined = NULL;
3133
3134 LIST_FOREACH(tokens, token, head_token)
3135 if (token_is_for_parents(token))
3136 (void) strextend_with_separator(&joined, ", ", token->token_str);
3137 else
3138 break;
3139
3140 log_event_line(event, line, "Checking conditions for parent devices (including self): %s", strna(joined));
3141 }
3142
3143 event->dev_parent = ASSERT_PTR(event->dev);
3144
3145 for (;;) {
3146 LIST_FOREACH(tokens, token, head_token) {
3147 if (!token_is_for_parents(token)) {
3148 r = 1; /* avoid false maybe-uninitialized warning */
3149 break; /* All parent tokens match. */
3150 }
3151
3152 r = udev_rule_apply_token_to_event(token, event->dev_parent, event);
3153 if (r < 0)
3154 return r;
3155 if (r == 0)
3156 break;
3157 }
3158 if (r > 0) {
3159 if (event->trace) {
3160 const char *s = NULL;
3161 (void) sd_device_get_syspath(event->dev_parent, &s);
3162 log_event_line(event, line, "Parent device \"%s\" passed all parent conditions.", strna(s));
3163 }
3164 return true;
3165 }
3166
3167 if (sd_device_get_parent(event->dev_parent, &event->dev_parent) < 0) {
3168 event->dev_parent = NULL;
3169 log_event_line(event, line, "No parent device passed parent conditions.");
3170 return false;
3171 }
3172 }
3173 }
3174
3175 static int udev_rule_apply_line_to_event(
3176 UdevRuleLine *line,
3177 UdevEvent *event,
3178 UdevRuleLine **next_line) {
3179
3180 UdevRuleLineType mask = LINE_HAS_GOTO | LINE_UPDATE_SOMETHING;
3181 bool parents_done = false;
3182 sd_device_action_t action;
3183 int r;
3184
3185 assert(line);
3186 assert(event);
3187 assert(next_line);
3188
3189 r = sd_device_get_action(event->dev, &action);
3190 if (r < 0)
3191 return r;
3192
3193 if (action != SD_DEVICE_REMOVE) {
3194 if (sd_device_get_devnum(event->dev, NULL) >= 0)
3195 mask |= LINE_HAS_DEVLINK;
3196
3197 if (sd_device_get_ifindex(event->dev, NULL) >= 0)
3198 mask |= LINE_HAS_NAME;
3199 }
3200
3201 if ((line->type & mask) == 0)
3202 return 0;
3203
3204 event->esc = ESCAPE_UNSET;
3205
3206 DEVICE_TRACE_POINT(rules_apply_line, event->dev, line->rule_file->filename, line->line_number);
3207
3208 LIST_FOREACH(tokens, token, line->tokens) {
3209 if (token_is_for_parents(token)) {
3210 if (parents_done)
3211 continue;
3212
3213 r = udev_rule_apply_parent_token_to_event(token, event);
3214 if (r <= 0)
3215 return r;
3216
3217 parents_done = true;
3218 continue;
3219 }
3220
3221 r = udev_rule_apply_token_to_event(token, event->dev, event);
3222 if (r <= 0)
3223 return r;
3224 }
3225
3226 if (line->goto_line) {
3227 log_event_line(event, line, "GOTO=%s", strna(line->goto_label));
3228 *next_line = line->goto_line; /* update next_line only when the line has GOTO token. */
3229 }
3230
3231 return 0;
3232 }
3233
3234 int udev_rules_apply_to_event(UdevRules *rules, UdevEvent *event) {
3235 int r;
3236
3237 assert(rules);
3238 assert(event);
3239
3240 LIST_FOREACH(rule_files, file, rules->rule_files)
3241 LIST_FOREACH_WITH_NEXT(rule_lines, line, next_line, file->rule_lines) {
3242 r = udev_rule_apply_line_to_event(line, event, &next_line);
3243 if (r < 0)
3244 return r;
3245 }
3246
3247 return 0;
3248 }
3249
3250 static int udev_rule_line_apply_static_dev_perms(UdevRuleLine *rule_line) {
3251 _cleanup_strv_free_ char **tags = NULL;
3252 uid_t uid = UID_INVALID;
3253 gid_t gid = GID_INVALID;
3254 mode_t mode = MODE_INVALID;
3255 int r;
3256
3257 assert(rule_line);
3258
3259 if (!FLAGS_SET(rule_line->type, LINE_HAS_STATIC_NODE))
3260 return 0;
3261
3262 LIST_FOREACH(tokens, token, rule_line->tokens)
3263 if (token->type == TK_A_OWNER_ID)
3264 uid = PTR_TO_UID(token->data);
3265 else if (token->type == TK_A_GROUP_ID)
3266 gid = PTR_TO_GID(token->data);
3267 else if (token->type == TK_A_MODE_ID)
3268 mode = PTR_TO_MODE(token->data);
3269 else if (token->type == TK_A_TAG) {
3270 r = strv_extend(&tags, token->value);
3271 if (r < 0)
3272 return log_oom();
3273 } else if (token->type == TK_A_OPTIONS_STATIC_NODE) {
3274 r = static_node_apply_permissions(token->value, mode, uid, gid, tags);
3275 if (r < 0)
3276 return r;
3277 }
3278
3279 return 0;
3280 }
3281
3282 int udev_rules_apply_static_dev_perms(UdevRules *rules) {
3283 int r;
3284
3285 assert(rules);
3286
3287 LIST_FOREACH(rule_files, file, rules->rule_files)
3288 LIST_FOREACH(rule_lines, line, file->rule_lines) {
3289 r = udev_rule_line_apply_static_dev_perms(line);
3290 if (r < 0)
3291 return r;
3292 }
3293
3294 return 0;
3295 }
3296
3297 static const char* const resolve_name_timing_table[_RESOLVE_NAME_TIMING_MAX] = {
3298 [RESOLVE_NAME_NEVER] = "never",
3299 [RESOLVE_NAME_LATE] = "late",
3300 [RESOLVE_NAME_EARLY] = "early",
3301 };
3302
3303 DEFINE_STRING_TABLE_LOOKUP(resolve_name_timing, ResolveNameTiming);