]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/udev/udev-rules.c
pkgconfig: define variables relative to ${prefix}/${rootprefix}/${sysconfdir}
[thirdparty/systemd.git] / src / udev / udev-rules.c
1 /* SPDX-License-Identifier: GPL-2.0+ */
2
3 #include <ctype.h>
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <fnmatch.h>
7 #include <limits.h>
8 #include <stdbool.h>
9 #include <stddef.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <time.h>
14 #include <unistd.h>
15
16 #include "alloc-util.h"
17 #include "conf-files.h"
18 #include "device-private.h"
19 #include "device-util.h"
20 #include "dirent-util.h"
21 #include "escape.h"
22 #include "fd-util.h"
23 #include "fileio.h"
24 #include "fs-util.h"
25 #include "glob-util.h"
26 #include "libudev-private.h"
27 #include "path-util.h"
28 #include "proc-cmdline.h"
29 #include "stat-util.h"
30 #include "stdio-util.h"
31 #include "strbuf.h"
32 #include "string-util.h"
33 #include "strv.h"
34 #include "sysctl-util.h"
35 #include "udev-builtin.h"
36 #include "udev.h"
37 #include "user-util.h"
38 #include "util.h"
39
40 #define PREALLOC_TOKEN 2048
41
42 struct uid_gid {
43 unsigned name_off;
44 union {
45 uid_t uid;
46 gid_t gid;
47 };
48 };
49
50 static const char* const rules_dirs[] = {
51 "/etc/udev/rules.d",
52 "/run/udev/rules.d",
53 UDEVLIBEXECDIR "/rules.d",
54 NULL
55 };
56
57 struct udev_rules {
58 usec_t dirs_ts_usec;
59 ResolveNameTiming resolve_name_timing;
60
61 /* every key in the rules file becomes a token */
62 struct token *tokens;
63 unsigned token_cur;
64 unsigned token_max;
65
66 /* all key strings are copied and de-duplicated in a single continuous string buffer */
67 struct strbuf *strbuf;
68
69 /* during rule parsing, uid/gid lookup results are cached */
70 struct uid_gid *uids;
71 unsigned uids_cur;
72 unsigned uids_max;
73 struct uid_gid *gids;
74 unsigned gids_cur;
75 unsigned gids_max;
76 };
77
78 static char *rules_str(struct udev_rules *rules, unsigned off) {
79 return rules->strbuf->buf + off;
80 }
81
82 static unsigned rules_add_string(struct udev_rules *rules, const char *s) {
83 return strbuf_add_string(rules->strbuf, s, strlen(s));
84 }
85
86 /* KEY=="", KEY!="", KEY+="", KEY-="", KEY="", KEY:="" */
87 enum operation_type {
88 OP_UNSET,
89
90 OP_MATCH,
91 OP_NOMATCH,
92 OP_MATCH_MAX,
93
94 OP_ADD,
95 OP_REMOVE,
96 OP_ASSIGN,
97 OP_ASSIGN_FINAL,
98 };
99
100 enum string_glob_type {
101 GL_UNSET,
102 GL_PLAIN, /* no special chars */
103 GL_GLOB, /* shell globs ?,*,[] */
104 GL_SPLIT, /* multi-value A|B */
105 GL_SPLIT_GLOB, /* multi-value with glob A*|B* */
106 GL_SOMETHING, /* commonly used "?*" */
107 };
108
109 enum string_subst_type {
110 SB_UNSET,
111 SB_NONE,
112 SB_FORMAT,
113 SB_SUBSYS,
114 };
115
116 /* tokens of a rule are sorted/handled in this order */
117 enum token_type {
118 TK_UNSET,
119 TK_RULE,
120
121 TK_M_ACTION, /* val */
122 TK_M_DEVPATH, /* val */
123 TK_M_KERNEL, /* val */
124 TK_M_DEVLINK, /* val */
125 TK_M_NAME, /* val */
126 TK_M_ENV, /* val, attr */
127 TK_M_TAG, /* val */
128 TK_M_SUBSYSTEM, /* val */
129 TK_M_DRIVER, /* val */
130 TK_M_WAITFOR, /* val */
131 TK_M_ATTR, /* val, attr */
132 TK_M_SYSCTL, /* val, attr */
133
134 TK_M_PARENTS_MIN,
135 TK_M_KERNELS, /* val */
136 TK_M_SUBSYSTEMS, /* val */
137 TK_M_DRIVERS, /* val */
138 TK_M_ATTRS, /* val, attr */
139 TK_M_TAGS, /* val */
140 TK_M_PARENTS_MAX,
141
142 TK_M_TEST, /* val, mode_t */
143 TK_M_PROGRAM, /* val */
144 TK_M_IMPORT_FILE, /* val */
145 TK_M_IMPORT_PROG, /* val */
146 TK_M_IMPORT_BUILTIN, /* val */
147 TK_M_IMPORT_DB, /* val */
148 TK_M_IMPORT_CMDLINE, /* val */
149 TK_M_IMPORT_PARENT, /* val */
150 TK_M_RESULT, /* val */
151 TK_M_MAX,
152
153 TK_A_STRING_ESCAPE_NONE,
154 TK_A_STRING_ESCAPE_REPLACE,
155 TK_A_DB_PERSIST,
156 TK_A_INOTIFY_WATCH, /* int */
157 TK_A_DEVLINK_PRIO, /* int */
158 TK_A_OWNER, /* val */
159 TK_A_GROUP, /* val */
160 TK_A_MODE, /* val */
161 TK_A_OWNER_ID, /* uid_t */
162 TK_A_GROUP_ID, /* gid_t */
163 TK_A_MODE_ID, /* mode_t */
164 TK_A_TAG, /* val */
165 TK_A_STATIC_NODE, /* val */
166 TK_A_SECLABEL, /* val, attr */
167 TK_A_ENV, /* val, attr */
168 TK_A_NAME, /* val */
169 TK_A_DEVLINK, /* val */
170 TK_A_ATTR, /* val, attr */
171 TK_A_SYSCTL, /* val, attr */
172 TK_A_RUN_BUILTIN, /* val, bool */
173 TK_A_RUN_PROGRAM, /* val, bool */
174 TK_A_GOTO, /* size_t */
175
176 TK_END,
177 };
178
179 /* we try to pack stuff in a way that we take only 12 bytes per token */
180 struct token {
181 union {
182 unsigned char type; /* same in rule and key */
183 struct {
184 enum token_type type:8;
185 bool can_set_name:1;
186 bool has_static_node:1;
187 unsigned unused:6;
188 unsigned short token_count;
189 unsigned label_off;
190 unsigned short filename_off;
191 unsigned short filename_line;
192 } rule;
193 struct {
194 enum token_type type:8;
195 enum operation_type op:8;
196 enum string_glob_type glob:8;
197 enum string_subst_type subst:4;
198 enum string_subst_type attrsubst:4;
199 unsigned value_off;
200 union {
201 unsigned attr_off;
202 unsigned rule_goto;
203 mode_t mode;
204 uid_t uid;
205 gid_t gid;
206 int devlink_prio;
207 int watch;
208 enum udev_builtin_cmd builtin_cmd;
209 };
210 } key;
211 };
212 };
213
214 #define MAX_TK 64
215 struct rule_tmp {
216 struct udev_rules *rules;
217 struct token rule;
218 struct token token[MAX_TK];
219 unsigned token_cur;
220 };
221
222 #ifdef DEBUG
223 static const char *operation_str(enum operation_type type) {
224 static const char *operation_strs[] = {
225 [OP_UNSET] = "UNSET",
226 [OP_MATCH] = "match",
227 [OP_NOMATCH] = "nomatch",
228 [OP_MATCH_MAX] = "MATCH_MAX",
229
230 [OP_ADD] = "add",
231 [OP_REMOVE] = "remove",
232 [OP_ASSIGN] = "assign",
233 [OP_ASSIGN_FINAL] = "assign-final",
234 } ;
235
236 return operation_strs[type];
237 }
238
239 static const char *string_glob_str(enum string_glob_type type) {
240 static const char *string_glob_strs[] = {
241 [GL_UNSET] = "UNSET",
242 [GL_PLAIN] = "plain",
243 [GL_GLOB] = "glob",
244 [GL_SPLIT] = "split",
245 [GL_SPLIT_GLOB] = "split-glob",
246 [GL_SOMETHING] = "split-glob",
247 };
248
249 return string_glob_strs[type];
250 }
251
252 static const char *token_str(enum token_type type) {
253 static const char *token_strs[] = {
254 [TK_UNSET] = "UNSET",
255 [TK_RULE] = "RULE",
256
257 [TK_M_ACTION] = "M ACTION",
258 [TK_M_DEVPATH] = "M DEVPATH",
259 [TK_M_KERNEL] = "M KERNEL",
260 [TK_M_DEVLINK] = "M DEVLINK",
261 [TK_M_NAME] = "M NAME",
262 [TK_M_ENV] = "M ENV",
263 [TK_M_TAG] = "M TAG",
264 [TK_M_SUBSYSTEM] = "M SUBSYSTEM",
265 [TK_M_DRIVER] = "M DRIVER",
266 [TK_M_WAITFOR] = "M WAITFOR",
267 [TK_M_ATTR] = "M ATTR",
268 [TK_M_SYSCTL] = "M SYSCTL",
269
270 [TK_M_PARENTS_MIN] = "M PARENTS_MIN",
271 [TK_M_KERNELS] = "M KERNELS",
272 [TK_M_SUBSYSTEMS] = "M SUBSYSTEMS",
273 [TK_M_DRIVERS] = "M DRIVERS",
274 [TK_M_ATTRS] = "M ATTRS",
275 [TK_M_TAGS] = "M TAGS",
276 [TK_M_PARENTS_MAX] = "M PARENTS_MAX",
277
278 [TK_M_TEST] = "M TEST",
279 [TK_M_PROGRAM] = "M PROGRAM",
280 [TK_M_IMPORT_FILE] = "M IMPORT_FILE",
281 [TK_M_IMPORT_PROG] = "M IMPORT_PROG",
282 [TK_M_IMPORT_BUILTIN] = "M IMPORT_BUILTIN",
283 [TK_M_IMPORT_DB] = "M IMPORT_DB",
284 [TK_M_IMPORT_CMDLINE] = "M IMPORT_CMDLINE",
285 [TK_M_IMPORT_PARENT] = "M IMPORT_PARENT",
286 [TK_M_RESULT] = "M RESULT",
287 [TK_M_MAX] = "M MAX",
288
289 [TK_A_STRING_ESCAPE_NONE] = "A STRING_ESCAPE_NONE",
290 [TK_A_STRING_ESCAPE_REPLACE] = "A STRING_ESCAPE_REPLACE",
291 [TK_A_DB_PERSIST] = "A DB_PERSIST",
292 [TK_A_INOTIFY_WATCH] = "A INOTIFY_WATCH",
293 [TK_A_DEVLINK_PRIO] = "A DEVLINK_PRIO",
294 [TK_A_OWNER] = "A OWNER",
295 [TK_A_GROUP] = "A GROUP",
296 [TK_A_MODE] = "A MODE",
297 [TK_A_OWNER_ID] = "A OWNER_ID",
298 [TK_A_GROUP_ID] = "A GROUP_ID",
299 [TK_A_STATIC_NODE] = "A STATIC_NODE",
300 [TK_A_SECLABEL] = "A SECLABEL",
301 [TK_A_MODE_ID] = "A MODE_ID",
302 [TK_A_ENV] = "A ENV",
303 [TK_A_TAG] = "A ENV",
304 [TK_A_NAME] = "A NAME",
305 [TK_A_DEVLINK] = "A DEVLINK",
306 [TK_A_ATTR] = "A ATTR",
307 [TK_A_SYSCTL] = "A SYSCTL",
308 [TK_A_RUN_BUILTIN] = "A RUN_BUILTIN",
309 [TK_A_RUN_PROGRAM] = "A RUN_PROGRAM",
310 [TK_A_GOTO] = "A GOTO",
311
312 [TK_END] = "END",
313 };
314
315 return token_strs[type];
316 }
317
318 static void dump_token(struct udev_rules *rules, struct token *token) {
319 enum token_type type = token->type;
320 enum operation_type op = token->key.op;
321 enum string_glob_type glob = token->key.glob;
322 const char *value = rules_str(rules, token->key.value_off);
323 const char *attr = &rules->strbuf->buf[token->key.attr_off];
324
325 switch (type) {
326 case TK_RULE:
327 {
328 const char *tks_ptr = (char *)rules->tokens;
329 const char *tk_ptr = (char *)token;
330 unsigned idx = (tk_ptr - tks_ptr) / sizeof(struct token);
331
332 log_debug("* RULE %s:%u, token: %u, count: %u, label: '%s'",
333 &rules->strbuf->buf[token->rule.filename_off], token->rule.filename_line,
334 idx, token->rule.token_count,
335 &rules->strbuf->buf[token->rule.label_off]);
336 break;
337 }
338 case TK_M_ACTION:
339 case TK_M_DEVPATH:
340 case TK_M_KERNEL:
341 case TK_M_SUBSYSTEM:
342 case TK_M_DRIVER:
343 case TK_M_WAITFOR:
344 case TK_M_DEVLINK:
345 case TK_M_NAME:
346 case TK_M_KERNELS:
347 case TK_M_SUBSYSTEMS:
348 case TK_M_DRIVERS:
349 case TK_M_TAGS:
350 case TK_M_PROGRAM:
351 case TK_M_IMPORT_FILE:
352 case TK_M_IMPORT_PROG:
353 case TK_M_IMPORT_DB:
354 case TK_M_IMPORT_CMDLINE:
355 case TK_M_IMPORT_PARENT:
356 case TK_M_RESULT:
357 case TK_A_NAME:
358 case TK_A_DEVLINK:
359 case TK_A_OWNER:
360 case TK_A_GROUP:
361 case TK_A_MODE:
362 case TK_A_RUN_BUILTIN:
363 case TK_A_RUN_PROGRAM:
364 log_debug("%s %s '%s'(%s)",
365 token_str(type), operation_str(op), value, string_glob_str(glob));
366 break;
367 case TK_M_IMPORT_BUILTIN:
368 log_debug("%s %i '%s'", token_str(type), token->key.builtin_cmd, value);
369 break;
370 case TK_M_ATTR:
371 case TK_M_SYSCTL:
372 case TK_M_ATTRS:
373 case TK_M_ENV:
374 case TK_A_ATTR:
375 case TK_A_SYSCTL:
376 case TK_A_ENV:
377 log_debug("%s %s '%s' '%s'(%s)",
378 token_str(type), operation_str(op), attr, value, string_glob_str(glob));
379 break;
380 case TK_M_TAG:
381 case TK_A_TAG:
382 log_debug("%s %s '%s'", token_str(type), operation_str(op), value);
383 break;
384 case TK_A_STRING_ESCAPE_NONE:
385 case TK_A_STRING_ESCAPE_REPLACE:
386 case TK_A_DB_PERSIST:
387 log_debug("%s", token_str(type));
388 break;
389 case TK_M_TEST:
390 log_debug("%s %s '%s'(%s) %#o",
391 token_str(type), operation_str(op), value, string_glob_str(glob), token->key.mode);
392 break;
393 case TK_A_INOTIFY_WATCH:
394 log_debug("%s %u", token_str(type), token->key.watch);
395 break;
396 case TK_A_DEVLINK_PRIO:
397 log_debug("%s %u", token_str(type), token->key.devlink_prio);
398 break;
399 case TK_A_OWNER_ID:
400 log_debug("%s %s %u", token_str(type), operation_str(op), token->key.uid);
401 break;
402 case TK_A_GROUP_ID:
403 log_debug("%s %s %u", token_str(type), operation_str(op), token->key.gid);
404 break;
405 case TK_A_MODE_ID:
406 log_debug("%s %s %#o", token_str(type), operation_str(op), token->key.mode);
407 break;
408 case TK_A_STATIC_NODE:
409 log_debug("%s '%s'", token_str(type), value);
410 break;
411 case TK_A_SECLABEL:
412 log_debug("%s %s '%s' '%s'", token_str(type), operation_str(op), attr, value);
413 break;
414 case TK_A_GOTO:
415 log_debug("%s '%s' %u", token_str(type), value, token->key.rule_goto);
416 break;
417 case TK_END:
418 log_debug("* %s", token_str(type));
419 break;
420 case TK_M_PARENTS_MIN:
421 case TK_M_PARENTS_MAX:
422 case TK_M_MAX:
423 case TK_UNSET:
424 log_debug("unknown type %u", type);
425 break;
426 }
427 }
428
429 static void dump_rules(struct udev_rules *rules) {
430 unsigned i;
431
432 log_debug("dumping %u (%zu bytes) tokens, %zu (%zu bytes) strings",
433 rules->token_cur,
434 rules->token_cur * sizeof(struct token),
435 rules->strbuf->nodes_count,
436 rules->strbuf->len);
437 for (i = 0; i < rules->token_cur; i++)
438 dump_token(rules, &rules->tokens[i]);
439 }
440 #else
441 static inline void dump_token(struct udev_rules *rules, struct token *token) {}
442 static inline void dump_rules(struct udev_rules *rules) {}
443 #endif /* DEBUG */
444
445 static int add_token(struct udev_rules *rules, struct token *token) {
446 /* grow buffer if needed */
447 if (rules->token_cur+1 >= rules->token_max) {
448 struct token *tokens;
449 unsigned add;
450
451 /* double the buffer size */
452 add = rules->token_max;
453 if (add < 8)
454 add = 8;
455
456 tokens = reallocarray(rules->tokens, rules->token_max + add, sizeof(struct token));
457 if (tokens == NULL)
458 return -1;
459 rules->tokens = tokens;
460 rules->token_max += add;
461 }
462 memcpy(&rules->tokens[rules->token_cur], token, sizeof(struct token));
463 rules->token_cur++;
464 return 0;
465 }
466
467 static void log_unknown_owner(int error, const char *entity, const char *owner) {
468 if (IN_SET(abs(error), ENOENT, ESRCH))
469 log_error("Specified %s '%s' unknown", entity, owner);
470 else
471 log_error_errno(error, "Error resolving %s '%s': %m", entity, owner);
472 }
473
474 static uid_t add_uid(struct udev_rules *rules, const char *owner) {
475 unsigned i;
476 uid_t uid = 0;
477 unsigned off;
478 int r;
479
480 /* lookup, if we know it already */
481 for (i = 0; i < rules->uids_cur; i++) {
482 off = rules->uids[i].name_off;
483 if (streq(rules_str(rules, off), owner)) {
484 uid = rules->uids[i].uid;
485 return uid;
486 }
487 }
488 r = get_user_creds(&owner, &uid, NULL, NULL, NULL, USER_CREDS_ALLOW_MISSING);
489 if (r < 0)
490 log_unknown_owner(r, "user", owner);
491
492 /* grow buffer if needed */
493 if (rules->uids_cur+1 >= rules->uids_max) {
494 struct uid_gid *uids;
495 unsigned add;
496
497 /* double the buffer size */
498 add = rules->uids_max;
499 if (add < 1)
500 add = 8;
501
502 uids = reallocarray(rules->uids, rules->uids_max + add, sizeof(struct uid_gid));
503 if (uids == NULL)
504 return uid;
505 rules->uids = uids;
506 rules->uids_max += add;
507 }
508 rules->uids[rules->uids_cur].uid = uid;
509 off = rules_add_string(rules, owner);
510 if (off <= 0)
511 return uid;
512 rules->uids[rules->uids_cur].name_off = off;
513 rules->uids_cur++;
514 return uid;
515 }
516
517 static gid_t add_gid(struct udev_rules *rules, const char *group) {
518 unsigned i;
519 gid_t gid = 0;
520 unsigned off;
521 int r;
522
523 /* lookup, if we know it already */
524 for (i = 0; i < rules->gids_cur; i++) {
525 off = rules->gids[i].name_off;
526 if (streq(rules_str(rules, off), group)) {
527 gid = rules->gids[i].gid;
528 return gid;
529 }
530 }
531 r = get_group_creds(&group, &gid, USER_CREDS_ALLOW_MISSING);
532 if (r < 0)
533 log_unknown_owner(r, "group", group);
534
535 /* grow buffer if needed */
536 if (rules->gids_cur+1 >= rules->gids_max) {
537 struct uid_gid *gids;
538 unsigned add;
539
540 /* double the buffer size */
541 add = rules->gids_max;
542 if (add < 1)
543 add = 8;
544
545 gids = reallocarray(rules->gids, rules->gids_max + add, sizeof(struct uid_gid));
546 if (gids == NULL)
547 return gid;
548 rules->gids = gids;
549 rules->gids_max += add;
550 }
551 rules->gids[rules->gids_cur].gid = gid;
552 off = rules_add_string(rules, group);
553 if (off <= 0)
554 return gid;
555 rules->gids[rules->gids_cur].name_off = off;
556 rules->gids_cur++;
557 return gid;
558 }
559
560 static int import_property_from_string(sd_device *dev, char *line) {
561 char *key;
562 char *val;
563 size_t len;
564
565 /* find key */
566 key = line;
567 while (isspace(key[0]))
568 key++;
569
570 /* comment or empty line */
571 if (IN_SET(key[0], '#', '\0'))
572 return 0;
573
574 /* split key/value */
575 val = strchr(key, '=');
576 if (!val)
577 return -EINVAL;
578 val[0] = '\0';
579 val++;
580
581 /* find value */
582 while (isspace(val[0]))
583 val++;
584
585 /* terminate key */
586 len = strlen(key);
587 if (len == 0)
588 return -EINVAL;
589 while (isspace(key[len-1]))
590 len--;
591 key[len] = '\0';
592
593 /* terminate value */
594 len = strlen(val);
595 if (len == 0)
596 return -EINVAL;
597 while (isspace(val[len-1]))
598 len--;
599 val[len] = '\0';
600
601 if (len == 0)
602 return -EINVAL;
603
604 /* unquote */
605 if (IN_SET(val[0], '"', '\'')) {
606 if (len == 1 || val[len-1] != val[0]) {
607 log_debug("inconsistent quoting: '%s', skip", line);
608 return -EINVAL;
609 }
610 val[len-1] = '\0';
611 val++;
612 }
613
614 return device_add_property(dev, key, val);
615 }
616
617 static int import_file_into_properties(sd_device *dev, const char *filename) {
618 _cleanup_fclose_ FILE *f = NULL;
619 int r;
620
621 f = fopen(filename, "re");
622 if (!f)
623 return -errno;
624
625 for (;;) {
626 _cleanup_free_ char *line = NULL;
627
628 r = read_line(f, LONG_LINE_MAX, &line);
629 if (r < 0)
630 return r;
631 if (r == 0)
632 break;
633
634 (void) import_property_from_string(dev, line);
635 }
636
637 return 0;
638 }
639
640 static int import_program_into_properties(struct udev_event *event,
641 usec_t timeout_usec,
642 const char *program) {
643 char result[UTIL_LINE_SIZE];
644 char *line;
645 int err;
646
647 err = udev_event_spawn(event, timeout_usec, true, program, result, sizeof(result));
648 if (err < 0)
649 return err;
650
651 line = result;
652 while (line != NULL) {
653 char *pos;
654
655 pos = strchr(line, '\n');
656 if (pos != NULL) {
657 pos[0] = '\0';
658 pos = &pos[1];
659 }
660 (void) import_property_from_string(event->dev, line);
661 line = pos;
662 }
663 return 0;
664 }
665
666 static int import_parent_into_properties(sd_device *dev, const char *filter) {
667 const char *key, *val;
668 sd_device *parent;
669 int r;
670
671 assert(dev);
672 assert(filter);
673
674 r = sd_device_get_parent(dev, &parent);
675 if (r < 0)
676 return r;
677
678 FOREACH_DEVICE_PROPERTY(parent, key, val)
679 if (fnmatch(filter, key, 0) == 0)
680 device_add_property(dev, key, val);
681 return 0;
682 }
683
684 static void attr_subst_subdir(char *attr, size_t len) {
685 const char *pos, *tail, *path;
686 _cleanup_closedir_ DIR *dir = NULL;
687 struct dirent *dent;
688
689 pos = strstr(attr, "/*/");
690 if (!pos)
691 return;
692
693 tail = pos + 2;
694 path = strndupa(attr, pos - attr + 1); /* include slash at end */
695 dir = opendir(path);
696 if (dir == NULL)
697 return;
698
699 FOREACH_DIRENT_ALL(dent, dir, break)
700 if (dent->d_name[0] != '.') {
701 char n[strlen(dent->d_name) + strlen(tail) + 1];
702
703 strscpyl(n, sizeof n, dent->d_name, tail, NULL);
704 if (faccessat(dirfd(dir), n, F_OK, 0) == 0) {
705 strscpyl(attr, len, path, n, NULL);
706 break;
707 }
708 }
709 }
710
711 static int get_key(char **line, char **key, enum operation_type *op, char **value) {
712 char *linepos;
713 char *temp;
714 unsigned i, j;
715
716 linepos = *line;
717 if (linepos == NULL || linepos[0] == '\0')
718 return -1;
719
720 /* skip whitespace */
721 while (isspace(linepos[0]) || linepos[0] == ',')
722 linepos++;
723
724 /* get the key */
725 if (linepos[0] == '\0')
726 return -1;
727 *key = linepos;
728
729 for (;;) {
730 linepos++;
731 if (linepos[0] == '\0')
732 return -1;
733 if (isspace(linepos[0]))
734 break;
735 if (linepos[0] == '=')
736 break;
737 if (IN_SET(linepos[0], '+', '-', '!', ':'))
738 if (linepos[1] == '=')
739 break;
740 }
741
742 /* remember end of key */
743 temp = linepos;
744
745 /* skip whitespace after key */
746 while (isspace(linepos[0]))
747 linepos++;
748 if (linepos[0] == '\0')
749 return -1;
750
751 /* get operation type */
752 if (linepos[0] == '=' && linepos[1] == '=') {
753 *op = OP_MATCH;
754 linepos += 2;
755 } else if (linepos[0] == '!' && linepos[1] == '=') {
756 *op = OP_NOMATCH;
757 linepos += 2;
758 } else if (linepos[0] == '+' && linepos[1] == '=') {
759 *op = OP_ADD;
760 linepos += 2;
761 } else if (linepos[0] == '-' && linepos[1] == '=') {
762 *op = OP_REMOVE;
763 linepos += 2;
764 } else if (linepos[0] == '=') {
765 *op = OP_ASSIGN;
766 linepos++;
767 } else if (linepos[0] == ':' && linepos[1] == '=') {
768 *op = OP_ASSIGN_FINAL;
769 linepos += 2;
770 } else
771 return -1;
772
773 /* terminate key */
774 temp[0] = '\0';
775
776 /* skip whitespace after operator */
777 while (isspace(linepos[0]))
778 linepos++;
779 if (linepos[0] == '\0')
780 return -1;
781
782 /* get the value */
783 if (linepos[0] == '"')
784 linepos++;
785 else
786 return -1;
787 *value = linepos;
788
789 /* terminate */
790 for (i = 0, j = 0; ; i++, j++) {
791
792 if (linepos[i] == '"')
793 break;
794
795 if (linepos[i] == '\0')
796 return -1;
797
798 /* double quotes can be escaped */
799 if (linepos[i] == '\\')
800 if (linepos[i+1] == '"')
801 i++;
802
803 linepos[j] = linepos[i];
804 }
805 linepos[j] = '\0';
806
807 /* move line to next key */
808 *line = linepos + i + 1;
809 return 0;
810 }
811
812 /* extract possible KEY{attr} */
813 static const char *get_key_attribute(char *str) {
814 char *pos;
815 char *attr;
816
817 attr = strchr(str, '{');
818 if (attr != NULL) {
819 attr++;
820 pos = strchr(attr, '}');
821 if (pos == NULL) {
822 log_error("Missing closing brace for format");
823 return NULL;
824 }
825 pos[0] = '\0';
826 return attr;
827 }
828 return NULL;
829 }
830
831 static void rule_add_key(struct rule_tmp *rule_tmp, enum token_type type,
832 enum operation_type op,
833 const char *value, const void *data) {
834 struct token *token = rule_tmp->token + rule_tmp->token_cur;
835 const char *attr = NULL;
836
837 assert(rule_tmp->token_cur < ELEMENTSOF(rule_tmp->token));
838 memzero(token, sizeof(struct token));
839
840 switch (type) {
841 case TK_M_ACTION:
842 case TK_M_DEVPATH:
843 case TK_M_KERNEL:
844 case TK_M_SUBSYSTEM:
845 case TK_M_DRIVER:
846 case TK_M_WAITFOR:
847 case TK_M_DEVLINK:
848 case TK_M_NAME:
849 case TK_M_KERNELS:
850 case TK_M_SUBSYSTEMS:
851 case TK_M_DRIVERS:
852 case TK_M_TAGS:
853 case TK_M_PROGRAM:
854 case TK_M_IMPORT_FILE:
855 case TK_M_IMPORT_PROG:
856 case TK_M_IMPORT_DB:
857 case TK_M_IMPORT_CMDLINE:
858 case TK_M_IMPORT_PARENT:
859 case TK_M_RESULT:
860 case TK_A_OWNER:
861 case TK_A_GROUP:
862 case TK_A_MODE:
863 case TK_A_DEVLINK:
864 case TK_A_NAME:
865 case TK_A_GOTO:
866 case TK_M_TAG:
867 case TK_A_TAG:
868 case TK_A_STATIC_NODE:
869 token->key.value_off = rules_add_string(rule_tmp->rules, value);
870 break;
871 case TK_M_IMPORT_BUILTIN:
872 token->key.value_off = rules_add_string(rule_tmp->rules, value);
873 token->key.builtin_cmd = *(enum udev_builtin_cmd *)data;
874 break;
875 case TK_M_ENV:
876 case TK_M_ATTR:
877 case TK_M_SYSCTL:
878 case TK_M_ATTRS:
879 case TK_A_ATTR:
880 case TK_A_SYSCTL:
881 case TK_A_ENV:
882 case TK_A_SECLABEL:
883 attr = data;
884 token->key.value_off = rules_add_string(rule_tmp->rules, value);
885 token->key.attr_off = rules_add_string(rule_tmp->rules, attr);
886 break;
887 case TK_M_TEST:
888 token->key.value_off = rules_add_string(rule_tmp->rules, value);
889 if (data != NULL)
890 token->key.mode = *(mode_t *)data;
891 break;
892 case TK_A_STRING_ESCAPE_NONE:
893 case TK_A_STRING_ESCAPE_REPLACE:
894 case TK_A_DB_PERSIST:
895 break;
896 case TK_A_RUN_BUILTIN:
897 case TK_A_RUN_PROGRAM:
898 token->key.builtin_cmd = *(enum udev_builtin_cmd *)data;
899 token->key.value_off = rules_add_string(rule_tmp->rules, value);
900 break;
901 case TK_A_INOTIFY_WATCH:
902 case TK_A_DEVLINK_PRIO:
903 token->key.devlink_prio = *(int *)data;
904 break;
905 case TK_A_OWNER_ID:
906 token->key.uid = *(uid_t *)data;
907 break;
908 case TK_A_GROUP_ID:
909 token->key.gid = *(gid_t *)data;
910 break;
911 case TK_A_MODE_ID:
912 token->key.mode = *(mode_t *)data;
913 break;
914 case TK_RULE:
915 case TK_M_PARENTS_MIN:
916 case TK_M_PARENTS_MAX:
917 case TK_M_MAX:
918 case TK_END:
919 case TK_UNSET:
920 assert_not_reached("wrong type");
921 }
922
923 if (value != NULL && type < TK_M_MAX) {
924 /* check if we need to split or call fnmatch() while matching rules */
925 enum string_glob_type glob;
926 int has_split;
927 int has_glob;
928
929 has_split = (strchr(value, '|') != NULL);
930 has_glob = string_is_glob(value);
931 if (has_split && has_glob) {
932 glob = GL_SPLIT_GLOB;
933 } else if (has_split) {
934 glob = GL_SPLIT;
935 } else if (has_glob) {
936 if (streq(value, "?*"))
937 glob = GL_SOMETHING;
938 else
939 glob = GL_GLOB;
940 } else {
941 glob = GL_PLAIN;
942 }
943 token->key.glob = glob;
944 }
945
946 if (value != NULL && type > TK_M_MAX) {
947 /* check if assigned value has substitution chars */
948 if (value[0] == '[')
949 token->key.subst = SB_SUBSYS;
950 else if (strchr(value, '%') != NULL || strchr(value, '$') != NULL)
951 token->key.subst = SB_FORMAT;
952 else
953 token->key.subst = SB_NONE;
954 }
955
956 if (attr != NULL) {
957 /* check if property/attribute name has substitution chars */
958 if (attr[0] == '[')
959 token->key.attrsubst = SB_SUBSYS;
960 else if (strchr(attr, '%') != NULL || strchr(attr, '$') != NULL)
961 token->key.attrsubst = SB_FORMAT;
962 else
963 token->key.attrsubst = SB_NONE;
964 }
965
966 token->key.type = type;
967 token->key.op = op;
968 rule_tmp->token_cur++;
969 }
970
971 static int sort_token(struct udev_rules *rules, struct rule_tmp *rule_tmp) {
972 unsigned i;
973 unsigned start = 0;
974 unsigned end = rule_tmp->token_cur;
975
976 for (i = 0; i < rule_tmp->token_cur; i++) {
977 enum token_type next_val = TK_UNSET;
978 unsigned next_idx = 0;
979 unsigned j;
980
981 /* find smallest value */
982 for (j = start; j < end; j++) {
983 if (rule_tmp->token[j].type == TK_UNSET)
984 continue;
985 if (next_val == TK_UNSET || rule_tmp->token[j].type < next_val) {
986 next_val = rule_tmp->token[j].type;
987 next_idx = j;
988 }
989 }
990
991 /* add token and mark done */
992 if (add_token(rules, &rule_tmp->token[next_idx]) != 0)
993 return -1;
994 rule_tmp->token[next_idx].type = TK_UNSET;
995
996 /* shrink range */
997 if (next_idx == start)
998 start++;
999 if (next_idx+1 == end)
1000 end--;
1001 }
1002 return 0;
1003 }
1004
1005 #define LOG_RULE_ERROR(fmt, ...) log_error("Invalid rule %s:%u: " fmt, filename, lineno, ##__VA_ARGS__)
1006 #define LOG_RULE_WARNING(fmt, ...) log_warning("%s:%u: " fmt, filename, lineno, ##__VA_ARGS__)
1007 #define LOG_RULE_DEBUG(fmt, ...) log_debug("%s:%u: " fmt, filename, lineno, ##__VA_ARGS__)
1008 #define LOG_AND_RETURN(fmt, ...) { LOG_RULE_ERROR(fmt, __VA_ARGS__); return; }
1009
1010 static void add_rule(struct udev_rules *rules, char *line,
1011 const char *filename, unsigned filename_off, unsigned lineno) {
1012 char *linepos;
1013 const char *attr;
1014 struct rule_tmp rule_tmp = {
1015 .rules = rules,
1016 .rule.type = TK_RULE,
1017 };
1018
1019 /* the offset in the rule is limited to unsigned short */
1020 if (filename_off < USHRT_MAX)
1021 rule_tmp.rule.rule.filename_off = filename_off;
1022 rule_tmp.rule.rule.filename_line = lineno;
1023
1024 linepos = line;
1025 for (;;) {
1026 char *key;
1027 char *value;
1028 enum operation_type op;
1029
1030 if (get_key(&linepos, &key, &op, &value) != 0) {
1031 /* Avoid erroring on trailing whitespace. This is probably rare
1032 * so save the work for the error case instead of always trying
1033 * to strip the trailing whitespace with strstrip(). */
1034 while (isblank(*linepos))
1035 linepos++;
1036
1037 /* If we aren't at the end of the line, this is a parsing error.
1038 * Make a best effort to describe where the problem is. */
1039 if (!strchr(NEWLINE, *linepos)) {
1040 char buf[2] = {*linepos};
1041 _cleanup_free_ char *tmp;
1042
1043 tmp = cescape(buf);
1044 log_error("invalid key/value pair in file %s on line %u, starting at character %tu ('%s')",
1045 filename, lineno, linepos - line + 1, tmp);
1046 if (*linepos == '#')
1047 log_error("hint: comments can only start at beginning of line");
1048 }
1049 break;
1050 }
1051
1052 if (rule_tmp.token_cur >= ELEMENTSOF(rule_tmp.token))
1053 LOG_AND_RETURN("temporary rule array too small, aborting event processing with %u items", rule_tmp.token_cur);
1054
1055 if (streq(key, "ACTION")) {
1056 if (op > OP_MATCH_MAX)
1057 LOG_AND_RETURN("invalid %s operation", key);
1058
1059 rule_add_key(&rule_tmp, TK_M_ACTION, op, value, NULL);
1060
1061 } else if (streq(key, "DEVPATH")) {
1062 if (op > OP_MATCH_MAX)
1063 LOG_AND_RETURN("invalid %s operation", key);
1064
1065 rule_add_key(&rule_tmp, TK_M_DEVPATH, op, value, NULL);
1066
1067 } else if (streq(key, "KERNEL")) {
1068 if (op > OP_MATCH_MAX)
1069 LOG_AND_RETURN("invalid %s operation", key);
1070
1071 rule_add_key(&rule_tmp, TK_M_KERNEL, op, value, NULL);
1072
1073 } else if (streq(key, "SUBSYSTEM")) {
1074 if (op > OP_MATCH_MAX)
1075 LOG_AND_RETURN("invalid %s operation", key);
1076
1077 /* bus, class, subsystem events should all be the same */
1078 if (STR_IN_SET(value, "subsystem", "bus", "class")) {
1079 if (!streq(value, "subsystem"))
1080 LOG_RULE_WARNING("'%s' must be specified as 'subsystem'; please fix", value);
1081
1082 rule_add_key(&rule_tmp, TK_M_SUBSYSTEM, op, "subsystem|class|bus", NULL);
1083 } else
1084 rule_add_key(&rule_tmp, TK_M_SUBSYSTEM, op, value, NULL);
1085
1086 } else if (streq(key, "DRIVER")) {
1087 if (op > OP_MATCH_MAX)
1088 LOG_AND_RETURN("invalid %s operation", key);
1089
1090 rule_add_key(&rule_tmp, TK_M_DRIVER, op, value, NULL);
1091
1092 } else if (startswith(key, "ATTR{")) {
1093 attr = get_key_attribute(key + STRLEN("ATTR"));
1094 if (attr == NULL)
1095 LOG_AND_RETURN("error parsing %s attribute", "ATTR");
1096
1097 if (op == OP_REMOVE)
1098 LOG_AND_RETURN("invalid %s operation", "ATTR");
1099
1100 if (op < OP_MATCH_MAX)
1101 rule_add_key(&rule_tmp, TK_M_ATTR, op, value, attr);
1102 else
1103 rule_add_key(&rule_tmp, TK_A_ATTR, op, value, attr);
1104
1105 } else if (startswith(key, "SYSCTL{")) {
1106 attr = get_key_attribute(key + STRLEN("SYSCTL"));
1107 if (attr == NULL)
1108 LOG_AND_RETURN("error parsing %s attribute", "ATTR");
1109
1110 if (op == OP_REMOVE)
1111 LOG_AND_RETURN("invalid %s operation", "ATTR");
1112
1113 if (op < OP_MATCH_MAX)
1114 rule_add_key(&rule_tmp, TK_M_SYSCTL, op, value, attr);
1115 else
1116 rule_add_key(&rule_tmp, TK_A_SYSCTL, op, value, attr);
1117
1118 } else if (startswith(key, "SECLABEL{")) {
1119 attr = get_key_attribute(key + STRLEN("SECLABEL"));
1120 if (attr == NULL)
1121 LOG_AND_RETURN("error parsing %s attribute", "SECLABEL");
1122
1123 if (op == OP_REMOVE)
1124 LOG_AND_RETURN("invalid %s operation", "SECLABEL");
1125
1126 rule_add_key(&rule_tmp, TK_A_SECLABEL, op, value, attr);
1127
1128 } else if (streq(key, "KERNELS")) {
1129 if (op > OP_MATCH_MAX)
1130 LOG_AND_RETURN("invalid %s operation", key);
1131
1132 rule_add_key(&rule_tmp, TK_M_KERNELS, op, value, NULL);
1133
1134 } else if (streq(key, "SUBSYSTEMS")) {
1135 if (op > OP_MATCH_MAX)
1136 LOG_AND_RETURN("invalid %s operation", key);
1137
1138 rule_add_key(&rule_tmp, TK_M_SUBSYSTEMS, op, value, NULL);
1139
1140 } else if (streq(key, "DRIVERS")) {
1141 if (op > OP_MATCH_MAX)
1142 LOG_AND_RETURN("invalid %s operation", key);
1143
1144 rule_add_key(&rule_tmp, TK_M_DRIVERS, op, value, NULL);
1145
1146 } else if (startswith(key, "ATTRS{")) {
1147 if (op > OP_MATCH_MAX)
1148 LOG_AND_RETURN("invalid %s operation", "ATTRS");
1149
1150 attr = get_key_attribute(key + STRLEN("ATTRS"));
1151 if (attr == NULL)
1152 LOG_AND_RETURN("error parsing %s attribute", "ATTRS");
1153
1154 if (startswith(attr, "device/"))
1155 LOG_RULE_WARNING("'device' link may not be available in future kernels; please fix");
1156 if (strstr(attr, "../") != NULL)
1157 LOG_RULE_WARNING("direct reference to parent sysfs directory, may break in future kernels; please fix");
1158 rule_add_key(&rule_tmp, TK_M_ATTRS, op, value, attr);
1159
1160 } else if (streq(key, "TAGS")) {
1161 if (op > OP_MATCH_MAX)
1162 LOG_AND_RETURN("invalid %s operation", key);
1163
1164 rule_add_key(&rule_tmp, TK_M_TAGS, op, value, NULL);
1165
1166 } else if (startswith(key, "ENV{")) {
1167 attr = get_key_attribute(key + STRLEN("ENV"));
1168 if (attr == NULL)
1169 LOG_AND_RETURN("error parsing %s attribute", "ENV");
1170
1171 if (op == OP_REMOVE)
1172 LOG_AND_RETURN("invalid %s operation", "ENV");
1173
1174 if (op < OP_MATCH_MAX)
1175 rule_add_key(&rule_tmp, TK_M_ENV, op, value, attr);
1176 else {
1177 if (STR_IN_SET(attr,
1178 "ACTION",
1179 "SUBSYSTEM",
1180 "DEVTYPE",
1181 "MAJOR",
1182 "MINOR",
1183 "DRIVER",
1184 "IFINDEX",
1185 "DEVNAME",
1186 "DEVLINKS",
1187 "DEVPATH",
1188 "TAGS"))
1189 LOG_AND_RETURN("invalid ENV attribute, '%s' cannot be set", attr);
1190
1191 rule_add_key(&rule_tmp, TK_A_ENV, op, value, attr);
1192 }
1193
1194 } else if (streq(key, "TAG")) {
1195 if (op < OP_MATCH_MAX)
1196 rule_add_key(&rule_tmp, TK_M_TAG, op, value, NULL);
1197 else
1198 rule_add_key(&rule_tmp, TK_A_TAG, op, value, NULL);
1199
1200 } else if (streq(key, "PROGRAM")) {
1201 if (op == OP_REMOVE)
1202 LOG_AND_RETURN("invalid %s operation", key);
1203
1204 rule_add_key(&rule_tmp, TK_M_PROGRAM, op, value, NULL);
1205
1206 } else if (streq(key, "RESULT")) {
1207 if (op > OP_MATCH_MAX)
1208 LOG_AND_RETURN("invalid %s operation", key);
1209
1210 rule_add_key(&rule_tmp, TK_M_RESULT, op, value, NULL);
1211
1212 } else if (startswith(key, "IMPORT")) {
1213 attr = get_key_attribute(key + STRLEN("IMPORT"));
1214 if (attr == NULL) {
1215 LOG_RULE_WARNING("ignoring IMPORT{} with missing type");
1216 continue;
1217 }
1218 if (op == OP_REMOVE)
1219 LOG_AND_RETURN("invalid %s operation", "IMPORT");
1220
1221 if (streq(attr, "program")) {
1222 /* find known built-in command */
1223 if (value[0] != '/') {
1224 const enum udev_builtin_cmd cmd = udev_builtin_lookup(value);
1225
1226 if (cmd >= 0) {
1227 LOG_RULE_DEBUG("IMPORT found builtin '%s', replacing", value);
1228 rule_add_key(&rule_tmp, TK_M_IMPORT_BUILTIN, op, value, &cmd);
1229 continue;
1230 }
1231 }
1232 rule_add_key(&rule_tmp, TK_M_IMPORT_PROG, op, value, NULL);
1233 } else if (streq(attr, "builtin")) {
1234 const enum udev_builtin_cmd cmd = udev_builtin_lookup(value);
1235
1236 if (cmd < 0)
1237 LOG_RULE_WARNING("IMPORT{builtin} '%s' unknown", value);
1238 else
1239 rule_add_key(&rule_tmp, TK_M_IMPORT_BUILTIN, op, value, &cmd);
1240 } else if (streq(attr, "file"))
1241 rule_add_key(&rule_tmp, TK_M_IMPORT_FILE, op, value, NULL);
1242 else if (streq(attr, "db"))
1243 rule_add_key(&rule_tmp, TK_M_IMPORT_DB, op, value, NULL);
1244 else if (streq(attr, "cmdline"))
1245 rule_add_key(&rule_tmp, TK_M_IMPORT_CMDLINE, op, value, NULL);
1246 else if (streq(attr, "parent"))
1247 rule_add_key(&rule_tmp, TK_M_IMPORT_PARENT, op, value, NULL);
1248 else
1249 LOG_RULE_ERROR("ignoring unknown %s{} type '%s'", "IMPORT", attr);
1250
1251 } else if (startswith(key, "TEST")) {
1252 mode_t mode = 0;
1253
1254 if (op > OP_MATCH_MAX)
1255 LOG_AND_RETURN("invalid %s operation", "TEST");
1256
1257 attr = get_key_attribute(key + STRLEN("TEST"));
1258 if (attr != NULL) {
1259 mode = strtol(attr, NULL, 8);
1260 rule_add_key(&rule_tmp, TK_M_TEST, op, value, &mode);
1261 } else
1262 rule_add_key(&rule_tmp, TK_M_TEST, op, value, NULL);
1263
1264 } else if (startswith(key, "RUN")) {
1265 attr = get_key_attribute(key + STRLEN("RUN"));
1266 if (attr == NULL)
1267 attr = "program";
1268 if (op == OP_REMOVE)
1269 LOG_AND_RETURN("invalid %s operation", "RUN");
1270
1271 if (streq(attr, "builtin")) {
1272 const enum udev_builtin_cmd cmd = udev_builtin_lookup(value);
1273
1274 if (cmd < 0)
1275 LOG_RULE_ERROR("RUN{builtin}: '%s' unknown", value);
1276 else
1277 rule_add_key(&rule_tmp, TK_A_RUN_BUILTIN, op, value, &cmd);
1278 } else if (streq(attr, "program")) {
1279 const enum udev_builtin_cmd cmd = _UDEV_BUILTIN_MAX;
1280
1281 rule_add_key(&rule_tmp, TK_A_RUN_PROGRAM, op, value, &cmd);
1282 } else
1283 LOG_RULE_ERROR("ignoring unknown %s{} type '%s'", "RUN", attr);
1284
1285 } else if (streq(key, "LABEL")) {
1286 if (op == OP_REMOVE)
1287 LOG_AND_RETURN("invalid %s operation", key);
1288
1289 rule_tmp.rule.rule.label_off = rules_add_string(rules, value);
1290
1291 } else if (streq(key, "GOTO")) {
1292 if (op == OP_REMOVE)
1293 LOG_AND_RETURN("invalid %s operation", key);
1294
1295 rule_add_key(&rule_tmp, TK_A_GOTO, 0, value, NULL);
1296
1297 } else if (startswith(key, "NAME")) {
1298 if (op == OP_REMOVE)
1299 LOG_AND_RETURN("invalid %s operation", key);
1300
1301 if (op < OP_MATCH_MAX)
1302 rule_add_key(&rule_tmp, TK_M_NAME, op, value, NULL);
1303 else {
1304 if (streq(value, "%k")) {
1305 LOG_RULE_WARNING("NAME=\"%%k\" is ignored, because it breaks kernel supplied names; please remove");
1306 continue;
1307 }
1308 if (isempty(value)) {
1309 LOG_RULE_DEBUG("NAME=\"\" is ignored, because udev will not delete any device nodes; please remove");
1310 continue;
1311 }
1312 rule_add_key(&rule_tmp, TK_A_NAME, op, value, NULL);
1313 }
1314 rule_tmp.rule.rule.can_set_name = true;
1315
1316 } else if (streq(key, "SYMLINK")) {
1317 if (op == OP_REMOVE)
1318 LOG_AND_RETURN("invalid %s operation", key);
1319
1320 if (op < OP_MATCH_MAX)
1321 rule_add_key(&rule_tmp, TK_M_DEVLINK, op, value, NULL);
1322 else
1323 rule_add_key(&rule_tmp, TK_A_DEVLINK, op, value, NULL);
1324 rule_tmp.rule.rule.can_set_name = true;
1325
1326 } else if (streq(key, "OWNER")) {
1327 uid_t uid;
1328 char *endptr;
1329
1330 if (op == OP_REMOVE)
1331 LOG_AND_RETURN("invalid %s operation", key);
1332
1333 uid = strtoul(value, &endptr, 10);
1334 if (endptr[0] == '\0')
1335 rule_add_key(&rule_tmp, TK_A_OWNER_ID, op, NULL, &uid);
1336 else if (rules->resolve_name_timing == RESOLVE_NAME_EARLY && strchr("$%", value[0]) == NULL) {
1337 uid = add_uid(rules, value);
1338 rule_add_key(&rule_tmp, TK_A_OWNER_ID, op, NULL, &uid);
1339 } else if (rules->resolve_name_timing != RESOLVE_NAME_NEVER)
1340 rule_add_key(&rule_tmp, TK_A_OWNER, op, value, NULL);
1341
1342 rule_tmp.rule.rule.can_set_name = true;
1343
1344 } else if (streq(key, "GROUP")) {
1345 gid_t gid;
1346 char *endptr;
1347
1348 if (op == OP_REMOVE)
1349 LOG_AND_RETURN("invalid %s operation", key);
1350
1351 gid = strtoul(value, &endptr, 10);
1352 if (endptr[0] == '\0')
1353 rule_add_key(&rule_tmp, TK_A_GROUP_ID, op, NULL, &gid);
1354 else if ((rules->resolve_name_timing == RESOLVE_NAME_EARLY) && strchr("$%", value[0]) == NULL) {
1355 gid = add_gid(rules, value);
1356 rule_add_key(&rule_tmp, TK_A_GROUP_ID, op, NULL, &gid);
1357 } else if (rules->resolve_name_timing != RESOLVE_NAME_NEVER)
1358 rule_add_key(&rule_tmp, TK_A_GROUP, op, value, NULL);
1359
1360 rule_tmp.rule.rule.can_set_name = true;
1361
1362 } else if (streq(key, "MODE")) {
1363 mode_t mode;
1364 char *endptr;
1365
1366 if (op == OP_REMOVE)
1367 LOG_AND_RETURN("invalid %s operation", key);
1368
1369 mode = strtol(value, &endptr, 8);
1370 if (endptr[0] == '\0')
1371 rule_add_key(&rule_tmp, TK_A_MODE_ID, op, NULL, &mode);
1372 else
1373 rule_add_key(&rule_tmp, TK_A_MODE, op, value, NULL);
1374 rule_tmp.rule.rule.can_set_name = true;
1375
1376 } else if (streq(key, "OPTIONS")) {
1377 const char *pos;
1378
1379 if (op == OP_REMOVE)
1380 LOG_AND_RETURN("invalid %s operation", key);
1381
1382 pos = strstr(value, "link_priority=");
1383 if (pos != NULL) {
1384 int prio = atoi(pos + STRLEN("link_priority="));
1385
1386 rule_add_key(&rule_tmp, TK_A_DEVLINK_PRIO, op, NULL, &prio);
1387 }
1388
1389 pos = strstr(value, "string_escape=");
1390 if (pos != NULL) {
1391 pos += STRLEN("string_escape=");
1392 if (startswith(pos, "none"))
1393 rule_add_key(&rule_tmp, TK_A_STRING_ESCAPE_NONE, op, NULL, NULL);
1394 else if (startswith(pos, "replace"))
1395 rule_add_key(&rule_tmp, TK_A_STRING_ESCAPE_REPLACE, op, NULL, NULL);
1396 }
1397
1398 pos = strstr(value, "db_persist");
1399 if (pos != NULL)
1400 rule_add_key(&rule_tmp, TK_A_DB_PERSIST, op, NULL, NULL);
1401
1402 pos = strstr(value, "nowatch");
1403 if (pos) {
1404 static const int zero = 0;
1405 rule_add_key(&rule_tmp, TK_A_INOTIFY_WATCH, op, NULL, &zero);
1406 } else {
1407 static const int one = 1;
1408 pos = strstr(value, "watch");
1409 if (pos)
1410 rule_add_key(&rule_tmp, TK_A_INOTIFY_WATCH, op, NULL, &one);
1411 }
1412
1413 pos = strstr(value, "static_node=");
1414 if (pos != NULL) {
1415 pos += STRLEN("static_node=");
1416 rule_add_key(&rule_tmp, TK_A_STATIC_NODE, op, pos, NULL);
1417 rule_tmp.rule.rule.has_static_node = true;
1418 }
1419
1420 } else
1421 LOG_AND_RETURN("unknown key '%s'", key);
1422 }
1423
1424 /* add rule token and sort tokens */
1425 rule_tmp.rule.rule.token_count = 1 + rule_tmp.token_cur;
1426 if (add_token(rules, &rule_tmp.rule) != 0 || sort_token(rules, &rule_tmp) != 0)
1427 LOG_RULE_ERROR("failed to add rule token");
1428 }
1429
1430 static int parse_file(struct udev_rules *rules, const char *filename) {
1431 _cleanup_fclose_ FILE *f = NULL;
1432 unsigned first_token;
1433 unsigned filename_off;
1434 char line[UTIL_LINE_SIZE];
1435 int line_nr = 0;
1436 unsigned i;
1437
1438 f = fopen(filename, "re");
1439 if (!f) {
1440 if (errno == ENOENT)
1441 return 0;
1442
1443 return -errno;
1444 }
1445
1446 if (null_or_empty_fd(fileno(f))) {
1447 log_debug("Skipping empty file: %s", filename);
1448 return 0;
1449 } else
1450 log_debug("Reading rules file: %s", filename);
1451
1452 first_token = rules->token_cur;
1453 filename_off = rules_add_string(rules, filename);
1454
1455 while (fgets(line, sizeof(line), f) != NULL) {
1456 char *key;
1457 size_t len;
1458
1459 /* skip whitespace */
1460 line_nr++;
1461 key = line;
1462 while (isspace(key[0]))
1463 key++;
1464
1465 /* comment */
1466 if (key[0] == '#')
1467 continue;
1468
1469 len = strlen(line);
1470 if (len < 3)
1471 continue;
1472
1473 /* continue reading if backslash+newline is found */
1474 while (line[len-2] == '\\') {
1475 if (fgets(&line[len-2], (sizeof(line)-len)+2, f) == NULL)
1476 break;
1477 if (strlen(&line[len-2]) < 2)
1478 break;
1479 line_nr++;
1480 len = strlen(line);
1481 }
1482
1483 if (len+1 >= sizeof(line)) {
1484 log_error("line too long '%s':%u, ignored", filename, line_nr);
1485 continue;
1486 }
1487 add_rule(rules, key, filename, filename_off, line_nr);
1488 }
1489
1490 /* link GOTOs to LABEL rules in this file to be able to fast-forward */
1491 for (i = first_token+1; i < rules->token_cur; i++) {
1492 if (rules->tokens[i].type == TK_A_GOTO) {
1493 char *label = rules_str(rules, rules->tokens[i].key.value_off);
1494 unsigned j;
1495
1496 for (j = i+1; j < rules->token_cur; j++) {
1497 if (rules->tokens[j].type != TK_RULE)
1498 continue;
1499 if (rules->tokens[j].rule.label_off == 0)
1500 continue;
1501 if (!streq(label, rules_str(rules, rules->tokens[j].rule.label_off)))
1502 continue;
1503 rules->tokens[i].key.rule_goto = j;
1504 break;
1505 }
1506 if (rules->tokens[i].key.rule_goto == 0)
1507 log_error("GOTO '%s' has no matching label in: '%s'", label, filename);
1508 }
1509 }
1510 return 0;
1511 }
1512
1513 struct udev_rules *udev_rules_new(ResolveNameTiming resolve_name_timing) {
1514 struct udev_rules *rules;
1515 struct token end_token;
1516 char **files, **f;
1517 int r;
1518
1519 assert(resolve_name_timing >= 0 && resolve_name_timing < _RESOLVE_NAME_TIMING_MAX);
1520
1521 rules = new(struct udev_rules, 1);
1522 if (!rules)
1523 return NULL;
1524
1525 *rules = (struct udev_rules) {
1526 .resolve_name_timing = resolve_name_timing,
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 Hashmap *properties_list) {
1729 sd_device *dev = event->dev;
1730 enum escape_type esc = ESCAPE_UNSET;
1731 struct token *cur, *rule;
1732 const char *action, *val;
1733 bool can_set_name;
1734 int r;
1735
1736 if (!rules->tokens)
1737 return 0;
1738
1739 r = sd_device_get_property_value(dev, "ACTION", &action);
1740 if (r < 0)
1741 return r;
1742
1743 can_set_name = (!streq(action, "remove") &&
1744 (sd_device_get_devnum(dev, NULL) >= 0 ||
1745 sd_device_get_ifindex(dev, NULL) >= 0));
1746
1747 /* loop through token list, match, run actions or forward to next rule */
1748 cur = &rules->tokens[0];
1749 rule = cur;
1750 for (;;) {
1751 dump_token(rules, cur);
1752 switch (cur->type) {
1753 case TK_RULE:
1754 /* current rule */
1755 rule = cur;
1756 /* possibly skip rules which want to set NAME, SYMLINK, OWNER, GROUP, MODE */
1757 if (!can_set_name && rule->rule.can_set_name)
1758 goto nomatch;
1759 esc = ESCAPE_UNSET;
1760 break;
1761 case TK_M_ACTION:
1762 if (match_key(rules, cur, action) != 0)
1763 goto nomatch;
1764 break;
1765 case TK_M_DEVPATH:
1766 if (sd_device_get_devpath(dev, &val) < 0)
1767 goto nomatch;
1768 if (match_key(rules, cur, val) != 0)
1769 goto nomatch;
1770 break;
1771 case TK_M_KERNEL:
1772 if (sd_device_get_sysname(dev, &val) < 0)
1773 goto nomatch;
1774 if (match_key(rules, cur, val) != 0)
1775 goto nomatch;
1776 break;
1777 case TK_M_DEVLINK: {
1778 const char *devlink;
1779 bool match = false;
1780
1781 FOREACH_DEVICE_DEVLINK(dev, devlink)
1782 if (match_key(rules, cur, devlink + STRLEN("/dev/")) == 0) {
1783 match = true;
1784 break;
1785 }
1786
1787 if (!match)
1788 goto nomatch;
1789 break;
1790 }
1791 case TK_M_NAME:
1792 if (match_key(rules, cur, event->name) != 0)
1793 goto nomatch;
1794 break;
1795 case TK_M_ENV: {
1796 const char *key_name = rules_str(rules, cur->key.attr_off);
1797
1798 if (sd_device_get_property_value(dev, key_name, &val) < 0) {
1799 /* check global properties */
1800 if (properties_list)
1801 val = hashmap_get(properties_list, key_name);
1802 else
1803 val = NULL;
1804 }
1805
1806 if (match_key(rules, cur, strempty(val)))
1807 goto nomatch;
1808 break;
1809 }
1810 case TK_M_TAG: {
1811 bool match = false;
1812 const char *tag;
1813
1814 FOREACH_DEVICE_TAG(dev, tag)
1815 if (streq(rules_str(rules, cur->key.value_off), tag)) {
1816 match = true;
1817 break;
1818 }
1819
1820 if ((!match && (cur->key.op != OP_NOMATCH)) ||
1821 (match && (cur->key.op == OP_NOMATCH)))
1822 goto nomatch;
1823 break;
1824 }
1825 case TK_M_SUBSYSTEM:
1826 if (sd_device_get_subsystem(dev, &val) < 0)
1827 goto nomatch;
1828 if (match_key(rules, cur, val) != 0)
1829 goto nomatch;
1830 break;
1831 case TK_M_DRIVER:
1832 if (sd_device_get_driver(dev, &val) < 0)
1833 goto nomatch;
1834 if (match_key(rules, cur, val) != 0)
1835 goto nomatch;
1836 break;
1837 case TK_M_ATTR:
1838 if (match_attr(rules, dev, event, cur) != 0)
1839 goto nomatch;
1840 break;
1841 case TK_M_SYSCTL: {
1842 char filename[UTIL_PATH_SIZE];
1843 _cleanup_free_ char *value = NULL;
1844 size_t len;
1845
1846 udev_event_apply_format(event, rules_str(rules, cur->key.attr_off), filename, sizeof(filename), false);
1847 sysctl_normalize(filename);
1848 if (sysctl_read(filename, &value) < 0)
1849 goto nomatch;
1850
1851 len = strlen(value);
1852 while (len > 0 && isspace(value[--len]))
1853 value[len] = '\0';
1854 if (match_key(rules, cur, value) != 0)
1855 goto nomatch;
1856 break;
1857 }
1858 case TK_M_KERNELS:
1859 case TK_M_SUBSYSTEMS:
1860 case TK_M_DRIVERS:
1861 case TK_M_ATTRS:
1862 case TK_M_TAGS: {
1863 struct token *next;
1864
1865 /* get whole sequence of parent matches */
1866 next = cur;
1867 while (next->type > TK_M_PARENTS_MIN && next->type < TK_M_PARENTS_MAX)
1868 next++;
1869
1870 /* loop over parents */
1871 event->dev_parent = dev;
1872 for (;;) {
1873 struct token *key;
1874
1875 /* loop over sequence of parent match keys */
1876 for (key = cur; key < next; key++ ) {
1877 dump_token(rules, key);
1878 switch(key->type) {
1879 case TK_M_KERNELS:
1880 if (sd_device_get_sysname(event->dev_parent, &val) < 0)
1881 goto try_parent;
1882 if (match_key(rules, key, val) != 0)
1883 goto try_parent;
1884 break;
1885 case TK_M_SUBSYSTEMS:
1886 if (sd_device_get_subsystem(event->dev_parent, &val) < 0)
1887 goto try_parent;
1888 if (match_key(rules, key, val) != 0)
1889 goto try_parent;
1890 break;
1891 case TK_M_DRIVERS:
1892 if (sd_device_get_driver(event->dev_parent, &val) < 0)
1893 goto try_parent;
1894 if (match_key(rules, key, val) != 0)
1895 goto try_parent;
1896 break;
1897 case TK_M_ATTRS:
1898 if (match_attr(rules, event->dev_parent, event, key) != 0)
1899 goto try_parent;
1900 break;
1901 case TK_M_TAGS: {
1902 bool match = sd_device_has_tag(event->dev_parent, rules_str(rules, cur->key.value_off));
1903
1904 if (match && key->key.op == OP_NOMATCH)
1905 goto try_parent;
1906 if (!match && key->key.op == OP_MATCH)
1907 goto try_parent;
1908 break;
1909 }
1910 default:
1911 goto nomatch;
1912 }
1913 }
1914 break;
1915
1916 try_parent:
1917 if (sd_device_get_parent(event->dev_parent, &event->dev_parent) < 0) {
1918 event->dev_parent = NULL;
1919 goto nomatch;
1920 }
1921 }
1922 /* move behind our sequence of parent match keys */
1923 cur = next;
1924 continue;
1925 }
1926 case TK_M_TEST: {
1927 char filename[UTIL_PATH_SIZE];
1928 struct stat statbuf;
1929 int match;
1930
1931 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), filename, sizeof(filename), false);
1932 if (util_resolve_subsys_kernel(filename, filename, sizeof(filename), 0) != 0) {
1933 if (filename[0] != '/') {
1934 char tmp[UTIL_PATH_SIZE];
1935
1936 if (sd_device_get_syspath(dev, &val) < 0)
1937 goto nomatch;
1938
1939 strscpy(tmp, sizeof(tmp), filename);
1940 strscpyl(filename, sizeof(filename), val, "/", tmp, NULL);
1941 }
1942 }
1943 attr_subst_subdir(filename, sizeof(filename));
1944
1945 match = (stat(filename, &statbuf) == 0);
1946 if (match && cur->key.mode > 0)
1947 match = ((statbuf.st_mode & cur->key.mode) > 0);
1948 if (match && cur->key.op == OP_NOMATCH)
1949 goto nomatch;
1950 if (!match && cur->key.op == OP_MATCH)
1951 goto nomatch;
1952 break;
1953 }
1954 case TK_M_PROGRAM: {
1955 char program[UTIL_PATH_SIZE], result[UTIL_LINE_SIZE];
1956
1957 event->program_result = mfree(event->program_result);
1958 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), program, sizeof(program), false);
1959 log_debug("PROGRAM '%s' %s:%u",
1960 program,
1961 rules_str(rules, rule->rule.filename_off),
1962 rule->rule.filename_line);
1963
1964 if (udev_event_spawn(event, timeout_usec, true, program, result, sizeof(result)) < 0) {
1965 if (cur->key.op != OP_NOMATCH)
1966 goto nomatch;
1967 } else {
1968 int count;
1969
1970 delete_trailing_chars(result, "\n");
1971 if (IN_SET(esc, ESCAPE_UNSET, ESCAPE_REPLACE)) {
1972 count = util_replace_chars(result, UDEV_ALLOWED_CHARS_INPUT);
1973 if (count > 0)
1974 log_debug("%i character(s) replaced" , count);
1975 }
1976 event->program_result = strdup(result);
1977 if (cur->key.op == OP_NOMATCH)
1978 goto nomatch;
1979 }
1980 break;
1981 }
1982 case TK_M_IMPORT_FILE: {
1983 char import[UTIL_PATH_SIZE];
1984
1985 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), import, sizeof(import), false);
1986 if (import_file_into_properties(dev, import) != 0)
1987 if (cur->key.op != OP_NOMATCH)
1988 goto nomatch;
1989 break;
1990 }
1991 case TK_M_IMPORT_PROG: {
1992 char import[UTIL_PATH_SIZE];
1993
1994 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), import, sizeof(import), false);
1995 log_debug("IMPORT '%s' %s:%u",
1996 import,
1997 rules_str(rules, rule->rule.filename_off),
1998 rule->rule.filename_line);
1999
2000 if (import_program_into_properties(event, timeout_usec, import) != 0)
2001 if (cur->key.op != OP_NOMATCH)
2002 goto nomatch;
2003 break;
2004 }
2005 case TK_M_IMPORT_BUILTIN: {
2006 char command[UTIL_PATH_SIZE];
2007
2008 if (udev_builtin_run_once(cur->key.builtin_cmd)) {
2009 /* check if we ran already */
2010 if (event->builtin_run & (1 << cur->key.builtin_cmd)) {
2011 log_debug("IMPORT builtin skip '%s' %s:%u",
2012 udev_builtin_name(cur->key.builtin_cmd),
2013 rules_str(rules, rule->rule.filename_off),
2014 rule->rule.filename_line);
2015 /* return the result from earlier run */
2016 if (event->builtin_ret & (1 << cur->key.builtin_cmd))
2017 if (cur->key.op != OP_NOMATCH)
2018 goto nomatch;
2019 break;
2020 }
2021 /* mark as ran */
2022 event->builtin_run |= (1 << cur->key.builtin_cmd);
2023 }
2024
2025 udev_event_apply_format(event, rules_str(rules, cur->key.value_off), command, sizeof(command), false);
2026 log_debug("IMPORT builtin '%s' %s:%u",
2027 udev_builtin_name(cur->key.builtin_cmd),
2028 rules_str(rules, rule->rule.filename_off),
2029 rule->rule.filename_line);
2030
2031 r = udev_builtin_run(dev, cur->key.builtin_cmd, command, false);
2032 if (r < 0) {
2033 /* remember failure */
2034 log_debug_errno(r, "IMPORT builtin '%s' fails: %m",
2035 udev_builtin_name(cur->key.builtin_cmd));
2036 event->builtin_ret |= (1 << cur->key.builtin_cmd);
2037 if (cur->key.op != OP_NOMATCH)
2038 goto nomatch;
2039 }
2040 break;
2041 }
2042 case TK_M_IMPORT_DB: {
2043 const char *key;
2044
2045 key = rules_str(rules, cur->key.value_off);
2046 if (event->dev_db_clone &&
2047 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 }