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