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