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 "fd-util.h"
13 #include "fileio.h"
14 #include "format-util.h"
15 #include "fs-util.h"
16 #include "glob-util.h"
17 #include "list.h"
18 #include "mkdir.h"
19 #include "netif-naming-scheme.h"
20 #include "nulstr-util.h"
21 #include "parse-util.h"
22 #include "path-util.h"
23 #include "proc-cmdline.h"
24 #include "stat-util.h"
25 #include "strv.h"
26 #include "strxcpyx.h"
27 #include "sysctl-util.h"
28 #include "syslog-util.h"
29 #include "udev-builtin.h"
30 #include "udev-event.h"
31 #include "udev-netlink.h"
32 #include "udev-node.h"
33 #include "udev-rules.h"
34 #include "udev-util.h"
35 #include "user-util.h"
36 #include "virt.h"
37
38 #define RULES_DIRS (const char* const*) CONF_PATHS_STRV("udev/rules.d")
39
40 typedef enum {
41 OP_MATCH, /* == */
42 OP_NOMATCH, /* != */
43 OP_ADD, /* += */
44 OP_REMOVE, /* -= */
45 OP_ASSIGN, /* = */
46 OP_ASSIGN_FINAL, /* := */
47 _OP_TYPE_MAX,
48 _OP_TYPE_INVALID = -EINVAL,
49 } UdevRuleOperatorType;
50
51 typedef enum {
52 MATCH_TYPE_EMPTY, /* empty string */
53 MATCH_TYPE_PLAIN, /* no special characters */
54 MATCH_TYPE_PLAIN_WITH_EMPTY, /* no special characters with empty string, e.g., "|foo" */
55 MATCH_TYPE_GLOB, /* shell globs ?,*,[] */
56 MATCH_TYPE_GLOB_WITH_EMPTY, /* shell globs ?,*,[] with empty string, e.g., "|foo*" */
57 MATCH_TYPE_SUBSYSTEM, /* "subsystem", "bus", or "class" */
58 _MATCH_TYPE_MAX,
59 _MATCH_TYPE_INVALID = -EINVAL,
60 } UdevRuleMatchType;
61
62 typedef enum {
63 SUBST_TYPE_PLAIN, /* no substitution */
64 SUBST_TYPE_FORMAT, /* % or $ */
65 SUBST_TYPE_SUBSYS, /* "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
66 _SUBST_TYPE_MAX,
67 _SUBST_TYPE_INVALID = -EINVAL,
68 } UdevRuleSubstituteType;
69
70 typedef enum {
71 /* lvalues which take match or nomatch operator */
72 TK_M_ACTION, /* string, device_get_action() */
73 TK_M_DEVPATH, /* path, sd_device_get_devpath() */
74 TK_M_KERNEL, /* string, sd_device_get_sysname() */
75 TK_M_DEVLINK, /* strv, sd_device_get_devlink_first(), sd_device_get_devlink_next() */
76 TK_M_NAME, /* string, name of network interface */
77 TK_M_ENV, /* string, device property, takes key through attribute */
78 TK_M_CONST, /* string, system-specific hard-coded constant */
79 TK_M_TAG, /* strv, sd_device_get_tag_first(), sd_device_get_tag_next() */
80 TK_M_SUBSYSTEM, /* string, sd_device_get_subsystem() */
81 TK_M_DRIVER, /* string, sd_device_get_driver() */
82 TK_M_ATTR, /* string, takes filename through attribute, sd_device_get_sysattr_value(), udev_resolve_subsys_kernel(), etc. */
83 TK_M_SYSCTL, /* string, takes kernel parameter through attribute */
84
85 /* matches parent parameters */
86 TK_M_PARENTS_KERNEL, /* string */
87 TK_M_PARENTS_SUBSYSTEM, /* string */
88 TK_M_PARENTS_DRIVER, /* string */
89 TK_M_PARENTS_ATTR, /* string */
90 TK_M_PARENTS_TAG, /* strv */
91
92 TK_M_TEST, /* path, optionally mode_t can be specified by attribute, test the existence of a file */
93 TK_M_PROGRAM, /* string, execute a program */
94 TK_M_IMPORT_FILE, /* path */
95 TK_M_IMPORT_PROGRAM, /* string, import properties from the result of program */
96 TK_M_IMPORT_BUILTIN, /* string, import properties from the result of built-in command */
97 TK_M_IMPORT_DB, /* string, import properties from database */
98 TK_M_IMPORT_CMDLINE, /* string, kernel command line */
99 TK_M_IMPORT_PARENT, /* string, parent property */
100 TK_M_RESULT, /* string, result of TK_M_PROGRAM */
101
102 #define _TK_M_MAX (TK_M_RESULT + 1)
103 #define _TK_A_MIN _TK_M_MAX
104
105 /* lvalues which take one of assign operators */
106 TK_A_OPTIONS_STRING_ESCAPE_NONE, /* no argument */
107 TK_A_OPTIONS_STRING_ESCAPE_REPLACE, /* no argument */
108 TK_A_OPTIONS_DB_PERSIST, /* no argument */
109 TK_A_OPTIONS_INOTIFY_WATCH, /* boolean */
110 TK_A_OPTIONS_DEVLINK_PRIORITY, /* int */
111 TK_A_OPTIONS_LOG_LEVEL, /* string of log level or "reset" */
112 TK_A_OWNER, /* user name */
113 TK_A_GROUP, /* group name */
114 TK_A_MODE, /* mode string */
115 TK_A_OWNER_ID, /* uid_t */
116 TK_A_GROUP_ID, /* gid_t */
117 TK_A_MODE_ID, /* mode_t */
118 TK_A_TAG, /* string */
119 TK_A_OPTIONS_STATIC_NODE, /* device path, /dev/... */
120 TK_A_SECLABEL, /* string with attribute */
121 TK_A_ENV, /* string with attribute */
122 TK_A_NAME, /* ifname */
123 TK_A_DEVLINK, /* string */
124 TK_A_ATTR, /* string with attribute */
125 TK_A_SYSCTL, /* string with attribute */
126 TK_A_RUN_BUILTIN, /* string */
127 TK_A_RUN_PROGRAM, /* string */
128
129 _TK_TYPE_MAX,
130 _TK_TYPE_INVALID = -EINVAL,
131 } UdevRuleTokenType;
132
133 typedef enum {
134 LINE_HAS_NAME = 1 << 0, /* has NAME= */
135 LINE_HAS_DEVLINK = 1 << 1, /* has SYMLINK=, OWNER=, GROUP= or MODE= */
136 LINE_HAS_STATIC_NODE = 1 << 2, /* has OPTIONS=static_node */
137 LINE_HAS_GOTO = 1 << 3, /* has GOTO= */
138 LINE_HAS_LABEL = 1 << 4, /* has LABEL= */
139 LINE_UPDATE_SOMETHING = 1 << 5, /* has other TK_A_* or TK_M_IMPORT tokens */
140 } UdevRuleLineType;
141
142 typedef struct UdevRuleFile UdevRuleFile;
143 typedef struct UdevRuleLine UdevRuleLine;
144 typedef struct UdevRuleToken UdevRuleToken;
145
146 struct UdevRuleToken {
147 UdevRuleTokenType type:8;
148 UdevRuleOperatorType op:8;
149 UdevRuleMatchType match_type:8;
150 UdevRuleSubstituteType attr_subst_type:7;
151 bool attr_match_remove_trailing_whitespace:1;
152 const char *value;
153 void *data;
154 LIST_FIELDS(UdevRuleToken, tokens);
155 };
156
157 struct UdevRuleLine {
158 char *line;
159 unsigned line_number;
160 UdevRuleLineType type;
161
162 const char *label;
163 const char *goto_label;
164 UdevRuleLine *goto_line;
165
166 UdevRuleFile *rule_file;
167 UdevRuleToken *current_token;
168 LIST_HEAD(UdevRuleToken, tokens);
169 LIST_FIELDS(UdevRuleLine, rule_lines);
170 };
171
172 struct UdevRuleFile {
173 char *filename;
174 UdevRuleLine *current_line;
175 LIST_HEAD(UdevRuleLine, rule_lines);
176 LIST_FIELDS(UdevRuleFile, rule_files);
177 };
178
179 struct UdevRules {
180 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
log_unknown_owner(sd_device * dev,UdevRules * rules,int error,const char * entity,const char * name)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
udev_rule_token_free(UdevRuleToken * token)266 static void udev_rule_token_free(UdevRuleToken *token) {
267 free(token);
268 }
269
udev_rule_line_clear_tokens(UdevRuleLine * rule_line)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
udev_rule_line_free(UdevRuleLine * rule_line)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
udev_rule_file_free(UdevRuleFile * rule_file)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
udev_rules_free(UdevRules * rules)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
rule_resolve_user(UdevRules * rules,const char * name,uid_t * ret)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
rule_resolve_group(UdevRules * rules,const char * name,gid_t * ret)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
rule_get_substitution_type(const char * str)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
rule_line_append_token(UdevRuleLine * rule_line,UdevRuleToken * token)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
rule_line_add_token(UdevRuleLine * rule_line,UdevRuleTokenType type,UdevRuleOperatorType op,char * value,void * data)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
check_value_format_and_warn(UdevRules * rules,const char * key,const char * value,bool nonempty)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
check_attr_format_and_warn(UdevRules * rules,const char * key,const char * value)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
parse_token(UdevRules * rules,const char * key,char * attr,UdevRuleOperatorType op,char * value)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
parse_operator(const char * op)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
parse_line(char ** line,char ** ret_key,char ** ret_attr,UdevRuleOperatorType * ret_op,char ** ret_value)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
sort_tokens(UdevRuleLine * rule_line)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
rule_add_line(UdevRules * rules,const char * line_str,unsigned line_nr)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
rule_resolve_goto(UdevRuleFile * rule_file)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
udev_rules_parse_file(UdevRules * rules,const char * filename)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
udev_rules_new(ResolveNameTiming resolve_name_timing)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
udev_rules_load(UdevRules ** ret_rules,ResolveNameTiming resolve_name_timing)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 int r;
1296
1297 rules = udev_rules_new(resolve_name_timing);
1298 if (!rules)
1299 return -ENOMEM;
1300
1301 (void) udev_rules_check_timestamp(rules);
1302
1303 r = conf_files_list_strv(&files, ".rules", NULL, 0, RULES_DIRS);
1304 if (r < 0)
1305 return log_debug_errno(r, "Failed to enumerate rules files: %m");
1306
1307 STRV_FOREACH(f, files) {
1308 r = udev_rules_parse_file(rules, *f);
1309 if (r < 0)
1310 log_debug_errno(r, "Failed to read rules file %s, ignoring: %m", *f);
1311 }
1312
1313 *ret_rules = TAKE_PTR(rules);
1314 return 0;
1315 }
1316
udev_rules_check_timestamp(UdevRules * rules)1317 bool udev_rules_check_timestamp(UdevRules *rules) {
1318 if (!rules)
1319 return false;
1320
1321 return paths_check_timestamp(RULES_DIRS, &rules->dirs_ts_usec, true);
1322 }
1323
token_match_string(UdevRuleToken * token,const char * str)1324 static bool token_match_string(UdevRuleToken *token, const char *str) {
1325 const char *i, *value;
1326 bool match = false;
1327
1328 assert(token);
1329 assert(token->value);
1330 assert(token->type < _TK_M_MAX);
1331
1332 str = strempty(str);
1333 value = token->value;
1334
1335 switch (token->match_type) {
1336 case MATCH_TYPE_EMPTY:
1337 match = isempty(str);
1338 break;
1339 case MATCH_TYPE_SUBSYSTEM:
1340 match = STR_IN_SET(str, "subsystem", "class", "bus");
1341 break;
1342 case MATCH_TYPE_PLAIN_WITH_EMPTY:
1343 if (isempty(str)) {
1344 match = true;
1345 break;
1346 }
1347 _fallthrough_;
1348 case MATCH_TYPE_PLAIN:
1349 NULSTR_FOREACH(i, value)
1350 if (streq(i, str)) {
1351 match = true;
1352 break;
1353 }
1354 break;
1355 case MATCH_TYPE_GLOB_WITH_EMPTY:
1356 if (isempty(str)) {
1357 match = true;
1358 break;
1359 }
1360 _fallthrough_;
1361 case MATCH_TYPE_GLOB:
1362 NULSTR_FOREACH(i, value)
1363 if ((fnmatch(i, str, 0) == 0)) {
1364 match = true;
1365 break;
1366 }
1367 break;
1368 default:
1369 assert_not_reached();
1370 }
1371
1372 return token->op == (match ? OP_MATCH : OP_NOMATCH);
1373 }
1374
token_match_attr(UdevRules * rules,UdevRuleToken * token,sd_device * dev,UdevEvent * event)1375 static bool token_match_attr(UdevRules *rules, UdevRuleToken *token, sd_device *dev, UdevEvent *event) {
1376 char nbuf[UDEV_NAME_SIZE], vbuf[UDEV_NAME_SIZE];
1377 const char *name, *value;
1378 bool truncated;
1379
1380 assert(rules);
1381 assert(token);
1382 assert(IN_SET(token->type, TK_M_ATTR, TK_M_PARENTS_ATTR));
1383 assert(dev);
1384 assert(event);
1385
1386 name = token->data;
1387
1388 switch (token->attr_subst_type) {
1389 case SUBST_TYPE_FORMAT:
1390 (void) udev_event_apply_format(event, name, nbuf, sizeof(nbuf), false, &truncated);
1391 if (truncated) {
1392 log_rule_debug(dev, rules,
1393 "The sysfs attribute name '%s' is truncated while substituting into '%s', "
1394 "assuming the %s key does not match.", nbuf, name,
1395 token->type == TK_M_ATTR ? "ATTR" : "ATTRS");
1396 return false;
1397 }
1398
1399 name = nbuf;
1400 _fallthrough_;
1401 case SUBST_TYPE_PLAIN:
1402 if (device_get_sysattr_value_maybe_from_netlink(dev, &event->rtnl, name, &value) < 0)
1403 return false;
1404 break;
1405 case SUBST_TYPE_SUBSYS:
1406 if (udev_resolve_subsys_kernel(name, vbuf, sizeof(vbuf), true) < 0)
1407 return false;
1408 value = vbuf;
1409 break;
1410 default:
1411 assert_not_reached();
1412 }
1413
1414 /* remove trailing whitespace, if not asked to match for it */
1415 if (token->attr_match_remove_trailing_whitespace) {
1416 if (value != vbuf) {
1417 strscpy(vbuf, sizeof(vbuf), value);
1418 value = vbuf;
1419 }
1420
1421 delete_trailing_chars(vbuf, NULL);
1422 }
1423
1424 return token_match_string(token, value);
1425 }
1426
get_property_from_string(char * line,char ** ret_key,char ** ret_value)1427 static int get_property_from_string(char *line, char **ret_key, char **ret_value) {
1428 char *key, *val;
1429 size_t len;
1430
1431 assert(line);
1432 assert(ret_key);
1433 assert(ret_value);
1434
1435 /* find key */
1436 key = skip_leading_chars(line, NULL);
1437
1438 /* comment or empty line */
1439 if (IN_SET(key[0], '#', '\0')) {
1440 *ret_key = *ret_value = NULL;
1441 return 0;
1442 }
1443
1444 /* split key/value */
1445 val = strchr(key, '=');
1446 if (!val)
1447 return -EINVAL;
1448 *val++ = '\0';
1449
1450 key = strstrip(key);
1451 if (isempty(key))
1452 return -EINVAL;
1453
1454 val = strstrip(val);
1455 if (isempty(val))
1456 return -EINVAL;
1457
1458 /* unquote */
1459 if (IN_SET(val[0], '"', '\'')) {
1460 len = strlen(val);
1461 if (len == 1 || val[len-1] != val[0])
1462 return -EINVAL;
1463 val[len-1] = '\0';
1464 val++;
1465 }
1466
1467 *ret_key = key;
1468 *ret_value = val;
1469 return 1;
1470 }
1471
import_parent_into_properties(sd_device * dev,const char * filter)1472 static int import_parent_into_properties(sd_device *dev, const char *filter) {
1473 const char *key, *val;
1474 sd_device *parent;
1475 int r;
1476
1477 assert(dev);
1478 assert(filter);
1479
1480 r = sd_device_get_parent(dev, &parent);
1481 if (r == -ENOENT)
1482 return 0;
1483 if (r < 0)
1484 return r;
1485
1486 FOREACH_DEVICE_PROPERTY(parent, key, val) {
1487 if (fnmatch(filter, key, 0) != 0)
1488 continue;
1489 r = device_add_property(dev, key, val);
1490 if (r < 0)
1491 return r;
1492 }
1493
1494 return 1;
1495 }
1496
attr_subst_subdir(char attr[static UDEV_PATH_SIZE])1497 static int attr_subst_subdir(char attr[static UDEV_PATH_SIZE]) {
1498 _cleanup_closedir_ DIR *dir = NULL;
1499 char buf[UDEV_PATH_SIZE], *p;
1500 const char *tail;
1501 size_t len, size;
1502 bool truncated;
1503
1504 assert(attr);
1505
1506 tail = strstr(attr, "/*/");
1507 if (!tail)
1508 return 0;
1509
1510 len = tail - attr + 1; /* include slash at the end */
1511 tail += 2; /* include slash at the beginning */
1512
1513 p = buf;
1514 size = sizeof(buf);
1515 size -= strnpcpy_full(&p, size, attr, len, &truncated);
1516 if (truncated)
1517 return -ENOENT;
1518
1519 dir = opendir(buf);
1520 if (!dir)
1521 return -errno;
1522
1523 FOREACH_DIRENT_ALL(de, dir, break) {
1524 if (de->d_name[0] == '.')
1525 continue;
1526
1527 strscpyl_full(p, size, &truncated, de->d_name, tail, NULL);
1528 if (truncated)
1529 continue;
1530
1531 if (faccessat(dirfd(dir), p, F_OK, 0) < 0)
1532 continue;
1533
1534 strcpy(attr, buf);
1535 return 0;
1536 }
1537
1538 return -ENOENT;
1539 }
1540
udev_rule_apply_token_to_event(UdevRules * rules,sd_device * dev,UdevEvent * event,usec_t timeout_usec,int timeout_signal,Hashmap * properties_list)1541 static int udev_rule_apply_token_to_event(
1542 UdevRules *rules,
1543 sd_device *dev,
1544 UdevEvent *event,
1545 usec_t timeout_usec,
1546 int timeout_signal,
1547 Hashmap *properties_list) {
1548
1549 UdevRuleToken *token;
1550 int r;
1551
1552 assert(rules);
1553 assert(dev);
1554 assert(event);
1555
1556 /* This returns the following values:
1557 * 0 on the current token does not match the event,
1558 * 1 on the current token matches the event, and
1559 * negative errno on some critical errors. */
1560
1561 token = rules->current_file->current_line->current_token;
1562
1563 switch (token->type) {
1564 case TK_M_ACTION: {
1565 sd_device_action_t a;
1566
1567 r = sd_device_get_action(dev, &a);
1568 if (r < 0)
1569 return log_rule_error_errno(dev, rules, r, "Failed to get uevent action type: %m");
1570
1571 return token_match_string(token, device_action_to_string(a));
1572 }
1573 case TK_M_DEVPATH: {
1574 const char *val;
1575
1576 r = sd_device_get_devpath(dev, &val);
1577 if (r < 0)
1578 return log_rule_error_errno(dev, rules, r, "Failed to get devpath: %m");
1579
1580 return token_match_string(token, val);
1581 }
1582 case TK_M_KERNEL:
1583 case TK_M_PARENTS_KERNEL: {
1584 const char *val;
1585
1586 r = sd_device_get_sysname(dev, &val);
1587 if (r < 0)
1588 return log_rule_error_errno(dev, rules, r, "Failed to get sysname: %m");
1589
1590 return token_match_string(token, val);
1591 }
1592 case TK_M_DEVLINK: {
1593 const char *val;
1594
1595 FOREACH_DEVICE_DEVLINK(dev, val)
1596 if (token_match_string(token, strempty(startswith(val, "/dev/"))))
1597 return token->op == OP_MATCH;
1598 return token->op == OP_NOMATCH;
1599 }
1600 case TK_M_NAME:
1601 return token_match_string(token, event->name);
1602 case TK_M_ENV: {
1603 const char *val;
1604
1605 if (sd_device_get_property_value(dev, token->data, &val) < 0)
1606 val = hashmap_get(properties_list, token->data);
1607
1608 return token_match_string(token, val);
1609 }
1610 case TK_M_CONST: {
1611 const char *val, *k = token->data;
1612
1613 if (streq(k, "arch"))
1614 val = architecture_to_string(uname_architecture());
1615 else if (streq(k, "virt"))
1616 val = virtualization_to_string(detect_virtualization());
1617 else
1618 assert_not_reached();
1619 return token_match_string(token, val);
1620 }
1621 case TK_M_TAG:
1622 case TK_M_PARENTS_TAG: {
1623 const char *val;
1624
1625 FOREACH_DEVICE_TAG(dev, val)
1626 if (token_match_string(token, val))
1627 return token->op == OP_MATCH;
1628 return token->op == OP_NOMATCH;
1629 }
1630 case TK_M_SUBSYSTEM:
1631 case TK_M_PARENTS_SUBSYSTEM: {
1632 const char *val;
1633
1634 r = sd_device_get_subsystem(dev, &val);
1635 if (r == -ENOENT)
1636 val = NULL;
1637 else if (r < 0)
1638 return log_rule_error_errno(dev, rules, r, "Failed to get subsystem: %m");
1639
1640 return token_match_string(token, val);
1641 }
1642 case TK_M_DRIVER:
1643 case TK_M_PARENTS_DRIVER: {
1644 const char *val;
1645
1646 r = sd_device_get_driver(dev, &val);
1647 if (r == -ENOENT)
1648 val = NULL;
1649 else if (r < 0)
1650 return log_rule_error_errno(dev, rules, r, "Failed to get driver: %m");
1651
1652 return token_match_string(token, val);
1653 }
1654 case TK_M_ATTR:
1655 case TK_M_PARENTS_ATTR:
1656 return token_match_attr(rules, token, dev, event);
1657 case TK_M_SYSCTL: {
1658 _cleanup_free_ char *value = NULL;
1659 char buf[UDEV_PATH_SIZE];
1660 bool truncated;
1661
1662 (void) udev_event_apply_format(event, token->data, buf, sizeof(buf), false, &truncated);
1663 if (truncated) {
1664 log_rule_debug(dev, rules, "The sysctl entry name '%s' is truncated while substituting into '%s', "
1665 "assuming the SYSCTL key does not match.", buf, (const char*) token->data);
1666 return false;
1667 }
1668
1669 r = sysctl_read(sysctl_normalize(buf), &value);
1670 if (r < 0 && r != -ENOENT)
1671 return log_rule_error_errno(dev, rules, r, "Failed to read sysctl '%s': %m", buf);
1672
1673 return token_match_string(token, strstrip(value));
1674 }
1675 case TK_M_TEST: {
1676 mode_t mode = PTR_TO_MODE(token->data);
1677 char buf[UDEV_PATH_SIZE];
1678 struct stat statbuf;
1679 bool match, truncated;
1680
1681 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
1682 if (truncated) {
1683 log_rule_debug(dev, rules, "The file name '%s' is truncated while substituting into '%s', "
1684 "assuming the TEST key does not match", buf, token->value);
1685 return false;
1686 }
1687
1688 if (!path_is_absolute(buf) &&
1689 udev_resolve_subsys_kernel(buf, buf, sizeof(buf), false) < 0) {
1690 char tmp[UDEV_PATH_SIZE];
1691 const char *val;
1692
1693 r = sd_device_get_syspath(dev, &val);
1694 if (r < 0)
1695 return log_rule_error_errno(dev, rules, r, "Failed to get syspath: %m");
1696
1697 strscpy_full(tmp, sizeof(tmp), buf, &truncated);
1698 assert(!truncated);
1699 strscpyl_full(buf, sizeof(buf), &truncated, val, "/", tmp, NULL);
1700 if (truncated)
1701 return false;
1702 }
1703
1704 r = attr_subst_subdir(buf);
1705 if (r == -ENOENT)
1706 return token->op == OP_NOMATCH;
1707 if (r < 0)
1708 return log_rule_error_errno(dev, rules, r, "Failed to test for the existence of '%s': %m", buf);
1709
1710 if (stat(buf, &statbuf) < 0)
1711 return token->op == OP_NOMATCH;
1712
1713 if (mode == MODE_INVALID)
1714 return token->op == OP_MATCH;
1715
1716 match = (statbuf.st_mode & mode) > 0;
1717 return token->op == (match ? OP_MATCH : OP_NOMATCH);
1718 }
1719 case TK_M_PROGRAM: {
1720 char buf[UDEV_PATH_SIZE], result[UDEV_LINE_SIZE];
1721 bool truncated;
1722 size_t count;
1723
1724 event->program_result = mfree(event->program_result);
1725 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
1726 if (truncated) {
1727 log_rule_debug(dev, rules, "The command '%s' is truncated while substituting into '%s', "
1728 "assuming the PROGRAM key does not match.", buf, token->value);
1729 return false;
1730 }
1731
1732 log_rule_debug(dev, rules, "Running PROGRAM '%s'", buf);
1733
1734 r = udev_event_spawn(event, timeout_usec, timeout_signal, true, buf, result, sizeof(result), NULL);
1735 if (r != 0) {
1736 if (r < 0)
1737 log_rule_warning_errno(dev, rules, r, "Failed to execute \"%s\": %m", buf);
1738 else /* returned value is positive when program fails */
1739 log_rule_debug(dev, rules, "Command \"%s\" returned %d (error)", buf, r);
1740 return token->op == OP_NOMATCH;
1741 }
1742
1743 delete_trailing_chars(result, "\n");
1744 count = udev_replace_chars(result, UDEV_ALLOWED_CHARS_INPUT);
1745 if (count > 0)
1746 log_rule_debug(dev, rules, "Replaced %zu character(s) in result of \"%s\"",
1747 count, buf);
1748
1749 event->program_result = strdup(result);
1750 return token->op == OP_MATCH;
1751 }
1752 case TK_M_IMPORT_FILE: {
1753 _cleanup_fclose_ FILE *f = NULL;
1754 char buf[UDEV_PATH_SIZE];
1755 bool truncated;
1756
1757 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
1758 if (truncated) {
1759 log_rule_debug(dev, rules, "The file name '%s' to be imported is truncated while substituting into '%s', "
1760 "assuming the IMPORT key does not match.", buf, token->value);
1761 return false;
1762 }
1763
1764 log_rule_debug(dev, rules, "Importing properties from '%s'", buf);
1765
1766 f = fopen(buf, "re");
1767 if (!f) {
1768 if (errno != ENOENT)
1769 return log_rule_error_errno(dev, rules, errno,
1770 "Failed to open '%s': %m", buf);
1771 return token->op == OP_NOMATCH;
1772 }
1773
1774 for (;;) {
1775 _cleanup_free_ char *line = NULL;
1776 char *key, *value;
1777
1778 r = read_line(f, LONG_LINE_MAX, &line);
1779 if (r < 0) {
1780 log_rule_debug_errno(dev, rules, r,
1781 "Failed to read '%s', ignoring: %m", buf);
1782 return token->op == OP_NOMATCH;
1783 }
1784 if (r == 0)
1785 break;
1786
1787 r = get_property_from_string(line, &key, &value);
1788 if (r < 0) {
1789 log_rule_debug_errno(dev, rules, r,
1790 "Failed to parse key and value from '%s', ignoring: %m",
1791 line);
1792 continue;
1793 }
1794 if (r == 0)
1795 continue;
1796
1797 r = device_add_property(dev, key, value);
1798 if (r < 0)
1799 return log_rule_error_errno(dev, rules, r,
1800 "Failed to add property %s=%s: %m",
1801 key, value);
1802 }
1803
1804 return token->op == OP_MATCH;
1805 }
1806 case TK_M_IMPORT_PROGRAM: {
1807 _cleanup_strv_free_ char **lines = NULL;
1808 char buf[UDEV_PATH_SIZE], result[UDEV_LINE_SIZE];
1809 bool truncated;
1810
1811 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
1812 if (truncated) {
1813 log_rule_debug(dev, rules, "The command '%s' is truncated while substituting into '%s', "
1814 "assuming the IMPORT key does not match.", buf, token->value);
1815 return false;
1816 }
1817
1818 log_rule_debug(dev, rules, "Importing properties from results of '%s'", buf);
1819
1820 r = udev_event_spawn(event, timeout_usec, timeout_signal, true, buf, result, sizeof result, &truncated);
1821 if (r != 0) {
1822 if (r < 0)
1823 log_rule_warning_errno(dev, rules, r, "Failed to execute '%s', ignoring: %m", buf);
1824 else /* returned value is positive when program fails */
1825 log_rule_debug(dev, rules, "Command \"%s\" returned %d (error), ignoring", buf, r);
1826 return token->op == OP_NOMATCH;
1827 }
1828
1829 if (truncated) {
1830 bool found = false;
1831
1832 /* Drop the last line. */
1833 for (char *p = PTR_SUB1(buf + strlen(buf), buf); p; p = PTR_SUB1(p, buf))
1834 if (strchr(NEWLINE, *p)) {
1835 *p = '\0';
1836 found = true;
1837 } else if (found)
1838 break;
1839 }
1840
1841 r = strv_split_newlines_full(&lines, result, EXTRACT_RETAIN_ESCAPE);
1842 if (r == -ENOMEM)
1843 return log_oom();
1844 if (r < 0) {
1845 log_rule_warning_errno(dev, rules, r,
1846 "Failed to extract lines from result of command \"%s\", ignoring: %m", buf);
1847 return false;
1848 }
1849
1850 STRV_FOREACH(line, lines) {
1851 char *key, *value;
1852
1853 r = get_property_from_string(*line, &key, &value);
1854 if (r < 0) {
1855 log_rule_debug_errno(dev, rules, r,
1856 "Failed to parse key and value from '%s', ignoring: %m",
1857 *line);
1858 continue;
1859 }
1860 if (r == 0)
1861 continue;
1862
1863 r = device_add_property(dev, key, value);
1864 if (r < 0)
1865 return log_rule_error_errno(dev, rules, r,
1866 "Failed to add property %s=%s: %m",
1867 key, value);
1868 }
1869
1870 return token->op == OP_MATCH;
1871 }
1872 case TK_M_IMPORT_BUILTIN: {
1873 UdevBuiltinCommand cmd = PTR_TO_UDEV_BUILTIN_CMD(token->data);
1874 assert(cmd >= 0 && cmd < _UDEV_BUILTIN_MAX);
1875 unsigned mask = 1U << (int) cmd;
1876 char buf[UDEV_PATH_SIZE];
1877 bool truncated;
1878
1879 if (udev_builtin_run_once(cmd)) {
1880 /* check if we ran already */
1881 if (event->builtin_run & mask) {
1882 log_rule_debug(dev, rules, "Skipping builtin '%s' in IMPORT key",
1883 udev_builtin_name(cmd));
1884 /* return the result from earlier run */
1885 return token->op == (event->builtin_ret & mask ? OP_NOMATCH : OP_MATCH);
1886 }
1887 /* mark as ran */
1888 event->builtin_run |= mask;
1889 }
1890
1891 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
1892 if (truncated) {
1893 log_rule_debug(dev, rules, "The builtin command '%s' is truncated while substituting into '%s', "
1894 "assuming the IMPORT key does not match", buf, token->value);
1895 return false;
1896 }
1897
1898 log_rule_debug(dev, rules, "Importing properties from results of builtin command '%s'", buf);
1899
1900 r = udev_builtin_run(dev, &event->rtnl, cmd, buf, false);
1901 if (r < 0) {
1902 /* remember failure */
1903 log_rule_debug_errno(dev, rules, r, "Failed to run builtin '%s': %m", buf);
1904 event->builtin_ret |= mask;
1905 }
1906 return token->op == (r >= 0 ? OP_MATCH : OP_NOMATCH);
1907 }
1908 case TK_M_IMPORT_DB: {
1909 const char *val;
1910
1911 if (!event->dev_db_clone)
1912 return token->op == OP_NOMATCH;
1913 r = sd_device_get_property_value(event->dev_db_clone, token->value, &val);
1914 if (r == -ENOENT)
1915 return token->op == OP_NOMATCH;
1916 if (r < 0)
1917 return log_rule_error_errno(dev, rules, r,
1918 "Failed to get property '%s' from database: %m",
1919 token->value);
1920
1921 r = device_add_property(dev, token->value, val);
1922 if (r < 0)
1923 return log_rule_error_errno(dev, rules, r, "Failed to add property '%s=%s': %m",
1924 token->value, val);
1925 return token->op == OP_MATCH;
1926 }
1927 case TK_M_IMPORT_CMDLINE: {
1928 _cleanup_free_ char *value = NULL;
1929
1930 r = proc_cmdline_get_key(token->value, PROC_CMDLINE_VALUE_OPTIONAL|PROC_CMDLINE_IGNORE_EFI_OPTIONS, &value);
1931 if (r < 0)
1932 return log_rule_error_errno(dev, rules, r,
1933 "Failed to read '%s' option from /proc/cmdline: %m",
1934 token->value);
1935 if (r == 0)
1936 return token->op == OP_NOMATCH;
1937
1938 r = device_add_property(dev, token->value, value ?: "1");
1939 if (r < 0)
1940 return log_rule_error_errno(dev, rules, r, "Failed to add property '%s=%s': %m",
1941 token->value, value ?: "1");
1942 return token->op == OP_MATCH;
1943 }
1944 case TK_M_IMPORT_PARENT: {
1945 char buf[UDEV_PATH_SIZE];
1946 bool truncated;
1947
1948 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
1949 if (truncated) {
1950 log_rule_debug(dev, rules, "The property name '%s' is truncated while substituting into '%s', "
1951 "assuming the IMPORT key does not match.", buf, token->value);
1952 return false;
1953 }
1954
1955 r = import_parent_into_properties(dev, buf);
1956 if (r < 0)
1957 return log_rule_error_errno(dev, rules, r,
1958 "Failed to import properties '%s' from parent: %m",
1959 buf);
1960 return token->op == (r > 0 ? OP_MATCH : OP_NOMATCH);
1961 }
1962 case TK_M_RESULT:
1963 return token_match_string(token, event->program_result);
1964 case TK_A_OPTIONS_STRING_ESCAPE_NONE:
1965 event->esc = ESCAPE_NONE;
1966 break;
1967 case TK_A_OPTIONS_STRING_ESCAPE_REPLACE:
1968 event->esc = ESCAPE_REPLACE;
1969 break;
1970 case TK_A_OPTIONS_DB_PERSIST:
1971 device_set_db_persist(dev);
1972 break;
1973 case TK_A_OPTIONS_INOTIFY_WATCH:
1974 if (event->inotify_watch_final)
1975 break;
1976 if (token->op == OP_ASSIGN_FINAL)
1977 event->inotify_watch_final = true;
1978
1979 event->inotify_watch = token->data;
1980 break;
1981 case TK_A_OPTIONS_DEVLINK_PRIORITY:
1982 device_set_devlink_priority(dev, PTR_TO_INT(token->data));
1983 break;
1984 case TK_A_OPTIONS_LOG_LEVEL: {
1985 int level = PTR_TO_INT(token->data);
1986
1987 if (level < 0)
1988 level = event->default_log_level;
1989
1990 log_set_max_level(level);
1991
1992 if (level == LOG_DEBUG && !event->log_level_was_debug) {
1993 /* The log level becomes LOG_DEBUG at first time. Let's log basic information. */
1994 log_device_uevent(dev, "The log level is changed to 'debug' while processing device");
1995 event->log_level_was_debug = true;
1996 }
1997
1998 break;
1999 }
2000 case TK_A_OWNER: {
2001 char owner[UDEV_NAME_SIZE];
2002 const char *ow = owner;
2003 bool truncated;
2004
2005 if (event->owner_final)
2006 break;
2007 if (token->op == OP_ASSIGN_FINAL)
2008 event->owner_final = true;
2009
2010 (void) udev_event_apply_format(event, token->value, owner, sizeof(owner), false, &truncated);
2011 if (truncated) {
2012 log_rule_warning(dev, rules, "The user name '%s' is truncated while substituting into '%s', "
2013 "refusing to apply the OWNER key.", owner, token->value);
2014 break;
2015 }
2016
2017 r = get_user_creds(&ow, &event->uid, NULL, NULL, NULL, USER_CREDS_ALLOW_MISSING);
2018 if (r < 0)
2019 log_unknown_owner(dev, rules, r, "user", owner);
2020 else
2021 log_rule_debug(dev, rules, "OWNER %s(%u)", owner, event->uid);
2022 break;
2023 }
2024 case TK_A_GROUP: {
2025 char group[UDEV_NAME_SIZE];
2026 const char *gr = group;
2027 bool truncated;
2028
2029 if (event->group_final)
2030 break;
2031 if (token->op == OP_ASSIGN_FINAL)
2032 event->group_final = true;
2033
2034 (void) udev_event_apply_format(event, token->value, group, sizeof(group), false, &truncated);
2035 if (truncated) {
2036 log_rule_warning(dev, rules, "The group name '%s' is truncated while substituting into '%s', "
2037 "refusing to apply the GROUP key.", group, token->value);
2038 break;
2039 }
2040
2041 r = get_group_creds(&gr, &event->gid, USER_CREDS_ALLOW_MISSING);
2042 if (r < 0)
2043 log_unknown_owner(dev, rules, r, "group", group);
2044 else
2045 log_rule_debug(dev, rules, "GROUP %s(%u)", group, event->gid);
2046 break;
2047 }
2048 case TK_A_MODE: {
2049 char mode_str[UDEV_NAME_SIZE];
2050 bool truncated;
2051
2052 if (event->mode_final)
2053 break;
2054 if (token->op == OP_ASSIGN_FINAL)
2055 event->mode_final = true;
2056
2057 (void) udev_event_apply_format(event, token->value, mode_str, sizeof(mode_str), false, &truncated);
2058 if (truncated) {
2059 log_rule_warning(dev, rules, "The mode '%s' is truncated while substituting into %s, "
2060 "refusing to apply the MODE key.", mode_str, token->value);
2061 break;
2062 }
2063
2064 r = parse_mode(mode_str, &event->mode);
2065 if (r < 0)
2066 log_rule_error_errno(dev, rules, r, "Failed to parse mode '%s', ignoring: %m", mode_str);
2067 else
2068 log_rule_debug(dev, rules, "MODE %#o", event->mode);
2069 break;
2070 }
2071 case TK_A_OWNER_ID:
2072 if (event->owner_final)
2073 break;
2074 if (token->op == OP_ASSIGN_FINAL)
2075 event->owner_final = true;
2076 if (!token->data)
2077 break;
2078 event->uid = PTR_TO_UID(token->data);
2079 log_rule_debug(dev, rules, "OWNER %u", event->uid);
2080 break;
2081 case TK_A_GROUP_ID:
2082 if (event->group_final)
2083 break;
2084 if (token->op == OP_ASSIGN_FINAL)
2085 event->group_final = true;
2086 if (!token->data)
2087 break;
2088 event->gid = PTR_TO_GID(token->data);
2089 log_rule_debug(dev, rules, "GROUP %u", event->gid);
2090 break;
2091 case TK_A_MODE_ID:
2092 if (event->mode_final)
2093 break;
2094 if (token->op == OP_ASSIGN_FINAL)
2095 event->mode_final = true;
2096 if (!token->data)
2097 break;
2098 event->mode = PTR_TO_MODE(token->data);
2099 log_rule_debug(dev, rules, "MODE %#o", event->mode);
2100 break;
2101 case TK_A_SECLABEL: {
2102 _cleanup_free_ char *name = NULL, *label = NULL;
2103 char label_str[UDEV_LINE_SIZE] = {};
2104 bool truncated;
2105
2106 name = strdup(token->data);
2107 if (!name)
2108 return log_oom();
2109
2110 (void) udev_event_apply_format(event, token->value, label_str, sizeof(label_str), false, &truncated);
2111 if (truncated) {
2112 log_rule_warning(dev, rules, "The security label '%s' is truncated while substituting into '%s', "
2113 "refusing to apply the SECLABEL key.", label_str, token->value);
2114 break;
2115 }
2116
2117 if (!isempty(label_str))
2118 label = strdup(label_str);
2119 else
2120 label = strdup(token->value);
2121 if (!label)
2122 return log_oom();
2123
2124 if (token->op == OP_ASSIGN)
2125 ordered_hashmap_clear_free_free(event->seclabel_list);
2126
2127 r = ordered_hashmap_ensure_put(&event->seclabel_list, NULL, name, label);
2128 if (r == -ENOMEM)
2129 return log_oom();
2130 if (r < 0)
2131 return log_rule_error_errno(dev, rules, r, "Failed to store SECLABEL{%s}='%s': %m", name, label);;
2132
2133 log_rule_debug(dev, rules, "SECLABEL{%s}='%s'", name, label);
2134
2135 TAKE_PTR(name);
2136 TAKE_PTR(label);
2137 break;
2138 }
2139 case TK_A_ENV: {
2140 const char *val, *name = token->data;
2141 char value_new[UDEV_NAME_SIZE], *p = value_new;
2142 size_t count, l = sizeof(value_new);
2143 bool truncated;
2144
2145 if (isempty(token->value)) {
2146 if (token->op == OP_ADD)
2147 break;
2148 r = device_add_property(dev, name, NULL);
2149 if (r < 0)
2150 return log_rule_error_errno(dev, rules, r, "Failed to remove property '%s': %m", name);
2151 break;
2152 }
2153
2154 if (token->op == OP_ADD &&
2155 sd_device_get_property_value(dev, name, &val) >= 0) {
2156 l = strpcpyl_full(&p, l, &truncated, val, " ", NULL);
2157 if (truncated) {
2158 log_rule_warning(dev, rules, "The buffer for the property '%s' is full, "
2159 "refusing to append the new value '%s'.", name, token->value);
2160 break;
2161 }
2162 }
2163
2164 (void) udev_event_apply_format(event, token->value, p, l, false, &truncated);
2165 if (truncated) {
2166 log_rule_warning(dev, rules, "The property value '%s' is truncated while substituting into '%s', "
2167 "refusing to add property '%s'.", p, token->value, name);
2168 break;
2169 }
2170
2171 if (event->esc == ESCAPE_REPLACE) {
2172 count = udev_replace_chars(p, NULL);
2173 if (count > 0)
2174 log_rule_debug(dev, rules, "Replaced %zu slash(es) from result of ENV{%s}%s=\"%s\"",
2175 count, name, token->op == OP_ADD ? "+" : "", token->value);
2176 }
2177
2178 r = device_add_property(dev, name, value_new);
2179 if (r < 0)
2180 return log_rule_error_errno(dev, rules, r, "Failed to add property '%s=%s': %m", name, value_new);
2181 break;
2182 }
2183 case TK_A_TAG: {
2184 char buf[UDEV_PATH_SIZE];
2185 bool truncated;
2186
2187 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2188 if (truncated) {
2189 log_rule_warning(dev, rules, "The tag name '%s' is truncated while substituting into '%s',"
2190 "refusing to %s the tag.", buf, token->value,
2191 token->op == OP_REMOVE ? "remove" : "add");
2192 break;
2193 }
2194
2195 if (token->op == OP_ASSIGN)
2196 device_cleanup_tags(dev);
2197
2198 if (buf[strspn(buf, ALPHANUMERICAL "-_")] != '\0') {
2199 log_rule_error(dev, rules, "Invalid tag name '%s', ignoring", buf);
2200 break;
2201 }
2202 if (token->op == OP_REMOVE)
2203 device_remove_tag(dev, buf);
2204 else {
2205 r = device_add_tag(dev, buf, true);
2206 if (r < 0)
2207 return log_rule_error_errno(dev, rules, r, "Failed to add tag '%s': %m", buf);
2208 }
2209 break;
2210 }
2211 case TK_A_NAME: {
2212 char buf[UDEV_PATH_SIZE];
2213 bool truncated;
2214 size_t count;
2215
2216 if (event->name_final)
2217 break;
2218 if (token->op == OP_ASSIGN_FINAL)
2219 event->name_final = true;
2220
2221 if (sd_device_get_ifindex(dev, NULL) < 0) {
2222 log_rule_error(dev, rules,
2223 "Only network interfaces can be renamed, ignoring NAME=\"%s\".",
2224 token->value);
2225 break;
2226 }
2227
2228 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2229 if (truncated) {
2230 log_rule_warning(dev, rules, "The network interface name '%s' is truncated while substituting into '%s', "
2231 "refusing to set the name.", buf, token->value);
2232 break;
2233 }
2234
2235 if (IN_SET(event->esc, ESCAPE_UNSET, ESCAPE_REPLACE)) {
2236 if (naming_scheme_has(NAMING_REPLACE_STRICTLY))
2237 count = udev_replace_ifname(buf);
2238 else
2239 count = udev_replace_chars(buf, "/");
2240 if (count > 0)
2241 log_rule_debug(dev, rules, "Replaced %zu character(s) from result of NAME=\"%s\"",
2242 count, token->value);
2243 }
2244 r = free_and_strdup_warn(&event->name, buf);
2245 if (r < 0)
2246 return r;
2247
2248 log_rule_debug(dev, rules, "NAME '%s'", event->name);
2249 break;
2250 }
2251 case TK_A_DEVLINK: {
2252 char buf[UDEV_PATH_SIZE], *p;
2253 bool truncated;
2254 size_t count;
2255
2256 if (event->devlink_final)
2257 break;
2258 if (sd_device_get_devnum(dev, NULL) < 0)
2259 break;
2260 if (token->op == OP_ASSIGN_FINAL)
2261 event->devlink_final = true;
2262 if (IN_SET(token->op, OP_ASSIGN, OP_ASSIGN_FINAL))
2263 device_cleanup_devlinks(dev);
2264
2265 /* allow multiple symlinks separated by spaces */
2266 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), event->esc != ESCAPE_NONE, &truncated);
2267 if (truncated) {
2268 log_rule_warning(dev, rules, "The symbolic link path '%s' is truncated while substituting into '%s', "
2269 "refusing to add the device symbolic link.", buf, token->value);
2270 break;
2271 }
2272
2273 if (event->esc == ESCAPE_UNSET)
2274 count = udev_replace_chars(buf, "/ ");
2275 else if (event->esc == ESCAPE_REPLACE)
2276 count = udev_replace_chars(buf, "/");
2277 else
2278 count = 0;
2279 if (count > 0)
2280 log_rule_debug(dev, rules, "Replaced %zu character(s) from result of SYMLINK=\"%s\"",
2281 count, token->value);
2282
2283 p = skip_leading_chars(buf, NULL);
2284 while (!isempty(p)) {
2285 char filename[UDEV_PATH_SIZE], *next;
2286
2287 next = strchr(p, ' ');
2288 if (next) {
2289 *next++ = '\0';
2290 next = skip_leading_chars(next, NULL);
2291 }
2292
2293 strscpyl_full(filename, sizeof(filename), &truncated, "/dev/", p, NULL);
2294 if (truncated)
2295 continue;
2296
2297 r = device_add_devlink(dev, filename);
2298 if (r < 0)
2299 return log_rule_error_errno(dev, rules, r, "Failed to add devlink '%s': %m", filename);
2300
2301 log_rule_debug(dev, rules, "LINK '%s'", p);
2302 p = next;
2303 }
2304 break;
2305 }
2306 case TK_A_ATTR: {
2307 char buf[UDEV_PATH_SIZE], value[UDEV_NAME_SIZE];
2308 const char *val, *key_name = token->data;
2309 bool truncated;
2310
2311 if (udev_resolve_subsys_kernel(key_name, buf, sizeof(buf), false) < 0 &&
2312 sd_device_get_syspath(dev, &val) >= 0) {
2313 strscpyl_full(buf, sizeof(buf), &truncated, val, "/", key_name, NULL);
2314 if (truncated) {
2315 log_rule_warning(dev, rules,
2316 "The path to the attribute '%s/%s' is too long, refusing to set the attribute.",
2317 val, key_name);
2318 break;
2319 }
2320 }
2321
2322 r = attr_subst_subdir(buf);
2323 if (r < 0) {
2324 log_rule_error_errno(dev, rules, r, "Could not find file matches '%s', ignoring: %m", buf);
2325 break;
2326 }
2327 (void) udev_event_apply_format(event, token->value, value, sizeof(value), false, &truncated);
2328 if (truncated) {
2329 log_rule_warning(dev, rules, "The attribute value '%s' is truncated while substituting into '%s', "
2330 "refusing to set the attribute '%s'", value, token->value, buf);
2331 break;
2332 }
2333
2334 log_rule_debug(dev, rules, "ATTR '%s' writing '%s'", buf, value);
2335 r = write_string_file(buf, value,
2336 WRITE_STRING_FILE_VERIFY_ON_FAILURE |
2337 WRITE_STRING_FILE_DISABLE_BUFFER |
2338 WRITE_STRING_FILE_AVOID_NEWLINE |
2339 WRITE_STRING_FILE_VERIFY_IGNORE_NEWLINE);
2340 if (r < 0)
2341 log_rule_error_errno(dev, rules, r, "Failed to write ATTR{%s}, ignoring: %m", buf);
2342 break;
2343 }
2344 case TK_A_SYSCTL: {
2345 char buf[UDEV_PATH_SIZE], value[UDEV_NAME_SIZE];
2346 bool truncated;
2347
2348 (void) udev_event_apply_format(event, token->data, buf, sizeof(buf), false, &truncated);
2349 if (truncated) {
2350 log_rule_warning(dev, rules, "The sysctl entry name '%s' is truncated while substituting into '%s', "
2351 "refusing to set the sysctl entry.", buf, (const char*) token->data);
2352 break;
2353 }
2354
2355 (void) udev_event_apply_format(event, token->value, value, sizeof(value), false, &truncated);
2356 if (truncated) {
2357 log_rule_warning(dev, rules, "The sysctl value '%s' is truncated while substituting into '%s', "
2358 "refusing to set the sysctl entry '%s'", value, token->value, buf);
2359 break;
2360 }
2361
2362 sysctl_normalize(buf);
2363 log_rule_debug(dev, rules, "SYSCTL '%s' writing '%s'", buf, value);
2364 r = sysctl_write(buf, value);
2365 if (r < 0)
2366 log_rule_error_errno(dev, rules, r, "Failed to write SYSCTL{%s}='%s', ignoring: %m", buf, value);
2367 break;
2368 }
2369 case TK_A_RUN_BUILTIN:
2370 case TK_A_RUN_PROGRAM: {
2371 _cleanup_free_ char *cmd = NULL;
2372 char buf[UDEV_PATH_SIZE];
2373 bool truncated;
2374
2375 if (event->run_final)
2376 break;
2377 if (token->op == OP_ASSIGN_FINAL)
2378 event->run_final = true;
2379
2380 if (IN_SET(token->op, OP_ASSIGN, OP_ASSIGN_FINAL))
2381 ordered_hashmap_clear_free_key(event->run_list);
2382
2383 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2384 if (truncated) {
2385 log_rule_warning(dev, rules, "The command '%s' is truncated while substituting into '%s', "
2386 "refusing to invoke the command.", buf, token->value);
2387 break;
2388 }
2389
2390 cmd = strdup(buf);
2391 if (!cmd)
2392 return log_oom();
2393
2394 r = ordered_hashmap_ensure_put(&event->run_list, NULL, cmd, token->data);
2395 if (r == -ENOMEM)
2396 return log_oom();
2397 if (r < 0)
2398 return log_rule_error_errno(dev, rules, r, "Failed to store command '%s': %m", cmd);
2399
2400 TAKE_PTR(cmd);
2401
2402 log_rule_debug(dev, rules, "RUN '%s'", token->value);
2403 break;
2404 }
2405 case TK_A_OPTIONS_STATIC_NODE:
2406 /* do nothing for events. */
2407 break;
2408 default:
2409 assert_not_reached();
2410 }
2411
2412 return true;
2413 }
2414
token_is_for_parents(UdevRuleToken * token)2415 static bool token_is_for_parents(UdevRuleToken *token) {
2416 return token->type >= TK_M_PARENTS_KERNEL && token->type <= TK_M_PARENTS_TAG;
2417 }
2418
udev_rule_apply_parent_token_to_event(UdevRules * rules,UdevEvent * event,int timeout_signal)2419 static int udev_rule_apply_parent_token_to_event(
2420 UdevRules *rules,
2421 UdevEvent *event,
2422 int timeout_signal) {
2423
2424 UdevRuleLine *line;
2425 UdevRuleToken *head;
2426 int r;
2427
2428 assert(rules);
2429 assert(rules->current_file);
2430 assert(event);
2431
2432 line = ASSERT_PTR(rules->current_file->current_line);
2433 head = ASSERT_PTR(rules->current_file->current_line->current_token);
2434 event->dev_parent = ASSERT_PTR(event->dev);
2435
2436 for (;;) {
2437 LIST_FOREACH(tokens, token, head) {
2438 if (!token_is_for_parents(token))
2439 return true; /* All parent tokens match. */
2440
2441 line->current_token = token;
2442 r = udev_rule_apply_token_to_event(rules, event->dev_parent, event, 0, timeout_signal, NULL);
2443 if (r < 0)
2444 return r;
2445 if (r == 0)
2446 break;
2447 }
2448 if (r > 0)
2449 /* All parent tokens match, and no more token (except for GOTO) in the line. */
2450 return true;
2451
2452 if (sd_device_get_parent(event->dev_parent, &event->dev_parent) < 0) {
2453 event->dev_parent = NULL;
2454 return false;
2455 }
2456 }
2457 }
2458
udev_rule_apply_line_to_event(UdevRules * rules,UdevEvent * event,usec_t timeout_usec,int timeout_signal,Hashmap * properties_list,UdevRuleLine ** next_line)2459 static int udev_rule_apply_line_to_event(
2460 UdevRules *rules,
2461 UdevEvent *event,
2462 usec_t timeout_usec,
2463 int timeout_signal,
2464 Hashmap *properties_list,
2465 UdevRuleLine **next_line) {
2466
2467 UdevRuleLine *line = rules->current_file->current_line;
2468 UdevRuleLineType mask = LINE_HAS_GOTO | LINE_UPDATE_SOMETHING;
2469 bool parents_done = false;
2470 sd_device_action_t action;
2471 int r;
2472
2473 r = sd_device_get_action(event->dev, &action);
2474 if (r < 0)
2475 return r;
2476
2477 if (action != SD_DEVICE_REMOVE) {
2478 if (sd_device_get_devnum(event->dev, NULL) >= 0)
2479 mask |= LINE_HAS_DEVLINK;
2480
2481 if (sd_device_get_ifindex(event->dev, NULL) >= 0)
2482 mask |= LINE_HAS_NAME;
2483 }
2484
2485 if ((line->type & mask) == 0)
2486 return 0;
2487
2488 event->esc = ESCAPE_UNSET;
2489
2490 DEVICE_TRACE_POINT(rules_apply_line, event->dev, line->rule_file->filename, line->line_number);
2491
2492 LIST_FOREACH(tokens, token, line->tokens) {
2493 line->current_token = token;
2494
2495 if (token_is_for_parents(token)) {
2496 if (parents_done)
2497 continue;
2498
2499 r = udev_rule_apply_parent_token_to_event(rules, event, timeout_signal);
2500 if (r <= 0)
2501 return r;
2502
2503 parents_done = true;
2504 continue;
2505 }
2506
2507 r = udev_rule_apply_token_to_event(rules, event->dev, event, timeout_usec, timeout_signal, properties_list);
2508 if (r <= 0)
2509 return r;
2510 }
2511
2512 if (line->goto_line)
2513 *next_line = line->goto_line;
2514
2515 return 0;
2516 }
2517
udev_rules_apply_to_event(UdevRules * rules,UdevEvent * event,usec_t timeout_usec,int timeout_signal,Hashmap * properties_list)2518 int udev_rules_apply_to_event(
2519 UdevRules *rules,
2520 UdevEvent *event,
2521 usec_t timeout_usec,
2522 int timeout_signal,
2523 Hashmap *properties_list) {
2524
2525 int r;
2526
2527 assert(rules);
2528 assert(event);
2529
2530 LIST_FOREACH(rule_files, file, rules->rule_files) {
2531 rules->current_file = file;
2532 LIST_FOREACH_WITH_NEXT(rule_lines, line, next_line, file->rule_lines) {
2533 file->current_line = line;
2534 r = udev_rule_apply_line_to_event(rules, event, timeout_usec, timeout_signal, properties_list, &next_line);
2535 if (r < 0)
2536 return r;
2537 }
2538 }
2539
2540 return 0;
2541 }
2542
udev_rule_line_apply_static_dev_perms(UdevRuleLine * rule_line)2543 static int udev_rule_line_apply_static_dev_perms(UdevRuleLine *rule_line) {
2544 _cleanup_strv_free_ char **tags = NULL;
2545 uid_t uid = UID_INVALID;
2546 gid_t gid = GID_INVALID;
2547 mode_t mode = MODE_INVALID;
2548 int r;
2549
2550 assert(rule_line);
2551
2552 if (!FLAGS_SET(rule_line->type, LINE_HAS_STATIC_NODE))
2553 return 0;
2554
2555 LIST_FOREACH(tokens, token, rule_line->tokens)
2556 if (token->type == TK_A_OWNER_ID)
2557 uid = PTR_TO_UID(token->data);
2558 else if (token->type == TK_A_GROUP_ID)
2559 gid = PTR_TO_GID(token->data);
2560 else if (token->type == TK_A_MODE_ID)
2561 mode = PTR_TO_MODE(token->data);
2562 else if (token->type == TK_A_TAG) {
2563 r = strv_extend(&tags, token->value);
2564 if (r < 0)
2565 return log_oom();
2566 } else if (token->type == TK_A_OPTIONS_STATIC_NODE) {
2567 r = static_node_apply_permissions(token->value, mode, uid, gid, tags);
2568 if (r < 0)
2569 return r;
2570 }
2571
2572 return 0;
2573 }
2574
udev_rules_apply_static_dev_perms(UdevRules * rules)2575 int udev_rules_apply_static_dev_perms(UdevRules *rules) {
2576 int r;
2577
2578 assert(rules);
2579
2580 LIST_FOREACH(rule_files, file, rules->rule_files)
2581 LIST_FOREACH(rule_lines, line, file->rule_lines) {
2582 r = udev_rule_line_apply_static_dev_perms(line);
2583 if (r < 0)
2584 return r;
2585 }
2586
2587 return 0;
2588 }
2589