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