]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/udev/udev-rules.c
device-util: Declare iterator variables inline
[thirdparty/systemd.git] / src / udev / udev-rules.c
CommitLineData
f13467ec 1/* SPDX-License-Identifier: GPL-2.0-or-later */
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"
acfbd71c 8#include "conf-parser.h"
6e2e83b4 9#include "confidential-virt.h"
28db6fbf 10#include "constants.h"
a1130022 11#include "device-private.h"
480ecb7d 12#include "device-util.h"
8fb3f009 13#include "dirent-util.h"
3ffd4af2 14#include "fd-util.h"
fae0f8a0 15#include "fileio.h"
4b3b5bc7 16#include "format-util.h"
fdd21be6 17#include "fs-util.h"
7d50b32a 18#include "glob-util.h"
e79c228b 19#include "list.h"
5ea78a39 20#include "mkdir.h"
b4d885f0 21#include "netif-naming-scheme.h"
25de7aa7 22#include "nulstr-util.h"
b4ba2fe3 23#include "parse-util.h"
4f5dd394 24#include "path-util.h"
88b013b2 25#include "proc-cmdline.h"
8fcde012 26#include "stat-util.h"
84b6ad70 27#include "strv.h"
5ea78a39 28#include "strxcpyx.h"
f4cf2e5b 29#include "sysctl-util.h"
1a0bd015 30#include "syslog-util.h"
07a26e42 31#include "udev-builtin.h"
25de7aa7 32#include "udev-event.h"
26dd37f6 33#include "udev-node.h"
25de7aa7 34#include "udev-rules.h"
b428efa5 35#include "udev-util.h"
b1d4f8e1 36#include "user-util.h"
4801d8af 37#include "virt.h"
2232cac8 38
29162ba0 39#define RULES_DIRS ((const char* const*) CONF_PATHS_STRV("udev/rules.d"))
c7521974 40
e79c228b
ZJS
41typedef enum {
42 OP_MATCH, /* == */
43 OP_NOMATCH, /* != */
44 OP_ADD, /* += */
45 OP_REMOVE, /* -= */
46 OP_ASSIGN, /* = */
47 OP_ASSIGN_FINAL, /* := */
48 _OP_TYPE_MAX,
2d93c20e 49 _OP_TYPE_INVALID = -EINVAL,
e79c228b
ZJS
50} UdevRuleOperatorType;
51
52typedef enum {
067cc51f
YW
53 MATCH_TYPE_EMPTY, /* empty string */
54 MATCH_TYPE_PLAIN, /* no special characters */
55 MATCH_TYPE_PLAIN_WITH_EMPTY, /* no special characters with empty string, e.g., "|foo" */
56 MATCH_TYPE_GLOB, /* shell globs ?,*,[] */
57 MATCH_TYPE_GLOB_WITH_EMPTY, /* shell globs ?,*,[] with empty string, e.g., "|foo*" */
58 MATCH_TYPE_SUBSYSTEM, /* "subsystem", "bus", or "class" */
e79c228b 59 _MATCH_TYPE_MAX,
2d93c20e 60 _MATCH_TYPE_INVALID = -EINVAL,
e79c228b
ZJS
61} UdevRuleMatchType;
62
63typedef enum {
64 SUBST_TYPE_PLAIN, /* no substitution */
65 SUBST_TYPE_FORMAT, /* % or $ */
66 SUBST_TYPE_SUBSYS, /* "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
67 _SUBST_TYPE_MAX,
2d93c20e 68 _SUBST_TYPE_INVALID = -EINVAL,
e79c228b
ZJS
69} UdevRuleSubstituteType;
70
71typedef enum {
72 /* lvalues which take match or nomatch operator */
73 TK_M_ACTION, /* string, device_get_action() */
74 TK_M_DEVPATH, /* path, sd_device_get_devpath() */
75 TK_M_KERNEL, /* string, sd_device_get_sysname() */
76 TK_M_DEVLINK, /* strv, sd_device_get_devlink_first(), sd_device_get_devlink_next() */
77 TK_M_NAME, /* string, name of network interface */
78 TK_M_ENV, /* string, device property, takes key through attribute */
4801d8af 79 TK_M_CONST, /* string, system-specific hard-coded constant */
e79c228b
ZJS
80 TK_M_TAG, /* strv, sd_device_get_tag_first(), sd_device_get_tag_next() */
81 TK_M_SUBSYSTEM, /* string, sd_device_get_subsystem() */
82 TK_M_DRIVER, /* string, sd_device_get_driver() */
1223227f 83 TK_M_ATTR, /* string, takes filename through attribute, sd_device_get_sysattr_value(), udev_resolve_subsys_kernel(), etc. */
e79c228b
ZJS
84 TK_M_SYSCTL, /* string, takes kernel parameter through attribute */
85
162392b7 86 /* matches parent parameters */
e79c228b
ZJS
87 TK_M_PARENTS_KERNEL, /* string */
88 TK_M_PARENTS_SUBSYSTEM, /* string */
89 TK_M_PARENTS_DRIVER, /* string */
90 TK_M_PARENTS_ATTR, /* string */
91 TK_M_PARENTS_TAG, /* strv */
92
93 TK_M_TEST, /* path, optionally mode_t can be specified by attribute, test the existence of a file */
94 TK_M_PROGRAM, /* string, execute a program */
95 TK_M_IMPORT_FILE, /* path */
96 TK_M_IMPORT_PROGRAM, /* string, import properties from the result of program */
97 TK_M_IMPORT_BUILTIN, /* string, import properties from the result of built-in command */
98 TK_M_IMPORT_DB, /* string, import properties from database */
99 TK_M_IMPORT_CMDLINE, /* string, kernel command line */
100 TK_M_IMPORT_PARENT, /* string, parent property */
101 TK_M_RESULT, /* string, result of TK_M_PROGRAM */
102
103#define _TK_M_MAX (TK_M_RESULT + 1)
104#define _TK_A_MIN _TK_M_MAX
105
106 /* lvalues which take one of assign operators */
107 TK_A_OPTIONS_STRING_ESCAPE_NONE, /* no argument */
108 TK_A_OPTIONS_STRING_ESCAPE_REPLACE, /* no argument */
109 TK_A_OPTIONS_DB_PERSIST, /* no argument */
110 TK_A_OPTIONS_INOTIFY_WATCH, /* boolean */
111 TK_A_OPTIONS_DEVLINK_PRIORITY, /* int */
1a0bd015 112 TK_A_OPTIONS_LOG_LEVEL, /* string of log level or "reset" */
e79c228b
ZJS
113 TK_A_OWNER, /* user name */
114 TK_A_GROUP, /* group name */
115 TK_A_MODE, /* mode string */
116 TK_A_OWNER_ID, /* uid_t */
117 TK_A_GROUP_ID, /* gid_t */
118 TK_A_MODE_ID, /* mode_t */
119 TK_A_TAG, /* string */
120 TK_A_OPTIONS_STATIC_NODE, /* device path, /dev/... */
121 TK_A_SECLABEL, /* string with attribute */
122 TK_A_ENV, /* string with attribute */
123 TK_A_NAME, /* ifname */
124 TK_A_DEVLINK, /* string */
125 TK_A_ATTR, /* string with attribute */
126 TK_A_SYSCTL, /* string with attribute */
127 TK_A_RUN_BUILTIN, /* string */
128 TK_A_RUN_PROGRAM, /* string */
129
130 _TK_TYPE_MAX,
2d93c20e 131 _TK_TYPE_INVALID = -EINVAL,
e79c228b
ZJS
132} UdevRuleTokenType;
133
134typedef enum {
135 LINE_HAS_NAME = 1 << 0, /* has NAME= */
136 LINE_HAS_DEVLINK = 1 << 1, /* has SYMLINK=, OWNER=, GROUP= or MODE= */
137 LINE_HAS_STATIC_NODE = 1 << 2, /* has OPTIONS=static_node */
138 LINE_HAS_GOTO = 1 << 3, /* has GOTO= */
139 LINE_HAS_LABEL = 1 << 4, /* has LABEL= */
140 LINE_UPDATE_SOMETHING = 1 << 5, /* has other TK_A_* or TK_M_IMPORT tokens */
7a771d1d 141 LINE_IS_REFERENCED = 1 << 6, /* is referenced by GOTO */
e79c228b
ZJS
142} UdevRuleLineType;
143
144typedef struct UdevRuleFile UdevRuleFile;
145typedef struct UdevRuleLine UdevRuleLine;
146typedef struct UdevRuleToken UdevRuleToken;
147
148struct UdevRuleToken {
149 UdevRuleTokenType type:8;
150 UdevRuleOperatorType op:8;
151 UdevRuleMatchType match_type:8;
152 UdevRuleSubstituteType attr_subst_type:7;
153 bool attr_match_remove_trailing_whitespace:1;
154 const char *value;
155 void *data;
c06ab041
YW
156
157 UdevRuleLine *rule_line;
e79c228b
ZJS
158 LIST_FIELDS(UdevRuleToken, tokens);
159};
160
161struct UdevRuleLine {
162 char *line;
163 unsigned line_number;
164 UdevRuleLineType type;
165
166 const char *label;
167 const char *goto_label;
168 UdevRuleLine *goto_line;
169
170 UdevRuleFile *rule_file;
e79c228b
ZJS
171 LIST_HEAD(UdevRuleToken, tokens);
172 LIST_FIELDS(UdevRuleLine, rule_lines);
173};
174
175struct UdevRuleFile {
176 char *filename;
c06ab041
YW
177 unsigned issues; /* used by "udevadm verify" */
178
179 UdevRules *rules;
e79c228b
ZJS
180 LIST_HEAD(UdevRuleLine, rule_lines);
181 LIST_FIELDS(UdevRuleFile, rule_files);
182};
183
184struct UdevRules {
e79c228b
ZJS
185 ResolveNameTiming resolve_name_timing;
186 Hashmap *known_users;
187 Hashmap *known_groups;
acfbd71c 188 Hashmap *stats_by_path;
e79c228b
ZJS
189 LIST_HEAD(UdevRuleFile, rule_files);
190};
191
c06ab041
YW
192#define LINE_GET_RULES(line) \
193 ASSERT_PTR(ASSERT_PTR(ASSERT_PTR(line)->rule_file)->rules)
194
d4114f70
ZJS
195/*** Logging helpers ***/
196
c06ab041 197#define log_udev_rule_internal(device, file, line_nr, level, error, fmt, ...) \
d4114f70 198 ({ \
4f5de157 199 int _lv = (level); \
2aa5fe5e 200 sd_device *_dev = (device); \
c06ab041 201 UdevRuleFile *_f = (file); \
d4114f70
ZJS
202 const char *_n = _f ? _f->filename : NULL; \
203 \
2aa5fe5e
YW
204 if (!_dev && _f) \
205 _f->issues |= (1U << _lv); \
206 \
8d1c9489 207 log_device_full_errno_zerook( \
2aa5fe5e 208 _dev, _lv, error, "%s:%u " fmt, \
c06ab041 209 strna(_n), line_nr, \
8d1c9489
ZJS
210 ##__VA_ARGS__); \
211 })
212
c06ab041
YW
213/* Mainly used when applying tokens to the event device. */
214#define log_event_full_errno_zerook(device, token, ...) \
215 ({ \
216 UdevRuleToken *_t = (token); \
217 UdevRuleLine *_l = _t ? _t->rule_line : NULL; \
218 \
219 log_udev_rule_internal( \
220 device, \
221 _l ? _l->rule_file : NULL, \
222 _l ? _l->line_number : 0, \
223 __VA_ARGS__); \
224 })
225
226#define log_event_full_errno(device, token, level, error, ...) \
8d1c9489
ZJS
227 ({ \
228 int _error = (error); \
229 ASSERT_NON_ZERO(_error); \
c06ab041
YW
230 log_event_full_errno_zerook( \
231 device, token, level, _error, ##__VA_ARGS__); \
d4114f70
ZJS
232 })
233
c06ab041
YW
234#define log_event_full(device, token, level, ...) (void) log_event_full_errno_zerook(device, token, level, 0, __VA_ARGS__)
235
236#define log_event_debug(device, token, ...) log_event_full(device, token, LOG_DEBUG, __VA_ARGS__)
237#define log_event_info(device, token, ...) log_event_full(device, token, LOG_INFO, __VA_ARGS__)
238#define log_event_notice(device, token, ...) log_event_full(device, token, LOG_NOTICE, __VA_ARGS__)
239#define log_event_warning(device, token, ...) log_event_full(device, token, LOG_WARNING, __VA_ARGS__)
240#define log_event_error(device, token, ...) log_event_full(device, token, LOG_ERR, __VA_ARGS__)
241
242#define log_event_debug_errno(device, token, error, ...) log_event_full_errno(device, token, LOG_DEBUG, error, __VA_ARGS__)
243#define log_event_info_errno(device, token, error, ...) log_event_full_errno(device, token, LOG_INFO, error, __VA_ARGS__)
244#define log_event_notice_errno(device, token, error, ...) log_event_full_errno(device, token, LOG_NOTICE, error, __VA_ARGS__)
245#define log_event_warning_errno(device, token, error, ...) log_event_full_errno(device, token, LOG_WARNING, error, __VA_ARGS__)
246#define log_event_error_errno(device, token, error, ...) log_event_full_errno(device, token, LOG_ERR, error, __VA_ARGS__)
247
248/* Mainly used when parsing .rules files. */
249#define log_file_full_errno_zerook(...) \
250 log_udev_rule_internal(NULL, __VA_ARGS__)
251
252#define log_file_error(file, line_nr, ...) \
253 log_file_full_errno_zerook(file, line_nr, LOG_ERR, 0, __VA_ARGS__)
254
255#define log_line_full_errno_zerook(line, ...) \
4f5de157 256 ({ \
c06ab041
YW
257 UdevRuleLine *_l = (line); \
258 log_file_full_errno_zerook( \
259 _l ? _l->rule_file : NULL, \
260 _l ? _l->line_number : 0, \
261 __VA_ARGS__); \
4f5de157
DL
262 })
263
c06ab041 264#define log_line_full_errno(line, level, error, ...) \
4f5de157
DL
265 ({ \
266 int _error = (error); \
267 ASSERT_NON_ZERO(_error); \
268 log_line_full_errno_zerook( \
c06ab041 269 line, level, _error, ##__VA_ARGS__); \
4f5de157
DL
270 })
271
c06ab041
YW
272#define log_line_full(line, level, ...) (void) log_line_full_errno_zerook(line, level, 0, __VA_ARGS__)
273
274#define log_line_debug(line, ...) log_line_full(line, LOG_DEBUG, __VA_ARGS__)
275#define log_line_info(line, ...) log_line_full(line, LOG_INFO, __VA_ARGS__)
276#define log_line_notice(line, ...) log_line_full(line, LOG_NOTICE, __VA_ARGS__)
277#define log_line_warning(line, ...) log_line_full(line, LOG_WARNING, __VA_ARGS__)
278#define log_line_error(line, ...) log_line_full(line, LOG_ERR, __VA_ARGS__)
279
280#define log_line_debug_errno(line, error, ...) log_line_full_errno(line, LOG_DEBUG, error, __VA_ARGS__)
281#define log_line_info_errno(line, error, ...) log_line_full_errno(line, LOG_INFO, error, __VA_ARGS__)
282#define log_line_notice_errno(line, error, ...) log_line_full_errno(line, LOG_NOTICE, error, __VA_ARGS__)
283#define log_line_warning_errno(line, error, ...) log_line_full_errno(line, LOG_WARNING, error, __VA_ARGS__)
284#define log_line_error_errno(line, error, ...) log_line_full_errno(line, LOG_ERR, error, __VA_ARGS__)
4f5de157 285
c06ab041
YW
286#define _log_line_invalid_token(line, key, type) \
287 log_line_error_errno(line, SYNTHETIC_ERRNO(EINVAL), \
288 "Invalid %s for %s.", type, key)
4f5de157 289
c06ab041
YW
290#define log_line_invalid_op(line, key) _log_line_invalid_token(line, key, "operator")
291#define log_line_invalid_attr(line, key) _log_line_invalid_token(line, key, "attribute")
292
293#define log_line_invalid_attr_format(line, key, attr, offset, hint) \
294 log_line_error_errno(line, SYNTHETIC_ERRNO(EINVAL), \
295 "Invalid attribute \"%s\" for %s (char %zu: %s), ignoring.", \
296 attr, key, offset, hint)
297#define log_line_invalid_value(line, key, value, offset, hint) \
298 log_line_error_errno(line, SYNTHETIC_ERRNO(EINVAL), \
299 "Invalid value \"%s\" for %s (char %zu: %s), ignoring.", \
300 value, key, offset, hint)
4f5de157 301
c06ab041
YW
302static void log_unknown_owner(sd_device *dev, UdevRuleLine *line, int error, const char *entity, const char *name) {
303 assert(line);
304 ASSERT_NON_ZERO(error);
305
d4114f70 306 if (IN_SET(abs(error), ENOENT, ESRCH))
c06ab041 307 log_udev_rule_internal(dev, line->rule_file, line->line_number, LOG_ERR, error,
4134614f 308 "Unknown %s '%s', ignoring.", entity, name);
d4114f70 309 else
c06ab041
YW
310 log_udev_rule_internal(dev, line->rule_file, line->line_number, LOG_ERR, error,
311 "Failed to resolve %s '%s', ignoring: %m", entity, name);
d4114f70
ZJS
312}
313
e5a34948
YW
314static void log_event_truncated(
315 sd_device *dev,
316 UdevRuleToken *token,
317 const char *what,
318 const char *format,
319 const char *key,
320 bool is_match) {
321
322 if (is_match)
323 log_event_debug(dev, token,
324 "The %s is truncated while substituting into '%s', "
325 "assuming the %s key does not match.",
326 what, format, key);
327 else
328 log_event_warning(dev, token,
329 "The %s is truncated while substituting into '%s', "
330 "refusing to apply the %s key.",
331 what, format, key);
332}
333
d4114f70
ZJS
334/*** Other functions ***/
335
a0244c5d
YW
336static UdevRuleToken *udev_rule_token_free(UdevRuleToken *token) {
337 if (!token)
338 return NULL;
339
340 if (token->rule_line)
341 LIST_REMOVE(tokens, token->rule_line->tokens, token);
342
343 return mfree(token);
915bf0f6
KS
344}
345
a0244c5d
YW
346DEFINE_TRIVIAL_CLEANUP_FUNC(UdevRuleToken*, udev_rule_token_free);
347
25de7aa7 348static void udev_rule_line_clear_tokens(UdevRuleLine *rule_line) {
25de7aa7 349 assert(rule_line);
4052400f 350
80a226b2 351 LIST_FOREACH(tokens, i, rule_line->tokens)
25de7aa7 352 udev_rule_token_free(i);
5d6a1fa6
KS
353}
354
a0244c5d 355static UdevRuleLine *udev_rule_line_free(UdevRuleLine *rule_line) {
25de7aa7 356 if (!rule_line)
75db809a 357 return NULL;
912541b0 358
25de7aa7 359 udev_rule_line_clear_tokens(rule_line);
c7521974 360
c06ab041 361 if (rule_line->rule_file)
25de7aa7 362 LIST_REMOVE(rule_lines, rule_line->rule_file->rule_lines, rule_line);
25de7aa7
YW
363
364 free(rule_line->line);
75db809a 365 return mfree(rule_line);
4052400f 366}
154a7b84 367
25de7aa7
YW
368DEFINE_TRIVIAL_CLEANUP_FUNC(UdevRuleLine*, udev_rule_line_free);
369
a0244c5d 370static UdevRuleFile *udev_rule_file_free(UdevRuleFile *rule_file) {
25de7aa7 371 if (!rule_file)
a0244c5d 372 return NULL;
25de7aa7 373
80a226b2 374 LIST_FOREACH(rule_lines, i, rule_file->rule_lines)
25de7aa7 375 udev_rule_line_free(i);
912541b0 376
a0244c5d
YW
377 if (rule_file->rules)
378 LIST_REMOVE(rule_files, rule_file->rules->rule_files, rule_file);
379
25de7aa7 380 free(rule_file->filename);
a0244c5d 381 return mfree(rule_file);
4052400f 382}
530727ae 383
a0244c5d
YW
384DEFINE_TRIVIAL_CLEANUP_FUNC(UdevRuleFile*, udev_rule_file_free);
385
25de7aa7 386UdevRules *udev_rules_free(UdevRules *rules) {
25de7aa7
YW
387 if (!rules)
388 return NULL;
389
80a226b2 390 LIST_FOREACH(rule_files, i, rules->rule_files)
25de7aa7
YW
391 udev_rule_file_free(i);
392
393 hashmap_free_free_key(rules->known_users);
394 hashmap_free_free_key(rules->known_groups);
acfbd71c 395 hashmap_free(rules->stats_by_path);
25de7aa7 396 return mfree(rules);
c7521974 397}
a27cd06c 398
c06ab041
YW
399static int rule_resolve_user(UdevRuleLine *rule_line, const char *name, uid_t *ret) {
400 Hashmap **known_users = &LINE_GET_RULES(rule_line)->known_users;
25de7aa7
YW
401 _cleanup_free_ char *n = NULL;
402 uid_t uid;
403 void *val;
23bf8dd7 404 int r;
912541b0 405
25de7aa7 406 assert(name);
c06ab041 407 assert(ret);
25de7aa7 408
c06ab041 409 val = hashmap_get(*known_users, name);
25de7aa7
YW
410 if (val) {
411 *ret = PTR_TO_UID(val);
412 return 0;
413 }
414
415 r = get_user_creds(&name, &uid, NULL, NULL, NULL, USER_CREDS_ALLOW_MISSING);
416 if (r < 0) {
c06ab041 417 log_unknown_owner(NULL, rule_line, r, "user", name);
25de7aa7
YW
418 *ret = UID_INVALID;
419 return 0;
912541b0 420 }
912541b0 421
25de7aa7
YW
422 n = strdup(name);
423 if (!n)
530727ae
YW
424 return -ENOMEM;
425
c06ab041 426 r = hashmap_ensure_put(known_users, &string_hash_ops, n, UID_TO_PTR(uid));
25de7aa7
YW
427 if (r < 0)
428 return r;
429
430 TAKE_PTR(n);
431 *ret = uid;
432 return 0;
154a7b84
KS
433}
434
c06ab041
YW
435static int rule_resolve_group(UdevRuleLine *rule_line, const char *name, gid_t *ret) {
436 Hashmap **known_groups = &LINE_GET_RULES(rule_line)->known_groups;
25de7aa7
YW
437 _cleanup_free_ char *n = NULL;
438 gid_t gid;
439 void *val;
23bf8dd7 440 int r;
912541b0 441
25de7aa7 442 assert(name);
c06ab041 443 assert(ret);
25de7aa7 444
c06ab041 445 val = hashmap_get(*known_groups, name);
25de7aa7
YW
446 if (val) {
447 *ret = PTR_TO_GID(val);
448 return 0;
449 }
450
451 r = get_group_creds(&name, &gid, USER_CREDS_ALLOW_MISSING);
452 if (r < 0) {
c06ab041 453 log_unknown_owner(NULL, rule_line, r, "group", name);
25de7aa7
YW
454 *ret = GID_INVALID;
455 return 0;
912541b0 456 }
912541b0 457
25de7aa7
YW
458 n = strdup(name);
459 if (!n)
530727ae
YW
460 return -ENOMEM;
461
c06ab041 462 r = hashmap_ensure_put(known_groups, &string_hash_ops, n, GID_TO_PTR(gid));
25de7aa7
YW
463 if (r < 0)
464 return r;
465
466 TAKE_PTR(n);
467 *ret = gid;
468 return 0;
154a7b84
KS
469}
470
25de7aa7
YW
471static UdevRuleSubstituteType rule_get_substitution_type(const char *str) {
472 assert(str);
912541b0 473
25de7aa7
YW
474 if (str[0] == '[')
475 return SUBST_TYPE_SUBSYS;
476 if (strchr(str, '%') || strchr(str, '$'))
477 return SUBST_TYPE_FORMAT;
478 return SUBST_TYPE_PLAIN;
479}
912541b0 480
5004aa84
DL
481static bool type_has_nulstr_value(UdevRuleTokenType type) {
482 return type < TK_M_TEST || type == TK_M_RESULT;
483}
484
25de7aa7 485static int rule_line_add_token(UdevRuleLine *rule_line, UdevRuleTokenType type, UdevRuleOperatorType op, char *value, void *data) {
a0244c5d 486 _cleanup_(udev_rule_token_freep) UdevRuleToken *token = NULL;
25de7aa7
YW
487 UdevRuleMatchType match_type = _MATCH_TYPE_INVALID;
488 UdevRuleSubstituteType subst_type = _SUBST_TYPE_INVALID;
489 bool remove_trailing_whitespace = false;
490 size_t len;
912541b0 491
25de7aa7
YW
492 assert(rule_line);
493 assert(type >= 0 && type < _TK_TYPE_MAX);
494 assert(op >= 0 && op < _OP_TYPE_MAX);
495
496 if (type < _TK_M_MAX) {
497 assert(value);
498 assert(IN_SET(op, OP_MATCH, OP_NOMATCH));
499
500 if (type == TK_M_SUBSYSTEM && STR_IN_SET(value, "subsystem", "bus", "class"))
501 match_type = MATCH_TYPE_SUBSYSTEM;
502 else if (isempty(value))
503 match_type = MATCH_TYPE_EMPTY;
504 else if (streq(value, "?*")) {
505 /* Convert KEY=="?*" -> KEY!="" */
506 match_type = MATCH_TYPE_EMPTY;
507 op = op == OP_MATCH ? OP_NOMATCH : OP_MATCH;
508 } else if (string_is_glob(value))
509 match_type = MATCH_TYPE_GLOB;
510 else
511 match_type = MATCH_TYPE_PLAIN;
912541b0 512
5004aa84 513 if (type_has_nulstr_value(type)) {
25de7aa7 514 /* Convert value string to nulstr. */
067cc51f
YW
515 bool bar = true, empty = false;
516 char *a, *b;
517
518 for (a = b = value; *a != '\0'; a++) {
519 if (*a != '|') {
520 *b++ = *a;
521 bar = false;
522 } else {
523 if (bar)
524 empty = true;
525 else
526 *b++ = '\0';
527 bar = true;
528 }
529 }
530 *b = '\0';
1e67a9c2
YG
531
532 /* Make sure the value is end, so NULSTR_FOREACH can read correct match */
533 if (b < a)
534 b[1] = '\0';
535
067cc51f
YW
536 if (bar)
537 empty = true;
538
539 if (empty) {
540 if (match_type == MATCH_TYPE_GLOB)
541 match_type = MATCH_TYPE_GLOB_WITH_EMPTY;
542 if (match_type == MATCH_TYPE_PLAIN)
543 match_type = MATCH_TYPE_PLAIN_WITH_EMPTY;
25de7aa7
YW
544 }
545 }
912541b0
KS
546 }
547
25de7aa7
YW
548 if (IN_SET(type, TK_M_ATTR, TK_M_PARENTS_ATTR)) {
549 assert(value);
550 assert(data);
be4bedd1 551
25de7aa7
YW
552 len = strlen(value);
553 if (len > 0 && !isspace(value[len - 1]))
554 remove_trailing_whitespace = true;
912541b0 555
af2e52f4 556 subst_type = rule_get_substitution_type(data);
25de7aa7 557 }
fae0f8a0 558
25de7aa7
YW
559 token = new(UdevRuleToken, 1);
560 if (!token)
561 return -ENOMEM;
fae0f8a0 562
25de7aa7
YW
563 *token = (UdevRuleToken) {
564 .type = type,
565 .op = op,
566 .value = value,
567 .data = data,
568 .match_type = match_type,
569 .attr_subst_type = subst_type,
570 .attr_match_remove_trailing_whitespace = remove_trailing_whitespace,
e7f5d708 571 .rule_line = rule_line,
25de7aa7 572 };
fae0f8a0 573
e7f5d708 574 LIST_APPEND(tokens, rule_line->tokens, token);
25de7aa7
YW
575
576 if (token->type == TK_A_NAME)
577 SET_FLAG(rule_line->type, LINE_HAS_NAME, true);
578
579 else if (IN_SET(token->type, TK_A_DEVLINK,
580 TK_A_OWNER, TK_A_GROUP, TK_A_MODE,
581 TK_A_OWNER_ID, TK_A_GROUP_ID, TK_A_MODE_ID))
582 SET_FLAG(rule_line->type, LINE_HAS_DEVLINK, true);
583
5abba26e
YW
584 else if (token->type == TK_A_OPTIONS_STATIC_NODE)
585 SET_FLAG(rule_line->type, LINE_HAS_STATIC_NODE, true);
586
25de7aa7 587 else if (token->type >= _TK_A_MIN ||
9c69cd7e 588 IN_SET(token->type, TK_M_PROGRAM,
25de7aa7
YW
589 TK_M_IMPORT_FILE, TK_M_IMPORT_PROGRAM, TK_M_IMPORT_BUILTIN,
590 TK_M_IMPORT_DB, TK_M_IMPORT_CMDLINE, TK_M_IMPORT_PARENT))
591 SET_FLAG(rule_line->type, LINE_UPDATE_SOMETHING, true);
fae0f8a0 592
a0244c5d 593 TAKE_PTR(token);
912541b0 594 return 0;
bd0ed2ff
KS
595}
596
c06ab041 597static void check_value_format_and_warn(UdevRuleLine *line, const char *key, const char *value, bool nonempty) {
f85cc54c
ZJS
598 size_t offset;
599 const char *hint;
600
601 if (nonempty && isempty(value))
c06ab041 602 log_line_invalid_value(line, key, value, (size_t) 0, "empty value");
f85cc54c 603 else if (udev_check_format(value, &offset, &hint) < 0)
c06ab041 604 log_line_invalid_value(line, key, value, offset + 1, hint);
f85cc54c
ZJS
605}
606
c06ab041 607static int check_attr_format_and_warn(UdevRuleLine *line, const char *key, const char *value) {
7504610b
ZJS
608 size_t offset;
609 const char *hint;
610
611 if (isempty(value))
c06ab041 612 return log_line_invalid_attr(line, key);
7504610b 613 if (udev_check_format(value, &offset, &hint) < 0)
c06ab041 614 log_line_invalid_attr_format(line, key, value, offset + 1, hint);
7504610b
ZJS
615 return 0;
616}
617
c06ab041
YW
618static int parse_token(UdevRuleLine *rule_line, const char *key, char *attr, UdevRuleOperatorType op, char *value) {
619 ResolveNameTiming resolve_name_timing = LINE_GET_RULES(rule_line)->resolve_name_timing;
25de7aa7 620 bool is_match = IN_SET(op, OP_MATCH, OP_NOMATCH);
a7521142 621 int r;
912541b0 622
25de7aa7
YW
623 assert(key);
624 assert(value);
625
25de7aa7
YW
626 if (streq(key, "ACTION")) {
627 if (attr)
c06ab041 628 return log_line_invalid_attr(rule_line, key);
25de7aa7 629 if (!is_match)
c06ab041 630 return log_line_invalid_op(rule_line, key);
25de7aa7
YW
631
632 r = rule_line_add_token(rule_line, TK_M_ACTION, op, value, NULL);
633 } else if (streq(key, "DEVPATH")) {
634 if (attr)
c06ab041 635 return log_line_invalid_attr(rule_line, key);
25de7aa7 636 if (!is_match)
c06ab041 637 return log_line_invalid_op(rule_line, key);
25de7aa7
YW
638
639 r = rule_line_add_token(rule_line, TK_M_DEVPATH, op, value, NULL);
640 } else if (streq(key, "KERNEL")) {
641 if (attr)
c06ab041 642 return log_line_invalid_attr(rule_line, key);
25de7aa7 643 if (!is_match)
c06ab041 644 return log_line_invalid_op(rule_line, key);
25de7aa7
YW
645
646 r = rule_line_add_token(rule_line, TK_M_KERNEL, op, value, NULL);
647 } else if (streq(key, "SYMLINK")) {
648 if (attr)
c06ab041 649 return log_line_invalid_attr(rule_line, key);
d7aee41d 650 if (!is_match) {
c06ab041 651 check_value_format_and_warn(rule_line, key, value, false);
d7aee41d
YW
652 r = rule_line_add_token(rule_line, TK_A_DEVLINK, op, value, NULL);
653 } else
654 r = rule_line_add_token(rule_line, TK_M_DEVLINK, op, value, NULL);
25de7aa7
YW
655 } else if (streq(key, "NAME")) {
656 if (attr)
c06ab041 657 return log_line_invalid_attr(rule_line, key);
25de7aa7 658 if (op == OP_REMOVE)
c06ab041 659 return log_line_invalid_op(rule_line, key);
25de7aa7 660 if (op == OP_ADD) {
c06ab041 661 log_line_warning(rule_line, "%s key takes '==', '!=', '=', or ':=' operator, assuming '='.", key);
25de7aa7
YW
662 op = OP_ASSIGN;
663 }
664
665 if (!is_match) {
666 if (streq(value, "%k"))
c06ab041
YW
667 return log_line_error_errno(rule_line, SYNTHETIC_ERRNO(EINVAL),
668 "Ignoring NAME=\"%%k\", as it will take no effect.");
25de7aa7 669 if (isempty(value))
c06ab041
YW
670 return log_line_error_errno(rule_line, SYNTHETIC_ERRNO(EINVAL),
671 "Ignoring NAME=\"\", as udev will not delete any network interfaces.");
672 check_value_format_and_warn(rule_line, key, value, false);
d7aee41d 673
25de7aa7
YW
674 r = rule_line_add_token(rule_line, TK_A_NAME, op, value, NULL);
675 } else
676 r = rule_line_add_token(rule_line, TK_M_NAME, op, value, NULL);
677 } else if (streq(key, "ENV")) {
678 if (isempty(attr))
c06ab041 679 return log_line_invalid_attr(rule_line, key);
25de7aa7 680 if (op == OP_REMOVE)
c06ab041 681 return log_line_invalid_op(rule_line, key);
25de7aa7 682 if (op == OP_ASSIGN_FINAL) {
c06ab041 683 log_line_warning(rule_line, "%s key takes '==', '!=', '=', or '+=' operator, assuming '='.", key);
25de7aa7
YW
684 op = OP_ASSIGN;
685 }
912541b0 686
25de7aa7
YW
687 if (!is_match) {
688 if (STR_IN_SET(attr,
689 "ACTION", "DEVLINKS", "DEVNAME", "DEVPATH", "DEVTYPE", "DRIVER",
690 "IFINDEX", "MAJOR", "MINOR", "SEQNUM", "SUBSYSTEM", "TAGS"))
c06ab041
YW
691 return log_line_error_errno(rule_line, SYNTHETIC_ERRNO(EINVAL),
692 "Invalid ENV attribute. '%s' cannot be set.", attr);
912541b0 693
c06ab041 694 check_value_format_and_warn(rule_line, key, value, false);
f85cc54c 695
25de7aa7
YW
696 r = rule_line_add_token(rule_line, TK_A_ENV, op, value, attr);
697 } else
698 r = rule_line_add_token(rule_line, TK_M_ENV, op, value, attr);
4801d8af
JS
699 } else if (streq(key, "CONST")) {
700 if (isempty(attr) || !STR_IN_SET(attr, "arch", "virt"))
c06ab041 701 return log_line_invalid_attr(rule_line, key);
4801d8af 702 if (!is_match)
c06ab041 703 return log_line_invalid_op(rule_line, key);
4801d8af 704 r = rule_line_add_token(rule_line, TK_M_CONST, op, value, attr);
25de7aa7
YW
705 } else if (streq(key, "TAG")) {
706 if (attr)
c06ab041 707 return log_line_invalid_attr(rule_line, key);
25de7aa7 708 if (op == OP_ASSIGN_FINAL) {
c06ab041 709 log_line_warning(rule_line, "%s key takes '==', '!=', '=', or '+=' operator, assuming '='.", key);
25de7aa7 710 op = OP_ASSIGN;
912541b0 711 }
319c6700 712
d7aee41d 713 if (!is_match) {
c06ab041 714 check_value_format_and_warn(rule_line, key, value, true);
f85cc54c 715
d7aee41d
YW
716 r = rule_line_add_token(rule_line, TK_A_TAG, op, value, NULL);
717 } else
718 r = rule_line_add_token(rule_line, TK_M_TAG, op, value, NULL);
25de7aa7
YW
719 } else if (streq(key, "SUBSYSTEM")) {
720 if (attr)
c06ab041 721 return log_line_invalid_attr(rule_line, key);
25de7aa7 722 if (!is_match)
c06ab041 723 return log_line_invalid_op(rule_line, key);
25de7aa7
YW
724
725 if (STR_IN_SET(value, "bus", "class"))
c06ab041 726 log_line_warning(rule_line, "\"%s\" must be specified as \"subsystem\".", value);
25de7aa7
YW
727
728 r = rule_line_add_token(rule_line, TK_M_SUBSYSTEM, op, value, NULL);
729 } else if (streq(key, "DRIVER")) {
730 if (attr)
c06ab041 731 return log_line_invalid_attr(rule_line, key);
25de7aa7 732 if (!is_match)
c06ab041 733 return log_line_invalid_op(rule_line, key);
25de7aa7
YW
734
735 r = rule_line_add_token(rule_line, TK_M_DRIVER, op, value, NULL);
736 } else if (streq(key, "ATTR")) {
c06ab041 737 r = check_attr_format_and_warn(rule_line, key, attr);
7504610b
ZJS
738 if (r < 0)
739 return r;
25de7aa7 740 if (op == OP_REMOVE)
c06ab041 741 return log_line_invalid_op(rule_line, key);
25de7aa7 742 if (IN_SET(op, OP_ADD, OP_ASSIGN_FINAL)) {
c06ab041 743 log_line_warning(rule_line, "%s key takes '==', '!=', or '=' operator, assuming '='.", key);
25de7aa7
YW
744 op = OP_ASSIGN;
745 }
912541b0 746
d7aee41d 747 if (!is_match) {
c06ab041 748 check_value_format_and_warn(rule_line, key, value, false);
d7aee41d
YW
749 r = rule_line_add_token(rule_line, TK_A_ATTR, op, value, attr);
750 } else
751 r = rule_line_add_token(rule_line, TK_M_ATTR, op, value, attr);
25de7aa7 752 } else if (streq(key, "SYSCTL")) {
c06ab041 753 r = check_attr_format_and_warn(rule_line, key, attr);
7504610b
ZJS
754 if (r < 0)
755 return r;
25de7aa7 756 if (op == OP_REMOVE)
c06ab041 757 return log_line_invalid_op(rule_line, key);
25de7aa7 758 if (IN_SET(op, OP_ADD, OP_ASSIGN_FINAL)) {
c06ab041 759 log_line_warning(rule_line, "%s key takes '==', '!=', or '=' operator, assuming '='.", key);
25de7aa7
YW
760 op = OP_ASSIGN;
761 }
3b64e4d4 762
d7aee41d 763 if (!is_match) {
c06ab041 764 check_value_format_and_warn(rule_line, key, value, false);
d7aee41d
YW
765 r = rule_line_add_token(rule_line, TK_A_SYSCTL, op, value, attr);
766 } else
767 r = rule_line_add_token(rule_line, TK_M_SYSCTL, op, value, attr);
25de7aa7
YW
768 } else if (streq(key, "KERNELS")) {
769 if (attr)
c06ab041 770 return log_line_invalid_attr(rule_line, key);
25de7aa7 771 if (!is_match)
c06ab041 772 return log_line_invalid_op(rule_line, key);
25de7aa7
YW
773
774 r = rule_line_add_token(rule_line, TK_M_PARENTS_KERNEL, op, value, NULL);
775 } else if (streq(key, "SUBSYSTEMS")) {
776 if (attr)
c06ab041 777 return log_line_invalid_attr(rule_line, key);
25de7aa7 778 if (!is_match)
c06ab041 779 return log_line_invalid_op(rule_line, key);
25de7aa7
YW
780
781 r = rule_line_add_token(rule_line, TK_M_PARENTS_SUBSYSTEM, op, value, NULL);
782 } else if (streq(key, "DRIVERS")) {
783 if (attr)
c06ab041 784 return log_line_invalid_attr(rule_line, key);
25de7aa7 785 if (!is_match)
c06ab041 786 return log_line_invalid_op(rule_line, key);
25de7aa7
YW
787
788 r = rule_line_add_token(rule_line, TK_M_PARENTS_DRIVER, op, value, NULL);
789 } else if (streq(key, "ATTRS")) {
c06ab041 790 r = check_attr_format_and_warn(rule_line, key, attr);
7504610b
ZJS
791 if (r < 0)
792 return r;
25de7aa7 793 if (!is_match)
c06ab041 794 return log_line_invalid_op(rule_line, key);
25de7aa7
YW
795
796 if (startswith(attr, "device/"))
c06ab041 797 log_line_warning(rule_line, "'device' link may not be available in future kernels.");
25de7aa7 798 if (strstr(attr, "../"))
c06ab041 799 log_line_warning(rule_line, "Direct reference to parent sysfs directory, may break in future kernels.");
25de7aa7
YW
800
801 r = rule_line_add_token(rule_line, TK_M_PARENTS_ATTR, op, value, attr);
802 } else if (streq(key, "TAGS")) {
803 if (attr)
c06ab041 804 return log_line_invalid_attr(rule_line, key);
25de7aa7 805 if (!is_match)
c06ab041 806 return log_line_invalid_op(rule_line, key);
25de7aa7
YW
807
808 r = rule_line_add_token(rule_line, TK_M_PARENTS_TAG, op, value, NULL);
809 } else if (streq(key, "TEST")) {
810 mode_t mode = MODE_INVALID;
811
812 if (!isempty(attr)) {
813 r = parse_mode(attr, &mode);
814 if (r < 0)
c06ab041 815 return log_line_error_errno(rule_line, r, "Failed to parse mode '%s': %m", attr);
25de7aa7 816 }
c06ab041 817 check_value_format_and_warn(rule_line, key, value, true);
25de7aa7 818 if (!is_match)
c06ab041 819 return log_line_invalid_op(rule_line, key);
25de7aa7
YW
820
821 r = rule_line_add_token(rule_line, TK_M_TEST, op, value, MODE_TO_PTR(mode));
822 } else if (streq(key, "PROGRAM")) {
823 if (attr)
c06ab041
YW
824 return log_line_invalid_attr(rule_line, key);
825 check_value_format_and_warn(rule_line, key, value, true);
25de7aa7 826 if (op == OP_REMOVE)
c06ab041 827 return log_line_invalid_op(rule_line, key);
b6a80b83 828 if (!is_match)
25de7aa7 829 op = OP_MATCH;
912541b0 830
25de7aa7
YW
831 r = rule_line_add_token(rule_line, TK_M_PROGRAM, op, value, NULL);
832 } else if (streq(key, "IMPORT")) {
833 if (isempty(attr))
c06ab041
YW
834 return log_line_invalid_attr(rule_line, key);
835 check_value_format_and_warn(rule_line, key, value, true);
25de7aa7 836 if (op == OP_REMOVE)
c06ab041 837 return log_line_invalid_op(rule_line, key);
b6a80b83 838 if (!is_match)
25de7aa7 839 op = OP_MATCH;
e2ecb34f 840
25de7aa7
YW
841 if (streq(attr, "file"))
842 r = rule_line_add_token(rule_line, TK_M_IMPORT_FILE, op, value, NULL);
843 else if (streq(attr, "program")) {
844 UdevBuiltinCommand cmd;
f4850a1d 845
25de7aa7
YW
846 cmd = udev_builtin_lookup(value);
847 if (cmd >= 0) {
4134614f 848 log_line_debug(rule_line, "Found builtin command '%s' for %s, replacing attribute.", value, key);
25de7aa7
YW
849 r = rule_line_add_token(rule_line, TK_M_IMPORT_BUILTIN, op, value, UDEV_BUILTIN_CMD_TO_PTR(cmd));
850 } else
851 r = rule_line_add_token(rule_line, TK_M_IMPORT_PROGRAM, op, value, NULL);
852 } else if (streq(attr, "builtin")) {
853 UdevBuiltinCommand cmd;
854
855 cmd = udev_builtin_lookup(value);
856 if (cmd < 0)
c06ab041
YW
857 return log_line_error_errno(rule_line, SYNTHETIC_ERRNO(EINVAL),
858 "Unknown builtin command: %s", value);
25de7aa7
YW
859 r = rule_line_add_token(rule_line, TK_M_IMPORT_BUILTIN, op, value, UDEV_BUILTIN_CMD_TO_PTR(cmd));
860 } else if (streq(attr, "db"))
861 r = rule_line_add_token(rule_line, TK_M_IMPORT_DB, op, value, NULL);
862 else if (streq(attr, "cmdline"))
863 r = rule_line_add_token(rule_line, TK_M_IMPORT_CMDLINE, op, value, NULL);
864 else if (streq(attr, "parent"))
865 r = rule_line_add_token(rule_line, TK_M_IMPORT_PARENT, op, value, NULL);
866 else
c06ab041 867 return log_line_invalid_attr(rule_line, key);
25de7aa7
YW
868 } else if (streq(key, "RESULT")) {
869 if (attr)
c06ab041 870 return log_line_invalid_attr(rule_line, key);
25de7aa7 871 if (!is_match)
c06ab041 872 return log_line_invalid_op(rule_line, key);
25de7aa7
YW
873
874 r = rule_line_add_token(rule_line, TK_M_RESULT, op, value, NULL);
875 } else if (streq(key, "OPTIONS")) {
876 char *tmp;
877
878 if (attr)
c06ab041 879 return log_line_invalid_attr(rule_line, key);
25de7aa7 880 if (is_match || op == OP_REMOVE)
c06ab041 881 return log_line_invalid_op(rule_line, key);
ba60127d 882 if (op == OP_ADD)
25de7aa7 883 op = OP_ASSIGN;
f4850a1d 884
25de7aa7
YW
885 if (streq(value, "string_escape=none"))
886 r = rule_line_add_token(rule_line, TK_A_OPTIONS_STRING_ESCAPE_NONE, op, NULL, NULL);
887 else if (streq(value, "string_escape=replace"))
888 r = rule_line_add_token(rule_line, TK_A_OPTIONS_STRING_ESCAPE_REPLACE, op, NULL, NULL);
889 else if (streq(value, "db_persist"))
890 r = rule_line_add_token(rule_line, TK_A_OPTIONS_DB_PERSIST, op, NULL, NULL);
891 else if (streq(value, "watch"))
892 r = rule_line_add_token(rule_line, TK_A_OPTIONS_INOTIFY_WATCH, op, NULL, INT_TO_PTR(1));
893 else if (streq(value, "nowatch"))
894 r = rule_line_add_token(rule_line, TK_A_OPTIONS_INOTIFY_WATCH, op, NULL, INT_TO_PTR(0));
895 else if ((tmp = startswith(value, "static_node=")))
896 r = rule_line_add_token(rule_line, TK_A_OPTIONS_STATIC_NODE, op, tmp, NULL);
897 else if ((tmp = startswith(value, "link_priority="))) {
898 int prio;
899
900 r = safe_atoi(tmp, &prio);
901 if (r < 0)
c06ab041 902 return log_line_error_errno(rule_line, r, "Failed to parse link priority '%s': %m", tmp);
25de7aa7 903 r = rule_line_add_token(rule_line, TK_A_OPTIONS_DEVLINK_PRIORITY, op, NULL, INT_TO_PTR(prio));
1a0bd015
YW
904 } else if ((tmp = startswith(value, "log_level="))) {
905 int level;
906
907 if (streq(tmp, "reset"))
908 level = -1;
909 else {
910 level = log_level_from_string(tmp);
911 if (level < 0)
c06ab041 912 return log_line_error_errno(rule_line, level, "Failed to parse log level '%s': %m", tmp);
1a0bd015
YW
913 }
914 r = rule_line_add_token(rule_line, TK_A_OPTIONS_LOG_LEVEL, op, NULL, INT_TO_PTR(level));
25de7aa7 915 } else {
c06ab041 916 log_line_warning(rule_line, "Invalid value for OPTIONS key, ignoring: '%s'", value);
25de7aa7
YW
917 return 0;
918 }
919 } else if (streq(key, "OWNER")) {
920 uid_t uid;
f4850a1d 921
25de7aa7 922 if (attr)
c06ab041 923 return log_line_invalid_attr(rule_line, key);
25de7aa7 924 if (is_match || op == OP_REMOVE)
c06ab041 925 return log_line_invalid_op(rule_line, key);
25de7aa7 926 if (op == OP_ADD) {
c06ab041 927 log_line_warning(rule_line, "%s key takes '=' or ':=' operator, assuming '='.", key);
25de7aa7
YW
928 op = OP_ASSIGN;
929 }
f4850a1d 930
25de7aa7
YW
931 if (parse_uid(value, &uid) >= 0)
932 r = rule_line_add_token(rule_line, TK_A_OWNER_ID, op, NULL, UID_TO_PTR(uid));
c06ab041 933 else if (resolve_name_timing == RESOLVE_NAME_EARLY &&
25de7aa7 934 rule_get_substitution_type(value) == SUBST_TYPE_PLAIN) {
c06ab041 935 r = rule_resolve_user(rule_line, value, &uid);
25de7aa7 936 if (r < 0)
c06ab041 937 return log_line_error_errno(rule_line, r, "Failed to resolve user name '%s': %m", value);
25de7aa7
YW
938
939 r = rule_line_add_token(rule_line, TK_A_OWNER_ID, op, NULL, UID_TO_PTR(uid));
c06ab041
YW
940 } else if (resolve_name_timing != RESOLVE_NAME_NEVER) {
941 check_value_format_and_warn(rule_line, key, value, true);
25de7aa7 942 r = rule_line_add_token(rule_line, TK_A_OWNER, op, value, NULL);
d7aee41d 943 } else {
4134614f 944 log_line_debug(rule_line, "User name resolution is disabled, ignoring %s=\"%s\".", key, value);
25de7aa7
YW
945 return 0;
946 }
947 } else if (streq(key, "GROUP")) {
948 gid_t gid;
949
950 if (attr)
c06ab041 951 return log_line_invalid_attr(rule_line, key);
25de7aa7 952 if (is_match || op == OP_REMOVE)
c06ab041 953 return log_line_invalid_op(rule_line, key);
25de7aa7 954 if (op == OP_ADD) {
c06ab041 955 log_line_warning(rule_line, "%s key takes '=' or ':=' operator, assuming '='.", key);
25de7aa7
YW
956 op = OP_ASSIGN;
957 }
958
959 if (parse_gid(value, &gid) >= 0)
960 r = rule_line_add_token(rule_line, TK_A_GROUP_ID, op, NULL, GID_TO_PTR(gid));
c06ab041 961 else if (resolve_name_timing == RESOLVE_NAME_EARLY &&
25de7aa7 962 rule_get_substitution_type(value) == SUBST_TYPE_PLAIN) {
c06ab041 963 r = rule_resolve_group(rule_line, value, &gid);
25de7aa7 964 if (r < 0)
c06ab041 965 return log_line_error_errno(rule_line, r, "Failed to resolve group name '%s': %m", value);
25de7aa7
YW
966
967 r = rule_line_add_token(rule_line, TK_A_GROUP_ID, op, NULL, GID_TO_PTR(gid));
c06ab041
YW
968 } else if (resolve_name_timing != RESOLVE_NAME_NEVER) {
969 check_value_format_and_warn(rule_line, key, value, true);
25de7aa7 970 r = rule_line_add_token(rule_line, TK_A_GROUP, op, value, NULL);
d7aee41d 971 } else {
4134614f 972 log_line_debug(rule_line, "Resolving group name is disabled, ignoring GROUP=\"%s\".", value);
25de7aa7
YW
973 return 0;
974 }
975 } else if (streq(key, "MODE")) {
976 mode_t mode;
977
978 if (attr)
c06ab041 979 return log_line_invalid_attr(rule_line, key);
25de7aa7 980 if (is_match || op == OP_REMOVE)
c06ab041 981 return log_line_invalid_op(rule_line, key);
25de7aa7 982 if (op == OP_ADD) {
c06ab041 983 log_line_warning(rule_line, "%s key takes '=' or ':=' operator, assuming '='.", key);
25de7aa7
YW
984 op = OP_ASSIGN;
985 }
986
987 if (parse_mode(value, &mode) >= 0)
988 r = rule_line_add_token(rule_line, TK_A_MODE_ID, op, NULL, MODE_TO_PTR(mode));
d7aee41d 989 else {
c06ab041 990 check_value_format_and_warn(rule_line, key, value, true);
25de7aa7 991 r = rule_line_add_token(rule_line, TK_A_MODE, op, value, NULL);
d7aee41d 992 }
25de7aa7
YW
993 } else if (streq(key, "SECLABEL")) {
994 if (isempty(attr))
c06ab041
YW
995 return log_line_invalid_attr(rule_line, key);
996 check_value_format_and_warn(rule_line, key, value, true);
25de7aa7 997 if (is_match || op == OP_REMOVE)
c06ab041 998 return log_line_invalid_op(rule_line, key);
25de7aa7 999 if (op == OP_ASSIGN_FINAL) {
c06ab041 1000 log_line_warning(rule_line, "%s key takes '=' or '+=' operator, assuming '='.", key);
25de7aa7
YW
1001 op = OP_ASSIGN;
1002 }
1003
0335d110 1004 r = rule_line_add_token(rule_line, TK_A_SECLABEL, op, value, attr);
25de7aa7
YW
1005 } else if (streq(key, "RUN")) {
1006 if (is_match || op == OP_REMOVE)
c06ab041
YW
1007 return log_line_invalid_op(rule_line, key);
1008 check_value_format_and_warn(rule_line, key, value, true);
25de7aa7
YW
1009 if (!attr || streq(attr, "program"))
1010 r = rule_line_add_token(rule_line, TK_A_RUN_PROGRAM, op, value, NULL);
1011 else if (streq(attr, "builtin")) {
1012 UdevBuiltinCommand cmd;
1013
1014 cmd = udev_builtin_lookup(value);
1015 if (cmd < 0)
c06ab041 1016 return log_line_error_errno(rule_line, SYNTHETIC_ERRNO(EINVAL),
4134614f 1017 "Unknown builtin command '%s', ignoring.", value);
25de7aa7
YW
1018 r = rule_line_add_token(rule_line, TK_A_RUN_BUILTIN, op, value, UDEV_BUILTIN_CMD_TO_PTR(cmd));
1019 } else
c06ab041 1020 return log_line_invalid_attr(rule_line, key);
25de7aa7
YW
1021 } else if (streq(key, "GOTO")) {
1022 if (attr)
c06ab041 1023 return log_line_invalid_attr(rule_line, key);
25de7aa7 1024 if (op != OP_ASSIGN)
c06ab041 1025 return log_line_invalid_op(rule_line, key);
25de7aa7 1026 if (FLAGS_SET(rule_line->type, LINE_HAS_GOTO)) {
c06ab041 1027 log_line_warning(rule_line, "Contains multiple GOTO keys, ignoring GOTO=\"%s\".", value);
25de7aa7 1028 return 0;
912541b0 1029 }
25de7aa7
YW
1030
1031 rule_line->goto_label = value;
1032 SET_FLAG(rule_line->type, LINE_HAS_GOTO, true);
1033 return 1;
1034 } else if (streq(key, "LABEL")) {
1035 if (attr)
c06ab041 1036 return log_line_invalid_attr(rule_line, key);
25de7aa7 1037 if (op != OP_ASSIGN)
c06ab041 1038 return log_line_invalid_op(rule_line, key);
b2f7bb76 1039 if (FLAGS_SET(rule_line->type, LINE_HAS_LABEL))
c06ab041
YW
1040 log_line_warning(rule_line, "Contains multiple LABEL keys, ignoring LABEL=\"%s\".",
1041 rule_line->label);
25de7aa7
YW
1042
1043 rule_line->label = value;
1044 SET_FLAG(rule_line->type, LINE_HAS_LABEL, true);
1045 return 1;
1046 } else
4134614f 1047 return log_line_error_errno(rule_line, SYNTHETIC_ERRNO(EINVAL), "Invalid key '%s'.", key);
25de7aa7
YW
1048 if (r < 0)
1049 return log_oom();
1050
1051 return 1;
0ea5e96e
KS
1052}
1053
25de7aa7
YW
1054static UdevRuleOperatorType parse_operator(const char *op) {
1055 assert(op);
1056
1057 if (startswith(op, "=="))
1058 return OP_MATCH;
1059 if (startswith(op, "!="))
1060 return OP_NOMATCH;
1061 if (startswith(op, "+="))
1062 return OP_ADD;
1063 if (startswith(op, "-="))
1064 return OP_REMOVE;
1065 if (startswith(op, "="))
1066 return OP_ASSIGN;
1067 if (startswith(op, ":="))
1068 return OP_ASSIGN_FINAL;
1069
1070 return _OP_TYPE_INVALID;
1071}
912541b0 1072
acc1954a
DL
1073static void check_token_delimiters(UdevRuleLine *rule_line, const char *line) {
1074 assert(rule_line);
1075
1076 size_t n_comma = 0;
1077 bool ws_before_comma = false, ws_after_comma = false;
1078 const char *p;
1079
1080 for (p = line; !isempty(p); ++p) {
1081 if (*p == ',')
1082 ++n_comma;
1083 else if (strchr(WHITESPACE, *p)) {
1084 if (n_comma > 0)
1085 ws_after_comma = true;
1086 else
1087 ws_before_comma = true;
1088 } else
1089 break;
1090 }
1091
1092 if (line == rule_line->line) {
1093 /* this is the first token of the rule */
1094 if (n_comma > 0)
1bf3dd41 1095 log_line_notice(rule_line, "style: stray leading comma.");
acc1954a
DL
1096 } else if (isempty(p)) {
1097 /* there are no more tokens in the rule */
1098 if (n_comma > 0)
1bf3dd41 1099 log_line_notice(rule_line, "style: stray trailing comma.");
acc1954a
DL
1100 } else {
1101 /* single comma is expected */
1102 if (n_comma == 0)
1bf3dd41 1103 log_line_notice(rule_line, "style: a comma between tokens is expected.");
acc1954a 1104 else if (n_comma > 1)
1bf3dd41 1105 log_line_notice(rule_line, "style: more than one comma between tokens.");
acc1954a
DL
1106
1107 /* whitespace after comma is expected */
1108 if (n_comma > 0) {
1109 if (ws_before_comma)
1bf3dd41 1110 log_line_notice(rule_line, "style: stray whitespace before comma.");
acc1954a 1111 if (!ws_after_comma)
1bf3dd41 1112 log_line_notice(rule_line, "style: whitespace after comma is expected.");
acc1954a 1113 } else if (!ws_before_comma && !ws_after_comma)
1bf3dd41 1114 log_line_notice(rule_line, "style: whitespace between tokens is expected.");
acc1954a
DL
1115 }
1116}
1117
25de7aa7 1118static int parse_line(char **line, char **ret_key, char **ret_attr, UdevRuleOperatorType *ret_op, char **ret_value) {
aea3253e 1119 char *key_begin, *key_end, *attr, *tmp;
25de7aa7 1120 UdevRuleOperatorType op;
aea3253e 1121 int r;
912541b0 1122
25de7aa7
YW
1123 assert(line);
1124 assert(*line);
1125 assert(ret_key);
1126 assert(ret_op);
1127 assert(ret_value);
912541b0 1128
25de7aa7 1129 key_begin = skip_leading_chars(*line, WHITESPACE ",");
912541b0 1130
25de7aa7
YW
1131 if (isempty(key_begin))
1132 return 0;
1133
1134 for (key_end = key_begin; ; key_end++) {
1135 if (key_end[0] == '\0')
704dbfb2 1136 return -EINVAL;
25de7aa7 1137 if (strchr(WHITESPACE "={", key_end[0]))
912541b0 1138 break;
25de7aa7 1139 if (strchr("+-!:", key_end[0]) && key_end[1] == '=')
912541b0 1140 break;
25de7aa7
YW
1141 }
1142 if (key_end[0] == '{') {
1143 attr = key_end + 1;
1144 tmp = strchr(attr, '}');
1145 if (!tmp)
1146 return -EINVAL;
1147 *tmp++ = '\0';
1148 } else {
1149 attr = NULL;
1150 tmp = key_end;
912541b0
KS
1151 }
1152
25de7aa7
YW
1153 tmp = skip_leading_chars(tmp, NULL);
1154 op = parse_operator(tmp);
1155 if (op < 0)
704dbfb2 1156 return -EINVAL;
912541b0 1157
25de7aa7 1158 key_end[0] = '\0';
912541b0 1159
25de7aa7 1160 tmp += op == OP_ASSIGN ? 1 : 2;
aea3253e
YLY
1161 tmp = skip_leading_chars(tmp, NULL);
1162 r = udev_rule_parse_value(tmp, ret_value, line);
1163 if (r < 0)
1164 return r;
25de7aa7 1165
25de7aa7
YW
1166 *ret_key = key_begin;
1167 *ret_attr = attr;
1168 *ret_op = op;
25de7aa7
YW
1169 return 1;
1170}
7e760b79 1171
56df2f6f
DL
1172static void check_tokens_order(UdevRuleLine *rule_line) {
1173 bool has_result = false;
1174
1175 assert(rule_line);
1176
1177 LIST_FOREACH(tokens, t, rule_line->tokens)
1178 if (t->type == TK_M_RESULT)
1179 has_result = true;
1180 else if (has_result && t->type == TK_M_PROGRAM) {
1181 log_line_warning(rule_line, "Reordering RESULT check after PROGRAM assignment.");
1182 break;
1183 }
1184}
1185
25de7aa7 1186static void sort_tokens(UdevRuleLine *rule_line) {
25de7aa7 1187 assert(rule_line);
912541b0 1188
d5fe7f7f 1189 UdevRuleToken *old_tokens = TAKE_PTR(rule_line->tokens);
95776dc6 1190
d5fe7f7f 1191 while (old_tokens) {
03677889 1192 UdevRuleToken *min_token = NULL;
25de7aa7 1193
d5fe7f7f 1194 LIST_FOREACH(tokens, t, old_tokens)
25de7aa7
YW
1195 if (!min_token || min_token->type > t->type)
1196 min_token = t;
1197
d5fe7f7f 1198 LIST_REMOVE(tokens, old_tokens, min_token);
e7f5d708 1199 LIST_APPEND(tokens, rule_line->tokens, min_token);
912541b0 1200 }
6880b25d 1201}
95776dc6 1202
acc1954a 1203static int rule_add_line(UdevRuleFile *rule_file, const char *line_str, unsigned line_nr, bool extra_checks) {
25de7aa7
YW
1204 _cleanup_(udev_rule_line_freep) UdevRuleLine *rule_line = NULL;
1205 _cleanup_free_ char *line = NULL;
25de7aa7
YW
1206 char *p;
1207 int r;
912541b0 1208
c06ab041 1209 assert(rule_file);
25de7aa7 1210 assert(line_str);
6e2efb6c 1211
25de7aa7
YW
1212 if (isempty(line_str))
1213 return 0;
912541b0 1214
8c499a61 1215 line = strdup(line_str);
25de7aa7
YW
1216 if (!line)
1217 return log_oom();
67e4b385 1218
25de7aa7
YW
1219 rule_line = new(UdevRuleLine, 1);
1220 if (!rule_line)
1221 return log_oom();
912541b0 1222
25de7aa7
YW
1223 *rule_line = (UdevRuleLine) {
1224 .line = TAKE_PTR(line),
1225 .line_number = line_nr,
1226 .rule_file = rule_file,
1227 };
912541b0 1228
c06ab041 1229 LIST_APPEND(rule_lines, rule_file->rule_lines, rule_line);
912541b0 1230
25de7aa7
YW
1231 for (p = rule_line->line; !isempty(p); ) {
1232 char *key, *attr, *value;
1233 UdevRuleOperatorType op;
912541b0 1234
acc1954a
DL
1235 if (extra_checks)
1236 check_token_delimiters(rule_line, p);
1237
25de7aa7
YW
1238 r = parse_line(&p, &key, &attr, &op, &value);
1239 if (r < 0)
c06ab041 1240 return log_line_error_errno(rule_line, r, "Invalid key/value pair, ignoring.");
25de7aa7
YW
1241 if (r == 0)
1242 break;
912541b0 1243
c06ab041 1244 r = parse_token(rule_line, key, attr, op, value);
ef660d07
YW
1245 if (r < 0)
1246 return r;
25de7aa7 1247 }
912541b0 1248
25de7aa7 1249 if (rule_line->type == 0) {
ebb00082 1250 log_line_warning(rule_line, "The line has no effect, ignoring.");
25de7aa7 1251 return 0;
912541b0 1252 }
25de7aa7 1253
56df2f6f
DL
1254 if (extra_checks)
1255 check_tokens_order(rule_line);
1256
25de7aa7
YW
1257 sort_tokens(rule_line);
1258 TAKE_PTR(rule_line);
912541b0 1259 return 0;
724257d9
GKH
1260}
1261
25de7aa7 1262static void rule_resolve_goto(UdevRuleFile *rule_file) {
25de7aa7 1263 assert(rule_file);
912541b0 1264
25de7aa7 1265 /* link GOTOs to LABEL rules in this file to be able to fast-forward */
80a226b2 1266 LIST_FOREACH(rule_lines, line, rule_file->rule_lines) {
25de7aa7
YW
1267 if (!FLAGS_SET(line->type, LINE_HAS_GOTO))
1268 continue;
912541b0 1269
bd335c96 1270 LIST_FOREACH(rule_lines, i, line->rule_lines_next)
25de7aa7
YW
1271 if (streq_ptr(i->label, line->goto_label)) {
1272 line->goto_line = i;
7a771d1d 1273 SET_FLAG(i->type, LINE_IS_REFERENCED, true);
25de7aa7 1274 break;
912541b0
KS
1275 }
1276
25de7aa7 1277 if (!line->goto_line) {
4134614f 1278 log_line_error(line, "GOTO=\"%s\" has no matching label, ignoring.",
4f5de157 1279 line->goto_label);
912541b0 1280
25de7aa7
YW
1281 SET_FLAG(line->type, LINE_HAS_GOTO, false);
1282 line->goto_label = NULL;
912541b0 1283
7a771d1d 1284 if ((line->type & ~(LINE_HAS_LABEL|LINE_IS_REFERENCED)) == 0) {
1bf3dd41 1285 log_line_warning(line, "The line has no effect any more, dropping.");
7a771d1d
DL
1286 /* LINE_IS_REFERENCED implies LINE_HAS_LABEL */
1287 if (line->type & LINE_HAS_LABEL)
25de7aa7
YW
1288 udev_rule_line_clear_tokens(line);
1289 else
1290 udev_rule_line_free(line);
912541b0 1291 }
25de7aa7 1292 }
912541b0 1293 }
c7521974
KS
1294}
1295
3ec58d0c
DL
1296static bool token_data_is_string(UdevRuleTokenType type) {
1297 return IN_SET(type, TK_M_ENV,
1298 TK_M_CONST,
1299 TK_M_ATTR,
1300 TK_M_SYSCTL,
1301 TK_M_PARENTS_ATTR,
1302 TK_A_SECLABEL,
1303 TK_A_ENV,
1304 TK_A_ATTR,
1305 TK_A_SYSCTL);
1306}
1307
1308static bool token_type_and_data_eq(const UdevRuleToken *a, const UdevRuleToken *b) {
1309 assert(a);
1310 assert(b);
1311
1312 return a->type == b->type &&
1313 (token_data_is_string(a->type) ? streq_ptr(a->data, b->data) : (a->data == b->data));
1314}
1315
5004aa84
DL
1316static bool nulstr_eq(const char *a, const char *b) {
1317 NULSTR_FOREACH(i, a)
1318 if (!nulstr_contains(b, i))
1319 return false;
1320
1321 NULSTR_FOREACH(i, b)
1322 if (!nulstr_contains(a, i))
1323 return false;
1324
1325 return true;
1326}
1327
1328static bool token_type_and_value_eq(const UdevRuleToken *a, const UdevRuleToken *b) {
3ec58d0c
DL
1329 assert(a);
1330 assert(b);
1331
5004aa84
DL
1332 if (a->type != b->type ||
1333 a->match_type != b->match_type)
3ec58d0c
DL
1334 return false;
1335
1336 /* token value is ignored for certain match types */
1337 if (IN_SET(a->match_type, MATCH_TYPE_EMPTY, MATCH_TYPE_SUBSYSTEM))
1338 return true;
1339
5004aa84
DL
1340 return type_has_nulstr_value(a->type) ? nulstr_eq(a->value, b->value) :
1341 streq_ptr(a->value, b->value);
3ec58d0c
DL
1342}
1343
1344static bool conflicting_op(UdevRuleOperatorType a, UdevRuleOperatorType b) {
1345 return (a == OP_MATCH && b == OP_NOMATCH) ||
1346 (a == OP_NOMATCH && b == OP_MATCH);
1347}
1348
1349/* test whether all fields besides UdevRuleOperatorType of two tokens match */
1350static bool tokens_eq(const UdevRuleToken *a, const UdevRuleToken *b) {
1351 assert(a);
1352 assert(b);
1353
1354 return a->attr_subst_type == b->attr_subst_type &&
1355 a->attr_match_remove_trailing_whitespace == b->attr_match_remove_trailing_whitespace &&
5004aa84 1356 token_type_and_value_eq(a, b) &&
3ec58d0c
DL
1357 token_type_and_data_eq(a, b);
1358}
1359
f0a16c9a
DL
1360static bool nulstr_tokens_conflict(const UdevRuleToken *a, const UdevRuleToken *b) {
1361 assert(a);
1362 assert(b);
1363
1364 if (!(a->type == b->type &&
1365 type_has_nulstr_value(a->type) &&
1366 a->op == b->op &&
1367 a->op == OP_MATCH &&
1368 a->match_type == b->match_type &&
f0a16c9a
DL
1369 a->attr_subst_type == b->attr_subst_type &&
1370 a->attr_match_remove_trailing_whitespace == b->attr_match_remove_trailing_whitespace &&
1371 token_type_and_data_eq(a, b)))
1372 return false;
1373
860e2a11
DL
1374 if (a->match_type == MATCH_TYPE_PLAIN) {
1375 NULSTR_FOREACH(i, a->value)
1376 if (nulstr_contains(b->value, i))
1377 return false;
1378 return true;
1379 }
f0a16c9a 1380
860e2a11
DL
1381 if (a->match_type == MATCH_TYPE_GLOB) {
1382 NULSTR_FOREACH(i, a->value) {
1383 size_t i_n = strcspn(i, GLOB_CHARS);
1384 if (i_n == 0)
1385 return false;
1386 NULSTR_FOREACH(j, b->value) {
1387 size_t j_n = strcspn(j, GLOB_CHARS);
1388 if (j_n == 0 || strneq(i, j, MIN(i_n, j_n)))
1389 return false;
1390 }
1391
1392 }
1393 return true;
1394 }
1395
1396 return false;
f0a16c9a
DL
1397}
1398
3ec58d0c 1399static void udev_check_unused_labels(UdevRuleLine *line) {
c06ab041
YW
1400 assert(line);
1401
7a771d1d
DL
1402 if (FLAGS_SET(line->type, LINE_HAS_LABEL) &&
1403 !FLAGS_SET(line->type, LINE_IS_REFERENCED))
1bf3dd41 1404 log_line_notice(line, "style: LABEL=\"%s\" is unused.", line->label);
7a771d1d
DL
1405}
1406
3ec58d0c
DL
1407static void udev_check_conflicts_duplicates(UdevRuleLine *line) {
1408 assert(line);
1409
1410 bool conflicts = false, duplicates = false;
1411
1412 LIST_FOREACH(tokens, token, line->tokens)
1413 LIST_FOREACH(tokens, i, token->tokens_next) {
f0a16c9a
DL
1414 bool new_conflicts = false, new_duplicates = false;
1415
1416 if (tokens_eq(token, i)) {
1417 if (!duplicates && token->op == i->op)
1418 new_duplicates = true;
1419 if (!conflicts && conflicting_op(token->op, i->op))
1420 new_conflicts = true;
1421 } else if (!conflicts && nulstr_tokens_conflict(token, i))
1422 new_conflicts = true;
1423 else
3ec58d0c 1424 continue;
f0a16c9a
DL
1425
1426 if (new_duplicates) {
1427 duplicates = new_duplicates;
4134614f 1428 log_line_warning(line, "duplicate expressions.");
3ec58d0c 1429 }
f0a16c9a
DL
1430 if (new_conflicts) {
1431 conflicts = new_conflicts;
4134614f 1432 log_line_error(line, "conflicting match expressions, the line has no effect.");
3ec58d0c
DL
1433 }
1434 if (conflicts && duplicates)
1435 return;
1436 }
1437}
1438
1439static void udev_check_rule_line(UdevRuleLine *line) {
1440 udev_check_unused_labels(line);
1441 udev_check_conflicts_duplicates(line);
1442}
1443
9b419eb0 1444int udev_rules_parse_file(UdevRules *rules, const char *filename, bool extra_checks, UdevRuleFile **ret) {
3b948231
DL
1445 _cleanup_(udev_rule_file_freep) UdevRuleFile *rule_file = NULL;
1446 _cleanup_free_ char *continuation = NULL, *name = NULL;
1447 _cleanup_fclose_ FILE *f = NULL;
1448 bool ignore_line = false;
1449 unsigned line_nr = 0;
1450 struct stat st;
1451 int r;
1452
1453 assert(rules);
1454 assert(filename);
1455
1456 f = fopen(filename, "re");
9db7081d 1457 if (!f) {
f3664340
DL
1458 if (extra_checks)
1459 return -errno;
1460
1461 if (errno == ENOENT)
9db7081d
ZJS
1462 return 0;
1463
3b948231 1464 return log_warning_errno(errno, "Failed to open %s, ignoring: %m", filename);
9db7081d 1465 }
3b948231
DL
1466
1467 if (fstat(fileno(f), &st) < 0)
1468 return log_warning_errno(errno, "Failed to stat %s, ignoring: %m", filename);
1469
1470 if (null_or_empty(&st)) {
1471 log_debug("Skipping empty file: %s", filename);
1472 if (ret)
1473 *ret = NULL;
1474 return 0;
1475 }
1476
1477 r = hashmap_put_stats_by_path(&rules->stats_by_path, filename, &st);
1478 if (r < 0)
1479 return log_warning_errno(errno, "Failed to save stat for %s, ignoring: %m", filename);
1480
1481 (void) fd_warn_permissions(filename, fileno(f));
1482
1483 log_debug("Reading rules file: %s", filename);
1484
1485 name = strdup(filename);
1486 if (!name)
1487 return log_oom();
1488
1489 rule_file = new(UdevRuleFile, 1);
1490 if (!rule_file)
1491 return log_oom();
1492
1493 *rule_file = (UdevRuleFile) {
1494 .filename = TAKE_PTR(name),
1495 .rules = rules,
1496 };
1497
1498 LIST_APPEND(rule_files, rules->rule_files, rule_file);
1499
1500 for (;;) {
1501 _cleanup_free_ char *buf = NULL;
1502 size_t len;
1503 char *line;
1504
1505 r = read_line(f, UDEV_LINE_SIZE, &buf);
1506 if (r < 0)
1507 return r;
1508 if (r == 0)
1509 break;
1510
1511 line_nr++;
1512 line = skip_leading_chars(buf, NULL);
1513
1514 /* Lines beginning with '#' are ignored regardless of line continuation. */
1515 if (line[0] == '#')
1516 continue;
1517
1518 len = strlen(line);
1519
1520 if (continuation && !ignore_line) {
1521 if (strlen(continuation) + len >= UDEV_LINE_SIZE)
1522 ignore_line = true;
1523
1524 if (!strextend(&continuation, line))
1525 return log_oom();
1526
1527 if (!ignore_line) {
1528 line = continuation;
1529 len = strlen(line);
1530 }
1531 }
1532
1533 if (len > 0 && line[len - 1] == '\\') {
1534 if (ignore_line)
1535 continue;
1536
1537 line[len - 1] = '\0';
1538 if (!continuation) {
1539 continuation = strdup(line);
1540 if (!continuation)
1541 return log_oom();
1542 }
1543
1544 continue;
1545 }
1546
1547 if (ignore_line)
4134614f 1548 log_file_error(rule_file, line_nr, "Line is too long, ignored.");
3b948231 1549 else if (len > 0)
acc1954a 1550 (void) rule_add_line(rule_file, line, line_nr, extra_checks);
3b948231
DL
1551
1552 continuation = mfree(continuation);
1553 ignore_line = false;
1554 }
1555
1556 if (continuation)
1557 log_file_error(rule_file, line_nr,
4134614f 1558 "Unexpected EOF after line continuation, line ignored.");
3b948231
DL
1559
1560 rule_resolve_goto(rule_file);
1561
9b419eb0
DL
1562 if (extra_checks)
1563 LIST_FOREACH(rule_lines, line, rule_file->rule_lines)
1564 udev_check_rule_line(line);
1565
3b948231
DL
1566 if (ret)
1567 *ret = rule_file;
1568
1569 TAKE_PTR(rule_file);
1570 return 1;
1571}
1572
c06ab041
YW
1573unsigned udev_rule_file_get_issues(UdevRuleFile *rule_file) {
1574 assert(rule_file);
acdba85e
DL
1575
1576 return rule_file->issues;
1577}
1578
c238a1f5 1579UdevRules* udev_rules_new(ResolveNameTiming resolve_name_timing) {
c4d44cba
YW
1580 assert(resolve_name_timing >= 0 && resolve_name_timing < _RESOLVE_NAME_TIMING_MAX);
1581
c238a1f5 1582 UdevRules *rules = new(UdevRules, 1);
1017d66b 1583 if (!rules)
c238a1f5 1584 return NULL;
1017d66b 1585
9a07157d 1586 *rules = (UdevRules) {
c4d44cba 1587 .resolve_name_timing = resolve_name_timing,
1017d66b 1588 };
912541b0 1589
c238a1f5
ZJS
1590 return rules;
1591}
1592
1593int udev_rules_load(UdevRules **ret_rules, ResolveNameTiming resolve_name_timing) {
1594 _cleanup_(udev_rules_freep) UdevRules *rules = NULL;
1595 _cleanup_strv_free_ char **files = NULL;
c238a1f5
ZJS
1596 int r;
1597
1598 rules = udev_rules_new(resolve_name_timing);
1599 if (!rules)
1600 return -ENOMEM;
1601
116b91e8 1602 r = conf_files_list_strv(&files, ".rules", NULL, 0, RULES_DIRS);
1d791281 1603 if (r < 0)
c238a1f5 1604 return log_debug_errno(r, "Failed to enumerate rules files: %m");
912541b0 1605
f23810da 1606 STRV_FOREACH(f, files) {
9b419eb0 1607 r = udev_rules_parse_file(rules, *f, /* extra_checks = */ false, NULL);
f23810da
ZJS
1608 if (r < 0)
1609 log_debug_errno(r, "Failed to read rules file %s, ignoring: %m", *f);
1610 }
912541b0 1611
1d791281
ZJS
1612 *ret_rules = TAKE_PTR(rules);
1613 return 0;
c7521974
KS
1614}
1615
acfbd71c
YW
1616bool udev_rules_should_reload(UdevRules *rules) {
1617 _cleanup_hashmap_free_ Hashmap *stats_by_path = NULL;
1618 int r;
1619
5c11fbe3 1620 if (!rules)
acfbd71c
YW
1621 return true;
1622
1623 r = config_get_stats_by_path(".rules", NULL, 0, RULES_DIRS, /* check_dropins = */ false, &stats_by_path);
1624 if (r < 0) {
1625 log_warning_errno(r, "Failed to get stats of udev rules, ignoring: %m");
1626 return true;
1627 }
1628
1629 if (!stats_by_path_equal(rules->stats_by_path, stats_by_path)) {
1630 log_debug("Udev rules need reloading");
1631 return true;
1632 }
5c11fbe3 1633
acfbd71c 1634 return false;
6ada823a
KS
1635}
1636
25de7aa7 1637static bool token_match_string(UdevRuleToken *token, const char *str) {
12e2b70f 1638 const char *value;
912541b0
KS
1639 bool match = false;
1640
25de7aa7
YW
1641 assert(token);
1642 assert(token->value);
1643 assert(token->type < _TK_M_MAX);
912541b0 1644
25de7aa7
YW
1645 str = strempty(str);
1646 value = token->value;
1647
1648 switch (token->match_type) {
1649 case MATCH_TYPE_EMPTY:
1650 match = isempty(str);
912541b0 1651 break;
25de7aa7 1652 case MATCH_TYPE_SUBSYSTEM:
9663ed37 1653 match = STR_IN_SET(str, "subsystem", "class", "bus");
067cc51f
YW
1654 break;
1655 case MATCH_TYPE_PLAIN_WITH_EMPTY:
1656 if (isempty(str)) {
1657 match = true;
1658 break;
1659 }
25de7aa7
YW
1660 _fallthrough_;
1661 case MATCH_TYPE_PLAIN:
1662 NULSTR_FOREACH(i, value)
1663 if (streq(i, str)) {
1664 match = true;
1665 break;
912541b0 1666 }
25de7aa7 1667 break;
067cc51f
YW
1668 case MATCH_TYPE_GLOB_WITH_EMPTY:
1669 if (isempty(str)) {
1670 match = true;
1671 break;
1672 }
1673 _fallthrough_;
25de7aa7
YW
1674 case MATCH_TYPE_GLOB:
1675 NULSTR_FOREACH(i, value)
1676 if ((fnmatch(i, str, 0) == 0)) {
1677 match = true;
1678 break;
912541b0 1679 }
912541b0 1680 break;
25de7aa7 1681 default:
04499a70 1682 assert_not_reached();
912541b0
KS
1683 }
1684
25de7aa7 1685 return token->op == (match ? OP_MATCH : OP_NOMATCH);
6880b25d
KS
1686}
1687
c06ab041 1688static bool token_match_attr(UdevRuleToken *token, sd_device *dev, UdevEvent *event) {
c8eaaf69 1689 char nbuf[UDEV_NAME_SIZE], vbuf[UDEV_NAME_SIZE];
5ba7e798 1690 const char *name, *value;
f6caab89 1691 bool truncated;
912541b0 1692
25de7aa7 1693 assert(token);
f6caab89 1694 assert(IN_SET(token->type, TK_M_ATTR, TK_M_PARENTS_ATTR));
25de7aa7
YW
1695 assert(dev);
1696 assert(event);
1697
af2e52f4 1698 name = token->data;
25de7aa7
YW
1699
1700 switch (token->attr_subst_type) {
1701 case SUBST_TYPE_FORMAT:
f6caab89
YW
1702 (void) udev_event_apply_format(event, name, nbuf, sizeof(nbuf), false, &truncated);
1703 if (truncated) {
e5a34948
YW
1704 log_event_truncated(dev, token, "sysfs attribute name", name,
1705 token->type == TK_M_ATTR ? "ATTR" : "ATTRS", /* is_match = */ true);
f6caab89
YW
1706 return false;
1707 }
1708
912541b0 1709 name = nbuf;
4831981d 1710 _fallthrough_;
25de7aa7 1711 case SUBST_TYPE_PLAIN:
5bbcfbaa 1712 if (sd_device_get_sysattr_value(dev, name, &value) < 0)
605aa52f 1713 return false;
912541b0 1714 break;
25de7aa7 1715 case SUBST_TYPE_SUBSYS:
1223227f 1716 if (udev_resolve_subsys_kernel(name, vbuf, sizeof(vbuf), true) < 0)
605aa52f 1717 return false;
912541b0
KS
1718 value = vbuf;
1719 break;
1720 default:
04499a70 1721 assert_not_reached();
912541b0
KS
1722 }
1723
1724 /* remove trailing whitespace, if not asked to match for it */
25de7aa7
YW
1725 if (token->attr_match_remove_trailing_whitespace) {
1726 if (value != vbuf) {
1727 strscpy(vbuf, sizeof(vbuf), value);
1728 value = vbuf;
912541b0 1729 }
25de7aa7
YW
1730
1731 delete_trailing_chars(vbuf, NULL);
912541b0
KS
1732 }
1733
25de7aa7 1734 return token_match_string(token, value);
6880b25d
KS
1735}
1736
25de7aa7
YW
1737static int get_property_from_string(char *line, char **ret_key, char **ret_value) {
1738 char *key, *val;
1739 size_t len;
6880b25d 1740
25de7aa7
YW
1741 assert(line);
1742 assert(ret_key);
1743 assert(ret_value);
1744
1745 /* find key */
1746 key = skip_leading_chars(line, NULL);
912541b0 1747
25de7aa7 1748 /* comment or empty line */
41c81c4a
YW
1749 if (IN_SET(key[0], '#', '\0')) {
1750 *ret_key = *ret_value = NULL;
d838e145 1751 return 0;
41c81c4a 1752 }
912541b0 1753
25de7aa7
YW
1754 /* split key/value */
1755 val = strchr(key, '=');
1756 if (!val)
1757 return -EINVAL;
1758 *val++ = '\0';
cf697ec0 1759
25de7aa7
YW
1760 key = strstrip(key);
1761 if (isempty(key))
1762 return -EINVAL;
912541b0 1763
25de7aa7
YW
1764 val = strstrip(val);
1765 if (isempty(val))
1766 return -EINVAL;
912541b0 1767
25de7aa7
YW
1768 /* unquote */
1769 if (IN_SET(val[0], '"', '\'')) {
1770 len = strlen(val);
1771 if (len == 1 || val[len-1] != val[0])
1772 return -EINVAL;
1773 val[len-1] = '\0';
1774 val++;
1775 }
adeba500 1776
25de7aa7
YW
1777 *ret_key = key;
1778 *ret_value = val;
41c81c4a 1779 return 1;
25de7aa7 1780}
f4cf2e5b 1781
25de7aa7 1782static int import_parent_into_properties(sd_device *dev, const char *filter) {
25de7aa7
YW
1783 sd_device *parent;
1784 int r;
f4cf2e5b 1785
25de7aa7
YW
1786 assert(dev);
1787 assert(filter);
912541b0 1788
25de7aa7
YW
1789 r = sd_device_get_parent(dev, &parent);
1790 if (r == -ENOENT)
1791 return 0;
1792 if (r < 0)
1793 return r;
1794
1795 FOREACH_DEVICE_PROPERTY(parent, key, val) {
1796 if (fnmatch(filter, key, 0) != 0)
912541b0 1797 continue;
25de7aa7
YW
1798 r = device_add_property(dev, key, val);
1799 if (r < 0)
1800 return r;
1801 }
912541b0 1802
25de7aa7
YW
1803 return 1;
1804}
912541b0 1805
c8eaaf69 1806static int attr_subst_subdir(char attr[static UDEV_PATH_SIZE]) {
25de7aa7 1807 _cleanup_closedir_ DIR *dir = NULL;
c8eaaf69 1808 char buf[UDEV_PATH_SIZE], *p;
25de7aa7
YW
1809 const char *tail;
1810 size_t len, size;
f6caab89 1811 bool truncated;
912541b0 1812
2caa38e9
LP
1813 assert(attr);
1814
25de7aa7
YW
1815 tail = strstr(attr, "/*/");
1816 if (!tail)
f6caab89 1817 return 0;
912541b0 1818
25de7aa7
YW
1819 len = tail - attr + 1; /* include slash at the end */
1820 tail += 2; /* include slash at the beginning */
88b013b2 1821
25de7aa7
YW
1822 p = buf;
1823 size = sizeof(buf);
f6caab89
YW
1824 size -= strnpcpy_full(&p, size, attr, len, &truncated);
1825 if (truncated)
1826 return -ENOENT;
88b013b2 1827
25de7aa7
YW
1828 dir = opendir(buf);
1829 if (!dir)
1830 return -errno;
912541b0 1831
c7f0d9e5
ZJS
1832 FOREACH_DIRENT_ALL(de, dir, break) {
1833 if (de->d_name[0] == '.')
25de7aa7
YW
1834 continue;
1835
f6caab89
YW
1836 strscpyl_full(p, size, &truncated, de->d_name, tail, NULL);
1837 if (truncated)
1838 continue;
1839
25de7aa7
YW
1840 if (faccessat(dirfd(dir), p, F_OK, 0) < 0)
1841 continue;
1842
1843 strcpy(attr, buf);
1844 return 0;
1845 }
1846
1847 return -ENOENT;
1848}
1849
1850static int udev_rule_apply_token_to_event(
c06ab041 1851 UdevRuleToken *token,
25de7aa7
YW
1852 sd_device *dev,
1853 UdevEvent *event,
1854 usec_t timeout_usec,
e2099267 1855 int timeout_signal,
25de7aa7
YW
1856 Hashmap *properties_list) {
1857
25de7aa7
YW
1858 int r;
1859
c06ab041 1860 assert(token);
25de7aa7
YW
1861 assert(dev);
1862 assert(event);
1863
1864 /* This returns the following values:
1865 * 0 on the current token does not match the event,
1866 * 1 on the current token matches the event, and
1867 * negative errno on some critical errors. */
1868
25de7aa7
YW
1869 switch (token->type) {
1870 case TK_M_ACTION: {
a1130022 1871 sd_device_action_t a;
25de7aa7 1872
a1130022 1873 r = sd_device_get_action(dev, &a);
25de7aa7 1874 if (r < 0)
c06ab041 1875 return log_event_error_errno(dev, token, r, "Failed to get uevent action type: %m");
25de7aa7
YW
1876
1877 return token_match_string(token, device_action_to_string(a));
1878 }
7dc846f9
YW
1879 case TK_M_DEVPATH: {
1880 const char *val;
1881
25de7aa7
YW
1882 r = sd_device_get_devpath(dev, &val);
1883 if (r < 0)
c06ab041 1884 return log_event_error_errno(dev, token, r, "Failed to get devpath: %m");
25de7aa7
YW
1885
1886 return token_match_string(token, val);
7dc846f9 1887 }
25de7aa7 1888 case TK_M_KERNEL:
7dc846f9
YW
1889 case TK_M_PARENTS_KERNEL: {
1890 const char *val;
1891
25de7aa7
YW
1892 r = sd_device_get_sysname(dev, &val);
1893 if (r < 0)
c06ab041 1894 return log_event_error_errno(dev, token, r, "Failed to get sysname: %m");
25de7aa7
YW
1895
1896 return token_match_string(token, val);
7dc846f9 1897 }
a1af8372 1898 case TK_M_DEVLINK:
25de7aa7 1899 FOREACH_DEVICE_DEVLINK(dev, val)
2b43ab00 1900 if (token_match_string(token, strempty(startswith(val, "/dev/"))) == (token->op == OP_MATCH))
25de7aa7
YW
1901 return token->op == OP_MATCH;
1902 return token->op == OP_NOMATCH;
1903 case TK_M_NAME:
1904 return token_match_string(token, event->name);
7dc846f9
YW
1905 case TK_M_ENV: {
1906 const char *val;
1907
af2e52f4 1908 if (sd_device_get_property_value(dev, token->data, &val) < 0)
25de7aa7
YW
1909 val = hashmap_get(properties_list, token->data);
1910
1911 return token_match_string(token, val);
7dc846f9 1912 }
4801d8af 1913 case TK_M_CONST: {
7dc846f9 1914 const char *val, *k = token->data;
4801d8af
JS
1915
1916 if (streq(k, "arch"))
1917 val = architecture_to_string(uname_architecture());
1918 else if (streq(k, "virt"))
1919 val = virtualization_to_string(detect_virtualization());
6e2e83b4
DB
1920 else if (streq(k, "cvm"))
1921 val = confidential_virtualization_to_string(detect_confidential_virtualization());
4801d8af 1922 else
04499a70 1923 assert_not_reached();
4801d8af
JS
1924 return token_match_string(token, val);
1925 }
25de7aa7 1926 case TK_M_TAG:
a1af8372 1927 case TK_M_PARENTS_TAG:
31024990 1928 FOREACH_DEVICE_CURRENT_TAG(dev, val)
2b43ab00 1929 if (token_match_string(token, val) == (token->op == OP_MATCH))
25de7aa7
YW
1930 return token->op == OP_MATCH;
1931 return token->op == OP_NOMATCH;
1932 case TK_M_SUBSYSTEM:
7dc846f9
YW
1933 case TK_M_PARENTS_SUBSYSTEM: {
1934 const char *val;
1935
25de7aa7
YW
1936 r = sd_device_get_subsystem(dev, &val);
1937 if (r == -ENOENT)
1938 val = NULL;
1939 else if (r < 0)
c06ab041 1940 return log_event_error_errno(dev, token, r, "Failed to get subsystem: %m");
25de7aa7
YW
1941
1942 return token_match_string(token, val);
7dc846f9 1943 }
25de7aa7 1944 case TK_M_DRIVER:
7dc846f9
YW
1945 case TK_M_PARENTS_DRIVER: {
1946 const char *val;
1947
25de7aa7
YW
1948 r = sd_device_get_driver(dev, &val);
1949 if (r == -ENOENT)
1950 val = NULL;
1951 else if (r < 0)
c06ab041 1952 return log_event_error_errno(dev, token, r, "Failed to get driver: %m");
25de7aa7
YW
1953
1954 return token_match_string(token, val);
7dc846f9 1955 }
25de7aa7
YW
1956 case TK_M_ATTR:
1957 case TK_M_PARENTS_ATTR:
c06ab041 1958 return token_match_attr(token, dev, event);
25de7aa7
YW
1959 case TK_M_SYSCTL: {
1960 _cleanup_free_ char *value = NULL;
7dc846f9 1961 char buf[UDEV_PATH_SIZE];
f6caab89
YW
1962 bool truncated;
1963
1964 (void) udev_event_apply_format(event, token->data, buf, sizeof(buf), false, &truncated);
1965 if (truncated) {
e5a34948 1966 log_event_truncated(dev, token, "sysctl entry name", token->data, "SYSCTL", /* is_match = */ true);
f6caab89
YW
1967 return false;
1968 }
25de7aa7 1969
25de7aa7
YW
1970 r = sysctl_read(sysctl_normalize(buf), &value);
1971 if (r < 0 && r != -ENOENT)
c06ab041 1972 return log_event_error_errno(dev, token, r, "Failed to read sysctl '%s': %m", buf);
25de7aa7
YW
1973
1974 return token_match_string(token, strstrip(value));
1975 }
1976 case TK_M_TEST: {
1977 mode_t mode = PTR_TO_MODE(token->data);
7dc846f9 1978 char buf[UDEV_PATH_SIZE];
25de7aa7 1979 struct stat statbuf;
f6caab89
YW
1980 bool match, truncated;
1981
1982 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
1983 if (truncated) {
e5a34948 1984 log_event_truncated(dev, token, "file name", token->value, "TEST", /* is_match = */ true);
f6caab89
YW
1985 return false;
1986 }
25de7aa7 1987
25de7aa7 1988 if (!path_is_absolute(buf) &&
1223227f 1989 udev_resolve_subsys_kernel(buf, buf, sizeof(buf), false) < 0) {
c8eaaf69 1990 char tmp[UDEV_PATH_SIZE];
7dc846f9 1991 const char *val;
25de7aa7
YW
1992
1993 r = sd_device_get_syspath(dev, &val);
1994 if (r < 0)
c06ab041 1995 return log_event_error_errno(dev, token, r, "Failed to get syspath: %m");
25de7aa7 1996
f6caab89
YW
1997 strscpy_full(tmp, sizeof(tmp), buf, &truncated);
1998 assert(!truncated);
1999 strscpyl_full(buf, sizeof(buf), &truncated, val, "/", tmp, NULL);
2000 if (truncated)
2001 return false;
25de7aa7
YW
2002 }
2003
2004 r = attr_subst_subdir(buf);
2005 if (r == -ENOENT)
2006 return token->op == OP_NOMATCH;
2007 if (r < 0)
c06ab041 2008 return log_event_error_errno(dev, token, r, "Failed to test for the existence of '%s': %m", buf);
25de7aa7
YW
2009
2010 if (stat(buf, &statbuf) < 0)
2011 return token->op == OP_NOMATCH;
2012
2013 if (mode == MODE_INVALID)
2014 return token->op == OP_MATCH;
2015
7a182f10 2016 match = (statbuf.st_mode & mode) > 0;
25de7aa7
YW
2017 return token->op == (match ? OP_MATCH : OP_NOMATCH);
2018 }
2019 case TK_M_PROGRAM: {
c3613ee5 2020 char buf[UDEV_LINE_SIZE], result[UDEV_LINE_SIZE];
f6caab89 2021 bool truncated;
7dc846f9 2022 size_t count;
25de7aa7
YW
2023
2024 event->program_result = mfree(event->program_result);
f6caab89
YW
2025 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2026 if (truncated) {
e5a34948 2027 log_event_truncated(dev, token, "command", token->value, "PROGRAM", /* is_match = */ true);
f6caab89
YW
2028 return false;
2029 }
2030
c06ab041 2031 log_event_debug(dev, token, "Running PROGRAM '%s'", buf);
25de7aa7 2032
6b6e471a 2033 r = udev_event_spawn(event, timeout_usec, timeout_signal, true, buf, result, sizeof(result), NULL);
08de1958
YW
2034 if (r != 0) {
2035 if (r < 0)
c06ab041 2036 log_event_warning_errno(dev, token, r, "Failed to execute \"%s\": %m", buf);
08de1958 2037 else /* returned value is positive when program fails */
c06ab041 2038 log_event_debug(dev, token, "Command \"%s\" returned %d (error)", buf, r);
25de7aa7 2039 return token->op == OP_NOMATCH;
08de1958 2040 }
25de7aa7
YW
2041
2042 delete_trailing_chars(result, "\n");
393fcaf7 2043 count = udev_replace_chars(result, UDEV_ALLOWED_CHARS_INPUT);
25de7aa7 2044 if (count > 0)
c06ab041
YW
2045 log_event_debug(dev, token,
2046 "Replaced %zu character(s) in result of \"%s\"",
2047 count, buf);
25de7aa7
YW
2048
2049 event->program_result = strdup(result);
2050 return token->op == OP_MATCH;
2051 }
2052 case TK_M_IMPORT_FILE: {
2053 _cleanup_fclose_ FILE *f = NULL;
7dc846f9 2054 char buf[UDEV_PATH_SIZE];
f6caab89
YW
2055 bool truncated;
2056
2057 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2058 if (truncated) {
e5a34948 2059 log_event_truncated(dev, token, "file name to be imported", token->value, "IMPORT", /* is_match = */ true);
f6caab89
YW
2060 return false;
2061 }
25de7aa7 2062
c06ab041 2063 log_event_debug(dev, token, "Importing properties from '%s'", buf);
25de7aa7
YW
2064
2065 f = fopen(buf, "re");
2066 if (!f) {
2067 if (errno != ENOENT)
c06ab041 2068 return log_event_error_errno(dev, token, errno, "Failed to open '%s': %m", buf);
25de7aa7
YW
2069 return token->op == OP_NOMATCH;
2070 }
912541b0 2071
25de7aa7
YW
2072 for (;;) {
2073 _cleanup_free_ char *line = NULL;
2074 char *key, *value;
2075
2076 r = read_line(f, LONG_LINE_MAX, &line);
2077 if (r < 0) {
c06ab041 2078 log_event_debug_errno(dev, token, r, "Failed to read '%s', ignoring: %m", buf);
25de7aa7
YW
2079 return token->op == OP_NOMATCH;
2080 }
2081 if (r == 0)
912541b0 2082 break;
25de7aa7
YW
2083
2084 r = get_property_from_string(line, &key, &value);
23bf8dd7 2085 if (r < 0) {
c06ab041
YW
2086 log_event_debug_errno(dev, token, r,
2087 "Failed to parse key and value from '%s', ignoring: %m",
2088 line);
25de7aa7 2089 continue;
23bf8dd7 2090 }
41c81c4a
YW
2091 if (r == 0)
2092 continue;
25de7aa7
YW
2093
2094 r = device_add_property(dev, key, value);
2095 if (r < 0)
c06ab041
YW
2096 return log_event_error_errno(dev, token, r,
2097 "Failed to add property %s=%s: %m",
2098 key, value);
912541b0 2099 }
912541b0 2100
25de7aa7
YW
2101 return token->op == OP_MATCH;
2102 }
2103 case TK_M_IMPORT_PROGRAM: {
28a50651 2104 _cleanup_strv_free_ char **lines = NULL;
c3613ee5 2105 char buf[UDEV_LINE_SIZE], result[UDEV_LINE_SIZE];
f6caab89
YW
2106 bool truncated;
2107
2108 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2109 if (truncated) {
e5a34948 2110 log_event_truncated(dev, token, "command", token->value, "IMPORT", /* is_match = */ true);
f6caab89
YW
2111 return false;
2112 }
25de7aa7 2113
c06ab041 2114 log_event_debug(dev, token, "Importing properties from results of '%s'", buf);
25de7aa7 2115
6b6e471a 2116 r = udev_event_spawn(event, timeout_usec, timeout_signal, true, buf, result, sizeof result, &truncated);
08de1958
YW
2117 if (r != 0) {
2118 if (r < 0)
c06ab041 2119 log_event_warning_errno(dev, token, r, "Failed to execute '%s', ignoring: %m", buf);
08de1958 2120 else /* returned value is positive when program fails */
c06ab041 2121 log_event_debug(dev, token, "Command \"%s\" returned %d (error), ignoring", buf, r);
25de7aa7
YW
2122 return token->op == OP_NOMATCH;
2123 }
2124
6b6e471a
YW
2125 if (truncated) {
2126 bool found = false;
2127
2128 /* Drop the last line. */
3e3ee420 2129 for (char *p = PTR_SUB1(buf + strlen(buf), buf); p; p = PTR_SUB1(p, buf))
6b6e471a
YW
2130 if (strchr(NEWLINE, *p)) {
2131 *p = '\0';
2132 found = true;
2133 } else if (found)
2134 break;
2135 }
2136
86c783d9 2137 r = strv_split_newlines_full(&lines, result, EXTRACT_RETAIN_ESCAPE);
567c19a6
YW
2138 if (r == -ENOMEM)
2139 return log_oom();
2140 if (r < 0) {
c06ab041
YW
2141 log_event_warning_errno(dev, token, r,
2142 "Failed to extract lines from result of command \"%s\", ignoring: %m", buf);
567c19a6
YW
2143 return false;
2144 }
25de7aa7 2145
28a50651
YW
2146 STRV_FOREACH(line, lines) {
2147 char *key, *value;
25de7aa7 2148
28a50651 2149 r = get_property_from_string(*line, &key, &value);
23bf8dd7 2150 if (r < 0) {
c06ab041
YW
2151 log_event_debug_errno(dev, token, r,
2152 "Failed to parse key and value from '%s', ignoring: %m",
2153 *line);
25de7aa7 2154 continue;
23bf8dd7 2155 }
41c81c4a
YW
2156 if (r == 0)
2157 continue;
25de7aa7
YW
2158
2159 r = device_add_property(dev, key, value);
2160 if (r < 0)
c06ab041
YW
2161 return log_event_error_errno(dev, token, r,
2162 "Failed to add property %s=%s: %m",
2163 key, value);
912541b0 2164 }
912541b0 2165
25de7aa7
YW
2166 return token->op == OP_MATCH;
2167 }
2168 case TK_M_IMPORT_BUILTIN: {
2169 UdevBuiltinCommand cmd = PTR_TO_UDEV_BUILTIN_CMD(token->data);
b5f1c0d8 2170 assert(cmd >= 0 && cmd < _UDEV_BUILTIN_MAX);
25de7aa7 2171 unsigned mask = 1U << (int) cmd;
c3613ee5 2172 char buf[UDEV_LINE_SIZE];
f6caab89 2173 bool truncated;
25de7aa7
YW
2174
2175 if (udev_builtin_run_once(cmd)) {
2176 /* check if we ran already */
2177 if (event->builtin_run & mask) {
c06ab041
YW
2178 log_event_debug(dev, token, "Skipping builtin '%s' in IMPORT key",
2179 udev_builtin_name(cmd));
25de7aa7
YW
2180 /* return the result from earlier run */
2181 return token->op == (event->builtin_ret & mask ? OP_NOMATCH : OP_MATCH);
912541b0 2182 }
25de7aa7
YW
2183 /* mark as ran */
2184 event->builtin_run |= mask;
912541b0 2185 }
25de7aa7 2186
f6caab89
YW
2187 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2188 if (truncated) {
e5a34948 2189 log_event_truncated(dev, token, "builtin command", token->value, "IMPORT", /* is_match = */ true);
f6caab89
YW
2190 return false;
2191 }
2192
c06ab041 2193 log_event_debug(dev, token, "Importing properties from results of builtin command '%s'", buf);
25de7aa7 2194
5668f3a7 2195 r = udev_builtin_run(event, cmd, buf, false);
25de7aa7
YW
2196 if (r < 0) {
2197 /* remember failure */
c06ab041 2198 log_event_debug_errno(dev, token, r, "Failed to run builtin '%s': %m", buf);
25de7aa7
YW
2199 event->builtin_ret |= mask;
2200 }
2201 return token->op == (r >= 0 ? OP_MATCH : OP_NOMATCH);
2202 }
2203 case TK_M_IMPORT_DB: {
7dc846f9
YW
2204 const char *val;
2205
25de7aa7
YW
2206 if (!event->dev_db_clone)
2207 return token->op == OP_NOMATCH;
2208 r = sd_device_get_property_value(event->dev_db_clone, token->value, &val);
2209 if (r == -ENOENT)
2210 return token->op == OP_NOMATCH;
2211 if (r < 0)
c06ab041
YW
2212 return log_event_error_errno(dev, token, r,
2213 "Failed to get property '%s' from database: %m",
2214 token->value);
25de7aa7
YW
2215
2216 r = device_add_property(dev, token->value, val);
2217 if (r < 0)
c06ab041
YW
2218 return log_event_error_errno(dev, token, r, "Failed to add property '%s=%s': %m",
2219 token->value, val);
25de7aa7
YW
2220 return token->op == OP_MATCH;
2221 }
2222 case TK_M_IMPORT_CMDLINE: {
2223 _cleanup_free_ char *value = NULL;
2224
09835de3 2225 r = proc_cmdline_get_key(token->value, PROC_CMDLINE_VALUE_OPTIONAL|PROC_CMDLINE_IGNORE_EFI_OPTIONS, &value);
25de7aa7 2226 if (r < 0)
c06ab041
YW
2227 return log_event_error_errno(dev, token, r,
2228 "Failed to read '%s' option from /proc/cmdline: %m",
2229 token->value);
25de7aa7
YW
2230 if (r == 0)
2231 return token->op == OP_NOMATCH;
2232
2233 r = device_add_property(dev, token->value, value ?: "1");
2234 if (r < 0)
c06ab041
YW
2235 return log_event_error_errno(dev, token, r, "Failed to add property '%s=%s': %m",
2236 token->value, value ?: "1");
25de7aa7
YW
2237 return token->op == OP_MATCH;
2238 }
2239 case TK_M_IMPORT_PARENT: {
7dc846f9 2240 char buf[UDEV_PATH_SIZE];
f6caab89
YW
2241 bool truncated;
2242
2243 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2244 if (truncated) {
e5a34948 2245 log_event_truncated(dev, token, "property name", token->value, "IMPORT", /* is_match = */ true);
f6caab89
YW
2246 return false;
2247 }
7dc846f9 2248
25de7aa7
YW
2249 r = import_parent_into_properties(dev, buf);
2250 if (r < 0)
c06ab041
YW
2251 return log_event_error_errno(dev, token, r,
2252 "Failed to import properties '%s' from parent: %m",
2253 buf);
25de7aa7
YW
2254 return token->op == (r > 0 ? OP_MATCH : OP_NOMATCH);
2255 }
2256 case TK_M_RESULT:
2257 return token_match_string(token, event->program_result);
2258 case TK_A_OPTIONS_STRING_ESCAPE_NONE:
2259 event->esc = ESCAPE_NONE;
2260 break;
2261 case TK_A_OPTIONS_STRING_ESCAPE_REPLACE:
2262 event->esc = ESCAPE_REPLACE;
2263 break;
2264 case TK_A_OPTIONS_DB_PERSIST:
2265 device_set_db_persist(dev);
2266 break;
2267 case TK_A_OPTIONS_INOTIFY_WATCH:
2268 if (event->inotify_watch_final)
912541b0 2269 break;
25de7aa7
YW
2270 if (token->op == OP_ASSIGN_FINAL)
2271 event->inotify_watch_final = true;
2272
2273 event->inotify_watch = token->data;
2274 break;
2275 case TK_A_OPTIONS_DEVLINK_PRIORITY:
2276 device_set_devlink_priority(dev, PTR_TO_INT(token->data));
2277 break;
1a0bd015
YW
2278 case TK_A_OPTIONS_LOG_LEVEL: {
2279 int level = PTR_TO_INT(token->data);
2280
2281 if (level < 0)
2282 level = event->default_log_level;
2283
3cc6b14a 2284 log_set_max_level(level);
1a0bd015
YW
2285
2286 if (level == LOG_DEBUG && !event->log_level_was_debug) {
2287 /* The log level becomes LOG_DEBUG at first time. Let's log basic information. */
2288 log_device_uevent(dev, "The log level is changed to 'debug' while processing device");
2289 event->log_level_was_debug = true;
2290 }
2291
2292 break;
2293 }
25de7aa7 2294 case TK_A_OWNER: {
c8eaaf69 2295 char owner[UDEV_NAME_SIZE];
25de7aa7 2296 const char *ow = owner;
f6caab89 2297 bool truncated;
25de7aa7
YW
2298
2299 if (event->owner_final)
912541b0 2300 break;
25de7aa7
YW
2301 if (token->op == OP_ASSIGN_FINAL)
2302 event->owner_final = true;
2303
f6caab89
YW
2304 (void) udev_event_apply_format(event, token->value, owner, sizeof(owner), false, &truncated);
2305 if (truncated) {
e5a34948 2306 log_event_truncated(dev, token, "user name", token->value, "OWNER", /* is_match = */ false);
f6caab89
YW
2307 break;
2308 }
2309
25de7aa7
YW
2310 r = get_user_creds(&ow, &event->uid, NULL, NULL, NULL, USER_CREDS_ALLOW_MISSING);
2311 if (r < 0)
c06ab041 2312 log_unknown_owner(dev, token->rule_line, r, "user", owner);
25de7aa7 2313 else
c06ab041 2314 log_event_debug(dev, token, "OWNER %s(%u)", owner, event->uid);
25de7aa7
YW
2315 break;
2316 }
2317 case TK_A_GROUP: {
c8eaaf69 2318 char group[UDEV_NAME_SIZE];
25de7aa7 2319 const char *gr = group;
f6caab89 2320 bool truncated;
25de7aa7
YW
2321
2322 if (event->group_final)
912541b0 2323 break;
25de7aa7
YW
2324 if (token->op == OP_ASSIGN_FINAL)
2325 event->group_final = true;
c26547d6 2326
f6caab89
YW
2327 (void) udev_event_apply_format(event, token->value, group, sizeof(group), false, &truncated);
2328 if (truncated) {
e5a34948 2329 log_event_truncated(dev, token, "group name", token->value, "GROUP", /* is_match = */ false);
f6caab89
YW
2330 break;
2331 }
2332
25de7aa7
YW
2333 r = get_group_creds(&gr, &event->gid, USER_CREDS_ALLOW_MISSING);
2334 if (r < 0)
c06ab041 2335 log_unknown_owner(dev, token->rule_line, r, "group", group);
25de7aa7 2336 else
c06ab041 2337 log_event_debug(dev, token, "GROUP %s(%u)", group, event->gid);
25de7aa7
YW
2338 break;
2339 }
2340 case TK_A_MODE: {
c8eaaf69 2341 char mode_str[UDEV_NAME_SIZE];
f6caab89 2342 bool truncated;
d838e145 2343
25de7aa7
YW
2344 if (event->mode_final)
2345 break;
2346 if (token->op == OP_ASSIGN_FINAL)
2347 event->mode_final = true;
4f985bd8 2348
f6caab89
YW
2349 (void) udev_event_apply_format(event, token->value, mode_str, sizeof(mode_str), false, &truncated);
2350 if (truncated) {
e5a34948 2351 log_event_truncated(dev, token, "mode", token->value, "MODE", /* is_match = */ false);
f6caab89
YW
2352 break;
2353 }
2354
25de7aa7
YW
2355 r = parse_mode(mode_str, &event->mode);
2356 if (r < 0)
c06ab041 2357 log_event_error_errno(dev, token, r, "Failed to parse mode '%s', ignoring: %m", mode_str);
25de7aa7 2358 else
c06ab041 2359 log_event_debug(dev, token, "MODE %#o", event->mode);
25de7aa7
YW
2360 break;
2361 }
2362 case TK_A_OWNER_ID:
2363 if (event->owner_final)
2364 break;
2365 if (token->op == OP_ASSIGN_FINAL)
2366 event->owner_final = true;
2367 if (!token->data)
2368 break;
2369 event->uid = PTR_TO_UID(token->data);
c06ab041 2370 log_event_debug(dev, token, "OWNER %u", event->uid);
25de7aa7
YW
2371 break;
2372 case TK_A_GROUP_ID:
2373 if (event->group_final)
2374 break;
2375 if (token->op == OP_ASSIGN_FINAL)
2376 event->group_final = true;
2377 if (!token->data)
2378 break;
2379 event->gid = PTR_TO_GID(token->data);
c06ab041 2380 log_event_debug(dev, token, "GROUP %u", event->gid);
25de7aa7
YW
2381 break;
2382 case TK_A_MODE_ID:
2383 if (event->mode_final)
2384 break;
2385 if (token->op == OP_ASSIGN_FINAL)
2386 event->mode_final = true;
2387 if (!token->data)
2388 break;
2389 event->mode = PTR_TO_MODE(token->data);
c06ab041 2390 log_event_debug(dev, token, "MODE %#o", event->mode);
25de7aa7
YW
2391 break;
2392 case TK_A_SECLABEL: {
2393 _cleanup_free_ char *name = NULL, *label = NULL;
c8eaaf69 2394 char label_str[UDEV_LINE_SIZE] = {};
f6caab89 2395 bool truncated;
d838e145 2396
af2e52f4 2397 name = strdup(token->data);
25de7aa7
YW
2398 if (!name)
2399 return log_oom();
d838e145 2400
f6caab89
YW
2401 (void) udev_event_apply_format(event, token->value, label_str, sizeof(label_str), false, &truncated);
2402 if (truncated) {
e5a34948 2403 log_event_truncated(dev, token, "security label", token->value, "SECLABEL", /* is_match = */ false);
f6caab89
YW
2404 break;
2405 }
2406
25de7aa7
YW
2407 if (!isempty(label_str))
2408 label = strdup(label_str);
2409 else
2410 label = strdup(token->value);
2411 if (!label)
2412 return log_oom();
a6ca3c19 2413
25de7aa7
YW
2414 if (token->op == OP_ASSIGN)
2415 ordered_hashmap_clear_free_free(event->seclabel_list);
07845c14 2416
f5b73a7f
SS
2417 r = ordered_hashmap_ensure_put(&event->seclabel_list, NULL, name, label);
2418 if (r == -ENOMEM)
25de7aa7 2419 return log_oom();
25de7aa7 2420 if (r < 0)
c06ab041 2421 return log_event_error_errno(dev, token, r, "Failed to store SECLABEL{%s}='%s': %m", name, label);
f5b73a7f 2422
c06ab041 2423 log_event_debug(dev, token, "SECLABEL{%s}='%s'", name, label);
3c291376
SS
2424
2425 TAKE_PTR(name);
2426 TAKE_PTR(label);
25de7aa7
YW
2427 break;
2428 }
2429 case TK_A_ENV: {
7dc846f9 2430 const char *val, *name = token->data;
c8eaaf69 2431 char value_new[UDEV_NAME_SIZE], *p = value_new;
7dc846f9 2432 size_t count, l = sizeof(value_new);
f6caab89 2433 bool truncated;
07845c14 2434
25de7aa7
YW
2435 if (isempty(token->value)) {
2436 if (token->op == OP_ADD)
912541b0 2437 break;
25de7aa7
YW
2438 r = device_add_property(dev, name, NULL);
2439 if (r < 0)
c06ab041 2440 return log_event_error_errno(dev, token, r, "Failed to remove property '%s': %m", name);
912541b0
KS
2441 break;
2442 }
912541b0 2443
25de7aa7 2444 if (token->op == OP_ADD &&
f6caab89
YW
2445 sd_device_get_property_value(dev, name, &val) >= 0) {
2446 l = strpcpyl_full(&p, l, &truncated, val, " ", NULL);
2447 if (truncated) {
c06ab041
YW
2448 log_event_warning(dev, token,
2449 "The buffer for the property '%s' is full, "
2450 "refusing to append the new value '%s'.", name, token->value);
f6caab89
YW
2451 break;
2452 }
2453 }
2454
2455 (void) udev_event_apply_format(event, token->value, p, l, false, &truncated);
2456 if (truncated) {
e5a34948
YW
2457 _cleanup_free_ char *key_with_name = strjoin("ENV{", name, "}");
2458 log_event_truncated(dev, token, "property value", token->value,
2459 key_with_name ?: "ENV", /* is_match = */ false);
f6caab89
YW
2460 break;
2461 }
25de7aa7 2462
ea0f4578 2463 if (event->esc == ESCAPE_REPLACE) {
7db6b672 2464 count = udev_replace_chars(p, NULL);
ea0f4578 2465 if (count > 0)
c06ab041
YW
2466 log_event_debug(dev, token,
2467 "Replaced %zu slash(es) from result of ENV{%s}%s=\"%s\"",
2468 count, name, token->op == OP_ADD ? "+" : "", token->value);
ea0f4578 2469 }
d838e145 2470
25de7aa7
YW
2471 r = device_add_property(dev, name, value_new);
2472 if (r < 0)
c06ab041 2473 return log_event_error_errno(dev, token, r, "Failed to add property '%s=%s': %m", name, value_new);
25de7aa7
YW
2474 break;
2475 }
2476 case TK_A_TAG: {
7dc846f9 2477 char buf[UDEV_PATH_SIZE];
f6caab89
YW
2478 bool truncated;
2479
2480 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2481 if (truncated) {
e5a34948 2482 log_event_truncated(dev, token, "tag name", token->value, "TAG", /* is_match = */ false);
f6caab89
YW
2483 break;
2484 }
7dc846f9 2485
25de7aa7
YW
2486 if (token->op == OP_ASSIGN)
2487 device_cleanup_tags(dev);
2488
25de7aa7
YW
2489 if (token->op == OP_REMOVE)
2490 device_remove_tag(dev, buf);
2491 else {
e77b146f 2492 r = device_add_tag(dev, buf, true);
0b4c70b4
YW
2493 if (r == -ENOMEM)
2494 return log_oom();
25de7aa7 2495 if (r < 0)
0b4c70b4 2496 log_event_warning_errno(dev, token, r, "Failed to add tag '%s', ignoring: %m", buf);
25de7aa7
YW
2497 }
2498 break;
2499 }
2500 case TK_A_NAME: {
7dc846f9 2501 char buf[UDEV_PATH_SIZE];
f6caab89 2502 bool truncated;
7dc846f9
YW
2503 size_t count;
2504
25de7aa7
YW
2505 if (event->name_final)
2506 break;
2507 if (token->op == OP_ASSIGN_FINAL)
2508 event->name_final = true;
912541b0 2509
d37f3e3e 2510 if (sd_device_get_ifindex(dev, NULL) < 0) {
c06ab041
YW
2511 log_event_error(dev, token,
2512 "Only network interfaces can be renamed, ignoring NAME=\"%s\".",
2513 token->value);
d37f3e3e
YW
2514 break;
2515 }
2516
f6caab89
YW
2517 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2518 if (truncated) {
e5a34948 2519 log_event_truncated(dev, token, "network interface name", token->value, "NAME", /* is_match = */ false);
f6caab89
YW
2520 break;
2521 }
2522
25de7aa7 2523 if (IN_SET(event->esc, ESCAPE_UNSET, ESCAPE_REPLACE)) {
b4d885f0
YW
2524 if (naming_scheme_has(NAMING_REPLACE_STRICTLY))
2525 count = udev_replace_ifname(buf);
2526 else
2527 count = udev_replace_chars(buf, "/");
912541b0 2528 if (count > 0)
c06ab041
YW
2529 log_event_debug(dev, token,
2530 "Replaced %zu character(s) from result of NAME=\"%s\"",
2531 count, token->value);
912541b0 2532 }
b3f9c17a
YW
2533 r = free_and_strdup_warn(&event->name, buf);
2534 if (r < 0)
2535 return r;
25de7aa7 2536
c06ab041 2537 log_event_debug(dev, token, "NAME '%s'", event->name);
25de7aa7
YW
2538 break;
2539 }
2540 case TK_A_DEVLINK: {
733b7bfd 2541 char buf[UDEV_PATH_SIZE];
f6caab89 2542 bool truncated;
7dc846f9 2543 size_t count;
25de7aa7
YW
2544
2545 if (event->devlink_final)
2546 break;
2547 if (sd_device_get_devnum(dev, NULL) < 0)
2548 break;
2549 if (token->op == OP_ASSIGN_FINAL)
2550 event->devlink_final = true;
2551 if (IN_SET(token->op, OP_ASSIGN, OP_ASSIGN_FINAL))
2552 device_cleanup_devlinks(dev);
2553
03ff9c70
YW
2554 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf),
2555 /* replace_whitespace = */ event->esc != ESCAPE_NONE, &truncated);
f6caab89 2556 if (truncated) {
e5a34948 2557 log_event_truncated(dev, token, "symbolic link path", token->value, "SYMLINK", /* is_match = */ false);
f6caab89
YW
2558 break;
2559 }
2560
03ff9c70 2561 /* By default or string_escape=none, allow multiple symlinks separated by spaces. */
25de7aa7 2562 if (event->esc == ESCAPE_UNSET)
03ff9c70 2563 count = udev_replace_chars(buf, /* allow = */ "/ ");
25de7aa7 2564 else if (event->esc == ESCAPE_REPLACE)
03ff9c70 2565 count = udev_replace_chars(buf, /* allow = */ "/");
25de7aa7
YW
2566 else
2567 count = 0;
2568 if (count > 0)
c06ab041
YW
2569 log_event_debug(dev, token,
2570 "Replaced %zu character(s) from result of SYMLINK=\"%s\"",
2571 count, token->value);
25de7aa7 2572
733b7bfd 2573 for (const char *p = buf;;) {
2c5f119c 2574 _cleanup_free_ char *path = NULL;
25de7aa7 2575
2c5f119c 2576 r = extract_first_word(&p, &path, NULL, EXTRACT_RETAIN_ESCAPE);
733b7bfd
YW
2577 if (r == -ENOMEM)
2578 return log_oom();
2579 if (r < 0) {
2580 log_warning_errno(r, "Failed to extract first path in SYMLINK=, ignoring: %m");
2581 break;
25de7aa7 2582 }
733b7bfd
YW
2583 if (r == 0)
2584 break;
25de7aa7 2585
aeefa4d2 2586 if (token->op == OP_REMOVE) {
2c5f119c
YW
2587 r = device_remove_devlink(dev, path);
2588 if (r == -ENOMEM)
2589 return log_oom();
2590 if (r < 0)
2591 log_event_warning_errno(dev, token, r, "Failed to remove devlink '%s', ignoring: %m", path);
2592 else if (r > 0)
2593 log_event_debug(dev, token, "Dropped SYMLINK '%s'", path);
aeefa4d2 2594 } else {
f17af9c9 2595 r = device_add_devlink(dev, path);
2c5f119c
YW
2596 if (r == -ENOMEM)
2597 return log_oom();
aeefa4d2 2598 if (r < 0)
2c5f119c
YW
2599 log_event_warning_errno(dev, token, r, "Failed to add devlink '%s', ignoring: %m", path);
2600 else if (r > 0)
2601 log_event_debug(dev, token, "Added SYMLINK '%s'", path);
aeefa4d2 2602 }
25de7aa7
YW
2603 }
2604 break;
2605 }
2606 case TK_A_ATTR: {
7dc846f9
YW
2607 char buf[UDEV_PATH_SIZE], value[UDEV_NAME_SIZE];
2608 const char *val, *key_name = token->data;
f6caab89 2609 bool truncated;
25de7aa7 2610
1223227f 2611 if (udev_resolve_subsys_kernel(key_name, buf, sizeof(buf), false) < 0 &&
f6caab89
YW
2612 sd_device_get_syspath(dev, &val) >= 0) {
2613 strscpyl_full(buf, sizeof(buf), &truncated, val, "/", key_name, NULL);
2614 if (truncated) {
c06ab041
YW
2615 log_event_warning(dev, token,
2616 "The path to the attribute '%s/%s' is too long, refusing to set the attribute.",
2617 val, key_name);
f6caab89
YW
2618 break;
2619 }
2620 }
25de7aa7
YW
2621
2622 r = attr_subst_subdir(buf);
2623 if (r < 0) {
c06ab041 2624 log_event_error_errno(dev, token, r, "Could not find file matches '%s', ignoring: %m", buf);
f4cf2e5b
KS
2625 break;
2626 }
f6caab89
YW
2627 (void) udev_event_apply_format(event, token->value, value, sizeof(value), false, &truncated);
2628 if (truncated) {
e5a34948 2629 log_event_truncated(dev, token, "attribute value", token->value, "ATTR", /* is_match = */ false);
f6caab89
YW
2630 break;
2631 }
6cdc62aa 2632
c06ab041 2633 log_event_debug(dev, token, "ATTR '%s' writing '%s'", buf, value);
6fb61918
YW
2634 r = write_string_file(buf, value,
2635 WRITE_STRING_FILE_VERIFY_ON_FAILURE |
2636 WRITE_STRING_FILE_DISABLE_BUFFER |
2637 WRITE_STRING_FILE_AVOID_NEWLINE |
2638 WRITE_STRING_FILE_VERIFY_IGNORE_NEWLINE);
25de7aa7 2639 if (r < 0)
c06ab041 2640 log_event_error_errno(dev, token, r, "Failed to write ATTR{%s}, ignoring: %m", buf);
25de7aa7
YW
2641 break;
2642 }
2643 case TK_A_SYSCTL: {
7dc846f9 2644 char buf[UDEV_PATH_SIZE], value[UDEV_NAME_SIZE];
f6caab89
YW
2645 bool truncated;
2646
2647 (void) udev_event_apply_format(event, token->data, buf, sizeof(buf), false, &truncated);
2648 if (truncated) {
e5a34948 2649 log_event_truncated(dev, token, "sysctl entry name", token->data, "SYSCTL", /* is_match = */ false);
f6caab89
YW
2650 break;
2651 }
2652
2653 (void) udev_event_apply_format(event, token->value, value, sizeof(value), false, &truncated);
2654 if (truncated) {
e5a34948
YW
2655 _cleanup_free_ char *key_with_name = strjoin("SYSCTL{", buf, "}");
2656 log_event_truncated(dev, token, "sysctl value", token->value,
2657 key_with_name ?: "SYSCTL", /* is_match = */ false);
f6caab89
YW
2658 break;
2659 }
25de7aa7 2660
25de7aa7 2661 sysctl_normalize(buf);
c06ab041 2662 log_event_debug(dev, token, "SYSCTL '%s' writing '%s'", buf, value);
25de7aa7
YW
2663 r = sysctl_write(buf, value);
2664 if (r < 0)
c06ab041 2665 log_event_error_errno(dev, token, r, "Failed to write SYSCTL{%s}='%s', ignoring: %m", buf, value);
25de7aa7
YW
2666 break;
2667 }
2668 case TK_A_RUN_BUILTIN:
2669 case TK_A_RUN_PROGRAM: {
2670 _cleanup_free_ char *cmd = NULL;
c3613ee5 2671 char buf[UDEV_LINE_SIZE];
f6caab89 2672 bool truncated;
29448498 2673
25de7aa7
YW
2674 if (event->run_final)
2675 break;
2676 if (token->op == OP_ASSIGN_FINAL)
2677 event->run_final = true;
29448498 2678
25de7aa7
YW
2679 if (IN_SET(token->op, OP_ASSIGN, OP_ASSIGN_FINAL))
2680 ordered_hashmap_clear_free_key(event->run_list);
29448498 2681
f6caab89
YW
2682 (void) udev_event_apply_format(event, token->value, buf, sizeof(buf), false, &truncated);
2683 if (truncated) {
e5a34948
YW
2684 log_event_truncated(dev, token, "command", token->value,
2685 token->type == TK_A_RUN_BUILTIN ? "RUN{builtin}" : "RUN{program}",
2686 /* is_match = */ false);
f6caab89
YW
2687 break;
2688 }
1448820a
YW
2689
2690 cmd = strdup(buf);
25de7aa7
YW
2691 if (!cmd)
2692 return log_oom();
29448498 2693
875038d5
SS
2694 r = ordered_hashmap_ensure_put(&event->run_list, NULL, cmd, token->data);
2695 if (r == -ENOMEM)
25de7aa7 2696 return log_oom();
875038d5 2697 if (r < 0)
c06ab041 2698 return log_event_error_errno(dev, token, r, "Failed to store command '%s': %m", cmd);
83cd6b75 2699
25de7aa7
YW
2700 TAKE_PTR(cmd);
2701
c06ab041 2702 log_event_debug(dev, token, "RUN '%s'", token->value);
25de7aa7
YW
2703 break;
2704 }
2705 case TK_A_OPTIONS_STATIC_NODE:
2706 /* do nothing for events. */
2707 break;
2708 default:
04499a70 2709 assert_not_reached();
25de7aa7
YW
2710 }
2711
2712 return true;
2713}
2714
2715static bool token_is_for_parents(UdevRuleToken *token) {
2716 return token->type >= TK_M_PARENTS_KERNEL && token->type <= TK_M_PARENTS_TAG;
2717}
2718
2719static int udev_rule_apply_parent_token_to_event(
c06ab041 2720 UdevRuleToken *head_token,
e2099267
MS
2721 UdevEvent *event,
2722 int timeout_signal) {
25de7aa7 2723
25de7aa7
YW
2724 int r;
2725
c06ab041 2726 assert(head_token);
eba782d5
YW
2727 assert(event);
2728
eba782d5
YW
2729 event->dev_parent = ASSERT_PTR(event->dev);
2730
25de7aa7 2731 for (;;) {
c06ab041 2732 LIST_FOREACH(tokens, token, head_token) {
03677889 2733 if (!token_is_for_parents(token))
25de7aa7 2734 return true; /* All parent tokens match. */
03677889 2735
c06ab041 2736 r = udev_rule_apply_token_to_event(token, event->dev_parent, event, 0, timeout_signal, NULL);
25de7aa7
YW
2737 if (r < 0)
2738 return r;
2739 if (r == 0)
912541b0 2740 break;
25de7aa7 2741 }
eba782d5
YW
2742 if (r > 0)
2743 /* All parent tokens match, and no more token (except for GOTO) in the line. */
25de7aa7
YW
2744 return true;
2745
2746 if (sd_device_get_parent(event->dev_parent, &event->dev_parent) < 0) {
2747 event->dev_parent = NULL;
2748 return false;
2749 }
2750 }
2751}
2752
2753static int udev_rule_apply_line_to_event(
c06ab041 2754 UdevRuleLine *line,
25de7aa7
YW
2755 UdevEvent *event,
2756 usec_t timeout_usec,
e2099267 2757 int timeout_signal,
25de7aa7
YW
2758 Hashmap *properties_list,
2759 UdevRuleLine **next_line) {
2760
25de7aa7 2761 UdevRuleLineType mask = LINE_HAS_GOTO | LINE_UPDATE_SOMETHING;
25de7aa7 2762 bool parents_done = false;
a1130022 2763 sd_device_action_t action;
25de7aa7 2764 int r;
912541b0 2765
c06ab041
YW
2766 assert(line);
2767 assert(event);
2768 assert(next_line);
2769
a1130022 2770 r = sd_device_get_action(event->dev, &action);
25de7aa7
YW
2771 if (r < 0)
2772 return r;
2773
a1130022 2774 if (action != SD_DEVICE_REMOVE) {
25de7aa7
YW
2775 if (sd_device_get_devnum(event->dev, NULL) >= 0)
2776 mask |= LINE_HAS_DEVLINK;
2777
2778 if (sd_device_get_ifindex(event->dev, NULL) >= 0)
2779 mask |= LINE_HAS_NAME;
2780 }
2781
2782 if ((line->type & mask) == 0)
2783 return 0;
2784
2785 event->esc = ESCAPE_UNSET;
b428efa5
MS
2786
2787 DEVICE_TRACE_POINT(rules_apply_line, event->dev, line->rule_file->filename, line->line_number);
2788
80a226b2 2789 LIST_FOREACH(tokens, token, line->tokens) {
25de7aa7
YW
2790 if (token_is_for_parents(token)) {
2791 if (parents_done)
2792 continue;
2793
c06ab041 2794 r = udev_rule_apply_parent_token_to_event(token, event, timeout_signal);
25de7aa7
YW
2795 if (r <= 0)
2796 return r;
2797
2798 parents_done = true;
2799 continue;
912541b0
KS
2800 }
2801
c06ab041 2802 r = udev_rule_apply_token_to_event(token, event->dev, event, timeout_usec, timeout_signal, properties_list);
25de7aa7
YW
2803 if (r <= 0)
2804 return r;
912541b0 2805 }
d838e145 2806
25de7aa7 2807 if (line->goto_line)
c06ab041 2808 *next_line = line->goto_line; /* update next_line only when the line has GOTO token. */
25de7aa7 2809
d838e145 2810 return 0;
6880b25d 2811}
761dfddc 2812
25de7aa7
YW
2813int udev_rules_apply_to_event(
2814 UdevRules *rules,
2815 UdevEvent *event,
2816 usec_t timeout_usec,
e2099267 2817 int timeout_signal,
25de7aa7
YW
2818 Hashmap *properties_list) {
2819
25de7aa7
YW
2820 int r;
2821
2822 assert(rules);
2823 assert(event);
2824
c06ab041 2825 LIST_FOREACH(rule_files, file, rules->rule_files)
80a226b2 2826 LIST_FOREACH_WITH_NEXT(rule_lines, line, next_line, file->rule_lines) {
c06ab041 2827 r = udev_rule_apply_line_to_event(line, event, timeout_usec, timeout_signal, properties_list, &next_line);
25de7aa7
YW
2828 if (r < 0)
2829 return r;
2830 }
25de7aa7
YW
2831
2832 return 0;
2833}
2834
25de7aa7 2835static int udev_rule_line_apply_static_dev_perms(UdevRuleLine *rule_line) {
f4f6f2c7 2836 _cleanup_strv_free_ char **tags = NULL;
25de7aa7
YW
2837 uid_t uid = UID_INVALID;
2838 gid_t gid = GID_INVALID;
2839 mode_t mode = MODE_INVALID;
2840 int r;
d6f116a7 2841
25de7aa7 2842 assert(rule_line);
912541b0 2843
25de7aa7
YW
2844 if (!FLAGS_SET(rule_line->type, LINE_HAS_STATIC_NODE))
2845 return 0;
912541b0 2846
25de7aa7
YW
2847 LIST_FOREACH(tokens, token, rule_line->tokens)
2848 if (token->type == TK_A_OWNER_ID)
2849 uid = PTR_TO_UID(token->data);
2850 else if (token->type == TK_A_GROUP_ID)
2851 gid = PTR_TO_GID(token->data);
2852 else if (token->type == TK_A_MODE_ID)
2853 mode = PTR_TO_MODE(token->data);
2854 else if (token->type == TK_A_TAG) {
2855 r = strv_extend(&tags, token->value);
2856 if (r < 0)
2857 return log_oom();
2858 } else if (token->type == TK_A_OPTIONS_STATIC_NODE) {
26dd37f6 2859 r = static_node_apply_permissions(token->value, mode, uid, gid, tags);
25de7aa7
YW
2860 if (r < 0)
2861 return r;
912541b0
KS
2862 }
2863
25de7aa7
YW
2864 return 0;
2865}
2866
2867int udev_rules_apply_static_dev_perms(UdevRules *rules) {
25de7aa7
YW
2868 int r;
2869
2870 assert(rules);
84b6ad70 2871
25de7aa7
YW
2872 LIST_FOREACH(rule_files, file, rules->rule_files)
2873 LIST_FOREACH(rule_lines, line, file->rule_lines) {
2874 r = udev_rule_line_apply_static_dev_perms(line);
2875 if (r < 0)
2876 return r;
84b6ad70 2877 }
84b6ad70 2878
fdd21be6 2879 return 0;
761dfddc 2880}