chiark / gitweb /
Merge nss-myhostname
[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         } else {
325                 if (len > 0) {
326                         *dest = mempcpy(*dest, src, len);
327                         size -= len;
328                 }
329         }
330         *dest[0] = '\0';
331         return size;
332 }
333
334 size_t util_strpcpyf(char **dest, size_t size, const char *src, ...)
335 {
336         va_list va;
337         int i;
338
339         va_start(va, src);
340         i = vsnprintf(*dest, size, src, va);
341         if (i < (int)size) {
342                 *dest += i;
343                 size -= i;
344         } else {
345                 *dest += size;
346                 size = 0;
347         }
348         va_end(va);
349         *dest[0] = '\0';
350         return size;
351 }
352
353 /* concatenates list of strings, moves dest forward */
354 size_t util_strpcpyl(char **dest, size_t size, const char *src, ...)
355 {
356         va_list va;
357
358         va_start(va, src);
359         do {
360                 size = util_strpcpy(dest, size, src);
361                 src = va_arg(va, char *);
362         } while (src != NULL);
363         va_end(va);
364         return size;
365 }
366
367 /* copies string */
368 size_t util_strscpy(char *dest, size_t size, const char *src)
369 {
370         char *s;
371
372         s = dest;
373         return util_strpcpy(&s, size, src);
374 }
375
376 /* concatenates list of strings */
377 size_t util_strscpyl(char *dest, size_t size, const char *src, ...)
378 {
379         va_list va;
380         char *s;
381
382         va_start(va, src);
383         s = dest;
384         do {
385                 size = util_strpcpy(&s, size, src);
386                 src = va_arg(va, char *);
387         } while (src != NULL);
388         va_end(va);
389
390         return size;
391 }
392
393 /* count of characters used to encode one unicode char */
394 static int utf8_encoded_expected_len(const char *str)
395 {
396         unsigned char c = (unsigned char)str[0];
397
398         if (c < 0x80)
399                 return 1;
400         if ((c & 0xe0) == 0xc0)
401                 return 2;
402         if ((c & 0xf0) == 0xe0)
403                 return 3;
404         if ((c & 0xf8) == 0xf0)
405                 return 4;
406         if ((c & 0xfc) == 0xf8)
407                 return 5;
408         if ((c & 0xfe) == 0xfc)
409                 return 6;
410         return 0;
411 }
412
413 /* decode one unicode char */
414 static int utf8_encoded_to_unichar(const char *str)
415 {
416         int unichar;
417         int len;
418         int i;
419
420         len = utf8_encoded_expected_len(str);
421         switch (len) {
422         case 1:
423                 return (int)str[0];
424         case 2:
425                 unichar = str[0] & 0x1f;
426                 break;
427         case 3:
428                 unichar = (int)str[0] & 0x0f;
429                 break;
430         case 4:
431                 unichar = (int)str[0] & 0x07;
432                 break;
433         case 5:
434                 unichar = (int)str[0] & 0x03;
435                 break;
436         case 6:
437                 unichar = (int)str[0] & 0x01;
438                 break;
439         default:
440                 return -1;
441         }
442
443         for (i = 1; i < len; i++) {
444                 if (((int)str[i] & 0xc0) != 0x80)
445                         return -1;
446                 unichar <<= 6;
447                 unichar |= (int)str[i] & 0x3f;
448         }
449
450         return unichar;
451 }
452
453 /* expected size used to encode one unicode char */
454 static int utf8_unichar_to_encoded_len(int unichar)
455 {
456         if (unichar < 0x80)
457                 return 1;
458         if (unichar < 0x800)
459                 return 2;
460         if (unichar < 0x10000)
461                 return 3;
462         if (unichar < 0x200000)
463                 return 4;
464         if (unichar < 0x4000000)
465                 return 5;
466         return 6;
467 }
468
469 /* check if unicode char has a valid numeric range */
470 static int utf8_unichar_valid_range(int unichar)
471 {
472         if (unichar > 0x10ffff)
473                 return 0;
474         if ((unichar & 0xfffff800) == 0xd800)
475                 return 0;
476         if ((unichar > 0xfdcf) && (unichar < 0xfdf0))
477                 return 0;
478         if ((unichar & 0xffff) == 0xffff)
479                 return 0;
480         return 1;
481 }
482
483 /* validate one encoded unicode char and return its length */
484 static int utf8_encoded_valid_unichar(const char *str)
485 {
486         int len;
487         int unichar;
488         int i;
489
490         len = utf8_encoded_expected_len(str);
491         if (len == 0)
492                 return -1;
493
494         /* ascii is valid */
495         if (len == 1)
496                 return 1;
497
498         /* check if expected encoded chars are available */
499         for (i = 0; i < len; i++)
500                 if ((str[i] & 0x80) != 0x80)
501                         return -1;
502
503         unichar = utf8_encoded_to_unichar(str);
504
505         /* check if encoded length matches encoded value */
506         if (utf8_unichar_to_encoded_len(unichar) != len)
507                 return -1;
508
509         /* check if value has valid range */
510         if (!utf8_unichar_valid_range(unichar))
511                 return -1;
512
513         return len;
514 }
515
516 int util_replace_whitespace(const char *str, char *to, size_t len)
517 {
518         size_t i, j;
519
520         /* strip trailing whitespace */
521         len = strnlen(str, len);
522         while (len && isspace(str[len-1]))
523                 len--;
524
525         /* strip leading whitespace */
526         i = 0;
527         while (isspace(str[i]) && (i < len))
528                 i++;
529
530         j = 0;
531         while (i < len) {
532                 /* substitute multiple whitespace with a single '_' */
533                 if (isspace(str[i])) {
534                         while (isspace(str[i]))
535                                 i++;
536                         to[j++] = '_';
537                 }
538                 to[j++] = str[i++];
539         }
540         to[j] = '\0';
541         return 0;
542 }
543
544 static int is_whitelisted(char c, const char *white)
545 {
546         if ((c >= '0' && c <= '9') ||
547             (c >= 'A' && c <= 'Z') ||
548             (c >= 'a' && c <= 'z') ||
549             strchr("#+-.:=@_", c) != NULL ||
550             (white != NULL && strchr(white, c) != NULL))
551                 return 1;
552         return 0;
553 }
554
555 /* allow chars in whitelist, plain ascii, hex-escaping and valid utf8 */
556 int util_replace_chars(char *str, const char *white)
557 {
558         size_t i = 0;
559         int replaced = 0;
560
561         while (str[i] != '\0') {
562                 int len;
563
564                 if (is_whitelisted(str[i], white)) {
565                         i++;
566                         continue;
567                 }
568
569                 /* accept hex encoding */
570                 if (str[i] == '\\' && str[i+1] == 'x') {
571                         i += 2;
572                         continue;
573                 }
574
575                 /* accept valid utf8 */
576                 len = utf8_encoded_valid_unichar(&str[i]);
577                 if (len > 1) {
578                         i += len;
579                         continue;
580                 }
581
582                 /* if space is allowed, replace whitespace with ordinary space */
583                 if (isspace(str[i]) && white != NULL && strchr(white, ' ') != NULL) {
584                         str[i] = ' ';
585                         i++;
586                         replaced++;
587                         continue;
588                 }
589
590                 /* everything else is replaced with '_' */
591                 str[i] = '_';
592                 i++;
593                 replaced++;
594         }
595         return replaced;
596 }
597
598 /**
599  * udev_util_encode_string:
600  * @str: input string to be encoded
601  * @str_enc: output string to store the encoded input string
602  * @len: maximum size of the output string, which may be
603  *       four times as long as the input string
604  *
605  * Encode all potentially unsafe characters of a string to the
606  * corresponding 2 char hex value prefixed by '\x'.
607  *
608  * Returns: 0 if the entire string was copied, non-zero otherwise.
609  **/
610 _public_ int udev_util_encode_string(const char *str, char *str_enc, size_t len)
611 {
612         size_t i, j;
613
614         if (str == NULL || str_enc == NULL)
615                 return -1;
616
617         for (i = 0, j = 0; str[i] != '\0'; i++) {
618                 int seqlen;
619
620                 seqlen = utf8_encoded_valid_unichar(&str[i]);
621                 if (seqlen > 1) {
622                         if (len-j < (size_t)seqlen)
623                                 goto err;
624                         memcpy(&str_enc[j], &str[i], seqlen);
625                         j += seqlen;
626                         i += (seqlen-1);
627                 } else if (str[i] == '\\' || !is_whitelisted(str[i], NULL)) {
628                         if (len-j < 4)
629                                 goto err;
630                         sprintf(&str_enc[j], "\\x%02x", (unsigned char) str[i]);
631                         j += 4;
632                 } else {
633                         if (len-j < 1)
634                                 goto err;
635                         str_enc[j] = str[i];
636                         j++;
637                 }
638         }
639         if (len-j < 1)
640                 goto err;
641         str_enc[j] = '\0';
642         return 0;
643 err:
644         return -1;
645 }
646
647 /*
648  * http://sites.google.com/site/murmurhash/
649  *
650  * All code is released to the public domain. For business purposes,
651  * Murmurhash is under the MIT license.
652  *
653  */
654 static unsigned int murmur_hash2(const char *key, int len, unsigned int seed)
655 {
656         /*
657          *  'm' and 'r' are mixing constants generated offline.
658          *  They're not really 'magic', they just happen to work well.
659          */
660         const unsigned int m = 0x5bd1e995;
661         const int r = 24;
662
663         /* initialize the hash to a 'random' value */
664         unsigned int h = seed ^ len;
665
666         /* mix 4 bytes at a time into the hash */
667         const unsigned char * data = (const unsigned char *)key;
668
669         while(len >= 4) {
670                 unsigned int k = *(unsigned int *)data;
671
672                 k *= m;
673                 k ^= k >> r;
674                 k *= m;
675                 h *= m;
676                 h ^= k;
677
678                 data += 4;
679                 len -= 4;
680         }
681
682         /* handle the last few bytes of the input array */
683         switch(len) {
684         case 3:
685                 h ^= data[2] << 16;
686         case 2:
687                 h ^= data[1] << 8;
688         case 1:
689                 h ^= data[0];
690                 h *= m;
691         };
692
693         /* do a few final mixes of the hash to ensure the last few bytes are well-incorporated */
694         h ^= h >> 13;
695         h *= m;
696         h ^= h >> 15;
697
698         return h;
699 }
700
701 unsigned int util_string_hash32(const char *str)
702 {
703         return murmur_hash2(str, strlen(str), 0);
704 }
705
706 /* get a bunch of bit numbers out of the hash, and set the bits in our bit field */
707 uint64_t util_string_bloom64(const char *str)
708 {
709         uint64_t bits = 0;
710         unsigned int hash = util_string_hash32(str);
711
712         bits |= 1LLU << (hash & 63);
713         bits |= 1LLU << ((hash >> 6) & 63);
714         bits |= 1LLU << ((hash >> 12) & 63);
715         bits |= 1LLU << ((hash >> 18) & 63);
716         return bits;
717 }
718
719 ssize_t print_kmsg(const char *fmt, ...)
720 {
721         int fd;
722         va_list ap;
723         char text[1024];
724         ssize_t len;
725         ssize_t ret;
726
727         fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
728         if (fd < 0)
729                 return -errno;
730
731         len = snprintf(text, sizeof(text), "<30>systemd-udevd[%u]: ", getpid());
732
733         va_start(ap, fmt);
734         len += vsnprintf(text + len, sizeof(text) - len, fmt, ap);
735         va_end(ap);
736
737         ret = write(fd, text, len);
738         if (ret < 0)
739                 ret = -errno;
740         close(fd);
741         return ret;
742 }