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