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