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