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