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