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