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