chiark / gitweb /
move utf8 functions from libudev-private.h to utf8.h
[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 #include "utf8.h"
38
39 /**
40  * SECTION:libudev-util
41  * @short_description: utils
42  *
43  * Utilities useful when dealing with devices and device node names.
44  */
45
46 int util_delete_path(struct udev *udev, const char *path)
47 {
48         char p[UTIL_PATH_SIZE];
49         char *pos;
50         int err = 0;
51
52         if (path[0] == '/')
53                 while(path[1] == '/')
54                         path++;
55         strscpy(p, sizeof(p), path);
56         pos = strrchr(p, '/');
57         if (pos == p || pos == NULL)
58                 return 0;
59
60         for (;;) {
61                 *pos = '\0';
62                 pos = strrchr(p, '/');
63
64                 /* don't remove the last one */
65                 if ((pos == p) || (pos == NULL))
66                         break;
67
68                 err = rmdir(p);
69                 if (err < 0) {
70                         if (errno == ENOENT)
71                                 err = 0;
72                         break;
73                 }
74         }
75         return err;
76 }
77
78 uid_t util_lookup_user(struct udev *udev, const char *user)
79 {
80         char *endptr;
81         struct passwd pwbuf;
82         struct passwd *pw;
83         uid_t uid;
84         size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
85         char *buf = alloca(buflen);
86
87         if (streq(user, "root"))
88                 return 0;
89         uid = strtoul(user, &endptr, 10);
90         if (endptr[0] == '\0')
91                 return uid;
92
93         errno = getpwnam_r(user, &pwbuf, buf, buflen, &pw);
94         if (pw != NULL)
95                 return pw->pw_uid;
96         if (errno == 0 || errno == ENOENT || errno == ESRCH)
97                 udev_err(udev, "specified user '%s' unknown\n", user);
98         else
99                 udev_err(udev, "error resolving user '%s': %m\n", user);
100         return 0;
101 }
102
103 gid_t util_lookup_group(struct udev *udev, const char *group)
104 {
105         char *endptr;
106         struct group grbuf;
107         struct group *gr;
108         gid_t gid = 0;
109         size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
110         char *buf = NULL;
111
112         if (streq(group, "root"))
113                 return 0;
114         gid = strtoul(group, &endptr, 10);
115         if (endptr[0] == '\0')
116                 return gid;
117         gid = 0;
118         for (;;) {
119                 char *newbuf;
120
121                 newbuf = realloc(buf, buflen);
122                 if (!newbuf)
123                         break;
124                 buf = newbuf;
125                 errno = getgrnam_r(group, &grbuf, buf, buflen, &gr);
126                 if (gr != NULL) {
127                         gid = gr->gr_gid;
128                 } else if (errno == ERANGE) {
129                         buflen *= 2;
130                         continue;
131                 } else if (errno == 0 || errno == ENOENT || errno == ESRCH) {
132                         udev_err(udev, "specified group '%s' unknown\n", group);
133                 } else {
134                         udev_err(udev, "error resolving group '%s': %m\n", group);
135                 }
136                 break;
137         }
138         free(buf);
139         return gid;
140 }
141
142 /* handle "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
143 int util_resolve_subsys_kernel(struct udev *udev, const char *string,
144                                char *result, size_t maxsize, int read_value)
145 {
146         char temp[UTIL_PATH_SIZE];
147         char *subsys;
148         char *sysname;
149         struct udev_device *dev;
150         char *attr;
151
152         if (string[0] != '[')
153                 return -1;
154
155         strscpy(temp, sizeof(temp), string);
156
157         subsys = &temp[1];
158
159         sysname = strchr(subsys, '/');
160         if (sysname == NULL)
161                 return -1;
162         sysname[0] = '\0';
163         sysname = &sysname[1];
164
165         attr = strchr(sysname, ']');
166         if (attr == NULL)
167                 return -1;
168         attr[0] = '\0';
169         attr = &attr[1];
170         if (attr[0] == '/')
171                 attr = &attr[1];
172         if (attr[0] == '\0')
173                 attr = NULL;
174
175         if (read_value && attr == NULL)
176                 return -1;
177
178         dev = udev_device_new_from_subsystem_sysname(udev, subsys, sysname);
179         if (dev == NULL)
180                 return -1;
181
182         if (read_value) {
183                 const char *val;
184
185                 val = udev_device_get_sysattr_value(dev, attr);
186                 if (val != NULL)
187                         strscpy(result, maxsize, val);
188                 else
189                         result[0] = '\0';
190                 udev_dbg(udev, "value '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
191         } else {
192                 size_t l;
193                 char *s;
194
195                 s = result;
196                 l = strpcpyl(&s, maxsize, udev_device_get_syspath(dev), NULL);
197                 if (attr != NULL)
198                         strpcpyl(&s, l, "/", attr, NULL);
199                 udev_dbg(udev, "path '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
200         }
201         udev_device_unref(dev);
202         return 0;
203 }
204 ssize_t util_get_sys_core_link_value(struct udev *udev, const char *slink, const char *syspath, char *value, size_t size)
205 {
206         char path[UTIL_PATH_SIZE];
207         char target[UTIL_PATH_SIZE];
208         ssize_t len;
209         const char *pos;
210
211         strscpyl(path, sizeof(path), syspath, "/", slink, NULL);
212         len = readlink(path, target, sizeof(target));
213         if (len <= 0 || len == (ssize_t)sizeof(target))
214                 return -1;
215         target[len] = '\0';
216         pos = strrchr(target, '/');
217         if (pos == NULL)
218                 return -1;
219         pos = &pos[1];
220         return strscpy(value, size, pos);
221 }
222
223 int util_resolve_sys_link(struct udev *udev, char *syspath, size_t size)
224 {
225         char link_target[UTIL_PATH_SIZE];
226
227         ssize_t len;
228         int i;
229         int back;
230         char *base = NULL;
231
232         len = readlink(syspath, link_target, sizeof(link_target));
233         if (len <= 0 || len == (ssize_t)sizeof(link_target))
234                 return -1;
235         link_target[len] = '\0';
236
237         for (back = 0; startswith(&link_target[back * 3], "../"); back++)
238                 ;
239         for (i = 0; i <= back; i++) {
240                 base = strrchr(syspath, '/');
241                 if (base == NULL)
242                         return -EINVAL;
243                 base[0] = '\0';
244         }
245
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 int util_replace_whitespace(const char *str, char *to, size_t len)
311 {
312         size_t i, j;
313
314         /* strip trailing whitespace */
315         len = strnlen(str, len);
316         while (len && isspace(str[len-1]))
317                 len--;
318
319         /* strip leading whitespace */
320         i = 0;
321         while (isspace(str[i]) && (i < len))
322                 i++;
323
324         j = 0;
325         while (i < len) {
326                 /* substitute multiple whitespace with a single '_' */
327                 if (isspace(str[i])) {
328                         while (isspace(str[i]))
329                                 i++;
330                         to[j++] = '_';
331                 }
332                 to[j++] = str[i++];
333         }
334         to[j] = '\0';
335         return 0;
336 }
337
338 /* allow chars in whitelist, plain ascii, hex-escaping and valid utf8 */
339 int util_replace_chars(char *str, const char *white)
340 {
341         size_t i = 0;
342         int replaced = 0;
343
344         while (str[i] != '\0') {
345                 int len;
346
347                 if (is_utf8_encoding_whitelisted(str[i], white)) {
348                         i++;
349                         continue;
350                 }
351
352                 /* accept hex encoding */
353                 if (str[i] == '\\' && str[i+1] == 'x') {
354                         i += 2;
355                         continue;
356                 }
357
358                 /* accept valid utf8 */
359                 len = utf8_encoded_valid_unichar(&str[i]);
360                 if (len > 1) {
361                         i += len;
362                         continue;
363                 }
364
365                 /* if space is allowed, replace whitespace with ordinary space */
366                 if (isspace(str[i]) && white != NULL && strchr(white, ' ') != NULL) {
367                         str[i] = ' ';
368                         i++;
369                         replaced++;
370                         continue;
371                 }
372
373                 /* everything else is replaced with '_' */
374                 str[i] = '_';
375                 i++;
376                 replaced++;
377         }
378         return replaced;
379 }
380
381 /**
382  * udev_util_encode_string:
383  * @str: input string to be encoded
384  * @str_enc: output string to store the encoded input string
385  * @len: maximum size of the output string, which may be
386  *       four times as long as the input string
387  *
388  * Encode all potentially unsafe characters of a string to the
389  * corresponding 2 char hex value prefixed by '\x'.
390  *
391  * Returns: 0 if the entire string was copied, non-zero otherwise.
392  **/
393 _public_ int udev_util_encode_string(const char *str, char *str_enc, size_t len)
394 {
395         return udev_encode_string(str, str_enc, len);
396 }
397
398 /*
399  * http://sites.google.com/site/murmurhash/
400  *
401  * All code is released to the public domain. For business purposes,
402  * Murmurhash is under the MIT license.
403  *
404  */
405 static unsigned int murmur_hash2(const char *key, size_t len, unsigned int seed)
406 {
407         /*
408          *  'm' and 'r' are mixing constants generated offline.
409          *  They're not really 'magic', they just happen to work well.
410          */
411         const unsigned int m = 0x5bd1e995;
412         const int r = 24;
413
414         /* initialize the hash to a 'random' value */
415         unsigned int h = seed ^ len;
416
417         /* mix 4 bytes at a time into the hash */
418         const unsigned char * data = (const unsigned char *)key;
419
420         while(len >= sizeof(unsigned int)) {
421                 unsigned int k;
422
423                 memcpy(&k, data, sizeof(k));
424                 k *= m;
425                 k ^= k >> r;
426                 k *= m;
427                 h *= m;
428                 h ^= k;
429
430                 data += sizeof(k);
431                 len -= sizeof(k);
432         }
433
434         /* handle the last few bytes of the input array */
435         switch(len) {
436         case 3:
437                 h ^= data[2] << 16;
438         case 2:
439                 h ^= data[1] << 8;
440         case 1:
441                 h ^= data[0];
442                 h *= m;
443         };
444
445         /* do a few final mixes of the hash to ensure the last few bytes are well-incorporated */
446         h ^= h >> 13;
447         h *= m;
448         h ^= h >> 15;
449
450         return h;
451 }
452
453 unsigned int util_string_hash32(const char *str)
454 {
455         return murmur_hash2(str, strlen(str), 0);
456 }
457
458 /* get a bunch of bit numbers out of the hash, and set the bits in our bit field */
459 uint64_t util_string_bloom64(const char *str)
460 {
461         uint64_t bits = 0;
462         unsigned int hash = util_string_hash32(str);
463
464         bits |= 1LLU << (hash & 63);
465         bits |= 1LLU << ((hash >> 6) & 63);
466         bits |= 1LLU << ((hash >> 12) & 63);
467         bits |= 1LLU << ((hash >> 18) & 63);
468         return bits;
469 }
470
471 ssize_t print_kmsg(const char *fmt, ...)
472 {
473         int fd;
474         va_list ap;
475         char text[1024];
476         ssize_t len;
477         ssize_t ret;
478
479         fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
480         if (fd < 0)
481                 return -errno;
482
483         len = snprintf(text, sizeof(text), "<30>systemd-udevd[%u]: ", getpid());
484
485         va_start(ap, fmt);
486         len += vsnprintf(text + len, sizeof(text) - len, fmt, ap);
487         va_end(ap);
488
489         ret = write(fd, text, len);
490         if (ret < 0)
491                 ret = -errno;
492         close(fd);
493         return ret;
494 }