]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/udev/udev-rules.c
udev-builtin: move definitions related to builtin commands to udev-builtin.h
[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-builtin.h"
32 #include "udev.h"
33 #include "user-util.h"
34 #include "util.h"
35
36 #define PREALLOC_TOKEN 2048
37
38 struct uid_gid {
39 unsigned int name_off;
40 union {
41 uid_t uid;
42 gid_t gid;
43 };
44 };
45
46 static const char* const rules_dirs[] = {
47 "/etc/udev/rules.d",
48 "/run/udev/rules.d",
49 UDEVLIBEXECDIR "/rules.d",
50 NULL
51 };
52
53 struct udev_rules {
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, USER_CREDS_ALLOW_MISSING);
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, USER_CREDS_ALLOW_MISSING);
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(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(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(&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(key + STRLEN("ATTR"));
1086 if (attr == NULL)
1087 LOG_AND_RETURN("error parsing %s attribute", "ATTR");
1088
1089 if (op == OP_REMOVE)
1090 LOG_AND_RETURN("invalid %s operation", "ATTR");
1091
1092 if (op < OP_MATCH_MAX)
1093 rule_add_key(&rule_tmp, TK_M_ATTR, op, value, attr);
1094 else
1095 rule_add_key(&rule_tmp, TK_A_ATTR, op, value, attr);
1096
1097 } else if (startswith(key, "SYSCTL{")) {
1098 attr = get_key_attribute(key + STRLEN("SYSCTL"));
1099 if (attr == NULL)
1100 LOG_AND_RETURN("error parsing %s attribute", "ATTR");
1101
1102 if (op == OP_REMOVE)
1103 LOG_AND_RETURN("invalid %s operation", "ATTR");
1104
1105 if (op < OP_MATCH_MAX)
1106 rule_add_key(&rule_tmp, TK_M_SYSCTL, op, value, attr);
1107 else
1108 rule_add_key(&rule_tmp, TK_A_SYSCTL, op, value, attr);
1109
1110 } else if (startswith(key, "SECLABEL{")) {
1111 attr = get_key_attribute(key + STRLEN("SECLABEL"));
1112 if (attr == NULL)
1113 LOG_AND_RETURN("error parsing %s attribute", "SECLABEL");
1114
1115 if (op == OP_REMOVE)
1116 LOG_AND_RETURN("invalid %s operation", "SECLABEL");
1117
1118 rule_add_key(&rule_tmp, TK_A_SECLABEL, op, value, attr);
1119
1120 } else if (streq(key, "KERNELS")) {
1121 if (op > OP_MATCH_MAX)
1122 LOG_AND_RETURN("invalid %s operation", key);
1123
1124 rule_add_key(&rule_tmp, TK_M_KERNELS, op, value, NULL);
1125
1126 } else if (streq(key, "SUBSYSTEMS")) {
1127 if (op > OP_MATCH_MAX)
1128 LOG_AND_RETURN("invalid %s operation", key);
1129
1130 rule_add_key(&rule_tmp, TK_M_SUBSYSTEMS, op, value, NULL);
1131
1132 } else if (streq(key, "DRIVERS")) {
1133 if (op > OP_MATCH_MAX)
1134 LOG_AND_RETURN("invalid %s operation", key);
1135
1136 rule_add_key(&rule_tmp, TK_M_DRIVERS, op, value, NULL);
1137
1138 } else if (startswith(key, "ATTRS{")) {
1139 if (op > OP_MATCH_MAX)
1140 LOG_AND_RETURN("invalid %s operation", "ATTRS");
1141
1142 attr = get_key_attribute(key + STRLEN("ATTRS"));
1143 if (attr == NULL)
1144 LOG_AND_RETURN("error parsing %s attribute", "ATTRS");
1145
1146 if (startswith(attr, "device/"))
1147 LOG_RULE_WARNING("'device' link may not be available in future kernels; please fix");
1148 if (strstr(attr, "../") != NULL)
1149 LOG_RULE_WARNING("direct reference to parent sysfs directory, may break in future kernels; please fix");
1150 rule_add_key(&rule_tmp, TK_M_ATTRS, op, value, attr);
1151
1152 } else if (streq(key, "TAGS")) {
1153 if (op > OP_MATCH_MAX)
1154 LOG_AND_RETURN("invalid %s operation", key);
1155
1156 rule_add_key(&rule_tmp, TK_M_TAGS, op, value, NULL);
1157
1158 } else if (startswith(key, "ENV{")) {
1159 attr = get_key_attribute(key + STRLEN("ENV"));
1160 if (attr == NULL)
1161 LOG_AND_RETURN("error parsing %s attribute", "ENV");
1162
1163 if (op == OP_REMOVE)
1164 LOG_AND_RETURN("invalid %s operation", "ENV");
1165
1166 if (op < OP_MATCH_MAX)
1167 rule_add_key(&rule_tmp, TK_M_ENV, op, value, attr);
1168 else {
1169 if (STR_IN_SET(attr,
1170 "ACTION",
1171 "SUBSYSTEM",
1172 "DEVTYPE",
1173 "MAJOR",
1174 "MINOR",
1175 "DRIVER",
1176 "IFINDEX",
1177 "DEVNAME",
1178 "DEVLINKS",
1179 "DEVPATH",
1180 "TAGS"))
1181 LOG_AND_RETURN("invalid ENV attribute, '%s' cannot be set", attr);
1182
1183 rule_add_key(&rule_tmp, TK_A_ENV, op, value, attr);
1184 }
1185
1186 } else if (streq(key, "TAG")) {
1187 if (op < OP_MATCH_MAX)
1188 rule_add_key(&rule_tmp, TK_M_TAG, op, value, NULL);
1189 else
1190 rule_add_key(&rule_tmp, TK_A_TAG, op, value, NULL);
1191
1192 } else if (streq(key, "PROGRAM")) {
1193 if (op == OP_REMOVE)
1194 LOG_AND_RETURN("invalid %s operation", key);
1195
1196 rule_add_key(&rule_tmp, TK_M_PROGRAM, op, value, NULL);
1197
1198 } else if (streq(key, "RESULT")) {
1199 if (op > OP_MATCH_MAX)
1200 LOG_AND_RETURN("invalid %s operation", key);
1201
1202 rule_add_key(&rule_tmp, TK_M_RESULT, op, value, NULL);
1203
1204 } else if (startswith(key, "IMPORT")) {
1205 attr = get_key_attribute(key + STRLEN("IMPORT"));
1206 if (attr == NULL) {
1207 LOG_RULE_WARNING("ignoring IMPORT{} with missing type");
1208 continue;
1209 }
1210 if (op == OP_REMOVE)
1211 LOG_AND_RETURN("invalid %s operation", "IMPORT");
1212
1213 if (streq(attr, "program")) {
1214 /* find known built-in command */
1215 if (value[0] != '/') {
1216 const enum udev_builtin_cmd cmd = udev_builtin_lookup(value);
1217
1218 if (cmd < UDEV_BUILTIN_MAX) {
1219 LOG_RULE_DEBUG("IMPORT found builtin '%s', replacing", value);
1220 rule_add_key(&rule_tmp, TK_M_IMPORT_BUILTIN, op, value, &cmd);
1221 continue;
1222 }
1223 }
1224 rule_add_key(&rule_tmp, TK_M_IMPORT_PROG, op, value, NULL);
1225 } else if (streq(attr, "builtin")) {
1226 const enum udev_builtin_cmd cmd = udev_builtin_lookup(value);
1227
1228 if (cmd >= UDEV_BUILTIN_MAX)
1229 LOG_RULE_WARNING("IMPORT{builtin} '%s' unknown", value);
1230 else
1231 rule_add_key(&rule_tmp, TK_M_IMPORT_BUILTIN, op, value, &cmd);
1232 } else if (streq(attr, "file"))
1233 rule_add_key(&rule_tmp, TK_M_IMPORT_FILE, op, value, NULL);
1234 else if (streq(attr, "db"))
1235 rule_add_key(&rule_tmp, TK_M_IMPORT_DB, op, value, NULL);
1236 else if (streq(attr, "cmdline"))
1237 rule_add_key(&rule_tmp, TK_M_IMPORT_CMDLINE, op, value, NULL);
1238 else if (streq(attr, "parent"))
1239 rule_add_key(&rule_tmp, TK_M_IMPORT_PARENT, op, value, NULL);
1240 else
1241 LOG_RULE_ERROR("ignoring unknown %s{} type '%s'", "IMPORT", attr);
1242
1243 } else if (startswith(key, "TEST")) {
1244 mode_t mode = 0;
1245
1246 if (op > OP_MATCH_MAX)
1247 LOG_AND_RETURN("invalid %s operation", "TEST");
1248
1249 attr = get_key_attribute(key + STRLEN("TEST"));
1250 if (attr != NULL) {
1251 mode = strtol(attr, NULL, 8);
1252 rule_add_key(&rule_tmp, TK_M_TEST, op, value, &mode);
1253 } else
1254 rule_add_key(&rule_tmp, TK_M_TEST, op, value, NULL);
1255
1256 } else if (startswith(key, "RUN")) {
1257 attr = get_key_attribute(key + STRLEN("RUN"));
1258 if (attr == NULL)
1259 attr = "program";
1260 if (op == OP_REMOVE)
1261 LOG_AND_RETURN("invalid %s operation", "RUN");
1262
1263 if (streq(attr, "builtin")) {
1264 const enum udev_builtin_cmd cmd = udev_builtin_lookup(value);
1265
1266 if (cmd < UDEV_BUILTIN_MAX)
1267 rule_add_key(&rule_tmp, TK_A_RUN_BUILTIN, op, value, &cmd);
1268 else
1269 LOG_RULE_ERROR("RUN{builtin}: '%s' unknown", value);
1270 } else if (streq(attr, "program")) {
1271 const enum udev_builtin_cmd cmd = UDEV_BUILTIN_MAX;
1272
1273 rule_add_key(&rule_tmp, TK_A_RUN_PROGRAM, op, value, &cmd);
1274 } else
1275 LOG_RULE_ERROR("ignoring unknown %s{} type '%s'", "RUN", attr);
1276
1277 } else if (streq(key, "LABEL")) {
1278 if (op == OP_REMOVE)
1279 LOG_AND_RETURN("invalid %s operation", key);
1280
1281 rule_tmp.rule.rule.label_off = rules_add_string(rules, value);
1282
1283 } else if (streq(key, "GOTO")) {
1284 if (op == OP_REMOVE)
1285 LOG_AND_RETURN("invalid %s operation", key);
1286
1287 rule_add_key(&rule_tmp, TK_A_GOTO, 0, value, NULL);
1288
1289 } else if (startswith(key, "NAME")) {
1290 if (op == OP_REMOVE)
1291 LOG_AND_RETURN("invalid %s operation", key);
1292
1293 if (op < OP_MATCH_MAX)
1294 rule_add_key(&rule_tmp, TK_M_NAME, op, value, NULL);
1295 else {
1296 if (streq(value, "%k")) {
1297 LOG_RULE_WARNING("NAME=\"%%k\" is ignored, because it breaks kernel supplied names; please remove");
1298 continue;
1299 }
1300 if (isempty(value)) {
1301 LOG_RULE_DEBUG("NAME=\"\" is ignored, because udev will not delete any device nodes; please remove");
1302 continue;
1303 }
1304 rule_add_key(&rule_tmp, TK_A_NAME, op, value, NULL);
1305 }
1306 rule_tmp.rule.rule.can_set_name = true;
1307
1308 } else if (streq(key, "SYMLINK")) {
1309 if (op == OP_REMOVE)
1310 LOG_AND_RETURN("invalid %s operation", key);
1311
1312 if (op < OP_MATCH_MAX)
1313 rule_add_key(&rule_tmp, TK_M_DEVLINK, op, value, NULL);
1314 else
1315 rule_add_key(&rule_tmp, TK_A_DEVLINK, op, value, NULL);
1316 rule_tmp.rule.rule.can_set_name = true;
1317
1318 } else if (streq(key, "OWNER")) {
1319 uid_t uid;
1320 char *endptr;
1321
1322 if (op == OP_REMOVE)
1323 LOG_AND_RETURN("invalid %s operation", key);
1324
1325 uid = strtoul(value, &endptr, 10);
1326 if (endptr[0] == '\0')
1327 rule_add_key(&rule_tmp, TK_A_OWNER_ID, op, NULL, &uid);
1328 else if (rules->resolve_names > 0 && strchr("$%", value[0]) == NULL) {
1329 uid = add_uid(rules, value);
1330 rule_add_key(&rule_tmp, TK_A_OWNER_ID, op, NULL, &uid);
1331 } else if (rules->resolve_names >= 0)
1332 rule_add_key(&rule_tmp, TK_A_OWNER, op, value, NULL);
1333
1334 rule_tmp.rule.rule.can_set_name = true;
1335
1336 } else if (streq(key, "GROUP")) {
1337 gid_t gid;
1338 char *endptr;
1339
1340 if (op == OP_REMOVE)
1341 LOG_AND_RETURN("invalid %s operation", key);
1342
1343 gid = strtoul(value, &endptr, 10);
1344 if (endptr[0] == '\0')
1345 rule_add_key(&rule_tmp, TK_A_GROUP_ID, op, NULL, &gid);
1346 else if ((rules->resolve_names > 0) && strchr("$%", value[0]) == NULL) {
1347 gid = add_gid(rules, value);
1348 rule_add_key(&rule_tmp, TK_A_GROUP_ID, op, NULL, &gid);
1349 } else if (rules->resolve_names >= 0)
1350 rule_add_key(&rule_tmp, TK_A_GROUP, op, value, NULL);
1351
1352 rule_tmp.rule.rule.can_set_name = true;
1353
1354 } else if (streq(key, "MODE")) {
1355 mode_t mode;
1356 char *endptr;
1357
1358 if (op == OP_REMOVE)
1359 LOG_AND_RETURN("invalid %s operation", key);
1360
1361 mode = strtol(value, &endptr, 8);
1362 if (endptr[0] == '\0')
1363 rule_add_key(&rule_tmp, TK_A_MODE_ID, op, NULL, &mode);
1364 else
1365 rule_add_key(&rule_tmp, TK_A_MODE, op, value, NULL);
1366 rule_tmp.rule.rule.can_set_name = true;
1367
1368 } else if (streq(key, "OPTIONS")) {
1369 const char *pos;
1370
1371 if (op == OP_REMOVE)
1372 LOG_AND_RETURN("invalid %s operation", key);
1373
1374 pos = strstr(value, "link_priority=");
1375 if (pos != NULL) {
1376 int prio = atoi(pos + STRLEN("link_priority="));
1377
1378 rule_add_key(&rule_tmp, TK_A_DEVLINK_PRIO, op, NULL, &prio);
1379 }
1380
1381 pos = strstr(value, "string_escape=");
1382 if (pos != NULL) {
1383 pos += STRLEN("string_escape=");
1384 if (startswith(pos, "none"))
1385 rule_add_key(&rule_tmp, TK_A_STRING_ESCAPE_NONE, op, NULL, NULL);
1386 else if (startswith(pos, "replace"))
1387 rule_add_key(&rule_tmp, TK_A_STRING_ESCAPE_REPLACE, op, NULL, NULL);
1388 }
1389
1390 pos = strstr(value, "db_persist");
1391 if (pos != NULL)
1392 rule_add_key(&rule_tmp, TK_A_DB_PERSIST, op, NULL, NULL);
1393
1394 pos = strstr(value, "nowatch");
1395 if (pos != NULL) {
1396 const int off = 0;
1397
1398 rule_add_key(&rule_tmp, TK_A_INOTIFY_WATCH, op, NULL, &off);
1399 } else {
1400 pos = strstr(value, "watch");
1401 if (pos != NULL) {
1402 const int on = 1;
1403
1404 rule_add_key(&rule_tmp, TK_A_INOTIFY_WATCH, op, NULL, &on);
1405 }
1406 }
1407
1408 pos = strstr(value, "static_node=");
1409 if (pos != NULL) {
1410 pos += STRLEN("static_node=");
1411 rule_add_key(&rule_tmp, TK_A_STATIC_NODE, op, pos, NULL);
1412 rule_tmp.rule.rule.has_static_node = true;
1413 }
1414
1415 } else
1416 LOG_AND_RETURN("unknown key '%s'", key);
1417 }
1418
1419 /* add rule token and sort tokens */
1420 rule_tmp.rule.rule.token_count = 1 + rule_tmp.token_cur;
1421 if (add_token(rules, &rule_tmp.rule) != 0 || sort_token(rules, &rule_tmp) != 0)
1422 LOG_RULE_ERROR("failed to add rule token");
1423 }
1424
1425 static int parse_file(struct udev_rules *rules, const char *filename) {
1426 _cleanup_fclose_ FILE *f = NULL;
1427 unsigned int first_token;
1428 unsigned int filename_off;
1429 char line[UTIL_LINE_SIZE];
1430 int line_nr = 0;
1431 unsigned int i;
1432
1433 f = fopen(filename, "re");
1434 if (!f) {
1435 if (errno == ENOENT)
1436 return 0;
1437 else
1438 return -errno;
1439 }
1440
1441 if (null_or_empty_fd(fileno(f))) {
1442 log_debug("Skipping empty file: %s", filename);
1443 return 0;
1444 } else
1445 log_debug("Reading rules file: %s", filename);
1446
1447 first_token = rules->token_cur;
1448 filename_off = rules_add_string(rules, filename);
1449
1450 while (fgets(line, sizeof(line), f) != NULL) {
1451 char *key;
1452 size_t len;
1453
1454 /* skip whitespace */
1455 line_nr++;
1456 key = line;
1457 while (isspace(key[0]))
1458 key++;
1459
1460 /* comment */
1461 if (key[0] == '#')
1462 continue;
1463
1464 len = strlen(line);
1465 if (len < 3)
1466 continue;
1467
1468 /* continue reading if backslash+newline is found */
1469 while (line[len-2] == '\\') {
1470 if (fgets(&line[len-2], (sizeof(line)-len)+2, f) == NULL)
1471 break;
1472 if (strlen(&line[len-2]) < 2)
1473 break;
1474 line_nr++;
1475 len = strlen(line);
1476 }
1477
1478 if (len+1 >= sizeof(line)) {
1479 log_error("line too long '%s':%u, ignored", filename, line_nr);
1480 continue;
1481 }
1482 add_rule(rules, key, filename, filename_off, line_nr);
1483 }
1484
1485 /* link GOTOs to LABEL rules in this file to be able to fast-forward */
1486 for (i = first_token+1; i < rules->token_cur; i++) {
1487 if (rules->tokens[i].type == TK_A_GOTO) {
1488 char *label = rules_str(rules, rules->tokens[i].key.value_off);
1489 unsigned int j;
1490
1491 for (j = i+1; j < rules->token_cur; j++) {
1492 if (rules->tokens[j].type != TK_RULE)
1493 continue;
1494 if (rules->tokens[j].rule.label_off == 0)
1495 continue;
1496 if (!streq(label, rules_str(rules, rules->tokens[j].rule.label_off)))
1497 continue;
1498 rules->tokens[i].key.rule_goto = j;
1499 break;
1500 }
1501 if (rules->tokens[i].key.rule_goto == 0)
1502 log_error("GOTO '%s' has no matching label in: '%s'", label, filename);
1503 }
1504 }
1505 return 0;
1506 }
1507
1508 struct udev_rules *udev_rules_new(int resolve_names) {
1509 struct udev_rules *rules;
1510 struct udev_list file_list;
1511 struct token end_token;
1512 char **files, **f;
1513 int r;
1514
1515 rules = new0(struct udev_rules, 1);
1516 if (rules == NULL)
1517 return NULL;
1518 rules->resolve_names = resolve_names;
1519 udev_list_init(NULL, &file_list, true);
1520
1521 /* init token array and string buffer */
1522 rules->tokens = malloc_multiply(PREALLOC_TOKEN, sizeof(struct token));
1523 if (rules->tokens == NULL)
1524 return udev_rules_unref(rules);
1525 rules->token_max = PREALLOC_TOKEN;
1526
1527 rules->strbuf = strbuf_new();
1528 if (!rules->strbuf)
1529 return udev_rules_unref(rules);
1530
1531 udev_rules_check_timestamp(rules);
1532
1533 r = conf_files_list_strv(&files, ".rules", NULL, 0, rules_dirs);
1534 if (r < 0) {
1535 log_error_errno(r, "failed to enumerate rules files: %m");
1536 return udev_rules_unref(rules);
1537 }
1538
1539 /*
1540 * The offset value in the rules strct is limited; add all
1541 * rules file names to the beginning of the string buffer.
1542 */
1543 STRV_FOREACH(f, files)
1544 rules_add_string(rules, *f);
1545
1546 STRV_FOREACH(f, files)
1547 parse_file(rules, *f);
1548
1549 strv_free(files);
1550
1551 memzero(&end_token, sizeof(struct token));
1552 end_token.type = TK_END;
1553 add_token(rules, &end_token);
1554 log_debug("rules contain %zu bytes tokens (%u * %zu bytes), %zu bytes strings",
1555 rules->token_max * sizeof(struct token), rules->token_max, sizeof(struct token), rules->strbuf->len);
1556
1557 /* cleanup temporary strbuf data */
1558 log_debug("%zu strings (%zu bytes), %zu de-duplicated (%zu bytes), %zu trie nodes used",
1559 rules->strbuf->in_count, rules->strbuf->in_len,
1560 rules->strbuf->dedup_count, rules->strbuf->dedup_len, rules->strbuf->nodes_count);
1561 strbuf_complete(rules->strbuf);
1562
1563 /* cleanup uid/gid cache */
1564 rules->uids = mfree(rules->uids);
1565 rules->uids_cur = 0;
1566 rules->uids_max = 0;
1567 rules->gids = mfree(rules->gids);
1568 rules->gids_cur = 0;
1569 rules->gids_max = 0;
1570
1571 dump_rules(rules);
1572 return rules;
1573 }
1574
1575 struct udev_rules *udev_rules_unref(struct udev_rules *rules) {
1576 if (rules == NULL)
1577 return NULL;
1578 free(rules->tokens);
1579 strbuf_cleanup(rules->strbuf);
1580 free(rules->uids);
1581 free(rules->gids);
1582 return mfree(rules);
1583 }
1584
1585 bool udev_rules_check_timestamp(struct udev_rules *rules) {
1586 if (!rules)
1587 return false;
1588
1589 return paths_check_timestamp(rules_dirs, &rules->dirs_ts_usec, true);
1590 }
1591
1592 static int match_key(struct udev_rules *rules, struct token *token, const char *val) {
1593 char *key_value = rules_str(rules, token->key.value_off);
1594 char *pos;
1595 bool match = false;
1596
1597 if (val == NULL)
1598 val = "";
1599
1600 switch (token->key.glob) {
1601 case GL_PLAIN:
1602 match = (streq(key_value, val));
1603 break;
1604 case GL_GLOB:
1605 match = (fnmatch(key_value, val, 0) == 0);
1606 break;
1607 case GL_SPLIT:
1608 {
1609 const char *s;
1610 size_t len;
1611
1612 s = rules_str(rules, token->key.value_off);
1613 len = strlen(val);
1614 for (;;) {
1615 const char *next;
1616
1617 next = strchr(s, '|');
1618 if (next != NULL) {
1619 size_t matchlen = (size_t)(next - s);
1620
1621 match = (matchlen == len && strneq(s, val, matchlen));
1622 if (match)
1623 break;
1624 } else {
1625 match = (streq(s, val));
1626 break;
1627 }
1628 s = &next[1];
1629 }
1630 break;
1631 }
1632 case GL_SPLIT_GLOB:
1633 {
1634 char value[UTIL_PATH_SIZE];
1635
1636 strscpy(value, sizeof(value), rules_str(rules, token->key.value_off));
1637 key_value = value;
1638 while (key_value != NULL) {
1639 pos = strchr(key_value, '|');
1640 if (pos != NULL) {
1641 pos[0] = '\0';
1642 pos = &pos[1];
1643 }
1644 match = (fnmatch(key_value, val, 0) == 0);
1645 if (match)
1646 break;
1647 key_value = pos;
1648 }
1649 break;
1650 }
1651 case GL_SOMETHING:
1652 match = (val[0] != '\0');
1653 break;
1654 case GL_UNSET:
1655 return -1;
1656 }
1657
1658 if (match && (token->key.op == OP_MATCH))
1659 return 0;
1660 if (!match && (token->key.op == OP_NOMATCH))
1661 return 0;
1662 return -1;
1663 }
1664
1665 static int match_attr(struct udev_rules *rules, struct udev_device *dev, struct udev_event *event, struct token *cur) {
1666 const char *name;
1667 char nbuf[UTIL_NAME_SIZE];
1668 const char *value;
1669 char vbuf[UTIL_NAME_SIZE];
1670 size_t len;
1671
1672 name = rules_str(rules, cur->key.attr_off);
1673 switch (cur->key.attrsubst) {
1674 case SB_FORMAT:
1675 udev_event_apply_format(event, name, nbuf, sizeof(nbuf), false);
1676 name = nbuf;
1677 _fallthrough_;
1678 case SB_NONE:
1679 value = udev_device_get_sysattr_value(dev, name);
1680 if (value == NULL)
1681 return -1;
1682 break;
1683 case SB_SUBSYS:
1684 if (util_resolve_subsys_kernel(name, vbuf, sizeof(vbuf), 1) != 0)
1685 return -1;
1686 value = vbuf;
1687 break;
1688 default:
1689 return -1;
1690 }
1691
1692 /* remove trailing whitespace, if not asked to match for it */
1693 len = strlen(value);
1694 if (len > 0 && isspace(value[len-1])) {
1695 const char *key_value;
1696 size_t klen;
1697
1698 key_value = rules_str(rules, cur->key.value_off);
1699 klen = strlen(key_value);
1700 if (klen > 0 && !isspace(key_value[klen-1])) {
1701 if (value != vbuf) {
1702 strscpy(vbuf, sizeof(vbuf), value);
1703 value = vbuf;
1704 }
1705 while (len > 0 && isspace(vbuf[--len]))
1706 vbuf[len] = '\0';
1707 }
1708 }
1709
1710 return match_key(rules, cur, value);
1711 }
1712
1713 enum escape_type {
1714 ESCAPE_UNSET,
1715 ESCAPE_NONE,
1716 ESCAPE_REPLACE,
1717 };
1718
1719 void udev_rules_apply_to_event(struct udev_rules *rules,
1720 struct udev_event *event,
1721 usec_t timeout_usec,
1722 usec_t timeout_warn_usec,
1723 struct udev_list *properties_list) {
1724 struct token *cur;
1725 struct token *rule;
1726 enum escape_type esc = ESCAPE_UNSET;
1727 bool can_set_name;
1728 int r;
1729
1730 if (rules->tokens == NULL)
1731 return;
1732
1733 can_set_name = ((!streq(udev_device_get_action(event->dev), "remove")) &&
1734 (major(udev_device_get_devnum(event->dev)) > 0 ||
1735 udev_device_get_ifindex(event->dev) > 0));
1736
1737 /* loop through token list, match, run actions or forward to next rule */
1738 cur = &rules->tokens[0];
1739 rule = cur;
1740 for (;;) {
1741 dump_token(rules, cur);
1742 switch (cur->type) {
1743 case TK_RULE:
1744 /* current rule */
1745 rule = cur;
1746 /* possibly skip rules which want to set NAME, SYMLINK, OWNER, GROUP, MODE */
1747 if (!can_set_name && rule->rule.can_set_name)
1748 goto nomatch;
1749 esc = ESCAPE_UNSET;
1750 break;
1751 case TK_M_ACTION:
1752 if (match_key(rules, cur, udev_device_get_action(event->dev)) != 0)
1753 goto nomatch;
1754 break;
1755 case TK_M_DEVPATH:
1756 if (match_key(rules, cur, udev_device_get_devpath(event->dev)) != 0)
1757 goto nomatch;
1758 break;
1759 case TK_M_KERNEL:
1760 if (match_key(rules, cur, udev_device_get_sysname(event->dev)) != 0)
1761 goto nomatch;
1762 break;
1763 case TK_M_DEVLINK: {
1764 struct udev_list_entry *list_entry;
1765 bool match = false;
1766
1767 udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(event->dev)) {
1768 const char *devlink;
1769
1770 devlink = udev_list_entry_get_name(list_entry) + STRLEN("/dev/");
1771 if (match_key(rules, cur, devlink) == 0) {
1772 match = true;
1773 break;
1774 }
1775 }
1776 if (!match)
1777 goto nomatch;
1778 break;
1779 }
1780 case TK_M_NAME:
1781 if (match_key(rules, cur, event->name) != 0)
1782 goto nomatch;
1783 break;
1784 case TK_M_ENV: {
1785 const char *key_name = rules_str(rules, cur->key.attr_off);
1786 const char *value;
1787
1788 value = udev_device_get_property_value(event->dev, key_name);
1789
1790 /* check global properties */
1791 if (!value && properties_list) {
1792 struct udev_list_entry *list_entry;
1793
1794 list_entry = udev_list_get_entry(properties_list);
1795 list_entry = udev_list_entry_get_by_name(list_entry, key_name);
1796 if (list_entry != NULL)
1797 value = udev_list_entry_get_value(list_entry);
1798 }
1799
1800 if (!value)
1801 value = "";
1802 if (match_key(rules, cur, value))
1803 goto nomatch;
1804 break;
1805 }
1806 case TK_M_TAG: {
1807 struct udev_list_entry *list_entry;
1808 bool match = false;
1809
1810 udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(event->dev)) {
1811 if (streq(rules_str(rules, cur->key.value_off), udev_list_entry_get_name(list_entry))) {
1812 match = true;
1813 break;
1814 }
1815 }
1816 if ((!match && (cur->key.op != OP_NOMATCH)) ||
1817 (match && (cur->key.op == OP_NOMATCH)))
1818 goto nomatch;
1819 break;
1820 }
1821 case TK_M_SUBSYSTEM:
1822 if (match_key(rules, cur, udev_device_get_subsystem(event->dev)) != 0)
1823 goto nomatch;
1824 break;
1825 case TK_M_DRIVER:
1826 if (match_key(rules, cur, udev_device_get_driver(event->dev)) != 0)
1827 goto nomatch;
1828 break;
1829 case TK_M_ATTR:
1830 if (match_attr(rules, event->dev, event, cur) != 0)
1831 goto nomatch;
1832 break;
1833 case TK_M_SYSCTL: {
1834 char filename[UTIL_PATH_SIZE];
1835 _cleanup_free_ char *value = NULL;
1836 size_t len;
1837
1838 udev_event_apply_format(event, rules_str(rules, cur->key.attr_off), filename, sizeof(filename), false);
1839 sysctl_normalize(filename);
1840 if (sysctl_read(filename, &value) < 0)
1841 goto nomatch;
1842
1843 len = strlen(value);
1844 while (len > 0 && isspace(value[--len]))
1845 value[len] = '\0';
1846 if (match_key(rules, cur, value) != 0)
1847 goto nomatch;
1848 break;
1849 }
1850 case TK_M_KERNELS:
1851 case TK_M_SUBSYSTEMS:
1852 case TK_M_DRIVERS:
1853 case TK_M_ATTRS:
1854 case TK_M_TAGS: {
1855 struct token *next;
1856
1857 /* get whole sequence of parent matches */
1858 next = cur;
1859 while (next->type > TK_M_PARENTS_MIN && next->type < TK_M_PARENTS_MAX)
1860 next++;
1861
1862 /* loop over parents */
1863 event->dev_parent = event->dev;
1864 for (;;) {
1865 struct token *key;
1866
1867 /* loop over sequence of parent match keys */
1868 for (key = cur; key < next; key++ ) {
1869 dump_token(rules, key);
1870 switch(key->type) {
1871 case TK_M_KERNELS:
1872 if (match_key(rules, key, udev_device_get_sysname(event->dev_parent)) != 0)
1873 goto try_parent;
1874 break;
1875 case TK_M_SUBSYSTEMS:
1876 if (match_key(rules, key, udev_device_get_subsystem(event->dev_parent)) != 0)
1877 goto try_parent;
1878 break;
1879 case TK_M_DRIVERS:
1880 if (match_key(rules, key, udev_device_get_driver(event->dev_parent)) != 0)
1881 goto try_parent;
1882 break;
1883 case TK_M_ATTRS:
1884 if (match_attr(rules, event->dev_parent, event, key) != 0)
1885 goto try_parent;
1886 break;
1887 case TK_M_TAGS: {
1888 bool match = udev_device_has_tag(event->dev_parent, rules_str(rules, cur->key.value_off));
1889
1890 if (match && key->key.op == OP_NOMATCH)
1891 goto try_parent;
1892 if (!match && key->key.op == OP_MATCH)
1893 goto try_parent;
1894 break;
1895 }
1896 default:
1897 goto nomatch;
1898 }
1899 }
1900 break;
1901
1902 try_parent:
1903 event->dev_parent = udev_device_get_parent(event->dev_parent);
1904 if (event->dev_parent == NULL)
1905 goto nomatch;
1906 }
1907 /* move behind our sequence of parent match keys */
1908 cur = next;
1909 continue;
1910 }
1911 case TK_M_TEST: {
1912 char filename[UTIL_PATH_SIZE];
1913 struct stat statbuf;
1914 int match;
1915
1916 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), filename, sizeof(filename), false);
1917 if (util_resolve_subsys_kernel(filename, filename, sizeof(filename), 0) != 0) {
1918 if (filename[0] != '/') {
1919 char tmp[UTIL_PATH_SIZE];
1920
1921 strscpy(tmp, sizeof(tmp), filename);
1922 strscpyl(filename, sizeof(filename),
1923 udev_device_get_syspath(event->dev), "/", tmp, NULL);
1924 }
1925 }
1926 attr_subst_subdir(filename, sizeof(filename));
1927
1928 match = (stat(filename, &statbuf) == 0);
1929 if (match && cur->key.mode > 0)
1930 match = ((statbuf.st_mode & cur->key.mode) > 0);
1931 if (match && cur->key.op == OP_NOMATCH)
1932 goto nomatch;
1933 if (!match && cur->key.op == OP_MATCH)
1934 goto nomatch;
1935 break;
1936 }
1937 case TK_M_PROGRAM: {
1938 char program[UTIL_PATH_SIZE];
1939 char result[UTIL_LINE_SIZE];
1940
1941 event->program_result = mfree(event->program_result);
1942 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), program, sizeof(program), false);
1943 log_debug("PROGRAM '%s' %s:%u",
1944 program,
1945 rules_str(rules, rule->rule.filename_off),
1946 rule->rule.filename_line);
1947
1948 if (udev_event_spawn(event, timeout_usec, timeout_warn_usec, true, program, result, sizeof(result)) < 0) {
1949 if (cur->key.op != OP_NOMATCH)
1950 goto nomatch;
1951 } else {
1952 int count;
1953
1954 delete_trailing_chars(result, "\n");
1955 if (IN_SET(esc, ESCAPE_UNSET, ESCAPE_REPLACE)) {
1956 count = util_replace_chars(result, UDEV_ALLOWED_CHARS_INPUT);
1957 if (count > 0)
1958 log_debug("%i character(s) replaced" , count);
1959 }
1960 event->program_result = strdup(result);
1961 if (cur->key.op == OP_NOMATCH)
1962 goto nomatch;
1963 }
1964 break;
1965 }
1966 case TK_M_IMPORT_FILE: {
1967 char import[UTIL_PATH_SIZE];
1968
1969 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), import, sizeof(import), false);
1970 if (import_file_into_properties(event->dev, import) != 0)
1971 if (cur->key.op != OP_NOMATCH)
1972 goto nomatch;
1973 break;
1974 }
1975 case TK_M_IMPORT_PROG: {
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 log_debug("IMPORT '%s' %s:%u",
1980 import,
1981 rules_str(rules, rule->rule.filename_off),
1982 rule->rule.filename_line);
1983
1984 if (import_program_into_properties(event, timeout_usec, timeout_warn_usec, import) != 0)
1985 if (cur->key.op != OP_NOMATCH)
1986 goto nomatch;
1987 break;
1988 }
1989 case TK_M_IMPORT_BUILTIN: {
1990 char command[UTIL_PATH_SIZE];
1991
1992 if (udev_builtin_run_once(cur->key.builtin_cmd)) {
1993 /* check if we ran already */
1994 if (event->builtin_run & (1 << cur->key.builtin_cmd)) {
1995 log_debug("IMPORT builtin skip '%s' %s:%u",
1996 udev_builtin_name(cur->key.builtin_cmd),
1997 rules_str(rules, rule->rule.filename_off),
1998 rule->rule.filename_line);
1999 /* return the result from earlier run */
2000 if (event->builtin_ret & (1 << cur->key.builtin_cmd))
2001 if (cur->key.op != OP_NOMATCH)
2002 goto nomatch;
2003 break;
2004 }
2005 /* mark as ran */
2006 event->builtin_run |= (1 << cur->key.builtin_cmd);
2007 }
2008
2009 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), command, sizeof(command), false);
2010 log_debug("IMPORT builtin '%s' %s:%u",
2011 udev_builtin_name(cur->key.builtin_cmd),
2012 rules_str(rules, rule->rule.filename_off),
2013 rule->rule.filename_line);
2014
2015 if (udev_builtin_run(event->dev, cur->key.builtin_cmd, command, false) != 0) {
2016 /* remember failure */
2017 log_debug("IMPORT builtin '%s' returned non-zero",
2018 udev_builtin_name(cur->key.builtin_cmd));
2019 event->builtin_ret |= (1 << cur->key.builtin_cmd);
2020 if (cur->key.op != OP_NOMATCH)
2021 goto nomatch;
2022 }
2023 break;
2024 }
2025 case TK_M_IMPORT_DB: {
2026 const char *key = rules_str(rules, cur->key.value_off);
2027 const char *value;
2028
2029 value = udev_device_get_property_value(event->dev_db, key);
2030 if (value != NULL)
2031 udev_device_add_property(event->dev, key, value);
2032 else {
2033 if (cur->key.op != OP_NOMATCH)
2034 goto nomatch;
2035 }
2036 break;
2037 }
2038 case TK_M_IMPORT_CMDLINE: {
2039 _cleanup_free_ char *value = NULL;
2040 bool imported = false;
2041 const char *key;
2042
2043 key = rules_str(rules, cur->key.value_off);
2044
2045 r = proc_cmdline_get_key(key, PROC_CMDLINE_VALUE_OPTIONAL, &value);
2046 if (r < 0)
2047 log_debug_errno(r, "Failed to read %s from /proc/cmdline, ignoring: %m", key);
2048 else if (r > 0) {
2049 imported = true;
2050
2051 if (value)
2052 udev_device_add_property(event->dev, key, value);
2053 else
2054 /* we import simple flags as 'FLAG=1' */
2055 udev_device_add_property(event->dev, key, "1");
2056 }
2057
2058 if (!imported && cur->key.op != OP_NOMATCH)
2059 goto nomatch;
2060 break;
2061 }
2062 case TK_M_IMPORT_PARENT: {
2063 char import[UTIL_PATH_SIZE];
2064
2065 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), import, sizeof(import), false);
2066 if (import_parent_into_properties(event->dev, import) != 0)
2067 if (cur->key.op != OP_NOMATCH)
2068 goto nomatch;
2069 break;
2070 }
2071 case TK_M_RESULT:
2072 if (match_key(rules, cur, event->program_result) != 0)
2073 goto nomatch;
2074 break;
2075 case TK_A_STRING_ESCAPE_NONE:
2076 esc = ESCAPE_NONE;
2077 break;
2078 case TK_A_STRING_ESCAPE_REPLACE:
2079 esc = ESCAPE_REPLACE;
2080 break;
2081 case TK_A_DB_PERSIST:
2082 udev_device_set_db_persist(event->dev);
2083 break;
2084 case TK_A_INOTIFY_WATCH:
2085 if (event->inotify_watch_final)
2086 break;
2087 if (cur->key.op == OP_ASSIGN_FINAL)
2088 event->inotify_watch_final = true;
2089 event->inotify_watch = cur->key.watch;
2090 break;
2091 case TK_A_DEVLINK_PRIO:
2092 udev_device_set_devlink_priority(event->dev, cur->key.devlink_prio);
2093 break;
2094 case TK_A_OWNER: {
2095 char owner[UTIL_NAME_SIZE];
2096 const char *ow = owner;
2097
2098 if (event->owner_final)
2099 break;
2100 if (cur->key.op == OP_ASSIGN_FINAL)
2101 event->owner_final = true;
2102 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), owner, sizeof(owner), false);
2103 event->owner_set = true;
2104 r = get_user_creds(&ow, &event->uid, NULL, NULL, NULL, USER_CREDS_ALLOW_MISSING);
2105 if (r < 0) {
2106 log_unknown_owner(r, "user", owner);
2107 event->uid = 0;
2108 }
2109 log_debug("OWNER %u %s:%u",
2110 event->uid,
2111 rules_str(rules, rule->rule.filename_off),
2112 rule->rule.filename_line);
2113 break;
2114 }
2115 case TK_A_GROUP: {
2116 char group[UTIL_NAME_SIZE];
2117 const char *gr = group;
2118
2119 if (event->group_final)
2120 break;
2121 if (cur->key.op == OP_ASSIGN_FINAL)
2122 event->group_final = true;
2123 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), group, sizeof(group), false);
2124 event->group_set = true;
2125 r = get_group_creds(&gr, &event->gid, USER_CREDS_ALLOW_MISSING);
2126 if (r < 0) {
2127 log_unknown_owner(r, "group", group);
2128 event->gid = 0;
2129 }
2130 log_debug("GROUP %u %s:%u",
2131 event->gid,
2132 rules_str(rules, rule->rule.filename_off),
2133 rule->rule.filename_line);
2134 break;
2135 }
2136 case TK_A_MODE: {
2137 char mode_str[UTIL_NAME_SIZE];
2138 mode_t mode;
2139 char *endptr;
2140
2141 if (event->mode_final)
2142 break;
2143 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), mode_str, sizeof(mode_str), false);
2144 mode = strtol(mode_str, &endptr, 8);
2145 if (endptr[0] != '\0') {
2146 log_error("ignoring invalid mode '%s'", mode_str);
2147 break;
2148 }
2149 if (cur->key.op == OP_ASSIGN_FINAL)
2150 event->mode_final = true;
2151 event->mode_set = true;
2152 event->mode = mode;
2153 log_debug("MODE %#o %s:%u",
2154 event->mode,
2155 rules_str(rules, rule->rule.filename_off),
2156 rule->rule.filename_line);
2157 break;
2158 }
2159 case TK_A_OWNER_ID:
2160 if (event->owner_final)
2161 break;
2162 if (cur->key.op == OP_ASSIGN_FINAL)
2163 event->owner_final = true;
2164 event->owner_set = true;
2165 event->uid = cur->key.uid;
2166 log_debug("OWNER %u %s:%u",
2167 event->uid,
2168 rules_str(rules, rule->rule.filename_off),
2169 rule->rule.filename_line);
2170 break;
2171 case TK_A_GROUP_ID:
2172 if (event->group_final)
2173 break;
2174 if (cur->key.op == OP_ASSIGN_FINAL)
2175 event->group_final = true;
2176 event->group_set = true;
2177 event->gid = cur->key.gid;
2178 log_debug("GROUP %u %s:%u",
2179 event->gid,
2180 rules_str(rules, rule->rule.filename_off),
2181 rule->rule.filename_line);
2182 break;
2183 case TK_A_MODE_ID:
2184 if (event->mode_final)
2185 break;
2186 if (cur->key.op == OP_ASSIGN_FINAL)
2187 event->mode_final = true;
2188 event->mode_set = true;
2189 event->mode = cur->key.mode;
2190 log_debug("MODE %#o %s:%u",
2191 event->mode,
2192 rules_str(rules, rule->rule.filename_off),
2193 rule->rule.filename_line);
2194 break;
2195 case TK_A_SECLABEL: {
2196 char label_str[UTIL_LINE_SIZE] = {};
2197 const char *name, *label;
2198
2199 name = rules_str(rules, cur->key.attr_off);
2200 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), label_str, sizeof(label_str), false);
2201 if (label_str[0] != '\0')
2202 label = label_str;
2203 else
2204 label = rules_str(rules, cur->key.value_off);
2205
2206 if (IN_SET(cur->key.op, OP_ASSIGN, OP_ASSIGN_FINAL))
2207 udev_list_cleanup(&event->seclabel_list);
2208 udev_list_entry_add(&event->seclabel_list, name, label);
2209 log_debug("SECLABEL{%s}='%s' %s:%u",
2210 name, label,
2211 rules_str(rules, rule->rule.filename_off),
2212 rule->rule.filename_line);
2213 break;
2214 }
2215 case TK_A_ENV: {
2216 const char *name = rules_str(rules, cur->key.attr_off);
2217 char *value = rules_str(rules, cur->key.value_off);
2218 char value_new[UTIL_NAME_SIZE];
2219 const char *value_old = NULL;
2220
2221 if (value[0] == '\0') {
2222 if (cur->key.op == OP_ADD)
2223 break;
2224 udev_device_add_property(event->dev, name, NULL);
2225 break;
2226 }
2227
2228 if (cur->key.op == OP_ADD)
2229 value_old = udev_device_get_property_value(event->dev, name);
2230 if (value_old) {
2231 char temp[UTIL_NAME_SIZE];
2232
2233 /* append value separated by space */
2234 udev_event_apply_format(event, value, temp, sizeof(temp), false);
2235 strscpyl(value_new, sizeof(value_new), value_old, " ", temp, NULL);
2236 } else
2237 udev_event_apply_format(event, value, value_new, sizeof(value_new), false);
2238
2239 udev_device_add_property(event->dev, name, value_new);
2240 break;
2241 }
2242 case TK_A_TAG: {
2243 char tag[UTIL_PATH_SIZE];
2244 const char *p;
2245
2246 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), tag, sizeof(tag), false);
2247 if (IN_SET(cur->key.op, OP_ASSIGN, OP_ASSIGN_FINAL))
2248 udev_device_cleanup_tags_list(event->dev);
2249 for (p = tag; *p != '\0'; p++) {
2250 if ((*p >= 'a' && *p <= 'z') ||
2251 (*p >= 'A' && *p <= 'Z') ||
2252 (*p >= '0' && *p <= '9') ||
2253 IN_SET(*p, '-', '_'))
2254 continue;
2255 log_error("ignoring invalid tag name '%s'", tag);
2256 break;
2257 }
2258 if (cur->key.op == OP_REMOVE)
2259 udev_device_remove_tag(event->dev, tag);
2260 else
2261 udev_device_add_tag(event->dev, tag);
2262 break;
2263 }
2264 case TK_A_NAME: {
2265 const char *name = rules_str(rules, cur->key.value_off);
2266
2267 char name_str[UTIL_PATH_SIZE];
2268 int count;
2269
2270 if (event->name_final)
2271 break;
2272 if (cur->key.op == OP_ASSIGN_FINAL)
2273 event->name_final = true;
2274 udev_event_apply_format(event, name, name_str, sizeof(name_str), false);
2275 if (IN_SET(esc, ESCAPE_UNSET, ESCAPE_REPLACE)) {
2276 count = util_replace_chars(name_str, "/");
2277 if (count > 0)
2278 log_debug("%i character(s) replaced", count);
2279 }
2280 if (major(udev_device_get_devnum(event->dev)) &&
2281 !streq(name_str, udev_device_get_devnode(event->dev) + STRLEN("/dev/"))) {
2282 log_error("NAME=\"%s\" ignored, kernel device nodes cannot be renamed; please fix it in %s:%u\n",
2283 name,
2284 rules_str(rules, rule->rule.filename_off),
2285 rule->rule.filename_line);
2286 break;
2287 }
2288 if (free_and_strdup(&event->name, name_str) < 0) {
2289 log_oom();
2290 return;
2291 }
2292 log_debug("NAME '%s' %s:%u",
2293 event->name,
2294 rules_str(rules, rule->rule.filename_off),
2295 rule->rule.filename_line);
2296 break;
2297 }
2298 case TK_A_DEVLINK: {
2299 char temp[UTIL_PATH_SIZE];
2300 char filename[UTIL_PATH_SIZE];
2301 char *pos, *next;
2302 int count = 0;
2303
2304 if (event->devlink_final)
2305 break;
2306 if (major(udev_device_get_devnum(event->dev)) == 0)
2307 break;
2308 if (cur->key.op == OP_ASSIGN_FINAL)
2309 event->devlink_final = true;
2310 if (IN_SET(cur->key.op, OP_ASSIGN, OP_ASSIGN_FINAL))
2311 udev_device_cleanup_devlinks_list(event->dev);
2312
2313 /* allow multiple symlinks separated by spaces */
2314 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), temp, sizeof(temp), esc != ESCAPE_NONE);
2315 if (esc == ESCAPE_UNSET)
2316 count = util_replace_chars(temp, "/ ");
2317 else if (esc == ESCAPE_REPLACE)
2318 count = util_replace_chars(temp, "/");
2319 if (count > 0)
2320 log_debug("%i character(s) replaced" , count);
2321 pos = temp;
2322 while (isspace(pos[0]))
2323 pos++;
2324 next = strchr(pos, ' ');
2325 while (next != NULL) {
2326 next[0] = '\0';
2327 log_debug("LINK '%s' %s:%u", pos,
2328 rules_str(rules, rule->rule.filename_off), rule->rule.filename_line);
2329 strscpyl(filename, sizeof(filename), "/dev/", pos, NULL);
2330 udev_device_add_devlink(event->dev, filename);
2331 while (isspace(next[1]))
2332 next++;
2333 pos = &next[1];
2334 next = strchr(pos, ' ');
2335 }
2336 if (pos[0] != '\0') {
2337 log_debug("LINK '%s' %s:%u", pos,
2338 rules_str(rules, rule->rule.filename_off), rule->rule.filename_line);
2339 strscpyl(filename, sizeof(filename), "/dev/", pos, NULL);
2340 udev_device_add_devlink(event->dev, filename);
2341 }
2342 break;
2343 }
2344 case TK_A_ATTR: {
2345 const char *key_name = rules_str(rules, cur->key.attr_off);
2346 char attr[UTIL_PATH_SIZE];
2347 char value[UTIL_NAME_SIZE];
2348 _cleanup_fclose_ FILE *f = NULL;
2349
2350 if (util_resolve_subsys_kernel(key_name, attr, sizeof(attr), 0) != 0)
2351 strscpyl(attr, sizeof(attr), udev_device_get_syspath(event->dev), "/", key_name, NULL);
2352 attr_subst_subdir(attr, sizeof(attr));
2353
2354 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), value, sizeof(value), false);
2355 log_debug("ATTR '%s' writing '%s' %s:%u", attr, value,
2356 rules_str(rules, rule->rule.filename_off),
2357 rule->rule.filename_line);
2358 f = fopen(attr, "we");
2359 if (f == NULL)
2360 log_error_errno(errno, "error opening ATTR{%s} for writing: %m", attr);
2361 else if (fprintf(f, "%s", value) <= 0)
2362 log_error_errno(errno, "error writing ATTR{%s}: %m", attr);
2363 break;
2364 }
2365 case TK_A_SYSCTL: {
2366 char filename[UTIL_PATH_SIZE];
2367 char value[UTIL_NAME_SIZE];
2368
2369 udev_event_apply_format(event, rules_str(rules, cur->key.attr_off), filename, sizeof(filename), false);
2370 sysctl_normalize(filename);
2371 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), value, sizeof(value), false);
2372 log_debug("SYSCTL '%s' writing '%s' %s:%u", filename, value,
2373 rules_str(rules, rule->rule.filename_off), rule->rule.filename_line);
2374 r = sysctl_write(filename, value);
2375 if (r < 0)
2376 log_error_errno(r, "error writing SYSCTL{%s}='%s': %m", filename, value);
2377 break;
2378 }
2379 case TK_A_RUN_BUILTIN:
2380 case TK_A_RUN_PROGRAM: {
2381 struct udev_list_entry *entry;
2382
2383 if (IN_SET(cur->key.op, OP_ASSIGN, OP_ASSIGN_FINAL))
2384 udev_list_cleanup(&event->run_list);
2385 log_debug("RUN '%s' %s:%u",
2386 rules_str(rules, cur->key.value_off),
2387 rules_str(rules, rule->rule.filename_off),
2388 rule->rule.filename_line);
2389 entry = udev_list_entry_add(&event->run_list, rules_str(rules, cur->key.value_off), NULL);
2390 udev_list_entry_set_num(entry, cur->key.builtin_cmd);
2391 break;
2392 }
2393 case TK_A_GOTO:
2394 if (cur->key.rule_goto == 0)
2395 break;
2396 cur = &rules->tokens[cur->key.rule_goto];
2397 continue;
2398 case TK_END:
2399 return;
2400
2401 case TK_M_PARENTS_MIN:
2402 case TK_M_PARENTS_MAX:
2403 case TK_M_MAX:
2404 case TK_UNSET:
2405 log_error("wrong type %u", cur->type);
2406 goto nomatch;
2407 }
2408
2409 cur++;
2410 continue;
2411 nomatch:
2412 /* fast-forward to next rule */
2413 cur = rule + rule->rule.token_count;
2414 }
2415 }
2416
2417 int udev_rules_apply_static_dev_perms(struct udev_rules *rules) {
2418 struct token *cur;
2419 struct token *rule;
2420 uid_t uid = 0;
2421 gid_t gid = 0;
2422 mode_t mode = 0;
2423 _cleanup_strv_free_ char **tags = NULL;
2424 char **t;
2425 FILE *f = NULL;
2426 _cleanup_free_ char *path = NULL;
2427 int r;
2428
2429 if (rules->tokens == NULL)
2430 return 0;
2431
2432 cur = &rules->tokens[0];
2433 rule = cur;
2434 for (;;) {
2435 switch (cur->type) {
2436 case TK_RULE:
2437 /* current rule */
2438 rule = cur;
2439
2440 /* skip rules without a static_node tag */
2441 if (!rule->rule.has_static_node)
2442 goto next;
2443
2444 uid = 0;
2445 gid = 0;
2446 mode = 0;
2447 tags = strv_free(tags);
2448 break;
2449 case TK_A_OWNER_ID:
2450 uid = cur->key.uid;
2451 break;
2452 case TK_A_GROUP_ID:
2453 gid = cur->key.gid;
2454 break;
2455 case TK_A_MODE_ID:
2456 mode = cur->key.mode;
2457 break;
2458 case TK_A_TAG:
2459 r = strv_extend(&tags, rules_str(rules, cur->key.value_off));
2460 if (r < 0)
2461 goto finish;
2462
2463 break;
2464 case TK_A_STATIC_NODE: {
2465 char device_node[UTIL_PATH_SIZE];
2466 char tags_dir[UTIL_PATH_SIZE];
2467 char tag_symlink[UTIL_PATH_SIZE];
2468 struct stat stats;
2469
2470 /* we assure, that the permissions tokens are sorted before the static token */
2471
2472 if (mode == 0 && uid == 0 && gid == 0 && tags == NULL)
2473 goto next;
2474
2475 strscpyl(device_node, sizeof(device_node), "/dev/", rules_str(rules, cur->key.value_off), NULL);
2476 if (stat(device_node, &stats) != 0)
2477 break;
2478 if (!S_ISBLK(stats.st_mode) && !S_ISCHR(stats.st_mode))
2479 break;
2480
2481 /* export the tags to a directory as symlinks, allowing otherwise dead nodes to be tagged */
2482 if (tags) {
2483 STRV_FOREACH(t, tags) {
2484 _cleanup_free_ char *unescaped_filename = NULL;
2485
2486 strscpyl(tags_dir, sizeof(tags_dir), "/run/udev/static_node-tags/", *t, "/", NULL);
2487 r = mkdir_p(tags_dir, 0755);
2488 if (r < 0)
2489 return log_error_errno(r, "failed to create %s: %m", tags_dir);
2490
2491 unescaped_filename = xescape(rules_str(rules, cur->key.value_off), "/.");
2492
2493 strscpyl(tag_symlink, sizeof(tag_symlink), tags_dir, unescaped_filename, NULL);
2494 r = symlink(device_node, tag_symlink);
2495 if (r < 0 && errno != EEXIST)
2496 return log_error_errno(errno, "failed to create symlink %s -> %s: %m",
2497 tag_symlink, device_node);
2498 }
2499 }
2500
2501 /* don't touch the permissions if only the tags were set */
2502 if (mode == 0 && uid == 0 && gid == 0)
2503 break;
2504
2505 if (mode == 0) {
2506 if (gid > 0)
2507 mode = 0660;
2508 else
2509 mode = 0600;
2510 }
2511 if (mode != (stats.st_mode & 01777)) {
2512 r = chmod(device_node, mode);
2513 if (r < 0)
2514 return log_error_errno(errno, "Failed to chmod '%s' %#o: %m",
2515 device_node, mode);
2516 else
2517 log_debug("chmod '%s' %#o", device_node, mode);
2518 }
2519
2520 if ((uid != 0 && uid != stats.st_uid) || (gid != 0 && gid != stats.st_gid)) {
2521 r = chown(device_node, uid, gid);
2522 if (r < 0)
2523 return log_error_errno(errno, "Failed to chown '%s' %u %u: %m",
2524 device_node, uid, gid);
2525 else
2526 log_debug("chown '%s' %u %u", device_node, uid, gid);
2527 }
2528
2529 utimensat(AT_FDCWD, device_node, NULL, 0);
2530 break;
2531 }
2532 case TK_END:
2533 goto finish;
2534 }
2535
2536 cur++;
2537 continue;
2538 next:
2539 /* fast-forward to next rule */
2540 cur = rule + rule->rule.token_count;
2541 continue;
2542 }
2543
2544 finish:
2545 if (f) {
2546 fflush(f);
2547 fchmod(fileno(f), 0644);
2548 if (ferror(f) || rename(path, "/run/udev/static_node-tags") < 0) {
2549 unlink_noerrno("/run/udev/static_node-tags");
2550 unlink_noerrno(path);
2551 return -errno;
2552 }
2553 }
2554
2555 return 0;
2556 }