]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/libudev/libudev-util.c
udev: move string copy functions to shared/
[thirdparty/systemd.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 (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 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 if (base == NULL)
245 return -EINVAL;
246 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 /* count of characters used to encode one unicode char */
311 static int utf8_encoded_expected_len(const char *str)
312 {
313 unsigned char c = (unsigned char)str[0];
314
315 if (c < 0x80)
316 return 1;
317 if ((c & 0xe0) == 0xc0)
318 return 2;
319 if ((c & 0xf0) == 0xe0)
320 return 3;
321 if ((c & 0xf8) == 0xf0)
322 return 4;
323 if ((c & 0xfc) == 0xf8)
324 return 5;
325 if ((c & 0xfe) == 0xfc)
326 return 6;
327 return 0;
328 }
329
330 /* decode one unicode char */
331 static int utf8_encoded_to_unichar(const char *str)
332 {
333 int unichar;
334 int len;
335 int i;
336
337 len = utf8_encoded_expected_len(str);
338 switch (len) {
339 case 1:
340 return (int)str[0];
341 case 2:
342 unichar = str[0] & 0x1f;
343 break;
344 case 3:
345 unichar = (int)str[0] & 0x0f;
346 break;
347 case 4:
348 unichar = (int)str[0] & 0x07;
349 break;
350 case 5:
351 unichar = (int)str[0] & 0x03;
352 break;
353 case 6:
354 unichar = (int)str[0] & 0x01;
355 break;
356 default:
357 return -1;
358 }
359
360 for (i = 1; i < len; i++) {
361 if (((int)str[i] & 0xc0) != 0x80)
362 return -1;
363 unichar <<= 6;
364 unichar |= (int)str[i] & 0x3f;
365 }
366
367 return unichar;
368 }
369
370 /* expected size used to encode one unicode char */
371 static int utf8_unichar_to_encoded_len(int unichar)
372 {
373 if (unichar < 0x80)
374 return 1;
375 if (unichar < 0x800)
376 return 2;
377 if (unichar < 0x10000)
378 return 3;
379 if (unichar < 0x200000)
380 return 4;
381 if (unichar < 0x4000000)
382 return 5;
383 return 6;
384 }
385
386 /* check if unicode char has a valid numeric range */
387 static int utf8_unichar_valid_range(int unichar)
388 {
389 if (unichar > 0x10ffff)
390 return 0;
391 if ((unichar & 0xfffff800) == 0xd800)
392 return 0;
393 if ((unichar > 0xfdcf) && (unichar < 0xfdf0))
394 return 0;
395 if ((unichar & 0xffff) == 0xffff)
396 return 0;
397 return 1;
398 }
399
400 /* validate one encoded unicode char and return its length */
401 static int utf8_encoded_valid_unichar(const char *str)
402 {
403 int len;
404 int unichar;
405 int i;
406
407 len = utf8_encoded_expected_len(str);
408 if (len == 0)
409 return -1;
410
411 /* ascii is valid */
412 if (len == 1)
413 return 1;
414
415 /* check if expected encoded chars are available */
416 for (i = 0; i < len; i++)
417 if ((str[i] & 0x80) != 0x80)
418 return -1;
419
420 unichar = utf8_encoded_to_unichar(str);
421
422 /* check if encoded length matches encoded value */
423 if (utf8_unichar_to_encoded_len(unichar) != len)
424 return -1;
425
426 /* check if value has valid range */
427 if (!utf8_unichar_valid_range(unichar))
428 return -1;
429
430 return len;
431 }
432
433 int util_replace_whitespace(const char *str, char *to, size_t len)
434 {
435 size_t i, j;
436
437 /* strip trailing whitespace */
438 len = strnlen(str, len);
439 while (len && isspace(str[len-1]))
440 len--;
441
442 /* strip leading whitespace */
443 i = 0;
444 while (isspace(str[i]) && (i < len))
445 i++;
446
447 j = 0;
448 while (i < len) {
449 /* substitute multiple whitespace with a single '_' */
450 if (isspace(str[i])) {
451 while (isspace(str[i]))
452 i++;
453 to[j++] = '_';
454 }
455 to[j++] = str[i++];
456 }
457 to[j] = '\0';
458 return 0;
459 }
460
461 static int is_whitelisted(char c, const char *white)
462 {
463 if ((c >= '0' && c <= '9') ||
464 (c >= 'A' && c <= 'Z') ||
465 (c >= 'a' && c <= 'z') ||
466 strchr("#+-.:=@_", c) != NULL ||
467 (white != NULL && strchr(white, c) != NULL))
468 return 1;
469 return 0;
470 }
471
472 /* allow chars in whitelist, plain ascii, hex-escaping and valid utf8 */
473 int util_replace_chars(char *str, const char *white)
474 {
475 size_t i = 0;
476 int replaced = 0;
477
478 while (str[i] != '\0') {
479 int len;
480
481 if (is_whitelisted(str[i], white)) {
482 i++;
483 continue;
484 }
485
486 /* accept hex encoding */
487 if (str[i] == '\\' && str[i+1] == 'x') {
488 i += 2;
489 continue;
490 }
491
492 /* accept valid utf8 */
493 len = utf8_encoded_valid_unichar(&str[i]);
494 if (len > 1) {
495 i += len;
496 continue;
497 }
498
499 /* if space is allowed, replace whitespace with ordinary space */
500 if (isspace(str[i]) && white != NULL && strchr(white, ' ') != NULL) {
501 str[i] = ' ';
502 i++;
503 replaced++;
504 continue;
505 }
506
507 /* everything else is replaced with '_' */
508 str[i] = '_';
509 i++;
510 replaced++;
511 }
512 return replaced;
513 }
514
515 /**
516 * udev_util_encode_string:
517 * @str: input string to be encoded
518 * @str_enc: output string to store the encoded input string
519 * @len: maximum size of the output string, which may be
520 * four times as long as the input string
521 *
522 * Encode all potentially unsafe characters of a string to the
523 * corresponding 2 char hex value prefixed by '\x'.
524 *
525 * Returns: 0 if the entire string was copied, non-zero otherwise.
526 **/
527 _public_ int udev_util_encode_string(const char *str, char *str_enc, size_t len)
528 {
529 size_t i, j;
530
531 if (str == NULL || str_enc == NULL)
532 return -1;
533
534 for (i = 0, j = 0; str[i] != '\0'; i++) {
535 int seqlen;
536
537 seqlen = utf8_encoded_valid_unichar(&str[i]);
538 if (seqlen > 1) {
539 if (len-j < (size_t)seqlen)
540 goto err;
541 memcpy(&str_enc[j], &str[i], seqlen);
542 j += seqlen;
543 i += (seqlen-1);
544 } else if (str[i] == '\\' || !is_whitelisted(str[i], NULL)) {
545 if (len-j < 4)
546 goto err;
547 sprintf(&str_enc[j], "\\x%02x", (unsigned char) str[i]);
548 j += 4;
549 } else {
550 if (len-j < 1)
551 goto err;
552 str_enc[j] = str[i];
553 j++;
554 }
555 }
556 if (len-j < 1)
557 goto err;
558 str_enc[j] = '\0';
559 return 0;
560 err:
561 return -1;
562 }
563
564 /*
565 * http://sites.google.com/site/murmurhash/
566 *
567 * All code is released to the public domain. For business purposes,
568 * Murmurhash is under the MIT license.
569 *
570 */
571 static unsigned int murmur_hash2(const char *key, int len, unsigned int seed)
572 {
573 /*
574 * 'm' and 'r' are mixing constants generated offline.
575 * They're not really 'magic', they just happen to work well.
576 */
577 const unsigned int m = 0x5bd1e995;
578 const int r = 24;
579
580 /* initialize the hash to a 'random' value */
581 unsigned int h = seed ^ len;
582
583 /* mix 4 bytes at a time into the hash */
584 const unsigned char * data = (const unsigned char *)key;
585
586 while(len >= 4) {
587 unsigned int k = *(unsigned int *)data;
588
589 k *= m;
590 k ^= k >> r;
591 k *= m;
592 h *= m;
593 h ^= k;
594
595 data += 4;
596 len -= 4;
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 }