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