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