chiark / gitweb /
release 171
[elogind.git] / libudev / libudev-util.c
1 /*
2  * libudev - interface to udev device information
3  *
4  * Copyright (C) 2008-2009 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 <sys/stat.h>
23
24 #include "libudev.h"
25 #include "libudev-private.h"
26
27 static ssize_t get_sys_link(struct udev *udev, const char *slink, const char *syspath, char *value, size_t size)
28 {
29         char path[UTIL_PATH_SIZE];
30         char target[UTIL_PATH_SIZE];
31         ssize_t len;
32         const char *pos;
33
34         util_strscpyl(path, sizeof(path), syspath, "/", slink, NULL);
35         len = readlink(path, target, sizeof(target));
36         if (len <= 0 || len == (ssize_t)sizeof(target))
37                 return -1;
38         target[len] = '\0';
39         pos = strrchr(target, '/');
40         if (pos == NULL)
41                 return -1;
42         pos = &pos[1];
43         dbg(udev, "resolved link to: '%s'\n", pos);
44         return util_strscpy(value, size, pos);
45 }
46
47 ssize_t util_get_sys_subsystem(struct udev *udev, const char *syspath, char *subsystem, size_t size)
48 {
49         return get_sys_link(udev, "subsystem", syspath, subsystem, size);
50 }
51
52 ssize_t util_get_sys_driver(struct udev *udev, const char *syspath, char *driver, size_t size)
53 {
54         return get_sys_link(udev, "driver", syspath, driver, size);
55 }
56
57 int util_resolve_sys_link(struct udev *udev, char *syspath, size_t size)
58 {
59         char link_target[UTIL_PATH_SIZE];
60
61         ssize_t len;
62         int i;
63         int back;
64         char *base;
65
66         len = readlink(syspath, link_target, sizeof(link_target));
67         if (len <= 0 || len == (ssize_t)sizeof(link_target))
68                 return -1;
69         link_target[len] = '\0';
70         dbg(udev, "path link '%s' points to '%s'\n", syspath, link_target);
71
72         for (back = 0; strncmp(&link_target[back * 3], "../", 3) == 0; back++)
73                 ;
74         dbg(udev, "base '%s', tail '%s', back %i\n", syspath, &link_target[back * 3], back);
75         for (i = 0; i <= back; i++) {
76                 base = strrchr(syspath, '/');
77                 if (base == NULL)
78                         return -1;
79                 base[0] = '\0';
80         }
81         dbg(udev, "after moving back '%s'\n", syspath);
82         util_strscpyl(base, size - (base - syspath), "/", &link_target[back * 3], NULL);
83         return 0;
84 }
85
86 int util_log_priority(const char *priority)
87 {
88         char *endptr;
89         int prio;
90
91         prio = strtol(priority, &endptr, 10);
92         if (endptr[0] == '\0' || isspace(endptr[0]))
93                 return prio;
94         if (strncmp(priority, "err", 3) == 0)
95                 return LOG_ERR;
96         if (strncmp(priority, "info", 4) == 0)
97                 return LOG_INFO;
98         if (strncmp(priority, "debug", 5) == 0)
99                 return LOG_DEBUG;
100         return 0;
101 }
102
103 size_t util_path_encode(const char *src, char *dest, size_t size)
104 {
105         size_t i, j;
106
107         for (i = 0, j = 0; src[i] != '\0'; i++) {
108                 if (src[i] == '/') {
109                         if (j+4 >= size) {
110                                 j = 0;
111                                 break;
112                         }
113                         memcpy(&dest[j], "\\x2f", 4);
114                         j += 4;
115                 } else if (src[i] == '\\') {
116                         if (j+4 >= size) {
117                                 j = 0;
118                                 break;
119                         }
120                         memcpy(&dest[j], "\\x5c", 4);
121                         j += 4;
122                 } else {
123                         if (j+1 >= size) {
124                                 j = 0;
125                                 break;
126                         }
127                         dest[j] = src[i];
128                         j++;
129                 }
130         }
131         dest[j] = '\0';
132         return j;
133 }
134
135 size_t util_path_decode(char *s)
136 {
137         size_t i, j;
138
139         for (i = 0, j = 0; s[i] != '\0'; j++) {
140                 if (memcmp(&s[i], "\\x2f", 4) == 0) {
141                         s[j] = '/';
142                         i += 4;
143                 } else if (memcmp(&s[i], "\\x5c", 4) == 0) {
144                         s[j] = '\\';
145                         i += 4;
146                 } else {
147                         s[j] = s[i];
148                         i++;
149                 }
150         }
151         s[j] = '\0';
152         return j;
153 }
154
155 void util_remove_trailing_chars(char *path, char c)
156 {
157         size_t len;
158
159         if (path == NULL)
160                 return;
161         len = strlen(path);
162         while (len > 0 && path[len-1] == c)
163                 path[--len] = '\0';
164 }
165
166 /*
167  * Concatenates strings. In any case, terminates in _all_ cases with '\0'
168  * and moves the @dest pointer forward to the added '\0'. Returns the
169  * remaining size, and 0 if the string was truncated.
170  */
171 size_t util_strpcpy(char **dest, size_t size, const char *src)
172 {
173         size_t len;
174
175         len = strlen(src);
176         if (len >= size) {
177                 if (size > 1)
178                         *dest = mempcpy(*dest, src, size-1);
179                 size = 0;
180                 *dest[0] = '\0';
181         } else {
182                 if (len > 0) {
183                         *dest = mempcpy(*dest, src, len);
184                         size -= len;
185                 }
186                 *dest[0] = '\0';
187         }
188         return size;
189 }
190
191 /* concatenates list of strings, moves dest forward */
192 size_t util_strpcpyl(char **dest, size_t size, const char *src, ...)
193 {
194         va_list va;
195
196         va_start(va, src);
197         do {
198                 size = util_strpcpy(dest, size, src);
199                 src = va_arg(va, char *);
200         } while (src != NULL);
201         va_end(va);
202
203         return size;
204 }
205
206 /* copies string */
207 size_t util_strscpy(char *dest, size_t size, const char *src)
208 {
209         char *s;
210
211         s = dest;
212         return util_strpcpy(&s, size, src);
213 }
214
215 /* concatenates list of strings */
216 size_t util_strscpyl(char *dest, size_t size, const char *src, ...)
217 {
218         va_list va;
219         char *s;
220
221         va_start(va, src);
222         s = dest;
223         do {
224                 size = util_strpcpy(&s, size, src);
225                 src = va_arg(va, char *);
226         } while (src != NULL);
227         va_end(va);
228
229         return size;
230 }
231
232 /* count of characters used to encode one unicode char */
233 static int utf8_encoded_expected_len(const char *str)
234 {
235         unsigned char c = (unsigned char)str[0];
236
237         if (c < 0x80)
238                 return 1;
239         if ((c & 0xe0) == 0xc0)
240                 return 2;
241         if ((c & 0xf0) == 0xe0)
242                 return 3;
243         if ((c & 0xf8) == 0xf0)
244                 return 4;
245         if ((c & 0xfc) == 0xf8)
246                 return 5;
247         if ((c & 0xfe) == 0xfc)
248                 return 6;
249         return 0;
250 }
251
252 /* decode one unicode char */
253 static int utf8_encoded_to_unichar(const char *str)
254 {
255         int unichar;
256         int len;
257         int i;
258
259         len = utf8_encoded_expected_len(str);
260         switch (len) {
261         case 1:
262                 return (int)str[0];
263         case 2:
264                 unichar = str[0] & 0x1f;
265                 break;
266         case 3:
267                 unichar = (int)str[0] & 0x0f;
268                 break;
269         case 4:
270                 unichar = (int)str[0] & 0x07;
271                 break;
272         case 5:
273                 unichar = (int)str[0] & 0x03;
274                 break;
275         case 6:
276                 unichar = (int)str[0] & 0x01;
277                 break;
278         default:
279                 return -1;
280         }
281
282         for (i = 1; i < len; i++) {
283                 if (((int)str[i] & 0xc0) != 0x80)
284                         return -1;
285                 unichar <<= 6;
286                 unichar |= (int)str[i] & 0x3f;
287         }
288
289         return unichar;
290 }
291
292 /* expected size used to encode one unicode char */
293 static int utf8_unichar_to_encoded_len(int unichar)
294 {
295         if (unichar < 0x80)
296                 return 1;
297         if (unichar < 0x800)
298                 return 2;
299         if (unichar < 0x10000)
300                 return 3;
301         if (unichar < 0x200000)
302                 return 4;
303         if (unichar < 0x4000000)
304                 return 5;
305         return 6;
306 }
307
308 /* check if unicode char has a valid numeric range */
309 static int utf8_unichar_valid_range(int unichar)
310 {
311         if (unichar > 0x10ffff)
312                 return 0;
313         if ((unichar & 0xfffff800) == 0xd800)
314                 return 0;
315         if ((unichar > 0xfdcf) && (unichar < 0xfdf0))
316                 return 0;
317         if ((unichar & 0xffff) == 0xffff)
318                 return 0;
319         return 1;
320 }
321
322 /* validate one encoded unicode char and return its length */
323 static int utf8_encoded_valid_unichar(const char *str)
324 {
325         int len;
326         int unichar;
327         int i;
328
329         len = utf8_encoded_expected_len(str);
330         if (len == 0)
331                 return -1;
332
333         /* ascii is valid */
334         if (len == 1)
335                 return 1;
336
337         /* check if expected encoded chars are available */
338         for (i = 0; i < len; i++)
339                 if ((str[i] & 0x80) != 0x80)
340                         return -1;
341
342         unichar = utf8_encoded_to_unichar(str);
343
344         /* check if encoded length matches encoded value */
345         if (utf8_unichar_to_encoded_len(unichar) != len)
346                 return -1;
347
348         /* check if value has valid range */
349         if (!utf8_unichar_valid_range(unichar))
350                 return -1;
351
352         return len;
353 }
354
355 int udev_util_replace_whitespace(const char *str, char *to, size_t len)
356 {
357         size_t i, j;
358
359         /* strip trailing whitespace */
360         len = strnlen(str, len);
361         while (len && isspace(str[len-1]))
362                 len--;
363
364         /* strip leading whitespace */
365         i = 0;
366         while (isspace(str[i]) && (i < len))
367                 i++;
368
369         j = 0;
370         while (i < len) {
371                 /* substitute multiple whitespace with a single '_' */
372                 if (isspace(str[i])) {
373                         while (isspace(str[i]))
374                                 i++;
375                         to[j++] = '_';
376                 }
377                 to[j++] = str[i++];
378         }
379         to[j] = '\0';
380         return 0;
381 }
382
383 static int is_whitelisted(char c, const char *white)
384 {
385         if ((c >= '0' && c <= '9') ||
386             (c >= 'A' && c <= 'Z') ||
387             (c >= 'a' && c <= 'z') ||
388             strchr("#+-.:=@_", c) != NULL ||
389             (white != NULL && strchr(white, c) != NULL))
390                 return 1;
391         return 0;
392 }
393
394 /* allow chars in whitelist, plain ascii, hex-escaping and valid utf8 */
395 int udev_util_replace_chars(char *str, const char *white)
396 {
397         size_t i = 0;
398         int replaced = 0;
399
400         while (str[i] != '\0') {
401                 int len;
402
403                 if (is_whitelisted(str[i], white)) {
404                         i++;
405                         continue;
406                 }
407
408                 /* accept hex encoding */
409                 if (str[i] == '\\' && str[i+1] == 'x') {
410                         i += 2;
411                         continue;
412                 }
413
414                 /* accept valid utf8 */
415                 len = utf8_encoded_valid_unichar(&str[i]);
416                 if (len > 1) {
417                         i += len;
418                         continue;
419                 }
420
421                 /* if space is allowed, replace whitespace with ordinary space */
422                 if (isspace(str[i]) && white != NULL && strchr(white, ' ') != NULL) {
423                         str[i] = ' ';
424                         i++;
425                         replaced++;
426                         continue;
427                 }
428
429                 /* everything else is replaced with '_' */
430                 str[i] = '_';
431                 i++;
432                 replaced++;
433         }
434         return replaced;
435 }
436
437 /**
438  * util_encode_string:
439  * @str: input string to be encoded
440  * @str_enc: output string to store the encoded input string
441  * @len: maximum size of the output string, which may be
442  *       four times as long as the input string
443  *
444  * Encode all potentially unsafe characters of a string to the
445  * corresponding hex value prefixed by '\x'.
446  *
447  * Returns: 0 if the entire string was copied, non-zero otherwise.
448  **/
449 int udev_util_encode_string(const char *str, char *str_enc, size_t len)
450 {
451         size_t i, j;
452
453         if (str == NULL || str_enc == NULL)
454                 return -1;
455
456         for (i = 0, j = 0; str[i] != '\0'; i++) {
457                 int seqlen;
458
459                 seqlen = utf8_encoded_valid_unichar(&str[i]);
460                 if (seqlen > 1) {
461                         if (len-j < (size_t)seqlen)
462                                 goto err;
463                         memcpy(&str_enc[j], &str[i], seqlen);
464                         j += seqlen;
465                         i += (seqlen-1);
466                 } else if (str[i] == '\\' || !is_whitelisted(str[i], NULL)) {
467                         if (len-j < 4)
468                                 goto err;
469                         sprintf(&str_enc[j], "\\x%02x", (unsigned char) str[i]);
470                         j += 4;
471                 } else {
472                         if (len-j < 1)
473                                 goto err;
474                         str_enc[j] = str[i];
475                         j++;
476                 }
477         }
478         if (len-j < 1)
479                 goto err;
480         str_enc[j] = '\0';
481         return 0;
482 err:
483         return -1;
484 }
485
486 /*
487  * http://sites.google.com/site/murmurhash/
488  *
489  * All code is released to the public domain. For business purposes,
490  * Murmurhash is under the MIT license.
491  *
492  */
493 static unsigned int murmur_hash2(const char *key, int len, unsigned int seed)
494 {
495         /*
496          *  'm' and 'r' are mixing constants generated offline.
497          *  They're not really 'magic', they just happen to work well.
498          */
499         const unsigned int m = 0x5bd1e995;
500         const int r = 24;
501
502         /* initialize the hash to a 'random' value */
503         unsigned int h = seed ^ len;
504
505         /* mix 4 bytes at a time into the hash */
506         const unsigned char * data = (const unsigned char *)key;
507
508         while(len >= 4) {
509                 unsigned int k = *(unsigned int *)data;
510
511                 k *= m; 
512                 k ^= k >> r; 
513                 k *= m; 
514                 h *= m; 
515                 h ^= k;
516
517                 data += 4;
518                 len -= 4;
519         }
520
521         /* handle the last few bytes of the input array */
522         switch(len) {
523         case 3:
524                 h ^= data[2] << 16;
525         case 2:
526                 h ^= data[1] << 8;
527         case 1:
528                 h ^= data[0];
529                 h *= m;
530         };
531
532         /* do a few final mixes of the hash to ensure the last few bytes are well-incorporated */
533         h ^= h >> 13;
534         h *= m;
535         h ^= h >> 15;
536
537         return h;
538 }
539
540 unsigned int util_string_hash32(const char *str)
541 {
542         return murmur_hash2(str, strlen(str), 0);
543 }
544
545 /* get a bunch of bit numbers out of the hash, and set the bits in our bit field */
546 uint64_t util_string_bloom64(const char *str)
547 {
548         uint64_t bits = 0;
549         unsigned int hash = util_string_hash32(str);
550
551         bits |= 1LLU << (hash & 63);
552         bits |= 1LLU << ((hash >> 6) & 63);
553         bits |= 1LLU << ((hash >> 12) & 63);
554         bits |= 1LLU << ((hash >> 18) & 63);
555         return bits;
556 }
557
558 #define USEC_PER_SEC  1000000ULL
559 #define NSEC_PER_USEC 1000ULL
560 unsigned long long now_usec(void)
561 {
562         struct timespec ts;
563
564         if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
565                 return 0;
566         return (unsigned long long) ts.tv_sec * USEC_PER_SEC +
567                (unsigned long long) ts.tv_nsec / NSEC_PER_USEC;
568 }