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