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