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