chiark / gitweb /
udev: replace util_create_path() with mkdir_parents()
[elogind.git] / src / libudev / libudev-util.c
1 /*
2  * libudev - interface to udev device information
3  *
4  * Copyright (C) 2008-2011 Kay Sievers <kay.sievers@vrfy.org>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  */
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <stddef.h>
15 #include <unistd.h>
16 #include <errno.h>
17 #include <string.h>
18 #include <dirent.h>
19 #include <ctype.h>
20 #include <fcntl.h>
21 #include <time.h>
22 #include <pwd.h>
23 #include <grp.h>
24 #include <sys/stat.h>
25 #include <sys/param.h>
26
27 #include "libudev.h"
28 #include "libudev-private.h"
29
30 /**
31  * SECTION:libudev-util
32  * @short_description: utils
33  */
34
35 int util_delete_path(struct udev *udev, const char *path)
36 {
37         char p[UTIL_PATH_SIZE];
38         char *pos;
39         int err = 0;
40
41         if (path[0] == '/')
42                 while(path[1] == '/')
43                         path++;
44         util_strscpy(p, sizeof(p), path);
45         pos = strrchr(p, '/');
46         if (pos == p || pos == NULL)
47                 return 0;
48
49         for (;;) {
50                 *pos = '\0';
51                 pos = strrchr(p, '/');
52
53                 /* don't remove the last one */
54                 if ((pos == p) || (pos == NULL))
55                         break;
56
57                 err = rmdir(p);
58                 if (err < 0) {
59                         if (errno == ENOENT)
60                                 err = 0;
61                         break;
62                 }
63         }
64         return err;
65 }
66
67 uid_t util_lookup_user(struct udev *udev, const char *user)
68 {
69         char *endptr;
70         struct passwd pwbuf;
71         struct passwd *pw;
72         uid_t uid;
73         size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
74         char *buf = alloca(buflen);
75
76         if (strcmp(user, "root") == 0)
77                 return 0;
78         uid = strtoul(user, &endptr, 10);
79         if (endptr[0] == '\0')
80                 return uid;
81
82         errno = getpwnam_r(user, &pwbuf, buf, buflen, &pw);
83         if (pw != NULL)
84                 return pw->pw_uid;
85         if (errno == 0 || errno == ENOENT || errno == ESRCH)
86                 err(udev, "specified user '%s' unknown\n", user);
87         else
88                 err(udev, "error resolving user '%s': %m\n", user);
89         return 0;
90 }
91
92 gid_t util_lookup_group(struct udev *udev, const char *group)
93 {
94         char *endptr;
95         struct group grbuf;
96         struct group *gr;
97         gid_t gid = 0;
98         size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
99         char *buf = NULL;
100
101         if (strcmp(group, "root") == 0)
102                 return 0;
103         gid = strtoul(group, &endptr, 10);
104         if (endptr[0] == '\0')
105                 return gid;
106         gid = 0;
107         for (;;) {
108                 char *newbuf;
109
110                 newbuf = realloc(buf, buflen);
111                 if (!newbuf)
112                         break;
113                 buf = newbuf;
114                 errno = getgrnam_r(group, &grbuf, buf, buflen, &gr);
115                 if (gr != NULL) {
116                         gid = gr->gr_gid;
117                 } else if (errno == ERANGE) {
118                         buflen *= 2;
119                         continue;
120                 } else if (errno == 0 || errno == ENOENT || errno == ESRCH) {
121                         err(udev, "specified group '%s' unknown\n", group);
122                 } else {
123                         err(udev, "error resolving group '%s': %m\n", group);
124                 }
125                 break;
126         }
127         free(buf);
128         return gid;
129 }
130
131 /* handle "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
132 int util_resolve_subsys_kernel(struct udev *udev, const char *string,
133                                char *result, size_t maxsize, int read_value)
134 {
135         char temp[UTIL_PATH_SIZE];
136         char *subsys;
137         char *sysname;
138         struct udev_device *dev;
139         char *attr;
140
141         if (string[0] != '[')
142                 return -1;
143
144         util_strscpy(temp, sizeof(temp), string);
145
146         subsys = &temp[1];
147
148         sysname = strchr(subsys, '/');
149         if (sysname == NULL)
150                 return -1;
151         sysname[0] = '\0';
152         sysname = &sysname[1];
153
154         attr = strchr(sysname, ']');
155         if (attr == NULL)
156                 return -1;
157         attr[0] = '\0';
158         attr = &attr[1];
159         if (attr[0] == '/')
160                 attr = &attr[1];
161         if (attr[0] == '\0')
162                 attr = NULL;
163
164         if (read_value && attr == NULL)
165                 return -1;
166
167         dev = udev_device_new_from_subsystem_sysname(udev, subsys, sysname);
168         if (dev == NULL)
169                 return -1;
170
171         if (read_value) {
172                 const char *val;
173
174                 val = udev_device_get_sysattr_value(dev, attr);
175                 if (val != NULL)
176                         util_strscpy(result, maxsize, val);
177                 else
178                         result[0] = '\0';
179                 dbg(udev, "value '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
180         } else {
181                 size_t l;
182                 char *s;
183
184                 s = result;
185                 l = util_strpcpyl(&s, maxsize, udev_device_get_syspath(dev), NULL);
186                 if (attr != NULL)
187                         util_strpcpyl(&s, l, "/", attr, NULL);
188                 dbg(udev, "path '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
189         }
190         udev_device_unref(dev);
191         return 0;
192 }
193 ssize_t util_get_sys_core_link_value(struct udev *udev, const char *slink, const char *syspath, char *value, size_t size)
194 {
195         char path[UTIL_PATH_SIZE];
196         char target[UTIL_PATH_SIZE];
197         ssize_t len;
198         const char *pos;
199
200         util_strscpyl(path, sizeof(path), syspath, "/", slink, NULL);
201         len = readlink(path, target, sizeof(target));
202         if (len <= 0 || len == (ssize_t)sizeof(target))
203                 return -1;
204         target[len] = '\0';
205         pos = strrchr(target, '/');
206         if (pos == NULL)
207                 return -1;
208         pos = &pos[1];
209         return util_strscpy(value, size, pos);
210 }
211
212 int util_resolve_sys_link(struct udev *udev, char *syspath, size_t size)
213 {
214         char link_target[UTIL_PATH_SIZE];
215
216         ssize_t len;
217         int i;
218         int back;
219         char *base = NULL;
220
221         len = readlink(syspath, link_target, sizeof(link_target));
222         if (len <= 0 || len == (ssize_t)sizeof(link_target))
223                 return -1;
224         link_target[len] = '\0';
225
226         for (back = 0; startswith(&link_target[back * 3], "../"); back++)
227                 ;
228         for (i = 0; i <= back; i++) {
229                 base = strrchr(syspath, '/');
230                 if (base == NULL)
231                         return -EINVAL;
232                 base[0] = '\0';
233         }
234         if (base == NULL)
235                 return -EINVAL;
236         util_strscpyl(base, size - (base - syspath), "/", &link_target[back * 3], NULL);
237         return 0;
238 }
239
240 int util_log_priority(const char *priority)
241 {
242         char *endptr;
243         int prio;
244
245         prio = strtol(priority, &endptr, 10);
246         if (endptr[0] == '\0' || isspace(endptr[0]))
247                 return prio;
248         if (startswith(priority, "err"))
249                 return LOG_ERR;
250         if (startswith(priority, "info"))
251                 return LOG_INFO;
252         if (startswith(priority, "debug"))
253                 return LOG_DEBUG;
254         return 0;
255 }
256
257 size_t util_path_encode(const char *src, char *dest, size_t size)
258 {
259         size_t i, j;
260
261         for (i = 0, j = 0; src[i] != '\0'; i++) {
262                 if (src[i] == '/') {
263                         if (j+4 >= size) {
264                                 j = 0;
265                                 break;
266                         }
267                         memcpy(&dest[j], "\\x2f", 4);
268                         j += 4;
269                 } else if (src[i] == '\\') {
270                         if (j+4 >= size) {
271                                 j = 0;
272                                 break;
273                         }
274                         memcpy(&dest[j], "\\x5c", 4);
275                         j += 4;
276                 } else {
277                         if (j+1 >= size) {
278                                 j = 0;
279                                 break;
280                         }
281                         dest[j] = src[i];
282                         j++;
283                 }
284         }
285         dest[j] = '\0';
286         return j;
287 }
288
289 size_t util_path_decode(char *s)
290 {
291         size_t i, j;
292
293         for (i = 0, j = 0; s[i] != '\0'; j++) {
294                 if (memcmp(&s[i], "\\x2f", 4) == 0) {
295                         s[j] = '/';
296                         i += 4;
297                 } else if (memcmp(&s[i], "\\x5c", 4) == 0) {
298                         s[j] = '\\';
299                         i += 4;
300                 } else {
301                         s[j] = s[i];
302                         i++;
303                 }
304         }
305         s[j] = '\0';
306         return j;
307 }
308
309 void util_remove_trailing_chars(char *path, char c)
310 {
311         size_t len;
312
313         if (path == NULL)
314                 return;
315         len = strlen(path);
316         while (len > 0 && path[len-1] == c)
317                 path[--len] = '\0';
318 }
319
320 /*
321  * Concatenates strings. In any case, terminates in _all_ cases with '\0'
322  * and moves the @dest pointer forward to the added '\0'. Returns the
323  * remaining size, and 0 if the string was truncated.
324  */
325 size_t util_strpcpy(char **dest, size_t size, const char *src)
326 {
327         size_t len;
328
329         len = strlen(src);
330         if (len >= size) {
331                 if (size > 1)
332                         *dest = mempcpy(*dest, src, size-1);
333                 size = 0;
334                 *dest[0] = '\0';
335         } else {
336                 if (len > 0) {
337                         *dest = mempcpy(*dest, src, len);
338                         size -= len;
339                 }
340                 *dest[0] = '\0';
341         }
342         return size;
343 }
344
345 /* concatenates list of strings, moves dest forward */
346 size_t util_strpcpyl(char **dest, size_t size, const char *src, ...)
347 {
348         va_list va;
349
350         va_start(va, src);
351         do {
352                 size = util_strpcpy(dest, size, src);
353                 src = va_arg(va, char *);
354         } while (src != NULL);
355         va_end(va);
356
357         return size;
358 }
359
360 /* copies string */
361 size_t util_strscpy(char *dest, size_t size, const char *src)
362 {
363         char *s;
364
365         s = dest;
366         return util_strpcpy(&s, size, src);
367 }
368
369 /* concatenates list of strings */
370 size_t util_strscpyl(char *dest, size_t size, const char *src, ...)
371 {
372         va_list va;
373         char *s;
374
375         va_start(va, src);
376         s = dest;
377         do {
378                 size = util_strpcpy(&s, size, src);
379                 src = va_arg(va, char *);
380         } while (src != NULL);
381         va_end(va);
382
383         return size;
384 }
385
386 /* count of characters used to encode one unicode char */
387 static int utf8_encoded_expected_len(const char *str)
388 {
389         unsigned char c = (unsigned char)str[0];
390
391         if (c < 0x80)
392                 return 1;
393         if ((c & 0xe0) == 0xc0)
394                 return 2;
395         if ((c & 0xf0) == 0xe0)
396                 return 3;
397         if ((c & 0xf8) == 0xf0)
398                 return 4;
399         if ((c & 0xfc) == 0xf8)
400                 return 5;
401         if ((c & 0xfe) == 0xfc)
402                 return 6;
403         return 0;
404 }
405
406 /* decode one unicode char */
407 static int utf8_encoded_to_unichar(const char *str)
408 {
409         int unichar;
410         int len;
411         int i;
412
413         len = utf8_encoded_expected_len(str);
414         switch (len) {
415         case 1:
416                 return (int)str[0];
417         case 2:
418                 unichar = str[0] & 0x1f;
419                 break;
420         case 3:
421                 unichar = (int)str[0] & 0x0f;
422                 break;
423         case 4:
424                 unichar = (int)str[0] & 0x07;
425                 break;
426         case 5:
427                 unichar = (int)str[0] & 0x03;
428                 break;
429         case 6:
430                 unichar = (int)str[0] & 0x01;
431                 break;
432         default:
433                 return -1;
434         }
435
436         for (i = 1; i < len; i++) {
437                 if (((int)str[i] & 0xc0) != 0x80)
438                         return -1;
439                 unichar <<= 6;
440                 unichar |= (int)str[i] & 0x3f;
441         }
442
443         return unichar;
444 }
445
446 /* expected size used to encode one unicode char */
447 static int utf8_unichar_to_encoded_len(int unichar)
448 {
449         if (unichar < 0x80)
450                 return 1;
451         if (unichar < 0x800)
452                 return 2;
453         if (unichar < 0x10000)
454                 return 3;
455         if (unichar < 0x200000)
456                 return 4;
457         if (unichar < 0x4000000)
458                 return 5;
459         return 6;
460 }
461
462 /* check if unicode char has a valid numeric range */
463 static int utf8_unichar_valid_range(int unichar)
464 {
465         if (unichar > 0x10ffff)
466                 return 0;
467         if ((unichar & 0xfffff800) == 0xd800)
468                 return 0;
469         if ((unichar > 0xfdcf) && (unichar < 0xfdf0))
470                 return 0;
471         if ((unichar & 0xffff) == 0xffff)
472                 return 0;
473         return 1;
474 }
475
476 /* validate one encoded unicode char and return its length */
477 static int utf8_encoded_valid_unichar(const char *str)
478 {
479         int len;
480         int unichar;
481         int i;
482
483         len = utf8_encoded_expected_len(str);
484         if (len == 0)
485                 return -1;
486
487         /* ascii is valid */
488         if (len == 1)
489                 return 1;
490
491         /* check if expected encoded chars are available */
492         for (i = 0; i < len; i++)
493                 if ((str[i] & 0x80) != 0x80)
494                         return -1;
495
496         unichar = utf8_encoded_to_unichar(str);
497
498         /* check if encoded length matches encoded value */
499         if (utf8_unichar_to_encoded_len(unichar) != len)
500                 return -1;
501
502         /* check if value has valid range */
503         if (!utf8_unichar_valid_range(unichar))
504                 return -1;
505
506         return len;
507 }
508
509 int util_replace_whitespace(const char *str, char *to, size_t len)
510 {
511         size_t i, j;
512
513         /* strip trailing whitespace */
514         len = strnlen(str, len);
515         while (len && isspace(str[len-1]))
516                 len--;
517
518         /* strip leading whitespace */
519         i = 0;
520         while (isspace(str[i]) && (i < len))
521                 i++;
522
523         j = 0;
524         while (i < len) {
525                 /* substitute multiple whitespace with a single '_' */
526                 if (isspace(str[i])) {
527                         while (isspace(str[i]))
528                                 i++;
529                         to[j++] = '_';
530                 }
531                 to[j++] = str[i++];
532         }
533         to[j] = '\0';
534         return 0;
535 }
536
537 static int is_whitelisted(char c, const char *white)
538 {
539         if ((c >= '0' && c <= '9') ||
540             (c >= 'A' && c <= 'Z') ||
541             (c >= 'a' && c <= 'z') ||
542             strchr("#+-.:=@_", c) != NULL ||
543             (white != NULL && strchr(white, c) != NULL))
544                 return 1;
545         return 0;
546 }
547
548 /* allow chars in whitelist, plain ascii, hex-escaping and valid utf8 */
549 int util_replace_chars(char *str, const char *white)
550 {
551         size_t i = 0;
552         int replaced = 0;
553
554         while (str[i] != '\0') {
555                 int len;
556
557                 if (is_whitelisted(str[i], white)) {
558                         i++;
559                         continue;
560                 }
561
562                 /* accept hex encoding */
563                 if (str[i] == '\\' && str[i+1] == 'x') {
564                         i += 2;
565                         continue;
566                 }
567
568                 /* accept valid utf8 */
569                 len = utf8_encoded_valid_unichar(&str[i]);
570                 if (len > 1) {
571                         i += len;
572                         continue;
573                 }
574
575                 /* if space is allowed, replace whitespace with ordinary space */
576                 if (isspace(str[i]) && white != NULL && strchr(white, ' ') != NULL) {
577                         str[i] = ' ';
578                         i++;
579                         replaced++;
580                         continue;
581                 }
582
583                 /* everything else is replaced with '_' */
584                 str[i] = '_';
585                 i++;
586                 replaced++;
587         }
588         return replaced;
589 }
590
591 /**
592  * udev_util_encode_string:
593  * @str: input string to be encoded
594  * @str_enc: output string to store the encoded input string
595  * @len: maximum size of the output string, which may be
596  *       four times as long as the input string
597  *
598  * Encode all potentially unsafe characters of a string to the
599  * corresponding 2 char hex value prefixed by '\x'.
600  *
601  * Returns: 0 if the entire string was copied, non-zero otherwise.
602  **/
603 _public_ int udev_util_encode_string(const char *str, char *str_enc, size_t len)
604 {
605         size_t i, j;
606
607         if (str == NULL || str_enc == NULL)
608                 return -1;
609
610         for (i = 0, j = 0; str[i] != '\0'; i++) {
611                 int seqlen;
612
613                 seqlen = utf8_encoded_valid_unichar(&str[i]);
614                 if (seqlen > 1) {
615                         if (len-j < (size_t)seqlen)
616                                 goto err;
617                         memcpy(&str_enc[j], &str[i], seqlen);
618                         j += seqlen;
619                         i += (seqlen-1);
620                 } else if (str[i] == '\\' || !is_whitelisted(str[i], NULL)) {
621                         if (len-j < 4)
622                                 goto err;
623                         sprintf(&str_enc[j], "\\x%02x", (unsigned char) str[i]);
624                         j += 4;
625                 } else {
626                         if (len-j < 1)
627                                 goto err;
628                         str_enc[j] = str[i];
629                         j++;
630                 }
631         }
632         if (len-j < 1)
633                 goto err;
634         str_enc[j] = '\0';
635         return 0;
636 err:
637         return -1;
638 }
639
640 /*
641  * http://sites.google.com/site/murmurhash/
642  *
643  * All code is released to the public domain. For business purposes,
644  * Murmurhash is under the MIT license.
645  *
646  */
647 static unsigned int murmur_hash2(const char *key, int len, unsigned int seed)
648 {
649         /*
650          *  'm' and 'r' are mixing constants generated offline.
651          *  They're not really 'magic', they just happen to work well.
652          */
653         const unsigned int m = 0x5bd1e995;
654         const int r = 24;
655
656         /* initialize the hash to a 'random' value */
657         unsigned int h = seed ^ len;
658
659         /* mix 4 bytes at a time into the hash */
660         const unsigned char * data = (const unsigned char *)key;
661
662         while(len >= 4) {
663                 unsigned int k = *(unsigned int *)data;
664
665                 k *= m;
666                 k ^= k >> r;
667                 k *= m;
668                 h *= m;
669                 h ^= k;
670
671                 data += 4;
672                 len -= 4;
673         }
674
675         /* handle the last few bytes of the input array */
676         switch(len) {
677         case 3:
678                 h ^= data[2] << 16;
679         case 2:
680                 h ^= data[1] << 8;
681         case 1:
682                 h ^= data[0];
683                 h *= m;
684         };
685
686         /* do a few final mixes of the hash to ensure the last few bytes are well-incorporated */
687         h ^= h >> 13;
688         h *= m;
689         h ^= h >> 15;
690
691         return h;
692 }
693
694 unsigned int util_string_hash32(const char *str)
695 {
696         return murmur_hash2(str, strlen(str), 0);
697 }
698
699 /* get a bunch of bit numbers out of the hash, and set the bits in our bit field */
700 uint64_t util_string_bloom64(const char *str)
701 {
702         uint64_t bits = 0;
703         unsigned int hash = util_string_hash32(str);
704
705         bits |= 1LLU << (hash & 63);
706         bits |= 1LLU << ((hash >> 6) & 63);
707         bits |= 1LLU << ((hash >> 12) & 63);
708         bits |= 1LLU << ((hash >> 18) & 63);
709         return bits;
710 }
711
712 #define USEC_PER_SEC  1000000ULL
713 #define NSEC_PER_USEC 1000ULL
714 unsigned long long ts_usec(const struct timespec *ts)
715 {
716         return (unsigned long long) ts->tv_sec * USEC_PER_SEC +
717                (unsigned long long) ts->tv_nsec / NSEC_PER_USEC;
718 }
719
720 unsigned long long now_usec(void)
721 {
722         struct timespec ts;
723
724         if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
725                 return 0;
726         return ts_usec(&ts);
727 }