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