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