chiark / gitweb /
daf3d7fff7992841ab766b10a0339712828dabf2
[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                 if (count >= sizeof(line)) {
353                         err("line too long, conf line skipped %s, line %d", udev_config_filename, lineno);
354                         continue;
355                 }
356
357                 /* eat the whitespace */
358                 while ((count > 0) && isspace(bufline[0])) {
359                         bufline++;
360                         count--;
361                 }
362                 if (count == 0)
363                         continue;
364
365                 /* see if this is a comment */
366                 if (bufline[0] == COMMENT_CHARACTER)
367                         continue;
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); i++) {
479                 bufpos += strlcpy(&buf[bufpos], environ[i], sizeof(buf) - bufpos-1);
480                 bufpos++;
481         }
482
483         count = sendto(sock, &buf, bufpos, 0, (struct sockaddr *)&saddr, addrlen);
484         if (count < 0)
485                 retval = -1;
486         info("passed %zi bytes to socket '%s', ", count, sockname);
487
488         close(sock);
489         return retval;
490 }
491
492 int udev_rules_run(struct udevice *udev)
493 {
494         struct name_entry *name_loop;
495         int retval = 0;
496
497         dbg("executing run list");
498         list_for_each_entry(name_loop, &udev->run_list, node) {
499                 if (strncmp(name_loop->name, "socket:", strlen("socket:")) == 0) {
500                         pass_env_to_socket(&name_loop->name[strlen("socket:")], udev->dev->devpath, udev->action);
501                 } else {
502                         char program[PATH_SIZE];
503
504                         strlcpy(program, name_loop->name, sizeof(program));
505                         udev_rules_apply_format(udev, program, sizeof(program));
506                         if (run_program(program, udev->dev->subsystem, NULL, 0, NULL) != 0)
507                                 if (!name_loop->ignore_error)
508                                         retval = -1;
509                 }
510         }
511
512         return retval;
513 }
514
515 #define WAIT_LOOP_PER_SECOND            50
516 static int wait_for_sysfs(struct udevice *udev, const char *file, int timeout)
517 {
518         char devicepath[PATH_SIZE];
519         char filepath[PATH_SIZE];
520         struct stat stats;
521         int loop = timeout * WAIT_LOOP_PER_SECOND;
522
523         strlcpy(devicepath, sysfs_path, sizeof(devicepath));
524         strlcat(devicepath, udev->dev->devpath, sizeof(devicepath));
525         strlcpy(filepath, devicepath, sizeof(filepath));
526         strlcat(filepath, "/", sizeof(filepath));
527         strlcat(filepath, file, sizeof(filepath));
528
529         dbg("will wait %i sec for '%s'", timeout, filepath);
530         while (--loop) {
531                 /* lookup file */
532                 if (stat(filepath, &stats) == 0) {
533                         info("file '%s' appeared after %i loops", filepath, (timeout * WAIT_LOOP_PER_SECOND) - loop-1);
534                         return 0;
535                 }
536                 /* make sure, the device did not disappear in the meantime */
537                 if (stat(devicepath, &stats) != 0) {
538                         info("device disappeared while waiting for '%s'", filepath);
539                         return -2;
540                 }
541                 info("wait for '%s' for %i mseconds", filepath, 1000 / WAIT_LOOP_PER_SECOND);
542                 usleep(1000 * 1000 / WAIT_LOOP_PER_SECOND);
543         }
544         info("waiting for '%s' failed", filepath);
545         return -1;
546 }
547
548 /* handle "[$SUBSYSTEM/$KERNEL]<attribute>" lookup */
549 static int attr_get_by_subsys_id(const char *attrstr, char *devpath, size_t len, char **attr)
550 {
551         char subsys[NAME_SIZE];
552         char *attrib;
553         char *id;
554         int found = 0;
555
556         if (attrstr[0] != '[')
557                 goto out;
558
559         strlcpy(subsys, &attrstr[1], sizeof(subsys));
560
561         attrib = strchr(subsys, ']');
562         if (attrib == NULL)
563                 goto out;
564         attrib[0] = '\0';
565         attrib = &attrib[1];
566
567         id = strchr(subsys, '/');
568         if (id == NULL)
569                 goto out;
570         id[0] = '\0';
571         id = &id[1];
572
573         if (sysfs_lookup_devpath_by_subsys_id(devpath, len, subsys, id)) {
574                 if (attr != NULL) {
575                         if (attrib[0] != '\0')
576                                 *attr = attrib;
577                         else
578                                 *attr = NULL;
579                 }
580                 found = 1;
581         }
582 out:
583         return found;
584 }
585
586 void udev_rules_apply_format(struct udevice *udev, char *string, size_t maxsize)
587 {
588         char temp[PATH_SIZE];
589         char temp2[PATH_SIZE];
590         char *head, *tail, *pos, *cpos, *attr, *rest;
591         int len;
592         int i;
593         int count;
594         enum subst_type {
595                 SUBST_UNKNOWN,
596                 SUBST_DEVPATH,
597                 SUBST_KERNEL,
598                 SUBST_KERNEL_NUMBER,
599                 SUBST_ID,
600                 SUBST_MAJOR,
601                 SUBST_MINOR,
602                 SUBST_RESULT,
603                 SUBST_ATTR,
604                 SUBST_PARENT,
605                 SUBST_TEMP_NODE,
606                 SUBST_ROOT,
607                 SUBST_SYS,
608                 SUBST_ENV,
609         };
610         static const struct subst_map {
611                 char *name;
612                 char fmt;
613                 enum subst_type type;
614         } map[] = {
615                 { .name = "devpath",    .fmt = 'p',     .type = SUBST_DEVPATH },
616                 { .name = "number",     .fmt = 'n',     .type = SUBST_KERNEL_NUMBER },
617                 { .name = "kernel",     .fmt = 'k',     .type = SUBST_KERNEL },
618                 { .name = "id",         .fmt = 'b',     .type = SUBST_ID },
619                 { .name = "major",      .fmt = 'M',     .type = SUBST_MAJOR },
620                 { .name = "minor",      .fmt = 'm',     .type = SUBST_MINOR },
621                 { .name = "result",     .fmt = 'c',     .type = SUBST_RESULT },
622                 { .name = "attr",       .fmt = 's',     .type = SUBST_ATTR },
623                 { .name = "sysfs",      .fmt = 's',     .type = SUBST_ATTR },
624                 { .name = "parent",     .fmt = 'P',     .type = SUBST_PARENT },
625                 { .name = "tempnode",   .fmt = 'N',     .type = SUBST_TEMP_NODE },
626                 { .name = "root",       .fmt = 'r',     .type = SUBST_ROOT },
627                 { .name = "sys",        .fmt = 'S',     .type = SUBST_SYS },
628                 { .name = "env",        .fmt = 'E',     .type = SUBST_ENV },
629                 { NULL, '\0', 0 }
630         };
631         enum subst_type type;
632         const struct subst_map *subst;
633
634         head = string;
635         while (1) {
636                 len = -1;
637                 while (head[0] != '\0') {
638                         if (head[0] == '$') {
639                                 /* substitute named variable */
640                                 if (head[1] == '\0')
641                                         break;
642                                 if (head[1] == '$') {
643                                         strlcpy(temp, head+2, sizeof(temp));
644                                         strlcpy(head+1, temp, maxsize);
645                                         head++;
646                                         continue;
647                                 }
648                                 head[0] = '\0';
649                                 for (subst = map; subst->name; subst++) {
650                                         if (strncasecmp(&head[1], subst->name, strlen(subst->name)) == 0) {
651                                                 type = subst->type;
652                                                 tail = head + strlen(subst->name)+1;
653                                                 dbg("will substitute format name '%s'", subst->name);
654                                                 goto found;
655                                         }
656                                 }
657                                 head[0] = '$';
658                                 err("unknown format variable '%s'", head);
659                         } else if (head[0] == '%') {
660                                 /* substitute format char */
661                                 if (head[1] == '\0')
662                                         break;
663                                 if (head[1] == '%') {
664                                         strlcpy(temp, head+2, sizeof(temp));
665                                         strlcpy(head+1, temp, maxsize);
666                                         head++;
667                                         continue;
668                                 }
669                                 head[0] = '\0';
670                                 tail = head+1;
671                                 len = get_format_len(&tail);
672                                 for (subst = map; subst->name; subst++) {
673                                         if (tail[0] == subst->fmt) {
674                                                 type = subst->type;
675                                                 tail++;
676                                                 dbg("will substitute format char '%c'", subst->fmt);
677                                                 goto found;
678                                         }
679                                 }
680                                 head[0] = '%';
681                                 err("unknown format char '%c'", tail[0]);
682                         }
683                         head++;
684                 }
685                 break;
686 found:
687                 attr = get_format_attribute(&tail);
688                 strlcpy(temp, tail, sizeof(temp));
689                 dbg("format=%i, string='%s', tail='%s'", type ,string, tail);
690
691                 switch (type) {
692                 case SUBST_DEVPATH:
693                         strlcat(string, udev->dev->devpath, maxsize);
694                         dbg("substitute devpath '%s'", udev->dev->devpath);
695                         break;
696                 case SUBST_KERNEL:
697                         strlcat(string, udev->dev->kernel, maxsize);
698                         dbg("substitute kernel name '%s'", udev->dev->kernel);
699                         break;
700                 case SUBST_KERNEL_NUMBER:
701                         strlcat(string, udev->dev->kernel_number, maxsize);
702                         dbg("substitute kernel number '%s'", udev->dev->kernel_number);
703                         break;
704                 case SUBST_ID:
705                         if (udev->dev_parent != NULL) {
706                                 strlcat(string, udev->dev_parent->kernel, maxsize);
707                                 dbg("substitute id '%s'", udev->dev_parent->kernel);
708                         }
709                         break;
710                 case SUBST_MAJOR:
711                         sprintf(temp2, "%d", major(udev->devt));
712                         strlcat(string, temp2, maxsize);
713                         dbg("substitute major number '%s'", temp2);
714                         break;
715                 case SUBST_MINOR:
716                         sprintf(temp2, "%d", minor(udev->devt));
717                         strlcat(string, temp2, maxsize);
718                         dbg("substitute minor number '%s'", temp2);
719                         break;
720                 case SUBST_RESULT:
721                         if (udev->program_result[0] == '\0')
722                                 break;
723                         /* get part part of the result string */
724                         i = 0;
725                         if (attr != NULL)
726                                 i = strtoul(attr, &rest, 10);
727                         if (i > 0) {
728                                 dbg("request part #%d of result string", i);
729                                 cpos = udev->program_result;
730                                 while (--i) {
731                                         while (cpos[0] != '\0' && !isspace(cpos[0]))
732                                                 cpos++;
733                                         while (isspace(cpos[0]))
734                                                 cpos++;
735                                 }
736                                 if (i > 0) {
737                                         err("requested part of result string not found");
738                                         break;
739                                 }
740                                 strlcpy(temp2, cpos, sizeof(temp2));
741                                 /* %{2+}c copies the whole string from the second part on */
742                                 if (rest[0] != '+') {
743                                         cpos = strchr(temp2, ' ');
744                                         if (cpos)
745                                                 cpos[0] = '\0';
746                                 }
747                                 strlcat(string, temp2, maxsize);
748                                 dbg("substitute part of result string '%s'", temp2);
749                         } else {
750                                 strlcat(string, udev->program_result, maxsize);
751                                 dbg("substitute result string '%s'", udev->program_result);
752                         }
753                         break;
754                 case SUBST_ATTR:
755                         if (attr == NULL)
756                                 err("missing file parameter for attr");
757                         else {
758                                 char devpath[PATH_SIZE];
759                                 char *attrib;
760                                 const char *value = NULL;
761                                 size_t size;
762
763                                 if (attr_get_by_subsys_id(attr, devpath, sizeof(devpath), &attrib)) {
764                                         if (attrib != NULL)
765                                                 value = sysfs_attr_get_value(devpath, attrib);
766                                         else
767                                                 break;
768                                 }
769
770                                 /* try the current device, other matches may have selected */
771                                 if (value == NULL && udev->dev_parent != NULL && udev->dev_parent != udev->dev)
772                                         value = sysfs_attr_get_value(udev->dev_parent->devpath, attr);
773
774                                 /* look at all devices along the chain of parents */
775                                 if (value == NULL) {
776                                         struct sysfs_device *dev_parent = udev->dev;
777
778                                         do {
779                                                 dbg("looking at '%s'", dev_parent->devpath);
780                                                 value = sysfs_attr_get_value(dev_parent->devpath, attr);
781                                                 if (value != NULL) {
782                                                         strlcpy(temp2, value, sizeof(temp2));
783                                                         break;
784                                                 }
785                                                 dev_parent = sysfs_device_get_parent(dev_parent);
786                                         } while (dev_parent != NULL);
787                                 }
788
789                                 if (value == NULL)
790                                         break;
791
792                                 /* strip trailing whitespace, and replace unwanted characters */
793                                 size = strlcpy(temp2, value, sizeof(temp2));
794                                 if (size >= sizeof(temp2))
795                                         size = sizeof(temp2)-1;
796                                 while (size > 0 && isspace(temp2[size-1]))
797                                         temp2[--size] = '\0';
798                                 count = replace_chars(temp2, ALLOWED_CHARS_INPUT);
799                                 if (count > 0)
800                                         info("%i character(s) replaced" , count);
801                                 strlcat(string, temp2, maxsize);
802                                 dbg("substitute sysfs value '%s'", temp2);
803                         }
804                         break;
805                 case SUBST_PARENT:
806                         {
807                                 struct sysfs_device *dev_parent;
808
809                                 dev_parent = sysfs_device_get_parent(udev->dev);
810                                 if (dev_parent != NULL) {
811                                         struct udevice *udev_parent;
812
813                                         dbg("found parent '%s', get the node name", dev_parent->devpath);
814                                         udev_parent = udev_device_init(NULL);
815                                         if (udev_parent != NULL) {
816                                                 /* lookup the name in the udev_db with the DEVPATH of the parent */
817                                                 if (udev_db_get_device(udev_parent, dev_parent->devpath) == 0) {
818                                                         strlcat(string, udev_parent->name, maxsize);
819                                                         dbg("substitute parent node name'%s'", udev_parent->name);
820                                                 } else
821                                                         dbg("parent not found in database");
822                                                 udev_device_cleanup(udev_parent);
823                                         }
824                                 }
825                         }
826                         break;
827                 case SUBST_TEMP_NODE:
828                         if (udev->tmp_node[0] == '\0' && major(udev->devt) > 0) {
829                                 dbg("create temporary device node for callout");
830                                 snprintf(udev->tmp_node, sizeof(udev->tmp_node), "%s/.tmp-%u-%u",
831                                          udev_root, major(udev->devt), minor(udev->devt));
832                                 udev->tmp_node[sizeof(udev->tmp_node)-1] = '\0';
833                                 udev_node_mknod(udev, udev->tmp_node, udev->devt, 0600, 0, 0);
834                         }
835                         strlcat(string, udev->tmp_node, maxsize);
836                         dbg("substitute temporary device node name '%s'", udev->tmp_node);
837                         break;
838                 case SUBST_ROOT:
839                         strlcat(string, udev_root, maxsize);
840                         dbg("substitute udev_root '%s'", udev_root);
841                         break;
842                 case SUBST_SYS:
843                         strlcat(string, sysfs_path, maxsize);
844                         dbg("substitute sysfs_path '%s'", sysfs_path);
845                         break;
846                 case SUBST_ENV:
847                         if (attr == NULL) {
848                                 dbg("missing attribute");
849                                 break;
850                         }
851                         pos = getenv(attr);
852                         if (pos == NULL) {
853                                 dbg("env '%s' not available", attr);
854                                 break;
855                         }
856                         dbg("substitute env '%s=%s'", attr, pos);
857                         strlcat(string, pos, maxsize);
858                         break;
859                 default:
860                         err("unknown substitution type=%i", type);
861                         break;
862                 }
863                 /* possibly truncate to format-char specified length */
864                 if (len >= 0 && len < (int)strlen(head)) {
865                         head[len] = '\0';
866                         dbg("truncate to %i chars, subtitution string becomes '%s'", len, head);
867                 }
868                 strlcat(string, temp, maxsize);
869         }
870 }
871
872 static char *key_val(struct udev_rule *rule, struct key *key)
873 {
874         return rule->buf + key->val_off;
875 }
876
877 static char *key_pair_name(struct udev_rule *rule, struct key_pair *pair)
878 {
879         return rule->buf + pair->key_name_off;
880 }
881
882 static int match_key(const char *key_name, struct udev_rule *rule, struct key *key, const char *val)
883 {
884         char value[PATH_SIZE];
885         char *key_value;
886         char *pos;
887         int match = 0;
888
889         if (key->operation != KEY_OP_MATCH &&
890             key->operation != KEY_OP_NOMATCH)
891                 return 0;
892
893         /* look for a matching string, parts are separated by '|' */
894         strlcpy(value, rule->buf + key->val_off, sizeof(value));
895         key_value = value;
896         dbg("key %s value='%s'", key_name, key_value);
897         while (key_value) {
898                 pos = strchr(key_value, '|');
899                 if (pos) {
900                         pos[0] = '\0';
901                         pos++;
902                 }
903
904                 dbg("match %s '%s' <-> '%s'", key_name, key_value, val);
905                 match = (fnmatch(key_value, val, 0) == 0);
906                 if (match)
907                         break;
908
909                 key_value = pos;
910         }
911
912         if (match && (key->operation == KEY_OP_MATCH)) {
913                 dbg("%s is true (matching value)", key_name);
914                 return 0;
915         }
916         if (!match && (key->operation == KEY_OP_NOMATCH)) {
917                 dbg("%s is true (non-matching value)", key_name);
918                 return 0;
919         }
920         return -1;
921 }
922
923 /* match a single rule against a given device and possibly its parent devices */
924 static int match_rule(struct udevice *udev, struct udev_rule *rule)
925 {
926         int i;
927
928         if (match_key("ACTION", rule, &rule->action, udev->action))
929                 goto nomatch;
930
931         if (match_key("KERNEL", rule, &rule->kernel, udev->dev->kernel))
932                 goto nomatch;
933
934         if (match_key("SUBSYSTEM", rule, &rule->subsystem, udev->dev->subsystem))
935                 goto nomatch;
936
937         if (match_key("DEVPATH", rule, &rule->devpath, udev->dev->devpath))
938                 goto nomatch;
939
940         if (match_key("DRIVER", rule, &rule->driver, udev->dev->driver))
941                 goto nomatch;
942
943         if (match_key("NAME", rule, &rule->name, udev->name))
944                 goto nomatch;
945
946         /* match against current list of symlinks */
947         if (rule->symlink_match.operation == KEY_OP_MATCH ||
948             rule->symlink_match.operation == KEY_OP_NOMATCH) {
949                 struct name_entry *name_loop;
950                 int match = 0;
951
952                 list_for_each_entry(name_loop, &udev->symlink_list, node) {
953                         if (match_key("SYMLINK", rule, &rule->symlink_match, name_loop->name) == 0) {
954                                 match = 1;
955                                 break;
956                         }
957                 }
958                 if (!match)
959                         goto nomatch;
960         }
961
962         for (i = 0; i < rule->env.count; i++) {
963                 struct key_pair *pair = &rule->env.keys[i];
964
965                 /* we only check for matches, assignments will be handled later */
966                 if (pair->key.operation == KEY_OP_MATCH ||
967                     pair->key.operation == KEY_OP_NOMATCH) {
968                         const char *key_name = key_pair_name(rule, pair);
969                         const char *value = getenv(key_name);
970
971                         if (!value) {
972                                 dbg("ENV{'%s'} is not set, treat as empty", key_name);
973                                 value = "";
974                         }
975                         if (match_key("ENV", rule, &pair->key, value))
976                                 goto nomatch;
977                 }
978         }
979
980         if (rule->test.operation != KEY_OP_UNSET) {
981                 char filename[PATH_SIZE];
982                 char devpath[PATH_SIZE];
983                 char *attr;
984                 struct stat statbuf;
985                 int match;
986
987                 strlcpy(filename, key_val(rule, &rule->test), sizeof(filename));
988                 udev_rules_apply_format(udev, filename, sizeof(filename));
989
990                 if (attr_get_by_subsys_id(filename, devpath, sizeof(devpath), &attr)) {
991                         strlcpy(filename, sysfs_path, sizeof(filename));
992                         strlcat(filename, devpath, sizeof(filename));
993                         if (attr != NULL) {
994                                 strlcat(filename, "/", sizeof(filename));
995                                 strlcat(filename, attr, sizeof(filename));
996                         }
997                 }
998
999                 match = (stat(filename, &statbuf) == 0);
1000                 info("'%s' %s", filename, match ? "exists" : "does not exist");
1001                 if (match && rule->test_mode_mask > 0) {
1002                         match = ((statbuf.st_mode & rule->test_mode_mask) > 0);
1003                         info("'%s' has mode=%#o and %s %#o", filename, statbuf.st_mode,
1004                              match ? "matches" : "does not match",
1005                              rule->test_mode_mask);
1006                 }
1007                 if (match && rule->test.operation == KEY_OP_NOMATCH)
1008                         goto nomatch;
1009                 if (!match && rule->test.operation == KEY_OP_MATCH)
1010                         goto nomatch;
1011                 dbg("TEST key is true");
1012         }
1013
1014         if (rule->wait_for_sysfs.operation != KEY_OP_UNSET) {
1015                 int found;
1016
1017                 found = (wait_for_sysfs(udev, key_val(rule, &rule->wait_for_sysfs), 3) == 0);
1018                 if (!found && (rule->wait_for_sysfs.operation != KEY_OP_NOMATCH))
1019                         goto nomatch;
1020         }
1021
1022         /* check for matching sysfs attribute pairs */
1023         for (i = 0; i < rule->attr.count; i++) {
1024                 struct key_pair *pair = &rule->attr.keys[i];
1025
1026                 if (pair->key.operation == KEY_OP_MATCH ||
1027                     pair->key.operation == KEY_OP_NOMATCH) {
1028                         const char *key_name = key_pair_name(rule, pair);
1029                         const char *key_value = key_val(rule, &pair->key);
1030                         char devpath[PATH_SIZE];
1031                         char *attrib;
1032                         const char *value = NULL;
1033                         char val[VALUE_SIZE];
1034                         size_t len;
1035
1036                         if (attr_get_by_subsys_id(key_name, devpath, sizeof(devpath), &attrib)) {
1037                                 if (attrib != NULL)
1038                                         value = sysfs_attr_get_value(devpath, attrib);
1039                                 else
1040                                         goto nomatch;
1041                         }
1042                         if (value == NULL)
1043                                 value = sysfs_attr_get_value(udev->dev->devpath, key_name);
1044                         if (value == NULL)
1045                                 goto nomatch;
1046                         strlcpy(val, value, sizeof(val));
1047
1048                         /* strip trailing whitespace of value, if not asked to match for it */
1049                         len = strlen(key_value);
1050                         if (len > 0 && !isspace(key_value[len-1])) {
1051                                 len = strlen(val);
1052                                 while (len > 0 && isspace(val[len-1]))
1053                                         val[--len] = '\0';
1054                                 dbg("removed %zi trailing whitespace chars from '%s'", strlen(val)-len, val);
1055                         }
1056
1057                         if (match_key("ATTR", rule, &pair->key, val))
1058                                 goto nomatch;
1059                 }
1060         }
1061
1062         /* walk up the chain of parent devices and find a match */
1063         udev->dev_parent = udev->dev;
1064         while (1) {
1065                 /* check for matching kernel device name */
1066                 if (match_key("KERNELS", rule, &rule->kernels, udev->dev_parent->kernel))
1067                         goto try_parent;
1068
1069                 /* check for matching subsystem value */
1070                 if (match_key("SUBSYSTEMS", rule, &rule->subsystems, udev->dev_parent->subsystem))
1071                         goto try_parent;
1072
1073                 /* check for matching driver */
1074                 if (match_key("DRIVERS", rule, &rule->drivers, udev->dev_parent->driver))
1075                         goto try_parent;
1076
1077                 /* check for matching sysfs attribute pairs */
1078                 for (i = 0; i < rule->attrs.count; i++) {
1079                         struct key_pair *pair = &rule->attrs.keys[i];
1080
1081                         if (pair->key.operation == KEY_OP_MATCH ||
1082                             pair->key.operation == KEY_OP_NOMATCH) {
1083                                 const char *key_name = key_pair_name(rule, pair);
1084                                 const char *key_value = key_val(rule, &pair->key);
1085                                 const char *value;
1086                                 char val[VALUE_SIZE];
1087                                 size_t len;
1088
1089                                 value = sysfs_attr_get_value(udev->dev_parent->devpath, key_name);
1090                                 if (value == NULL)
1091                                         value = sysfs_attr_get_value(udev->dev->devpath, key_name);
1092                                 if (value == NULL)
1093                                         goto try_parent;
1094                                 strlcpy(val, value, sizeof(val));
1095
1096                                 /* strip trailing whitespace of value, if not asked to match for it */
1097                                 len = strlen(key_value);
1098                                 if (len > 0 && !isspace(key_value[len-1])) {
1099                                         len = strlen(val);
1100                                         while (len > 0 && isspace(val[len-1]))
1101                                                 val[--len] = '\0';
1102                                         dbg("removed %zi trailing whitespace chars from '%s'", strlen(val)-len, val);
1103                                 }
1104
1105                                 if (match_key("ATTRS", rule, &pair->key, val))
1106                                         goto try_parent;
1107                         }
1108                 }
1109
1110                 /* found matching device  */
1111                 break;
1112 try_parent:
1113                 /* move to parent device */
1114                 dbg("try parent sysfs device");
1115                 udev->dev_parent = sysfs_device_get_parent(udev->dev_parent);
1116                 if (udev->dev_parent == NULL)
1117                         goto nomatch;
1118                 dbg("looking at dev_parent->devpath='%s'", udev->dev_parent->devpath);
1119                 dbg("looking at dev_parent->kernel='%s'", udev->dev_parent->kernel);
1120         }
1121
1122         /* execute external program */
1123         if (rule->program.operation != KEY_OP_UNSET) {
1124                 char program[PATH_SIZE];
1125                 char result[PATH_SIZE];
1126
1127                 strlcpy(program, key_val(rule, &rule->program), sizeof(program));
1128                 udev_rules_apply_format(udev, program, sizeof(program));
1129                 if (run_program(program, udev->dev->subsystem, result, sizeof(result), NULL) != 0) {
1130                         dbg("PROGRAM is false");
1131                         udev->program_result[0] = '\0';
1132                         if (rule->program.operation != KEY_OP_NOMATCH)
1133                                 goto nomatch;
1134                 } else {
1135                         int count;
1136
1137                         dbg("PROGRAM matches");
1138                         remove_trailing_chars(result, '\n');
1139                         if (rule->string_escape == ESCAPE_UNSET ||
1140                             rule->string_escape == ESCAPE_REPLACE) {
1141                                 count = replace_chars(result, ALLOWED_CHARS_INPUT);
1142                                 if (count > 0)
1143                                         info("%i character(s) replaced" , count);
1144                         }
1145                         dbg("result is '%s'", result);
1146                         strlcpy(udev->program_result, result, sizeof(udev->program_result));
1147                         dbg("PROGRAM returned successful");
1148                         if (rule->program.operation == KEY_OP_NOMATCH)
1149                                 goto nomatch;
1150                 }
1151                 dbg("PROGRAM key is true");
1152         }
1153
1154         /* check for matching result of external program */
1155         if (match_key("RESULT", rule, &rule->result, udev->program_result))
1156                 goto nomatch;
1157
1158         /* import variables returned from program or or file into environment */
1159         if (rule->import.operation != KEY_OP_UNSET) {
1160                 char import[PATH_SIZE];
1161                 int rc = -1;
1162
1163                 strlcpy(import, key_val(rule, &rule->import), sizeof(import));
1164                 udev_rules_apply_format(udev, import, sizeof(import));
1165                 dbg("check for IMPORT import='%s'", import);
1166                 if (rule->import_type == IMPORT_PROGRAM) {
1167                         rc = import_program_into_env(udev, import);
1168                 } else if (rule->import_type == IMPORT_FILE) {
1169                         dbg("import file import='%s'", import);
1170                         rc = import_file_into_env(udev, import);
1171                 } else if (rule->import_type == IMPORT_PARENT) {
1172                         dbg("import parent import='%s'", import);
1173                         rc = import_parent_into_env(udev, import);
1174                 }
1175                 if (rc != 0) {
1176                         dbg("IMPORT failed");
1177                         if (rule->import.operation != KEY_OP_NOMATCH)
1178                                 goto nomatch;
1179                 } else
1180                         dbg("IMPORT '%s' imported", key_val(rule, &rule->import));
1181                 dbg("IMPORT key is true");
1182         }
1183
1184         /* rule matches, if we have ENV assignments export it */
1185         for (i = 0; i < rule->env.count; i++) {
1186                 struct key_pair *pair = &rule->env.keys[i];
1187
1188                 if (pair->key.operation == KEY_OP_ASSIGN) {
1189                         char temp_value[NAME_SIZE];
1190                         const char *key_name = key_pair_name(rule, pair);
1191                         const char *value = key_val(rule, &pair->key);
1192
1193                         /* make sure we don't write to the same string we possibly read from */
1194                         strlcpy(temp_value, value, sizeof(temp_value));
1195                         udev_rules_apply_format(udev, temp_value, NAME_SIZE);
1196
1197                         if (temp_value[0] == '\0') {
1198                                 name_list_key_remove(&udev->env_list, key_name);
1199                                 unsetenv(key_name);
1200                                 info("unset ENV '%s'", key_name);
1201                         } else {
1202                                 struct name_entry *entry;
1203
1204                                 entry = name_list_key_add(&udev->env_list, key_name, temp_value);
1205                                 if (entry == NULL)
1206                                         break;
1207                                 putenv(entry->name);
1208                                 info("set ENV '%s'", entry->name);
1209                         }
1210                 }
1211         }
1212
1213         /* if we have ATTR assignments, write value to sysfs file */
1214         for (i = 0; i < rule->attr.count; i++) {
1215                 struct key_pair *pair = &rule->attr.keys[i];
1216
1217                 if (pair->key.operation == KEY_OP_ASSIGN) {
1218                         const char *key_name = key_pair_name(rule, pair);
1219                         char devpath[PATH_SIZE];
1220                         char *attrib;
1221                         char attr[PATH_SIZE] = "";
1222                         char value[NAME_SIZE];
1223                         FILE *f;
1224
1225                         if (attr_get_by_subsys_id(key_name, devpath, sizeof(devpath), &attrib)) {
1226                                 if (attrib != NULL) {
1227                                         strlcpy(attr, sysfs_path, sizeof(attr));
1228                                         strlcat(attr, devpath, sizeof(attr));
1229                                         strlcat(attr, "/", sizeof(attr));
1230                                         strlcat(attr, attrib, sizeof(attr));
1231                                 }
1232                         }
1233
1234                         if (attr[0] == '\0') {
1235                                 strlcpy(attr, sysfs_path, sizeof(attr));
1236                                 strlcat(attr, udev->dev->devpath, sizeof(attr));
1237                                 strlcat(attr, "/", sizeof(attr));
1238                                 strlcat(attr, key_name, sizeof(attr));
1239                         }
1240
1241                         strlcpy(value, key_val(rule, &pair->key), sizeof(value));
1242                         udev_rules_apply_format(udev, value, sizeof(value));
1243                         info("writing '%s' to sysfs file '%s'", value, attr);
1244                         f = fopen(attr, "w");
1245                         if (f != NULL) {
1246                                 if (!udev->test_run)
1247                                         if (fprintf(f, "%s", value) <= 0)
1248                                                 err("error writing ATTR{%s}: %s", attr, strerror(errno));
1249                                 fclose(f);
1250                         } else
1251                                 err("error opening ATTR{%s} for writing: %s", attr, strerror(errno));
1252                 }
1253         }
1254         return 0;
1255
1256 nomatch:
1257         return -1;
1258 }
1259
1260 int udev_rules_get_name(struct udev_rules *rules, struct udevice *udev)
1261 {
1262         struct udev_rule *rule;
1263         int name_set = 0;
1264
1265         dbg("udev->dev->devpath='%s'", udev->dev->devpath);
1266         dbg("udev->dev->kernel='%s'", udev->dev->kernel);
1267
1268         /* use kernel name as default node name */
1269         strlcpy(udev->name, udev->dev->kernel, sizeof(udev->name));
1270
1271         /* look for a matching rule to apply */
1272         udev_rules_iter_init(rules);
1273         while (1) {
1274                 rule = udev_rules_iter_next(rules);
1275                 if (rule == NULL)
1276                         break;
1277
1278                 if (name_set &&
1279                     (rule->name.operation == KEY_OP_ASSIGN ||
1280                      rule->name.operation == KEY_OP_ASSIGN_FINAL ||
1281                      rule->name.operation == KEY_OP_ADD)) {
1282                         dbg("node name already set, rule ignored");
1283                         continue;
1284                 }
1285
1286                 dbg("process rule");
1287                 if (match_rule(udev, rule) == 0) {
1288                         /* apply options */
1289                         if (rule->ignore_device) {
1290                                 info("rule applied, '%s' is ignored", udev->dev->kernel);
1291                                 udev->ignore_device = 1;
1292                                 return 0;
1293                         }
1294                         if (rule->ignore_remove) {
1295                                 udev->ignore_remove = 1;
1296                                 dbg("remove event should be ignored");
1297                         }
1298                         if (rule->link_priority != 0) {
1299                                 udev->link_priority = rule->link_priority;
1300                                 info("link_priority=%i", udev->link_priority);
1301                         }
1302                         /* apply all_partitions option only at a main block device */
1303                         if (rule->partitions &&
1304                             strcmp(udev->dev->subsystem, "block") == 0 && udev->dev->kernel_number[0] == '\0') {
1305                                 udev->partitions = rule->partitions;
1306                                 dbg("creation of partition nodes requested");
1307                         }
1308
1309                         /* apply permissions */
1310                         if (!udev->mode_final && rule->mode != 0000) {
1311                                 if (rule->mode_operation == KEY_OP_ASSIGN_FINAL)
1312                                         udev->mode_final = 1;
1313                                 udev->mode = rule->mode;
1314                                 dbg("applied mode=%#o to '%s'", rule->mode, udev->dev->kernel);
1315                         }
1316                         if (!udev->owner_final && rule->owner.operation != KEY_OP_UNSET) {
1317                                 if (rule->owner.operation == KEY_OP_ASSIGN_FINAL)
1318                                         udev->owner_final = 1;
1319                                 strlcpy(udev->owner, key_val(rule, &rule->owner), sizeof(udev->owner));
1320                                 udev_rules_apply_format(udev, udev->owner, sizeof(udev->owner));
1321                                 dbg("applied owner='%s' to '%s'", udev->owner, udev->dev->kernel);
1322                         }
1323                         if (!udev->group_final && rule->group.operation != KEY_OP_UNSET) {
1324                                 if (rule->group.operation == KEY_OP_ASSIGN_FINAL)
1325                                         udev->group_final = 1;
1326                                 strlcpy(udev->group, key_val(rule, &rule->group), sizeof(udev->group));
1327                                 udev_rules_apply_format(udev, udev->group, sizeof(udev->group));
1328                                 dbg("applied group='%s' to '%s'", udev->group, udev->dev->kernel);
1329                         }
1330
1331                         /* collect symlinks */
1332                         if (!udev->symlink_final &&
1333                             (rule->symlink.operation == KEY_OP_ASSIGN ||
1334                              rule->symlink.operation == KEY_OP_ASSIGN_FINAL ||
1335                              rule->symlink.operation == KEY_OP_ADD)) {
1336                                 char temp[PATH_SIZE];
1337                                 char *pos, *next;
1338                                 int count;
1339
1340                                 if (rule->symlink.operation == KEY_OP_ASSIGN_FINAL)
1341                                         udev->symlink_final = 1;
1342                                 if (rule->symlink.operation == KEY_OP_ASSIGN ||
1343                                     rule->symlink.operation == KEY_OP_ASSIGN_FINAL) {
1344                                         info("reset symlink list");
1345                                         name_list_cleanup(&udev->symlink_list);
1346                                 }
1347                                 /* allow  multiple symlinks separated by spaces */
1348                                 strlcpy(temp, key_val(rule, &rule->symlink), sizeof(temp));
1349                                 udev_rules_apply_format(udev, temp, sizeof(temp));
1350                                 if (rule->string_escape == ESCAPE_UNSET ||
1351                                     rule->string_escape == ESCAPE_REPLACE) {
1352                                         count = replace_chars(temp, ALLOWED_CHARS_FILE " ");
1353                                         if (count > 0)
1354                                                 info("%i character(s) replaced" , count);
1355                                 }
1356                                 dbg("rule applied, added symlink(s) '%s'", temp);
1357                                 pos = temp;
1358                                 while (isspace(pos[0]))
1359                                         pos++;
1360                                 next = strchr(pos, ' ');
1361                                 while (next) {
1362                                         next[0] = '\0';
1363                                         info("add symlink '%s'", pos);
1364                                         name_list_add(&udev->symlink_list, pos, 0);
1365                                         while (isspace(next[1]))
1366                                                 next++;
1367                                         pos = &next[1];
1368                                         next = strchr(pos, ' ');
1369                                 }
1370                                 if (pos[0] != '\0') {
1371                                         info("add symlink '%s'", pos);
1372                                         name_list_add(&udev->symlink_list, pos, 0);
1373                                 }
1374                         }
1375
1376                         /* set name, later rules with name set will be ignored */
1377                         if (rule->name.operation == KEY_OP_ASSIGN ||
1378                             rule->name.operation == KEY_OP_ASSIGN_FINAL ||
1379                             rule->name.operation == KEY_OP_ADD) {
1380                                 int count;
1381
1382                                 name_set = 1;
1383                                 strlcpy(udev->name, key_val(rule, &rule->name), sizeof(udev->name));
1384                                 udev_rules_apply_format(udev, udev->name, sizeof(udev->name));
1385                                 if (rule->string_escape == ESCAPE_UNSET ||
1386                                     rule->string_escape == ESCAPE_REPLACE) {
1387                                         count = replace_chars(udev->name, ALLOWED_CHARS_FILE);
1388                                         if (count > 0)
1389                                                 info("%i character(s) replaced", count);
1390                                 }
1391
1392                                 info("rule applied, '%s' becomes '%s'", udev->dev->kernel, udev->name);
1393                                 if (strcmp(udev->dev->subsystem, "net") != 0)
1394                                         dbg("name, '%s' is going to have owner='%s', group='%s', mode=%#o partitions=%i",
1395                                             udev->name, udev->owner, udev->group, udev->mode, udev->partitions);
1396                         }
1397
1398                         if (!udev->run_final && rule->run.operation != KEY_OP_UNSET) {
1399                                 struct name_entry *entry;
1400
1401                                 if (rule->run.operation == KEY_OP_ASSIGN_FINAL)
1402                                         udev->run_final = 1;
1403                                 if (rule->run.operation == KEY_OP_ASSIGN || rule->run.operation == KEY_OP_ASSIGN_FINAL) {
1404                                         info("reset run list");
1405                                         name_list_cleanup(&udev->run_list);
1406                                 }
1407                                 dbg("add run '%s'", key_val(rule, &rule->run));
1408                                 entry = name_list_add(&udev->run_list, key_val(rule, &rule->run), 0);
1409                                 if (rule->run_ignore_error)
1410                                         entry->ignore_error = 1;
1411                         }
1412
1413                         if (rule->last_rule) {
1414                                 dbg("last rule to be applied");
1415                                 break;
1416                         }
1417
1418                         if (rule->goto_label.operation != KEY_OP_UNSET) {
1419                                 dbg("moving forward to label '%s'", key_val(rule, &rule->goto_label));
1420                                 udev_rules_iter_label(rules, key_val(rule, &rule->goto_label));
1421                         }
1422                 }
1423         }
1424
1425         if (!name_set)
1426                 info("no node name set, will use kernel name '%s'", udev->name);
1427
1428         if (udev->tmp_node[0] != '\0') {
1429                 dbg("removing temporary device node");
1430                 unlink_secure(udev->tmp_node);
1431                 udev->tmp_node[0] = '\0';
1432         }
1433
1434         return 0;
1435 }
1436
1437 int udev_rules_get_run(struct udev_rules *rules, struct udevice *udev)
1438 {
1439         struct udev_rule *rule;
1440
1441         dbg("udev->kernel='%s'", udev->dev->kernel);
1442
1443         /* look for a matching rule to apply */
1444         udev_rules_iter_init(rules);
1445         while (1) {
1446                 rule = udev_rules_iter_next(rules);
1447                 if (rule == NULL)
1448                         break;
1449
1450                 dbg("process rule");
1451                 if (rule->name.operation != KEY_OP_UNSET || rule->symlink.operation != KEY_OP_UNSET ||
1452                     rule->mode_operation != KEY_OP_UNSET || rule->owner.operation != KEY_OP_UNSET ||
1453                     rule->group.operation != KEY_OP_UNSET) {
1454                         dbg("skip rule that names a device");
1455                         continue;
1456                 }
1457
1458                 if (match_rule(udev, rule) == 0) {
1459                         if (rule->ignore_device) {
1460                                 info("rule applied, '%s' is ignored", udev->dev->kernel);
1461                                 udev->ignore_device = 1;
1462                                 return 0;
1463                         }
1464
1465                         if (!udev->run_final && rule->run.operation != KEY_OP_UNSET) {
1466                                 struct name_entry *entry;
1467
1468                                 if (rule->run.operation == KEY_OP_ASSIGN ||
1469                                     rule->run.operation == KEY_OP_ASSIGN_FINAL) {
1470                                         info("reset run list");
1471                                         name_list_cleanup(&udev->run_list);
1472                                 }
1473                                 dbg("add run '%s'", key_val(rule, &rule->run));
1474                                 entry = name_list_add(&udev->run_list, key_val(rule, &rule->run), 0);
1475                                 if (rule->run_ignore_error)
1476                                         entry->ignore_error = 1;
1477                                 if (rule->run.operation == KEY_OP_ASSIGN_FINAL)
1478                                         break;
1479                         }
1480
1481                         if (rule->last_rule) {
1482                                 dbg("last rule to be applied");
1483                                 break;
1484                         }
1485
1486                         if (rule->goto_label.operation != KEY_OP_UNSET) {
1487                                 dbg("moving forward to label '%s'", key_val(rule, &rule->goto_label));
1488                                 udev_rules_iter_label(rules, key_val(rule, &rule->goto_label));
1489                         }
1490                 }
1491         }
1492
1493         return 0;
1494 }