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