chiark / gitweb /
sysfs: depend on "subsystem" link
[elogind.git] / udev_rules.c
1 /*
2  * Copyright (C) 2003 Greg Kroah-Hartman <greg@kroah.com>
3  * Copyright (C) 2003-2006 Kay Sievers <kay.sievers@vrfy.org>
4  *
5  *      This program is free software; you can redistribute it and/or modify it
6  *      under the terms of the GNU General Public License as published by the
7  *      Free Software Foundation version 2 of the License.
8  *
9  *      This program is distributed in the hope that it will be useful, but
10  *      WITHOUT ANY WARRANTY; without even the implied warranty of
11  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  *      General Public License for more details.
13  *
14  *      You should have received a copy of the GNU General Public License along
15  *      with this program; if not, write to the Free Software Foundation, Inc.,
16  *      51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17  *
18  */
19
20 #include <stddef.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <stdio.h>
24 #include <fcntl.h>
25 #include <ctype.h>
26 #include <unistd.h>
27 #include <errno.h>
28 #include <syslog.h>
29 #include <dirent.h>
30 #include <fnmatch.h>
31 #include <sys/socket.h>
32 #include <sys/un.h>
33 #include <sys/wait.h>
34 #include <sys/stat.h>
35
36 #include "udev.h"
37 #include "udev_rules.h"
38
39 extern char **environ;
40
41 /* extract possible {attr} and move str behind it */
42 static char *get_format_attribute(char **str)
43 {
44         char *pos;
45         char *attr = NULL;
46
47         if (*str[0] == '{') {
48                 pos = strchr(*str, '}');
49                 if (pos == NULL) {
50                         err("missing closing brace for format");
51                         return NULL;
52                 }
53                 pos[0] = '\0';
54                 attr = *str+1;
55                 *str = pos+1;
56                 dbg("attribute='%s', str='%s'", attr, *str);
57         }
58         return attr;
59 }
60
61 /* extract possible format length and move str behind it*/
62 static int get_format_len(char **str)
63 {
64         int num;
65         char *tail;
66
67         if (isdigit(*str[0])) {
68                 num = (int) strtoul(*str, &tail, 10);
69                 if (num > 0) {
70                         *str = tail;
71                         dbg("format length=%i", num);
72                         return num;
73                 } else {
74                         err("format parsing error '%s'", *str);
75                 }
76         }
77         return -1;
78 }
79
80 static int get_key(char **line, char **key, char **value)
81 {
82         char *linepos;
83         char *temp;
84
85         linepos = *line;
86         if (linepos == NULL)
87                 return -1;
88
89         /* skip whitespace */
90         while (isspace(linepos[0]))
91                 linepos++;
92
93         /* get the key */
94         temp = strchr(linepos, '=');
95         if (temp == NULL || temp == linepos)
96                 return -1;
97         temp[0] = '\0';
98         *key = linepos;
99         linepos = &temp[1];
100
101         /* get a quoted value */
102         if (linepos[0] == '"' || linepos[0] == '\'') {
103                 temp = strchr(&linepos[1], linepos[0]);
104                 if (temp != NULL) {
105                         temp[0] = '\0';
106                         *value = &linepos[1];
107                         goto out;
108                 }
109         }
110
111         /* get the value*/
112         temp = strchr(linepos, '\n');
113         if (temp != NULL)
114                 temp[0] = '\0';
115         *value = linepos;
116 out:
117         return 0;
118 }
119
120 static int run_program(const char *command, const char *subsystem,
121                 char *result, size_t ressize, size_t *reslen)
122 {
123         int status;
124         int outpipe[2] = {-1, -1};
125         int errpipe[2] = {-1, -1};
126         pid_t pid;
127         char arg[PATH_SIZE];
128         char program[PATH_SIZE];
129         char *argv[(sizeof(arg) / 2) + 1];
130         int devnull;
131         int i;
132         int retval = 0;
133
134         /* build argv from comand */
135         strlcpy(arg, command, sizeof(arg));
136         i = 0;
137         if (strchr(arg, ' ') != NULL) {
138                 char *pos = arg;
139
140                 while (pos != NULL) {
141                         if (pos[0] == '\'') {
142                                 /* don't separate if in apostrophes */
143                                 pos++;
144                                 argv[i] = strsep(&pos, "\'");
145                                 while (pos != NULL && pos[0] == ' ')
146                                         pos++;
147                         } else {
148                                 argv[i] = strsep(&pos, " ");
149                         }
150                         dbg("arg[%i] '%s'", i, argv[i]);
151                         i++;
152                 }
153                 argv[i] = NULL;
154         } else {
155                 argv[0] = arg;
156                 argv[1] = NULL;
157         }
158         info("'%s'", command);
159
160         /* prepare pipes from child to parent */
161         if (result != NULL || udev_log_priority >= LOG_INFO) {
162                 if (pipe(outpipe) != 0) {
163                         err("pipe failed: %s", strerror(errno));
164                         return -1;
165                 }
166         }
167         if (udev_log_priority >= LOG_INFO) {
168                 if (pipe(errpipe) != 0) {
169                         err("pipe failed: %s", strerror(errno));
170                         return -1;
171                 }
172         }
173
174         /* allow programs in /lib/udev called without the path */
175         if (strchr(argv[0], '/') == NULL) {
176                 strlcpy(program, "/lib/udev/", sizeof(program));
177                 strlcat(program, argv[0], sizeof(program));
178                 argv[0] = program;
179         }
180
181         pid = fork();
182         switch(pid) {
183         case 0:
184                 /* child closes parent ends of pipes */
185                 if (outpipe[READ_END] > 0)
186                         close(outpipe[READ_END]);
187                 if (errpipe[READ_END] > 0)
188                         close(errpipe[READ_END]);
189
190                 /* discard child output or connect to pipe */
191                 devnull = open("/dev/null", O_RDWR);
192                 if (devnull > 0) {
193                         dup2(devnull, STDIN_FILENO);
194                         if (outpipe[WRITE_END] < 0)
195                                 dup2(devnull, STDOUT_FILENO);
196                         if (errpipe[WRITE_END] < 0)
197                                 dup2(devnull, STDERR_FILENO);
198                         close(devnull);
199                 } else
200                         err("open /dev/null failed: %s", strerror(errno));
201                 if (outpipe[WRITE_END] > 0) {
202                         dup2(outpipe[WRITE_END], STDOUT_FILENO);
203                         close(outpipe[WRITE_END]);
204                 }
205                 if (errpipe[WRITE_END] > 0) {
206                         dup2(errpipe[WRITE_END], STDERR_FILENO);
207                         close(errpipe[WRITE_END]);
208                 }
209                 execv(argv[0], argv);
210                 if (errno == ENOENT || errno == ENOTDIR) {
211                         /* may be on a filesytem which is not mounted right now */
212                         info("program '%s' not found", argv[0]);
213                 } else {
214                         /* other problems */
215                         err("exec of program '%s' failed", argv[0]);
216                 }
217                 _exit(1);
218         case -1:
219                 err("fork of '%s' failed: %s", argv[0], strerror(errno));
220                 return -1;
221         default:
222                 /* read from child if requested */
223                 if (outpipe[READ_END] > 0 || errpipe[READ_END] > 0) {
224                         ssize_t count;
225                         size_t respos = 0;
226
227                         /* parent closes child ends of pipes */
228                         if (outpipe[WRITE_END] > 0)
229                                 close(outpipe[WRITE_END]);
230                         if (errpipe[WRITE_END] > 0)
231                                 close(errpipe[WRITE_END]);
232
233                         /* read child output */
234                         while (outpipe[READ_END] > 0 || errpipe[READ_END] > 0) {
235                                 int fdcount;
236                                 fd_set readfds;
237
238                                 FD_ZERO(&readfds);
239                                 if (outpipe[READ_END] > 0)
240                                         FD_SET(outpipe[READ_END], &readfds);
241                                 if (errpipe[READ_END] > 0)
242                                         FD_SET(errpipe[READ_END], &readfds);
243                                 fdcount = select(UDEV_MAX(outpipe[READ_END], errpipe[READ_END])+1, &readfds, NULL, NULL, NULL);
244                                 if (fdcount < 0) {
245                                         if (errno == EINTR)
246                                                 continue;
247                                         retval = -1;
248                                         break;
249                                 }
250
251                                 /* get stdout */
252                                 if (outpipe[READ_END] > 0 && FD_ISSET(outpipe[READ_END], &readfds)) {
253                                         char inbuf[1024];
254                                         char *pos;
255                                         char *line;
256
257                                         count = read(outpipe[READ_END], inbuf, sizeof(inbuf)-1);
258                                         if (count <= 0) {
259                                                 close(outpipe[READ_END]);
260                                                 outpipe[READ_END] = -1;
261                                                 if (count < 0) {
262                                                         err("stdin read failed: %s", strerror(errno));
263                                                         retval = -1;
264                                                 }
265                                                 continue;
266                                         }
267                                         inbuf[count] = '\0';
268
269                                         /* store result for rule processing */
270                                         if (result) {
271                                                 if (respos + count < ressize) {
272                                                         memcpy(&result[respos], inbuf, count);
273                                                         respos += count;
274                                                 } else {
275                                                         err("ressize %ld too short", (long)ressize);
276                                                         retval = -1;
277                                                 }
278                                         }
279                                         pos = inbuf;
280                                         while ((line = strsep(&pos, "\n")))
281                                                 if (pos || line[0] != '\0')
282                                                         info("'%s' (stdout) '%s'", argv[0], line);
283                                 }
284
285                                 /* get stderr */
286                                 if (errpipe[READ_END] > 0 && FD_ISSET(errpipe[READ_END], &readfds)) {
287                                         char errbuf[1024];
288                                         char *pos;
289                                         char *line;
290
291                                         count = read(errpipe[READ_END], errbuf, sizeof(errbuf)-1);
292                                         if (count <= 0) {
293                                                 close(errpipe[READ_END]);
294                                                 errpipe[READ_END] = -1;
295                                                 if (count < 0)
296                                                         err("stderr read failed: %s", strerror(errno));
297                                                 continue;
298                                         }
299                                         errbuf[count] = '\0';
300                                         pos = errbuf;
301                                         while ((line = strsep(&pos, "\n")))
302                                                 if (pos || line[0] != '\0')
303                                                         info("'%s' (stderr) '%s'", argv[0], line);
304                                 }
305                         }
306                         if (outpipe[READ_END] > 0)
307                                 close(outpipe[READ_END]);
308                         if (errpipe[READ_END] > 0)
309                                 close(errpipe[READ_END]);
310
311                         /* return the childs stdout string */
312                         if (result) {
313                                 result[respos] = '\0';
314                                 dbg("result='%s'", result);
315                                 if (reslen)
316                                         *reslen = respos;
317                         }
318                 }
319                 waitpid(pid, &status, 0);
320                 if (WIFEXITED(status)) {
321                         info("'%s' returned with status %i", argv[0], WEXITSTATUS(status));
322                         if (WEXITSTATUS(status) != 0)
323                                 retval = -1;
324                 } else {
325                         err("'%s' abnormal exit", argv[0]);
326                         retval = -1;
327                 }
328         }
329
330         return retval;
331 }
332
333 static int import_keys_into_env(struct udevice *udev, const char *buf, size_t bufsize)
334 {
335         char line[LINE_SIZE];
336         const char *bufline;
337         char *linepos;
338         char *variable;
339         char *value;
340         size_t cur;
341         size_t count;
342         int lineno;
343
344         /* loop through the whole buffer */
345         lineno = 0;
346         cur = 0;
347         while (cur < bufsize) {
348                 count = buf_get_line(buf, bufsize, cur);
349                 bufline = &buf[cur];
350                 cur += count+1;
351                 lineno++;
352
353                 /* eat the whitespace */
354                 while ((count > 0) && isspace(bufline[0])) {
355                         bufline++;
356                         count--;
357                 }
358                 if (count == 0)
359                         continue;
360
361                 /* see if this is a comment */
362                 if (bufline[0] == COMMENT_CHARACTER)
363                         continue;
364
365                 if (count >= sizeof(line)) {
366                         err("line too long, conf line skipped %s, line %d", udev_config_filename, lineno);
367                         continue;
368                 }
369
370                 memcpy(line, bufline, count);
371                 line[count] = '\0';
372
373                 linepos = line;
374                 if (get_key(&linepos, &variable, &value) == 0) {
375                         dbg("import '%s=%s'", variable, value);
376
377                         /* handle device, renamed by external tool, returning new path */
378                         if (strcmp(variable, "DEVPATH") == 0) {
379                                 info("updating devpath from '%s' to '%s'", udev->dev->devpath, value);
380                                 sysfs_device_set_values(udev->dev, value, NULL, NULL);
381                         } else
382                                 name_list_key_add(&udev->env_list, variable, value);
383                         setenv(variable, value, 1);
384                 }
385         }
386
387         return 0;
388 }
389
390 static int import_file_into_env(struct udevice *udev, const char *filename)
391 {
392         char *buf;
393         size_t bufsize;
394
395         if (file_map(filename, &buf, &bufsize) != 0) {
396                 err("can't open '%s': %s", filename, strerror(errno));
397                 return -1;
398         }
399         import_keys_into_env(udev, buf, bufsize);
400         file_unmap(buf, bufsize);
401
402         return 0;
403 }
404
405 static int import_program_into_env(struct udevice *udev, const char *program)
406 {
407         char result[2048];
408         size_t reslen;
409
410         if (run_program(program, udev->dev->subsystem, result, sizeof(result), &reslen) != 0)
411                 return -1;
412         return import_keys_into_env(udev, result, reslen);
413 }
414
415 static int import_parent_into_env(struct udevice *udev, const char *filter)
416 {
417         struct sysfs_device *dev_parent;
418         int rc = -1;
419
420         dev_parent = sysfs_device_get_parent(udev->dev);
421         if (dev_parent != NULL) {
422                 struct udevice *udev_parent;
423                 struct name_entry *name_loop;
424
425                 dbg("found parent '%s', get the node name", dev_parent->devpath);
426                 udev_parent = udev_device_init(NULL);
427                 if (udev_parent == NULL)
428                         return -1;
429                 /* import the udev_db of the parent */
430                 if (udev_db_get_device(udev_parent, dev_parent->devpath) == 0) {
431                         dbg("import stored parent env '%s'", udev_parent->name);
432                         list_for_each_entry(name_loop, &udev_parent->env_list, node) {
433                                 char name[NAME_SIZE];
434                                 char *pos;
435
436                                 strlcpy(name, name_loop->name, sizeof(name));
437                                 pos = strchr(name, '=');
438                                 if (pos) {
439                                         pos[0] = '\0';
440                                         pos++;
441                                         if (fnmatch(filter, name, 0) == 0) {
442                                                 dbg("import key '%s'", name_loop->name);
443                                                 name_list_add(&udev->env_list, name_loop->name, 0);
444                                                 setenv(name, pos, 1);
445                                         } else
446                                                 dbg("skip key '%s'", name_loop->name);
447                                 }
448                         }
449                         rc = 0;
450                 } else
451                         dbg("parent not found in database");
452                 udev_device_cleanup(udev_parent);
453         }
454
455         return rc;
456 }
457
458 static int pass_env_to_socket(const char *sockname, const char *devpath, const char *action)
459 {
460         int sock;
461         struct sockaddr_un saddr;
462         socklen_t addrlen;
463         char buf[2048];
464         size_t bufpos = 0;
465         int i;
466         ssize_t count;
467         int retval = 0;
468
469         dbg("pass environment to socket '%s'", sockname);
470         sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
471         memset(&saddr, 0x00, sizeof(struct sockaddr_un));
472         saddr.sun_family = AF_LOCAL;
473         /* abstract namespace only */
474         strcpy(&saddr.sun_path[1], sockname);
475         addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
476
477         bufpos = snprintf(buf, sizeof(buf)-1, "%s@%s", action, devpath);
478         bufpos++;
479         for (i = 0; environ[i] != NULL && bufpos < (sizeof(buf)-1); i++) {
480                 bufpos += strlcpy(&buf[bufpos], environ[i], sizeof(buf) - bufpos-1);
481                 bufpos++;
482         }
483         if (bufpos > sizeof(buf))
484                 bufpos = sizeof(buf);
485
486         count = sendto(sock, &buf, bufpos, 0, (struct sockaddr *)&saddr, addrlen);
487         if (count < 0)
488                 retval = -1;
489         info("passed %zi bytes to socket '%s', ", count, sockname);
490
491         close(sock);
492         return retval;
493 }
494
495 int udev_rules_run(struct udevice *udev)
496 {
497         struct name_entry *name_loop;
498         int retval = 0;
499
500         dbg("executing run list");
501         list_for_each_entry(name_loop, &udev->run_list, node) {
502                 if (strncmp(name_loop->name, "socket:", strlen("socket:")) == 0) {
503                         pass_env_to_socket(&name_loop->name[strlen("socket:")], udev->dev->devpath, udev->action);
504                 } else {
505                         char program[PATH_SIZE];
506
507                         strlcpy(program, name_loop->name, sizeof(program));
508                         udev_rules_apply_format(udev, program, sizeof(program));
509                         if (run_program(program, udev->dev->subsystem, NULL, 0, NULL) != 0)
510                                 if (!name_loop->ignore_error)
511                                         retval = -1;
512                 }
513         }
514
515         return retval;
516 }
517
518 #define WAIT_LOOP_PER_SECOND            50
519 static int wait_for_sysfs(struct udevice *udev, const char *file, int timeout)
520 {
521         char devicepath[PATH_SIZE];
522         char filepath[PATH_SIZE];
523         struct stat stats;
524         int loop = timeout * WAIT_LOOP_PER_SECOND;
525
526         strlcpy(devicepath, sysfs_path, sizeof(devicepath));
527         strlcat(devicepath, udev->dev->devpath, sizeof(devicepath));
528         strlcpy(filepath, devicepath, sizeof(filepath));
529         strlcat(filepath, "/", sizeof(filepath));
530         strlcat(filepath, file, sizeof(filepath));
531
532         dbg("will wait %i sec for '%s'", timeout, filepath);
533         while (--loop) {
534                 /* lookup file */
535                 if (stat(filepath, &stats) == 0) {
536                         info("file '%s' appeared after %i loops", filepath, (timeout * WAIT_LOOP_PER_SECOND) - loop-1);
537                         return 0;
538                 }
539                 /* make sure, the device did not disappear in the meantime */
540                 if (stat(devicepath, &stats) != 0) {
541                         info("device disappeared while waiting for '%s'", filepath);
542                         return -2;
543                 }
544                 info("wait for '%s' for %i mseconds", filepath, 1000 / WAIT_LOOP_PER_SECOND);
545                 usleep(1000 * 1000 / WAIT_LOOP_PER_SECOND);
546         }
547         info("waiting for '%s' failed", filepath);
548         return -1;
549 }
550
551 /* handle "[$SUBSYSTEM/$KERNEL]<attribute>" lookup */
552 static int attr_get_by_subsys_id(const char *attrstr, char *devpath, size_t len, char **attr)
553 {
554         char subsys[NAME_SIZE];
555         char *attrib;
556         char *id;
557         int found = 0;
558
559         if (attrstr[0] != '[')
560                 goto out;
561
562         strlcpy(subsys, &attrstr[1], sizeof(subsys));
563
564         attrib = strchr(subsys, ']');
565         if (attrib == NULL)
566                 goto out;
567         attrib[0] = '\0';
568         attrib = &attrib[1];
569
570         id = strchr(subsys, '/');
571         if (id == NULL)
572                 goto out;
573         id[0] = '\0';
574         id = &id[1];
575
576         if (sysfs_lookup_devpath_by_subsys_id(devpath, len, subsys, id)) {
577                 if (attr != NULL) {
578                         if (attrib[0] != '\0')
579                                 *attr = attrib;
580                         else
581                                 *attr = NULL;
582                 }
583                 found = 1;
584         }
585 out:
586         return found;
587 }
588
589 void udev_rules_apply_format(struct udevice *udev, char *string, size_t maxsize)
590 {
591         char temp[PATH_SIZE];
592         char temp2[PATH_SIZE];
593         char *head, *tail, *pos, *cpos, *attr, *rest;
594         int len;
595         int i;
596         int count;
597         enum subst_type {
598                 SUBST_UNKNOWN,
599                 SUBST_DEVPATH,
600                 SUBST_KERNEL,
601                 SUBST_KERNEL_NUMBER,
602                 SUBST_ID,
603                 SUBST_DRIVER,
604                 SUBST_MAJOR,
605                 SUBST_MINOR,
606                 SUBST_RESULT,
607                 SUBST_ATTR,
608                 SUBST_PARENT,
609                 SUBST_TEMP_NODE,
610                 SUBST_NAME,
611                 SUBST_ROOT,
612                 SUBST_SYS,
613                 SUBST_ENV,
614         };
615         static const struct subst_map {
616                 char *name;
617                 char fmt;
618                 enum subst_type type;
619         } map[] = {
620                 { .name = "devpath",    .fmt = 'p',     .type = SUBST_DEVPATH },
621                 { .name = "number",     .fmt = 'n',     .type = SUBST_KERNEL_NUMBER },
622                 { .name = "kernel",     .fmt = 'k',     .type = SUBST_KERNEL },
623                 { .name = "id",         .fmt = 'b',     .type = SUBST_ID },
624                 { .name = "driver",     .fmt = 'd',     .type = SUBST_DRIVER },
625                 { .name = "major",      .fmt = 'M',     .type = SUBST_MAJOR },
626                 { .name = "minor",      .fmt = 'm',     .type = SUBST_MINOR },
627                 { .name = "result",     .fmt = 'c',     .type = SUBST_RESULT },
628                 { .name = "attr",       .fmt = 's',     .type = SUBST_ATTR },
629                 { .name = "sysfs",      .fmt = 's',     .type = SUBST_ATTR },
630                 { .name = "parent",     .fmt = 'P',     .type = SUBST_PARENT },
631                 { .name = "tempnode",   .fmt = 'N',     .type = SUBST_TEMP_NODE },
632                 { .name = "name",       .fmt = 'D',     .type = SUBST_NAME },
633                 { .name = "root",       .fmt = 'r',     .type = SUBST_ROOT },
634                 { .name = "sys",        .fmt = 'S',     .type = SUBST_SYS },
635                 { .name = "env",        .fmt = 'E',     .type = SUBST_ENV },
636                 { NULL, '\0', 0 }
637         };
638         enum subst_type type;
639         const struct subst_map *subst;
640
641         head = string;
642         while (1) {
643                 len = -1;
644                 while (head[0] != '\0') {
645                         if (head[0] == '$') {
646                                 /* substitute named variable */
647                                 if (head[1] == '\0')
648                                         break;
649                                 if (head[1] == '$') {
650                                         strlcpy(temp, head+2, sizeof(temp));
651                                         strlcpy(head+1, temp, maxsize);
652                                         head++;
653                                         continue;
654                                 }
655                                 head[0] = '\0';
656                                 for (subst = map; subst->name; subst++) {
657                                         if (strncasecmp(&head[1], subst->name, strlen(subst->name)) == 0) {
658                                                 type = subst->type;
659                                                 tail = head + strlen(subst->name)+1;
660                                                 dbg("will substitute format name '%s'", subst->name);
661                                                 goto found;
662                                         }
663                                 }
664                                 head[0] = '$';
665                                 err("unknown format variable '%s'", head);
666                         } else if (head[0] == '%') {
667                                 /* substitute format char */
668                                 if (head[1] == '\0')
669                                         break;
670                                 if (head[1] == '%') {
671                                         strlcpy(temp, head+2, sizeof(temp));
672                                         strlcpy(head+1, temp, maxsize);
673                                         head++;
674                                         continue;
675                                 }
676                                 head[0] = '\0';
677                                 tail = head+1;
678                                 len = get_format_len(&tail);
679                                 for (subst = map; subst->name; subst++) {
680                                         if (tail[0] == subst->fmt) {
681                                                 type = subst->type;
682                                                 tail++;
683                                                 dbg("will substitute format char '%c'", subst->fmt);
684                                                 goto found;
685                                         }
686                                 }
687                                 head[0] = '%';
688                                 err("unknown format char '%c'", tail[0]);
689                         }
690                         head++;
691                 }
692                 break;
693 found:
694                 attr = get_format_attribute(&tail);
695                 strlcpy(temp, tail, sizeof(temp));
696                 dbg("format=%i, string='%s', tail='%s'", type ,string, tail);
697
698                 switch (type) {
699                 case SUBST_DEVPATH:
700                         strlcat(string, udev->dev->devpath, maxsize);
701                         dbg("substitute devpath '%s'", udev->dev->devpath);
702                         break;
703                 case SUBST_KERNEL:
704                         strlcat(string, udev->dev->kernel, maxsize);
705                         dbg("substitute kernel name '%s'", udev->dev->kernel);
706                         break;
707                 case SUBST_KERNEL_NUMBER:
708                         strlcat(string, udev->dev->kernel_number, maxsize);
709                         dbg("substitute kernel number '%s'", udev->dev->kernel_number);
710                         break;
711                 case SUBST_ID:
712                         if (udev->dev_parent != NULL) {
713                                 strlcat(string, udev->dev_parent->kernel, maxsize);
714                                 dbg("substitute id '%s'", udev->dev_parent->kernel);
715                         }
716                         break;
717                 case SUBST_DRIVER:
718                         if (udev->dev_parent != NULL) {
719                                 strlcat(string, udev->dev_parent->driver, maxsize);
720                                 dbg("substitute driver '%s'", udev->dev_parent->driver);
721                         }
722                         break;
723                 case SUBST_MAJOR:
724                         sprintf(temp2, "%d", major(udev->devt));
725                         strlcat(string, temp2, maxsize);
726                         dbg("substitute major number '%s'", temp2);
727                         break;
728                 case SUBST_MINOR:
729                         sprintf(temp2, "%d", minor(udev->devt));
730                         strlcat(string, temp2, maxsize);
731                         dbg("substitute minor number '%s'", temp2);
732                         break;
733                 case SUBST_RESULT:
734                         if (udev->program_result[0] == '\0')
735                                 break;
736                         /* get part part of the result string */
737                         i = 0;
738                         if (attr != NULL)
739                                 i = strtoul(attr, &rest, 10);
740                         if (i > 0) {
741                                 dbg("request part #%d of result string", i);
742                                 cpos = udev->program_result;
743                                 while (--i) {
744                                         while (cpos[0] != '\0' && !isspace(cpos[0]))
745                                                 cpos++;
746                                         while (isspace(cpos[0]))
747                                                 cpos++;
748                                 }
749                                 if (i > 0) {
750                                         err("requested part of result string not found");
751                                         break;
752                                 }
753                                 strlcpy(temp2, cpos, sizeof(temp2));
754                                 /* %{2+}c copies the whole string from the second part on */
755                                 if (rest[0] != '+') {
756                                         cpos = strchr(temp2, ' ');
757                                         if (cpos)
758                                                 cpos[0] = '\0';
759                                 }
760                                 strlcat(string, temp2, maxsize);
761                                 dbg("substitute part of result string '%s'", temp2);
762                         } else {
763                                 strlcat(string, udev->program_result, maxsize);
764                                 dbg("substitute result string '%s'", udev->program_result);
765                         }
766                         break;
767                 case SUBST_ATTR:
768                         if (attr == NULL)
769                                 err("missing file parameter for attr");
770                         else {
771                                 char devpath[PATH_SIZE];
772                                 char *attrib;
773                                 const char *value = NULL;
774                                 size_t size;
775
776                                 if (attr_get_by_subsys_id(attr, devpath, sizeof(devpath), &attrib)) {
777                                         if (attrib != NULL)
778                                                 value = sysfs_attr_get_value(devpath, attrib);
779                                         else
780                                                 break;
781                                 }
782
783                                 /* try the current device, other matches may have selected */
784                                 if (value == NULL && udev->dev_parent != NULL && udev->dev_parent != udev->dev)
785                                         value = sysfs_attr_get_value(udev->dev_parent->devpath, attr);
786
787                                 /* look at all devices along the chain of parents */
788                                 if (value == NULL) {
789                                         struct sysfs_device *dev_parent = udev->dev;
790
791                                         do {
792                                                 dbg("looking at '%s'", dev_parent->devpath);
793                                                 value = sysfs_attr_get_value(dev_parent->devpath, attr);
794                                                 if (value != NULL) {
795                                                         strlcpy(temp2, value, sizeof(temp2));
796                                                         break;
797                                                 }
798                                                 dev_parent = sysfs_device_get_parent(dev_parent);
799                                         } while (dev_parent != NULL);
800                                 }
801
802                                 if (value == NULL)
803                                         break;
804
805                                 /* strip trailing whitespace, and replace unwanted characters */
806                                 size = strlcpy(temp2, value, sizeof(temp2));
807                                 if (size >= sizeof(temp2))
808                                         size = sizeof(temp2)-1;
809                                 while (size > 0 && isspace(temp2[size-1]))
810                                         temp2[--size] = '\0';
811                                 count = replace_chars(temp2, ALLOWED_CHARS_INPUT);
812                                 if (count > 0)
813                                         info("%i character(s) replaced" , count);
814                                 strlcat(string, temp2, maxsize);
815                                 dbg("substitute sysfs value '%s'", temp2);
816                         }
817                         break;
818                 case SUBST_PARENT:
819                         {
820                                 struct sysfs_device *dev_parent;
821
822                                 dev_parent = sysfs_device_get_parent(udev->dev);
823                                 if (dev_parent != NULL) {
824                                         struct udevice *udev_parent;
825
826                                         dbg("found parent '%s', get the node name", dev_parent->devpath);
827                                         udev_parent = udev_device_init(NULL);
828                                         if (udev_parent != NULL) {
829                                                 /* lookup the name in the udev_db with the DEVPATH of the parent */
830                                                 if (udev_db_get_device(udev_parent, dev_parent->devpath) == 0) {
831                                                         strlcat(string, udev_parent->name, maxsize);
832                                                         dbg("substitute parent node name'%s'", udev_parent->name);
833                                                 } else
834                                                         dbg("parent not found in database");
835                                                 udev_device_cleanup(udev_parent);
836                                         }
837                                 }
838                         }
839                         break;
840                 case SUBST_TEMP_NODE:
841                         if (udev->tmp_node[0] == '\0' && major(udev->devt) > 0) {
842                                 dbg("create temporary device node for callout");
843                                 snprintf(udev->tmp_node, sizeof(udev->tmp_node), "%s/.tmp-%u-%u",
844                                          udev_root, major(udev->devt), minor(udev->devt));
845                                 udev->tmp_node[sizeof(udev->tmp_node)-1] = '\0';
846                                 udev_node_mknod(udev, udev->tmp_node, udev->devt, 0600, 0, 0);
847                         }
848                         strlcat(string, udev->tmp_node, maxsize);
849                         dbg("substitute temporary device node name '%s'", udev->tmp_node);
850                         break;
851                 case SUBST_NAME:
852                         strlcat(string, udev->name, maxsize);
853                         dbg("substitute udev->name '%s'", udev->name);
854                         break;
855                 case SUBST_ROOT:
856                         strlcat(string, udev_root, maxsize);
857                         dbg("substitute udev_root '%s'", udev_root);
858                         break;
859                 case SUBST_SYS:
860                         strlcat(string, sysfs_path, maxsize);
861                         dbg("substitute sysfs_path '%s'", sysfs_path);
862                         break;
863                 case SUBST_ENV:
864                         if (attr == NULL) {
865                                 dbg("missing attribute");
866                                 break;
867                         }
868                         pos = getenv(attr);
869                         if (pos == NULL) {
870                                 dbg("env '%s' not available", attr);
871                                 break;
872                         }
873                         dbg("substitute env '%s=%s'", attr, pos);
874                         strlcat(string, pos, maxsize);
875                         break;
876                 default:
877                         err("unknown substitution type=%i", type);
878                         break;
879                 }
880                 /* possibly truncate to format-char specified length */
881                 if (len >= 0 && len < (int)strlen(head)) {
882                         head[len] = '\0';
883                         dbg("truncate to %i chars, subtitution string becomes '%s'", len, head);
884                 }
885                 strlcat(string, temp, maxsize);
886         }
887 }
888
889 static char *key_val(struct udev_rule *rule, struct key *key)
890 {
891         return rule->buf + key->val_off;
892 }
893
894 static char *key_pair_name(struct udev_rule *rule, struct key_pair *pair)
895 {
896         return rule->buf + pair->key_name_off;
897 }
898
899 static int match_key(const char *key_name, struct udev_rule *rule, struct key *key, const char *val)
900 {
901         char value[PATH_SIZE];
902         char *key_value;
903         char *pos;
904         int match = 0;
905
906         if (key->operation != KEY_OP_MATCH &&
907             key->operation != KEY_OP_NOMATCH)
908                 return 0;
909
910         /* look for a matching string, parts are separated by '|' */
911         strlcpy(value, rule->buf + key->val_off, sizeof(value));
912         key_value = value;
913         dbg("key %s value='%s'", key_name, key_value);
914         while (key_value) {
915                 pos = strchr(key_value, '|');
916                 if (pos) {
917                         pos[0] = '\0';
918                         pos++;
919                 }
920
921                 dbg("match %s '%s' <-> '%s'", key_name, key_value, val);
922                 match = (fnmatch(key_value, val, 0) == 0);
923                 if (match)
924                         break;
925
926                 key_value = pos;
927         }
928
929         if (match && (key->operation == KEY_OP_MATCH)) {
930                 dbg("%s is true (matching value)", key_name);
931                 return 0;
932         }
933         if (!match && (key->operation == KEY_OP_NOMATCH)) {
934                 dbg("%s is true (non-matching value)", key_name);
935                 return 0;
936         }
937         return -1;
938 }
939
940 /* match a single rule against a given device and possibly its parent devices */
941 static int match_rule(struct udevice *udev, struct udev_rule *rule)
942 {
943         int i;
944
945         if (match_key("ACTION", rule, &rule->action, udev->action))
946                 goto nomatch;
947
948         if (match_key("KERNEL", rule, &rule->kernel, udev->dev->kernel))
949                 goto nomatch;
950
951         if (match_key("SUBSYSTEM", rule, &rule->subsystem, udev->dev->subsystem))
952                 goto nomatch;
953
954         if (match_key("DEVPATH", rule, &rule->devpath, udev->dev->devpath))
955                 goto nomatch;
956
957         if (match_key("DRIVER", rule, &rule->driver, udev->dev->driver))
958                 goto nomatch;
959
960         /* match NAME against a value assigned by an earlier rule */
961         if (match_key("NAME", rule, &rule->name, udev->name))
962                 goto nomatch;
963
964         /* match against current list of symlinks */
965         if (rule->symlink_match.operation == KEY_OP_MATCH ||
966             rule->symlink_match.operation == KEY_OP_NOMATCH) {
967                 struct name_entry *name_loop;
968                 int match = 0;
969
970                 list_for_each_entry(name_loop, &udev->symlink_list, node) {
971                         if (match_key("SYMLINK", rule, &rule->symlink_match, name_loop->name) == 0) {
972                                 match = 1;
973                                 break;
974                         }
975                 }
976                 if (!match)
977                         goto nomatch;
978         }
979
980         for (i = 0; i < rule->env.count; i++) {
981                 struct key_pair *pair = &rule->env.keys[i];
982
983                 /* we only check for matches, assignments will be handled later */
984                 if (pair->key.operation == KEY_OP_MATCH ||
985                     pair->key.operation == KEY_OP_NOMATCH) {
986                         const char *key_name = key_pair_name(rule, pair);
987                         const char *value = getenv(key_name);
988
989                         if (!value) {
990                                 dbg("ENV{'%s'} is not set, treat as empty", key_name);
991                                 value = "";
992                         }
993                         if (match_key("ENV", rule, &pair->key, value))
994                                 goto nomatch;
995                 }
996         }
997
998         if (rule->test.operation == KEY_OP_MATCH ||
999             rule->test.operation == KEY_OP_NOMATCH) {
1000                 char filename[PATH_SIZE];
1001                 char devpath[PATH_SIZE];
1002                 char *attr;
1003                 struct stat statbuf;
1004                 int match;
1005
1006                 strlcpy(filename, key_val(rule, &rule->test), sizeof(filename));
1007                 udev_rules_apply_format(udev, filename, sizeof(filename));
1008
1009                 if (attr_get_by_subsys_id(filename, devpath, sizeof(devpath), &attr)) {
1010                         strlcpy(filename, sysfs_path, sizeof(filename));
1011                         strlcat(filename, devpath, sizeof(filename));
1012                         if (attr != NULL) {
1013                                 strlcat(filename, "/", sizeof(filename));
1014                                 strlcat(filename, attr, sizeof(filename));
1015                         }
1016                 } else if (filename[0] != '/') {
1017                         char tmp[PATH_SIZE];
1018
1019                         strlcpy(tmp, sysfs_path, sizeof(tmp));
1020                         strlcat(tmp, udev->dev->devpath, sizeof(tmp));
1021                         strlcat(tmp, "/", sizeof(tmp));
1022                         strlcat(tmp, filename, sizeof(tmp));
1023                         strlcpy(filename, tmp, sizeof(filename));
1024                 }
1025
1026                 match = (stat(filename, &statbuf) == 0);
1027                 info("'%s' %s", filename, match ? "exists" : "does not exist");
1028                 if (match && rule->test_mode_mask > 0) {
1029                         match = ((statbuf.st_mode & rule->test_mode_mask) > 0);
1030                         info("'%s' has mode=%#o and %s %#o", filename, statbuf.st_mode,
1031                              match ? "matches" : "does not match",
1032                              rule->test_mode_mask);
1033                 }
1034                 if (match && rule->test.operation == KEY_OP_NOMATCH)
1035                         goto nomatch;
1036                 if (!match && rule->test.operation == KEY_OP_MATCH)
1037                         goto nomatch;
1038                 dbg("TEST key is true");
1039         }
1040
1041         if (rule->wait_for_sysfs.operation != KEY_OP_UNSET) {
1042                 int found;
1043
1044                 found = (wait_for_sysfs(udev, key_val(rule, &rule->wait_for_sysfs), 10) == 0);
1045                 if (!found && (rule->wait_for_sysfs.operation != KEY_OP_NOMATCH))
1046                         goto nomatch;
1047         }
1048
1049         /* check for matching sysfs attribute pairs */
1050         for (i = 0; i < rule->attr.count; i++) {
1051                 struct key_pair *pair = &rule->attr.keys[i];
1052
1053                 if (pair->key.operation == KEY_OP_MATCH ||
1054                     pair->key.operation == KEY_OP_NOMATCH) {
1055                         const char *key_name = key_pair_name(rule, pair);
1056                         const char *key_value = key_val(rule, &pair->key);
1057                         char devpath[PATH_SIZE];
1058                         char *attrib;
1059                         const char *value = NULL;
1060                         char val[VALUE_SIZE];
1061                         size_t len;
1062
1063                         if (attr_get_by_subsys_id(key_name, devpath, sizeof(devpath), &attrib)) {
1064                                 if (attrib != NULL)
1065                                         value = sysfs_attr_get_value(devpath, attrib);
1066                                 else
1067                                         goto nomatch;
1068                         }
1069                         if (value == NULL)
1070                                 value = sysfs_attr_get_value(udev->dev->devpath, key_name);
1071                         if (value == NULL)
1072                                 goto nomatch;
1073                         strlcpy(val, value, sizeof(val));
1074
1075                         /* strip trailing whitespace of value, if not asked to match for it */
1076                         len = strlen(key_value);
1077                         if (len > 0 && !isspace(key_value[len-1])) {
1078                                 len = strlen(val);
1079                                 while (len > 0 && isspace(val[len-1]))
1080                                         val[--len] = '\0';
1081                                 dbg("removed %zi trailing whitespace chars from '%s'", strlen(val)-len, val);
1082                         }
1083
1084                         if (match_key("ATTR", rule, &pair->key, val))
1085                                 goto nomatch;
1086                 }
1087         }
1088
1089         /* walk up the chain of parent devices and find a match */
1090         udev->dev_parent = udev->dev;
1091         while (1) {
1092                 /* check for matching kernel device name */
1093                 if (match_key("KERNELS", rule, &rule->kernels, udev->dev_parent->kernel))
1094                         goto try_parent;
1095
1096                 /* check for matching subsystem value */
1097                 if (match_key("SUBSYSTEMS", rule, &rule->subsystems, udev->dev_parent->subsystem))
1098                         goto try_parent;
1099
1100                 /* check for matching driver */
1101                 if (match_key("DRIVERS", rule, &rule->drivers, udev->dev_parent->driver))
1102                         goto try_parent;
1103
1104                 /* check for matching sysfs attribute pairs */
1105                 for (i = 0; i < rule->attrs.count; i++) {
1106                         struct key_pair *pair = &rule->attrs.keys[i];
1107
1108                         if (pair->key.operation == KEY_OP_MATCH ||
1109                             pair->key.operation == KEY_OP_NOMATCH) {
1110                                 const char *key_name = key_pair_name(rule, pair);
1111                                 const char *key_value = key_val(rule, &pair->key);
1112                                 const char *value;
1113                                 char val[VALUE_SIZE];
1114                                 size_t len;
1115
1116                                 value = sysfs_attr_get_value(udev->dev_parent->devpath, key_name);
1117                                 if (value == NULL)
1118                                         value = sysfs_attr_get_value(udev->dev->devpath, key_name);
1119                                 if (value == NULL)
1120                                         goto try_parent;
1121                                 strlcpy(val, value, sizeof(val));
1122
1123                                 /* strip trailing whitespace of value, if not asked to match for it */
1124                                 len = strlen(key_value);
1125                                 if (len > 0 && !isspace(key_value[len-1])) {
1126                                         len = strlen(val);
1127                                         while (len > 0 && isspace(val[len-1]))
1128                                                 val[--len] = '\0';
1129                                         dbg("removed %zi trailing whitespace chars from '%s'", strlen(val)-len, val);
1130                                 }
1131
1132                                 if (match_key("ATTRS", rule, &pair->key, val))
1133                                         goto try_parent;
1134                         }
1135                 }
1136
1137                 /* found matching device  */
1138                 break;
1139 try_parent:
1140                 /* move to parent device */
1141                 dbg("try parent sysfs device");
1142                 udev->dev_parent = sysfs_device_get_parent(udev->dev_parent);
1143                 if (udev->dev_parent == NULL)
1144                         goto nomatch;
1145                 dbg("looking at dev_parent->devpath='%s'", udev->dev_parent->devpath);
1146                 dbg("looking at dev_parent->kernel='%s'", udev->dev_parent->kernel);
1147         }
1148
1149         /* execute external program */
1150         if (rule->program.operation != KEY_OP_UNSET) {
1151                 char program[PATH_SIZE];
1152                 char result[PATH_SIZE];
1153
1154                 strlcpy(program, key_val(rule, &rule->program), sizeof(program));
1155                 udev_rules_apply_format(udev, program, sizeof(program));
1156                 if (run_program(program, udev->dev->subsystem, result, sizeof(result), NULL) != 0) {
1157                         dbg("PROGRAM is false");
1158                         udev->program_result[0] = '\0';
1159                         if (rule->program.operation != KEY_OP_NOMATCH)
1160                                 goto nomatch;
1161                 } else {
1162                         int count;
1163
1164                         dbg("PROGRAM matches");
1165                         remove_trailing_chars(result, '\n');
1166                         if (rule->string_escape == ESCAPE_UNSET ||
1167                             rule->string_escape == ESCAPE_REPLACE) {
1168                                 count = replace_chars(result, ALLOWED_CHARS_INPUT);
1169                                 if (count > 0)
1170                                         info("%i character(s) replaced" , count);
1171                         }
1172                         dbg("result is '%s'", result);
1173                         strlcpy(udev->program_result, result, sizeof(udev->program_result));
1174                         dbg("PROGRAM returned successful");
1175                         if (rule->program.operation == KEY_OP_NOMATCH)
1176                                 goto nomatch;
1177                 }
1178                 dbg("PROGRAM key is true");
1179         }
1180
1181         /* check for matching result of external program */
1182         if (match_key("RESULT", rule, &rule->result, udev->program_result))
1183                 goto nomatch;
1184
1185         /* import variables returned from program or or file into environment */
1186         if (rule->import.operation != KEY_OP_UNSET) {
1187                 char import[PATH_SIZE];
1188                 int rc = -1;
1189
1190                 strlcpy(import, key_val(rule, &rule->import), sizeof(import));
1191                 udev_rules_apply_format(udev, import, sizeof(import));
1192                 dbg("check for IMPORT import='%s'", import);
1193                 if (rule->import_type == IMPORT_PROGRAM) {
1194                         rc = import_program_into_env(udev, import);
1195                 } else if (rule->import_type == IMPORT_FILE) {
1196                         dbg("import file import='%s'", import);
1197                         rc = import_file_into_env(udev, import);
1198                 } else if (rule->import_type == IMPORT_PARENT) {
1199                         dbg("import parent import='%s'", import);
1200                         rc = import_parent_into_env(udev, import);
1201                 }
1202                 if (rc != 0) {
1203                         dbg("IMPORT failed");
1204                         if (rule->import.operation != KEY_OP_NOMATCH)
1205                                 goto nomatch;
1206                 } else
1207                         dbg("IMPORT '%s' imported", key_val(rule, &rule->import));
1208                 dbg("IMPORT key is true");
1209         }
1210
1211         /* rule matches, if we have ENV assignments export it */
1212         for (i = 0; i < rule->env.count; i++) {
1213                 struct key_pair *pair = &rule->env.keys[i];
1214
1215                 if (pair->key.operation == KEY_OP_ASSIGN) {
1216                         char temp_value[NAME_SIZE];
1217                         const char *key_name = key_pair_name(rule, pair);
1218                         const char *value = key_val(rule, &pair->key);
1219
1220                         /* make sure we don't write to the same string we possibly read from */
1221                         strlcpy(temp_value, value, sizeof(temp_value));
1222                         udev_rules_apply_format(udev, temp_value, NAME_SIZE);
1223
1224                         if (temp_value[0] == '\0') {
1225                                 name_list_key_remove(&udev->env_list, key_name);
1226                                 unsetenv(key_name);
1227                                 info("unset ENV '%s'", key_name);
1228                         } else {
1229                                 struct name_entry *entry;
1230
1231                                 entry = name_list_key_add(&udev->env_list, key_name, temp_value);
1232                                 if (entry == NULL)
1233                                         break;
1234                                 putenv(entry->name);
1235                                 info("set ENV '%s'", entry->name);
1236                         }
1237                 }
1238         }
1239
1240         /* if we have ATTR assignments, write value to sysfs file */
1241         for (i = 0; i < rule->attr.count; i++) {
1242                 struct key_pair *pair = &rule->attr.keys[i];
1243
1244                 if (pair->key.operation == KEY_OP_ASSIGN) {
1245                         const char *key_name = key_pair_name(rule, pair);
1246                         char devpath[PATH_SIZE];
1247                         char *pos;
1248                         char *attrib;
1249                         char attr[PATH_SIZE] = "";
1250                         char value[NAME_SIZE];
1251                         FILE *f;
1252
1253                         if (attr_get_by_subsys_id(key_name, devpath, sizeof(devpath), &attrib)) {
1254                                 if (attrib != NULL) {
1255                                         strlcpy(attr, sysfs_path, sizeof(attr));
1256                                         strlcat(attr, devpath, sizeof(attr));
1257                                         strlcat(attr, "/", sizeof(attr));
1258                                         strlcat(attr, attrib, sizeof(attr));
1259                                 }
1260                         }
1261
1262                         if (attr[0] == '\0') {
1263                                 strlcpy(attr, sysfs_path, sizeof(attr));
1264                                 strlcat(attr, udev->dev->devpath, sizeof(attr));
1265                                 strlcat(attr, "/", sizeof(attr));
1266                                 strlcat(attr, key_name, sizeof(attr));
1267                         }
1268
1269                         pos = strstr(attr, "/*/");
1270                         if (pos != NULL) {
1271                                 char str[PATH_SIZE];
1272                                 DIR *dir;
1273
1274                                 pos[1] = '\0';
1275                                 strlcpy(str, &pos[2], sizeof(str));
1276                                 dir = opendir(attr);
1277                                 if (dir != NULL) {
1278                                         struct dirent *dent;
1279
1280                                         for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
1281                                                 if (dent->d_name[0] == '.')
1282                                                         continue;
1283                                                 strlcat(attr, dent->d_name, sizeof(attr));
1284                                                 break;
1285                                         }
1286                                         closedir(dir);
1287                                 }
1288                                 strlcat(attr, str, sizeof(attr));
1289                         }
1290
1291                         strlcpy(value, key_val(rule, &pair->key), sizeof(value));
1292                         udev_rules_apply_format(udev, value, sizeof(value));
1293                         info("writing '%s' to sysfs file '%s'", value, attr);
1294                         f = fopen(attr, "w");
1295                         if (f != NULL) {
1296                                 if (!udev->test_run)
1297                                         if (fprintf(f, "%s", value) <= 0)
1298                                                 err("error writing ATTR{%s}: %s", attr, strerror(errno));
1299                                 fclose(f);
1300                         } else
1301                                 err("error opening ATTR{%s} for writing: %s", attr, strerror(errno));
1302                 }
1303         }
1304         return 0;
1305
1306 nomatch:
1307         return -1;
1308 }
1309
1310 int udev_rules_get_name(struct udev_rules *rules, struct udevice *udev)
1311 {
1312         struct udev_rule *rule;
1313         int name_set = 0;
1314
1315         dbg("udev->dev->devpath='%s'", udev->dev->devpath);
1316         dbg("udev->dev->kernel='%s'", udev->dev->kernel);
1317
1318         /* look for a matching rule to apply */
1319         udev_rules_iter_init(rules);
1320         while (1) {
1321                 rule = udev_rules_iter_next(rules);
1322                 if (rule == NULL)
1323                         break;
1324
1325                 if (name_set &&
1326                     (rule->name.operation == KEY_OP_ASSIGN ||
1327                      rule->name.operation == KEY_OP_ASSIGN_FINAL ||
1328                      rule->name.operation == KEY_OP_ADD)) {
1329                         dbg("node name already set, rule ignored");
1330                         continue;
1331                 }
1332
1333                 dbg("process rule");
1334                 if (match_rule(udev, rule) == 0) {
1335                         /* apply options */
1336                         if (rule->ignore_device) {
1337                                 info("rule applied, '%s' is ignored", udev->dev->kernel);
1338                                 udev->ignore_device = 1;
1339                                 return 0;
1340                         }
1341                         if (rule->ignore_remove) {
1342                                 udev->ignore_remove = 1;
1343                                 dbg("remove event should be ignored");
1344                         }
1345                         if (rule->link_priority != 0) {
1346                                 udev->link_priority = rule->link_priority;
1347                                 info("link_priority=%i", udev->link_priority);
1348                         }
1349                         /* apply all_partitions option only at a main block device */
1350                         if (rule->partitions &&
1351                             strcmp(udev->dev->subsystem, "block") == 0 && udev->dev->kernel_number[0] == '\0') {
1352                                 udev->partitions = rule->partitions;
1353                                 dbg("creation of partition nodes requested");
1354                         }
1355
1356                         /* apply permissions */
1357                         if (!udev->mode_final && rule->mode != 0000) {
1358                                 if (rule->mode_operation == KEY_OP_ASSIGN_FINAL)
1359                                         udev->mode_final = 1;
1360                                 udev->mode = rule->mode;
1361                                 dbg("applied mode=%#o to '%s'", rule->mode, udev->dev->kernel);
1362                         }
1363                         if (!udev->owner_final && rule->owner.operation != KEY_OP_UNSET) {
1364                                 if (rule->owner.operation == KEY_OP_ASSIGN_FINAL)
1365                                         udev->owner_final = 1;
1366                                 strlcpy(udev->owner, key_val(rule, &rule->owner), sizeof(udev->owner));
1367                                 udev_rules_apply_format(udev, udev->owner, sizeof(udev->owner));
1368                                 dbg("applied owner='%s' to '%s'", udev->owner, udev->dev->kernel);
1369                         }
1370                         if (!udev->group_final && rule->group.operation != KEY_OP_UNSET) {
1371                                 if (rule->group.operation == KEY_OP_ASSIGN_FINAL)
1372                                         udev->group_final = 1;
1373                                 strlcpy(udev->group, key_val(rule, &rule->group), sizeof(udev->group));
1374                                 udev_rules_apply_format(udev, udev->group, sizeof(udev->group));
1375                                 dbg("applied group='%s' to '%s'", udev->group, udev->dev->kernel);
1376                         }
1377
1378                         /* collect symlinks */
1379                         if (!udev->symlink_final &&
1380                             (rule->symlink.operation == KEY_OP_ASSIGN ||
1381                              rule->symlink.operation == KEY_OP_ASSIGN_FINAL ||
1382                              rule->symlink.operation == KEY_OP_ADD)) {
1383                                 char temp[PATH_SIZE];
1384                                 char *pos, *next;
1385                                 int count;
1386
1387                                 if (rule->symlink.operation == KEY_OP_ASSIGN_FINAL)
1388                                         udev->symlink_final = 1;
1389                                 if (rule->symlink.operation == KEY_OP_ASSIGN ||
1390                                     rule->symlink.operation == KEY_OP_ASSIGN_FINAL) {
1391                                         info("reset symlink list");
1392                                         name_list_cleanup(&udev->symlink_list);
1393                                 }
1394                                 /* allow  multiple symlinks separated by spaces */
1395                                 strlcpy(temp, key_val(rule, &rule->symlink), sizeof(temp));
1396                                 udev_rules_apply_format(udev, temp, sizeof(temp));
1397                                 if (rule->string_escape == ESCAPE_UNSET ||
1398                                     rule->string_escape == ESCAPE_REPLACE) {
1399                                         count = replace_chars(temp, ALLOWED_CHARS_FILE " ");
1400                                         if (count > 0)
1401                                                 info("%i character(s) replaced" , count);
1402                                 }
1403                                 dbg("rule applied, added symlink(s) '%s'", temp);
1404                                 pos = temp;
1405                                 while (isspace(pos[0]))
1406                                         pos++;
1407                                 next = strchr(pos, ' ');
1408                                 while (next) {
1409                                         next[0] = '\0';
1410                                         info("add symlink '%s'", pos);
1411                                         name_list_add(&udev->symlink_list, pos, 0);
1412                                         while (isspace(next[1]))
1413                                                 next++;
1414                                         pos = &next[1];
1415                                         next = strchr(pos, ' ');
1416                                 }
1417                                 if (pos[0] != '\0') {
1418                                         info("add symlink '%s'", pos);
1419                                         name_list_add(&udev->symlink_list, pos, 0);
1420                                 }
1421                         }
1422
1423                         /* set name, later rules with name set will be ignored */
1424                         if (rule->name.operation == KEY_OP_ASSIGN ||
1425                             rule->name.operation == KEY_OP_ASSIGN_FINAL ||
1426                             rule->name.operation == KEY_OP_ADD) {
1427                                 int count;
1428
1429                                 name_set = 1;
1430                                 strlcpy(udev->name, key_val(rule, &rule->name), sizeof(udev->name));
1431                                 udev_rules_apply_format(udev, udev->name, sizeof(udev->name));
1432                                 if (rule->string_escape == ESCAPE_UNSET ||
1433                                     rule->string_escape == ESCAPE_REPLACE) {
1434                                         count = replace_chars(udev->name, ALLOWED_CHARS_FILE);
1435                                         if (count > 0)
1436                                                 info("%i character(s) replaced", count);
1437                                 }
1438
1439                                 info("rule applied, '%s' becomes '%s'", udev->dev->kernel, udev->name);
1440                                 if (strcmp(udev->dev->subsystem, "net") != 0)
1441                                         dbg("name, '%s' is going to have owner='%s', group='%s', mode=%#o partitions=%i",
1442                                             udev->name, udev->owner, udev->group, udev->mode, udev->partitions);
1443                         }
1444
1445                         if (!udev->run_final && rule->run.operation != KEY_OP_UNSET) {
1446                                 struct name_entry *entry;
1447
1448                                 if (rule->run.operation == KEY_OP_ASSIGN_FINAL)
1449                                         udev->run_final = 1;
1450                                 if (rule->run.operation == KEY_OP_ASSIGN || rule->run.operation == KEY_OP_ASSIGN_FINAL) {
1451                                         info("reset run list");
1452                                         name_list_cleanup(&udev->run_list);
1453                                 }
1454                                 dbg("add run '%s'", key_val(rule, &rule->run));
1455                                 entry = name_list_add(&udev->run_list, key_val(rule, &rule->run), 0);
1456                                 if (rule->run_ignore_error)
1457                                         entry->ignore_error = 1;
1458                         }
1459
1460                         if (rule->last_rule) {
1461                                 dbg("last rule to be applied");
1462                                 break;
1463                         }
1464
1465                         if (rule->goto_label.operation != KEY_OP_UNSET) {
1466                                 dbg("moving forward to label '%s'", key_val(rule, &rule->goto_label));
1467                                 udev_rules_iter_label(rules, key_val(rule, &rule->goto_label));
1468                         }
1469                 }
1470         }
1471
1472         if (!name_set) {
1473                 info("no node name set, will use kernel name '%s'", udev->dev->kernel);
1474                 strlcpy(udev->name, udev->dev->kernel, sizeof(udev->name));
1475         }
1476
1477         if (udev->tmp_node[0] != '\0') {
1478                 dbg("removing temporary device node");
1479                 unlink_secure(udev->tmp_node);
1480                 udev->tmp_node[0] = '\0';
1481         }
1482
1483         return 0;
1484 }
1485
1486 int udev_rules_get_run(struct udev_rules *rules, struct udevice *udev)
1487 {
1488         struct udev_rule *rule;
1489
1490         dbg("udev->kernel='%s'", udev->dev->kernel);
1491
1492         /* look for a matching rule to apply */
1493         udev_rules_iter_init(rules);
1494         while (1) {
1495                 rule = udev_rules_iter_next(rules);
1496                 if (rule == NULL)
1497                         break;
1498
1499                 dbg("process rule");
1500                 if (rule->name.operation == KEY_OP_ASSIGN ||
1501                     rule->name.operation == KEY_OP_ASSIGN_FINAL ||
1502                     rule->name.operation == KEY_OP_ADD ||
1503                     rule->symlink.operation == KEY_OP_ASSIGN ||
1504                     rule->symlink.operation == KEY_OP_ASSIGN_FINAL ||
1505                     rule->symlink.operation == KEY_OP_ADD ||
1506                     rule->mode_operation != KEY_OP_UNSET ||
1507                     rule->owner.operation != KEY_OP_UNSET || rule->group.operation != KEY_OP_UNSET) {
1508                         dbg("skip rule that names a device");
1509                         continue;
1510                 }
1511
1512                 if (match_rule(udev, rule) == 0) {
1513                         if (rule->ignore_device) {
1514                                 info("rule applied, '%s' is ignored", udev->dev->kernel);
1515                                 udev->ignore_device = 1;
1516                                 return 0;
1517                         }
1518                         if (rule->ignore_remove) {
1519                                 udev->ignore_remove = 1;
1520                                 dbg("remove event should be ignored");
1521                         }
1522
1523                         if (!udev->run_final && rule->run.operation != KEY_OP_UNSET) {
1524                                 struct name_entry *entry;
1525
1526                                 if (rule->run.operation == KEY_OP_ASSIGN ||
1527                                     rule->run.operation == KEY_OP_ASSIGN_FINAL) {
1528                                         info("reset run list");
1529                                         name_list_cleanup(&udev->run_list);
1530                                 }
1531                                 dbg("add run '%s'", key_val(rule, &rule->run));
1532                                 entry = name_list_add(&udev->run_list, key_val(rule, &rule->run), 0);
1533                                 if (rule->run_ignore_error)
1534                                         entry->ignore_error = 1;
1535                                 if (rule->run.operation == KEY_OP_ASSIGN_FINAL)
1536                                         break;
1537                         }
1538
1539                         if (rule->last_rule) {
1540                                 dbg("last rule to be applied");
1541                                 break;
1542                         }
1543
1544                         if (rule->goto_label.operation != KEY_OP_UNSET) {
1545                                 dbg("moving forward to label '%s'", key_val(rule, &rule->goto_label));
1546                                 udev_rules_iter_label(rules, key_val(rule, &rule->goto_label));
1547                         }
1548                 }
1549         }
1550
1551         return 0;
1552 }