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