chiark / gitweb /
Merge gregkh@ehlo.org:/home/kay/public_html/pub/scm/linux/hotplug/udev-kay
[elogind.git] / udev_utils.c
1 /*
2  * udev_utils.c - generic stuff used by udev
3  *
4  * Copyright (C) 2004-2005 Kay Sievers <kay.sievers@vrfy.org>
5  *
6  *      This program is free software; you can redistribute it and/or modify it
7  *      under the terms of the GNU General Public License as published by the
8  *      Free Software Foundation version 2 of the License.
9  * 
10  *      This program is distributed in the hope that it will be useful, but
11  *      WITHOUT ANY WARRANTY; without even the implied warranty of
12  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  *      General Public License for more details.
14  * 
15  *      You should have received a copy of the GNU General Public License along
16  *      with this program; if not, write to the Free Software Foundation, Inc.,
17  *      675 Mass Ave, Cambridge, MA 02139, USA.
18  *
19  */
20
21
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <stddef.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <errno.h>
28 #include <ctype.h>
29 #include <dirent.h>
30 #include <syslog.h>
31 #include <sys/socket.h>
32 #include <sys/un.h>
33 #include <sys/wait.h>
34 #include <sys/stat.h>
35 #include <sys/mman.h>
36 #include <sys/utsname.h>
37
38 #include "udev_libc_wrapper.h"
39 #include "udev.h"
40 #include "logging.h"
41 #include "udev_utils.h"
42 #include "list.h"
43
44 /* compare string with pattern (supports * ? [0-9] [!A-Z]) */
45 int strcmp_pattern(const char *p, const char *s)
46 {
47         if (s[0] == '\0') {
48                 while (p[0] == '*')
49                         p++;
50                 return (p[0] != '\0');
51         }
52         switch (p[0]) {
53         case '[':
54                 {
55                         int not = 0;
56                         p++;
57                         if (p[0] == '!') {
58                                 not = 1;
59                                 p++;
60                         }
61                         while ((p[0] != '\0') && (p[0] != ']')) {
62                                 int match = 0;
63                                 if (p[1] == '-') {
64                                         if ((s[0] >= p[0]) && (s[0] <= p[2]))
65                                                 match = 1;
66                                         p += 3;
67                                 } else {
68                                         match = (p[0] == s[0]);
69                                         p++;
70                                 }
71                                 if (match ^ not) {
72                                         while ((p[0] != '\0') && (p[0] != ']'))
73                                                 p++;
74                                         if (p[0] == ']')
75                                                 return strcmp_pattern(p+1, s+1);
76                                 }
77                         }
78                 }
79                 break;
80         case '*':
81                 if (strcmp_pattern(p, s+1))
82                         return strcmp_pattern(p+1, s);
83                 return 0;
84         case '\0':
85                 if (s[0] == '\0') {
86                         return 0;
87                 }
88                 break;
89         default:
90                 if ((p[0] == s[0]) || (p[0] == '?'))
91                         return strcmp_pattern(p+1, s+1);
92                 break;
93         }
94         return 1;
95 }
96
97 int string_is_true(const char *str)
98 {
99         if (strcasecmp(str, "true") == 0)
100                 return 1;
101         if (strcasecmp(str, "yes") == 0)
102                 return 1;
103         if (strcasecmp(str, "1") == 0)
104                 return 1;
105         return 0;
106 }
107
108 int log_priority(const char *priority)
109 {
110         char *endptr;
111         int prio;
112
113         prio = strtol(priority, &endptr, 10);
114         if (endptr[0] == '\0')
115                 return prio;
116         if (strncasecmp(priority, "err", 3) == 0)
117                 return LOG_ERR;
118         if (strcasecmp(priority, "info") == 0)
119                 return LOG_INFO;
120         if (strcasecmp(priority, "debug") == 0)
121                 return LOG_DEBUG;
122         if (string_is_true(priority))
123                 return LOG_ERR;
124
125         return 0;
126 }
127
128 int kernel_release_satisfactory(unsigned int version, unsigned int patchlevel, unsigned int sublevel)
129 {
130         static unsigned int kversion = 0;
131         static unsigned int kpatchlevel;
132         static unsigned int ksublevel;
133
134         if (kversion == 0) {
135                 struct utsname uts;
136                 if (uname(&uts) != 0)
137                         return -1;
138
139                 if (sscanf (uts.release, "%u.%u.%u", &kversion, &kpatchlevel, &ksublevel) != 3) {
140                         kversion = 0;
141                         return -1;
142                 }
143         }
144
145         if (kversion >= version && kpatchlevel >= patchlevel && ksublevel >= sublevel)
146                 return 1;
147         else
148                 return 0;
149 }
150
151 int create_path(const char *path)
152 {
153         char p[PATH_SIZE];
154         char *pos;
155         struct stat stats;
156
157         strcpy (p, path);
158         pos = strrchr(p, '/');
159         if (pos == p || pos == NULL)
160                 return 0;
161
162         while (pos[-1] == '/')
163                 pos--;
164
165         pos[0] = '\0';
166
167         dbg("stat '%s'\n", p);
168         if (stat (p, &stats) == 0 && (stats.st_mode & S_IFMT) == S_IFDIR)
169                 return 0;
170
171         if (create_path (p) != 0)
172                 return -1;
173
174         dbg("mkdir '%s'\n", p);
175         return mkdir(p, 0755);
176 }
177
178 /* Reset permissions on the device node, before unlinking it to make sure,
179  * that permisions of possible hard links will be removed too.
180  */
181 int unlink_secure(const char *filename)
182 {
183         int retval;
184
185         retval = chown(filename, 0, 0);
186         if (retval)
187                 dbg("chown(%s, 0, 0) failed with error '%s'", filename, strerror(errno));
188
189         retval = chmod(filename, 0000);
190         if (retval)
191                 dbg("chmod(%s, 0000) failed with error '%s'", filename, strerror(errno));
192
193         retval = unlink(filename);
194         if (errno == ENOENT)
195                 retval = 0;
196
197         if (retval)
198                 dbg("unlink(%s) failed with error '%s'", filename, strerror(errno));
199
200         return retval;
201 }
202
203 int file_map(const char *filename, char **buf, size_t *bufsize)
204 {
205         struct stat stats;
206         int fd;
207
208         fd = open(filename, O_RDONLY);
209         if (fd < 0) {
210                 return -1;
211         }
212
213         if (fstat(fd, &stats) < 0) {
214                 close(fd);
215                 return -1;
216         }
217
218         *buf = mmap(NULL, stats.st_size, PROT_READ, MAP_SHARED, fd, 0);
219         if (*buf == MAP_FAILED) {
220                 close(fd);
221                 return -1;
222         }
223         *bufsize = stats.st_size;
224
225         close(fd);
226
227         return 0;
228 }
229
230 void file_unmap(void *buf, size_t bufsize)
231 {
232         munmap(buf, bufsize);
233 }
234
235 /* return number of chars until the next newline, skip escaped newline */
236 size_t buf_get_line(const char *buf, size_t buflen, size_t cur)
237 {
238         int escape = 0;
239         size_t count;
240
241         for (count = cur; count < buflen; count++) {
242                 if (!escape && buf[count] == '\n')
243                         break;
244
245                 if (buf[count] == '\\')
246                         escape = 1;
247                 else
248                         escape = 0;
249         }
250
251         return count - cur;
252 }
253
254 void replace_untrusted_chars(char *string)
255 {
256         size_t len;
257
258         for (len = 0; string[len] != '\0'; len++) {
259                 if (strchr(";,~\\()\'", string[len])) {
260                         info("replace '%c' in '%s'", string[len], string);
261                         string[len] = '_';
262                 }
263         }
264 }
265
266 void remove_trailing_char(char *path, char c)
267 {
268         size_t len;
269
270         len = strlen(path);
271         while (len > 0 && path[len-1] == c)
272                 path[--len] = '\0';
273 }
274
275 int name_list_add(struct list_head *name_list, const char *name, int sort)
276 {
277         struct name_entry *loop_name;
278         struct name_entry *new_name;
279
280         list_for_each_entry(loop_name, name_list, node) {
281                 /* avoid doubles */
282                 if (strcmp(loop_name->name, name) == 0) {
283                         dbg("'%s' is already in the list", name);
284                         return 0;
285                 }
286         }
287
288         if (sort)
289                 list_for_each_entry(loop_name, name_list, node) {
290                         if (sort && strcmp(loop_name->name, name) > 0)
291                                 break;
292                 }
293
294         new_name = malloc(sizeof(struct name_entry));
295         if (new_name == NULL) {
296                 dbg("error malloc");
297                 return -ENOMEM;
298         }
299
300         strlcpy(new_name->name, name, sizeof(new_name->name));
301         dbg("adding '%s'", new_name->name);
302         list_add_tail(&new_name->node, &loop_name->node);
303
304         return 0;
305 }
306
307 int name_list_key_add(struct list_head *name_list, const char *key, const char *value)
308 {
309         struct name_entry *loop_name;
310         struct name_entry *new_name;
311
312         list_for_each_entry(loop_name, name_list, node) {
313                 if (strncmp(loop_name->name, key, strlen(key)) == 0) {
314                         dbg("key already present '%s', replace it", loop_name->name);
315                         snprintf(loop_name->name, sizeof(loop_name->name), "%s=%s", key, value);
316                         loop_name->name[sizeof(loop_name->name)-1] = '\0';
317                         return 0;
318                 }
319         }
320
321         new_name = malloc(sizeof(struct name_entry));
322         if (new_name == NULL) {
323                 dbg("error malloc");
324                 return -ENOMEM;
325         }
326
327         snprintf(new_name->name, sizeof(new_name->name), "%s=%s", key, value);
328         new_name->name[sizeof(new_name->name)-1] = '\0';
329         dbg("adding '%s'", new_name->name);
330         list_add_tail(&new_name->node, &loop_name->node);
331
332         return 0;
333 }
334
335 /* calls function for every file found in specified directory */
336 int add_matching_files(struct list_head *name_list, const char *dirname, const char *suffix)
337 {
338         struct dirent *ent;
339         DIR *dir;
340         char *ext;
341         char filename[PATH_SIZE];
342
343         dbg("open directory '%s'", dirname);
344         dir = opendir(dirname);
345         if (dir == NULL) {
346                 dbg("unable to open '%s'", dirname);
347                 return -1;
348         }
349
350         while (1) {
351                 ent = readdir(dir);
352                 if (ent == NULL || ent->d_name[0] == '\0')
353                         break;
354
355                 if ((ent->d_name[0] == '.') || (ent->d_name[0] == COMMENT_CHARACTER))
356                         continue;
357
358                 /* look for file matching with specified suffix */
359                 ext = strrchr(ent->d_name, '.');
360                 if (ext == NULL)
361                         continue;
362
363                 if (strcmp(ext, suffix) != 0)
364                         continue;
365
366                 dbg("put file '%s/%s' in list", dirname, ent->d_name);
367
368                 snprintf(filename, sizeof(filename), "%s/%s", dirname, ent->d_name);
369                 filename[sizeof(filename)-1] = '\0';
370                 name_list_add(name_list, filename, 1);
371         }
372
373         closedir(dir);
374         return 0;
375 }
376
377 int pass_env_to_socket(const char *sockname, const char *devpath, const char *action)
378 {
379         int sock;
380         struct sockaddr_un saddr;
381         socklen_t addrlen;
382         char buf[2048];
383         size_t bufpos = 0;
384         int i;
385         int retval;
386
387         dbg("pass environment to socket '%s'", sockname);
388         sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
389         memset(&saddr, 0x00, sizeof(struct sockaddr_un));
390         saddr.sun_family = AF_LOCAL;
391         /* only abstract namespace is supported */
392         strcpy(&saddr.sun_path[1], sockname);
393         addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
394
395         bufpos = snprintf(buf, sizeof(buf)-1, "%s@%s", action, devpath);
396         bufpos++;
397         for (i = 0; environ[i] != NULL && bufpos < sizeof(buf); i++) {
398                 bufpos += strlcpy(&buf[bufpos], environ[i], sizeof(buf) - bufpos-1);
399                 bufpos++;
400         }
401
402         retval = sendto(sock, &buf, bufpos, 0, (struct sockaddr *)&saddr, addrlen);
403         if (retval != -1)
404                 retval = 0;
405
406         close(sock);
407         return retval;
408 }
409
410 int execute_program(const char *command, const char *subsystem,
411                     char *result, size_t ressize, size_t *reslen)
412 {
413         int retval = 0;
414         int count;
415         int status;
416         int pipefds[2];
417         pid_t pid;
418         char *pos;
419         char arg[PATH_SIZE];
420         char *argv[(sizeof(arg) / 2) + 1];
421         int devnull;
422         int i;
423         size_t len;
424
425         strlcpy(arg, command, sizeof(arg));
426         i = 0;
427         if (strchr(arg, ' ')) {
428                 pos = arg;
429                 while (pos != NULL) {
430                         if (pos[0] == '\'') {
431                                 /* don't separate if in apostrophes */
432                                 pos++;
433                                 argv[i] = strsep(&pos, "\'");
434                                 while (pos && pos[0] == ' ')
435                                         pos++;
436                         } else {
437                                 argv[i] = strsep(&pos, " ");
438                         }
439                         dbg("arg[%i] '%s'", i, argv[i]);
440                         i++;
441                 }
442                 argv[i] =  NULL;
443                 dbg("execute '%s' with parsed arguments", arg);
444         } else {
445                 argv[0] = arg;
446                 argv[1] = (char *) subsystem;
447                 argv[2] = NULL;
448                 dbg("execute '%s' with subsystem '%s' argument", arg, argv[1]);
449         }
450
451         if (result) {
452                 if (pipe(pipefds) != 0) {
453                         err("pipe failed");
454                         return -1;
455                 }
456         }
457
458         pid = fork();
459         switch(pid) {
460         case 0:
461                 /* child dup2 write side of pipe to STDOUT */
462                 devnull = open("/dev/null", O_RDWR);
463                 if (devnull >= 0) {
464                         dup2(devnull, STDIN_FILENO);
465                         if (!result)
466                                 dup2(devnull, STDOUT_FILENO);
467                         dup2(devnull, STDERR_FILENO);
468                         close(devnull);
469                 }
470                 if (result)
471                         dup2(pipefds[1], STDOUT_FILENO);
472                 execv(arg, argv);
473                 err("exec of program failed");
474                 _exit(1);
475         case -1:
476                 err("fork of '%s' failed", arg);
477                 return -1;
478         default:
479                 /* parent reads from pipefds[0] */
480                 if (result) {
481                         close(pipefds[1]);
482                         len = 0;
483                         while (1) {
484                                 count = read(pipefds[0], result + len, ressize - len-1);
485                                 if (count < 0) {
486                                         err("read failed with '%s'", strerror(errno));
487                                         retval = -1;
488                                         break;
489                                 }
490
491                                 if (count == 0)
492                                         break;
493
494                                 len += count;
495                                 if (len >= ressize-1) {
496                                         err("ressize %ld too short", (long)ressize);
497                                         retval = -1;
498                                         break;
499                                 }
500                         }
501                         result[len] = '\0';
502                         close(pipefds[0]);
503                         if (reslen)
504                                 *reslen = len;
505                 }
506                 waitpid(pid, &status, 0);
507
508                 if (!WIFEXITED(status) || (WEXITSTATUS(status) != 0)) {
509                         dbg("exec program status 0x%x", status);
510                         retval = -1;
511                 }
512         }
513
514         return retval;
515 }