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