chiark / gitweb /
cryptsetup: RequiresMountsFor if source is a file
[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         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 (streq(user, "root"))
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 (streq(group, "root"))
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         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                         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 = strpcpyl(&s, maxsize, udev_device_get_syspath(dev), NULL);
196                 if (attr != NULL)
197                         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         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 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
245         strscpyl(base, size - (base - syspath), "/", &link_target[back * 3], NULL);
246         return 0;
247 }
248
249 int util_log_priority(const char *priority)
250 {
251         char *endptr;
252         int prio;
253
254         prio = strtol(priority, &endptr, 10);
255         if (endptr[0] == '\0' || isspace(endptr[0]))
256                 return prio;
257         if (startswith(priority, "err"))
258                 return LOG_ERR;
259         if (startswith(priority, "info"))
260                 return LOG_INFO;
261         if (startswith(priority, "debug"))
262                 return LOG_DEBUG;
263         return 0;
264 }
265
266 size_t util_path_encode(const char *src, char *dest, size_t size)
267 {
268         size_t i, j;
269
270         for (i = 0, j = 0; src[i] != '\0'; i++) {
271                 if (src[i] == '/') {
272                         if (j+4 >= size) {
273                                 j = 0;
274                                 break;
275                         }
276                         memcpy(&dest[j], "\\x2f", 4);
277                         j += 4;
278                 } else if (src[i] == '\\') {
279                         if (j+4 >= size) {
280                                 j = 0;
281                                 break;
282                         }
283                         memcpy(&dest[j], "\\x5c", 4);
284                         j += 4;
285                 } else {
286                         if (j+1 >= size) {
287                                 j = 0;
288                                 break;
289                         }
290                         dest[j] = src[i];
291                         j++;
292                 }
293         }
294         dest[j] = '\0';
295         return j;
296 }
297
298 void util_remove_trailing_chars(char *path, char c)
299 {
300         size_t len;
301
302         if (path == NULL)
303                 return;
304         len = strlen(path);
305         while (len > 0 && path[len-1] == c)
306                 path[--len] = '\0';
307 }
308
309 /* count of characters used to encode one unicode char */
310 static int utf8_encoded_expected_len(const char *str)
311 {
312         unsigned char c = (unsigned char)str[0];
313
314         if (c < 0x80)
315                 return 1;
316         if ((c & 0xe0) == 0xc0)
317                 return 2;
318         if ((c & 0xf0) == 0xe0)
319                 return 3;
320         if ((c & 0xf8) == 0xf0)
321                 return 4;
322         if ((c & 0xfc) == 0xf8)
323                 return 5;
324         if ((c & 0xfe) == 0xfc)
325                 return 6;
326         return 0;
327 }
328
329 /* decode one unicode char */
330 static int utf8_encoded_to_unichar(const char *str)
331 {
332         int unichar;
333         int len;
334         int i;
335
336         len = utf8_encoded_expected_len(str);
337         switch (len) {
338         case 1:
339                 return (int)str[0];
340         case 2:
341                 unichar = str[0] & 0x1f;
342                 break;
343         case 3:
344                 unichar = (int)str[0] & 0x0f;
345                 break;
346         case 4:
347                 unichar = (int)str[0] & 0x07;
348                 break;
349         case 5:
350                 unichar = (int)str[0] & 0x03;
351                 break;
352         case 6:
353                 unichar = (int)str[0] & 0x01;
354                 break;
355         default:
356                 return -1;
357         }
358
359         for (i = 1; i < len; i++) {
360                 if (((int)str[i] & 0xc0) != 0x80)
361                         return -1;
362                 unichar <<= 6;
363                 unichar |= (int)str[i] & 0x3f;
364         }
365
366         return unichar;
367 }
368
369 /* expected size used to encode one unicode char */
370 static int utf8_unichar_to_encoded_len(int unichar)
371 {
372         if (unichar < 0x80)
373                 return 1;
374         if (unichar < 0x800)
375                 return 2;
376         if (unichar < 0x10000)
377                 return 3;
378         if (unichar < 0x200000)
379                 return 4;
380         if (unichar < 0x4000000)
381                 return 5;
382         return 6;
383 }
384
385 /* check if unicode char has a valid numeric range */
386 static int utf8_unichar_valid_range(int unichar)
387 {
388         if (unichar > 0x10ffff)
389                 return 0;
390         if ((unichar & 0xfffff800) == 0xd800)
391                 return 0;
392         if ((unichar > 0xfdcf) && (unichar < 0xfdf0))
393                 return 0;
394         if ((unichar & 0xffff) == 0xffff)
395                 return 0;
396         return 1;
397 }
398
399 /* validate one encoded unicode char and return its length */
400 static int utf8_encoded_valid_unichar(const char *str)
401 {
402         int len;
403         int unichar;
404         int i;
405
406         len = utf8_encoded_expected_len(str);
407         if (len == 0)
408                 return -1;
409
410         /* ascii is valid */
411         if (len == 1)
412                 return 1;
413
414         /* check if expected encoded chars are available */
415         for (i = 0; i < len; i++)
416                 if ((str[i] & 0x80) != 0x80)
417                         return -1;
418
419         unichar = utf8_encoded_to_unichar(str);
420
421         /* check if encoded length matches encoded value */
422         if (utf8_unichar_to_encoded_len(unichar) != len)
423                 return -1;
424
425         /* check if value has valid range */
426         if (!utf8_unichar_valid_range(unichar))
427                 return -1;
428
429         return len;
430 }
431
432 int util_replace_whitespace(const char *str, char *to, size_t len)
433 {
434         size_t i, j;
435
436         /* strip trailing whitespace */
437         len = strnlen(str, len);
438         while (len && isspace(str[len-1]))
439                 len--;
440
441         /* strip leading whitespace */
442         i = 0;
443         while (isspace(str[i]) && (i < len))
444                 i++;
445
446         j = 0;
447         while (i < len) {
448                 /* substitute multiple whitespace with a single '_' */
449                 if (isspace(str[i])) {
450                         while (isspace(str[i]))
451                                 i++;
452                         to[j++] = '_';
453                 }
454                 to[j++] = str[i++];
455         }
456         to[j] = '\0';
457         return 0;
458 }
459
460 static int is_whitelisted(char c, const char *white)
461 {
462         if ((c >= '0' && c <= '9') ||
463             (c >= 'A' && c <= 'Z') ||
464             (c >= 'a' && c <= 'z') ||
465             strchr("#+-.:=@_", c) != NULL ||
466             (white != NULL && strchr(white, c) != NULL))
467                 return 1;
468         return 0;
469 }
470
471 /* allow chars in whitelist, plain ascii, hex-escaping and valid utf8 */
472 int util_replace_chars(char *str, const char *white)
473 {
474         size_t i = 0;
475         int replaced = 0;
476
477         while (str[i] != '\0') {
478                 int len;
479
480                 if (is_whitelisted(str[i], white)) {
481                         i++;
482                         continue;
483                 }
484
485                 /* accept hex encoding */
486                 if (str[i] == '\\' && str[i+1] == 'x') {
487                         i += 2;
488                         continue;
489                 }
490
491                 /* accept valid utf8 */
492                 len = utf8_encoded_valid_unichar(&str[i]);
493                 if (len > 1) {
494                         i += len;
495                         continue;
496                 }
497
498                 /* if space is allowed, replace whitespace with ordinary space */
499                 if (isspace(str[i]) && white != NULL && strchr(white, ' ') != NULL) {
500                         str[i] = ' ';
501                         i++;
502                         replaced++;
503                         continue;
504                 }
505
506                 /* everything else is replaced with '_' */
507                 str[i] = '_';
508                 i++;
509                 replaced++;
510         }
511         return replaced;
512 }
513
514 /**
515  * udev_util_encode_string:
516  * @str: input string to be encoded
517  * @str_enc: output string to store the encoded input string
518  * @len: maximum size of the output string, which may be
519  *       four times as long as the input string
520  *
521  * Encode all potentially unsafe characters of a string to the
522  * corresponding 2 char hex value prefixed by '\x'.
523  *
524  * Returns: 0 if the entire string was copied, non-zero otherwise.
525  **/
526 _public_ int udev_util_encode_string(const char *str, char *str_enc, size_t len)
527 {
528         size_t i, j;
529
530         if (str == NULL || str_enc == NULL)
531                 return -1;
532
533         for (i = 0, j = 0; str[i] != '\0'; i++) {
534                 int seqlen;
535
536                 seqlen = utf8_encoded_valid_unichar(&str[i]);
537                 if (seqlen > 1) {
538                         if (len-j < (size_t)seqlen)
539                                 goto err;
540                         memcpy(&str_enc[j], &str[i], seqlen);
541                         j += seqlen;
542                         i += (seqlen-1);
543                 } else if (str[i] == '\\' || !is_whitelisted(str[i], NULL)) {
544                         if (len-j < 4)
545                                 goto err;
546                         sprintf(&str_enc[j], "\\x%02x", (unsigned char) str[i]);
547                         j += 4;
548                 } else {
549                         if (len-j < 1)
550                                 goto err;
551                         str_enc[j] = str[i];
552                         j++;
553                 }
554         }
555         if (len-j < 1)
556                 goto err;
557         str_enc[j] = '\0';
558         return 0;
559 err:
560         return -1;
561 }
562
563 /*
564  * http://sites.google.com/site/murmurhash/
565  *
566  * All code is released to the public domain. For business purposes,
567  * Murmurhash is under the MIT license.
568  *
569  */
570 static unsigned int murmur_hash2(const char *key, size_t len, unsigned int seed)
571 {
572         /*
573          *  'm' and 'r' are mixing constants generated offline.
574          *  They're not really 'magic', they just happen to work well.
575          */
576         const unsigned int m = 0x5bd1e995;
577         const int r = 24;
578
579         /* initialize the hash to a 'random' value */
580         unsigned int h = seed ^ len;
581
582         /* mix 4 bytes at a time into the hash */
583         const unsigned char * data = (const unsigned char *)key;
584
585         while(len >= sizeof(unsigned int)) {
586                 unsigned int k;
587
588                 memcpy(&k, data, sizeof(k));
589                 k *= m;
590                 k ^= k >> r;
591                 k *= m;
592                 h *= m;
593                 h ^= k;
594
595                 data += sizeof(k);
596                 len -= sizeof(k);
597         }
598
599         /* handle the last few bytes of the input array */
600         switch(len) {
601         case 3:
602                 h ^= data[2] << 16;
603         case 2:
604                 h ^= data[1] << 8;
605         case 1:
606                 h ^= data[0];
607                 h *= m;
608         };
609
610         /* do a few final mixes of the hash to ensure the last few bytes are well-incorporated */
611         h ^= h >> 13;
612         h *= m;
613         h ^= h >> 15;
614
615         return h;
616 }
617
618 unsigned int util_string_hash32(const char *str)
619 {
620         return murmur_hash2(str, strlen(str), 0);
621 }
622
623 /* get a bunch of bit numbers out of the hash, and set the bits in our bit field */
624 uint64_t util_string_bloom64(const char *str)
625 {
626         uint64_t bits = 0;
627         unsigned int hash = util_string_hash32(str);
628
629         bits |= 1LLU << (hash & 63);
630         bits |= 1LLU << ((hash >> 6) & 63);
631         bits |= 1LLU << ((hash >> 12) & 63);
632         bits |= 1LLU << ((hash >> 18) & 63);
633         return bits;
634 }
635
636 ssize_t print_kmsg(const char *fmt, ...)
637 {
638         int fd;
639         va_list ap;
640         char text[1024];
641         ssize_t len;
642         ssize_t ret;
643
644         fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
645         if (fd < 0)
646                 return -errno;
647
648         len = snprintf(text, sizeof(text), "<30>systemd-udevd[%u]: ", getpid());
649
650         va_start(ap, fmt);
651         len += vsnprintf(text + len, sizeof(text) - len, fmt, ap);
652         va_end(ap);
653
654         ret = write(fd, text, len);
655         if (ret < 0)
656                 ret = -errno;
657         close(fd);
658         return ret;
659 }