]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/udev/udev-rules.c
Merge pull request #16504 from poettering/read-file-ipc
[thirdparty/systemd.git] / src / udev / udev-rules.c
CommitLineData
e7145211 1/* SPDX-License-Identifier: GPL-2.0+ */
2232cac8 2
2232cac8 3#include <ctype.h>
2232cac8 4
b5efdb8a 5#include "alloc-util.h"
4801d8af 6#include "architecture.h"
2c21044f 7#include "conf-files.h"
116b91e8 8#include "def.h"
480ecb7d 9#include "device-util.h"
8fb3f009 10#include "dirent-util.h"
4f5dd394 11#include "escape.h"
3ffd4af2 12#include "fd-util.h"
fae0f8a0 13#include "fileio.h"
4b3b5bc7 14#include "format-util.h"
fdd21be6 15#include "fs-util.h"
7d50b32a 16#include "glob-util.h"
5ea78a39 17#include "libudev-util.h"
e79c228b 18#include "list.h"
5ea78a39 19#include "mkdir.h"
25de7aa7 20#include "nulstr-util.h"
b4ba2fe3 21#include "parse-util.h"
4f5dd394 22#include "path-util.h"
88b013b2 23#include "proc-cmdline.h"
8fcde012 24#include "stat-util.h"
84b6ad70 25#include "strv.h"
5ea78a39 26#include "strxcpyx.h"
f4cf2e5b 27#include "sysctl-util.h"
07a26e42 28#include "udev-builtin.h"
25de7aa7
YW
29#include "udev-event.h"
30#include "udev-rules.h"
b1d4f8e1 31#include "user-util.h"
4801d8af 32#include "virt.h"
2232cac8 33
116b91e8 34#define RULES_DIRS (const char* const*) CONF_PATHS_STRV("udev/rules.d")
c7521974 35
e79c228b
ZJS
36typedef 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
47typedef enum {
067cc51f
YW
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" */
e79c228b
ZJS
54 _MATCH_TYPE_MAX,
55 _MATCH_TYPE_INVALID = -1
56} UdevRuleMatchType;
57
58typedef 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
66typedef 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 */
4801d8af 74 TK_M_CONST, /* string, system-specific hard-coded constant */
e79c228b
ZJS
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
162392b7 81 /* matches parent parameters */
e79c228b
ZJS
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
128typedef 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
137typedef struct UdevRuleFile UdevRuleFile;
138typedef struct UdevRuleLine UdevRuleLine;
139typedef struct UdevRuleToken UdevRuleToken;
140
141struct 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
152struct 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
167struct UdevRuleFile {
168 char *filename;
169 UdevRuleLine *current_line;
170 LIST_HEAD(UdevRuleLine, rule_lines);
171 LIST_FIELDS(UdevRuleFile, rule_files);
172};
173
174struct 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
d4114f70
ZJS
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
7504610b 230#define log_token_invalid_attr_format(rules, key, attr, offset, hint) \
d4114f70 231 log_token_error_errno(rules, SYNTHETIC_ERRNO(EINVAL), \
7504610b
ZJS
232 "Invalid attribute \"%s\" for %s (char %zu: %s), ignoring, but please fix it.", \
233 attr, key, offset, hint)
f85cc54c 234#define log_token_invalid_value(rules, key, value, offset, hint) \
d4114f70 235 log_token_error_errno(rules, SYNTHETIC_ERRNO(EINVAL), \
f85cc54c
ZJS
236 "Invalid value \"%s\" for %s (char %zu: %s), ignoring, but please fix it.", \
237 value, key, offset, hint)
d4114f70
ZJS
238
239static 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
25de7aa7
YW
248static void udev_rule_token_free(UdevRuleToken *token) {
249 free(token);
915bf0f6
KS
250}
251
25de7aa7
YW
252static void udev_rule_line_clear_tokens(UdevRuleLine *rule_line) {
253 UdevRuleToken *i, *next;
912541b0 254
25de7aa7 255 assert(rule_line);
4052400f 256
25de7aa7
YW
257 LIST_FOREACH_SAFE(tokens, i, next, rule_line->tokens)
258 udev_rule_token_free(i);
912541b0 259
25de7aa7 260 rule_line->tokens = NULL;
5d6a1fa6
KS
261}
262
25de7aa7
YW
263static void udev_rule_line_free(UdevRuleLine *rule_line) {
264 if (!rule_line)
265 return;
912541b0 266
25de7aa7 267 udev_rule_line_clear_tokens(rule_line);
c7521974 268
25de7aa7
YW
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);
912541b0 274 }
25de7aa7
YW
275
276 free(rule_line->line);
277 free(rule_line);
4052400f 278}
154a7b84 279
25de7aa7
YW
280DEFINE_TRIVIAL_CLEANUP_FUNC(UdevRuleLine*, udev_rule_line_free);
281
282static 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);
912541b0 290
25de7aa7
YW
291 free(rule_file->filename);
292 free(rule_file);
4052400f 293}
530727ae 294
25de7aa7
YW
295UdevRules *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);
c7521974 307}
a27cd06c 308
25de7aa7
YW
309static 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;
23bf8dd7 313 int r;
912541b0 314
25de7aa7
YW
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;
912541b0 329 }
912541b0 330
25de7aa7
YW
331 n = strdup(name);
332 if (!n)
530727ae
YW
333 return -ENOMEM;
334
25de7aa7
YW
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;
154a7b84
KS
346}
347
25de7aa7
YW
348static 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;
23bf8dd7 352 int r;
912541b0 353
25de7aa7
YW
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;
912541b0 368 }
912541b0 369
25de7aa7
YW
370 n = strdup(name);
371 if (!n)
530727ae
YW
372 return -ENOMEM;
373
25de7aa7
YW
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;
154a7b84
KS
385}
386
25de7aa7
YW
387static UdevRuleSubstituteType rule_get_substitution_type(const char *str) {
388 assert(str);
912541b0 389
25de7aa7
YW
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}
912541b0 396
25de7aa7
YW
397static void rule_line_append_token(UdevRuleLine *rule_line, UdevRuleToken *token) {
398 assert(rule_line);
399 assert(token);
912541b0 400
25de7aa7
YW
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);
912541b0 405
25de7aa7
YW
406 rule_line->current_token = token;
407}
912541b0 408
25de7aa7
YW
409static 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;
912541b0 415
25de7aa7
YW
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;
912541b0 436
25de7aa7
YW
437 if (type < TK_M_TEST || type == TK_M_RESULT) {
438 /* Convert value string to nulstr. */
067cc51f
YW
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';
1e67a9c2
YG
455
456 /* Make sure the value is end, so NULSTR_FOREACH can read correct match */
457 if (b < a)
458 b[1] = '\0';
459
067cc51f
YW
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;
25de7aa7
YW
468 }
469 }
912541b0
KS
470 }
471
25de7aa7
YW
472 if (IN_SET(type, TK_M_ATTR, TK_M_PARENTS_ATTR)) {
473 assert(value);
474 assert(data);
be4bedd1 475
25de7aa7
YW
476 len = strlen(value);
477 if (len > 0 && !isspace(value[len - 1]))
478 remove_trailing_whitespace = true;
912541b0 479
25de7aa7
YW
480 subst_type = rule_get_substitution_type((const char*) data);
481 }
fae0f8a0 482
25de7aa7
YW
483 token = new(UdevRuleToken, 1);
484 if (!token)
485 return -ENOMEM;
fae0f8a0 486
25de7aa7
YW
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 };
fae0f8a0 496
25de7aa7
YW
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
5abba26e
YW
507 else if (token->type == TK_A_OPTIONS_STATIC_NODE)
508 SET_FLAG(rule_line->type, LINE_HAS_STATIC_NODE, true);
509
25de7aa7 510 else if (token->type >= _TK_A_MIN ||
9c69cd7e 511 IN_SET(token->type, TK_M_PROGRAM,
25de7aa7
YW
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);
fae0f8a0 515
912541b0 516 return 0;
bd0ed2ff
KS
517}
518
f85cc54c
ZJS
519static 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
7504610b
ZJS
529static 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
25de7aa7
YW
540static 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;
a7521142 543 int r;
912541b0 544
25de7aa7
YW
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
d7aee41d 580 if (!is_match) {
f85cc54c 581 check_value_format_and_warn(rules, key, value, false);
d7aee41d
YW
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);
25de7aa7
YW
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),
22ba4525 598 "NAME=\"%%k\" is ignored, as it breaks kernel supplied names.");
25de7aa7
YW
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.");
f85cc54c 602 check_value_format_and_warn(rules, key, value, false);
d7aee41d 603
25de7aa7
YW
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 }
912541b0 616
25de7aa7
YW
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);
912541b0 623
f85cc54c
ZJS
624 check_value_format_and_warn(rules, key, value, false);
625
25de7aa7
YW
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);
4801d8af
JS
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);
25de7aa7
YW
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;
912541b0 641 }
319c6700 642
d7aee41d 643 if (!is_match) {
f85cc54c
ZJS
644 check_value_format_and_warn(rules, key, value, true);
645
d7aee41d
YW
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);
25de7aa7
YW
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")) {
7504610b
ZJS
667 r = check_attr_format_and_warn(rules, key, attr);
668 if (r < 0)
669 return r;
25de7aa7
YW
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 }
912541b0 676
d7aee41d 677 if (!is_match) {
f85cc54c 678 check_value_format_and_warn(rules, key, value, false);
d7aee41d
YW
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);
25de7aa7 682 } else if (streq(key, "SYSCTL")) {
7504610b
ZJS
683 r = check_attr_format_and_warn(rules, key, attr);
684 if (r < 0)
685 return r;
25de7aa7
YW
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 }
3b64e4d4 692
d7aee41d 693 if (!is_match) {
f85cc54c 694 check_value_format_and_warn(rules, key, value, false);
d7aee41d
YW
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);
25de7aa7
YW
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")) {
7504610b
ZJS
720 r = check_attr_format_and_warn(rules, key, attr);
721 if (r < 0)
722 return r;
25de7aa7
YW
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 }
f85cc54c 747 check_value_format_and_warn(rules, key, value, true);
25de7aa7
YW
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);
f85cc54c 755 check_value_format_and_warn(rules, key, value, true);
25de7aa7
YW
756 if (op == OP_REMOVE)
757 return log_token_invalid_op(rules, key);
b6a80b83 758 if (!is_match)
25de7aa7 759 op = OP_MATCH;
912541b0 760
25de7aa7
YW
761 r = rule_line_add_token(rule_line, TK_M_PROGRAM, op, value, NULL);
762 } else if (streq(key, "IMPORT")) {
763 if (isempty(attr))
764 return log_token_invalid_attr(rules, key);
f85cc54c 765 check_value_format_and_warn(rules, key, value, true);
25de7aa7
YW
766 if (op == OP_REMOVE)
767 return log_token_invalid_op(rules, key);
b6a80b83 768 if (!is_match)
25de7aa7 769 op = OP_MATCH;
e2ecb34f 770
25de7aa7
YW
771 if (streq(attr, "file"))
772 r = rule_line_add_token(rule_line, TK_M_IMPORT_FILE, op, value, NULL);
773 else if (streq(attr, "program")) {
774 UdevBuiltinCommand cmd;
f4850a1d 775
25de7aa7
YW
776 cmd = udev_builtin_lookup(value);
777 if (cmd >= 0) {
778 log_token_debug(rules,"Found builtin command '%s' for %s, replacing attribute", value, key);
779 r = rule_line_add_token(rule_line, TK_M_IMPORT_BUILTIN, op, value, UDEV_BUILTIN_CMD_TO_PTR(cmd));
780 } else
781 r = rule_line_add_token(rule_line, TK_M_IMPORT_PROGRAM, op, value, NULL);
782 } else if (streq(attr, "builtin")) {
783 UdevBuiltinCommand cmd;
784
785 cmd = udev_builtin_lookup(value);
786 if (cmd < 0)
787 return log_token_error_errno(rules, SYNTHETIC_ERRNO(EINVAL),
788 "Unknown builtin command: %s", value);
789 r = rule_line_add_token(rule_line, TK_M_IMPORT_BUILTIN, op, value, UDEV_BUILTIN_CMD_TO_PTR(cmd));
790 } else if (streq(attr, "db"))
791 r = rule_line_add_token(rule_line, TK_M_IMPORT_DB, op, value, NULL);
792 else if (streq(attr, "cmdline"))
793 r = rule_line_add_token(rule_line, TK_M_IMPORT_CMDLINE, op, value, NULL);
794 else if (streq(attr, "parent"))
795 r = rule_line_add_token(rule_line, TK_M_IMPORT_PARENT, op, value, NULL);
796 else
797 return log_token_invalid_attr(rules, key);
798 } else if (streq(key, "RESULT")) {
799 if (attr)
800 return log_token_invalid_attr(rules, key);
801 if (!is_match)
802 return log_token_invalid_op(rules, key);
803
804 r = rule_line_add_token(rule_line, TK_M_RESULT, op, value, NULL);
805 } else if (streq(key, "OPTIONS")) {
806 char *tmp;
807
808 if (attr)
809 return log_token_invalid_attr(rules, key);
810 if (is_match || op == OP_REMOVE)
811 return log_token_invalid_op(rules, key);
ba60127d 812 if (op == OP_ADD)
25de7aa7 813 op = OP_ASSIGN;
f4850a1d 814
25de7aa7
YW
815 if (streq(value, "string_escape=none"))
816 r = rule_line_add_token(rule_line, TK_A_OPTIONS_STRING_ESCAPE_NONE, op, NULL, NULL);
817 else if (streq(value, "string_escape=replace"))
818 r = rule_line_add_token(rule_line, TK_A_OPTIONS_STRING_ESCAPE_REPLACE, op, NULL, NULL);
819 else if (streq(value, "db_persist"))
820 r = rule_line_add_token(rule_line, TK_A_OPTIONS_DB_PERSIST, op, NULL, NULL);
821 else if (streq(value, "watch"))
822 r = rule_line_add_token(rule_line, TK_A_OPTIONS_INOTIFY_WATCH, op, NULL, INT_TO_PTR(1));
823 else if (streq(value, "nowatch"))
824 r = rule_line_add_token(rule_line, TK_A_OPTIONS_INOTIFY_WATCH, op, NULL, INT_TO_PTR(0));
825 else if ((tmp = startswith(value, "static_node=")))
826 r = rule_line_add_token(rule_line, TK_A_OPTIONS_STATIC_NODE, op, tmp, NULL);
827 else if ((tmp = startswith(value, "link_priority="))) {
828 int prio;
829
830 r = safe_atoi(tmp, &prio);
831 if (r < 0)
832 return log_token_error_errno(rules, r, "Failed to parse link priority '%s': %m", tmp);
833 r = rule_line_add_token(rule_line, TK_A_OPTIONS_DEVLINK_PRIORITY, op, NULL, INT_TO_PTR(prio));
834 } else {
835 log_token_warning(rules, "Invalid value for OPTIONS key, ignoring: '%s'", value);
836 return 0;
837 }
838 } else if (streq(key, "OWNER")) {
839 uid_t uid;
f4850a1d 840
25de7aa7
YW
841 if (attr)
842 return log_token_invalid_attr(rules, key);
843 if (is_match || op == OP_REMOVE)
844 return log_token_invalid_op(rules, key);
845 if (op == OP_ADD) {
846 log_token_warning(rules, "%s key takes '=' or ':=' operator, assuming '=', but please fix it.", key);
847 op = OP_ASSIGN;
848 }
f4850a1d 849
25de7aa7
YW
850 if (parse_uid(value, &uid) >= 0)
851 r = rule_line_add_token(rule_line, TK_A_OWNER_ID, op, NULL, UID_TO_PTR(uid));
852 else if (rules->resolve_name_timing == RESOLVE_NAME_EARLY &&
853 rule_get_substitution_type(value) == SUBST_TYPE_PLAIN) {
854 r = rule_resolve_user(rules, value, &uid);
855 if (r < 0)
856 return log_token_error_errno(rules, r, "Failed to resolve user name '%s': %m", value);
857
858 r = rule_line_add_token(rule_line, TK_A_OWNER_ID, op, NULL, UID_TO_PTR(uid));
d7aee41d 859 } else if (rules->resolve_name_timing != RESOLVE_NAME_NEVER) {
f85cc54c 860 check_value_format_and_warn(rules, key, value, true);
25de7aa7 861 r = rule_line_add_token(rule_line, TK_A_OWNER, op, value, NULL);
d7aee41d 862 } else {
22ba4525 863 log_token_debug(rules, "User name resolution is disabled, ignoring %s=%s", key, value);
25de7aa7
YW
864 return 0;
865 }
866 } else if (streq(key, "GROUP")) {
867 gid_t gid;
868
869 if (attr)
870 return log_token_invalid_attr(rules, key);
871 if (is_match || op == OP_REMOVE)
872 return log_token_invalid_op(rules, key);
873 if (op == OP_ADD) {
874 log_token_warning(rules, "%s key takes '=' or ':=' operator, assuming '=', but please fix it.", key);
875 op = OP_ASSIGN;
876 }
877
878 if (parse_gid(value, &gid) >= 0)
879 r = rule_line_add_token(rule_line, TK_A_GROUP_ID, op, NULL, GID_TO_PTR(gid));
880 else if (rules->resolve_name_timing == RESOLVE_NAME_EARLY &&
881 rule_get_substitution_type(value) == SUBST_TYPE_PLAIN) {
882 r = rule_resolve_group(rules, value, &gid);
883 if (r < 0)
884 return log_token_error_errno(rules, r, "Failed to resolve group name '%s': %m", value);
885
886 r = rule_line_add_token(rule_line, TK_A_GROUP_ID, op, NULL, GID_TO_PTR(gid));
d7aee41d 887 } else if (rules->resolve_name_timing != RESOLVE_NAME_NEVER) {
f85cc54c 888 check_value_format_and_warn(rules, key, value, true);
25de7aa7 889 r = rule_line_add_token(rule_line, TK_A_GROUP, op, value, NULL);
d7aee41d 890 } else {
25de7aa7
YW
891 log_token_debug(rules, "Resolving group name is disabled, ignoring %s=%s", key, value);
892 return 0;
893 }
894 } else if (streq(key, "MODE")) {
895 mode_t mode;
896
897 if (attr)
898 return log_token_invalid_attr(rules, key);
899 if (is_match || op == OP_REMOVE)
900 return log_token_invalid_op(rules, key);
901 if (op == OP_ADD) {
902 log_token_warning(rules, "%s key takes '=' or ':=' operator, assuming '=', but please fix it.", key);
903 op = OP_ASSIGN;
904 }
905
906 if (parse_mode(value, &mode) >= 0)
907 r = rule_line_add_token(rule_line, TK_A_MODE_ID, op, NULL, MODE_TO_PTR(mode));
d7aee41d 908 else {
f85cc54c 909 check_value_format_and_warn(rules, key, value, true);
25de7aa7 910 r = rule_line_add_token(rule_line, TK_A_MODE, op, value, NULL);
d7aee41d 911 }
25de7aa7
YW
912 } else if (streq(key, "SECLABEL")) {
913 if (isempty(attr))
914 return log_token_invalid_attr(rules, key);
f85cc54c 915 check_value_format_and_warn(rules, key, value, true);
25de7aa7
YW
916 if (is_match || op == OP_REMOVE)
917 return log_token_invalid_op(rules, key);
918 if (op == OP_ASSIGN_FINAL) {
919 log_token_warning(rules, "%s key takes '=' or '+=' operator, assuming '=', but please fix it.", key);
920 op = OP_ASSIGN;
921 }
922
0335d110 923 r = rule_line_add_token(rule_line, TK_A_SECLABEL, op, value, attr);
25de7aa7
YW
924 } else if (streq(key, "RUN")) {
925 if (is_match || op == OP_REMOVE)
926 return log_token_invalid_op(rules, key);
f85cc54c 927 check_value_format_and_warn(rules, key, value, true);
25de7aa7
YW
928 if (!attr || streq(attr, "program"))
929 r = rule_line_add_token(rule_line, TK_A_RUN_PROGRAM, op, value, NULL);
930 else if (streq(attr, "builtin")) {
931 UdevBuiltinCommand cmd;
932
933 cmd = udev_builtin_lookup(value);
934 if (cmd < 0)
935 return log_token_error_errno(rules, SYNTHETIC_ERRNO(EINVAL),
936 "Unknown builtin command '%s', ignoring", value);
937 r = rule_line_add_token(rule_line, TK_A_RUN_BUILTIN, op, value, UDEV_BUILTIN_CMD_TO_PTR(cmd));
938 } else
939 return log_token_invalid_attr(rules, key);
940 } else if (streq(key, "GOTO")) {
941 if (attr)
942 return log_token_invalid_attr(rules, key);
943 if (op != OP_ASSIGN)
944 return log_token_invalid_op(rules, key);
945 if (FLAGS_SET(rule_line->type, LINE_HAS_GOTO)) {
22ba4525 946 log_token_warning(rules, "Contains multiple GOTO keys, ignoring GOTO=\"%s\".", value);
25de7aa7 947 return 0;
912541b0 948 }
25de7aa7
YW
949
950 rule_line->goto_label = value;
951 SET_FLAG(rule_line->type, LINE_HAS_GOTO, true);
952 return 1;
953 } else if (streq(key, "LABEL")) {
954 if (attr)
955 return log_token_invalid_attr(rules, key);
956 if (op != OP_ASSIGN)
957 return log_token_invalid_op(rules, key);
958
959 rule_line->label = value;
960 SET_FLAG(rule_line->type, LINE_HAS_LABEL, true);
961 return 1;
962 } else
963 return log_token_error_errno(rules, SYNTHETIC_ERRNO(EINVAL), "Invalid key '%s'", key);
964 if (r < 0)
965 return log_oom();
966
967 return 1;
0ea5e96e
KS
968}
969
25de7aa7
YW
970static UdevRuleOperatorType parse_operator(const char *op) {
971 assert(op);
972
973 if (startswith(op, "=="))
974 return OP_MATCH;
975 if (startswith(op, "!="))
976 return OP_NOMATCH;
977 if (startswith(op, "+="))
978 return OP_ADD;
979 if (startswith(op, "-="))
980 return OP_REMOVE;
981 if (startswith(op, "="))
982 return OP_ASSIGN;
983 if (startswith(op, ":="))
984 return OP_ASSIGN_FINAL;
985
986 return _OP_TYPE_INVALID;
987}
912541b0 988
25de7aa7
YW
989static int parse_line(char **line, char **ret_key, char **ret_attr, UdevRuleOperatorType *ret_op, char **ret_value) {
990 char *key_begin, *key_end, *attr, *tmp, *value, *i, *j;
991 UdevRuleOperatorType op;
912541b0 992
25de7aa7
YW
993 assert(line);
994 assert(*line);
995 assert(ret_key);
996 assert(ret_op);
997 assert(ret_value);
912541b0 998
25de7aa7 999 key_begin = skip_leading_chars(*line, WHITESPACE ",");
912541b0 1000
25de7aa7
YW
1001 if (isempty(key_begin))
1002 return 0;
1003
1004 for (key_end = key_begin; ; key_end++) {
1005 if (key_end[0] == '\0')
704dbfb2 1006 return -EINVAL;
25de7aa7 1007 if (strchr(WHITESPACE "={", key_end[0]))
912541b0 1008 break;
25de7aa7 1009 if (strchr("+-!:", key_end[0]) && key_end[1] == '=')
912541b0 1010 break;
25de7aa7
YW
1011 }
1012 if (key_end[0] == '{') {
1013 attr = key_end + 1;
1014 tmp = strchr(attr, '}');
1015 if (!tmp)
1016 return -EINVAL;
1017 *tmp++ = '\0';
1018 } else {
1019 attr = NULL;
1020 tmp = key_end;
912541b0
KS
1021 }
1022
25de7aa7
YW
1023 tmp = skip_leading_chars(tmp, NULL);
1024 op = parse_operator(tmp);
1025 if (op < 0)
704dbfb2 1026 return -EINVAL;
912541b0 1027
25de7aa7 1028 key_end[0] = '\0';
912541b0 1029
25de7aa7
YW
1030 tmp += op == OP_ASSIGN ? 1 : 2;
1031 value = skip_leading_chars(tmp, NULL);
912541b0 1032
25de7aa7
YW
1033 /* value must be double quotated */
1034 if (value[0] != '"')
704dbfb2 1035 return -EINVAL;
25de7aa7 1036 value++;
7e760b79 1037
25de7aa7
YW
1038 /* unescape double quotation '\"' -> '"' */
1039 for (i = j = value; ; i++, j++) {
1040 if (*i == '"')
7e760b79 1041 break;
25de7aa7 1042 if (*i == '\0')
704dbfb2 1043 return -EINVAL;
25de7aa7
YW
1044 if (i[0] == '\\' && i[1] == '"')
1045 i++;
1046 *j = *i;
1047 }
1048 j[0] = '\0';
1049
1050 *line = i+1;
1051 *ret_key = key_begin;
1052 *ret_attr = attr;
1053 *ret_op = op;
1054 *ret_value = value;
1055 return 1;
1056}
7e760b79 1057
25de7aa7
YW
1058static void sort_tokens(UdevRuleLine *rule_line) {
1059 UdevRuleToken *head_old;
7e760b79 1060
25de7aa7 1061 assert(rule_line);
912541b0 1062
25de7aa7
YW
1063 head_old = TAKE_PTR(rule_line->tokens);
1064 rule_line->current_token = NULL;
95776dc6 1065
25de7aa7
YW
1066 while (!LIST_IS_EMPTY(head_old)) {
1067 UdevRuleToken *t, *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);
912541b0 1075 }
6880b25d 1076}
95776dc6 1077
25de7aa7
YW
1078static 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;
912541b0 1084
25de7aa7
YW
1085 assert(rules);
1086 assert(rules->current_file);
1087 assert(line_str);
6e2efb6c 1088
25de7aa7 1089 rule_file = rules->current_file;
912541b0 1090
25de7aa7
YW
1091 if (isempty(line_str))
1092 return 0;
912541b0 1093
cd3c8a11
LP
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);
25de7aa7
YW
1097 if (!line)
1098 return log_oom();
67e4b385 1099
25de7aa7
YW
1100 rule_line = new(UdevRuleLine, 1);
1101 if (!rule_line)
1102 return log_oom();
912541b0 1103
25de7aa7
YW
1104 *rule_line = (UdevRuleLine) {
1105 .line = TAKE_PTR(line),
1106 .line_number = line_nr,
1107 .rule_file = rule_file,
1108 };
912541b0 1109
25de7aa7
YW
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);
e57e7bc1 1114
25de7aa7 1115 rule_file->current_line = rule_line;
912541b0 1116
25de7aa7
YW
1117 for (p = rule_line->line; !isempty(p); ) {
1118 char *key, *attr, *value;
1119 UdevRuleOperatorType op;
912541b0 1120
25de7aa7
YW
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;
912541b0 1126
25de7aa7 1127 r = parse_token(rules, key, attr, op, value);
ef660d07
YW
1128 if (r < 0)
1129 return r;
25de7aa7 1130 }
912541b0 1131
25de7aa7
YW
1132 if (rule_line->type == 0) {
1133 log_token_warning(rules, "The line takes no effect, ignoring.");
1134 return 0;
912541b0 1135 }
25de7aa7
YW
1136
1137 sort_tokens(rule_line);
1138 TAKE_PTR(rule_line);
912541b0 1139 return 0;
724257d9
GKH
1140}
1141
25de7aa7
YW
1142static void rule_resolve_goto(UdevRuleFile *rule_file) {
1143 UdevRuleLine *line, *line_next, *i;
912541b0 1144
25de7aa7 1145 assert(rule_file);
912541b0 1146
25de7aa7
YW
1147 /* link GOTOs to LABEL rules in this file to be able to fast-forward */
1148 LIST_FOREACH_SAFE(rule_lines, line, line_next, rule_file->rule_lines) {
1149 if (!FLAGS_SET(line->type, LINE_HAS_GOTO))
1150 continue;
912541b0 1151
25de7aa7
YW
1152 LIST_FOREACH_AFTER(rule_lines, i, line)
1153 if (streq_ptr(i->label, line->goto_label)) {
1154 line->goto_line = i;
1155 break;
912541b0
KS
1156 }
1157
25de7aa7
YW
1158 if (!line->goto_line) {
1159 log_error("%s:%u: GOTO=\"%s\" has no matching label, ignoring",
1160 rule_file->filename, line->line_number, line->goto_label);
912541b0 1161
25de7aa7
YW
1162 SET_FLAG(line->type, LINE_HAS_GOTO, false);
1163 line->goto_label = NULL;
912541b0 1164
25de7aa7
YW
1165 if ((line->type & ~LINE_HAS_LABEL) == 0) {
1166 log_notice("%s:%u: The line takes no effect any more, dropping",
1167 rule_file->filename, line->line_number);
1168 if (line->type == LINE_HAS_LABEL)
1169 udev_rule_line_clear_tokens(line);
1170 else
1171 udev_rule_line_free(line);
912541b0 1172 }
25de7aa7 1173 }
912541b0 1174 }
c7521974
KS
1175}
1176
c238a1f5 1177int udev_rules_parse_file(UdevRules *rules, const char *filename) {
25de7aa7 1178 _cleanup_free_ char *continuation = NULL, *name = NULL;
6c8aaf0c 1179 _cleanup_fclose_ FILE *f = NULL;
25de7aa7 1180 UdevRuleFile *rule_file;
f10aa08e 1181 bool ignore_line = false;
25de7aa7
YW
1182 unsigned line_nr = 0;
1183 int r;
912541b0 1184
ed88bcfb
ZJS
1185 f = fopen(filename, "re");
1186 if (!f) {
1187 if (errno == ENOENT)
1188 return 0;
fae0f8a0
LP
1189
1190 return -errno;
775f8b3c 1191 }
912541b0 1192
1f57abb3
LP
1193 (void) fd_warn_permissions(filename, fileno(f));
1194
ed88bcfb
ZJS
1195 if (null_or_empty_fd(fileno(f))) {
1196 log_debug("Skipping empty file: %s", filename);
1197 return 0;
25de7aa7 1198 }
912541b0 1199
25de7aa7
YW
1200 log_debug("Reading rules file: %s", filename);
1201
1202 name = strdup(filename);
1203 if (!name)
1204 return log_oom();
1205
1206 rule_file = new(UdevRuleFile, 1);
1207 if (!rule_file)
1208 return log_oom();
1209
1210 *rule_file = (UdevRuleFile) {
1211 .filename = TAKE_PTR(name),
1212 };
1213
1214 if (rules->current_file)
1215 LIST_APPEND(rule_files, rules->current_file, rule_file);
1216 else
1217 LIST_APPEND(rule_files, rules->rule_files, rule_file);
1218
1219 rules->current_file = rule_file;
912541b0 1220
f10aa08e
YW
1221 for (;;) {
1222 _cleanup_free_ char *buf = NULL;
912541b0 1223 size_t len;
f10aa08e
YW
1224 char *line;
1225
1226 r = read_line(f, UTIL_LINE_SIZE, &buf);
1227 if (r < 0)
1228 return r;
1229 if (r == 0)
1230 break;
912541b0 1231
912541b0 1232 line_nr++;
25de7aa7 1233 line = skip_leading_chars(buf, NULL);
912541b0 1234
f10aa08e 1235 if (line[0] == '#')
912541b0
KS
1236 continue;
1237
1238 len = strlen(line);
912541b0 1239
f10aa08e
YW
1240 if (continuation && !ignore_line) {
1241 if (strlen(continuation) + len >= UTIL_LINE_SIZE)
1242 ignore_line = true;
1243
1244 if (!strextend(&continuation, line, NULL))
1245 return log_oom();
1246
1247 if (!ignore_line) {
1248 line = continuation;
1249 len = strlen(line);
1250 }
912541b0
KS
1251 }
1252
e8b2737f 1253 if (len > 0 && line[len - 1] == '\\') {
f10aa08e
YW
1254 if (ignore_line)
1255 continue;
1256
1257 line[len - 1] = '\0';
1258 if (!continuation) {
1259 continuation = strdup(line);
1260 if (!continuation)
1261 return log_oom();
1262 }
1263
912541b0
KS
1264 continue;
1265 }
f10aa08e
YW
1266
1267 if (ignore_line)
25de7aa7 1268 log_error("%s:%u: Line is too long, ignored", filename, line_nr);
e8b2737f 1269 else if (len > 0)
25de7aa7 1270 (void) rule_add_line(rules, line, line_nr);
f10aa08e
YW
1271
1272 continuation = mfree(continuation);
1273 ignore_line = false;
912541b0 1274 }
912541b0 1275
25de7aa7 1276 rule_resolve_goto(rule_file);
912541b0 1277 return 0;
c7521974
KS
1278}
1279
c238a1f5 1280UdevRules* udev_rules_new(ResolveNameTiming resolve_name_timing) {
c4d44cba
YW
1281 assert(resolve_name_timing >= 0 && resolve_name_timing < _RESOLVE_NAME_TIMING_MAX);
1282
c238a1f5 1283 UdevRules *rules = new(UdevRules, 1);
1017d66b 1284 if (!rules)
c238a1f5 1285 return NULL;
1017d66b 1286
9a07157d 1287 *rules = (UdevRules) {
c4d44cba 1288 .resolve_name_timing = resolve_name_timing,
1017d66b 1289 };
912541b0 1290
c238a1f5
ZJS
1291 return rules;
1292}
1293
1294int udev_rules_load(UdevRules **ret_rules, ResolveNameTiming resolve_name_timing) {
1295 _cleanup_(udev_rules_freep) UdevRules *rules = NULL;
1296 _cleanup_strv_free_ char **files = NULL;
1297 char **f;
1298 int r;
1299
1300 rules = udev_rules_new(resolve_name_timing);
1301 if (!rules)
1302 return -ENOMEM;
1303
25de7aa7 1304 (void) udev_rules_check_timestamp(rules);
3b8c1cb0 1305
116b91e8 1306 r = conf_files_list_strv(&files, ".rules", NULL, 0, RULES_DIRS);
1d791281 1307 if (r < 0)
c238a1f5 1308 return log_debug_errno(r, "Failed to enumerate rules files: %m");
912541b0 1309
f23810da
ZJS
1310 STRV_FOREACH(f, files) {
1311 r = udev_rules_parse_file(rules, *f);
1312 if (r < 0)
1313 log_debug_errno(r, "Failed to read rules file %s, ignoring: %m", *f);
1314 }
912541b0 1315
1d791281
ZJS
1316 *ret_rules = TAKE_PTR(rules);
1317 return 0;
c7521974
KS
1318}
1319
9a07157d 1320bool udev_rules_check_timestamp(UdevRules *rules) {
5c11fbe3
KS
1321 if (!rules)
1322 return false;
1323
116b91e8 1324 return paths_check_timestamp(RULES_DIRS, &rules->dirs_ts_usec, true);
6ada823a
KS
1325}
1326
25de7aa7
YW
1327static bool token_match_string(UdevRuleToken *token, const char *str) {
1328 const char *i, *value;
912541b0
KS
1329 bool match = false;
1330
25de7aa7
YW
1331 assert(token);
1332 assert(token->value);
1333 assert(token->type < _TK_M_MAX);
912541b0 1334
25de7aa7
YW
1335 str = strempty(str);
1336 value = token->value;
1337
1338 switch (token->match_type) {
1339 case MATCH_TYPE_EMPTY:
1340 match = isempty(str);
912541b0 1341 break;
25de7aa7 1342 case MATCH_TYPE_SUBSYSTEM:
9663ed37 1343 match = STR_IN_SET(str, "subsystem", "class", "bus");
067cc51f
YW
1344 break;
1345 case MATCH_TYPE_PLAIN_WITH_EMPTY:
1346 if (isempty(str)) {
1347 match = true;
1348 break;
1349 }
25de7aa7
YW
1350 _fallthrough_;
1351 case MATCH_TYPE_PLAIN:
1352 NULSTR_FOREACH(i, value)
1353 if (streq(i, str)) {
1354 match = true;
1355 break;
912541b0 1356 }
25de7aa7 1357 break;
067cc51f
YW
1358 case MATCH_TYPE_GLOB_WITH_EMPTY:
1359 if (isempty(str)) {
1360 match = true;
1361 break;
1362 }
1363 _fallthrough_;
25de7aa7
YW
1364 case MATCH_TYPE_GLOB:
1365 NULSTR_FOREACH(i, value)
1366 if ((fnmatch(i, str, 0) == 0)) {
1367 match = true;
1368 break;
912541b0 1369 }
912541b0 1370 break;
25de7aa7
YW
1371 default:
1372 assert_not_reached("Invalid match type");
912541b0
KS
1373 }
1374
25de7aa7 1375 return token->op == (match ? OP_MATCH : OP_NOMATCH);
6880b25d
KS
1376}
1377
25de7aa7 1378static bool token_match_attr(UdevRuleToken *token, sd_device *dev, UdevEvent *event) {
5ba7e798
YW
1379 char nbuf[UTIL_NAME_SIZE], vbuf[UTIL_NAME_SIZE];
1380 const char *name, *value;
912541b0 1381
25de7aa7
YW
1382 assert(token);
1383 assert(dev);
1384 assert(event);
1385
1386 name = (const char*) 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);
912541b0 1391 name = nbuf;
4831981d 1392 _fallthrough_;
25de7aa7 1393 case SUBST_TYPE_PLAIN:
5ba7e798 1394 if (sd_device_get_sysattr_value(dev, name, &value) < 0)
605aa52f 1395 return false;
912541b0 1396 break;
25de7aa7 1397 case SUBST_TYPE_SUBSYS:
76b9bdd9 1398 if (util_resolve_subsys_kernel(name, vbuf, sizeof(vbuf), true) < 0)
605aa52f 1399 return false;
912541b0
KS
1400 value = vbuf;
1401 break;
1402 default:
25de7aa7 1403 assert_not_reached("Invalid attribute substitution type");
912541b0
KS
1404 }
1405
1406 /* remove trailing whitespace, if not asked to match for it */
25de7aa7
YW
1407 if (token->attr_match_remove_trailing_whitespace) {
1408 if (value != vbuf) {
1409 strscpy(vbuf, sizeof(vbuf), value);
1410 value = vbuf;
912541b0 1411 }
25de7aa7
YW
1412
1413 delete_trailing_chars(vbuf, NULL);
912541b0
KS
1414 }
1415
25de7aa7 1416 return token_match_string(token, value);
6880b25d
KS
1417}
1418
25de7aa7
YW
1419static int get_property_from_string(char *line, char **ret_key, char **ret_value) {
1420 char *key, *val;
1421 size_t len;
6880b25d 1422
25de7aa7
YW
1423 assert(line);
1424 assert(ret_key);
1425 assert(ret_value);
1426
1427 /* find key */
1428 key = skip_leading_chars(line, NULL);
912541b0 1429
25de7aa7 1430 /* comment or empty line */
41c81c4a
YW
1431 if (IN_SET(key[0], '#', '\0')) {
1432 *ret_key = *ret_value = NULL;
d838e145 1433 return 0;
41c81c4a 1434 }
912541b0 1435
25de7aa7
YW
1436 /* split key/value */
1437 val = strchr(key, '=');
1438 if (!val)
1439 return -EINVAL;
1440 *val++ = '\0';
cf697ec0 1441
25de7aa7
YW
1442 key = strstrip(key);
1443 if (isempty(key))
1444 return -EINVAL;
912541b0 1445
25de7aa7
YW
1446 val = strstrip(val);
1447 if (isempty(val))
1448 return -EINVAL;
912541b0 1449
25de7aa7
YW
1450 /* unquote */
1451 if (IN_SET(val[0], '"', '\'')) {
1452 len = strlen(val);
1453 if (len == 1 || val[len-1] != val[0])
1454 return -EINVAL;
1455 val[len-1] = '\0';
1456 val++;
1457 }
adeba500 1458
25de7aa7
YW
1459 *ret_key = key;
1460 *ret_value = val;
41c81c4a 1461 return 1;
25de7aa7 1462}
f4cf2e5b 1463
25de7aa7
YW
1464static int import_parent_into_properties(sd_device *dev, const char *filter) {
1465 const char *key, *val;
1466 sd_device *parent;
1467 int r;
f4cf2e5b 1468
25de7aa7
YW
1469 assert(dev);
1470 assert(filter);
912541b0 1471
25de7aa7
YW
1472 r = sd_device_get_parent(dev, &parent);
1473 if (r == -ENOENT)
1474 return 0;
1475 if (r < 0)
1476 return r;
1477
1478 FOREACH_DEVICE_PROPERTY(parent, key, val) {
1479 if (fnmatch(filter, key, 0) != 0)
912541b0 1480 continue;
25de7aa7
YW
1481 r = device_add_property(dev, key, val);
1482 if (r < 0)
1483 return r;
1484 }
912541b0 1485
25de7aa7
YW
1486 return 1;
1487}
912541b0 1488
25de7aa7
YW
1489static int attr_subst_subdir(char attr[static UTIL_PATH_SIZE]) {
1490 _cleanup_closedir_ DIR *dir = NULL;
1491 struct dirent *dent;
1492 char buf[UTIL_PATH_SIZE], *p;
1493 const char *tail;
1494 size_t len, size;
912541b0 1495
2caa38e9
LP
1496 assert(attr);
1497
25de7aa7
YW
1498 tail = strstr(attr, "/*/");
1499 if (!tail)
1500 return 0;
912541b0 1501
25de7aa7
YW
1502 len = tail - attr + 1; /* include slash at the end */
1503 tail += 2; /* include slash at the beginning */
88b013b2 1504
25de7aa7
YW
1505 p = buf;
1506 size = sizeof(buf);
1507 size -= strnpcpy(&p, size, attr, len);
88b013b2 1508
25de7aa7
YW
1509 dir = opendir(buf);
1510 if (!dir)
1511 return -errno;
912541b0 1512
25de7aa7
YW
1513 FOREACH_DIRENT_ALL(dent, dir, break) {
1514 if (dent->d_name[0] == '.')
1515 continue;
1516
1517 strscpyl(p, size, dent->d_name, tail, NULL);
1518 if (faccessat(dirfd(dir), p, F_OK, 0) < 0)
1519 continue;
1520
1521 strcpy(attr, buf);
1522 return 0;
1523 }
1524
1525 return -ENOENT;
1526}
1527
1528static int udev_rule_apply_token_to_event(
1529 UdevRules *rules,
1530 sd_device *dev,
1531 UdevEvent *event,
1532 usec_t timeout_usec,
e2099267 1533 int timeout_signal,
25de7aa7
YW
1534 Hashmap *properties_list) {
1535
1536 UdevRuleToken *token;
1537 char buf[UTIL_PATH_SIZE];
1538 const char *val;
1539 size_t count;
1540 bool match;
1541 int r;
1542
1543 assert(rules);
1544 assert(dev);
1545 assert(event);
1546
1547 /* This returns the following values:
1548 * 0 on the current token does not match the event,
1549 * 1 on the current token matches the event, and
1550 * negative errno on some critical errors. */
1551
1552 token = rules->current_file->current_line->current_token;
1553
1554 switch (token->type) {
1555 case TK_M_ACTION: {
1556 DeviceAction a;
1557
1558 r = device_get_action(dev, &a);
1559 if (r < 0)
1560 return log_rule_error_errno(dev, rules, r, "Failed to get uevent action type: %m");
1561
1562 return token_match_string(token, device_action_to_string(a));
1563 }
1564 case TK_M_DEVPATH:
1565 r = sd_device_get_devpath(dev, &val);
1566 if (r < 0)
1567 return log_rule_error_errno(dev, rules, r, "Failed to get devpath: %m");
1568
1569 return token_match_string(token, val);
1570 case TK_M_KERNEL:
1571 case TK_M_PARENTS_KERNEL:
1572 r = sd_device_get_sysname(dev, &val);
1573 if (r < 0)
1574 return log_rule_error_errno(dev, rules, r, "Failed to get sysname: %m");
1575
1576 return token_match_string(token, val);
1577 case TK_M_DEVLINK:
1578 FOREACH_DEVICE_DEVLINK(dev, val)
1579 if (token_match_string(token, strempty(startswith(val, "/dev/"))))
1580 return token->op == OP_MATCH;
1581 return token->op == OP_NOMATCH;
1582 case TK_M_NAME:
1583 return token_match_string(token, event->name);
1584 case TK_M_ENV:
1585 if (sd_device_get_property_value(dev, (const char*) token->data, &val) < 0)
1586 val = hashmap_get(properties_list, token->data);
1587
1588 return token_match_string(token, val);
4801d8af
JS
1589 case TK_M_CONST: {
1590 const char *k = token->data;
1591
1592 if (streq(k, "arch"))
1593 val = architecture_to_string(uname_architecture());
1594 else if (streq(k, "virt"))
1595 val = virtualization_to_string(detect_virtualization());
1596 else
1597 assert_not_reached("Invalid CONST key");
1598 return token_match_string(token, val);
1599 }
25de7aa7
YW
1600 case TK_M_TAG:
1601 case TK_M_PARENTS_TAG:
1602 FOREACH_DEVICE_TAG(dev, val)
1603 if (token_match_string(token, val))
1604 return token->op == OP_MATCH;
1605 return token->op == OP_NOMATCH;
1606 case TK_M_SUBSYSTEM:
1607 case TK_M_PARENTS_SUBSYSTEM:
1608 r = sd_device_get_subsystem(dev, &val);
1609 if (r == -ENOENT)
1610 val = NULL;
1611 else if (r < 0)
1612 return log_rule_error_errno(dev, rules, r, "Failed to get subsystem: %m");
1613
1614 return token_match_string(token, val);
1615 case TK_M_DRIVER:
1616 case TK_M_PARENTS_DRIVER:
1617 r = sd_device_get_driver(dev, &val);
1618 if (r == -ENOENT)
1619 val = NULL;
1620 else if (r < 0)
1621 return log_rule_error_errno(dev, rules, r, "Failed to get driver: %m");
1622
1623 return token_match_string(token, val);
1624 case TK_M_ATTR:
1625 case TK_M_PARENTS_ATTR:
1626 return token_match_attr(token, dev, event);
1627 case TK_M_SYSCTL: {
1628 _cleanup_free_ char *value = NULL;
1629
1630 (void) udev_event_apply_format(event, (const char*) token->data, buf, sizeof(buf), false);
1631 r = sysctl_read(sysctl_normalize(buf), &value);
1632 if (r < 0 && r != -ENOENT)
1633 return log_rule_error_errno(dev, rules, r, "Failed to read sysctl '%s': %m", buf);
1634
1635 return token_match_string(token, strstrip(value));
1636 }
1637 case TK_M_TEST: {
1638 mode_t mode = PTR_TO_MODE(token->data);
1639 struct stat statbuf;
1640
1641 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false);
1642 if (!path_is_absolute(buf) &&
1643 util_resolve_subsys_kernel(buf, buf, sizeof(buf), false) < 0) {
1644 char tmp[UTIL_PATH_SIZE];
1645
1646 r = sd_device_get_syspath(dev, &val);
1647 if (r < 0)
1648 return log_rule_error_errno(dev, rules, r, "Failed to get syspath: %m");
1649
1650 strscpy(tmp, sizeof(tmp), buf);
1651 strscpyl(buf, sizeof(buf), val, "/", tmp, NULL);
1652 }
1653
1654 r = attr_subst_subdir(buf);
1655 if (r == -ENOENT)
1656 return token->op == OP_NOMATCH;
1657 if (r < 0)
22ba4525 1658 return log_rule_error_errno(dev, rules, r, "Failed to test for the existence of '%s': %m", buf);
25de7aa7
YW
1659
1660 if (stat(buf, &statbuf) < 0)
1661 return token->op == OP_NOMATCH;
1662
1663 if (mode == MODE_INVALID)
1664 return token->op == OP_MATCH;
1665
7a182f10 1666 match = (statbuf.st_mode & mode) > 0;
25de7aa7
YW
1667 return token->op == (match ? OP_MATCH : OP_NOMATCH);
1668 }
1669 case TK_M_PROGRAM: {
1670 char result[UTIL_LINE_SIZE];
1671
1672 event->program_result = mfree(event->program_result);
1673 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false);
1674 log_rule_debug(dev, rules, "Running PROGRAM '%s'", buf);
1675
e2099267 1676 r = udev_event_spawn(event, timeout_usec, timeout_signal, true, buf, result, sizeof(result));
08de1958
YW
1677 if (r != 0) {
1678 if (r < 0)
22ba4525 1679 log_rule_warning_errno(dev, rules, r, "Failed to execute \"%s\": %m", buf);
08de1958 1680 else /* returned value is positive when program fails */
22ba4525 1681 log_rule_debug(dev, rules, "Command \"%s\" returned %d (error)", buf, r);
25de7aa7 1682 return token->op == OP_NOMATCH;
08de1958 1683 }
25de7aa7
YW
1684
1685 delete_trailing_chars(result, "\n");
1686 count = util_replace_chars(result, UDEV_ALLOWED_CHARS_INPUT);
1687 if (count > 0)
22ba4525 1688 log_rule_debug(dev, rules, "Replaced %zu character(s) in result of \"%s\"",
25de7aa7
YW
1689 count, buf);
1690
1691 event->program_result = strdup(result);
1692 return token->op == OP_MATCH;
1693 }
1694 case TK_M_IMPORT_FILE: {
1695 _cleanup_fclose_ FILE *f = NULL;
1696
1697 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false);
1698 log_rule_debug(dev, rules, "Importing properties from '%s'", buf);
1699
1700 f = fopen(buf, "re");
1701 if (!f) {
1702 if (errno != ENOENT)
1703 return log_rule_error_errno(dev, rules, errno,
1704 "Failed to open '%s': %m", buf);
1705 return token->op == OP_NOMATCH;
1706 }
912541b0 1707
25de7aa7
YW
1708 for (;;) {
1709 _cleanup_free_ char *line = NULL;
1710 char *key, *value;
1711
1712 r = read_line(f, LONG_LINE_MAX, &line);
1713 if (r < 0) {
1714 log_rule_debug_errno(dev, rules, r,
1715 "Failed to read '%s', ignoring: %m", buf);
1716 return token->op == OP_NOMATCH;
1717 }
1718 if (r == 0)
912541b0 1719 break;
25de7aa7
YW
1720
1721 r = get_property_from_string(line, &key, &value);
23bf8dd7 1722 if (r < 0) {
25de7aa7
YW
1723 log_rule_debug_errno(dev, rules, r,
1724 "Failed to parse key and value from '%s', ignoring: %m",
1725 line);
1726 continue;
23bf8dd7 1727 }
41c81c4a
YW
1728 if (r == 0)
1729 continue;
25de7aa7
YW
1730
1731 r = device_add_property(dev, key, value);
1732 if (r < 0)
1733 return log_rule_error_errno(dev, rules, r,
1734 "Failed to add property %s=%s: %m",
1735 key, value);
912541b0 1736 }
912541b0 1737
25de7aa7
YW
1738 return token->op == OP_MATCH;
1739 }
1740 case TK_M_IMPORT_PROGRAM: {
1741 char result[UTIL_LINE_SIZE], *line, *pos;
1742
1743 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false);
1744 log_rule_debug(dev, rules, "Importing properties from results of '%s'", buf);
1745
e2099267 1746 r = udev_event_spawn(event, timeout_usec, timeout_signal, true, buf, result, sizeof result);
08de1958
YW
1747 if (r != 0) {
1748 if (r < 0)
1749 log_rule_warning_errno(dev, rules, r, "Failed to execute '%s', ignoring: %m", buf);
1750 else /* returned value is positive when program fails */
1751 log_rule_debug(dev, rules, "Command \"%s\" returned %d (error), ignoring", buf, r);
25de7aa7
YW
1752 return token->op == OP_NOMATCH;
1753 }
1754
1755 for (line = result; !isempty(line); line = pos) {
1756 char *key, *value;
1757
1758 pos = strchr(line, '\n');
1759 if (pos)
1760 *pos++ = '\0';
1761
1762 r = get_property_from_string(line, &key, &value);
23bf8dd7 1763 if (r < 0) {
25de7aa7
YW
1764 log_rule_debug_errno(dev, rules, r,
1765 "Failed to parse key and value from '%s', ignoring: %m",
1766 line);
1767 continue;
23bf8dd7 1768 }
41c81c4a
YW
1769 if (r == 0)
1770 continue;
25de7aa7
YW
1771
1772 r = device_add_property(dev, key, value);
1773 if (r < 0)
1774 return log_rule_error_errno(dev, rules, r,
1775 "Failed to add property %s=%s: %m",
1776 key, value);
912541b0 1777 }
912541b0 1778
25de7aa7
YW
1779 return token->op == OP_MATCH;
1780 }
1781 case TK_M_IMPORT_BUILTIN: {
1782 UdevBuiltinCommand cmd = PTR_TO_UDEV_BUILTIN_CMD(token->data);
1783 unsigned mask = 1U << (int) cmd;
1784
1785 if (udev_builtin_run_once(cmd)) {
1786 /* check if we ran already */
1787 if (event->builtin_run & mask) {
1788 log_rule_debug(dev, rules, "Skipping builtin '%s' in IMPORT key",
1789 udev_builtin_name(cmd));
1790 /* return the result from earlier run */
1791 return token->op == (event->builtin_ret & mask ? OP_NOMATCH : OP_MATCH);
912541b0 1792 }
25de7aa7
YW
1793 /* mark as ran */
1794 event->builtin_run |= mask;
912541b0 1795 }
25de7aa7
YW
1796
1797 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false);
1798 log_rule_debug(dev, rules, "Importing properties from results of builtin command '%s'", buf);
1799
1800 r = udev_builtin_run(dev, cmd, buf, false);
1801 if (r < 0) {
1802 /* remember failure */
1803 log_rule_debug_errno(dev, rules, r, "Failed to run builtin '%s': %m", buf);
1804 event->builtin_ret |= mask;
1805 }
1806 return token->op == (r >= 0 ? OP_MATCH : OP_NOMATCH);
1807 }
1808 case TK_M_IMPORT_DB: {
1809 if (!event->dev_db_clone)
1810 return token->op == OP_NOMATCH;
1811 r = sd_device_get_property_value(event->dev_db_clone, token->value, &val);
1812 if (r == -ENOENT)
1813 return token->op == OP_NOMATCH;
1814 if (r < 0)
1815 return log_rule_error_errno(dev, rules, r,
1816 "Failed to get property '%s' from database: %m",
1817 token->value);
1818
1819 r = device_add_property(dev, token->value, val);
1820 if (r < 0)
1821 return log_rule_error_errno(dev, rules, r, "Failed to add property '%s=%s': %m",
1822 token->value, val);
1823 return token->op == OP_MATCH;
1824 }
1825 case TK_M_IMPORT_CMDLINE: {
1826 _cleanup_free_ char *value = NULL;
1827
09835de3 1828 r = proc_cmdline_get_key(token->value, PROC_CMDLINE_VALUE_OPTIONAL|PROC_CMDLINE_IGNORE_EFI_OPTIONS, &value);
25de7aa7
YW
1829 if (r < 0)
1830 return log_rule_error_errno(dev, rules, r,
1831 "Failed to read '%s' option from /proc/cmdline: %m",
1832 token->value);
1833 if (r == 0)
1834 return token->op == OP_NOMATCH;
1835
1836 r = device_add_property(dev, token->value, value ?: "1");
1837 if (r < 0)
1838 return log_rule_error_errno(dev, rules, r, "Failed to add property '%s=%s': %m",
1839 token->value, value ?: "1");
1840 return token->op == OP_MATCH;
1841 }
1842 case TK_M_IMPORT_PARENT: {
1843 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false);
1844 r = import_parent_into_properties(dev, buf);
1845 if (r < 0)
1846 return log_rule_error_errno(dev, rules, r,
1847 "Failed to import properties '%s' from parent: %m",
1848 buf);
1849 return token->op == (r > 0 ? OP_MATCH : OP_NOMATCH);
1850 }
1851 case TK_M_RESULT:
1852 return token_match_string(token, event->program_result);
1853 case TK_A_OPTIONS_STRING_ESCAPE_NONE:
1854 event->esc = ESCAPE_NONE;
1855 break;
1856 case TK_A_OPTIONS_STRING_ESCAPE_REPLACE:
1857 event->esc = ESCAPE_REPLACE;
1858 break;
1859 case TK_A_OPTIONS_DB_PERSIST:
1860 device_set_db_persist(dev);
1861 break;
1862 case TK_A_OPTIONS_INOTIFY_WATCH:
1863 if (event->inotify_watch_final)
912541b0 1864 break;
25de7aa7
YW
1865 if (token->op == OP_ASSIGN_FINAL)
1866 event->inotify_watch_final = true;
1867
1868 event->inotify_watch = token->data;
1869 break;
1870 case TK_A_OPTIONS_DEVLINK_PRIORITY:
1871 device_set_devlink_priority(dev, PTR_TO_INT(token->data));
1872 break;
1873 case TK_A_OWNER: {
1874 char owner[UTIL_NAME_SIZE];
1875 const char *ow = owner;
1876
1877 if (event->owner_final)
912541b0 1878 break;
25de7aa7
YW
1879 if (token->op == OP_ASSIGN_FINAL)
1880 event->owner_final = true;
1881
1882 (void) udev_event_apply_format(event, token->value, owner, sizeof(owner), false);
1883 r = get_user_creds(&ow, &event->uid, NULL, NULL, NULL, USER_CREDS_ALLOW_MISSING);
1884 if (r < 0)
1885 log_unknown_owner(dev, rules, r, "user", owner);
1886 else
1887 log_rule_debug(dev, rules, "OWNER %s(%u)", owner, event->uid);
1888 break;
1889 }
1890 case TK_A_GROUP: {
1891 char group[UTIL_NAME_SIZE];
1892 const char *gr = group;
1893
1894 if (event->group_final)
912541b0 1895 break;
25de7aa7
YW
1896 if (token->op == OP_ASSIGN_FINAL)
1897 event->group_final = true;
c26547d6 1898
25de7aa7
YW
1899 (void) udev_event_apply_format(event, token->value, group, sizeof(group), false);
1900 r = get_group_creds(&gr, &event->gid, USER_CREDS_ALLOW_MISSING);
1901 if (r < 0)
1902 log_unknown_owner(dev, rules, r, "group", group);
1903 else
1904 log_rule_debug(dev, rules, "GROUP %s(%u)", group, event->gid);
1905 break;
1906 }
1907 case TK_A_MODE: {
1908 char mode_str[UTIL_NAME_SIZE];
d838e145 1909
25de7aa7
YW
1910 if (event->mode_final)
1911 break;
1912 if (token->op == OP_ASSIGN_FINAL)
1913 event->mode_final = true;
4f985bd8 1914
25de7aa7
YW
1915 (void) udev_event_apply_format(event, token->value, mode_str, sizeof(mode_str), false);
1916 r = parse_mode(mode_str, &event->mode);
1917 if (r < 0)
1918 log_rule_error_errno(dev, rules, r, "Failed to parse mode '%s', ignoring: %m", mode_str);
1919 else
1920 log_rule_debug(dev, rules, "MODE %#o", event->mode);
1921 break;
1922 }
1923 case TK_A_OWNER_ID:
1924 if (event->owner_final)
1925 break;
1926 if (token->op == OP_ASSIGN_FINAL)
1927 event->owner_final = true;
1928 if (!token->data)
1929 break;
1930 event->uid = PTR_TO_UID(token->data);
1931 log_rule_debug(dev, rules, "OWNER %u", event->uid);
1932 break;
1933 case TK_A_GROUP_ID:
1934 if (event->group_final)
1935 break;
1936 if (token->op == OP_ASSIGN_FINAL)
1937 event->group_final = true;
1938 if (!token->data)
1939 break;
1940 event->gid = PTR_TO_GID(token->data);
1941 log_rule_debug(dev, rules, "GROUP %u", event->gid);
1942 break;
1943 case TK_A_MODE_ID:
1944 if (event->mode_final)
1945 break;
1946 if (token->op == OP_ASSIGN_FINAL)
1947 event->mode_final = true;
1948 if (!token->data)
1949 break;
1950 event->mode = PTR_TO_MODE(token->data);
1951 log_rule_debug(dev, rules, "MODE %#o", event->mode);
1952 break;
1953 case TK_A_SECLABEL: {
1954 _cleanup_free_ char *name = NULL, *label = NULL;
1955 char label_str[UTIL_LINE_SIZE] = {};
d838e145 1956
25de7aa7
YW
1957 name = strdup((const char*) token->data);
1958 if (!name)
1959 return log_oom();
d838e145 1960
25de7aa7
YW
1961 (void) udev_event_apply_format(event, token->value, label_str, sizeof(label_str), false);
1962 if (!isempty(label_str))
1963 label = strdup(label_str);
1964 else
1965 label = strdup(token->value);
1966 if (!label)
1967 return log_oom();
a6ca3c19 1968
25de7aa7
YW
1969 if (token->op == OP_ASSIGN)
1970 ordered_hashmap_clear_free_free(event->seclabel_list);
07845c14 1971
25de7aa7
YW
1972 r = ordered_hashmap_ensure_allocated(&event->seclabel_list, NULL);
1973 if (r < 0)
1974 return log_oom();
07845c14 1975
25de7aa7
YW
1976 r = ordered_hashmap_put(event->seclabel_list, name, label);
1977 if (r < 0)
1978 return log_oom();
1979 log_rule_debug(dev, rules, "SECLABEL{%s}='%s'", name, label);
1980 name = label = NULL;
1981 break;
1982 }
1983 case TK_A_ENV: {
1984 const char *name = (const char*) token->data;
1985 char value_new[UTIL_NAME_SIZE], *p = value_new;
1986 size_t l = sizeof(value_new);
07845c14 1987
25de7aa7
YW
1988 if (isempty(token->value)) {
1989 if (token->op == OP_ADD)
912541b0 1990 break;
25de7aa7
YW
1991 r = device_add_property(dev, name, NULL);
1992 if (r < 0)
1993 return log_rule_error_errno(dev, rules, r, "Failed to remove property '%s': %m", name);
912541b0
KS
1994 break;
1995 }
912541b0 1996
25de7aa7
YW
1997 if (token->op == OP_ADD &&
1998 sd_device_get_property_value(dev, name, &val) >= 0)
1999 l = strpcpyl(&p, l, val, " ", NULL);
2000
2001 (void) udev_event_apply_format(event, token->value, p, l, false);
d838e145 2002
25de7aa7
YW
2003 r = device_add_property(dev, name, value_new);
2004 if (r < 0)
2005 return log_rule_error_errno(dev, rules, r, "Failed to add property '%s=%s': %m", name, value_new);
2006 break;
2007 }
2008 case TK_A_TAG: {
2009 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false);
2010 if (token->op == OP_ASSIGN)
2011 device_cleanup_tags(dev);
2012
2013 if (buf[strspn(buf, ALPHANUMERICAL "-_")] != '\0') {
2014 log_rule_error(dev, rules, "Invalid tag name '%s', ignoring", buf);
912541b0
KS
2015 break;
2016 }
25de7aa7
YW
2017 if (token->op == OP_REMOVE)
2018 device_remove_tag(dev, buf);
2019 else {
2020 r = device_add_tag(dev, buf);
2021 if (r < 0)
2022 return log_rule_error_errno(dev, rules, r, "Failed to add tag '%s': %m", buf);
2023 }
2024 break;
2025 }
2026 case TK_A_NAME: {
2027 if (event->name_final)
2028 break;
2029 if (token->op == OP_ASSIGN_FINAL)
2030 event->name_final = true;
912541b0 2031
25de7aa7
YW
2032 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false);
2033 if (IN_SET(event->esc, ESCAPE_UNSET, ESCAPE_REPLACE)) {
2034 count = util_replace_chars(buf, "/");
912541b0 2035 if (count > 0)
25de7aa7
YW
2036 log_rule_debug(dev, rules, "Replaced %zu character(s) from result of NAME=\"%s\"",
2037 count, token->value);
912541b0 2038 }
25de7aa7
YW
2039 if (sd_device_get_devnum(dev, NULL) >= 0 &&
2040 (sd_device_get_devname(dev, &val) < 0 ||
2041 !streq_ptr(buf, startswith(val, "/dev/")))) {
2042 log_rule_error(dev, rules,
2043 "Kernel device nodes cannot be renamed, ignoring NAME=\"%s\"; please fix it.",
2044 token->value);
912541b0
KS
2045 break;
2046 }
25de7aa7
YW
2047 if (free_and_strdup(&event->name, buf) < 0)
2048 return log_oom();
2049
2050 log_rule_debug(dev, rules, "NAME '%s'", event->name);
2051 break;
2052 }
2053 case TK_A_DEVLINK: {
2054 char *p;
2055
2056 if (event->devlink_final)
2057 break;
2058 if (sd_device_get_devnum(dev, NULL) < 0)
2059 break;
2060 if (token->op == OP_ASSIGN_FINAL)
2061 event->devlink_final = true;
2062 if (IN_SET(token->op, OP_ASSIGN, OP_ASSIGN_FINAL))
2063 device_cleanup_devlinks(dev);
2064
2065 /* allow multiple symlinks separated by spaces */
2066 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), event->esc != ESCAPE_NONE);
2067 if (event->esc == ESCAPE_UNSET)
2068 count = util_replace_chars(buf, "/ ");
2069 else if (event->esc == ESCAPE_REPLACE)
2070 count = util_replace_chars(buf, "/");
2071 else
2072 count = 0;
2073 if (count > 0)
2074 log_rule_debug(dev, rules, "Replaced %zu character(s) from result of LINK", count);
2075
2076 p = skip_leading_chars(buf, NULL);
2077 while (!isempty(p)) {
2078 char filename[UTIL_PATH_SIZE], *next;
2079
2080 next = strchr(p, ' ');
2081 if (next) {
2082 *next++ = '\0';
2083 next = skip_leading_chars(next, NULL);
2084 }
2085
2086 strscpyl(filename, sizeof(filename), "/dev/", p, NULL);
2087 r = device_add_devlink(dev, filename);
f4cf2e5b 2088 if (r < 0)
25de7aa7
YW
2089 return log_rule_error_errno(dev, rules, r, "Failed to add devlink '%s': %m", filename);
2090
2091 log_rule_debug(dev, rules, "LINK '%s'", p);
2092 p = next;
2093 }
2094 break;
2095 }
2096 case TK_A_ATTR: {
2097 const char *key_name = (const char*) token->data;
2098 char value[UTIL_NAME_SIZE];
2099
2100 if (util_resolve_subsys_kernel(key_name, buf, sizeof(buf), false) < 0 &&
2101 sd_device_get_syspath(dev, &val) >= 0)
2102 strscpyl(buf, sizeof(buf), val, "/", key_name, NULL);
2103
2104 r = attr_subst_subdir(buf);
2105 if (r < 0) {
2106 log_rule_error_errno(dev, rules, r, "Could not find file matches '%s', ignoring: %m", buf);
f4cf2e5b
KS
2107 break;
2108 }
25de7aa7 2109 (void) udev_event_apply_format(event, token->value, value, sizeof(value), false);
6cdc62aa 2110
25de7aa7 2111 log_rule_debug(dev, rules, "ATTR '%s' writing '%s'", buf, value);
a566ed2c 2112 r = write_string_file(buf, value, WRITE_STRING_FILE_VERIFY_ON_FAILURE | WRITE_STRING_FILE_DISABLE_BUFFER | WRITE_STRING_FILE_AVOID_NEWLINE);
25de7aa7
YW
2113 if (r < 0)
2114 log_rule_error_errno(dev, rules, r, "Failed to write ATTR{%s}, ignoring: %m", buf);
2115 break;
2116 }
2117 case TK_A_SYSCTL: {
2118 char value[UTIL_NAME_SIZE];
2119
2120 (void) udev_event_apply_format(event, (const char*) token->data, buf, sizeof(buf), false);
2121 (void) udev_event_apply_format(event, token->value, value, sizeof(value), false);
2122 sysctl_normalize(buf);
2123 log_rule_debug(dev, rules, "SYSCTL '%s' writing '%s'", buf, value);
2124 r = sysctl_write(buf, value);
2125 if (r < 0)
2126 log_rule_error_errno(dev, rules, r, "Failed to write SYSCTL{%s}='%s', ignoring: %m", buf, value);
2127 break;
2128 }
2129 case TK_A_RUN_BUILTIN:
2130 case TK_A_RUN_PROGRAM: {
2131 _cleanup_free_ char *cmd = NULL;
29448498 2132
25de7aa7
YW
2133 if (event->run_final)
2134 break;
2135 if (token->op == OP_ASSIGN_FINAL)
2136 event->run_final = true;
29448498 2137
25de7aa7
YW
2138 if (IN_SET(token->op, OP_ASSIGN, OP_ASSIGN_FINAL))
2139 ordered_hashmap_clear_free_key(event->run_list);
29448498 2140
25de7aa7
YW
2141 r = ordered_hashmap_ensure_allocated(&event->run_list, NULL);
2142 if (r < 0)
2143 return log_oom();
29448498 2144
1448820a
YW
2145 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false);
2146
2147 cmd = strdup(buf);
25de7aa7
YW
2148 if (!cmd)
2149 return log_oom();
29448498 2150
25de7aa7
YW
2151 r = ordered_hashmap_put(event->run_list, cmd, token->data);
2152 if (r < 0)
2153 return log_oom();
83cd6b75 2154
25de7aa7
YW
2155 TAKE_PTR(cmd);
2156
2157 log_rule_debug(dev, rules, "RUN '%s'", token->value);
2158 break;
2159 }
2160 case TK_A_OPTIONS_STATIC_NODE:
2161 /* do nothing for events. */
2162 break;
2163 default:
2164 assert_not_reached("Invalid token type");
2165 }
2166
2167 return true;
2168}
2169
2170static bool token_is_for_parents(UdevRuleToken *token) {
2171 return token->type >= TK_M_PARENTS_KERNEL && token->type <= TK_M_PARENTS_TAG;
2172}
2173
2174static int udev_rule_apply_parent_token_to_event(
2175 UdevRules *rules,
e2099267
MS
2176 UdevEvent *event,
2177 int timeout_signal) {
25de7aa7
YW
2178
2179 UdevRuleLine *line;
2180 UdevRuleToken *head;
2181 int r;
2182
2183 line = rules->current_file->current_line;
2184 head = rules->current_file->current_line->current_token;
2185 event->dev_parent = event->dev;
2186 for (;;) {
2187 LIST_FOREACH(tokens, line->current_token, head) {
2188 if (!token_is_for_parents(line->current_token))
2189 return true; /* All parent tokens match. */
e2099267 2190 r = udev_rule_apply_token_to_event(rules, event->dev_parent, event, 0, timeout_signal, NULL);
25de7aa7
YW
2191 if (r < 0)
2192 return r;
2193 if (r == 0)
912541b0 2194 break;
25de7aa7
YW
2195 }
2196 if (!line->current_token)
2197 /* All parent tokens match. But no assign tokens in the line. Hmm... */
2198 return true;
2199
2200 if (sd_device_get_parent(event->dev_parent, &event->dev_parent) < 0) {
2201 event->dev_parent = NULL;
2202 return false;
2203 }
2204 }
2205}
2206
2207static int udev_rule_apply_line_to_event(
2208 UdevRules *rules,
2209 UdevEvent *event,
2210 usec_t timeout_usec,
e2099267 2211 int timeout_signal,
25de7aa7
YW
2212 Hashmap *properties_list,
2213 UdevRuleLine **next_line) {
2214
2215 UdevRuleLine *line = rules->current_file->current_line;
2216 UdevRuleLineType mask = LINE_HAS_GOTO | LINE_UPDATE_SOMETHING;
2217 UdevRuleToken *token, *next_token;
2218 bool parents_done = false;
2219 DeviceAction action;
2220 int r;
912541b0 2221
25de7aa7
YW
2222 r = device_get_action(event->dev, &action);
2223 if (r < 0)
2224 return r;
2225
2226 if (action != DEVICE_ACTION_REMOVE) {
2227 if (sd_device_get_devnum(event->dev, NULL) >= 0)
2228 mask |= LINE_HAS_DEVLINK;
2229
2230 if (sd_device_get_ifindex(event->dev, NULL) >= 0)
2231 mask |= LINE_HAS_NAME;
2232 }
2233
2234 if ((line->type & mask) == 0)
2235 return 0;
2236
2237 event->esc = ESCAPE_UNSET;
2238 LIST_FOREACH_SAFE(tokens, token, next_token, line->tokens) {
2239 line->current_token = token;
2240
2241 if (token_is_for_parents(token)) {
2242 if (parents_done)
2243 continue;
2244
e2099267 2245 r = udev_rule_apply_parent_token_to_event(rules, event, timeout_signal);
25de7aa7
YW
2246 if (r <= 0)
2247 return r;
2248
2249 parents_done = true;
2250 continue;
912541b0
KS
2251 }
2252
e2099267 2253 r = udev_rule_apply_token_to_event(rules, event->dev, event, timeout_usec, timeout_signal, properties_list);
25de7aa7
YW
2254 if (r <= 0)
2255 return r;
912541b0 2256 }
d838e145 2257
25de7aa7
YW
2258 if (line->goto_line)
2259 *next_line = line->goto_line;
2260
d838e145 2261 return 0;
6880b25d 2262}
761dfddc 2263
25de7aa7
YW
2264int udev_rules_apply_to_event(
2265 UdevRules *rules,
2266 UdevEvent *event,
2267 usec_t timeout_usec,
e2099267 2268 int timeout_signal,
25de7aa7
YW
2269 Hashmap *properties_list) {
2270
2271 UdevRuleFile *file;
2272 UdevRuleLine *next_line;
2273 int r;
2274
2275 assert(rules);
2276 assert(event);
2277
2278 LIST_FOREACH(rule_files, file, rules->rule_files) {
2279 rules->current_file = file;
2280 LIST_FOREACH_SAFE(rule_lines, file->current_line, next_line, file->rule_lines) {
e2099267 2281 r = udev_rule_apply_line_to_event(rules, event, timeout_usec, timeout_signal, properties_list, &next_line);
25de7aa7
YW
2282 if (r < 0)
2283 return r;
2284 }
2285 }
2286
2287 return 0;
2288}
2289
2290static int apply_static_dev_perms(const char *devnode, uid_t uid, gid_t gid, mode_t mode, char **tags) {
2291 char device_node[UTIL_PATH_SIZE], tags_dir[UTIL_PATH_SIZE], tag_symlink[UTIL_PATH_SIZE];
2292 _cleanup_free_ char *unescaped_filename = NULL;
2293 struct stat stats;
84b6ad70 2294 char **t;
fdd21be6 2295 int r;
912541b0 2296
25de7aa7
YW
2297 assert(devnode);
2298
2299 if (uid == UID_INVALID && gid == GID_INVALID && mode == MODE_INVALID && !tags)
84b6ad70 2300 return 0;
912541b0 2301
25de7aa7
YW
2302 strscpyl(device_node, sizeof(device_node), "/dev/", devnode, NULL);
2303 if (stat(device_node, &stats) < 0) {
2304 if (errno != ENOENT)
2305 return log_error_errno(errno, "Failed to stat %s: %m", device_node);
2306 return 0;
2307 }
84b6ad70 2308
25de7aa7
YW
2309 if (!S_ISBLK(stats.st_mode) && !S_ISCHR(stats.st_mode)) {
2310 log_warning("%s is neither block nor character device, ignoring.", device_node);
2311 return 0;
2312 }
912541b0 2313
25de7aa7
YW
2314 if (!strv_isempty(tags)) {
2315 unescaped_filename = xescape(devnode, "/.");
2316 if (!unescaped_filename)
2317 return log_oom();
2318 }
ca2bb160 2319
25de7aa7
YW
2320 /* export the tags to a directory as symlinks, allowing otherwise dead nodes to be tagged */
2321 STRV_FOREACH(t, tags) {
2322 strscpyl(tags_dir, sizeof(tags_dir), "/run/udev/static_node-tags/", *t, "/", NULL);
2323 r = mkdir_p(tags_dir, 0755);
2324 if (r < 0)
2325 return log_error_errno(r, "Failed to create %s: %m", tags_dir);
d6f116a7 2326
25de7aa7
YW
2327 strscpyl(tag_symlink, sizeof(tag_symlink), tags_dir, unescaped_filename, NULL);
2328 r = symlink(device_node, tag_symlink);
2329 if (r < 0 && errno != EEXIST)
2330 return log_error_errno(errno, "Failed to create symlink %s -> %s: %m",
2331 tag_symlink, device_node);
2332 }
84b6ad70 2333
25de7aa7
YW
2334 /* don't touch the permissions if only the tags were set */
2335 if (uid == UID_INVALID && gid == GID_INVALID && mode == MODE_INVALID)
2336 return 0;
84b6ad70 2337
25de7aa7
YW
2338 if (mode == MODE_INVALID)
2339 mode = gid_is_valid(gid) ? 0660 : 0600;
2340 if (!uid_is_valid(uid))
2341 uid = 0;
2342 if (!gid_is_valid(gid))
2343 gid = 0;
84b6ad70 2344
25de7aa7 2345 r = chmod_and_chown(device_node, mode, uid, gid);
4b613ec2
YW
2346 if (r == -ENOENT)
2347 return 0;
25de7aa7 2348 if (r < 0)
ffdc9c89 2349 return log_error_errno(r, "Failed to chown '%s' %u %u: %m", device_node, uid, gid);
25de7aa7 2350 else
20eef7c5 2351 log_debug("chown '%s' %u:%u with mode %#o", device_node, uid, gid, mode);
84b6ad70 2352
25de7aa7
YW
2353 (void) utimensat(AT_FDCWD, device_node, NULL, 0);
2354 return 0;
2355}
84b6ad70 2356
25de7aa7
YW
2357static int udev_rule_line_apply_static_dev_perms(UdevRuleLine *rule_line) {
2358 UdevRuleToken *token;
f4f6f2c7 2359 _cleanup_strv_free_ char **tags = NULL;
25de7aa7
YW
2360 uid_t uid = UID_INVALID;
2361 gid_t gid = GID_INVALID;
2362 mode_t mode = MODE_INVALID;
2363 int r;
d6f116a7 2364
25de7aa7 2365 assert(rule_line);
912541b0 2366
25de7aa7
YW
2367 if (!FLAGS_SET(rule_line->type, LINE_HAS_STATIC_NODE))
2368 return 0;
912541b0 2369
25de7aa7
YW
2370 LIST_FOREACH(tokens, token, rule_line->tokens)
2371 if (token->type == TK_A_OWNER_ID)
2372 uid = PTR_TO_UID(token->data);
2373 else if (token->type == TK_A_GROUP_ID)
2374 gid = PTR_TO_GID(token->data);
2375 else if (token->type == TK_A_MODE_ID)
2376 mode = PTR_TO_MODE(token->data);
2377 else if (token->type == TK_A_TAG) {
2378 r = strv_extend(&tags, token->value);
2379 if (r < 0)
2380 return log_oom();
2381 } else if (token->type == TK_A_OPTIONS_STATIC_NODE) {
2382 r = apply_static_dev_perms(token->value, uid, gid, mode, tags);
2383 if (r < 0)
2384 return r;
912541b0
KS
2385 }
2386
25de7aa7
YW
2387 return 0;
2388}
2389
2390int udev_rules_apply_static_dev_perms(UdevRules *rules) {
2391 UdevRuleFile *file;
2392 UdevRuleLine *line;
2393 int r;
2394
2395 assert(rules);
84b6ad70 2396
25de7aa7
YW
2397 LIST_FOREACH(rule_files, file, rules->rule_files)
2398 LIST_FOREACH(rule_lines, line, file->rule_lines) {
2399 r = udev_rule_line_apply_static_dev_perms(line);
2400 if (r < 0)
2401 return r;
84b6ad70 2402 }
84b6ad70 2403
fdd21be6 2404 return 0;
761dfddc 2405}