]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/udev/udev-rules.c
2d4eb3d3414c51118fb3f2ad3493f44b8d81ed75
[thirdparty/systemd.git] / src / udev / udev-rules.c
1 /* SPDX-License-Identifier: GPL-2.0+ */
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-util.h"
10 #include "dirent-util.h"
11 #include "escape.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 "libudev-util.h"
18 #include "list.h"
19 #include "mkdir.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 "udev-builtin.h"
29 #include "udev-event.h"
30 #include "udev-rules.h"
31 #include "user-util.h"
32 #include "virt.h"
33
34 #define RULES_DIRS (const char* const*) CONF_PATHS_STRV("udev/rules.d")
35
36 typedef enum {
37 OP_MATCH, /* == */
38 OP_NOMATCH, /* != */
39 OP_ADD, /* += */
40 OP_REMOVE, /* -= */
41 OP_ASSIGN, /* = */
42 OP_ASSIGN_FINAL, /* := */
43 _OP_TYPE_MAX,
44 _OP_TYPE_INVALID = -1
45 } UdevRuleOperatorType;
46
47 typedef enum {
48 MATCH_TYPE_EMPTY, /* empty string */
49 MATCH_TYPE_PLAIN, /* no special characters */
50 MATCH_TYPE_PLAIN_WITH_EMPTY, /* no special characters with empty string, e.g., "|foo" */
51 MATCH_TYPE_GLOB, /* shell globs ?,*,[] */
52 MATCH_TYPE_GLOB_WITH_EMPTY, /* shell globs ?,*,[] with empty string, e.g., "|foo*" */
53 MATCH_TYPE_SUBSYSTEM, /* "subsystem", "bus", or "class" */
54 _MATCH_TYPE_MAX,
55 _MATCH_TYPE_INVALID = -1
56 } UdevRuleMatchType;
57
58 typedef enum {
59 SUBST_TYPE_PLAIN, /* no substitution */
60 SUBST_TYPE_FORMAT, /* % or $ */
61 SUBST_TYPE_SUBSYS, /* "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
62 _SUBST_TYPE_MAX,
63 _SUBST_TYPE_INVALID = -1
64 } UdevRuleSubstituteType;
65
66 typedef enum {
67 /* lvalues which take match or nomatch operator */
68 TK_M_ACTION, /* string, device_get_action() */
69 TK_M_DEVPATH, /* path, sd_device_get_devpath() */
70 TK_M_KERNEL, /* string, sd_device_get_sysname() */
71 TK_M_DEVLINK, /* strv, sd_device_get_devlink_first(), sd_device_get_devlink_next() */
72 TK_M_NAME, /* string, name of network interface */
73 TK_M_ENV, /* string, device property, takes key through attribute */
74 TK_M_CONST, /* string, system-specific hard-coded constant */
75 TK_M_TAG, /* strv, sd_device_get_tag_first(), sd_device_get_tag_next() */
76 TK_M_SUBSYSTEM, /* string, sd_device_get_subsystem() */
77 TK_M_DRIVER, /* string, sd_device_get_driver() */
78 TK_M_ATTR, /* string, takes filename through attribute, sd_device_get_sysattr_value(), util_resolve_subsys_kernel(), etc. */
79 TK_M_SYSCTL, /* string, takes kernel parameter through attribute */
80
81 /* matches parent parameters */
82 TK_M_PARENTS_KERNEL, /* string */
83 TK_M_PARENTS_SUBSYSTEM, /* string */
84 TK_M_PARENTS_DRIVER, /* string */
85 TK_M_PARENTS_ATTR, /* string */
86 TK_M_PARENTS_TAG, /* strv */
87
88 TK_M_TEST, /* path, optionally mode_t can be specified by attribute, test the existence of a file */
89 TK_M_PROGRAM, /* string, execute a program */
90 TK_M_IMPORT_FILE, /* path */
91 TK_M_IMPORT_PROGRAM, /* string, import properties from the result of program */
92 TK_M_IMPORT_BUILTIN, /* string, import properties from the result of built-in command */
93 TK_M_IMPORT_DB, /* string, import properties from database */
94 TK_M_IMPORT_CMDLINE, /* string, kernel command line */
95 TK_M_IMPORT_PARENT, /* string, parent property */
96 TK_M_RESULT, /* string, result of TK_M_PROGRAM */
97
98 #define _TK_M_MAX (TK_M_RESULT + 1)
99 #define _TK_A_MIN _TK_M_MAX
100
101 /* lvalues which take one of assign operators */
102 TK_A_OPTIONS_STRING_ESCAPE_NONE, /* no argument */
103 TK_A_OPTIONS_STRING_ESCAPE_REPLACE, /* no argument */
104 TK_A_OPTIONS_DB_PERSIST, /* no argument */
105 TK_A_OPTIONS_INOTIFY_WATCH, /* boolean */
106 TK_A_OPTIONS_DEVLINK_PRIORITY, /* int */
107 TK_A_OWNER, /* user name */
108 TK_A_GROUP, /* group name */
109 TK_A_MODE, /* mode string */
110 TK_A_OWNER_ID, /* uid_t */
111 TK_A_GROUP_ID, /* gid_t */
112 TK_A_MODE_ID, /* mode_t */
113 TK_A_TAG, /* string */
114 TK_A_OPTIONS_STATIC_NODE, /* device path, /dev/... */
115 TK_A_SECLABEL, /* string with attribute */
116 TK_A_ENV, /* string with attribute */
117 TK_A_NAME, /* ifname */
118 TK_A_DEVLINK, /* string */
119 TK_A_ATTR, /* string with attribute */
120 TK_A_SYSCTL, /* string with attribute */
121 TK_A_RUN_BUILTIN, /* string */
122 TK_A_RUN_PROGRAM, /* string */
123
124 _TK_TYPE_MAX,
125 _TK_TYPE_INVALID = -1,
126 } UdevRuleTokenType;
127
128 typedef enum {
129 LINE_HAS_NAME = 1 << 0, /* has NAME= */
130 LINE_HAS_DEVLINK = 1 << 1, /* has SYMLINK=, OWNER=, GROUP= or MODE= */
131 LINE_HAS_STATIC_NODE = 1 << 2, /* has OPTIONS=static_node */
132 LINE_HAS_GOTO = 1 << 3, /* has GOTO= */
133 LINE_HAS_LABEL = 1 << 4, /* has LABEL= */
134 LINE_UPDATE_SOMETHING = 1 << 5, /* has other TK_A_* or TK_M_IMPORT tokens */
135 } UdevRuleLineType;
136
137 typedef struct UdevRuleFile UdevRuleFile;
138 typedef struct UdevRuleLine UdevRuleLine;
139 typedef struct UdevRuleToken UdevRuleToken;
140
141 struct UdevRuleToken {
142 UdevRuleTokenType type:8;
143 UdevRuleOperatorType op:8;
144 UdevRuleMatchType match_type:8;
145 UdevRuleSubstituteType attr_subst_type:7;
146 bool attr_match_remove_trailing_whitespace:1;
147 const char *value;
148 void *data;
149 LIST_FIELDS(UdevRuleToken, tokens);
150 };
151
152 struct UdevRuleLine {
153 char *line;
154 unsigned line_number;
155 UdevRuleLineType type;
156
157 const char *label;
158 const char *goto_label;
159 UdevRuleLine *goto_line;
160
161 UdevRuleFile *rule_file;
162 UdevRuleToken *current_token;
163 LIST_HEAD(UdevRuleToken, tokens);
164 LIST_FIELDS(UdevRuleLine, rule_lines);
165 };
166
167 struct UdevRuleFile {
168 char *filename;
169 UdevRuleLine *current_line;
170 LIST_HEAD(UdevRuleLine, rule_lines);
171 LIST_FIELDS(UdevRuleFile, rule_files);
172 };
173
174 struct UdevRules {
175 usec_t dirs_ts_usec;
176 ResolveNameTiming resolve_name_timing;
177 Hashmap *known_users;
178 Hashmap *known_groups;
179 UdevRuleFile *current_file;
180 LIST_HEAD(UdevRuleFile, rule_files);
181 };
182
183 /*** Logging helpers ***/
184
185 #define log_rule_full(device, rules, level, error, fmt, ...) \
186 ({ \
187 UdevRules *_r = (rules); \
188 UdevRuleFile *_f = _r ? _r->current_file : NULL; \
189 UdevRuleLine *_l = _f ? _f->current_line : NULL; \
190 const char *_n = _f ? _f->filename : NULL; \
191 \
192 log_device_full(device, level, error, "%s:%u " fmt, \
193 strna(_n), _l ? _l->line_number : 0, \
194 ##__VA_ARGS__); \
195 })
196
197 #define log_rule_debug(device, rules, ...) log_rule_full(device, rules, LOG_DEBUG, 0, ##__VA_ARGS__)
198 #define log_rule_info(device, rules, ...) log_rule_full(device, rules, LOG_INFO, 0, ##__VA_ARGS__)
199 #define log_rule_notice(device, rules, ...) log_rule_full(device, rules, LOG_NOTICE, 0, ##__VA_ARGS__)
200 #define log_rule_warning(device, rules, ...) log_rule_full(device, rules, LOG_WARNING, 0, ##__VA_ARGS__)
201 #define log_rule_error(device, rules, ...) log_rule_full(device, rules, LOG_ERR, 0, ##__VA_ARGS__)
202
203 #define log_rule_debug_errno(device, rules, error, ...) log_rule_full(device, rules, LOG_DEBUG, error, ##__VA_ARGS__)
204 #define log_rule_info_errno(device, rules, error, ...) log_rule_full(device, rules, LOG_INFO, error, ##__VA_ARGS__)
205 #define log_rule_notice_errno(device, rules, error, ...) log_rule_full(device, rules, LOG_NOTICE, error, ##__VA_ARGS__)
206 #define log_rule_warning_errno(device, rules, error, ...) log_rule_full(device, rules, LOG_WARNING, error, ##__VA_ARGS__)
207 #define log_rule_error_errno(device, rules, error, ...) log_rule_full(device, rules, LOG_ERR, error, ##__VA_ARGS__)
208
209 #define log_token_full(rules, ...) log_rule_full(NULL, rules, ##__VA_ARGS__)
210
211 #define log_token_debug(rules, ...) log_token_full(rules, LOG_DEBUG, 0, ##__VA_ARGS__)
212 #define log_token_info(rules, ...) log_token_full(rules, LOG_INFO, 0, ##__VA_ARGS__)
213 #define log_token_notice(rules, ...) log_token_full(rules, LOG_NOTICE, 0, ##__VA_ARGS__)
214 #define log_token_warning(rules, ...) log_token_full(rules, LOG_WARNING, 0, ##__VA_ARGS__)
215 #define log_token_error(rules, ...) log_token_full(rules, LOG_ERR, 0, ##__VA_ARGS__)
216
217 #define log_token_debug_errno(rules, error, ...) log_token_full(rules, LOG_DEBUG, error, ##__VA_ARGS__)
218 #define log_token_info_errno(rules, error, ...) log_token_full(rules, LOG_INFO, error, ##__VA_ARGS__)
219 #define log_token_notice_errno(rules, error, ...) log_token_full(rules, LOG_NOTICE, error, ##__VA_ARGS__)
220 #define log_token_warning_errno(rules, error, ...) log_token_full(rules, LOG_WARNING, error, ##__VA_ARGS__)
221 #define log_token_error_errno(rules, error, ...) log_token_full(rules, LOG_ERR, error, ##__VA_ARGS__)
222
223 #define _log_token_invalid(rules, key, type) \
224 log_token_error_errno(rules, SYNTHETIC_ERRNO(EINVAL), \
225 "Invalid %s for %s.", type, key)
226
227 #define log_token_invalid_op(rules, key) _log_token_invalid(rules, key, "operator")
228 #define log_token_invalid_attr(rules, key) _log_token_invalid(rules, key, "attribute")
229
230 #define log_token_invalid_attr_format(rules, key, attr, offset, hint) \
231 log_token_error_errno(rules, SYNTHETIC_ERRNO(EINVAL), \
232 "Invalid attribute \"%s\" for %s (char %zu: %s), ignoring, but please fix it.", \
233 attr, key, offset, hint)
234 #define log_token_invalid_value(rules, key, value, offset, hint) \
235 log_token_error_errno(rules, SYNTHETIC_ERRNO(EINVAL), \
236 "Invalid value \"%s\" for %s (char %zu: %s), ignoring, but please fix it.", \
237 value, key, offset, hint)
238
239 static void log_unknown_owner(sd_device *dev, UdevRules *rules, int error, const char *entity, const char *name) {
240 if (IN_SET(abs(error), ENOENT, ESRCH))
241 log_rule_error(dev, rules, "Unknown %s '%s', ignoring", entity, name);
242 else
243 log_rule_error_errno(dev, rules, error, "Failed to resolve %s '%s', ignoring: %m", entity, name);
244 }
245
246 /*** Other functions ***/
247
248 static void udev_rule_token_free(UdevRuleToken *token) {
249 free(token);
250 }
251
252 static void udev_rule_line_clear_tokens(UdevRuleLine *rule_line) {
253 UdevRuleToken *i, *next;
254
255 assert(rule_line);
256
257 LIST_FOREACH_SAFE(tokens, i, next, rule_line->tokens)
258 udev_rule_token_free(i);
259
260 rule_line->tokens = NULL;
261 }
262
263 static void udev_rule_line_free(UdevRuleLine *rule_line) {
264 if (!rule_line)
265 return;
266
267 udev_rule_line_clear_tokens(rule_line);
268
269 if (rule_line->rule_file) {
270 if (rule_line->rule_file->current_line == rule_line)
271 rule_line->rule_file->current_line = rule_line->rule_lines_prev;
272
273 LIST_REMOVE(rule_lines, rule_line->rule_file->rule_lines, rule_line);
274 }
275
276 free(rule_line->line);
277 free(rule_line);
278 }
279
280 DEFINE_TRIVIAL_CLEANUP_FUNC(UdevRuleLine*, udev_rule_line_free);
281
282 static void udev_rule_file_free(UdevRuleFile *rule_file) {
283 UdevRuleLine *i, *next;
284
285 if (!rule_file)
286 return;
287
288 LIST_FOREACH_SAFE(rule_lines, i, next, rule_file->rule_lines)
289 udev_rule_line_free(i);
290
291 free(rule_file->filename);
292 free(rule_file);
293 }
294
295 UdevRules *udev_rules_free(UdevRules *rules) {
296 UdevRuleFile *i, *next;
297
298 if (!rules)
299 return NULL;
300
301 LIST_FOREACH_SAFE(rule_files, i, next, rules->rule_files)
302 udev_rule_file_free(i);
303
304 hashmap_free_free_key(rules->known_users);
305 hashmap_free_free_key(rules->known_groups);
306 return mfree(rules);
307 }
308
309 static int rule_resolve_user(UdevRules *rules, const char *name, uid_t *ret) {
310 _cleanup_free_ char *n = NULL;
311 uid_t uid;
312 void *val;
313 int r;
314
315 assert(rules);
316 assert(name);
317
318 val = hashmap_get(rules->known_users, name);
319 if (val) {
320 *ret = PTR_TO_UID(val);
321 return 0;
322 }
323
324 r = get_user_creds(&name, &uid, NULL, NULL, NULL, USER_CREDS_ALLOW_MISSING);
325 if (r < 0) {
326 log_unknown_owner(NULL, rules, r, "user", name);
327 *ret = UID_INVALID;
328 return 0;
329 }
330
331 n = strdup(name);
332 if (!n)
333 return -ENOMEM;
334
335 r = hashmap_ensure_allocated(&rules->known_users, &string_hash_ops);
336 if (r < 0)
337 return r;
338
339 r = hashmap_put(rules->known_users, n, UID_TO_PTR(uid));
340 if (r < 0)
341 return r;
342
343 TAKE_PTR(n);
344 *ret = uid;
345 return 0;
346 }
347
348 static int rule_resolve_group(UdevRules *rules, const char *name, gid_t *ret) {
349 _cleanup_free_ char *n = NULL;
350 gid_t gid;
351 void *val;
352 int r;
353
354 assert(rules);
355 assert(name);
356
357 val = hashmap_get(rules->known_groups, name);
358 if (val) {
359 *ret = PTR_TO_GID(val);
360 return 0;
361 }
362
363 r = get_group_creds(&name, &gid, USER_CREDS_ALLOW_MISSING);
364 if (r < 0) {
365 log_unknown_owner(NULL, rules, r, "group", name);
366 *ret = GID_INVALID;
367 return 0;
368 }
369
370 n = strdup(name);
371 if (!n)
372 return -ENOMEM;
373
374 r = hashmap_ensure_allocated(&rules->known_groups, &string_hash_ops);
375 if (r < 0)
376 return r;
377
378 r = hashmap_put(rules->known_groups, n, GID_TO_PTR(gid));
379 if (r < 0)
380 return r;
381
382 TAKE_PTR(n);
383 *ret = gid;
384 return 0;
385 }
386
387 static UdevRuleSubstituteType rule_get_substitution_type(const char *str) {
388 assert(str);
389
390 if (str[0] == '[')
391 return SUBST_TYPE_SUBSYS;
392 if (strchr(str, '%') || strchr(str, '$'))
393 return SUBST_TYPE_FORMAT;
394 return SUBST_TYPE_PLAIN;
395 }
396
397 static void rule_line_append_token(UdevRuleLine *rule_line, UdevRuleToken *token) {
398 assert(rule_line);
399 assert(token);
400
401 if (rule_line->current_token)
402 LIST_APPEND(tokens, rule_line->current_token, token);
403 else
404 LIST_APPEND(tokens, rule_line->tokens, token);
405
406 rule_line->current_token = token;
407 }
408
409 static int rule_line_add_token(UdevRuleLine *rule_line, UdevRuleTokenType type, UdevRuleOperatorType op, char *value, void *data) {
410 UdevRuleToken *token;
411 UdevRuleMatchType match_type = _MATCH_TYPE_INVALID;
412 UdevRuleSubstituteType subst_type = _SUBST_TYPE_INVALID;
413 bool remove_trailing_whitespace = false;
414 size_t len;
415
416 assert(rule_line);
417 assert(type >= 0 && type < _TK_TYPE_MAX);
418 assert(op >= 0 && op < _OP_TYPE_MAX);
419
420 if (type < _TK_M_MAX) {
421 assert(value);
422 assert(IN_SET(op, OP_MATCH, OP_NOMATCH));
423
424 if (type == TK_M_SUBSYSTEM && STR_IN_SET(value, "subsystem", "bus", "class"))
425 match_type = MATCH_TYPE_SUBSYSTEM;
426 else if (isempty(value))
427 match_type = MATCH_TYPE_EMPTY;
428 else if (streq(value, "?*")) {
429 /* Convert KEY=="?*" -> KEY!="" */
430 match_type = MATCH_TYPE_EMPTY;
431 op = op == OP_MATCH ? OP_NOMATCH : OP_MATCH;
432 } else if (string_is_glob(value))
433 match_type = MATCH_TYPE_GLOB;
434 else
435 match_type = MATCH_TYPE_PLAIN;
436
437 if (type < TK_M_TEST || type == TK_M_RESULT) {
438 /* Convert value string to nulstr. */
439 bool bar = true, empty = false;
440 char *a, *b;
441
442 for (a = b = value; *a != '\0'; a++) {
443 if (*a != '|') {
444 *b++ = *a;
445 bar = false;
446 } else {
447 if (bar)
448 empty = true;
449 else
450 *b++ = '\0';
451 bar = true;
452 }
453 }
454 *b = '\0';
455
456 /* Make sure the value is end, so NULSTR_FOREACH can read correct match */
457 if (b < a)
458 b[1] = '\0';
459
460 if (bar)
461 empty = true;
462
463 if (empty) {
464 if (match_type == MATCH_TYPE_GLOB)
465 match_type = MATCH_TYPE_GLOB_WITH_EMPTY;
466 if (match_type == MATCH_TYPE_PLAIN)
467 match_type = MATCH_TYPE_PLAIN_WITH_EMPTY;
468 }
469 }
470 }
471
472 if (IN_SET(type, TK_M_ATTR, TK_M_PARENTS_ATTR)) {
473 assert(value);
474 assert(data);
475
476 len = strlen(value);
477 if (len > 0 && !isspace(value[len - 1]))
478 remove_trailing_whitespace = true;
479
480 subst_type = rule_get_substitution_type((const char*) data);
481 }
482
483 token = new(UdevRuleToken, 1);
484 if (!token)
485 return -ENOMEM;
486
487 *token = (UdevRuleToken) {
488 .type = type,
489 .op = op,
490 .value = value,
491 .data = data,
492 .match_type = match_type,
493 .attr_subst_type = subst_type,
494 .attr_match_remove_trailing_whitespace = remove_trailing_whitespace,
495 };
496
497 rule_line_append_token(rule_line, token);
498
499 if (token->type == TK_A_NAME)
500 SET_FLAG(rule_line->type, LINE_HAS_NAME, true);
501
502 else if (IN_SET(token->type, TK_A_DEVLINK,
503 TK_A_OWNER, TK_A_GROUP, TK_A_MODE,
504 TK_A_OWNER_ID, TK_A_GROUP_ID, TK_A_MODE_ID))
505 SET_FLAG(rule_line->type, LINE_HAS_DEVLINK, true);
506
507 else if (token->type == TK_A_OPTIONS_STATIC_NODE)
508 SET_FLAG(rule_line->type, LINE_HAS_STATIC_NODE, true);
509
510 else if (token->type >= _TK_A_MIN ||
511 IN_SET(token->type, TK_M_PROGRAM,
512 TK_M_IMPORT_FILE, TK_M_IMPORT_PROGRAM, TK_M_IMPORT_BUILTIN,
513 TK_M_IMPORT_DB, TK_M_IMPORT_CMDLINE, TK_M_IMPORT_PARENT))
514 SET_FLAG(rule_line->type, LINE_UPDATE_SOMETHING, true);
515
516 return 0;
517 }
518
519 static void check_value_format_and_warn(UdevRules *rules, const char *key, const char *value, bool nonempty) {
520 size_t offset;
521 const char *hint;
522
523 if (nonempty && isempty(value))
524 log_token_invalid_value(rules, key, value, (size_t) 0, "empty value");
525 else if (udev_check_format(value, &offset, &hint) < 0)
526 log_token_invalid_value(rules, key, value, offset + 1, hint);
527 }
528
529 static int check_attr_format_and_warn(UdevRules *rules, const char *key, const char *value) {
530 size_t offset;
531 const char *hint;
532
533 if (isempty(value))
534 return log_token_invalid_attr(rules, key);
535 if (udev_check_format(value, &offset, &hint) < 0)
536 log_token_invalid_attr_format(rules, key, value, offset + 1, hint);
537 return 0;
538 }
539
540 static int parse_token(UdevRules *rules, const char *key, char *attr, UdevRuleOperatorType op, char *value) {
541 bool is_match = IN_SET(op, OP_MATCH, OP_NOMATCH);
542 UdevRuleLine *rule_line;
543 int r;
544
545 assert(rules);
546 assert(rules->current_file);
547 assert(rules->current_file->current_line);
548 assert(key);
549 assert(value);
550
551 rule_line = rules->current_file->current_line;
552
553 if (streq(key, "ACTION")) {
554 if (attr)
555 return log_token_invalid_attr(rules, key);
556 if (!is_match)
557 return log_token_invalid_op(rules, key);
558
559 r = rule_line_add_token(rule_line, TK_M_ACTION, op, value, NULL);
560 } else if (streq(key, "DEVPATH")) {
561 if (attr)
562 return log_token_invalid_attr(rules, key);
563 if (!is_match)
564 return log_token_invalid_op(rules, key);
565
566 r = rule_line_add_token(rule_line, TK_M_DEVPATH, op, value, NULL);
567 } else if (streq(key, "KERNEL")) {
568 if (attr)
569 return log_token_invalid_attr(rules, key);
570 if (!is_match)
571 return log_token_invalid_op(rules, key);
572
573 r = rule_line_add_token(rule_line, TK_M_KERNEL, op, value, NULL);
574 } else if (streq(key, "SYMLINK")) {
575 if (attr)
576 return log_token_invalid_attr(rules, key);
577 if (op == OP_REMOVE)
578 return log_token_invalid_op(rules, key);
579
580 if (!is_match) {
581 check_value_format_and_warn(rules, key, value, false);
582 r = rule_line_add_token(rule_line, TK_A_DEVLINK, op, value, NULL);
583 } else
584 r = rule_line_add_token(rule_line, TK_M_DEVLINK, op, value, NULL);
585 } else if (streq(key, "NAME")) {
586 if (attr)
587 return log_token_invalid_attr(rules, key);
588 if (op == OP_REMOVE)
589 return log_token_invalid_op(rules, key);
590 if (op == OP_ADD) {
591 log_token_warning(rules, "%s key takes '==', '!=', '=', or ':=' operator, assuming '=', but please fix it.", key);
592 op = OP_ASSIGN;
593 }
594
595 if (!is_match) {
596 if (streq(value, "%k"))
597 return log_token_error_errno(rules, SYNTHETIC_ERRNO(EINVAL),
598 "Ignoring NAME=\"%%k\" is ignored, as it breaks kernel supplied names.");
599 if (isempty(value))
600 return log_token_error_errno(rules, SYNTHETIC_ERRNO(EINVAL),
601 "Ignoring NAME=\"\", as udev will not delete any device nodes.");
602 check_value_format_and_warn(rules, key, value, false);
603
604 r = rule_line_add_token(rule_line, TK_A_NAME, op, value, NULL);
605 } else
606 r = rule_line_add_token(rule_line, TK_M_NAME, op, value, NULL);
607 } else if (streq(key, "ENV")) {
608 if (isempty(attr))
609 return log_token_invalid_attr(rules, key);
610 if (op == OP_REMOVE)
611 return log_token_invalid_op(rules, key);
612 if (op == OP_ASSIGN_FINAL) {
613 log_token_warning(rules, "%s key takes '==', '!=', '=', or '+=' operator, assuming '=', but please fix it.", key);
614 op = OP_ASSIGN;
615 }
616
617 if (!is_match) {
618 if (STR_IN_SET(attr,
619 "ACTION", "DEVLINKS", "DEVNAME", "DEVPATH", "DEVTYPE", "DRIVER",
620 "IFINDEX", "MAJOR", "MINOR", "SEQNUM", "SUBSYSTEM", "TAGS"))
621 return log_token_error_errno(rules, SYNTHETIC_ERRNO(EINVAL),
622 "Invalid ENV attribute. '%s' cannot be set.", attr);
623
624 check_value_format_and_warn(rules, key, value, false);
625
626 r = rule_line_add_token(rule_line, TK_A_ENV, op, value, attr);
627 } else
628 r = rule_line_add_token(rule_line, TK_M_ENV, op, value, attr);
629 } else if (streq(key, "CONST")) {
630 if (isempty(attr) || !STR_IN_SET(attr, "arch", "virt"))
631 return log_token_invalid_attr(rules, key);
632 if (!is_match)
633 return log_token_invalid_op(rules, key);
634 r = rule_line_add_token(rule_line, TK_M_CONST, op, value, attr);
635 } else if (streq(key, "TAG")) {
636 if (attr)
637 return log_token_invalid_attr(rules, key);
638 if (op == OP_ASSIGN_FINAL) {
639 log_token_warning(rules, "%s key takes '==', '!=', '=', or '+=' operator, assuming '=', but please fix it.", key);
640 op = OP_ASSIGN;
641 }
642
643 if (!is_match) {
644 check_value_format_and_warn(rules, key, value, true);
645
646 r = rule_line_add_token(rule_line, TK_A_TAG, op, value, NULL);
647 } else
648 r = rule_line_add_token(rule_line, TK_M_TAG, op, value, NULL);
649 } else if (streq(key, "SUBSYSTEM")) {
650 if (attr)
651 return log_token_invalid_attr(rules, key);
652 if (!is_match)
653 return log_token_invalid_op(rules, key);
654
655 if (STR_IN_SET(value, "bus", "class"))
656 log_token_warning(rules, "'%s' must be specified as 'subsystem'; please fix it", value);
657
658 r = rule_line_add_token(rule_line, TK_M_SUBSYSTEM, op, value, NULL);
659 } else if (streq(key, "DRIVER")) {
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 r = rule_line_add_token(rule_line, TK_M_DRIVER, op, value, NULL);
666 } else if (streq(key, "ATTR")) {
667 r = check_attr_format_and_warn(rules, key, attr);
668 if (r < 0)
669 return r;
670 if (op == OP_REMOVE)
671 return log_token_invalid_op(rules, key);
672 if (IN_SET(op, OP_ADD, OP_ASSIGN_FINAL)) {
673 log_token_warning(rules, "%s key takes '==', '!=', or '=' operator, assuming '=', but please fix it.", key);
674 op = OP_ASSIGN;
675 }
676
677 if (!is_match) {
678 check_value_format_and_warn(rules, key, value, false);
679 r = rule_line_add_token(rule_line, TK_A_ATTR, op, value, attr);
680 } else
681 r = rule_line_add_token(rule_line, TK_M_ATTR, op, value, attr);
682 } else if (streq(key, "SYSCTL")) {
683 r = check_attr_format_and_warn(rules, key, attr);
684 if (r < 0)
685 return r;
686 if (op == OP_REMOVE)
687 return log_token_invalid_op(rules, key);
688 if (IN_SET(op, OP_ADD, OP_ASSIGN_FINAL)) {
689 log_token_warning(rules, "%s key takes '==', '!=', or '=' operator, assuming '=', but please fix it.", key);
690 op = OP_ASSIGN;
691 }
692
693 if (!is_match) {
694 check_value_format_and_warn(rules, key, value, false);
695 r = rule_line_add_token(rule_line, TK_A_SYSCTL, op, value, attr);
696 } else
697 r = rule_line_add_token(rule_line, TK_M_SYSCTL, op, value, attr);
698 } else if (streq(key, "KERNELS")) {
699 if (attr)
700 return log_token_invalid_attr(rules, key);
701 if (!is_match)
702 return log_token_invalid_op(rules, key);
703
704 r = rule_line_add_token(rule_line, TK_M_PARENTS_KERNEL, op, value, NULL);
705 } else if (streq(key, "SUBSYSTEMS")) {
706 if (attr)
707 return log_token_invalid_attr(rules, key);
708 if (!is_match)
709 return log_token_invalid_op(rules, key);
710
711 r = rule_line_add_token(rule_line, TK_M_PARENTS_SUBSYSTEM, op, value, NULL);
712 } else if (streq(key, "DRIVERS")) {
713 if (attr)
714 return log_token_invalid_attr(rules, key);
715 if (!is_match)
716 return log_token_invalid_op(rules, key);
717
718 r = rule_line_add_token(rule_line, TK_M_PARENTS_DRIVER, op, value, NULL);
719 } else if (streq(key, "ATTRS")) {
720 r = check_attr_format_and_warn(rules, key, attr);
721 if (r < 0)
722 return r;
723 if (!is_match)
724 return log_token_invalid_op(rules, key);
725
726 if (startswith(attr, "device/"))
727 log_token_warning(rules, "'device' link may not be available in future kernels; please fix it.");
728 if (strstr(attr, "../"))
729 log_token_warning(rules, "Direct reference to parent sysfs directory, may break in future kernels; please fix it.");
730
731 r = rule_line_add_token(rule_line, TK_M_PARENTS_ATTR, op, value, attr);
732 } else if (streq(key, "TAGS")) {
733 if (attr)
734 return log_token_invalid_attr(rules, key);
735 if (!is_match)
736 return log_token_invalid_op(rules, key);
737
738 r = rule_line_add_token(rule_line, TK_M_PARENTS_TAG, op, value, NULL);
739 } else if (streq(key, "TEST")) {
740 mode_t mode = MODE_INVALID;
741
742 if (!isempty(attr)) {
743 r = parse_mode(attr, &mode);
744 if (r < 0)
745 return log_token_error_errno(rules, r, "Failed to parse mode '%s': %m", attr);
746 }
747 check_value_format_and_warn(rules, key, value, true);
748 if (!is_match)
749 return log_token_invalid_op(rules, key);
750
751 r = rule_line_add_token(rule_line, TK_M_TEST, op, value, MODE_TO_PTR(mode));
752 } else if (streq(key, "PROGRAM")) {
753 if (attr)
754 return log_token_invalid_attr(rules, key);
755 check_value_format_and_warn(rules, key, value, true);
756 if (op == OP_REMOVE)
757 return log_token_invalid_op(rules, key);
758 if (!is_match) {
759 log_token_debug(rules, "%s key takes '==' or '!=' operator, assuming '=='.", key);
760 op = OP_MATCH;
761 }
762
763 r = rule_line_add_token(rule_line, TK_M_PROGRAM, op, value, NULL);
764 } else if (streq(key, "IMPORT")) {
765 if (isempty(attr))
766 return log_token_invalid_attr(rules, key);
767 check_value_format_and_warn(rules, key, value, true);
768 if (op == OP_REMOVE)
769 return log_token_invalid_op(rules, key);
770 if (!is_match) {
771 log_token_debug(rules, "%s key takes '==' or '!=' operator, assuming '=='.", key);
772 op = OP_MATCH;
773 }
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 log_token_debug(rules, "Operator '+=' is specified to %s key, assuming '='.", key);
818 op = OP_ASSIGN;
819 }
820
821 if (streq(value, "string_escape=none"))
822 r = rule_line_add_token(rule_line, TK_A_OPTIONS_STRING_ESCAPE_NONE, op, NULL, NULL);
823 else if (streq(value, "string_escape=replace"))
824 r = rule_line_add_token(rule_line, TK_A_OPTIONS_STRING_ESCAPE_REPLACE, op, NULL, NULL);
825 else if (streq(value, "db_persist"))
826 r = rule_line_add_token(rule_line, TK_A_OPTIONS_DB_PERSIST, op, NULL, NULL);
827 else if (streq(value, "watch"))
828 r = rule_line_add_token(rule_line, TK_A_OPTIONS_INOTIFY_WATCH, op, NULL, INT_TO_PTR(1));
829 else if (streq(value, "nowatch"))
830 r = rule_line_add_token(rule_line, TK_A_OPTIONS_INOTIFY_WATCH, op, NULL, INT_TO_PTR(0));
831 else if ((tmp = startswith(value, "static_node=")))
832 r = rule_line_add_token(rule_line, TK_A_OPTIONS_STATIC_NODE, op, tmp, NULL);
833 else if ((tmp = startswith(value, "link_priority="))) {
834 int prio;
835
836 r = safe_atoi(tmp, &prio);
837 if (r < 0)
838 return log_token_error_errno(rules, r, "Failed to parse link priority '%s': %m", tmp);
839 r = rule_line_add_token(rule_line, TK_A_OPTIONS_DEVLINK_PRIORITY, op, NULL, INT_TO_PTR(prio));
840 } else {
841 log_token_warning(rules, "Invalid value for OPTIONS key, ignoring: '%s'", value);
842 return 0;
843 }
844 } else if (streq(key, "OWNER")) {
845 uid_t uid;
846
847 if (attr)
848 return log_token_invalid_attr(rules, key);
849 if (is_match || op == OP_REMOVE)
850 return log_token_invalid_op(rules, key);
851 if (op == OP_ADD) {
852 log_token_warning(rules, "%s key takes '=' or ':=' operator, assuming '=', but please fix it.", key);
853 op = OP_ASSIGN;
854 }
855
856 if (parse_uid(value, &uid) >= 0)
857 r = rule_line_add_token(rule_line, TK_A_OWNER_ID, op, NULL, UID_TO_PTR(uid));
858 else if (rules->resolve_name_timing == RESOLVE_NAME_EARLY &&
859 rule_get_substitution_type(value) == SUBST_TYPE_PLAIN) {
860 r = rule_resolve_user(rules, value, &uid);
861 if (r < 0)
862 return log_token_error_errno(rules, r, "Failed to resolve user name '%s': %m", value);
863
864 r = rule_line_add_token(rule_line, TK_A_OWNER_ID, op, NULL, UID_TO_PTR(uid));
865 } else if (rules->resolve_name_timing != RESOLVE_NAME_NEVER) {
866 check_value_format_and_warn(rules, key, value, true);
867 r = rule_line_add_token(rule_line, TK_A_OWNER, op, value, NULL);
868 } else {
869 log_token_debug(rules, "Resolving user name is disabled, ignoring %s=%s", key, value);
870 return 0;
871 }
872 } else if (streq(key, "GROUP")) {
873 gid_t gid;
874
875 if (attr)
876 return log_token_invalid_attr(rules, key);
877 if (is_match || op == OP_REMOVE)
878 return log_token_invalid_op(rules, key);
879 if (op == OP_ADD) {
880 log_token_warning(rules, "%s key takes '=' or ':=' operator, assuming '=', but please fix it.", key);
881 op = OP_ASSIGN;
882 }
883
884 if (parse_gid(value, &gid) >= 0)
885 r = rule_line_add_token(rule_line, TK_A_GROUP_ID, op, NULL, GID_TO_PTR(gid));
886 else if (rules->resolve_name_timing == RESOLVE_NAME_EARLY &&
887 rule_get_substitution_type(value) == SUBST_TYPE_PLAIN) {
888 r = rule_resolve_group(rules, value, &gid);
889 if (r < 0)
890 return log_token_error_errno(rules, r, "Failed to resolve group name '%s': %m", value);
891
892 r = rule_line_add_token(rule_line, TK_A_GROUP_ID, op, NULL, GID_TO_PTR(gid));
893 } else if (rules->resolve_name_timing != RESOLVE_NAME_NEVER) {
894 check_value_format_and_warn(rules, key, value, true);
895 r = rule_line_add_token(rule_line, TK_A_GROUP, op, value, NULL);
896 } else {
897 log_token_debug(rules, "Resolving group name is disabled, ignoring %s=%s", key, value);
898 return 0;
899 }
900 } else if (streq(key, "MODE")) {
901 mode_t mode;
902
903 if (attr)
904 return log_token_invalid_attr(rules, key);
905 if (is_match || op == OP_REMOVE)
906 return log_token_invalid_op(rules, key);
907 if (op == OP_ADD) {
908 log_token_warning(rules, "%s key takes '=' or ':=' operator, assuming '=', but please fix it.", key);
909 op = OP_ASSIGN;
910 }
911
912 if (parse_mode(value, &mode) >= 0)
913 r = rule_line_add_token(rule_line, TK_A_MODE_ID, op, NULL, MODE_TO_PTR(mode));
914 else {
915 check_value_format_and_warn(rules, key, value, true);
916 r = rule_line_add_token(rule_line, TK_A_MODE, op, value, NULL);
917 }
918 } else if (streq(key, "SECLABEL")) {
919 if (isempty(attr))
920 return log_token_invalid_attr(rules, key);
921 check_value_format_and_warn(rules, key, value, true);
922 if (is_match || op == OP_REMOVE)
923 return log_token_invalid_op(rules, key);
924 if (op == OP_ASSIGN_FINAL) {
925 log_token_warning(rules, "%s key takes '=' or '+=' operator, assuming '=', but please fix it.", key);
926 op = OP_ASSIGN;
927 }
928
929 r = rule_line_add_token(rule_line, TK_A_SECLABEL, op, value, attr);
930 } else if (streq(key, "RUN")) {
931 if (is_match || op == OP_REMOVE)
932 return log_token_invalid_op(rules, key);
933 check_value_format_and_warn(rules, key, value, true);
934 if (!attr || streq(attr, "program"))
935 r = rule_line_add_token(rule_line, TK_A_RUN_PROGRAM, op, value, NULL);
936 else if (streq(attr, "builtin")) {
937 UdevBuiltinCommand cmd;
938
939 cmd = udev_builtin_lookup(value);
940 if (cmd < 0)
941 return log_token_error_errno(rules, SYNTHETIC_ERRNO(EINVAL),
942 "Unknown builtin command '%s', ignoring", value);
943 r = rule_line_add_token(rule_line, TK_A_RUN_BUILTIN, op, value, UDEV_BUILTIN_CMD_TO_PTR(cmd));
944 } else
945 return log_token_invalid_attr(rules, key);
946 } else if (streq(key, "GOTO")) {
947 if (attr)
948 return log_token_invalid_attr(rules, key);
949 if (op != OP_ASSIGN)
950 return log_token_invalid_op(rules, key);
951 if (FLAGS_SET(rule_line->type, LINE_HAS_GOTO)) {
952 log_token_warning(rules, "Contains multiple GOTO key, ignoring GOTO=\"%s\".", value);
953 return 0;
954 }
955
956 rule_line->goto_label = value;
957 SET_FLAG(rule_line->type, LINE_HAS_GOTO, true);
958 return 1;
959 } else if (streq(key, "LABEL")) {
960 if (attr)
961 return log_token_invalid_attr(rules, key);
962 if (op != OP_ASSIGN)
963 return log_token_invalid_op(rules, key);
964
965 rule_line->label = value;
966 SET_FLAG(rule_line->type, LINE_HAS_LABEL, true);
967 return 1;
968 } else
969 return log_token_error_errno(rules, SYNTHETIC_ERRNO(EINVAL), "Invalid key '%s'", key);
970 if (r < 0)
971 return log_oom();
972
973 return 1;
974 }
975
976 static UdevRuleOperatorType parse_operator(const char *op) {
977 assert(op);
978
979 if (startswith(op, "=="))
980 return OP_MATCH;
981 if (startswith(op, "!="))
982 return OP_NOMATCH;
983 if (startswith(op, "+="))
984 return OP_ADD;
985 if (startswith(op, "-="))
986 return OP_REMOVE;
987 if (startswith(op, "="))
988 return OP_ASSIGN;
989 if (startswith(op, ":="))
990 return OP_ASSIGN_FINAL;
991
992 return _OP_TYPE_INVALID;
993 }
994
995 static int parse_line(char **line, char **ret_key, char **ret_attr, UdevRuleOperatorType *ret_op, char **ret_value) {
996 char *key_begin, *key_end, *attr, *tmp, *value, *i, *j;
997 UdevRuleOperatorType op;
998
999 assert(line);
1000 assert(*line);
1001 assert(ret_key);
1002 assert(ret_op);
1003 assert(ret_value);
1004
1005 key_begin = skip_leading_chars(*line, WHITESPACE ",");
1006
1007 if (isempty(key_begin))
1008 return 0;
1009
1010 for (key_end = key_begin; ; key_end++) {
1011 if (key_end[0] == '\0')
1012 return -EINVAL;
1013 if (strchr(WHITESPACE "={", key_end[0]))
1014 break;
1015 if (strchr("+-!:", key_end[0]) && key_end[1] == '=')
1016 break;
1017 }
1018 if (key_end[0] == '{') {
1019 attr = key_end + 1;
1020 tmp = strchr(attr, '}');
1021 if (!tmp)
1022 return -EINVAL;
1023 *tmp++ = '\0';
1024 } else {
1025 attr = NULL;
1026 tmp = key_end;
1027 }
1028
1029 tmp = skip_leading_chars(tmp, NULL);
1030 op = parse_operator(tmp);
1031 if (op < 0)
1032 return -EINVAL;
1033
1034 key_end[0] = '\0';
1035
1036 tmp += op == OP_ASSIGN ? 1 : 2;
1037 value = skip_leading_chars(tmp, NULL);
1038
1039 /* value must be double quotated */
1040 if (value[0] != '"')
1041 return -EINVAL;
1042 value++;
1043
1044 /* unescape double quotation '\"' -> '"' */
1045 for (i = j = value; ; i++, j++) {
1046 if (*i == '"')
1047 break;
1048 if (*i == '\0')
1049 return -EINVAL;
1050 if (i[0] == '\\' && i[1] == '"')
1051 i++;
1052 *j = *i;
1053 }
1054 j[0] = '\0';
1055
1056 *line = i+1;
1057 *ret_key = key_begin;
1058 *ret_attr = attr;
1059 *ret_op = op;
1060 *ret_value = value;
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_AFTER(rule_lines, i, line)
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, UTIL_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 >= UTIL_LINE_SIZE)
1248 ignore_line = true;
1249
1250 if (!strextend(&continuation, line, NULL))
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("Invalid match type");
1379 }
1380
1381 return token->op == (match ? OP_MATCH : OP_NOMATCH);
1382 }
1383
1384 static bool token_match_attr(UdevRuleToken *token, sd_device *dev, UdevEvent *event) {
1385 char nbuf[UTIL_NAME_SIZE], vbuf[UTIL_NAME_SIZE];
1386 const char *name, *value;
1387
1388 assert(token);
1389 assert(dev);
1390 assert(event);
1391
1392 name = (const char*) token->data;
1393
1394 switch (token->attr_subst_type) {
1395 case SUBST_TYPE_FORMAT:
1396 (void) udev_event_apply_format(event, name, nbuf, sizeof(nbuf), false);
1397 name = nbuf;
1398 _fallthrough_;
1399 case SUBST_TYPE_PLAIN:
1400 if (sd_device_get_sysattr_value(dev, name, &value) < 0)
1401 return false;
1402 break;
1403 case SUBST_TYPE_SUBSYS:
1404 if (util_resolve_subsys_kernel(name, vbuf, sizeof(vbuf), true) < 0)
1405 return false;
1406 value = vbuf;
1407 break;
1408 default:
1409 assert_not_reached("Invalid attribute substitution type");
1410 }
1411
1412 /* remove trailing whitespace, if not asked to match for it */
1413 if (token->attr_match_remove_trailing_whitespace) {
1414 if (value != vbuf) {
1415 strscpy(vbuf, sizeof(vbuf), value);
1416 value = vbuf;
1417 }
1418
1419 delete_trailing_chars(vbuf, NULL);
1420 }
1421
1422 return token_match_string(token, value);
1423 }
1424
1425 static int get_property_from_string(char *line, char **ret_key, char **ret_value) {
1426 char *key, *val;
1427 size_t len;
1428
1429 assert(line);
1430 assert(ret_key);
1431 assert(ret_value);
1432
1433 /* find key */
1434 key = skip_leading_chars(line, NULL);
1435
1436 /* comment or empty line */
1437 if (IN_SET(key[0], '#', '\0')) {
1438 *ret_key = *ret_value = NULL;
1439 return 0;
1440 }
1441
1442 /* split key/value */
1443 val = strchr(key, '=');
1444 if (!val)
1445 return -EINVAL;
1446 *val++ = '\0';
1447
1448 key = strstrip(key);
1449 if (isempty(key))
1450 return -EINVAL;
1451
1452 val = strstrip(val);
1453 if (isempty(val))
1454 return -EINVAL;
1455
1456 /* unquote */
1457 if (IN_SET(val[0], '"', '\'')) {
1458 len = strlen(val);
1459 if (len == 1 || val[len-1] != val[0])
1460 return -EINVAL;
1461 val[len-1] = '\0';
1462 val++;
1463 }
1464
1465 *ret_key = key;
1466 *ret_value = val;
1467 return 1;
1468 }
1469
1470 static int import_parent_into_properties(sd_device *dev, const char *filter) {
1471 const char *key, *val;
1472 sd_device *parent;
1473 int r;
1474
1475 assert(dev);
1476 assert(filter);
1477
1478 r = sd_device_get_parent(dev, &parent);
1479 if (r == -ENOENT)
1480 return 0;
1481 if (r < 0)
1482 return r;
1483
1484 FOREACH_DEVICE_PROPERTY(parent, key, val) {
1485 if (fnmatch(filter, key, 0) != 0)
1486 continue;
1487 r = device_add_property(dev, key, val);
1488 if (r < 0)
1489 return r;
1490 }
1491
1492 return 1;
1493 }
1494
1495 static int attr_subst_subdir(char attr[static UTIL_PATH_SIZE]) {
1496 _cleanup_closedir_ DIR *dir = NULL;
1497 struct dirent *dent;
1498 char buf[UTIL_PATH_SIZE], *p;
1499 const char *tail;
1500 size_t len, size;
1501
1502 assert(attr);
1503
1504 tail = strstr(attr, "/*/");
1505 if (!tail)
1506 return 0;
1507
1508 len = tail - attr + 1; /* include slash at the end */
1509 tail += 2; /* include slash at the beginning */
1510
1511 p = buf;
1512 size = sizeof(buf);
1513 size -= strnpcpy(&p, size, attr, len);
1514
1515 dir = opendir(buf);
1516 if (!dir)
1517 return -errno;
1518
1519 FOREACH_DIRENT_ALL(dent, dir, break) {
1520 if (dent->d_name[0] == '.')
1521 continue;
1522
1523 strscpyl(p, size, dent->d_name, tail, NULL);
1524 if (faccessat(dirfd(dir), p, F_OK, 0) < 0)
1525 continue;
1526
1527 strcpy(attr, buf);
1528 return 0;
1529 }
1530
1531 return -ENOENT;
1532 }
1533
1534 static int udev_rule_apply_token_to_event(
1535 UdevRules *rules,
1536 sd_device *dev,
1537 UdevEvent *event,
1538 usec_t timeout_usec,
1539 int timeout_signal,
1540 Hashmap *properties_list) {
1541
1542 UdevRuleToken *token;
1543 char buf[UTIL_PATH_SIZE];
1544 const char *val;
1545 size_t count;
1546 bool match;
1547 int r;
1548
1549 assert(rules);
1550 assert(dev);
1551 assert(event);
1552
1553 /* This returns the following values:
1554 * 0 on the current token does not match the event,
1555 * 1 on the current token matches the event, and
1556 * negative errno on some critical errors. */
1557
1558 token = rules->current_file->current_line->current_token;
1559
1560 switch (token->type) {
1561 case TK_M_ACTION: {
1562 DeviceAction a;
1563
1564 r = device_get_action(dev, &a);
1565 if (r < 0)
1566 return log_rule_error_errno(dev, rules, r, "Failed to get uevent action type: %m");
1567
1568 return token_match_string(token, device_action_to_string(a));
1569 }
1570 case TK_M_DEVPATH:
1571 r = sd_device_get_devpath(dev, &val);
1572 if (r < 0)
1573 return log_rule_error_errno(dev, rules, r, "Failed to get devpath: %m");
1574
1575 return token_match_string(token, val);
1576 case TK_M_KERNEL:
1577 case TK_M_PARENTS_KERNEL:
1578 r = sd_device_get_sysname(dev, &val);
1579 if (r < 0)
1580 return log_rule_error_errno(dev, rules, r, "Failed to get sysname: %m");
1581
1582 return token_match_string(token, val);
1583 case TK_M_DEVLINK:
1584 FOREACH_DEVICE_DEVLINK(dev, val)
1585 if (token_match_string(token, strempty(startswith(val, "/dev/"))))
1586 return token->op == OP_MATCH;
1587 return token->op == OP_NOMATCH;
1588 case TK_M_NAME:
1589 return token_match_string(token, event->name);
1590 case TK_M_ENV:
1591 if (sd_device_get_property_value(dev, (const char*) token->data, &val) < 0)
1592 val = hashmap_get(properties_list, token->data);
1593
1594 return token_match_string(token, val);
1595 case TK_M_CONST: {
1596 const char *k = token->data;
1597
1598 if (streq(k, "arch"))
1599 val = architecture_to_string(uname_architecture());
1600 else if (streq(k, "virt"))
1601 val = virtualization_to_string(detect_virtualization());
1602 else
1603 assert_not_reached("Invalid CONST key");
1604 return token_match_string(token, val);
1605 }
1606 case TK_M_TAG:
1607 case TK_M_PARENTS_TAG:
1608 FOREACH_DEVICE_TAG(dev, val)
1609 if (token_match_string(token, val))
1610 return token->op == OP_MATCH;
1611 return token->op == OP_NOMATCH;
1612 case TK_M_SUBSYSTEM:
1613 case TK_M_PARENTS_SUBSYSTEM:
1614 r = sd_device_get_subsystem(dev, &val);
1615 if (r == -ENOENT)
1616 val = NULL;
1617 else if (r < 0)
1618 return log_rule_error_errno(dev, rules, r, "Failed to get subsystem: %m");
1619
1620 return token_match_string(token, val);
1621 case TK_M_DRIVER:
1622 case TK_M_PARENTS_DRIVER:
1623 r = sd_device_get_driver(dev, &val);
1624 if (r == -ENOENT)
1625 val = NULL;
1626 else if (r < 0)
1627 return log_rule_error_errno(dev, rules, r, "Failed to get driver: %m");
1628
1629 return token_match_string(token, val);
1630 case TK_M_ATTR:
1631 case TK_M_PARENTS_ATTR:
1632 return token_match_attr(token, dev, event);
1633 case TK_M_SYSCTL: {
1634 _cleanup_free_ char *value = NULL;
1635
1636 (void) udev_event_apply_format(event, (const char*) token->data, buf, sizeof(buf), false);
1637 r = sysctl_read(sysctl_normalize(buf), &value);
1638 if (r < 0 && r != -ENOENT)
1639 return log_rule_error_errno(dev, rules, r, "Failed to read sysctl '%s': %m", buf);
1640
1641 return token_match_string(token, strstrip(value));
1642 }
1643 case TK_M_TEST: {
1644 mode_t mode = PTR_TO_MODE(token->data);
1645 struct stat statbuf;
1646
1647 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false);
1648 if (!path_is_absolute(buf) &&
1649 util_resolve_subsys_kernel(buf, buf, sizeof(buf), false) < 0) {
1650 char tmp[UTIL_PATH_SIZE];
1651
1652 r = sd_device_get_syspath(dev, &val);
1653 if (r < 0)
1654 return log_rule_error_errno(dev, rules, r, "Failed to get syspath: %m");
1655
1656 strscpy(tmp, sizeof(tmp), buf);
1657 strscpyl(buf, sizeof(buf), val, "/", tmp, NULL);
1658 }
1659
1660 r = attr_subst_subdir(buf);
1661 if (r == -ENOENT)
1662 return token->op == OP_NOMATCH;
1663 if (r < 0)
1664 return log_rule_error_errno(dev, rules, r, "Failed to test the existence of '%s': %m", buf);
1665
1666 if (stat(buf, &statbuf) < 0)
1667 return token->op == OP_NOMATCH;
1668
1669 if (mode == MODE_INVALID)
1670 return token->op == OP_MATCH;
1671
1672 match = (statbuf.st_mode & mode) > 0;
1673 return token->op == (match ? OP_MATCH : OP_NOMATCH);
1674 }
1675 case TK_M_PROGRAM: {
1676 char result[UTIL_LINE_SIZE];
1677
1678 event->program_result = mfree(event->program_result);
1679 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false);
1680 log_rule_debug(dev, rules, "Running PROGRAM '%s'", buf);
1681
1682 r = udev_event_spawn(event, timeout_usec, timeout_signal, true, buf, result, sizeof(result));
1683 if (r != 0) {
1684 if (r < 0)
1685 log_rule_warning_errno(dev, rules, r, "Failed to execute '%s', ignoring: %m", buf);
1686 else /* returned value is positive when program fails */
1687 log_rule_debug(dev, rules, "Command \"%s\" returned %d (error), ignoring", buf, r);
1688 return token->op == OP_NOMATCH;
1689 }
1690
1691 delete_trailing_chars(result, "\n");
1692 count = util_replace_chars(result, UDEV_ALLOWED_CHARS_INPUT);
1693 if (count > 0)
1694 log_rule_debug(dev, rules, "Replaced %zu character(s) from result of '%s'",
1695 count, buf);
1696
1697 event->program_result = strdup(result);
1698 return token->op == OP_MATCH;
1699 }
1700 case TK_M_IMPORT_FILE: {
1701 _cleanup_fclose_ FILE *f = NULL;
1702
1703 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false);
1704 log_rule_debug(dev, rules, "Importing properties from '%s'", buf);
1705
1706 f = fopen(buf, "re");
1707 if (!f) {
1708 if (errno != ENOENT)
1709 return log_rule_error_errno(dev, rules, errno,
1710 "Failed to open '%s': %m", buf);
1711 return token->op == OP_NOMATCH;
1712 }
1713
1714 for (;;) {
1715 _cleanup_free_ char *line = NULL;
1716 char *key, *value;
1717
1718 r = read_line(f, LONG_LINE_MAX, &line);
1719 if (r < 0) {
1720 log_rule_debug_errno(dev, rules, r,
1721 "Failed to read '%s', ignoring: %m", buf);
1722 return token->op == OP_NOMATCH;
1723 }
1724 if (r == 0)
1725 break;
1726
1727 r = get_property_from_string(line, &key, &value);
1728 if (r < 0) {
1729 log_rule_debug_errno(dev, rules, r,
1730 "Failed to parse key and value from '%s', ignoring: %m",
1731 line);
1732 continue;
1733 }
1734 if (r == 0)
1735 continue;
1736
1737 r = device_add_property(dev, key, value);
1738 if (r < 0)
1739 return log_rule_error_errno(dev, rules, r,
1740 "Failed to add property %s=%s: %m",
1741 key, value);
1742 }
1743
1744 return token->op == OP_MATCH;
1745 }
1746 case TK_M_IMPORT_PROGRAM: {
1747 char result[UTIL_LINE_SIZE], *line, *pos;
1748
1749 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false);
1750 log_rule_debug(dev, rules, "Importing properties from results of '%s'", buf);
1751
1752 r = udev_event_spawn(event, timeout_usec, timeout_signal, true, buf, result, sizeof result);
1753 if (r != 0) {
1754 if (r < 0)
1755 log_rule_warning_errno(dev, rules, r, "Failed to execute '%s', ignoring: %m", buf);
1756 else /* returned value is positive when program fails */
1757 log_rule_debug(dev, rules, "Command \"%s\" returned %d (error), ignoring", buf, r);
1758 return token->op == OP_NOMATCH;
1759 }
1760
1761 for (line = result; !isempty(line); line = pos) {
1762 char *key, *value;
1763
1764 pos = strchr(line, '\n');
1765 if (pos)
1766 *pos++ = '\0';
1767
1768 r = get_property_from_string(line, &key, &value);
1769 if (r < 0) {
1770 log_rule_debug_errno(dev, rules, r,
1771 "Failed to parse key and value from '%s', ignoring: %m",
1772 line);
1773 continue;
1774 }
1775 if (r == 0)
1776 continue;
1777
1778 r = device_add_property(dev, key, value);
1779 if (r < 0)
1780 return log_rule_error_errno(dev, rules, r,
1781 "Failed to add property %s=%s: %m",
1782 key, value);
1783 }
1784
1785 return token->op == OP_MATCH;
1786 }
1787 case TK_M_IMPORT_BUILTIN: {
1788 UdevBuiltinCommand cmd = PTR_TO_UDEV_BUILTIN_CMD(token->data);
1789 unsigned mask = 1U << (int) cmd;
1790
1791 if (udev_builtin_run_once(cmd)) {
1792 /* check if we ran already */
1793 if (event->builtin_run & mask) {
1794 log_rule_debug(dev, rules, "Skipping builtin '%s' in IMPORT key",
1795 udev_builtin_name(cmd));
1796 /* return the result from earlier run */
1797 return token->op == (event->builtin_ret & mask ? OP_NOMATCH : OP_MATCH);
1798 }
1799 /* mark as ran */
1800 event->builtin_run |= mask;
1801 }
1802
1803 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false);
1804 log_rule_debug(dev, rules, "Importing properties from results of builtin command '%s'", buf);
1805
1806 r = udev_builtin_run(dev, cmd, buf, false);
1807 if (r < 0) {
1808 /* remember failure */
1809 log_rule_debug_errno(dev, rules, r, "Failed to run builtin '%s': %m", buf);
1810 event->builtin_ret |= mask;
1811 }
1812 return token->op == (r >= 0 ? OP_MATCH : OP_NOMATCH);
1813 }
1814 case TK_M_IMPORT_DB: {
1815 if (!event->dev_db_clone)
1816 return token->op == OP_NOMATCH;
1817 r = sd_device_get_property_value(event->dev_db_clone, token->value, &val);
1818 if (r == -ENOENT)
1819 return token->op == OP_NOMATCH;
1820 if (r < 0)
1821 return log_rule_error_errno(dev, rules, r,
1822 "Failed to get property '%s' from database: %m",
1823 token->value);
1824
1825 r = device_add_property(dev, token->value, val);
1826 if (r < 0)
1827 return log_rule_error_errno(dev, rules, r, "Failed to add property '%s=%s': %m",
1828 token->value, val);
1829 return token->op == OP_MATCH;
1830 }
1831 case TK_M_IMPORT_CMDLINE: {
1832 _cleanup_free_ char *value = NULL;
1833
1834 r = proc_cmdline_get_key(token->value, PROC_CMDLINE_VALUE_OPTIONAL|PROC_CMDLINE_IGNORE_EFI_OPTIONS, &value);
1835 if (r < 0)
1836 return log_rule_error_errno(dev, rules, r,
1837 "Failed to read '%s' option from /proc/cmdline: %m",
1838 token->value);
1839 if (r == 0)
1840 return token->op == OP_NOMATCH;
1841
1842 r = device_add_property(dev, token->value, value ?: "1");
1843 if (r < 0)
1844 return log_rule_error_errno(dev, rules, r, "Failed to add property '%s=%s': %m",
1845 token->value, value ?: "1");
1846 return token->op == OP_MATCH;
1847 }
1848 case TK_M_IMPORT_PARENT: {
1849 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false);
1850 r = import_parent_into_properties(dev, buf);
1851 if (r < 0)
1852 return log_rule_error_errno(dev, rules, r,
1853 "Failed to import properties '%s' from parent: %m",
1854 buf);
1855 return token->op == (r > 0 ? OP_MATCH : OP_NOMATCH);
1856 }
1857 case TK_M_RESULT:
1858 return token_match_string(token, event->program_result);
1859 case TK_A_OPTIONS_STRING_ESCAPE_NONE:
1860 event->esc = ESCAPE_NONE;
1861 break;
1862 case TK_A_OPTIONS_STRING_ESCAPE_REPLACE:
1863 event->esc = ESCAPE_REPLACE;
1864 break;
1865 case TK_A_OPTIONS_DB_PERSIST:
1866 device_set_db_persist(dev);
1867 break;
1868 case TK_A_OPTIONS_INOTIFY_WATCH:
1869 if (event->inotify_watch_final)
1870 break;
1871 if (token->op == OP_ASSIGN_FINAL)
1872 event->inotify_watch_final = true;
1873
1874 event->inotify_watch = token->data;
1875 break;
1876 case TK_A_OPTIONS_DEVLINK_PRIORITY:
1877 device_set_devlink_priority(dev, PTR_TO_INT(token->data));
1878 break;
1879 case TK_A_OWNER: {
1880 char owner[UTIL_NAME_SIZE];
1881 const char *ow = owner;
1882
1883 if (event->owner_final)
1884 break;
1885 if (token->op == OP_ASSIGN_FINAL)
1886 event->owner_final = true;
1887
1888 (void) udev_event_apply_format(event, token->value, owner, sizeof(owner), false);
1889 r = get_user_creds(&ow, &event->uid, NULL, NULL, NULL, USER_CREDS_ALLOW_MISSING);
1890 if (r < 0)
1891 log_unknown_owner(dev, rules, r, "user", owner);
1892 else
1893 log_rule_debug(dev, rules, "OWNER %s(%u)", owner, event->uid);
1894 break;
1895 }
1896 case TK_A_GROUP: {
1897 char group[UTIL_NAME_SIZE];
1898 const char *gr = group;
1899
1900 if (event->group_final)
1901 break;
1902 if (token->op == OP_ASSIGN_FINAL)
1903 event->group_final = true;
1904
1905 (void) udev_event_apply_format(event, token->value, group, sizeof(group), false);
1906 r = get_group_creds(&gr, &event->gid, USER_CREDS_ALLOW_MISSING);
1907 if (r < 0)
1908 log_unknown_owner(dev, rules, r, "group", group);
1909 else
1910 log_rule_debug(dev, rules, "GROUP %s(%u)", group, event->gid);
1911 break;
1912 }
1913 case TK_A_MODE: {
1914 char mode_str[UTIL_NAME_SIZE];
1915
1916 if (event->mode_final)
1917 break;
1918 if (token->op == OP_ASSIGN_FINAL)
1919 event->mode_final = true;
1920
1921 (void) udev_event_apply_format(event, token->value, mode_str, sizeof(mode_str), false);
1922 r = parse_mode(mode_str, &event->mode);
1923 if (r < 0)
1924 log_rule_error_errno(dev, rules, r, "Failed to parse mode '%s', ignoring: %m", mode_str);
1925 else
1926 log_rule_debug(dev, rules, "MODE %#o", event->mode);
1927 break;
1928 }
1929 case TK_A_OWNER_ID:
1930 if (event->owner_final)
1931 break;
1932 if (token->op == OP_ASSIGN_FINAL)
1933 event->owner_final = true;
1934 if (!token->data)
1935 break;
1936 event->uid = PTR_TO_UID(token->data);
1937 log_rule_debug(dev, rules, "OWNER %u", event->uid);
1938 break;
1939 case TK_A_GROUP_ID:
1940 if (event->group_final)
1941 break;
1942 if (token->op == OP_ASSIGN_FINAL)
1943 event->group_final = true;
1944 if (!token->data)
1945 break;
1946 event->gid = PTR_TO_GID(token->data);
1947 log_rule_debug(dev, rules, "GROUP %u", event->gid);
1948 break;
1949 case TK_A_MODE_ID:
1950 if (event->mode_final)
1951 break;
1952 if (token->op == OP_ASSIGN_FINAL)
1953 event->mode_final = true;
1954 if (!token->data)
1955 break;
1956 event->mode = PTR_TO_MODE(token->data);
1957 log_rule_debug(dev, rules, "MODE %#o", event->mode);
1958 break;
1959 case TK_A_SECLABEL: {
1960 _cleanup_free_ char *name = NULL, *label = NULL;
1961 char label_str[UTIL_LINE_SIZE] = {};
1962
1963 name = strdup((const char*) token->data);
1964 if (!name)
1965 return log_oom();
1966
1967 (void) udev_event_apply_format(event, token->value, label_str, sizeof(label_str), false);
1968 if (!isempty(label_str))
1969 label = strdup(label_str);
1970 else
1971 label = strdup(token->value);
1972 if (!label)
1973 return log_oom();
1974
1975 if (token->op == OP_ASSIGN)
1976 ordered_hashmap_clear_free_free(event->seclabel_list);
1977
1978 r = ordered_hashmap_ensure_allocated(&event->seclabel_list, NULL);
1979 if (r < 0)
1980 return log_oom();
1981
1982 r = ordered_hashmap_put(event->seclabel_list, name, label);
1983 if (r < 0)
1984 return log_oom();
1985 log_rule_debug(dev, rules, "SECLABEL{%s}='%s'", name, label);
1986 name = label = NULL;
1987 break;
1988 }
1989 case TK_A_ENV: {
1990 const char *name = (const char*) token->data;
1991 char value_new[UTIL_NAME_SIZE], *p = value_new;
1992 size_t l = sizeof(value_new);
1993
1994 if (isempty(token->value)) {
1995 if (token->op == OP_ADD)
1996 break;
1997 r = device_add_property(dev, name, NULL);
1998 if (r < 0)
1999 return log_rule_error_errno(dev, rules, r, "Failed to remove property '%s': %m", name);
2000 break;
2001 }
2002
2003 if (token->op == OP_ADD &&
2004 sd_device_get_property_value(dev, name, &val) >= 0)
2005 l = strpcpyl(&p, l, val, " ", NULL);
2006
2007 (void) udev_event_apply_format(event, token->value, p, l, false);
2008
2009 r = device_add_property(dev, name, value_new);
2010 if (r < 0)
2011 return log_rule_error_errno(dev, rules, r, "Failed to add property '%s=%s': %m", name, value_new);
2012 break;
2013 }
2014 case TK_A_TAG: {
2015 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false);
2016 if (token->op == OP_ASSIGN)
2017 device_cleanup_tags(dev);
2018
2019 if (buf[strspn(buf, ALPHANUMERICAL "-_")] != '\0') {
2020 log_rule_error(dev, rules, "Invalid tag name '%s', ignoring", buf);
2021 break;
2022 }
2023 if (token->op == OP_REMOVE)
2024 device_remove_tag(dev, buf);
2025 else {
2026 r = device_add_tag(dev, buf);
2027 if (r < 0)
2028 return log_rule_error_errno(dev, rules, r, "Failed to add tag '%s': %m", buf);
2029 }
2030 break;
2031 }
2032 case TK_A_NAME: {
2033 if (event->name_final)
2034 break;
2035 if (token->op == OP_ASSIGN_FINAL)
2036 event->name_final = true;
2037
2038 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false);
2039 if (IN_SET(event->esc, ESCAPE_UNSET, ESCAPE_REPLACE)) {
2040 count = util_replace_chars(buf, "/");
2041 if (count > 0)
2042 log_rule_debug(dev, rules, "Replaced %zu character(s) from result of NAME=\"%s\"",
2043 count, token->value);
2044 }
2045 if (sd_device_get_devnum(dev, NULL) >= 0 &&
2046 (sd_device_get_devname(dev, &val) < 0 ||
2047 !streq_ptr(buf, startswith(val, "/dev/")))) {
2048 log_rule_error(dev, rules,
2049 "Kernel device nodes cannot be renamed, ignoring NAME=\"%s\"; please fix it.",
2050 token->value);
2051 break;
2052 }
2053 if (free_and_strdup(&event->name, buf) < 0)
2054 return log_oom();
2055
2056 log_rule_debug(dev, rules, "NAME '%s'", event->name);
2057 break;
2058 }
2059 case TK_A_DEVLINK: {
2060 char *p;
2061
2062 if (event->devlink_final)
2063 break;
2064 if (sd_device_get_devnum(dev, NULL) < 0)
2065 break;
2066 if (token->op == OP_ASSIGN_FINAL)
2067 event->devlink_final = true;
2068 if (IN_SET(token->op, OP_ASSIGN, OP_ASSIGN_FINAL))
2069 device_cleanup_devlinks(dev);
2070
2071 /* allow multiple symlinks separated by spaces */
2072 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), event->esc != ESCAPE_NONE);
2073 if (event->esc == ESCAPE_UNSET)
2074 count = util_replace_chars(buf, "/ ");
2075 else if (event->esc == ESCAPE_REPLACE)
2076 count = util_replace_chars(buf, "/");
2077 else
2078 count = 0;
2079 if (count > 0)
2080 log_rule_debug(dev, rules, "Replaced %zu character(s) from result of LINK", count);
2081
2082 p = skip_leading_chars(buf, NULL);
2083 while (!isempty(p)) {
2084 char filename[UTIL_PATH_SIZE], *next;
2085
2086 next = strchr(p, ' ');
2087 if (next) {
2088 *next++ = '\0';
2089 next = skip_leading_chars(next, NULL);
2090 }
2091
2092 strscpyl(filename, sizeof(filename), "/dev/", p, NULL);
2093 r = device_add_devlink(dev, filename);
2094 if (r < 0)
2095 return log_rule_error_errno(dev, rules, r, "Failed to add devlink '%s': %m", filename);
2096
2097 log_rule_debug(dev, rules, "LINK '%s'", p);
2098 p = next;
2099 }
2100 break;
2101 }
2102 case TK_A_ATTR: {
2103 const char *key_name = (const char*) token->data;
2104 char value[UTIL_NAME_SIZE];
2105
2106 if (util_resolve_subsys_kernel(key_name, buf, sizeof(buf), false) < 0 &&
2107 sd_device_get_syspath(dev, &val) >= 0)
2108 strscpyl(buf, sizeof(buf), val, "/", key_name, NULL);
2109
2110 r = attr_subst_subdir(buf);
2111 if (r < 0) {
2112 log_rule_error_errno(dev, rules, r, "Could not find file matches '%s', ignoring: %m", buf);
2113 break;
2114 }
2115 (void) udev_event_apply_format(event, token->value, value, sizeof(value), false);
2116
2117 log_rule_debug(dev, rules, "ATTR '%s' writing '%s'", buf, value);
2118 r = write_string_file(buf, value, WRITE_STRING_FILE_VERIFY_ON_FAILURE | WRITE_STRING_FILE_DISABLE_BUFFER | WRITE_STRING_FILE_AVOID_NEWLINE);
2119 if (r < 0)
2120 log_rule_error_errno(dev, rules, r, "Failed to write ATTR{%s}, ignoring: %m", buf);
2121 break;
2122 }
2123 case TK_A_SYSCTL: {
2124 char value[UTIL_NAME_SIZE];
2125
2126 (void) udev_event_apply_format(event, (const char*) token->data, buf, sizeof(buf), false);
2127 (void) udev_event_apply_format(event, token->value, value, sizeof(value), false);
2128 sysctl_normalize(buf);
2129 log_rule_debug(dev, rules, "SYSCTL '%s' writing '%s'", buf, value);
2130 r = sysctl_write(buf, value);
2131 if (r < 0)
2132 log_rule_error_errno(dev, rules, r, "Failed to write SYSCTL{%s}='%s', ignoring: %m", buf, value);
2133 break;
2134 }
2135 case TK_A_RUN_BUILTIN:
2136 case TK_A_RUN_PROGRAM: {
2137 _cleanup_free_ char *cmd = NULL;
2138
2139 if (event->run_final)
2140 break;
2141 if (token->op == OP_ASSIGN_FINAL)
2142 event->run_final = true;
2143
2144 if (IN_SET(token->op, OP_ASSIGN, OP_ASSIGN_FINAL))
2145 ordered_hashmap_clear_free_key(event->run_list);
2146
2147 r = ordered_hashmap_ensure_allocated(&event->run_list, NULL);
2148 if (r < 0)
2149 return log_oom();
2150
2151 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false);
2152
2153 cmd = strdup(buf);
2154 if (!cmd)
2155 return log_oom();
2156
2157 r = ordered_hashmap_put(event->run_list, cmd, token->data);
2158 if (r < 0)
2159 return log_oom();
2160
2161 TAKE_PTR(cmd);
2162
2163 log_rule_debug(dev, rules, "RUN '%s'", token->value);
2164 break;
2165 }
2166 case TK_A_OPTIONS_STATIC_NODE:
2167 /* do nothing for events. */
2168 break;
2169 default:
2170 assert_not_reached("Invalid token type");
2171 }
2172
2173 return true;
2174 }
2175
2176 static bool token_is_for_parents(UdevRuleToken *token) {
2177 return token->type >= TK_M_PARENTS_KERNEL && token->type <= TK_M_PARENTS_TAG;
2178 }
2179
2180 static int udev_rule_apply_parent_token_to_event(
2181 UdevRules *rules,
2182 UdevEvent *event,
2183 int timeout_signal) {
2184
2185 UdevRuleLine *line;
2186 UdevRuleToken *head;
2187 int r;
2188
2189 line = rules->current_file->current_line;
2190 head = rules->current_file->current_line->current_token;
2191 event->dev_parent = event->dev;
2192 for (;;) {
2193 LIST_FOREACH(tokens, line->current_token, head) {
2194 if (!token_is_for_parents(line->current_token))
2195 return true; /* All parent tokens match. */
2196 r = udev_rule_apply_token_to_event(rules, event->dev_parent, event, 0, timeout_signal, NULL);
2197 if (r < 0)
2198 return r;
2199 if (r == 0)
2200 break;
2201 }
2202 if (!line->current_token)
2203 /* All parent tokens match. But no assign tokens in the line. Hmm... */
2204 return true;
2205
2206 if (sd_device_get_parent(event->dev_parent, &event->dev_parent) < 0) {
2207 event->dev_parent = NULL;
2208 return false;
2209 }
2210 }
2211 }
2212
2213 static int udev_rule_apply_line_to_event(
2214 UdevRules *rules,
2215 UdevEvent *event,
2216 usec_t timeout_usec,
2217 int timeout_signal,
2218 Hashmap *properties_list,
2219 UdevRuleLine **next_line) {
2220
2221 UdevRuleLine *line = rules->current_file->current_line;
2222 UdevRuleLineType mask = LINE_HAS_GOTO | LINE_UPDATE_SOMETHING;
2223 UdevRuleToken *token, *next_token;
2224 bool parents_done = false;
2225 DeviceAction action;
2226 int r;
2227
2228 r = device_get_action(event->dev, &action);
2229 if (r < 0)
2230 return r;
2231
2232 if (action != DEVICE_ACTION_REMOVE) {
2233 if (sd_device_get_devnum(event->dev, NULL) >= 0)
2234 mask |= LINE_HAS_DEVLINK;
2235
2236 if (sd_device_get_ifindex(event->dev, NULL) >= 0)
2237 mask |= LINE_HAS_NAME;
2238 }
2239
2240 if ((line->type & mask) == 0)
2241 return 0;
2242
2243 event->esc = ESCAPE_UNSET;
2244 LIST_FOREACH_SAFE(tokens, token, next_token, line->tokens) {
2245 line->current_token = token;
2246
2247 if (token_is_for_parents(token)) {
2248 if (parents_done)
2249 continue;
2250
2251 r = udev_rule_apply_parent_token_to_event(rules, event, timeout_signal);
2252 if (r <= 0)
2253 return r;
2254
2255 parents_done = true;
2256 continue;
2257 }
2258
2259 r = udev_rule_apply_token_to_event(rules, event->dev, event, timeout_usec, timeout_signal, properties_list);
2260 if (r <= 0)
2261 return r;
2262 }
2263
2264 if (line->goto_line)
2265 *next_line = line->goto_line;
2266
2267 return 0;
2268 }
2269
2270 int udev_rules_apply_to_event(
2271 UdevRules *rules,
2272 UdevEvent *event,
2273 usec_t timeout_usec,
2274 int timeout_signal,
2275 Hashmap *properties_list) {
2276
2277 UdevRuleFile *file;
2278 UdevRuleLine *next_line;
2279 int r;
2280
2281 assert(rules);
2282 assert(event);
2283
2284 LIST_FOREACH(rule_files, file, rules->rule_files) {
2285 rules->current_file = file;
2286 LIST_FOREACH_SAFE(rule_lines, file->current_line, next_line, file->rule_lines) {
2287 r = udev_rule_apply_line_to_event(rules, event, timeout_usec, timeout_signal, properties_list, &next_line);
2288 if (r < 0)
2289 return r;
2290 }
2291 }
2292
2293 return 0;
2294 }
2295
2296 static int apply_static_dev_perms(const char *devnode, uid_t uid, gid_t gid, mode_t mode, char **tags) {
2297 char device_node[UTIL_PATH_SIZE], tags_dir[UTIL_PATH_SIZE], tag_symlink[UTIL_PATH_SIZE];
2298 _cleanup_free_ char *unescaped_filename = NULL;
2299 struct stat stats;
2300 char **t;
2301 int r;
2302
2303 assert(devnode);
2304
2305 if (uid == UID_INVALID && gid == GID_INVALID && mode == MODE_INVALID && !tags)
2306 return 0;
2307
2308 strscpyl(device_node, sizeof(device_node), "/dev/", devnode, NULL);
2309 if (stat(device_node, &stats) < 0) {
2310 if (errno != ENOENT)
2311 return log_error_errno(errno, "Failed to stat %s: %m", device_node);
2312 return 0;
2313 }
2314
2315 if (!S_ISBLK(stats.st_mode) && !S_ISCHR(stats.st_mode)) {
2316 log_warning("%s is neither block nor character device, ignoring.", device_node);
2317 return 0;
2318 }
2319
2320 if (!strv_isempty(tags)) {
2321 unescaped_filename = xescape(devnode, "/.");
2322 if (!unescaped_filename)
2323 return log_oom();
2324 }
2325
2326 /* export the tags to a directory as symlinks, allowing otherwise dead nodes to be tagged */
2327 STRV_FOREACH(t, tags) {
2328 strscpyl(tags_dir, sizeof(tags_dir), "/run/udev/static_node-tags/", *t, "/", NULL);
2329 r = mkdir_p(tags_dir, 0755);
2330 if (r < 0)
2331 return log_error_errno(r, "Failed to create %s: %m", tags_dir);
2332
2333 strscpyl(tag_symlink, sizeof(tag_symlink), tags_dir, unescaped_filename, NULL);
2334 r = symlink(device_node, tag_symlink);
2335 if (r < 0 && errno != EEXIST)
2336 return log_error_errno(errno, "Failed to create symlink %s -> %s: %m",
2337 tag_symlink, device_node);
2338 }
2339
2340 /* don't touch the permissions if only the tags were set */
2341 if (uid == UID_INVALID && gid == GID_INVALID && mode == MODE_INVALID)
2342 return 0;
2343
2344 if (mode == MODE_INVALID)
2345 mode = gid_is_valid(gid) ? 0660 : 0600;
2346 if (!uid_is_valid(uid))
2347 uid = 0;
2348 if (!gid_is_valid(gid))
2349 gid = 0;
2350
2351 r = chmod_and_chown(device_node, mode, uid, gid);
2352 if (r == -ENOENT)
2353 return 0;
2354 if (r < 0)
2355 return log_error_errno(r, "Failed to chown '%s' %u %u: %m", device_node, uid, gid);
2356 else
2357 log_debug("chown '%s' %u:%u with mode %#o", device_node, uid, gid, mode);
2358
2359 (void) utimensat(AT_FDCWD, device_node, NULL, 0);
2360 return 0;
2361 }
2362
2363 static int udev_rule_line_apply_static_dev_perms(UdevRuleLine *rule_line) {
2364 UdevRuleToken *token;
2365 _cleanup_strv_free_ char **tags = NULL;
2366 uid_t uid = UID_INVALID;
2367 gid_t gid = GID_INVALID;
2368 mode_t mode = MODE_INVALID;
2369 int r;
2370
2371 assert(rule_line);
2372
2373 if (!FLAGS_SET(rule_line->type, LINE_HAS_STATIC_NODE))
2374 return 0;
2375
2376 LIST_FOREACH(tokens, token, rule_line->tokens)
2377 if (token->type == TK_A_OWNER_ID)
2378 uid = PTR_TO_UID(token->data);
2379 else if (token->type == TK_A_GROUP_ID)
2380 gid = PTR_TO_GID(token->data);
2381 else if (token->type == TK_A_MODE_ID)
2382 mode = PTR_TO_MODE(token->data);
2383 else if (token->type == TK_A_TAG) {
2384 r = strv_extend(&tags, token->value);
2385 if (r < 0)
2386 return log_oom();
2387 } else if (token->type == TK_A_OPTIONS_STATIC_NODE) {
2388 r = apply_static_dev_perms(token->value, uid, gid, mode, tags);
2389 if (r < 0)
2390 return r;
2391 }
2392
2393 return 0;
2394 }
2395
2396 int udev_rules_apply_static_dev_perms(UdevRules *rules) {
2397 UdevRuleFile *file;
2398 UdevRuleLine *line;
2399 int r;
2400
2401 assert(rules);
2402
2403 LIST_FOREACH(rule_files, file, rules->rule_files)
2404 LIST_FOREACH(rule_lines, line, file->rule_lines) {
2405 r = udev_rule_line_apply_static_dev_perms(line);
2406 if (r < 0)
2407 return r;
2408 }
2409
2410 return 0;
2411 }