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