chiark / gitweb /
libudev: monitor- add netlink uevent support
[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), "%s@%s", action, devpath);
490         bufpos++;
491         for (i = 0; environ[i] != NULL && bufpos < (sizeof(buf)); i++) {
492                 bufpos += strlcpy(&buf[bufpos], environ[i], sizeof(buf) - bufpos);
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                                                         break;
855                                                 dev_parent = sysfs_device_get_parent(udevice->udev, 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(udevice->udev, "%i character(s) replaced\n" , count);
871                                 strlcat(string, temp2, maxsize);
872                                 dbg(udevice->udev, "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(udevice->udev, udevice->dev);
880                                 if (dev_parent != NULL) {
881                                         struct udevice *udev_parent;
882
883                                         dbg(udevice->udev, "found parent '%s', get the node name\n", dev_parent->devpath);
884                                         udev_parent = udev_device_init(udevice->udev);
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(udevice->udev, "substitute parent node name'%s'\n", udev_parent->name);
890                                                 } else
891                                                         dbg(udevice->udev, "parent not found in database\n");
892                                                 udev_device_cleanup(udev_parent);
893                                         }
894                                 }
895                         }
896                         break;
897                 case SUBST_TEMP_NODE:
898                         if (udevice->tmp_node[0] == '\0' && major(udevice->devt) > 0) {
899                                 dbg(udevice->udev, "create temporary device node for callout\n");
900                                 snprintf(udevice->tmp_node, sizeof(udevice->tmp_node), "%s/.tmp-%u-%u",
901                                          udev_get_dev_path(udevice->udev), major(udevice->devt), minor(udevice->devt));
902                                 udevice->tmp_node[sizeof(udevice->tmp_node)-1] = '\0';
903                                 udev_node_mknod(udevice, udevice->tmp_node, udevice->devt, 0600, 0, 0);
904                         }
905                         strlcat(string, udevice->tmp_node, maxsize);
906                         dbg(udevice->udev, "substitute temporary device node name '%s'\n", udevice->tmp_node);
907                         break;
908                 case SUBST_NAME:
909                         if (udevice->name[0] == '\0') {
910                                 strlcat(string, udevice->dev->kernel, maxsize);
911                                 dbg(udevice->udev, "substitute udevice->kernel '%s'\n", udevice->name);
912                         } else {
913                                 strlcat(string, udevice->name, maxsize);
914                                 dbg(udevice->udev, "substitute udevice->name '%s'\n", udevice->name);
915                         }
916                         break;
917                 case SUBST_LINKS:
918                         if (!list_empty(&udevice->symlink_list)) {
919                                 struct name_entry *name_loop;
920                                 char symlinks[PATH_SIZE] = "";
921
922                                 list_for_each_entry(name_loop, &udevice->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_get_dev_path(udevice->udev), maxsize);
932                         dbg(udevice->udev, "substitute udev_root '%s'\n", udev_get_dev_path(udevice->udev));
933                         break;
934                 case SUBST_SYS:
935                         strlcat(string, udev_get_sys_path(udevice->udev), maxsize);
936                         dbg(udevice->udev, "substitute sys_path '%s'\n", udev_get_sys_path(udevice->udev));
937                         break;
938                 case SUBST_ENV:
939                         if (attr == NULL) {
940                                 dbg(udevice->udev, "missing attribute\n");
941                                 break;
942                         }
943                         pos = getenv(attr);
944                         if (pos == NULL) {
945                                 dbg(udevice->udev, "env '%s' not available\n", attr);
946                                 break;
947                         }
948                         dbg(udevice->udev, "substitute env '%s=%s'\n", attr, pos);
949                         strlcat(string, pos, maxsize);
950                         break;
951                 default:
952                         err(udevice->udev, "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(udevice->udev, "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(struct udev *udev, 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(udev, "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(udev, "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(udev, "%s is true (matching value)\n", key_name);
1006                 return 0;
1007         }
1008         if (!match && (key->operation == KEY_OP_NOMATCH)) {
1009                 dbg(udev, "%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 *udevice, struct udev_rule *rule)
1017 {
1018         int i;
1019
1020         if (match_key(udevice->udev, "ACTION", rule, &rule->action, udevice->action))
1021                 goto nomatch;
1022
1023         if (match_key(udevice->udev, "KERNEL", rule, &rule->kernel, udevice->dev->kernel))
1024                 goto nomatch;
1025
1026         if (match_key(udevice->udev, "SUBSYSTEM", rule, &rule->subsystem, udevice->dev->subsystem))
1027                 goto nomatch;
1028
1029         if (match_key(udevice->udev, "DEVPATH", rule, &rule->devpath, udevice->dev->devpath))
1030                 goto nomatch;
1031
1032         if (match_key(udevice->udev, "DRIVER", rule, &rule->driver, udevice->dev->driver))
1033                 goto nomatch;
1034
1035         /* match NAME against a value assigned by an earlier rule */
1036         if (match_key(udevice->udev, "NAME", rule, &rule->name, udevice->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, &udevice->symlink_list, node) {
1046                         if (match_key(udevice->udev, "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(udevice->udev, "ENV{'%s'} is not set, treat as empty\n", key_name);
1066                                 value = "";
1067                         }
1068                         if (match_key(udevice->udev, "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(udevice, filename, sizeof(filename));
1083
1084                 if (attr_get_by_subsys_id(udevice->udev, filename, devpath, sizeof(devpath), &attr)) {
1085                         strlcpy(filename, udev_get_sys_path(udevice->udev), 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, udev_get_sys_path(udevice->udev), sizeof(tmp));
1095                         strlcat(tmp, udevice->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(udevice->udev, "'%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(udevice->udev, "'%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(udevice->udev, "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(udevice, filename, sizeof(filename));
1124                 found = (wait_for_file(udevice, 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(udevice->udev, key_name, devpath, sizeof(devpath), &attrib)) {
1144                                 if (attrib != NULL)
1145                                         value = sysfs_attr_get_value(udevice->udev, devpath, attrib);
1146                                 else
1147                                         goto nomatch;
1148                         }
1149                         if (value == NULL)
1150                                 value = sysfs_attr_get_value(udevice->udev, udevice->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(udevice->udev, "removed %zi trailing whitespace chars from '%s'\n", strlen(val)-len, val);
1162                         }
1163
1164                         if (match_key(udevice->udev, "ATTR", rule, &pair->key, val))
1165                                 goto nomatch;
1166                 }
1167         }
1168
1169         /* walk up the chain of parent devices and find a match */
1170         udevice->dev_parent = udevice->dev;
1171         while (1) {
1172                 /* check for matching kernel device name */
1173                 if (match_key(udevice->udev, "KERNELS", rule, &rule->kernels, udevice->dev_parent->kernel))
1174                         goto try_parent;
1175
1176                 /* check for matching subsystem value */
1177                 if (match_key(udevice->udev, "SUBSYSTEMS", rule, &rule->subsystems, udevice->dev_parent->subsystem))
1178                         goto try_parent;
1179
1180                 /* check for matching driver */
1181                 if (match_key(udevice->udev, "DRIVERS", rule, &rule->drivers, udevice->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(udevice->udev, udevice->dev_parent->devpath, key_name);
1197                                 if (value == NULL)
1198                                         value = sysfs_attr_get_value(udevice->udev, udevice->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(udevice->udev, "removed %zi trailing whitespace chars from '%s'\n", strlen(val)-len, val);
1210                                 }
1211
1212                                 if (match_key(udevice->udev, "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(udevice->udev, "try parent sysfs device\n");
1222                 udevice->dev_parent = sysfs_device_get_parent(udevice->udev, udevice->dev_parent);
1223                 if (udevice->dev_parent == NULL)
1224                         goto nomatch;
1225                 dbg(udevice->udev, "looking at dev_parent->devpath='%s'\n", udevice->dev_parent->devpath);
1226                 dbg(udevice->udev, "looking at dev_parent->kernel='%s'\n", udevice->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(udevice, program, sizeof(program));
1236                 if (run_program(udevice->udev, program, udevice->dev->subsystem, result, sizeof(result), NULL) != 0) {
1237                         dbg(udevice->udev, "PROGRAM is false\n");
1238                         udevice->program_result[0] = '\0';
1239                         if (rule->program.operation != KEY_OP_NOMATCH)
1240                                 goto nomatch;
1241                 } else {
1242                         int count;
1243
1244                         dbg(udevice->udev, "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(udevice->udev, "%i character(s) replaced\n" , count);
1251                         }
1252                         dbg(udevice->udev, "result is '%s'\n", result);
1253                         strlcpy(udevice->program_result, result, sizeof(udevice->program_result));
1254                         dbg(udevice->udev, "PROGRAM returned successful\n");
1255                         if (rule->program.operation == KEY_OP_NOMATCH)
1256                                 goto nomatch;
1257                 }
1258                 dbg(udevice->udev, "PROGRAM key is true\n");
1259         }
1260
1261         /* check for matching result of external program */
1262         if (match_key(udevice->udev, "RESULT", rule, &rule->result, udevice->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(udevice, import, sizeof(import));
1272                 dbg(udevice->udev, "check for IMPORT import='%s'\n", import);
1273                 if (rule->import_type == IMPORT_PROGRAM) {
1274                         rc = import_program_into_env(udevice, import);
1275                 } else if (rule->import_type == IMPORT_FILE) {
1276                         dbg(udevice->udev, "import file import='%s'\n", import);
1277                         rc = import_file_into_env(udevice, import);
1278                 } else if (rule->import_type == IMPORT_PARENT) {
1279                         dbg(udevice->udev, "import parent import='%s'\n", import);
1280                         rc = import_parent_into_env(udevice, import);
1281                 }
1282                 if (rc != 0) {
1283                         dbg(udevice->udev, "IMPORT failed\n");
1284                         if (rule->import.operation != KEY_OP_NOMATCH)
1285                                 goto nomatch;
1286                 } else
1287                         dbg(udevice->udev, "IMPORT '%s' imported\n", key_val(rule, &rule->import));
1288                 dbg(udevice->udev, "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(udevice, temp_value, NAME_SIZE);
1303
1304                         if (temp_value[0] == '\0') {
1305                                 name_list_key_remove(udevice->udev, &udevice->env_list, key_name);
1306                                 unsetenv(key_name);
1307                                 info(udevice->udev, "unset ENV '%s'\n", key_name);
1308                         } else {
1309                                 struct name_entry *entry;
1310
1311                                 entry = name_list_key_add(udevice->udev, &udevice->env_list, key_name, temp_value);
1312                                 if (entry == NULL)
1313                                         break;
1314                                 putenv(entry->name);
1315                                 info(udevice->udev, "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(udevice->udev, key_name, devpath, sizeof(devpath), &attrib)) {
1333                                 if (attrib != NULL) {
1334                                         strlcpy(attr, udev_get_sys_path(udevice->udev), 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, udev_get_sys_path(udevice->udev), sizeof(attr));
1343                                 strlcat(attr, udevice->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(udevice, value, sizeof(value));
1352                         info(udevice->udev, "writing '%s' to sysfs file '%s'\n", value, attr);
1353                         f = fopen(attr, "w");
1354                         if (f != NULL) {
1355                                 if (!udevice->test_run)
1356                                         if (fprintf(f, "%s", value) <= 0)
1357                                                 err(udevice->udev, "error writing ATTR{%s}: %s\n", attr, strerror(errno));
1358                                 fclose(f);
1359                         } else
1360                                 err(udevice->udev, "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 *udevice)
1370 {
1371         struct udev_rules_iter iter;
1372         struct udev_rule *rule;
1373         int name_set = 0;
1374
1375         dbg(udevice->udev, "udevice->dev->devpath='%s'\n", udevice->dev->devpath);
1376         dbg(udevice->udev, "udevice->dev->kernel='%s'\n", udevice->dev->kernel);
1377
1378         /* look for a matching rule to apply */
1379         udev_rules_iter_init(&iter, rules);
1380         while (1) {
1381                 rule = udev_rules_iter_next(&iter);
1382                 if (rule == NULL)
1383                         break;
1384
1385                 if (name_set &&
1386                     (rule->name.operation == KEY_OP_ASSIGN ||
1387                      rule->name.operation == KEY_OP_ASSIGN_FINAL ||
1388                      rule->name.operation == KEY_OP_ADD)) {
1389                         dbg(udevice->udev, "node name already set, rule ignored\n");
1390                         continue;
1391                 }
1392
1393                 dbg(udevice->udev, "process rule\n");
1394                 if (match_rule(udevice, rule) == 0) {
1395                         /* apply options */
1396                         if (rule->ignore_device) {
1397                                 info(udevice->udev, "rule applied, '%s' is ignored\n", udevice->dev->kernel);
1398                                 udevice->ignore_device = 1;
1399                                 return 0;
1400                         }
1401                         if (rule->ignore_remove) {
1402                                 udevice->ignore_remove = 1;
1403                                 dbg(udevice->udev, "remove event should be ignored\n");
1404                         }
1405                         if (rule->link_priority != 0) {
1406                                 udevice->link_priority = rule->link_priority;
1407                                 info(udevice->udev, "link_priority=%i\n", udevice->link_priority);
1408                         }
1409                         if (rule->event_timeout >= 0) {
1410                                 udevice->event_timeout = rule->event_timeout;
1411                                 info(udevice->udev, "event_timeout=%i\n", udevice->event_timeout);
1412                         }
1413                         /* apply all_partitions option only at a main block device */
1414                         if (rule->partitions &&
1415                             strcmp(udevice->dev->subsystem, "block") == 0 && udevice->dev->kernel_number[0] == '\0') {
1416                                 udevice->partitions = rule->partitions;
1417                                 dbg(udevice->udev, "creation of partition nodes requested\n");
1418                         }
1419
1420                         /* apply permissions */
1421                         if (!udevice->mode_final && rule->mode.operation != KEY_OP_UNSET) {
1422                                 if (rule->mode.operation == KEY_OP_ASSIGN_FINAL)
1423                                         udevice->mode_final = 1;
1424                                 char buf[20];
1425                                 strlcpy(buf, key_val(rule, &rule->mode), sizeof(buf));
1426                                 udev_rules_apply_format(udevice, buf, sizeof(buf));
1427                                 udevice->mode = strtol(buf, NULL, 8);
1428                                 dbg(udevice->udev, "applied mode=%#o to '%s'\n", udevice->mode, udevice->dev->kernel);
1429                         }
1430                         if (!udevice->owner_final && rule->owner.operation != KEY_OP_UNSET) {
1431                                 if (rule->owner.operation == KEY_OP_ASSIGN_FINAL)
1432                                         udevice->owner_final = 1;
1433                                 strlcpy(udevice->owner, key_val(rule, &rule->owner), sizeof(udevice->owner));
1434                                 udev_rules_apply_format(udevice, udevice->owner, sizeof(udevice->owner));
1435                                 dbg(udevice->udev, "applied owner='%s' to '%s'\n", udevice->owner, udevice->dev->kernel);
1436                         }
1437                         if (!udevice->group_final && rule->group.operation != KEY_OP_UNSET) {
1438                                 if (rule->group.operation == KEY_OP_ASSIGN_FINAL)
1439                                         udevice->group_final = 1;
1440                                 strlcpy(udevice->group, key_val(rule, &rule->group), sizeof(udevice->group));
1441                                 udev_rules_apply_format(udevice, udevice->group, sizeof(udevice->group));
1442                                 dbg(udevice->udev, "applied group='%s' to '%s'\n", udevice->group, udevice->dev->kernel);
1443                         }
1444
1445                         /* collect symlinks */
1446                         if (!udevice->symlink_final &&
1447                             (rule->symlink.operation == KEY_OP_ASSIGN ||
1448                              rule->symlink.operation == KEY_OP_ASSIGN_FINAL ||
1449                              rule->symlink.operation == KEY_OP_ADD)) {
1450                                 char temp[PATH_SIZE];
1451                                 char *pos, *next;
1452                                 int count;
1453
1454                                 if (rule->symlink.operation == KEY_OP_ASSIGN_FINAL)
1455                                         udevice->symlink_final = 1;
1456                                 if (rule->symlink.operation == KEY_OP_ASSIGN ||
1457                                     rule->symlink.operation == KEY_OP_ASSIGN_FINAL) {
1458                                         info(udevice->udev, "reset symlink list\n");
1459                                         name_list_cleanup(udevice->udev, &udevice->symlink_list);
1460                                 }
1461                                 /* allow  multiple symlinks separated by spaces */
1462                                 strlcpy(temp, key_val(rule, &rule->symlink), sizeof(temp));
1463                                 udev_rules_apply_format(udevice, temp, sizeof(temp));
1464                                 if (rule->string_escape == ESCAPE_UNSET ||
1465                                     rule->string_escape == ESCAPE_REPLACE) {
1466                                         count = replace_chars(temp, ALLOWED_CHARS_FILE " ");
1467                                         if (count > 0)
1468                                                 info(udevice->udev, "%i character(s) replaced\n" , count);
1469                                 }
1470                                 dbg(udevice->udev, "rule applied, added symlink(s) '%s'\n", temp);
1471                                 pos = temp;
1472                                 while (isspace(pos[0]))
1473                                         pos++;
1474                                 next = strchr(pos, ' ');
1475                                 while (next) {
1476                                         next[0] = '\0';
1477                                         info(udevice->udev, "add symlink '%s'\n", pos);
1478                                         name_list_add(udevice->udev, &udevice->symlink_list, pos, 0);
1479                                         while (isspace(next[1]))
1480                                                 next++;
1481                                         pos = &next[1];
1482                                         next = strchr(pos, ' ');
1483                                 }
1484                                 if (pos[0] != '\0') {
1485                                         info(udevice->udev, "add symlink '%s'\n", pos);
1486                                         name_list_add(udevice->udev, &udevice->symlink_list, pos, 0);
1487                                 }
1488                         }
1489
1490                         /* set name, later rules with name set will be ignored */
1491                         if (rule->name.operation == KEY_OP_ASSIGN ||
1492                             rule->name.operation == KEY_OP_ASSIGN_FINAL ||
1493                             rule->name.operation == KEY_OP_ADD) {
1494                                 int count;
1495
1496                                 name_set = 1;
1497                                 strlcpy(udevice->name, key_val(rule, &rule->name), sizeof(udevice->name));
1498                                 udev_rules_apply_format(udevice, udevice->name, sizeof(udevice->name));
1499                                 if (rule->string_escape == ESCAPE_UNSET ||
1500                                     rule->string_escape == ESCAPE_REPLACE) {
1501                                         count = replace_chars(udevice->name, ALLOWED_CHARS_FILE);
1502                                         if (count > 0)
1503                                                 info(udevice->udev, "%i character(s) replaced\n", count);
1504                                 }
1505
1506                                 info(udevice->udev, "rule applied, '%s' becomes '%s'\n", udevice->dev->kernel, udevice->name);
1507                                 if (strcmp(udevice->dev->subsystem, "net") != 0)
1508                                         dbg(udevice->udev, "name, '%s' is going to have owner='%s', group='%s', mode=%#o partitions=%i\n",
1509                                             udevice->name, udevice->owner, udevice->group, udevice->mode, udevice->partitions);
1510                         }
1511
1512                         if (!udevice->run_final && rule->run.operation != KEY_OP_UNSET) {
1513                                 struct name_entry *entry;
1514
1515                                 if (rule->run.operation == KEY_OP_ASSIGN_FINAL)
1516                                         udevice->run_final = 1;
1517                                 if (rule->run.operation == KEY_OP_ASSIGN || rule->run.operation == KEY_OP_ASSIGN_FINAL) {
1518                                         info(udevice->udev, "reset run list\n");
1519                                         name_list_cleanup(udevice->udev, &udevice->run_list);
1520                                 }
1521                                 dbg(udevice->udev, "add run '%s'\n", key_val(rule, &rule->run));
1522                                 entry = name_list_add(udevice->udev, &udevice->run_list, key_val(rule, &rule->run), 0);
1523                                 if (rule->run_ignore_error)
1524                                         entry->ignore_error = 1;
1525                         }
1526
1527                         if (rule->last_rule) {
1528                                 dbg(udevice->udev, "last rule to be applied\n");
1529                                 break;
1530                         }
1531
1532                         if (rule->goto_label.operation != KEY_OP_UNSET) {
1533                                 dbg(udevice->udev, "moving forward to label '%s'\n", key_val(rule, &rule->goto_label));
1534                                 udev_rules_iter_label(&iter, key_val(rule, &rule->goto_label));
1535                         }
1536                 }
1537         }
1538
1539         if (!name_set) {
1540                 info(udevice->udev, "no node name set, will use kernel name '%s'\n", udevice->dev->kernel);
1541                 strlcpy(udevice->name, udevice->dev->kernel, sizeof(udevice->name));
1542         }
1543
1544         if (udevice->tmp_node[0] != '\0') {
1545                 dbg(udevice->udev, "removing temporary device node\n");
1546                 unlink_secure(udevice->udev, udevice->tmp_node);
1547                 udevice->tmp_node[0] = '\0';
1548         }
1549
1550         return 0;
1551 }
1552
1553 int udev_rules_get_run(struct udev_rules *rules, struct udevice *udevice)
1554 {
1555         struct udev_rules_iter iter;
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(&iter, rules);
1562         while (1) {
1563                 rule = udev_rules_iter_next(&iter);
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(&iter, key_val(rule, &rule->goto_label));
1615                         }
1616                 }
1617         }
1618
1619         return 0;
1620 }