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