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