]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/udev/udev-rules.c
Remove 'inline' attributes from static functions in .c files (#11426)
[thirdparty/systemd.git] / src / udev / udev-rules.c
CommitLineData
e7145211 1/* SPDX-License-Identifier: GPL-2.0+ */
2232cac8 2
2232cac8 3#include <ctype.h>
4f5dd394
LP
4#include <errno.h>
5#include <fcntl.h>
cea61f5c 6#include <fnmatch.h>
4f5dd394
LP
7#include <limits.h>
8#include <stdbool.h>
9#include <stddef.h>
10#include <stdio.h>
11#include <stdlib.h>
12#include <string.h>
959e8b5d 13#include <time.h>
4f5dd394 14#include <unistd.h>
2232cac8 15
b5efdb8a 16#include "alloc-util.h"
2c21044f 17#include "conf-files.h"
29b5eb5a 18#include "device-private.h"
480ecb7d 19#include "device-util.h"
8fb3f009 20#include "dirent-util.h"
4f5dd394 21#include "escape.h"
3ffd4af2 22#include "fd-util.h"
fae0f8a0 23#include "fileio.h"
fdd21be6 24#include "fs-util.h"
7d50b32a 25#include "glob-util.h"
5ea78a39
YW
26#include "libudev-util.h"
27#include "mkdir.h"
b4ba2fe3 28#include "parse-util.h"
4f5dd394 29#include "path-util.h"
88b013b2 30#include "proc-cmdline.h"
8fcde012 31#include "stat-util.h"
f4850a1d 32#include "stdio-util.h"
915bf0f6 33#include "strbuf.h"
07630cea 34#include "string-util.h"
84b6ad70 35#include "strv.h"
5ea78a39 36#include "strxcpyx.h"
f4cf2e5b 37#include "sysctl-util.h"
07a26e42 38#include "udev-builtin.h"
4f5dd394 39#include "udev.h"
b1d4f8e1 40#include "user-util.h"
07630cea 41#include "util.h"
2232cac8 42
a1525d17 43#define PREALLOC_TOKEN 2048
c7521974 44
4052400f 45struct uid_gid {
14cb109d 46 unsigned name_off;
912541b0 47 union {
a1525d17
KS
48 uid_t uid;
49 gid_t gid;
912541b0 50 };
4052400f
KS
51};
52
2ad8416d
ZJS
53static const char* const rules_dirs[] = {
54 "/etc/udev/rules.d",
55 "/run/udev/rules.d",
56 UDEVLIBEXECDIR "/rules.d",
4f5dd394
LP
57 NULL
58};
2ad8416d 59
9a07157d 60struct UdevRules {
97f2d76d 61 usec_t dirs_ts_usec;
c4d44cba 62 ResolveNameTiming resolve_name_timing;
912541b0
KS
63
64 /* every key in the rules file becomes a token */
65 struct token *tokens;
14cb109d
YW
66 unsigned token_cur;
67 unsigned token_max;
912541b0 68
ab06eef8 69 /* all key strings are copied and de-duplicated in a single continuous string buffer */
915bf0f6 70 struct strbuf *strbuf;
912541b0
KS
71
72 /* during rule parsing, uid/gid lookup results are cached */
73 struct uid_gid *uids;
14cb109d
YW
74 unsigned uids_cur;
75 unsigned uids_max;
912541b0 76 struct uid_gid *gids;
14cb109d
YW
77 unsigned gids_cur;
78 unsigned gids_max;
4052400f
KS
79};
80
9a07157d 81static char *rules_str(UdevRules *rules, unsigned off) {
915bf0f6
KS
82 return rules->strbuf->buf + off;
83}
84
9a07157d 85static unsigned rules_add_string(UdevRules *rules, const char *s) {
915bf0f6
KS
86 return strbuf_add_string(rules->strbuf, s, strlen(s));
87}
88
8e3ba377 89/* KEY=="", KEY!="", KEY+="", KEY-="", KEY="", KEY:="" */
b0f7409f 90enum operation_type {
912541b0 91 OP_UNSET,
b0f7409f 92
912541b0
KS
93 OP_MATCH,
94 OP_NOMATCH,
95 OP_MATCH_MAX,
b0f7409f 96
912541b0 97 OP_ADD,
8e3ba377 98 OP_REMOVE,
912541b0
KS
99 OP_ASSIGN,
100 OP_ASSIGN_FINAL,
c7521974
KS
101};
102
ac218d9c 103enum string_glob_type {
912541b0 104 GL_UNSET,
a1525d17 105 GL_PLAIN, /* no special chars */
912541b0 106 GL_GLOB, /* shell globs ?,*,[] */
a1525d17
KS
107 GL_SPLIT, /* multi-value A|B */
108 GL_SPLIT_GLOB, /* multi-value with glob A*|B* */
109 GL_SOMETHING, /* commonly used "?*" */
ac218d9c
KS
110};
111
32028733 112enum string_subst_type {
912541b0
KS
113 SB_UNSET,
114 SB_NONE,
115 SB_FORMAT,
116 SB_SUBSYS,
32028733
KS
117};
118
154a7b84 119/* tokens of a rule are sorted/handled in this order */
6880b25d 120enum token_type {
912541b0
KS
121 TK_UNSET,
122 TK_RULE,
123
a1525d17
KS
124 TK_M_ACTION, /* val */
125 TK_M_DEVPATH, /* val */
126 TK_M_KERNEL, /* val */
127 TK_M_DEVLINK, /* val */
128 TK_M_NAME, /* val */
129 TK_M_ENV, /* val, attr */
130 TK_M_TAG, /* val */
131 TK_M_SUBSYSTEM, /* val */
132 TK_M_DRIVER, /* val */
133 TK_M_WAITFOR, /* val */
134 TK_M_ATTR, /* val, attr */
f4cf2e5b 135 TK_M_SYSCTL, /* val, attr */
912541b0
KS
136
137 TK_M_PARENTS_MIN,
a1525d17 138 TK_M_KERNELS, /* val */
912541b0 139 TK_M_SUBSYSTEMS, /* val */
a1525d17
KS
140 TK_M_DRIVERS, /* val */
141 TK_M_ATTRS, /* val, attr */
142 TK_M_TAGS, /* val */
912541b0
KS
143 TK_M_PARENTS_MAX,
144
a1525d17 145 TK_M_TEST, /* val, mode_t */
a1525d17
KS
146 TK_M_PROGRAM, /* val */
147 TK_M_IMPORT_FILE, /* val */
148 TK_M_IMPORT_PROG, /* val */
149 TK_M_IMPORT_BUILTIN, /* val */
150 TK_M_IMPORT_DB, /* val */
151 TK_M_IMPORT_CMDLINE, /* val */
152 TK_M_IMPORT_PARENT, /* val */
153 TK_M_RESULT, /* val */
912541b0
KS
154 TK_M_MAX,
155
156 TK_A_STRING_ESCAPE_NONE,
157 TK_A_STRING_ESCAPE_REPLACE,
158 TK_A_DB_PERSIST,
a1525d17
KS
159 TK_A_INOTIFY_WATCH, /* int */
160 TK_A_DEVLINK_PRIO, /* int */
161 TK_A_OWNER, /* val */
162 TK_A_GROUP, /* val */
163 TK_A_MODE, /* val */
164 TK_A_OWNER_ID, /* uid_t */
165 TK_A_GROUP_ID, /* gid_t */
166 TK_A_MODE_ID, /* mode_t */
84b6ad70 167 TK_A_TAG, /* val */
a1525d17 168 TK_A_STATIC_NODE, /* val */
c26547d6 169 TK_A_SECLABEL, /* val, attr */
a1525d17 170 TK_A_ENV, /* val, attr */
a1525d17
KS
171 TK_A_NAME, /* val */
172 TK_A_DEVLINK, /* val */
173 TK_A_ATTR, /* val, attr */
f4cf2e5b 174 TK_A_SYSCTL, /* val, attr */
83cd6b75
KS
175 TK_A_RUN_BUILTIN, /* val, bool */
176 TK_A_RUN_PROGRAM, /* val, bool */
a1525d17 177 TK_A_GOTO, /* size_t */
912541b0
KS
178
179 TK_END,
c7521974
KS
180};
181
3f3aa9f5 182/* we try to pack stuff in a way that we take only 12 bytes per token */
4052400f 183struct token {
912541b0
KS
184 union {
185 unsigned char type; /* same in rule and key */
186 struct {
187 enum token_type type:8;
188 bool can_set_name:1;
189 bool has_static_node:1;
14cb109d 190 unsigned unused:6;
912541b0 191 unsigned short token_count;
14cb109d 192 unsigned label_off;
912541b0
KS
193 unsigned short filename_off;
194 unsigned short filename_line;
195 } rule;
196 struct {
197 enum token_type type:8;
198 enum operation_type op:8;
199 enum string_glob_type glob:8;
200 enum string_subst_type subst:4;
201 enum string_subst_type attrsubst:4;
14cb109d 202 unsigned value_off;
912541b0 203 union {
14cb109d
YW
204 unsigned attr_off;
205 unsigned rule_goto;
49c603bd 206 mode_t mode;
912541b0
KS
207 uid_t uid;
208 gid_t gid;
209 int devlink_prio;
912541b0
KS
210 int watch;
211 enum udev_builtin_cmd builtin_cmd;
212 };
213 } key;
214 };
4052400f
KS
215};
216
912541b0 217#define MAX_TK 64
4052400f 218struct rule_tmp {
9a07157d 219 UdevRules *rules;
912541b0
KS
220 struct token rule;
221 struct token token[MAX_TK];
14cb109d 222 unsigned token_cur;
4052400f
KS
223};
224
20e97dd3 225#if ENABLE_DEBUG_UDEV
9ec6e95b 226static const char *operation_str(enum operation_type type) {
912541b0 227 static const char *operation_strs[] = {
a1525d17
KS
228 [OP_UNSET] = "UNSET",
229 [OP_MATCH] = "match",
230 [OP_NOMATCH] = "nomatch",
912541b0
KS
231 [OP_MATCH_MAX] = "MATCH_MAX",
232
a1525d17 233 [OP_ADD] = "add",
8e3ba377 234 [OP_REMOVE] = "remove",
a1525d17
KS
235 [OP_ASSIGN] = "assign",
236 [OP_ASSIGN_FINAL] = "assign-final",
49c603bd 237 };
912541b0
KS
238
239 return operation_strs[type];
5d6a1fa6 240}
4052400f 241
9ec6e95b 242static const char *string_glob_str(enum string_glob_type type) {
912541b0 243 static const char *string_glob_strs[] = {
a1525d17
KS
244 [GL_UNSET] = "UNSET",
245 [GL_PLAIN] = "plain",
246 [GL_GLOB] = "glob",
247 [GL_SPLIT] = "split",
248 [GL_SPLIT_GLOB] = "split-glob",
249 [GL_SOMETHING] = "split-glob",
912541b0
KS
250 };
251
252 return string_glob_strs[type];
5d6a1fa6
KS
253}
254
9ec6e95b 255static const char *token_str(enum token_type type) {
912541b0 256 static const char *token_strs[] = {
a1525d17
KS
257 [TK_UNSET] = "UNSET",
258 [TK_RULE] = "RULE",
912541b0 259
a1525d17 260 [TK_M_ACTION] = "M ACTION",
912541b0 261 [TK_M_DEVPATH] = "M DEVPATH",
a1525d17 262 [TK_M_KERNEL] = "M KERNEL",
912541b0 263 [TK_M_DEVLINK] = "M DEVLINK",
a1525d17
KS
264 [TK_M_NAME] = "M NAME",
265 [TK_M_ENV] = "M ENV",
266 [TK_M_TAG] = "M TAG",
267 [TK_M_SUBSYSTEM] = "M SUBSYSTEM",
268 [TK_M_DRIVER] = "M DRIVER",
912541b0 269 [TK_M_WAITFOR] = "M WAITFOR",
a1525d17 270 [TK_M_ATTR] = "M ATTR",
f4cf2e5b 271 [TK_M_SYSCTL] = "M SYSCTL",
912541b0 272
a1525d17 273 [TK_M_PARENTS_MIN] = "M PARENTS_MIN",
912541b0 274 [TK_M_KERNELS] = "M KERNELS",
a1525d17 275 [TK_M_SUBSYSTEMS] = "M SUBSYSTEMS",
912541b0 276 [TK_M_DRIVERS] = "M DRIVERS",
a1525d17
KS
277 [TK_M_ATTRS] = "M ATTRS",
278 [TK_M_TAGS] = "M TAGS",
279 [TK_M_PARENTS_MAX] = "M PARENTS_MAX",
912541b0 280
a1525d17 281 [TK_M_TEST] = "M TEST",
912541b0 282 [TK_M_PROGRAM] = "M PROGRAM",
a1525d17
KS
283 [TK_M_IMPORT_FILE] = "M IMPORT_FILE",
284 [TK_M_IMPORT_PROG] = "M IMPORT_PROG",
285 [TK_M_IMPORT_BUILTIN] = "M IMPORT_BUILTIN",
286 [TK_M_IMPORT_DB] = "M IMPORT_DB",
287 [TK_M_IMPORT_CMDLINE] = "M IMPORT_CMDLINE",
288 [TK_M_IMPORT_PARENT] = "M IMPORT_PARENT",
289 [TK_M_RESULT] = "M RESULT",
290 [TK_M_MAX] = "M MAX",
291
292 [TK_A_STRING_ESCAPE_NONE] = "A STRING_ESCAPE_NONE",
293 [TK_A_STRING_ESCAPE_REPLACE] = "A STRING_ESCAPE_REPLACE",
294 [TK_A_DB_PERSIST] = "A DB_PERSIST",
295 [TK_A_INOTIFY_WATCH] = "A INOTIFY_WATCH",
296 [TK_A_DEVLINK_PRIO] = "A DEVLINK_PRIO",
297 [TK_A_OWNER] = "A OWNER",
298 [TK_A_GROUP] = "A GROUP",
299 [TK_A_MODE] = "A MODE",
300 [TK_A_OWNER_ID] = "A OWNER_ID",
301 [TK_A_GROUP_ID] = "A GROUP_ID",
302 [TK_A_STATIC_NODE] = "A STATIC_NODE",
c26547d6 303 [TK_A_SECLABEL] = "A SECLABEL",
912541b0 304 [TK_A_MODE_ID] = "A MODE_ID",
a1525d17
KS
305 [TK_A_ENV] = "A ENV",
306 [TK_A_TAG] = "A ENV",
307 [TK_A_NAME] = "A NAME",
912541b0 308 [TK_A_DEVLINK] = "A DEVLINK",
a1525d17 309 [TK_A_ATTR] = "A ATTR",
f4cf2e5b 310 [TK_A_SYSCTL] = "A SYSCTL",
83cd6b75
KS
311 [TK_A_RUN_BUILTIN] = "A RUN_BUILTIN",
312 [TK_A_RUN_PROGRAM] = "A RUN_PROGRAM",
a1525d17 313 [TK_A_GOTO] = "A GOTO",
912541b0 314
a1525d17 315 [TK_END] = "END",
912541b0
KS
316 };
317
318 return token_strs[type];
5d6a1fa6 319}
c7521974 320
9a07157d 321static void dump_token(UdevRules *rules, struct token *token) {
912541b0
KS
322 enum token_type type = token->type;
323 enum operation_type op = token->key.op;
324 enum string_glob_type glob = token->key.glob;
fa394301
LR
325 const char *value = rules_str(rules, token->key.value_off);
326 const char *attr = &rules->strbuf->buf[token->key.attr_off];
912541b0
KS
327
328 switch (type) {
329 case TK_RULE:
330 {
331 const char *tks_ptr = (char *)rules->tokens;
332 const char *tk_ptr = (char *)token;
14cb109d 333 unsigned idx = (tk_ptr - tks_ptr) / sizeof(struct token);
912541b0 334
9f6445e3 335 log_debug("* RULE %s:%u, token: %u, count: %u, label: '%s'",
fa394301 336 &rules->strbuf->buf[token->rule.filename_off], token->rule.filename_line,
baa30fbc 337 idx, token->rule.token_count,
fa394301 338 &rules->strbuf->buf[token->rule.label_off]);
912541b0
KS
339 break;
340 }
341 case TK_M_ACTION:
342 case TK_M_DEVPATH:
343 case TK_M_KERNEL:
344 case TK_M_SUBSYSTEM:
345 case TK_M_DRIVER:
346 case TK_M_WAITFOR:
347 case TK_M_DEVLINK:
348 case TK_M_NAME:
349 case TK_M_KERNELS:
350 case TK_M_SUBSYSTEMS:
351 case TK_M_DRIVERS:
352 case TK_M_TAGS:
353 case TK_M_PROGRAM:
354 case TK_M_IMPORT_FILE:
355 case TK_M_IMPORT_PROG:
356 case TK_M_IMPORT_DB:
357 case TK_M_IMPORT_CMDLINE:
358 case TK_M_IMPORT_PARENT:
359 case TK_M_RESULT:
360 case TK_A_NAME:
361 case TK_A_DEVLINK:
362 case TK_A_OWNER:
363 case TK_A_GROUP:
364 case TK_A_MODE:
83cd6b75
KS
365 case TK_A_RUN_BUILTIN:
366 case TK_A_RUN_PROGRAM:
9f6445e3 367 log_debug("%s %s '%s'(%s)",
baa30fbc 368 token_str(type), operation_str(op), value, string_glob_str(glob));
912541b0
KS
369 break;
370 case TK_M_IMPORT_BUILTIN:
9f6445e3 371 log_debug("%s %i '%s'", token_str(type), token->key.builtin_cmd, value);
912541b0
KS
372 break;
373 case TK_M_ATTR:
f4cf2e5b 374 case TK_M_SYSCTL:
912541b0
KS
375 case TK_M_ATTRS:
376 case TK_M_ENV:
377 case TK_A_ATTR:
f4cf2e5b 378 case TK_A_SYSCTL:
912541b0 379 case TK_A_ENV:
9f6445e3 380 log_debug("%s %s '%s' '%s'(%s)",
baa30fbc 381 token_str(type), operation_str(op), attr, value, string_glob_str(glob));
912541b0
KS
382 break;
383 case TK_M_TAG:
384 case TK_A_TAG:
9f6445e3 385 log_debug("%s %s '%s'", token_str(type), operation_str(op), value);
912541b0
KS
386 break;
387 case TK_A_STRING_ESCAPE_NONE:
388 case TK_A_STRING_ESCAPE_REPLACE:
389 case TK_A_DB_PERSIST:
9f6445e3 390 log_debug("%s", token_str(type));
912541b0
KS
391 break;
392 case TK_M_TEST:
9f6445e3 393 log_debug("%s %s '%s'(%s) %#o",
baa30fbc 394 token_str(type), operation_str(op), value, string_glob_str(glob), token->key.mode);
912541b0
KS
395 break;
396 case TK_A_INOTIFY_WATCH:
9f6445e3 397 log_debug("%s %u", token_str(type), token->key.watch);
912541b0
KS
398 break;
399 case TK_A_DEVLINK_PRIO:
9f6445e3 400 log_debug("%s %u", token_str(type), token->key.devlink_prio);
912541b0
KS
401 break;
402 case TK_A_OWNER_ID:
9f6445e3 403 log_debug("%s %s %u", token_str(type), operation_str(op), token->key.uid);
912541b0
KS
404 break;
405 case TK_A_GROUP_ID:
9f6445e3 406 log_debug("%s %s %u", token_str(type), operation_str(op), token->key.gid);
912541b0
KS
407 break;
408 case TK_A_MODE_ID:
9f6445e3 409 log_debug("%s %s %#o", token_str(type), operation_str(op), token->key.mode);
912541b0
KS
410 break;
411 case TK_A_STATIC_NODE:
9f6445e3 412 log_debug("%s '%s'", token_str(type), value);
912541b0 413 break;
c26547d6 414 case TK_A_SECLABEL:
9f6445e3 415 log_debug("%s %s '%s' '%s'", token_str(type), operation_str(op), attr, value);
c26547d6 416 break;
912541b0 417 case TK_A_GOTO:
9f6445e3 418 log_debug("%s '%s' %u", token_str(type), value, token->key.rule_goto);
912541b0
KS
419 break;
420 case TK_END:
9f6445e3 421 log_debug("* %s", token_str(type));
912541b0
KS
422 break;
423 case TK_M_PARENTS_MIN:
424 case TK_M_PARENTS_MAX:
425 case TK_M_MAX:
426 case TK_UNSET:
8c19dc54 427 log_debug("Unknown token type %u", type);
912541b0
KS
428 break;
429 }
4052400f 430}
154a7b84 431
9a07157d 432static void dump_rules(UdevRules *rules) {
14cb109d 433 unsigned i;
912541b0 434
8c19dc54 435 log_debug("Dumping %u (%zu bytes) tokens, %zu (%zu bytes) strings",
baa30fbc
KS
436 rules->token_cur,
437 rules->token_cur * sizeof(struct token),
fa394301
LR
438 rules->strbuf->nodes_count,
439 rules->strbuf->len);
f168c273 440 for (i = 0; i < rules->token_cur; i++)
912541b0 441 dump_token(rules, &rules->tokens[i]);
4052400f
KS
442}
443#else
a1e92eee
TM
444static void dump_token(UdevRules *rules, struct token *token) {}
445static void dump_rules(UdevRules *rules) {}
20e97dd3 446#endif /* ENABLE_DEBUG_UDEV */
c7521974 447
9a07157d 448static int add_token(UdevRules *rules, struct token *token) {
912541b0
KS
449 /* grow buffer if needed */
450 if (rules->token_cur+1 >= rules->token_max) {
451 struct token *tokens;
14cb109d 452 unsigned add;
912541b0
KS
453
454 /* double the buffer size */
455 add = rules->token_max;
456 if (add < 8)
457 add = 8;
458
62d74c78 459 tokens = reallocarray(rules->tokens, rules->token_max + add, sizeof(struct token));
67e4b385 460 if (!tokens)
912541b0 461 return -1;
912541b0
KS
462 rules->tokens = tokens;
463 rules->token_max += add;
464 }
465 memcpy(&rules->tokens[rules->token_cur], token, sizeof(struct token));
466 rules->token_cur++;
467 return 0;
c7521974 468}
a27cd06c 469
b4ba2fe3 470static void log_unknown_owner(sd_device *dev, int error, const char *entity, const char *owner) {
2da03cbf 471 if (IN_SET(abs(error), ENOENT, ESRCH))
b4ba2fe3 472 log_device_error(dev, "Specified %s '%s' unknown", entity, owner);
2da03cbf 473 else
b4ba2fe3 474 log_device_error_errno(dev, error, "Failed to resolve %s '%s': %m", entity, owner);
2da03cbf
ZJS
475}
476
9a07157d 477static uid_t add_uid(UdevRules *rules, const char *owner) {
14cb109d 478 unsigned i;
23bf8dd7 479 uid_t uid = 0;
14cb109d 480 unsigned off;
23bf8dd7 481 int r;
912541b0
KS
482
483 /* lookup, if we know it already */
484 for (i = 0; i < rules->uids_cur; i++) {
485 off = rules->uids[i].name_off;
915bf0f6 486 if (streq(rules_str(rules, off), owner)) {
912541b0 487 uid = rules->uids[i].uid;
912541b0
KS
488 return uid;
489 }
490 }
fafff8f1 491 r = get_user_creds(&owner, &uid, NULL, NULL, NULL, USER_CREDS_ALLOW_MISSING);
2da03cbf 492 if (r < 0)
b4ba2fe3 493 log_unknown_owner(NULL, r, "user", owner);
912541b0
KS
494
495 /* grow buffer if needed */
496 if (rules->uids_cur+1 >= rules->uids_max) {
497 struct uid_gid *uids;
14cb109d 498 unsigned add;
912541b0
KS
499
500 /* double the buffer size */
501 add = rules->uids_max;
502 if (add < 1)
503 add = 8;
504
62d74c78 505 uids = reallocarray(rules->uids, rules->uids_max + add, sizeof(struct uid_gid));
67e4b385 506 if (!uids)
912541b0 507 return uid;
912541b0
KS
508 rules->uids = uids;
509 rules->uids_max += add;
510 }
511 rules->uids[rules->uids_cur].uid = uid;
915bf0f6 512 off = rules_add_string(rules, owner);
912541b0
KS
513 if (off <= 0)
514 return uid;
515 rules->uids[rules->uids_cur].name_off = off;
516 rules->uids_cur++;
517 return uid;
154a7b84
KS
518}
519
9a07157d 520static gid_t add_gid(UdevRules *rules, const char *group) {
14cb109d 521 unsigned i;
23bf8dd7 522 gid_t gid = 0;
14cb109d 523 unsigned off;
23bf8dd7 524 int r;
912541b0
KS
525
526 /* lookup, if we know it already */
527 for (i = 0; i < rules->gids_cur; i++) {
528 off = rules->gids[i].name_off;
915bf0f6 529 if (streq(rules_str(rules, off), group)) {
912541b0 530 gid = rules->gids[i].gid;
912541b0
KS
531 return gid;
532 }
533 }
fafff8f1 534 r = get_group_creds(&group, &gid, USER_CREDS_ALLOW_MISSING);
2da03cbf 535 if (r < 0)
b4ba2fe3 536 log_unknown_owner(NULL, r, "group", group);
912541b0
KS
537
538 /* grow buffer if needed */
539 if (rules->gids_cur+1 >= rules->gids_max) {
540 struct uid_gid *gids;
14cb109d 541 unsigned add;
912541b0
KS
542
543 /* double the buffer size */
544 add = rules->gids_max;
545 if (add < 1)
546 add = 8;
547
62d74c78 548 gids = reallocarray(rules->gids, rules->gids_max + add, sizeof(struct uid_gid));
67e4b385 549 if (!gids)
912541b0 550 return gid;
912541b0
KS
551 rules->gids = gids;
552 rules->gids_max += add;
553 }
554 rules->gids[rules->gids_cur].gid = gid;
915bf0f6 555 off = rules_add_string(rules, group);
912541b0
KS
556 if (off <= 0)
557 return gid;
558 rules->gids[rules->gids_cur].name_off = off;
559 rules->gids_cur++;
560 return gid;
154a7b84
KS
561}
562
29b5eb5a 563static int import_property_from_string(sd_device *dev, char *line) {
912541b0
KS
564 char *key;
565 char *val;
566 size_t len;
567
568 /* find key */
569 key = line;
570 while (isspace(key[0]))
571 key++;
572
573 /* comment or empty line */
4c701096 574 if (IN_SET(key[0], '#', '\0'))
29b5eb5a 575 return 0;
912541b0
KS
576
577 /* split key/value */
578 val = strchr(key, '=');
29b5eb5a
YW
579 if (!val)
580 return -EINVAL;
912541b0
KS
581 val[0] = '\0';
582 val++;
583
584 /* find value */
585 while (isspace(val[0]))
586 val++;
587
588 /* terminate key */
589 len = strlen(key);
590 if (len == 0)
29b5eb5a 591 return -EINVAL;
912541b0
KS
592 while (isspace(key[len-1]))
593 len--;
594 key[len] = '\0';
595
596 /* terminate value */
597 len = strlen(val);
598 if (len == 0)
29b5eb5a 599 return -EINVAL;
912541b0
KS
600 while (isspace(val[len-1]))
601 len--;
602 val[len] = '\0';
603
604 if (len == 0)
29b5eb5a 605 return -EINVAL;
912541b0
KS
606
607 /* unquote */
4c701096 608 if (IN_SET(val[0], '"', '\'')) {
baaa35ad
ZJS
609 if (len == 1 || val[len-1] != val[0])
610 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
8c19dc54 611 "Inconsistent quoting: '%s', skip",
baaa35ad 612 line);
912541b0
KS
613 val[len-1] = '\0';
614 val++;
615 }
616
29b5eb5a 617 return device_add_property(dev, key, val);
be4bedd1
KS
618}
619
13c7b75f 620static int import_file_into_properties(sd_device *dev, const char *filename) {
fae0f8a0
LP
621 _cleanup_fclose_ FILE *f = NULL;
622 int r;
912541b0 623
47ef94ac 624 f = fopen(filename, "re");
fae0f8a0
LP
625 if (!f)
626 return -errno;
627
628 for (;;) {
629 _cleanup_free_ char *line = NULL;
630
631 r = read_line(f, LONG_LINE_MAX, &line);
632 if (r < 0)
633 return r;
634 if (r == 0)
635 break;
636
13c7b75f 637 (void) import_property_from_string(dev, line);
fae0f8a0
LP
638 }
639
912541b0 640 return 0;
bd0ed2ff
KS
641}
642
2e088715 643static int import_program_into_properties(UdevEvent *event,
dd5eddd2 644 usec_t timeout_usec,
8314de1d 645 const char *program) {
912541b0
KS
646 char result[UTIL_LINE_SIZE];
647 char *line;
a7521142 648 int r;
912541b0 649
a7521142
ZJS
650 r = udev_event_spawn(event, timeout_usec, false, program, result, sizeof result);
651 if (r < 0)
652 return r;
653 if (r > 0)
654 return -EIO;
912541b0
KS
655
656 line = result;
67e4b385 657 while (line) {
912541b0
KS
658 char *pos;
659
660 pos = strchr(line, '\n');
67e4b385 661 if (pos) {
912541b0
KS
662 pos[0] = '\0';
663 pos = &pos[1];
664 }
cf28ad46 665 (void) import_property_from_string(event->dev, line);
912541b0
KS
666 line = pos;
667 }
668 return 0;
319c6700
KS
669}
670
1ce7fecb
YW
671static int import_parent_into_properties(sd_device *dev, const char *filter) {
672 const char *key, *val;
673 sd_device *parent;
674 int r;
912541b0 675
3b64e4d4
TG
676 assert(dev);
677 assert(filter);
678
1ce7fecb
YW
679 r = sd_device_get_parent(dev, &parent);
680 if (r < 0)
681 return r;
912541b0 682
1ce7fecb 683 FOREACH_DEVICE_PROPERTY(parent, key, val)
ece174c5 684 if (fnmatch(filter, key, 0) == 0)
1ce7fecb 685 device_add_property(dev, key, val);
912541b0 686 return 0;
e2ecb34f
KS
687}
688
f4850a1d
ZJS
689static void attr_subst_subdir(char *attr, size_t len) {
690 const char *pos, *tail, *path;
691 _cleanup_closedir_ DIR *dir = NULL;
692 struct dirent *dent;
693
694 pos = strstr(attr, "/*/");
695 if (!pos)
696 return;
697
698 tail = pos + 2;
699 path = strndupa(attr, pos - attr + 1); /* include slash at end */
700 dir = opendir(path);
67e4b385 701 if (!dir)
f4850a1d
ZJS
702 return;
703
8fb3f009 704 FOREACH_DIRENT_ALL(dent, dir, break)
f4850a1d 705 if (dent->d_name[0] != '.') {
916a8d43 706 char n[strlen(dent->d_name) + strlen(tail) + 1];
f4850a1d 707
916a8d43
ZJS
708 strscpyl(n, sizeof n, dent->d_name, tail, NULL);
709 if (faccessat(dirfd(dir), n, F_OK, 0) == 0) {
f4850a1d
ZJS
710 strscpyl(attr, len, path, n, NULL);
711 break;
912541b0 712 }
912541b0 713 }
0ea5e96e
KS
714}
715
2024ed61 716static int get_key(char **line, char **key, enum operation_type *op, char **value) {
912541b0
KS
717 char *linepos;
718 char *temp;
7e760b79 719 unsigned i, j;
912541b0
KS
720
721 linepos = *line;
67e4b385 722 if (!linepos || linepos[0] == '\0')
912541b0
KS
723 return -1;
724
725 /* skip whitespace */
726 while (isspace(linepos[0]) || linepos[0] == ',')
727 linepos++;
728
729 /* get the key */
730 if (linepos[0] == '\0')
731 return -1;
732 *key = linepos;
733
734 for (;;) {
735 linepos++;
736 if (linepos[0] == '\0')
737 return -1;
738 if (isspace(linepos[0]))
739 break;
740 if (linepos[0] == '=')
741 break;
4c701096 742 if (IN_SET(linepos[0], '+', '-', '!', ':'))
912541b0
KS
743 if (linepos[1] == '=')
744 break;
745 }
746
747 /* remember end of key */
748 temp = linepos;
749
750 /* skip whitespace after key */
751 while (isspace(linepos[0]))
752 linepos++;
753 if (linepos[0] == '\0')
754 return -1;
755
756 /* get operation type */
757 if (linepos[0] == '=' && linepos[1] == '=') {
758 *op = OP_MATCH;
759 linepos += 2;
760 } else if (linepos[0] == '!' && linepos[1] == '=') {
761 *op = OP_NOMATCH;
762 linepos += 2;
763 } else if (linepos[0] == '+' && linepos[1] == '=') {
764 *op = OP_ADD;
765 linepos += 2;
8e3ba377
DH
766 } else if (linepos[0] == '-' && linepos[1] == '=') {
767 *op = OP_REMOVE;
768 linepos += 2;
912541b0
KS
769 } else if (linepos[0] == '=') {
770 *op = OP_ASSIGN;
771 linepos++;
772 } else if (linepos[0] == ':' && linepos[1] == '=') {
773 *op = OP_ASSIGN_FINAL;
774 linepos += 2;
775 } else
776 return -1;
777
778 /* terminate key */
779 temp[0] = '\0';
780
781 /* skip whitespace after operator */
782 while (isspace(linepos[0]))
783 linepos++;
784 if (linepos[0] == '\0')
785 return -1;
786
787 /* get the value */
788 if (linepos[0] == '"')
789 linepos++;
790 else
791 return -1;
792 *value = linepos;
793
794 /* terminate */
7e760b79
FB
795 for (i = 0, j = 0; ; i++, j++) {
796
797 if (linepos[i] == '"')
798 break;
799
800 if (linepos[i] == '\0')
801 return -1;
802
803 /* double quotes can be escaped */
804 if (linepos[i] == '\\')
805 if (linepos[i+1] == '"')
806 i++;
807
808 linepos[j] = linepos[i];
809 }
810 linepos[j] = '\0';
912541b0
KS
811
812 /* move line to next key */
7e760b79 813 *line = linepos + i + 1;
912541b0 814 return 0;
6880b25d 815}
95776dc6 816
6880b25d 817/* extract possible KEY{attr} */
2024ed61 818static const char *get_key_attribute(char *str) {
912541b0
KS
819 char *pos;
820 char *attr;
821
822 attr = strchr(str, '{');
67e4b385 823 if (attr) {
912541b0
KS
824 attr++;
825 pos = strchr(attr, '}');
67e4b385 826 if (!pos) {
25f027c5 827 log_error("Missing closing brace for format");
912541b0
KS
828 return NULL;
829 }
830 pos[0] = '\0';
912541b0
KS
831 return attr;
832 }
833 return NULL;
6880b25d 834}
95776dc6 835
19a8e656
ZJS
836static void rule_add_key(struct rule_tmp *rule_tmp, enum token_type type,
837 enum operation_type op,
838 const char *value, const void *data) {
839 struct token *token = rule_tmp->token + rule_tmp->token_cur;
912541b0
KS
840 const char *attr = NULL;
841
19a8e656 842 assert(rule_tmp->token_cur < ELEMENTSOF(rule_tmp->token));
29804cc1 843 memzero(token, sizeof(struct token));
912541b0
KS
844
845 switch (type) {
846 case TK_M_ACTION:
847 case TK_M_DEVPATH:
848 case TK_M_KERNEL:
849 case TK_M_SUBSYSTEM:
850 case TK_M_DRIVER:
851 case TK_M_WAITFOR:
852 case TK_M_DEVLINK:
853 case TK_M_NAME:
854 case TK_M_KERNELS:
855 case TK_M_SUBSYSTEMS:
856 case TK_M_DRIVERS:
857 case TK_M_TAGS:
858 case TK_M_PROGRAM:
859 case TK_M_IMPORT_FILE:
860 case TK_M_IMPORT_PROG:
861 case TK_M_IMPORT_DB:
862 case TK_M_IMPORT_CMDLINE:
863 case TK_M_IMPORT_PARENT:
864 case TK_M_RESULT:
865 case TK_A_OWNER:
866 case TK_A_GROUP:
867 case TK_A_MODE:
8a173387 868 case TK_A_DEVLINK:
912541b0
KS
869 case TK_A_NAME:
870 case TK_A_GOTO:
871 case TK_M_TAG:
872 case TK_A_TAG:
d6f116a7 873 case TK_A_STATIC_NODE:
915bf0f6 874 token->key.value_off = rules_add_string(rule_tmp->rules, value);
912541b0
KS
875 break;
876 case TK_M_IMPORT_BUILTIN:
915bf0f6 877 token->key.value_off = rules_add_string(rule_tmp->rules, value);
912541b0
KS
878 token->key.builtin_cmd = *(enum udev_builtin_cmd *)data;
879 break;
880 case TK_M_ENV:
881 case TK_M_ATTR:
f4cf2e5b 882 case TK_M_SYSCTL:
912541b0
KS
883 case TK_M_ATTRS:
884 case TK_A_ATTR:
f4cf2e5b 885 case TK_A_SYSCTL:
912541b0 886 case TK_A_ENV:
c26547d6 887 case TK_A_SECLABEL:
912541b0 888 attr = data;
915bf0f6
KS
889 token->key.value_off = rules_add_string(rule_tmp->rules, value);
890 token->key.attr_off = rules_add_string(rule_tmp->rules, attr);
912541b0 891 break;
912541b0 892 case TK_M_TEST:
915bf0f6 893 token->key.value_off = rules_add_string(rule_tmp->rules, value);
67e4b385 894 if (data)
912541b0
KS
895 token->key.mode = *(mode_t *)data;
896 break;
897 case TK_A_STRING_ESCAPE_NONE:
898 case TK_A_STRING_ESCAPE_REPLACE:
899 case TK_A_DB_PERSIST:
900 break;
83cd6b75 901 case TK_A_RUN_BUILTIN:
83cd6b75 902 case TK_A_RUN_PROGRAM:
4590cfe4 903 token->key.builtin_cmd = *(enum udev_builtin_cmd *)data;
915bf0f6 904 token->key.value_off = rules_add_string(rule_tmp->rules, value);
912541b0
KS
905 break;
906 case TK_A_INOTIFY_WATCH:
907 case TK_A_DEVLINK_PRIO:
908 token->key.devlink_prio = *(int *)data;
909 break;
910 case TK_A_OWNER_ID:
911 token->key.uid = *(uid_t *)data;
912 break;
913 case TK_A_GROUP_ID:
914 token->key.gid = *(gid_t *)data;
915 break;
916 case TK_A_MODE_ID:
917 token->key.mode = *(mode_t *)data;
918 break;
912541b0
KS
919 case TK_RULE:
920 case TK_M_PARENTS_MIN:
921 case TK_M_PARENTS_MAX:
922 case TK_M_MAX:
923 case TK_END:
924 case TK_UNSET:
19a8e656 925 assert_not_reached("wrong type");
912541b0
KS
926 }
927
67e4b385 928 if (value && type < TK_M_MAX) {
912541b0
KS
929 /* check if we need to split or call fnmatch() while matching rules */
930 enum string_glob_type glob;
67e4b385 931 bool has_split, has_glob;
912541b0 932
67e4b385 933 has_split = strchr(value, '|');
e3e0314b 934 has_glob = string_is_glob(value);
67e4b385 935 if (has_split && has_glob)
912541b0 936 glob = GL_SPLIT_GLOB;
67e4b385 937 else if (has_split)
912541b0 938 glob = GL_SPLIT;
67e4b385 939 else if (has_glob) {
33502ffe 940 if (streq(value, "?*"))
912541b0
KS
941 glob = GL_SOMETHING;
942 else
943 glob = GL_GLOB;
67e4b385 944 } else
912541b0 945 glob = GL_PLAIN;
67e4b385 946
912541b0
KS
947 token->key.glob = glob;
948 }
949
67e4b385 950 if (value && type > TK_M_MAX) {
912541b0
KS
951 /* check if assigned value has substitution chars */
952 if (value[0] == '[')
953 token->key.subst = SB_SUBSYS;
67e4b385 954 else if (strchr(value, '%') || strchr(value, '$'))
912541b0
KS
955 token->key.subst = SB_FORMAT;
956 else
957 token->key.subst = SB_NONE;
958 }
959
67e4b385 960 if (attr) {
d6f116a7 961 /* check if property/attribute name has substitution chars */
912541b0
KS
962 if (attr[0] == '[')
963 token->key.attrsubst = SB_SUBSYS;
67e4b385 964 else if (strchr(attr, '%') || strchr(attr, '$'))
912541b0
KS
965 token->key.attrsubst = SB_FORMAT;
966 else
967 token->key.attrsubst = SB_NONE;
968 }
969
970 token->key.type = type;
971 token->key.op = op;
972 rule_tmp->token_cur++;
6880b25d 973}
e57e7bc1 974
9a07157d 975static int sort_token(UdevRules *rules, struct rule_tmp *rule_tmp) {
14cb109d
YW
976 unsigned i;
977 unsigned start = 0;
978 unsigned end = rule_tmp->token_cur;
912541b0
KS
979
980 for (i = 0; i < rule_tmp->token_cur; i++) {
981 enum token_type next_val = TK_UNSET;
14cb109d
YW
982 unsigned next_idx = 0;
983 unsigned j;
912541b0
KS
984
985 /* find smallest value */
986 for (j = start; j < end; j++) {
987 if (rule_tmp->token[j].type == TK_UNSET)
988 continue;
989 if (next_val == TK_UNSET || rule_tmp->token[j].type < next_val) {
990 next_val = rule_tmp->token[j].type;
991 next_idx = j;
992 }
993 }
994
995 /* add token and mark done */
996 if (add_token(rules, &rule_tmp->token[next_idx]) != 0)
997 return -1;
998 rule_tmp->token[next_idx].type = TK_UNSET;
999
1000 /* shrink range */
1001 if (next_idx == start)
1002 start++;
1003 if (next_idx+1 == end)
1004 end--;
1005 }
1006 return 0;
724257d9
GKH
1007}
1008
8c19dc54
YW
1009#define LOG_RULE_FULL(level, fmt, ...) log_full(level, "%s:%u: " fmt, filename, lineno, ##__VA_ARGS__)
1010#define LOG_RULE_ERROR(fmt, ...) LOG_RULE_FULL(LOG_ERR, fmt, ##__VA_ARGS__)
1011#define LOG_RULE_WARNING(fmt, ...) LOG_RULE_FULL(LOG_WARNING, fmt, ##__VA_ARGS__)
1012#define LOG_RULE_DEBUG(fmt, ...) LOG_RULE_FULL(LOG_DEBUG, fmt, ##__VA_ARGS__)
19a8e656
ZJS
1013#define LOG_AND_RETURN(fmt, ...) { LOG_RULE_ERROR(fmt, __VA_ARGS__); return; }
1014
9a07157d 1015static void add_rule(UdevRules *rules, char *line,
14cb109d 1016 const char *filename, unsigned filename_off, unsigned lineno) {
912541b0 1017 char *linepos;
04a9d3a0 1018 const char *attr;
84198c18
TG
1019 struct rule_tmp rule_tmp = {
1020 .rules = rules,
1021 .rule.type = TK_RULE,
1022 };
912541b0 1023
775f8b3c
KS
1024 /* the offset in the rule is limited to unsigned short */
1025 if (filename_off < USHRT_MAX)
1026 rule_tmp.rule.rule.filename_off = filename_off;
912541b0
KS
1027 rule_tmp.rule.rule.filename_line = lineno;
1028
1029 linepos = line;
1030 for (;;) {
1031 char *key;
1032 char *value;
1033 enum operation_type op;
1034
2024ed61 1035 if (get_key(&linepos, &key, &op, &value) != 0) {
3cf0f8f7
DR
1036 /* Avoid erroring on trailing whitespace. This is probably rare
1037 * so save the work for the error case instead of always trying
1038 * to strip the trailing whitespace with strstrip(). */
1039 while (isblank(*linepos))
1040 linepos++;
1041
e736cf35
DR
1042 /* If we aren't at the end of the line, this is a parsing error.
1043 * Make a best effort to describe where the problem is. */
2783fe06 1044 if (!strchr(NEWLINE, *linepos)) {
6501b52d 1045 char buf[2] = {*linepos};
1291bc89
ZJS
1046 _cleanup_free_ char *tmp;
1047
1048 tmp = cescape(buf);
8c19dc54 1049 LOG_RULE_ERROR("Invalid key/value pair, starting at character %tu ('%s')", linepos - line + 1, tmp);
6501b52d 1050 if (*linepos == '#')
8c19dc54 1051 LOG_RULE_ERROR("Hint: comments can only start at beginning of line");
1291bc89 1052 }
912541b0 1053 break;
e736cf35 1054 }
912541b0 1055
19a8e656 1056 if (rule_tmp.token_cur >= ELEMENTSOF(rule_tmp.token))
8c19dc54 1057 LOG_AND_RETURN("Temporary rule array too small, aborting event processing with %u items", rule_tmp.token_cur);
19a8e656 1058
33502ffe 1059 if (streq(key, "ACTION")) {
19a8e656 1060 if (op > OP_MATCH_MAX)
8c19dc54 1061 LOG_AND_RETURN("Invalid %s operation", key);
19a8e656 1062
912541b0 1063 rule_add_key(&rule_tmp, TK_M_ACTION, op, value, NULL);
912541b0 1064
99f16bb8 1065 } else if (streq(key, "DEVPATH")) {
19a8e656 1066 if (op > OP_MATCH_MAX)
8c19dc54 1067 LOG_AND_RETURN("Invalid %s operation", key);
19a8e656 1068
912541b0 1069 rule_add_key(&rule_tmp, TK_M_DEVPATH, op, value, NULL);
912541b0 1070
99f16bb8 1071 } else if (streq(key, "KERNEL")) {
19a8e656 1072 if (op > OP_MATCH_MAX)
8c19dc54 1073 LOG_AND_RETURN("Invalid %s operation", key);
19a8e656 1074
912541b0 1075 rule_add_key(&rule_tmp, TK_M_KERNEL, op, value, NULL);
912541b0 1076
99f16bb8 1077 } else if (streq(key, "SUBSYSTEM")) {
19a8e656 1078 if (op > OP_MATCH_MAX)
8c19dc54 1079 LOG_AND_RETURN("Invalid %s operation", key);
19a8e656 1080
912541b0 1081 /* bus, class, subsystem events should all be the same */
99f16bb8
ZJS
1082 if (STR_IN_SET(value, "subsystem", "bus", "class")) {
1083 if (!streq(value, "subsystem"))
19a8e656
ZJS
1084 LOG_RULE_WARNING("'%s' must be specified as 'subsystem'; please fix", value);
1085
912541b0
KS
1086 rule_add_key(&rule_tmp, TK_M_SUBSYSTEM, op, "subsystem|class|bus", NULL);
1087 } else
1088 rule_add_key(&rule_tmp, TK_M_SUBSYSTEM, op, value, NULL);
912541b0 1089
99f16bb8 1090 } else if (streq(key, "DRIVER")) {
19a8e656 1091 if (op > OP_MATCH_MAX)
8c19dc54 1092 LOG_AND_RETURN("Invalid %s operation", key);
19a8e656 1093
912541b0 1094 rule_add_key(&rule_tmp, TK_M_DRIVER, op, value, NULL);
912541b0 1095
99f16bb8 1096 } else if (startswith(key, "ATTR{")) {
2024ed61 1097 attr = get_key_attribute(key + STRLEN("ATTR"));
67e4b385 1098 if (!attr)
8c19dc54 1099 LOG_AND_RETURN("Failed to parse %s attribute", "ATTR");
19a8e656
ZJS
1100
1101 if (op == OP_REMOVE)
8c19dc54 1102 LOG_AND_RETURN("Invalid %s operation", "ATTR");
19a8e656 1103
f4cf2e5b 1104 if (op < OP_MATCH_MAX)
912541b0 1105 rule_add_key(&rule_tmp, TK_M_ATTR, op, value, attr);
f4cf2e5b 1106 else
912541b0 1107 rule_add_key(&rule_tmp, TK_A_ATTR, op, value, attr);
f4cf2e5b 1108
99f16bb8 1109 } else if (startswith(key, "SYSCTL{")) {
2024ed61 1110 attr = get_key_attribute(key + STRLEN("SYSCTL"));
67e4b385 1111 if (!attr)
8c19dc54 1112 LOG_AND_RETURN("Failed to parse %s attribute", "ATTR");
19a8e656
ZJS
1113
1114 if (op == OP_REMOVE)
8c19dc54 1115 LOG_AND_RETURN("Invalid %s operation", "ATTR");
19a8e656 1116
f4cf2e5b
KS
1117 if (op < OP_MATCH_MAX)
1118 rule_add_key(&rule_tmp, TK_M_SYSCTL, op, value, attr);
1119 else
1120 rule_add_key(&rule_tmp, TK_A_SYSCTL, op, value, attr);
912541b0 1121
99f16bb8 1122 } else if (startswith(key, "SECLABEL{")) {
2024ed61 1123 attr = get_key_attribute(key + STRLEN("SECLABEL"));
67e4b385 1124 if (!attr)
8c19dc54 1125 LOG_AND_RETURN("Failed to parse %s attribute", "SECLABEL");
19a8e656
ZJS
1126
1127 if (op == OP_REMOVE)
8c19dc54 1128 LOG_AND_RETURN("Invalid %s operation", "SECLABEL");
c26547d6
KS
1129
1130 rule_add_key(&rule_tmp, TK_A_SECLABEL, op, value, attr);
c26547d6 1131
99f16bb8 1132 } else if (streq(key, "KERNELS")) {
19a8e656 1133 if (op > OP_MATCH_MAX)
8c19dc54 1134 LOG_AND_RETURN("Invalid %s operation", key);
19a8e656 1135
912541b0 1136 rule_add_key(&rule_tmp, TK_M_KERNELS, op, value, NULL);
912541b0 1137
99f16bb8 1138 } else if (streq(key, "SUBSYSTEMS")) {
19a8e656 1139 if (op > OP_MATCH_MAX)
8c19dc54 1140 LOG_AND_RETURN("Invalid %s operation", key);
19a8e656 1141
912541b0 1142 rule_add_key(&rule_tmp, TK_M_SUBSYSTEMS, op, value, NULL);
912541b0 1143
99f16bb8 1144 } else if (streq(key, "DRIVERS")) {
19a8e656 1145 if (op > OP_MATCH_MAX)
8c19dc54 1146 LOG_AND_RETURN("Invalid %s operation", key);
19a8e656 1147
912541b0 1148 rule_add_key(&rule_tmp, TK_M_DRIVERS, op, value, NULL);
912541b0 1149
99f16bb8 1150 } else if (startswith(key, "ATTRS{")) {
19a8e656 1151 if (op > OP_MATCH_MAX)
8c19dc54 1152 LOG_AND_RETURN("Invalid %s operation", "ATTRS");
19a8e656 1153
2024ed61 1154 attr = get_key_attribute(key + STRLEN("ATTRS"));
67e4b385 1155 if (!attr)
8c19dc54 1156 LOG_AND_RETURN("Failed to parse %s attribute", "ATTRS");
19a8e656 1157
33502ffe 1158 if (startswith(attr, "device/"))
19a8e656 1159 LOG_RULE_WARNING("'device' link may not be available in future kernels; please fix");
67e4b385 1160 if (strstr(attr, "../"))
8c19dc54 1161 LOG_RULE_WARNING("Direct reference to parent sysfs directory, may break in future kernels; please fix");
912541b0 1162 rule_add_key(&rule_tmp, TK_M_ATTRS, op, value, attr);
912541b0 1163
99f16bb8 1164 } else if (streq(key, "TAGS")) {
19a8e656 1165 if (op > OP_MATCH_MAX)
8c19dc54 1166 LOG_AND_RETURN("Invalid %s operation", key);
19a8e656 1167
912541b0 1168 rule_add_key(&rule_tmp, TK_M_TAGS, op, value, NULL);
912541b0 1169
99f16bb8 1170 } else if (startswith(key, "ENV{")) {
2024ed61 1171 attr = get_key_attribute(key + STRLEN("ENV"));
67e4b385 1172 if (!attr)
8c19dc54 1173 LOG_AND_RETURN("Failed to parse %s attribute", "ENV");
19a8e656
ZJS
1174
1175 if (op == OP_REMOVE)
8c19dc54 1176 LOG_AND_RETURN("Invalid %s operation", "ENV");
19a8e656
ZJS
1177
1178 if (op < OP_MATCH_MAX)
1179 rule_add_key(&rule_tmp, TK_M_ENV, op, value, attr);
1180 else {
99f16bb8
ZJS
1181 if (STR_IN_SET(attr,
1182 "ACTION",
1183 "SUBSYSTEM",
1184 "DEVTYPE",
1185 "MAJOR",
1186 "MINOR",
1187 "DRIVER",
1188 "IFINDEX",
1189 "DEVNAME",
1190 "DEVLINKS",
1191 "DEVPATH",
19a8e656 1192 "TAGS"))
8c19dc54 1193 LOG_AND_RETURN("Invalid ENV attribute, '%s' cannot be set", attr);
19a8e656
ZJS
1194
1195 rule_add_key(&rule_tmp, TK_A_ENV, op, value, attr);
912541b0 1196 }
912541b0 1197
99f16bb8 1198 } else if (streq(key, "TAG")) {
912541b0
KS
1199 if (op < OP_MATCH_MAX)
1200 rule_add_key(&rule_tmp, TK_M_TAG, op, value, NULL);
1201 else
1202 rule_add_key(&rule_tmp, TK_A_TAG, op, value, NULL);
912541b0 1203
99f16bb8 1204 } else if (streq(key, "PROGRAM")) {
19a8e656 1205 if (op == OP_REMOVE)
8c19dc54 1206 LOG_AND_RETURN("Invalid %s operation", key);
19a8e656 1207
912541b0 1208 rule_add_key(&rule_tmp, TK_M_PROGRAM, op, value, NULL);
912541b0 1209
99f16bb8 1210 } else if (streq(key, "RESULT")) {
19a8e656 1211 if (op > OP_MATCH_MAX)
8c19dc54 1212 LOG_AND_RETURN("Invalid %s operation", key);
19a8e656 1213
912541b0 1214 rule_add_key(&rule_tmp, TK_M_RESULT, op, value, NULL);
912541b0 1215
99f16bb8 1216 } else if (startswith(key, "IMPORT")) {
2024ed61 1217 attr = get_key_attribute(key + STRLEN("IMPORT"));
67e4b385 1218 if (!attr) {
8c19dc54 1219 LOG_RULE_WARNING("Ignoring IMPORT{} with missing type");
912541b0
KS
1220 continue;
1221 }
19a8e656 1222 if (op == OP_REMOVE)
8c19dc54 1223 LOG_AND_RETURN("Invalid %s operation", "IMPORT");
19a8e656 1224
33502ffe 1225 if (streq(attr, "program")) {
912541b0
KS
1226 /* find known built-in command */
1227 if (value[0] != '/') {
19a8e656 1228 const enum udev_builtin_cmd cmd = udev_builtin_lookup(value);
912541b0 1229
c45b369d 1230 if (cmd >= 0) {
19a8e656 1231 LOG_RULE_DEBUG("IMPORT found builtin '%s', replacing", value);
912541b0
KS
1232 rule_add_key(&rule_tmp, TK_M_IMPORT_BUILTIN, op, value, &cmd);
1233 continue;
1234 }
1235 }
912541b0 1236 rule_add_key(&rule_tmp, TK_M_IMPORT_PROG, op, value, NULL);
33502ffe 1237 } else if (streq(attr, "builtin")) {
19a8e656 1238 const enum udev_builtin_cmd cmd = udev_builtin_lookup(value);
912541b0 1239
c45b369d 1240 if (cmd < 0)
19a8e656 1241 LOG_RULE_WARNING("IMPORT{builtin} '%s' unknown", value);
912541b0 1242 else
19a8e656
ZJS
1243 rule_add_key(&rule_tmp, TK_M_IMPORT_BUILTIN, op, value, &cmd);
1244 } else if (streq(attr, "file"))
912541b0 1245 rule_add_key(&rule_tmp, TK_M_IMPORT_FILE, op, value, NULL);
19a8e656 1246 else if (streq(attr, "db"))
912541b0 1247 rule_add_key(&rule_tmp, TK_M_IMPORT_DB, op, value, NULL);
19a8e656 1248 else if (streq(attr, "cmdline"))
912541b0 1249 rule_add_key(&rule_tmp, TK_M_IMPORT_CMDLINE, op, value, NULL);
19a8e656 1250 else if (streq(attr, "parent"))
912541b0 1251 rule_add_key(&rule_tmp, TK_M_IMPORT_PARENT, op, value, NULL);
19a8e656 1252 else
8c19dc54 1253 LOG_RULE_ERROR("Ignoring unknown %s{} type '%s'", "IMPORT", attr);
912541b0 1254
99f16bb8 1255 } else if (startswith(key, "TEST")) {
912541b0
KS
1256 mode_t mode = 0;
1257
19a8e656 1258 if (op > OP_MATCH_MAX)
8c19dc54 1259 LOG_AND_RETURN("Invalid %s operation", "TEST");
19a8e656 1260
2024ed61 1261 attr = get_key_attribute(key + STRLEN("TEST"));
67e4b385 1262 if (attr) {
912541b0
KS
1263 mode = strtol(attr, NULL, 8);
1264 rule_add_key(&rule_tmp, TK_M_TEST, op, value, &mode);
99f16bb8 1265 } else
912541b0 1266 rule_add_key(&rule_tmp, TK_M_TEST, op, value, NULL);
912541b0 1267
99f16bb8 1268 } else if (startswith(key, "RUN")) {
2024ed61 1269 attr = get_key_attribute(key + STRLEN("RUN"));
67e4b385 1270 if (!attr)
83cd6b75 1271 attr = "program";
19a8e656 1272 if (op == OP_REMOVE)
8c19dc54 1273 LOG_AND_RETURN("Invalid %s operation", "RUN");
83cd6b75 1274
33502ffe 1275 if (streq(attr, "builtin")) {
19a8e656 1276 const enum udev_builtin_cmd cmd = udev_builtin_lookup(value);
83cd6b75 1277
c45b369d 1278 if (cmd < 0)
19a8e656 1279 LOG_RULE_ERROR("RUN{builtin}: '%s' unknown", value);
c45b369d
YW
1280 else
1281 rule_add_key(&rule_tmp, TK_A_RUN_BUILTIN, op, value, &cmd);
33502ffe 1282 } else if (streq(attr, "program")) {
c45b369d 1283 const enum udev_builtin_cmd cmd = _UDEV_BUILTIN_MAX;
83cd6b75 1284
83cd6b75 1285 rule_add_key(&rule_tmp, TK_A_RUN_PROGRAM, op, value, &cmd);
99f16bb8 1286 } else
8c19dc54 1287 LOG_RULE_ERROR("Ignoring unknown %s{} type '%s'", "RUN", attr);
912541b0 1288
99f16bb8 1289 } else if (streq(key, "LABEL")) {
19a8e656 1290 if (op == OP_REMOVE)
8c19dc54 1291 LOG_AND_RETURN("Invalid %s operation", key);
19a8e656 1292
915bf0f6 1293 rule_tmp.rule.rule.label_off = rules_add_string(rules, value);
912541b0 1294
99f16bb8 1295 } else if (streq(key, "GOTO")) {
19a8e656 1296 if (op == OP_REMOVE)
8c19dc54 1297 LOG_AND_RETURN("Invalid %s operation", key);
19a8e656 1298
912541b0 1299 rule_add_key(&rule_tmp, TK_A_GOTO, 0, value, NULL);
912541b0 1300
99f16bb8 1301 } else if (startswith(key, "NAME")) {
19a8e656 1302 if (op == OP_REMOVE)
8c19dc54 1303 LOG_AND_RETURN("Invalid %s operation", key);
19a8e656
ZJS
1304
1305 if (op < OP_MATCH_MAX)
912541b0 1306 rule_add_key(&rule_tmp, TK_M_NAME, op, value, NULL);
19a8e656 1307 else {
33502ffe 1308 if (streq(value, "%k")) {
19a8e656 1309 LOG_RULE_WARNING("NAME=\"%%k\" is ignored, because it breaks kernel supplied names; please remove");
912541b0
KS
1310 continue;
1311 }
19a8e656
ZJS
1312 if (isempty(value)) {
1313 LOG_RULE_DEBUG("NAME=\"\" is ignored, because udev will not delete any device nodes; please remove");
912541b0
KS
1314 continue;
1315 }
1316 rule_add_key(&rule_tmp, TK_A_NAME, op, value, NULL);
1317 }
1318 rule_tmp.rule.rule.can_set_name = true;
912541b0 1319
99f16bb8 1320 } else if (streq(key, "SYMLINK")) {
19a8e656 1321 if (op == OP_REMOVE)
8c19dc54 1322 LOG_AND_RETURN("Invalid %s operation", key);
19a8e656 1323
8a173387 1324 if (op < OP_MATCH_MAX)
912541b0 1325 rule_add_key(&rule_tmp, TK_M_DEVLINK, op, value, NULL);
8a173387
KS
1326 else
1327 rule_add_key(&rule_tmp, TK_A_DEVLINK, op, value, NULL);
912541b0 1328 rule_tmp.rule.rule.can_set_name = true;
912541b0 1329
99f16bb8 1330 } else if (streq(key, "OWNER")) {
912541b0
KS
1331 uid_t uid;
1332 char *endptr;
1333
19a8e656 1334 if (op == OP_REMOVE)
8c19dc54 1335 LOG_AND_RETURN("Invalid %s operation", key);
8e3ba377 1336
912541b0 1337 uid = strtoul(value, &endptr, 10);
19a8e656 1338 if (endptr[0] == '\0')
912541b0 1339 rule_add_key(&rule_tmp, TK_A_OWNER_ID, op, NULL, &uid);
67e4b385 1340 else if (rules->resolve_name_timing == RESOLVE_NAME_EARLY && !strchr("$%", value[0])) {
912541b0
KS
1341 uid = add_uid(rules, value);
1342 rule_add_key(&rule_tmp, TK_A_OWNER_ID, op, NULL, &uid);
c4d44cba 1343 } else if (rules->resolve_name_timing != RESOLVE_NAME_NEVER)
912541b0 1344 rule_add_key(&rule_tmp, TK_A_OWNER, op, value, NULL);
1f6b4113 1345
912541b0 1346 rule_tmp.rule.rule.can_set_name = true;
912541b0 1347
99f16bb8 1348 } else if (streq(key, "GROUP")) {
912541b0
KS
1349 gid_t gid;
1350 char *endptr;
1351
19a8e656 1352 if (op == OP_REMOVE)
8c19dc54 1353 LOG_AND_RETURN("Invalid %s operation", key);
8e3ba377 1354
912541b0 1355 gid = strtoul(value, &endptr, 10);
19a8e656 1356 if (endptr[0] == '\0')
912541b0 1357 rule_add_key(&rule_tmp, TK_A_GROUP_ID, op, NULL, &gid);
67e4b385 1358 else if ((rules->resolve_name_timing == RESOLVE_NAME_EARLY) && !strchr("$%", value[0])) {
912541b0
KS
1359 gid = add_gid(rules, value);
1360 rule_add_key(&rule_tmp, TK_A_GROUP_ID, op, NULL, &gid);
c4d44cba 1361 } else if (rules->resolve_name_timing != RESOLVE_NAME_NEVER)
912541b0 1362 rule_add_key(&rule_tmp, TK_A_GROUP, op, value, NULL);
1f6b4113 1363
912541b0 1364 rule_tmp.rule.rule.can_set_name = true;
912541b0 1365
99f16bb8 1366 } else if (streq(key, "MODE")) {
912541b0
KS
1367 mode_t mode;
1368 char *endptr;
1369
19a8e656 1370 if (op == OP_REMOVE)
8c19dc54 1371 LOG_AND_RETURN("Invalid %s operation", key);
8e3ba377 1372
912541b0
KS
1373 mode = strtol(value, &endptr, 8);
1374 if (endptr[0] == '\0')
1375 rule_add_key(&rule_tmp, TK_A_MODE_ID, op, NULL, &mode);
1376 else
1377 rule_add_key(&rule_tmp, TK_A_MODE, op, value, NULL);
1378 rule_tmp.rule.rule.can_set_name = true;
912541b0 1379
99f16bb8 1380 } else if (streq(key, "OPTIONS")) {
912541b0
KS
1381 const char *pos;
1382
19a8e656 1383 if (op == OP_REMOVE)
8c19dc54 1384 LOG_AND_RETURN("Invalid %s operation", key);
8e3ba377 1385
912541b0 1386 pos = strstr(value, "link_priority=");
67e4b385 1387 if (pos) {
fbd0b64f 1388 int prio = atoi(pos + STRLEN("link_priority="));
912541b0
KS
1389
1390 rule_add_key(&rule_tmp, TK_A_DEVLINK_PRIO, op, NULL, &prio);
912541b0
KS
1391 }
1392
9f20a8a3 1393 pos = strstr(value, "string_escape=");
67e4b385 1394 if (pos) {
fbd0b64f 1395 pos += STRLEN("string_escape=");
33502ffe 1396 if (startswith(pos, "none"))
912541b0 1397 rule_add_key(&rule_tmp, TK_A_STRING_ESCAPE_NONE, op, NULL, NULL);
33502ffe 1398 else if (startswith(pos, "replace"))
912541b0
KS
1399 rule_add_key(&rule_tmp, TK_A_STRING_ESCAPE_REPLACE, op, NULL, NULL);
1400 }
1401
1402 pos = strstr(value, "db_persist");
67e4b385 1403 if (pos)
912541b0
KS
1404 rule_add_key(&rule_tmp, TK_A_DB_PERSIST, op, NULL, NULL);
1405
1406 pos = strstr(value, "nowatch");
b33fa02b
LP
1407 if (pos) {
1408 static const int zero = 0;
1409 rule_add_key(&rule_tmp, TK_A_INOTIFY_WATCH, op, NULL, &zero);
1410 } else {
1411 static const int one = 1;
912541b0 1412 pos = strstr(value, "watch");
6d5e65f6 1413 if (pos)
b33fa02b 1414 rule_add_key(&rule_tmp, TK_A_INOTIFY_WATCH, op, NULL, &one);
912541b0
KS
1415 }
1416
1417 pos = strstr(value, "static_node=");
67e4b385 1418 if (pos) {
fbd0b64f 1419 pos += STRLEN("static_node=");
19a8e656 1420 rule_add_key(&rule_tmp, TK_A_STATIC_NODE, op, pos, NULL);
912541b0
KS
1421 rule_tmp.rule.rule.has_static_node = true;
1422 }
1423
19a8e656 1424 } else
8c19dc54 1425 LOG_AND_RETURN("Unknown key '%s'", key);
912541b0
KS
1426 }
1427
19a8e656 1428 /* add rule token and sort tokens */
912541b0 1429 rule_tmp.rule.rule.token_count = 1 + rule_tmp.token_cur;
19a8e656 1430 if (add_token(rules, &rule_tmp.rule) != 0 || sort_token(rules, &rule_tmp) != 0)
8c19dc54 1431 LOG_RULE_ERROR("Failed to add rule token");
c7521974
KS
1432}
1433
9a07157d 1434static int parse_file(UdevRules *rules, const char *filename) {
6c8aaf0c 1435 _cleanup_fclose_ FILE *f = NULL;
14cb109d
YW
1436 unsigned first_token;
1437 unsigned filename_off;
912541b0
KS
1438 char line[UTIL_LINE_SIZE];
1439 int line_nr = 0;
14cb109d 1440 unsigned i;
912541b0 1441
ed88bcfb
ZJS
1442 f = fopen(filename, "re");
1443 if (!f) {
1444 if (errno == ENOENT)
1445 return 0;
fae0f8a0
LP
1446
1447 return -errno;
775f8b3c 1448 }
912541b0 1449
ed88bcfb
ZJS
1450 if (null_or_empty_fd(fileno(f))) {
1451 log_debug("Skipping empty file: %s", filename);
1452 return 0;
1453 } else
1454 log_debug("Reading rules file: %s", filename);
912541b0
KS
1455
1456 first_token = rules->token_cur;
915bf0f6 1457 filename_off = rules_add_string(rules, filename);
912541b0 1458
67e4b385 1459 while (fgets(line, sizeof(line), f)) {
912541b0
KS
1460 char *key;
1461 size_t len;
1462
1463 /* skip whitespace */
1464 line_nr++;
1465 key = line;
1466 while (isspace(key[0]))
1467 key++;
1468
1469 /* comment */
1470 if (key[0] == '#')
1471 continue;
1472
1473 len = strlen(line);
1474 if (len < 3)
1475 continue;
1476
1477 /* continue reading if backslash+newline is found */
1478 while (line[len-2] == '\\') {
67e4b385 1479 if (!fgets(&line[len-2], (sizeof(line)-len)+2, f))
912541b0
KS
1480 break;
1481 if (strlen(&line[len-2]) < 2)
1482 break;
1483 line_nr++;
1484 len = strlen(line);
1485 }
1486
1487 if (len+1 >= sizeof(line)) {
8c19dc54 1488 log_error("Line too long '%s':%u, ignored", filename, line_nr);
912541b0
KS
1489 continue;
1490 }
1491 add_rule(rules, key, filename, filename_off, line_nr);
1492 }
912541b0
KS
1493
1494 /* link GOTOs to LABEL rules in this file to be able to fast-forward */
1495 for (i = first_token+1; i < rules->token_cur; i++) {
1496 if (rules->tokens[i].type == TK_A_GOTO) {
915bf0f6 1497 char *label = rules_str(rules, rules->tokens[i].key.value_off);
14cb109d 1498 unsigned j;
912541b0
KS
1499
1500 for (j = i+1; j < rules->token_cur; j++) {
1501 if (rules->tokens[j].type != TK_RULE)
1502 continue;
1503 if (rules->tokens[j].rule.label_off == 0)
1504 continue;
915bf0f6 1505 if (!streq(label, rules_str(rules, rules->tokens[j].rule.label_off)))
912541b0
KS
1506 continue;
1507 rules->tokens[i].key.rule_goto = j;
1508 break;
1509 }
1510 if (rules->tokens[i].key.rule_goto == 0)
9f6445e3 1511 log_error("GOTO '%s' has no matching label in: '%s'", label, filename);
912541b0
KS
1512 }
1513 }
1514 return 0;
c7521974
KS
1515}
1516
9a07157d
ZJS
1517int udev_rules_new(UdevRules **ret_rules, ResolveNameTiming resolve_name_timing) {
1518 _cleanup_(udev_rules_freep) UdevRules *rules = NULL;
1d791281
ZJS
1519 _cleanup_strv_free_ char **files = NULL;
1520 char **f;
775f8b3c 1521 int r;
912541b0 1522
c4d44cba
YW
1523 assert(resolve_name_timing >= 0 && resolve_name_timing < _RESOLVE_NAME_TIMING_MAX);
1524
9a07157d 1525 rules = new(UdevRules, 1);
1017d66b 1526 if (!rules)
1d791281 1527 return -ENOMEM;
1017d66b 1528
9a07157d 1529 *rules = (UdevRules) {
c4d44cba 1530 .resolve_name_timing = resolve_name_timing,
1017d66b 1531 };
912541b0
KS
1532
1533 /* init token array and string buffer */
8419d457 1534 rules->tokens = malloc_multiply(PREALLOC_TOKEN, sizeof(struct token));
67e4b385 1535 if (!rules->tokens)
1d791281 1536 return -ENOMEM;
912541b0
KS
1537 rules->token_max = PREALLOC_TOKEN;
1538
915bf0f6
KS
1539 rules->strbuf = strbuf_new();
1540 if (!rules->strbuf)
1d791281 1541 return -ENOMEM;
0820a4f0 1542
3b8c1cb0
KS
1543 udev_rules_check_timestamp(rules);
1544
b5084605 1545 r = conf_files_list_strv(&files, ".rules", NULL, 0, rules_dirs);
1d791281
ZJS
1546 if (r < 0)
1547 return log_error_errno(r, "Failed to enumerate rules files: %m");
912541b0 1548
775f8b3c
KS
1549 /*
1550 * The offset value in the rules strct is limited; add all
1551 * rules file names to the beginning of the string buffer.
1552 */
1553 STRV_FOREACH(f, files)
915bf0f6 1554 rules_add_string(rules, *f);
912541b0 1555
775f8b3c
KS
1556 STRV_FOREACH(f, files)
1557 parse_file(rules, *f);
1558
1d791281 1559 struct token end_token = { .type = TK_END };
912541b0 1560 add_token(rules, &end_token);
8c19dc54 1561 log_debug("Rules contain %zu bytes tokens (%u * %zu bytes), %zu bytes strings",
915bf0f6 1562 rules->token_max * sizeof(struct token), rules->token_max, sizeof(struct token), rules->strbuf->len);
912541b0 1563
915bf0f6 1564 /* cleanup temporary strbuf data */
9f6445e3 1565 log_debug("%zu strings (%zu bytes), %zu de-duplicated (%zu bytes), %zu trie nodes used",
915bf0f6
KS
1566 rules->strbuf->in_count, rules->strbuf->in_len,
1567 rules->strbuf->dedup_count, rules->strbuf->dedup_len, rules->strbuf->nodes_count);
1568 strbuf_complete(rules->strbuf);
912541b0
KS
1569
1570 /* cleanup uid/gid cache */
a1e58e8e 1571 rules->uids = mfree(rules->uids);
912541b0
KS
1572 rules->uids_cur = 0;
1573 rules->uids_max = 0;
a1e58e8e 1574 rules->gids = mfree(rules->gids);
912541b0
KS
1575 rules->gids_cur = 0;
1576 rules->gids_max = 0;
1577
1578 dump_rules(rules);
1d791281
ZJS
1579 *ret_rules = TAKE_PTR(rules);
1580 return 0;
c7521974
KS
1581}
1582
9a07157d 1583UdevRules *udev_rules_free(UdevRules *rules) {
67e4b385 1584 if (!rules)
912541b0
KS
1585 return NULL;
1586 free(rules->tokens);
915bf0f6 1587 strbuf_cleanup(rules->strbuf);
912541b0
KS
1588 free(rules->uids);
1589 free(rules->gids);
6b430fdb 1590 return mfree(rules);
c7521974 1591}
6880b25d 1592
9a07157d 1593bool udev_rules_check_timestamp(UdevRules *rules) {
5c11fbe3
KS
1594 if (!rules)
1595 return false;
1596
2ad8416d 1597 return paths_check_timestamp(rules_dirs, &rules->dirs_ts_usec, true);
6ada823a
KS
1598}
1599
9a07157d 1600static int match_key(UdevRules *rules, struct token *token, const char *val) {
915bf0f6 1601 char *key_value = rules_str(rules, token->key.value_off);
912541b0
KS
1602 char *pos;
1603 bool match = false;
1604
67e4b385 1605 if (!val)
912541b0
KS
1606 val = "";
1607
1608 switch (token->key.glob) {
1609 case GL_PLAIN:
33502ffe 1610 match = (streq(key_value, val));
912541b0
KS
1611 break;
1612 case GL_GLOB:
1613 match = (fnmatch(key_value, val, 0) == 0);
1614 break;
1615 case GL_SPLIT:
1616 {
33502ffe 1617 const char *s;
912541b0
KS
1618 size_t len;
1619
915bf0f6 1620 s = rules_str(rules, token->key.value_off);
912541b0
KS
1621 len = strlen(val);
1622 for (;;) {
1623 const char *next;
1624
33502ffe 1625 next = strchr(s, '|');
67e4b385 1626 if (next) {
33502ffe 1627 size_t matchlen = (size_t)(next - s);
912541b0 1628
641906e9 1629 match = (matchlen == len && strneq(s, val, matchlen));
912541b0
KS
1630 if (match)
1631 break;
1632 } else {
33502ffe 1633 match = (streq(s, val));
912541b0
KS
1634 break;
1635 }
33502ffe 1636 s = &next[1];
912541b0
KS
1637 }
1638 break;
1639 }
1640 case GL_SPLIT_GLOB:
1641 {
1642 char value[UTIL_PATH_SIZE];
1643
d5a89d7d 1644 strscpy(value, sizeof(value), rules_str(rules, token->key.value_off));
912541b0 1645 key_value = value;
67e4b385 1646 while (key_value) {
912541b0 1647 pos = strchr(key_value, '|');
67e4b385 1648 if (pos) {
912541b0
KS
1649 pos[0] = '\0';
1650 pos = &pos[1];
1651 }
912541b0
KS
1652 match = (fnmatch(key_value, val, 0) == 0);
1653 if (match)
1654 break;
1655 key_value = pos;
1656 }
1657 break;
1658 }
1659 case GL_SOMETHING:
1660 match = (val[0] != '\0');
1661 break;
1662 case GL_UNSET:
1663 return -1;
1664 }
1665
baa30fbc 1666 if (match && (token->key.op == OP_MATCH))
912541b0 1667 return 0;
baa30fbc 1668 if (!match && (token->key.op == OP_NOMATCH))
912541b0 1669 return 0;
912541b0 1670 return -1;
6880b25d
KS
1671}
1672
2e088715 1673static int match_attr(UdevRules *rules, sd_device *dev, UdevEvent *event, struct token *cur) {
5ba7e798
YW
1674 char nbuf[UTIL_NAME_SIZE], vbuf[UTIL_NAME_SIZE];
1675 const char *name, *value;
912541b0
KS
1676 size_t len;
1677
915bf0f6 1678 name = rules_str(rules, cur->key.attr_off);
912541b0
KS
1679 switch (cur->key.attrsubst) {
1680 case SB_FORMAT:
e20a9171 1681 udev_event_apply_format(event, name, nbuf, sizeof(nbuf), false);
912541b0 1682 name = nbuf;
4831981d 1683 _fallthrough_;
912541b0 1684 case SB_NONE:
5ba7e798 1685 if (sd_device_get_sysattr_value(dev, name, &value) < 0)
912541b0
KS
1686 return -1;
1687 break;
1688 case SB_SUBSYS:
3839535a 1689 if (util_resolve_subsys_kernel(name, vbuf, sizeof(vbuf), true) != 0)
912541b0
KS
1690 return -1;
1691 value = vbuf;
1692 break;
1693 default:
1694 return -1;
1695 }
1696
1697 /* remove trailing whitespace, if not asked to match for it */
1698 len = strlen(value);
1699 if (len > 0 && isspace(value[len-1])) {
1700 const char *key_value;
1701 size_t klen;
1702
915bf0f6 1703 key_value = rules_str(rules, cur->key.value_off);
912541b0
KS
1704 klen = strlen(key_value);
1705 if (klen > 0 && !isspace(key_value[klen-1])) {
1706 if (value != vbuf) {
d5a89d7d 1707 strscpy(vbuf, sizeof(vbuf), value);
912541b0
KS
1708 value = vbuf;
1709 }
1710 while (len > 0 && isspace(vbuf[--len]))
1711 vbuf[len] = '\0';
912541b0
KS
1712 }
1713 }
1714
1715 return match_key(rules, cur, value);
6880b25d
KS
1716}
1717
1718enum escape_type {
912541b0
KS
1719 ESCAPE_UNSET,
1720 ESCAPE_NONE,
1721 ESCAPE_REPLACE,
6880b25d
KS
1722};
1723
d838e145 1724int udev_rules_apply_to_event(
9a07157d 1725 UdevRules *rules,
2e088715 1726 UdevEvent *event,
d838e145 1727 usec_t timeout_usec,
9b5150b6 1728 Hashmap *properties_list) {
cf28ad46 1729 sd_device *dev = event->dev;
912541b0 1730 enum escape_type esc = ESCAPE_UNSET;
cf697ec0
YW
1731 struct token *cur, *rule;
1732 const char *action, *val;
912541b0 1733 bool can_set_name;
88b013b2 1734 int r;
912541b0 1735
d838e145
YW
1736 if (!rules->tokens)
1737 return 0;
912541b0 1738
cf697ec0
YW
1739 r = sd_device_get_property_value(dev, "ACTION", &action);
1740 if (r < 0)
1741 return r;
1742
1743 can_set_name = (!streq(action, "remove") &&
1744 (sd_device_get_devnum(dev, NULL) >= 0 ||
1745 sd_device_get_ifindex(dev, NULL) >= 0));
912541b0
KS
1746
1747 /* loop through token list, match, run actions or forward to next rule */
1748 cur = &rules->tokens[0];
1749 rule = cur;
1750 for (;;) {
1751 dump_token(rules, cur);
1752 switch (cur->type) {
1753 case TK_RULE:
1754 /* current rule */
1755 rule = cur;
1756 /* possibly skip rules which want to set NAME, SYMLINK, OWNER, GROUP, MODE */
1757 if (!can_set_name && rule->rule.can_set_name)
1758 goto nomatch;
1759 esc = ESCAPE_UNSET;
1760 break;
1761 case TK_M_ACTION:
cf697ec0 1762 if (match_key(rules, cur, action) != 0)
912541b0
KS
1763 goto nomatch;
1764 break;
1765 case TK_M_DEVPATH:
cf697ec0
YW
1766 if (sd_device_get_devpath(dev, &val) < 0)
1767 goto nomatch;
1768 if (match_key(rules, cur, val) != 0)
912541b0
KS
1769 goto nomatch;
1770 break;
1771 case TK_M_KERNEL:
cf697ec0
YW
1772 if (sd_device_get_sysname(dev, &val) < 0)
1773 goto nomatch;
1774 if (match_key(rules, cur, val) != 0)
912541b0
KS
1775 goto nomatch;
1776 break;
1777 case TK_M_DEVLINK: {
dbea7f24 1778 const char *devlink;
912541b0
KS
1779 bool match = false;
1780
cf697ec0 1781 FOREACH_DEVICE_DEVLINK(dev, devlink)
dbea7f24 1782 if (match_key(rules, cur, devlink + STRLEN("/dev/")) == 0) {
912541b0
KS
1783 match = true;
1784 break;
1785 }
dbea7f24 1786
912541b0
KS
1787 if (!match)
1788 goto nomatch;
1789 break;
1790 }
1791 case TK_M_NAME:
1792 if (match_key(rules, cur, event->name) != 0)
1793 goto nomatch;
1794 break;
1795 case TK_M_ENV: {
915bf0f6 1796 const char *key_name = rules_str(rules, cur->key.attr_off);
912541b0 1797
cf697ec0
YW
1798 if (sd_device_get_property_value(dev, key_name, &val) < 0) {
1799 /* check global properties */
1800 if (properties_list)
1801 val = hashmap_get(properties_list, key_name);
1802 else
1803 val = NULL;
1804 }
adeba500 1805
cf697ec0 1806 if (match_key(rules, cur, strempty(val)))
912541b0
KS
1807 goto nomatch;
1808 break;
1809 }
1810 case TK_M_TAG: {
912541b0 1811 bool match = false;
dbea7f24 1812 const char *tag;
912541b0 1813
cf697ec0 1814 FOREACH_DEVICE_TAG(dev, tag)
dbea7f24 1815 if (streq(rules_str(rules, cur->key.value_off), tag)) {
912541b0
KS
1816 match = true;
1817 break;
1818 }
dbea7f24 1819
4302857b
FF
1820 if ((!match && (cur->key.op != OP_NOMATCH)) ||
1821 (match && (cur->key.op == OP_NOMATCH)))
912541b0
KS
1822 goto nomatch;
1823 break;
1824 }
1825 case TK_M_SUBSYSTEM:
cf697ec0
YW
1826 if (sd_device_get_subsystem(dev, &val) < 0)
1827 goto nomatch;
1828 if (match_key(rules, cur, val) != 0)
912541b0
KS
1829 goto nomatch;
1830 break;
1831 case TK_M_DRIVER:
cf697ec0
YW
1832 if (sd_device_get_driver(dev, &val) < 0)
1833 goto nomatch;
1834 if (match_key(rules, cur, val) != 0)
912541b0
KS
1835 goto nomatch;
1836 break;
912541b0 1837 case TK_M_ATTR:
cf697ec0 1838 if (match_attr(rules, dev, event, cur) != 0)
912541b0
KS
1839 goto nomatch;
1840 break;
f4cf2e5b
KS
1841 case TK_M_SYSCTL: {
1842 char filename[UTIL_PATH_SIZE];
1843 _cleanup_free_ char *value = NULL;
1844 size_t len;
1845
e20a9171 1846 udev_event_apply_format(event, rules_str(rules, cur->key.attr_off), filename, sizeof(filename), false);
f4cf2e5b
KS
1847 sysctl_normalize(filename);
1848 if (sysctl_read(filename, &value) < 0)
1849 goto nomatch;
1850
1851 len = strlen(value);
1852 while (len > 0 && isspace(value[--len]))
1853 value[len] = '\0';
1854 if (match_key(rules, cur, value) != 0)
1855 goto nomatch;
1856 break;
1857 }
912541b0
KS
1858 case TK_M_KERNELS:
1859 case TK_M_SUBSYSTEMS:
1860 case TK_M_DRIVERS:
1861 case TK_M_ATTRS:
1862 case TK_M_TAGS: {
1863 struct token *next;
1864
1865 /* get whole sequence of parent matches */
1866 next = cur;
1867 while (next->type > TK_M_PARENTS_MIN && next->type < TK_M_PARENTS_MAX)
1868 next++;
1869
1870 /* loop over parents */
cf697ec0 1871 event->dev_parent = dev;
912541b0
KS
1872 for (;;) {
1873 struct token *key;
1874
912541b0
KS
1875 /* loop over sequence of parent match keys */
1876 for (key = cur; key < next; key++ ) {
1877 dump_token(rules, key);
1878 switch(key->type) {
1879 case TK_M_KERNELS:
f3d241fe
YW
1880 if (sd_device_get_sysname(event->dev_parent, &val) < 0)
1881 goto try_parent;
1882 if (match_key(rules, key, val) != 0)
912541b0
KS
1883 goto try_parent;
1884 break;
1885 case TK_M_SUBSYSTEMS:
f3d241fe
YW
1886 if (sd_device_get_subsystem(event->dev_parent, &val) < 0)
1887 goto try_parent;
1888 if (match_key(rules, key, val) != 0)
912541b0
KS
1889 goto try_parent;
1890 break;
1891 case TK_M_DRIVERS:
f3d241fe
YW
1892 if (sd_device_get_driver(event->dev_parent, &val) < 0)
1893 goto try_parent;
1894 if (match_key(rules, key, val) != 0)
912541b0
KS
1895 goto try_parent;
1896 break;
1897 case TK_M_ATTRS:
f3d241fe 1898 if (match_attr(rules, event->dev_parent, event, key) != 0)
912541b0
KS
1899 goto try_parent;
1900 break;
1901 case TK_M_TAGS: {
f3d241fe 1902 bool match = sd_device_has_tag(event->dev_parent, rules_str(rules, cur->key.value_off));
912541b0
KS
1903
1904 if (match && key->key.op == OP_NOMATCH)
1905 goto try_parent;
1906 if (!match && key->key.op == OP_MATCH)
1907 goto try_parent;
1908 break;
1909 }
1910 default:
1911 goto nomatch;
1912 }
912541b0 1913 }
912541b0
KS
1914 break;
1915
1916 try_parent:
f3d241fe
YW
1917 if (sd_device_get_parent(event->dev_parent, &event->dev_parent) < 0) {
1918 event->dev_parent = NULL;
912541b0 1919 goto nomatch;
f3d241fe 1920 }
912541b0
KS
1921 }
1922 /* move behind our sequence of parent match keys */
1923 cur = next;
1924 continue;
1925 }
1926 case TK_M_TEST: {
1927 char filename[UTIL_PATH_SIZE];
1928 struct stat statbuf;
1929 int match;
1930
e20a9171 1931 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), filename, sizeof(filename), false);
3839535a 1932 if (util_resolve_subsys_kernel(filename, filename, sizeof(filename), false) != 0) {
912541b0
KS
1933 if (filename[0] != '/') {
1934 char tmp[UTIL_PATH_SIZE];
1935
cf697ec0
YW
1936 if (sd_device_get_syspath(dev, &val) < 0)
1937 goto nomatch;
1938
d5a89d7d 1939 strscpy(tmp, sizeof(tmp), filename);
cf697ec0 1940 strscpyl(filename, sizeof(filename), val, "/", tmp, NULL);
912541b0
KS
1941 }
1942 }
1943 attr_subst_subdir(filename, sizeof(filename));
1944
1945 match = (stat(filename, &statbuf) == 0);
baa30fbc 1946 if (match && cur->key.mode > 0)
912541b0 1947 match = ((statbuf.st_mode & cur->key.mode) > 0);
912541b0
KS
1948 if (match && cur->key.op == OP_NOMATCH)
1949 goto nomatch;
1950 if (!match && cur->key.op == OP_MATCH)
1951 goto nomatch;
1952 break;
1953 }
912541b0 1954 case TK_M_PROGRAM: {
cf697ec0 1955 char program[UTIL_PATH_SIZE], result[UTIL_LINE_SIZE];
912541b0 1956
a1e58e8e 1957 event->program_result = mfree(event->program_result);
e20a9171 1958 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), program, sizeof(program), false);
b4ba2fe3
YW
1959 log_device_debug(dev, "PROGRAM '%s' %s:%u",
1960 program,
1961 rules_str(rules, rule->rule.filename_off),
1962 rule->rule.filename_line);
912541b0 1963
a7521142 1964 if (udev_event_spawn(event, timeout_usec, true, program, result, sizeof(result)) != 0) {
912541b0
KS
1965 if (cur->key.op != OP_NOMATCH)
1966 goto nomatch;
1967 } else {
1968 int count;
1969
7546145e 1970 delete_trailing_chars(result, "\n");
4c701096 1971 if (IN_SET(esc, ESCAPE_UNSET, ESCAPE_REPLACE)) {
912541b0
KS
1972 count = util_replace_chars(result, UDEV_ALLOWED_CHARS_INPUT);
1973 if (count > 0)
b4ba2fe3 1974 log_device_debug(dev, "Replaced %i character(s) from result of '%s'" , count, program);
912541b0
KS
1975 }
1976 event->program_result = strdup(result);
912541b0
KS
1977 if (cur->key.op == OP_NOMATCH)
1978 goto nomatch;
1979 }
1980 break;
1981 }
1982 case TK_M_IMPORT_FILE: {
1983 char import[UTIL_PATH_SIZE];
1984
e20a9171 1985 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), import, sizeof(import), false);
cf697ec0 1986 if (import_file_into_properties(dev, import) != 0)
912541b0
KS
1987 if (cur->key.op != OP_NOMATCH)
1988 goto nomatch;
1989 break;
1990 }
1991 case TK_M_IMPORT_PROG: {
1992 char import[UTIL_PATH_SIZE];
1993
e20a9171 1994 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), import, sizeof(import), false);
b4ba2fe3
YW
1995 log_device_debug(dev, "IMPORT '%s' %s:%u",
1996 import,
1997 rules_str(rules, rule->rule.filename_off),
1998 rule->rule.filename_line);
912541b0 1999
66f737b4 2000 if (import_program_into_properties(event, timeout_usec, import) != 0)
912541b0
KS
2001 if (cur->key.op != OP_NOMATCH)
2002 goto nomatch;
2003 break;
2004 }
2005 case TK_M_IMPORT_BUILTIN: {
2006 char command[UTIL_PATH_SIZE];
2007
2008 if (udev_builtin_run_once(cur->key.builtin_cmd)) {
2009 /* check if we ran already */
2010 if (event->builtin_run & (1 << cur->key.builtin_cmd)) {
b4ba2fe3
YW
2011 log_device_debug(dev, "IMPORT builtin skip '%s' %s:%u",
2012 udev_builtin_name(cur->key.builtin_cmd),
2013 rules_str(rules, rule->rule.filename_off),
2014 rule->rule.filename_line);
912541b0
KS
2015 /* return the result from earlier run */
2016 if (event->builtin_ret & (1 << cur->key.builtin_cmd))
7d6884b6 2017 if (cur->key.op != OP_NOMATCH)
912541b0
KS
2018 goto nomatch;
2019 break;
2020 }
2021 /* mark as ran */
2022 event->builtin_run |= (1 << cur->key.builtin_cmd);
2023 }
2024
e20a9171 2025 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), command, sizeof(command), false);
b4ba2fe3
YW
2026 log_device_debug(dev, "IMPORT builtin '%s' %s:%u",
2027 udev_builtin_name(cur->key.builtin_cmd),
2028 rules_str(rules, rule->rule.filename_off),
2029 rule->rule.filename_line);
912541b0 2030
cf697ec0 2031 r = udev_builtin_run(dev, cur->key.builtin_cmd, command, false);
d354690e 2032 if (r < 0) {
912541b0 2033 /* remember failure */
b4ba2fe3
YW
2034 log_device_debug_errno(dev, r, "IMPORT builtin '%s' fails: %m",
2035 udev_builtin_name(cur->key.builtin_cmd));
912541b0
KS
2036 event->builtin_ret |= (1 << cur->key.builtin_cmd);
2037 if (cur->key.op != OP_NOMATCH)
2038 goto nomatch;
2039 }
2040 break;
2041 }
2042 case TK_M_IMPORT_DB: {
cf697ec0 2043 const char *key;
912541b0 2044
cf697ec0 2045 key = rules_str(rules, cur->key.value_off);
a6da77b7
YW
2046 if (event->dev_db_clone &&
2047 sd_device_get_property_value(event->dev_db_clone, key, &val) >= 0)
cf697ec0 2048 device_add_property(dev, key, val);
480ecb7d
YW
2049 else if (cur->key.op != OP_NOMATCH)
2050 goto nomatch;
912541b0
KS
2051 break;
2052 }
2053 case TK_M_IMPORT_CMDLINE: {
88b013b2 2054 _cleanup_free_ char *value = NULL;
912541b0 2055 bool imported = false;
88b013b2 2056 const char *key;
912541b0 2057
88b013b2 2058 key = rules_str(rules, cur->key.value_off);
88b013b2
LP
2059 r = proc_cmdline_get_key(key, PROC_CMDLINE_VALUE_OPTIONAL, &value);
2060 if (r < 0)
b4ba2fe3 2061 log_device_debug_errno(dev, r, "Failed to read %s from /proc/cmdline, ignoring: %m", key);
88b013b2
LP
2062 else if (r > 0) {
2063 imported = true;
2064
2065 if (value)
cf697ec0 2066 device_add_property(dev, key, value);
88b013b2
LP
2067 else
2068 /* we import simple flags as 'FLAG=1' */
cf697ec0 2069 device_add_property(dev, key, "1");
912541b0 2070 }
88b013b2 2071
912541b0
KS
2072 if (!imported && cur->key.op != OP_NOMATCH)
2073 goto nomatch;
2074 break;
2075 }
2076 case TK_M_IMPORT_PARENT: {
2077 char import[UTIL_PATH_SIZE];
2078
e20a9171 2079 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), import, sizeof(import), false);
cf697ec0 2080 if (import_parent_into_properties(dev, import) != 0)
912541b0
KS
2081 if (cur->key.op != OP_NOMATCH)
2082 goto nomatch;
2083 break;
2084 }
2085 case TK_M_RESULT:
2086 if (match_key(rules, cur, event->program_result) != 0)
2087 goto nomatch;
2088 break;
2089 case TK_A_STRING_ESCAPE_NONE:
2090 esc = ESCAPE_NONE;
2091 break;
2092 case TK_A_STRING_ESCAPE_REPLACE:
2093 esc = ESCAPE_REPLACE;
2094 break;
2095 case TK_A_DB_PERSIST:
cf697ec0 2096 device_set_db_persist(dev);
912541b0
KS
2097 break;
2098 case TK_A_INOTIFY_WATCH:
2099 if (event->inotify_watch_final)
2100 break;
2101 if (cur->key.op == OP_ASSIGN_FINAL)
2102 event->inotify_watch_final = true;
2103 event->inotify_watch = cur->key.watch;
2104 break;
2105 case TK_A_DEVLINK_PRIO:
cf697ec0 2106 device_set_devlink_priority(dev, cur->key.devlink_prio);
912541b0
KS
2107 break;
2108 case TK_A_OWNER: {
2109 char owner[UTIL_NAME_SIZE];
23bf8dd7 2110 const char *ow = owner;
912541b0
KS
2111
2112 if (event->owner_final)
2113 break;
2114 if (cur->key.op == OP_ASSIGN_FINAL)
2115 event->owner_final = true;
e20a9171 2116 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), owner, sizeof(owner), false);
1edefa4f 2117 event->owner_set = true;
fafff8f1 2118 r = get_user_creds(&ow, &event->uid, NULL, NULL, NULL, USER_CREDS_ALLOW_MISSING);
23bf8dd7 2119 if (r < 0) {
b4ba2fe3 2120 log_unknown_owner(dev, r, "user", owner);
23bf8dd7
TG
2121 event->uid = 0;
2122 }
b4ba2fe3
YW
2123 log_device_debug(dev, "OWNER %u %s:%u",
2124 event->uid,
2125 rules_str(rules, rule->rule.filename_off),
2126 rule->rule.filename_line);
912541b0
KS
2127 break;
2128 }
2129 case TK_A_GROUP: {
2130 char group[UTIL_NAME_SIZE];
23bf8dd7 2131 const char *gr = group;
912541b0
KS
2132
2133 if (event->group_final)
2134 break;
2135 if (cur->key.op == OP_ASSIGN_FINAL)
2136 event->group_final = true;
e20a9171 2137 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), group, sizeof(group), false);
1edefa4f 2138 event->group_set = true;
fafff8f1 2139 r = get_group_creds(&gr, &event->gid, USER_CREDS_ALLOW_MISSING);
23bf8dd7 2140 if (r < 0) {
b4ba2fe3 2141 log_unknown_owner(dev, r, "group", group);
23bf8dd7
TG
2142 event->gid = 0;
2143 }
b4ba2fe3
YW
2144 log_device_debug(dev, "GROUP %u %s:%u",
2145 event->gid,
2146 rules_str(rules, rule->rule.filename_off),
2147 rule->rule.filename_line);
912541b0
KS
2148 break;
2149 }
2150 case TK_A_MODE: {
b4ba2fe3 2151 char mode_str[UTIL_NAME_SIZE];
912541b0 2152 mode_t mode;
912541b0
KS
2153
2154 if (event->mode_final)
2155 break;
e20a9171 2156 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), mode_str, sizeof(mode_str), false);
b4ba2fe3
YW
2157 r = parse_mode(mode_str, &mode);
2158 if (r < 0) {
2159 log_device_error_errno(dev, r, "Failed to parse mode '%s': %m", mode_str);
912541b0
KS
2160 break;
2161 }
2162 if (cur->key.op == OP_ASSIGN_FINAL)
2163 event->mode_final = true;
2164 event->mode_set = true;
2165 event->mode = mode;
b4ba2fe3
YW
2166 log_device_debug(dev, "MODE %#o %s:%u",
2167 event->mode,
2168 rules_str(rules, rule->rule.filename_off),
2169 rule->rule.filename_line);
912541b0
KS
2170 break;
2171 }
2172 case TK_A_OWNER_ID:
2173 if (event->owner_final)
2174 break;
2175 if (cur->key.op == OP_ASSIGN_FINAL)
2176 event->owner_final = true;
1edefa4f 2177 event->owner_set = true;
912541b0 2178 event->uid = cur->key.uid;
b4ba2fe3
YW
2179 log_device_debug(dev, "OWNER %u %s:%u",
2180 event->uid,
2181 rules_str(rules, rule->rule.filename_off),
2182 rule->rule.filename_line);
912541b0
KS
2183 break;
2184 case TK_A_GROUP_ID:
2185 if (event->group_final)
2186 break;
2187 if (cur->key.op == OP_ASSIGN_FINAL)
2188 event->group_final = true;
1edefa4f 2189 event->group_set = true;
912541b0 2190 event->gid = cur->key.gid;
b4ba2fe3
YW
2191 log_device_debug(dev, "GROUP %u %s:%u",
2192 event->gid,
2193 rules_str(rules, rule->rule.filename_off),
2194 rule->rule.filename_line);
912541b0
KS
2195 break;
2196 case TK_A_MODE_ID:
2197 if (event->mode_final)
2198 break;
2199 if (cur->key.op == OP_ASSIGN_FINAL)
2200 event->mode_final = true;
2201 event->mode_set = true;
2202 event->mode = cur->key.mode;
b4ba2fe3
YW
2203 log_device_debug(dev, "MODE %#o %s:%u",
2204 event->mode,
2205 rules_str(rules, rule->rule.filename_off),
2206 rule->rule.filename_line);
912541b0 2207 break;
c26547d6 2208 case TK_A_SECLABEL: {
d838e145 2209 _cleanup_free_ char *name = NULL, *label = NULL;
4f985bd8 2210 char label_str[UTIL_LINE_SIZE] = {};
c26547d6 2211
d838e145
YW
2212 name = strdup(rules_str(rules, cur->key.attr_off));
2213 if (!name)
2214 return log_oom();
2215
e20a9171 2216 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), label_str, sizeof(label_str), false);
d838e145
YW
2217 if (!isempty(label_str))
2218 label = strdup(label_str);
4f985bd8 2219 else
d838e145
YW
2220 label = strdup(rules_str(rules, cur->key.value_off));
2221 if (!label)
2222 return log_oom();
4f985bd8 2223
4c701096 2224 if (IN_SET(cur->key.op, OP_ASSIGN, OP_ASSIGN_FINAL))
d838e145
YW
2225 hashmap_clear_free_free(event->seclabel_list);
2226
2227 r = hashmap_ensure_allocated(&event->seclabel_list, NULL);
2228 if (r < 0)
2229 return log_oom();
2230
2231 r = hashmap_put(event->seclabel_list, name, label);
2232 if (r < 0)
2233 return log_oom();
2234
2235 name = label = NULL;
2236
b4ba2fe3
YW
2237 log_device_debug(dev, "SECLABEL{%s}='%s' %s:%u",
2238 name, label,
2239 rules_str(rules, rule->rule.filename_off),
2240 rule->rule.filename_line);
c26547d6
KS
2241 break;
2242 }
912541b0 2243 case TK_A_ENV: {
07845c14 2244 char value_new[UTIL_NAME_SIZE];
cf697ec0 2245 const char *name, *value_old;
912541b0 2246
cf697ec0
YW
2247 name = rules_str(rules, cur->key.attr_off);
2248 val = rules_str(rules, cur->key.value_off);
2249 if (val[0] == '\0') {
07845c14
KS
2250 if (cur->key.op == OP_ADD)
2251 break;
cf697ec0 2252 device_add_property(dev, name, NULL);
07845c14 2253 break;
912541b0 2254 }
07845c14 2255
cf697ec0
YW
2256 if (cur->key.op == OP_ADD &&
2257 sd_device_get_property_value(dev, name, &value_old) >= 0) {
07845c14
KS
2258 char temp[UTIL_NAME_SIZE];
2259
2260 /* append value separated by space */
cf697ec0 2261 udev_event_apply_format(event, val, temp, sizeof(temp), false);
d5a89d7d 2262 strscpyl(value_new, sizeof(value_new), value_old, " ", temp, NULL);
07845c14 2263 } else
cf697ec0 2264 udev_event_apply_format(event, val, value_new, sizeof(value_new), false);
07845c14 2265
cf697ec0 2266 device_add_property(dev, name, value_new);
912541b0
KS
2267 break;
2268 }
2269 case TK_A_TAG: {
2270 char tag[UTIL_PATH_SIZE];
2271 const char *p;
2272
e20a9171 2273 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), tag, sizeof(tag), false);
4c701096 2274 if (IN_SET(cur->key.op, OP_ASSIGN, OP_ASSIGN_FINAL))
cf697ec0 2275 device_cleanup_tags(dev);
912541b0
KS
2276 for (p = tag; *p != '\0'; p++) {
2277 if ((*p >= 'a' && *p <= 'z') ||
2278 (*p >= 'A' && *p <= 'Z') ||
2279 (*p >= '0' && *p <= '9') ||
4c701096 2280 IN_SET(*p, '-', '_'))
912541b0 2281 continue;
b4ba2fe3 2282 log_device_error(dev, "Ignoring invalid tag name '%s'", tag);
912541b0
KS
2283 break;
2284 }
8e3ba377 2285 if (cur->key.op == OP_REMOVE)
cf697ec0 2286 device_remove_tag(dev, tag);
8e3ba377 2287 else
cf697ec0 2288 device_add_tag(dev, tag);
912541b0
KS
2289 break;
2290 }
2291 case TK_A_NAME: {
912541b0 2292 char name_str[UTIL_PATH_SIZE];
cf697ec0 2293 const char *name;
912541b0
KS
2294 int count;
2295
cf697ec0 2296 name = rules_str(rules, cur->key.value_off);
912541b0
KS
2297 if (event->name_final)
2298 break;
2299 if (cur->key.op == OP_ASSIGN_FINAL)
2300 event->name_final = true;
e20a9171 2301 udev_event_apply_format(event, name, name_str, sizeof(name_str), false);
4c701096 2302 if (IN_SET(esc, ESCAPE_UNSET, ESCAPE_REPLACE)) {
912541b0
KS
2303 count = util_replace_chars(name_str, "/");
2304 if (count > 0)
b4ba2fe3 2305 log_device_debug(dev, "Replaced %i character(s) from result of NAME=\"%s\"", count, name);
912541b0 2306 }
cf697ec0
YW
2307 if (sd_device_get_devnum(dev, NULL) >= 0 &&
2308 (sd_device_get_devname(dev, &val) < 0 ||
2309 !streq(name_str, val + STRLEN("/dev/")))) {
b4ba2fe3
YW
2310 log_device_error(dev, "Kernel device nodes cannot be renamed, ignoring NAME=\"%s\"; please fix it in %s:%u\n",
2311 name,
2312 rules_str(rules, rule->rule.filename_off),
2313 rule->rule.filename_line);
6ada823a 2314 break;
0ecfcbd4 2315 }
d838e145
YW
2316 if (free_and_strdup(&event->name, name_str) < 0)
2317 return log_oom();
2318
b4ba2fe3
YW
2319 log_device_debug(dev, "NAME '%s' %s:%u",
2320 event->name,
2321 rules_str(rules, rule->rule.filename_off),
2322 rule->rule.filename_line);
912541b0
KS
2323 break;
2324 }
2325 case TK_A_DEVLINK: {
cf697ec0 2326 char temp[UTIL_PATH_SIZE], filename[UTIL_PATH_SIZE], *pos, *next;
912541b0
KS
2327 int count = 0;
2328
2329 if (event->devlink_final)
2330 break;
cf697ec0 2331 if (sd_device_get_devnum(dev, NULL) < 0)
912541b0
KS
2332 break;
2333 if (cur->key.op == OP_ASSIGN_FINAL)
2334 event->devlink_final = true;
4c701096 2335 if (IN_SET(cur->key.op, OP_ASSIGN, OP_ASSIGN_FINAL))
cf697ec0 2336 device_cleanup_devlinks(dev);
912541b0
KS
2337
2338 /* allow multiple symlinks separated by spaces */
0a10235e 2339 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), temp, sizeof(temp), esc != ESCAPE_NONE);
912541b0
KS
2340 if (esc == ESCAPE_UNSET)
2341 count = util_replace_chars(temp, "/ ");
2342 else if (esc == ESCAPE_REPLACE)
2343 count = util_replace_chars(temp, "/");
2344 if (count > 0)
b4ba2fe3 2345 log_device_debug(dev, "Replaced %i character(s) from result of LINK" , count);
912541b0
KS
2346 pos = temp;
2347 while (isspace(pos[0]))
2348 pos++;
2349 next = strchr(pos, ' ');
cf697ec0 2350 while (next) {
912541b0 2351 next[0] = '\0';
b4ba2fe3
YW
2352 log_device_debug(dev, "LINK '%s' %s:%u", pos,
2353 rules_str(rules, rule->rule.filename_off), rule->rule.filename_line);
d5a89d7d 2354 strscpyl(filename, sizeof(filename), "/dev/", pos, NULL);
cf697ec0 2355 device_add_devlink(dev, filename);
912541b0
KS
2356 while (isspace(next[1]))
2357 next++;
2358 pos = &next[1];
2359 next = strchr(pos, ' ');
2360 }
2361 if (pos[0] != '\0') {
b4ba2fe3
YW
2362 log_device_debug(dev, "LINK '%s' %s:%u", pos,
2363 rules_str(rules, rule->rule.filename_off), rule->rule.filename_line);
d5a89d7d 2364 strscpyl(filename, sizeof(filename), "/dev/", pos, NULL);
cf697ec0 2365 device_add_devlink(dev, filename);
912541b0
KS
2366 }
2367 break;
2368 }
2369 case TK_A_ATTR: {
cf697ec0 2370 char attr[UTIL_PATH_SIZE], value[UTIL_NAME_SIZE];
fdd21be6 2371 _cleanup_fclose_ FILE *f = NULL;
cf697ec0 2372 const char *key_name;
912541b0 2373
cf697ec0 2374 key_name = rules_str(rules, cur->key.attr_off);
3839535a 2375 if (util_resolve_subsys_kernel(key_name, attr, sizeof(attr), false) != 0 &&
cf697ec0
YW
2376 sd_device_get_syspath(dev, &val) >= 0)
2377 strscpyl(attr, sizeof(attr), val, "/", key_name, NULL);
912541b0
KS
2378 attr_subst_subdir(attr, sizeof(attr));
2379
e20a9171 2380 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), value, sizeof(value), false);
b4ba2fe3
YW
2381 log_device_debug(dev, "ATTR '%s' writing '%s' %s:%u", attr, value,
2382 rules_str(rules, rule->rule.filename_off),
2383 rule->rule.filename_line);
47ef94ac 2384 f = fopen(attr, "we");
67e4b385 2385 if (!f)
b4ba2fe3 2386 log_device_error_errno(dev, errno, "Failed to open ATTR{%s} for writing: %m", attr);
fdd21be6 2387 else if (fprintf(f, "%s", value) <= 0)
b4ba2fe3 2388 log_device_error_errno(dev, errno, "Failed to write ATTR{%s}: %m", attr);
912541b0
KS
2389 break;
2390 }
f4cf2e5b 2391 case TK_A_SYSCTL: {
cf697ec0 2392 char filename[UTIL_PATH_SIZE], value[UTIL_NAME_SIZE];
f4cf2e5b 2393
e20a9171 2394 udev_event_apply_format(event, rules_str(rules, cur->key.attr_off), filename, sizeof(filename), false);
f4cf2e5b 2395 sysctl_normalize(filename);
e20a9171 2396 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), value, sizeof(value), false);
b4ba2fe3
YW
2397 log_device_debug(dev, "SYSCTL '%s' writing '%s' %s:%u", filename, value,
2398 rules_str(rules, rule->rule.filename_off), rule->rule.filename_line);
f4cf2e5b
KS
2399 r = sysctl_write(filename, value);
2400 if (r < 0)
b4ba2fe3 2401 log_device_error_errno(dev, r, "Failed to write SYSCTL{%s}='%s': %m", filename, value);
f4cf2e5b
KS
2402 break;
2403 }
83cd6b75
KS
2404 case TK_A_RUN_BUILTIN:
2405 case TK_A_RUN_PROGRAM: {
29448498
YW
2406 _cleanup_free_ char *cmd = NULL;
2407
e924c60f
YW
2408 if (IN_SET(cur->key.op, OP_ASSIGN, OP_ASSIGN_FINAL))
2409 hashmap_clear_free_key(event->run_list);
29448498
YW
2410
2411 r = hashmap_ensure_allocated(&event->run_list, NULL);
2412 if (r < 0)
2413 return log_oom();
2414
2415 cmd = strdup(rules_str(rules, cur->key.value_off));
2416 if (!cmd)
2417 return log_oom();
2418
2419 r = hashmap_put(event->run_list, cmd, INT_TO_PTR(cur->key.builtin_cmd));
2420 if (r < 0)
2421 return log_oom();
2422
2423 cmd = NULL;
83cd6b75 2424
b4ba2fe3
YW
2425 log_device_debug(dev, "RUN '%s' %s:%u",
2426 rules_str(rules, cur->key.value_off),
2427 rules_str(rules, rule->rule.filename_off),
2428 rule->rule.filename_line);
912541b0
KS
2429 break;
2430 }
2431 case TK_A_GOTO:
2432 if (cur->key.rule_goto == 0)
2433 break;
2434 cur = &rules->tokens[cur->key.rule_goto];
2435 continue;
2436 case TK_END:
d838e145 2437 return 0;
912541b0
KS
2438
2439 case TK_M_PARENTS_MIN:
2440 case TK_M_PARENTS_MAX:
2441 case TK_M_MAX:
2442 case TK_UNSET:
b4ba2fe3 2443 log_device_error(dev, "Wrong type %u", cur->type);
912541b0
KS
2444 goto nomatch;
2445 }
2446
2447 cur++;
2448 continue;
2449 nomatch:
2450 /* fast-forward to next rule */
2451 cur = rule + rule->rule.token_count;
912541b0 2452 }
d838e145
YW
2453
2454 return 0;
6880b25d 2455}
761dfddc 2456
9a07157d 2457int udev_rules_apply_static_dev_perms(UdevRules *rules) {
912541b0
KS
2458 struct token *cur;
2459 struct token *rule;
2460 uid_t uid = 0;
2461 gid_t gid = 0;
2462 mode_t mode = 0;
84b6ad70
TG
2463 _cleanup_strv_free_ char **tags = NULL;
2464 char **t;
2465 FILE *f = NULL;
2466 _cleanup_free_ char *path = NULL;
fdd21be6 2467 int r;
912541b0 2468
67e4b385 2469 if (!rules->tokens)
84b6ad70 2470 return 0;
912541b0
KS
2471
2472 cur = &rules->tokens[0];
2473 rule = cur;
2474 for (;;) {
2475 switch (cur->type) {
2476 case TK_RULE:
2477 /* current rule */
2478 rule = cur;
2479
2480 /* skip rules without a static_node tag */
2481 if (!rule->rule.has_static_node)
2482 goto next;
2483
2484 uid = 0;
2485 gid = 0;
2486 mode = 0;
97b11eed 2487 tags = strv_free(tags);
912541b0
KS
2488 break;
2489 case TK_A_OWNER_ID:
2490 uid = cur->key.uid;
2491 break;
2492 case TK_A_GROUP_ID:
2493 gid = cur->key.gid;
2494 break;
2495 case TK_A_MODE_ID:
2496 mode = cur->key.mode;
84b6ad70
TG
2497 break;
2498 case TK_A_TAG:
2499 r = strv_extend(&tags, rules_str(rules, cur->key.value_off));
2500 if (r < 0)
2501 goto finish;
2502
912541b0
KS
2503 break;
2504 case TK_A_STATIC_NODE: {
84b6ad70
TG
2505 char device_node[UTIL_PATH_SIZE];
2506 char tags_dir[UTIL_PATH_SIZE];
2507 char tag_symlink[UTIL_PATH_SIZE];
912541b0
KS
2508 struct stat stats;
2509
2510 /* we assure, that the permissions tokens are sorted before the static token */
ca2bb160 2511
67e4b385 2512 if (mode == 0 && uid == 0 && gid == 0 && !tags)
912541b0 2513 goto next;
d6f116a7 2514
84b6ad70 2515 strscpyl(device_node, sizeof(device_node), "/dev/", rules_str(rules, cur->key.value_off), NULL);
ca2bb160
KS
2516 if (stat(device_node, &stats) != 0)
2517 break;
2518 if (!S_ISBLK(stats.st_mode) && !S_ISCHR(stats.st_mode))
2519 break;
84b6ad70 2520
d6f116a7 2521 /* export the tags to a directory as symlinks, allowing otherwise dead nodes to be tagged */
84b6ad70 2522 if (tags) {
84b6ad70
TG
2523 STRV_FOREACH(t, tags) {
2524 _cleanup_free_ char *unescaped_filename = NULL;
2525
2526 strscpyl(tags_dir, sizeof(tags_dir), "/run/udev/static_node-tags/", *t, "/", NULL);
2527 r = mkdir_p(tags_dir, 0755);
f647962d 2528 if (r < 0)
8c19dc54 2529 return log_error_errno(r, "Failed to create %s: %m", tags_dir);
84b6ad70
TG
2530
2531 unescaped_filename = xescape(rules_str(rules, cur->key.value_off), "/.");
2532
2533 strscpyl(tag_symlink, sizeof(tag_symlink), tags_dir, unescaped_filename, NULL);
2534 r = symlink(device_node, tag_symlink);
4a62c710 2535 if (r < 0 && errno != EEXIST)
8c19dc54 2536 return log_error_errno(errno, "Failed to create symlink %s -> %s: %m",
4a62c710 2537 tag_symlink, device_node);
84b6ad70
TG
2538 }
2539 }
2540
15a72200
TG
2541 /* don't touch the permissions if only the tags were set */
2542 if (mode == 0 && uid == 0 && gid == 0)
d6f116a7
KS
2543 break;
2544
912541b0
KS
2545 if (mode == 0) {
2546 if (gid > 0)
2547 mode = 0660;
2548 else
2549 mode = 0600;
2550 }
2551 if (mode != (stats.st_mode & 01777)) {
490f0087 2552 r = chmod(device_node, mode);
25f027c5
ZJS
2553 if (r < 0)
2554 return log_error_errno(errno, "Failed to chmod '%s' %#o: %m",
2555 device_node, mode);
2556 else
9f6445e3 2557 log_debug("chmod '%s' %#o", device_node, mode);
912541b0
KS
2558 }
2559
2560 if ((uid != 0 && uid != stats.st_uid) || (gid != 0 && gid != stats.st_gid)) {
490f0087 2561 r = chown(device_node, uid, gid);
25f027c5
ZJS
2562 if (r < 0)
2563 return log_error_errno(errno, "Failed to chown '%s' %u %u: %m",
2564 device_node, uid, gid);
2565 else
9f6445e3 2566 log_debug("chown '%s' %u %u", device_node, uid, gid);
912541b0
KS
2567 }
2568
84b6ad70 2569 utimensat(AT_FDCWD, device_node, NULL, 0);
912541b0
KS
2570 break;
2571 }
2572 case TK_END:
84b6ad70 2573 goto finish;
912541b0
KS
2574 }
2575
2576 cur++;
2577 continue;
761dfddc 2578next:
912541b0
KS
2579 /* fast-forward to next rule */
2580 cur = rule + rule->rule.token_count;
2581 continue;
2582 }
84b6ad70
TG
2583
2584finish:
2585 if (f) {
2586 fflush(f);
2587 fchmod(fileno(f), 0644);
2588 if (ferror(f) || rename(path, "/run/udev/static_node-tags") < 0) {
fdd21be6
ZJS
2589 unlink_noerrno("/run/udev/static_node-tags");
2590 unlink_noerrno(path);
2591 return -errno;
84b6ad70 2592 }
84b6ad70
TG
2593 }
2594
fdd21be6 2595 return 0;
761dfddc 2596}