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