chiark / gitweb /
3fe59c8ebba4b1a425bb0e4ee6bd2860d2715f9b
[elogind.git] / util.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <assert.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <errno.h>
26 #include <stdlib.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <syslog.h>
30 #include <sched.h>
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <fcntl.h>
36 #include <dirent.h>
37
38 #include "macro.h"
39 #include "util.h"
40 #include "ioprio.h"
41 #include "missing.h"
42 #include "log.h"
43 #include "strv.h"
44
45 bool streq_ptr(const char *a, const char *b) {
46
47         /* Like streq(), but tries to make sense of NULL pointers */
48
49         if (a && b)
50                 return streq(a, b);
51
52         if (!a && !b)
53                 return true;
54
55         return false;
56 }
57
58 usec_t now(clockid_t clock_id) {
59         struct timespec ts;
60
61         assert_se(clock_gettime(clock_id, &ts) == 0);
62
63         return timespec_load(&ts);
64 }
65
66 usec_t timespec_load(const struct timespec *ts) {
67         assert(ts);
68
69         return
70                 (usec_t) ts->tv_sec * USEC_PER_SEC +
71                 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
72 }
73
74 struct timespec *timespec_store(struct timespec *ts, usec_t u)  {
75         assert(ts);
76
77         ts->tv_sec = (time_t) (u / USEC_PER_SEC);
78         ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
79
80         return ts;
81 }
82
83 usec_t timeval_load(const struct timeval *tv) {
84         assert(tv);
85
86         return
87                 (usec_t) tv->tv_sec * USEC_PER_SEC +
88                 (usec_t) tv->tv_usec;
89 }
90
91 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
92         assert(tv);
93
94         tv->tv_sec = (time_t) (u / USEC_PER_SEC);
95         tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
96
97         return tv;
98 }
99
100 bool endswith(const char *s, const char *postfix) {
101         size_t sl, pl;
102
103         assert(s);
104         assert(postfix);
105
106         sl = strlen(s);
107         pl = strlen(postfix);
108
109         if (sl < pl)
110                 return false;
111
112         return memcmp(s + sl - pl, postfix, pl) == 0;
113 }
114
115 bool startswith(const char *s, const char *prefix) {
116         size_t sl, pl;
117
118         assert(s);
119         assert(prefix);
120
121         sl = strlen(s);
122         pl = strlen(prefix);
123
124         if (sl < pl)
125                 return false;
126
127         return memcmp(s, prefix, pl) == 0;
128 }
129
130 bool first_word(const char *s, const char *word) {
131         size_t sl, wl;
132
133         assert(s);
134         assert(word);
135
136         sl = strlen(s);
137         wl = strlen(word);
138
139         if (sl < wl)
140                 return false;
141
142         if (memcmp(s, word, wl) != 0)
143                 return false;
144
145         return (s[wl] == 0 ||
146                 strchr(WHITESPACE, s[wl]));
147 }
148
149 int close_nointr(int fd) {
150         assert(fd >= 0);
151
152         for (;;) {
153                 int r;
154
155                 if ((r = close(fd)) >= 0)
156                         return r;
157
158                 if (errno != EINTR)
159                         return r;
160         }
161 }
162
163 void close_nointr_nofail(int fd) {
164
165         /* like close_nointr() but cannot fail, and guarantees errno
166          * is unchanged */
167
168         assert_se(close_nointr(fd) == 0);
169 }
170
171 int parse_boolean(const char *v) {
172         assert(v);
173
174         if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
175                 return 1;
176         else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
177                 return 0;
178
179         return -EINVAL;
180 }
181
182 int safe_atou(const char *s, unsigned *ret_u) {
183         char *x = NULL;
184         unsigned long l;
185
186         assert(s);
187         assert(ret_u);
188
189         errno = 0;
190         l = strtoul(s, &x, 0);
191
192         if (!x || *x || errno)
193                 return errno ? -errno : -EINVAL;
194
195         if ((unsigned long) (unsigned) l != l)
196                 return -ERANGE;
197
198         *ret_u = (unsigned) l;
199         return 0;
200 }
201
202 int safe_atoi(const char *s, int *ret_i) {
203         char *x = NULL;
204         long l;
205
206         assert(s);
207         assert(ret_i);
208
209         errno = 0;
210         l = strtol(s, &x, 0);
211
212         if (!x || *x || errno)
213                 return errno ? -errno : -EINVAL;
214
215         if ((long) (int) l != l)
216                 return -ERANGE;
217
218         *ret_i = (int) l;
219         return 0;
220 }
221
222 int safe_atolu(const char *s, long unsigned *ret_lu) {
223         char *x = NULL;
224         unsigned long l;
225
226         assert(s);
227         assert(ret_lu);
228
229         errno = 0;
230         l = strtoul(s, &x, 0);
231
232         if (!x || *x || errno)
233                 return errno ? -errno : -EINVAL;
234
235         *ret_lu = l;
236         return 0;
237 }
238
239 int safe_atoli(const char *s, long int *ret_li) {
240         char *x = NULL;
241         long l;
242
243         assert(s);
244         assert(ret_li);
245
246         errno = 0;
247         l = strtol(s, &x, 0);
248
249         if (!x || *x || errno)
250                 return errno ? -errno : -EINVAL;
251
252         *ret_li = l;
253         return 0;
254 }
255
256 int safe_atollu(const char *s, long long unsigned *ret_llu) {
257         char *x = NULL;
258         unsigned long long l;
259
260         assert(s);
261         assert(ret_llu);
262
263         errno = 0;
264         l = strtoull(s, &x, 0);
265
266         if (!x || *x || errno)
267                 return errno ? -errno : -EINVAL;
268
269         *ret_llu = l;
270         return 0;
271 }
272
273 int safe_atolli(const char *s, long long int *ret_lli) {
274         char *x = NULL;
275         long long l;
276
277         assert(s);
278         assert(ret_lli);
279
280         errno = 0;
281         l = strtoll(s, &x, 0);
282
283         if (!x || *x || errno)
284                 return errno ? -errno : -EINVAL;
285
286         *ret_lli = l;
287         return 0;
288 }
289
290 /* Split a string into words. */
291 char *split(const char *c, size_t *l, const char *separator, char **state) {
292         char *current;
293
294         current = *state ? *state : (char*) c;
295
296         if (!*current || *c == 0)
297                 return NULL;
298
299         current += strspn(current, separator);
300         *l = strcspn(current, separator);
301         *state = current+*l;
302
303         return (char*) current;
304 }
305
306 /* Split a string into words, but consider strings enclosed in '' and
307  * "" as words even if they include spaces. */
308 char *split_quoted(const char *c, size_t *l, char **state) {
309         char *current;
310
311         current = *state ? *state : (char*) c;
312
313         if (!*current || *c == 0)
314                 return NULL;
315
316         current += strspn(current, WHITESPACE);
317
318         if (*current == '\'') {
319                 current ++;
320                 *l = strcspn(current, "'");
321                 *state = current+*l;
322
323                 if (**state == '\'')
324                         (*state)++;
325         } else if (*current == '\"') {
326                 current ++;
327                 *l = strcspn(current, "\"");
328                 *state = current+*l;
329
330                 if (**state == '\"')
331                         (*state)++;
332         } else {
333                 *l = strcspn(current, WHITESPACE);
334                 *state = current+*l;
335         }
336
337         /* FIXME: Cannot deal with strings that have spaces AND ticks
338          * in them */
339
340         return (char*) current;
341 }
342
343 char **split_path_and_make_absolute(const char *p) {
344         char **l;
345         assert(p);
346
347         if (!(l = strv_split(p, ":")))
348                 return NULL;
349
350         if (!strv_path_make_absolute_cwd(l)) {
351                 strv_free(l);
352                 return NULL;
353         }
354
355         return l;
356 }
357
358 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
359         int r;
360         FILE *f;
361         char fn[132], line[256], *p;
362         long long unsigned ppid;
363
364         assert(pid >= 0);
365         assert(_ppid);
366
367         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%llu/stat", (unsigned long long) pid) < (int) (sizeof(fn)-1));
368         fn[sizeof(fn)-1] = 0;
369
370         if (!(f = fopen(fn, "r")))
371                 return -errno;
372
373         if (!(fgets(line, sizeof(line), f))) {
374                 r = -errno;
375                 fclose(f);
376                 return r;
377         }
378
379         fclose(f);
380
381         /* Let's skip the pid and comm fields. The latter is enclosed
382          * in () but does not escape any () in its value, so let's
383          * skip over it manually */
384
385         if (!(p = strrchr(line, ')')))
386                 return -EIO;
387
388         p++;
389
390         if (sscanf(p, " "
391                    "%*c "  /* state */
392                    "%llu ", /* ppid */
393                    &ppid) != 1)
394                 return -EIO;
395
396         if ((long long unsigned) (pid_t) ppid != ppid)
397                 return -ERANGE;
398
399         *_ppid = (pid_t) ppid;
400
401         return 0;
402 }
403
404 int write_one_line_file(const char *fn, const char *line) {
405         FILE *f;
406         int r;
407
408         assert(fn);
409         assert(line);
410
411         if (!(f = fopen(fn, "we")))
412                 return -errno;
413
414         if (fputs(line, f) < 0) {
415                 r = -errno;
416                 goto finish;
417         }
418
419         r = 0;
420 finish:
421         fclose(f);
422         return r;
423 }
424
425 int read_one_line_file(const char *fn, char **line) {
426         FILE *f;
427         int r;
428         char t[2048], *c;
429
430         assert(fn);
431         assert(line);
432
433         if (!(f = fopen(fn, "re")))
434                 return -errno;
435
436         if (!(fgets(t, sizeof(t), f))) {
437                 r = -errno;
438                 goto finish;
439         }
440
441         if (!(c = strdup(t))) {
442                 r = -ENOMEM;
443                 goto finish;
444         }
445
446         *line = c;
447         r = 0;
448
449 finish:
450         fclose(f);
451         return r;
452 }
453
454 char *truncate_nl(char *s) {
455         assert(s);
456
457         s[strcspn(s, NEWLINE)] = 0;
458         return s;
459 }
460
461 int get_process_name(pid_t pid, char **name) {
462         char *p;
463         int r;
464
465         assert(pid >= 1);
466         assert(name);
467
468         if (asprintf(&p, "/proc/%llu/comm", (unsigned long long) pid) < 0)
469                 return -ENOMEM;
470
471         r = read_one_line_file(p, name);
472         free(p);
473
474         if (r < 0)
475                 return r;
476
477         truncate_nl(*name);
478         return 0;
479 }
480
481 char *strappend(const char *s, const char *suffix) {
482         size_t a, b;
483         char *r;
484
485         assert(s);
486         assert(suffix);
487
488         a = strlen(s);
489         b = strlen(suffix);
490
491         if (!(r = new(char, a+b+1)))
492                 return NULL;
493
494         memcpy(r, s, a);
495         memcpy(r+a, suffix, b);
496         r[a+b] = 0;
497
498         return r;
499 }
500
501 int readlink_malloc(const char *p, char **r) {
502         size_t l = 100;
503
504         assert(p);
505         assert(r);
506
507         for (;;) {
508                 char *c;
509                 ssize_t n;
510
511                 if (!(c = new(char, l)))
512                         return -ENOMEM;
513
514                 if ((n = readlink(p, c, l-1)) < 0) {
515                         int ret = -errno;
516                         free(c);
517                         return ret;
518                 }
519
520                 if ((size_t) n < l-1) {
521                         c[n] = 0;
522                         *r = c;
523                         return 0;
524                 }
525
526                 free(c);
527                 l *= 2;
528         }
529 }
530
531 char *file_name_from_path(const char *p) {
532         char *r;
533
534         assert(p);
535
536         if ((r = strrchr(p, '/')))
537                 return r + 1;
538
539         return (char*) p;
540 }
541
542 bool path_is_absolute(const char *p) {
543         assert(p);
544
545         return p[0] == '/';
546 }
547
548 bool is_path(const char *p) {
549
550         return !!strchr(p, '/');
551 }
552
553 char *path_make_absolute(const char *p, const char *prefix) {
554         char *r;
555
556         assert(p);
557
558         /* Makes every item in the list an absolute path by prepending
559          * the prefix, if specified and necessary */
560
561         if (path_is_absolute(p) || !prefix)
562                 return strdup(p);
563
564         if (asprintf(&r, "%s/%s", prefix, p) < 0)
565                 return NULL;
566
567         return r;
568 }
569
570 char *path_make_absolute_cwd(const char *p) {
571         char *cwd, *r;
572
573         assert(p);
574
575         /* Similar to path_make_absolute(), but prefixes with the
576          * current working directory. */
577
578         if (path_is_absolute(p))
579                 return strdup(p);
580
581         if (!(cwd = get_current_dir_name()))
582                 return NULL;
583
584         r = path_make_absolute(p, cwd);
585         free(cwd);
586
587         return r;
588 }
589
590 char **strv_path_make_absolute_cwd(char **l) {
591         char **s;
592
593         /* Goes through every item in the string list and makes it
594          * absolute. This works in place and won't rollback any
595          * changes on failure. */
596
597         STRV_FOREACH(s, l) {
598                 char *t;
599
600                 if (!(t = path_make_absolute_cwd(*s)))
601                         return NULL;
602
603                 free(*s);
604                 *s = t;
605         }
606
607         return l;
608 }
609
610 int reset_all_signal_handlers(void) {
611         int sig;
612
613         for (sig = 1; sig < _NSIG; sig++) {
614                 struct sigaction sa;
615
616                 if (sig == SIGKILL || sig == SIGSTOP)
617                         continue;
618
619                 zero(sa);
620                 sa.sa_handler = SIG_DFL;
621                 sa.sa_flags = SA_RESTART;
622
623                 /* On Linux the first two RT signals are reserved by
624                  * glibc, and sigaction() will return EINVAL for them. */
625                 if ((sigaction(sig, &sa, NULL) < 0))
626                         if (errno != EINVAL)
627                                 return -errno;
628         }
629
630         return 0;
631 }
632
633 char *strstrip(char *s) {
634         char *e, *l = NULL;
635
636         /* Drops trailing whitespace. Modifies the string in
637          * place. Returns pointer to first non-space character */
638
639         s += strspn(s, WHITESPACE);
640
641         for (e = s; *e; e++)
642                 if (!strchr(WHITESPACE, *e))
643                         l = e;
644
645         if (l)
646                 *(l+1) = 0;
647         else
648                 *s = 0;
649
650         return s;
651
652 }
653
654 char *delete_chars(char *s, const char *bad) {
655         char *f, *t;
656
657         /* Drops all whitespace, regardless where in the string */
658
659         for (f = s, t = s; *f; f++) {
660                 if (strchr(bad, *f))
661                         continue;
662
663                 *(t++) = *f;
664         }
665
666         *t = 0;
667
668         return s;
669 }
670
671 char *file_in_same_dir(const char *path, const char *filename) {
672         char *e, *r;
673         size_t k;
674
675         assert(path);
676         assert(filename);
677
678         /* This removes the last component of path and appends
679          * filename, unless the latter is absolute anyway or the
680          * former isn't */
681
682         if (path_is_absolute(filename))
683                 return strdup(filename);
684
685         if (!(e = strrchr(path, '/')))
686                 return strdup(filename);
687
688         k = strlen(filename);
689         if (!(r = new(char, e-path+1+k+1)))
690                 return NULL;
691
692         memcpy(r, path, e-path+1);
693         memcpy(r+(e-path)+1, filename, k+1);
694
695         return r;
696 }
697
698 int mkdir_parents(const char *path, mode_t mode) {
699         const char *p, *e;
700
701         assert(path);
702
703         /* Creates every parent directory in the path except the last
704          * component. */
705
706         p = path + strspn(path, "/");
707         for (;;) {
708                 int r;
709                 char *t;
710
711                 e = p + strcspn(p, "/");
712                 p = e + strspn(e, "/");
713
714                 /* Is this the last component? If so, then we're
715                  * done */
716                 if (*p == 0)
717                         return 0;
718
719                 if (!(t = strndup(path, e - path)))
720                         return -ENOMEM;
721
722                 r = mkdir(t, mode);
723
724                 free(t);
725
726                 if (r < 0 && errno != EEXIST)
727                         return -errno;
728         }
729 }
730
731 char hexchar(int x) {
732         static const char table[16] = "0123456789abcdef";
733
734         return table[x & 15];
735 }
736
737 int unhexchar(char c) {
738
739         if (c >= '0' && c <= '9')
740                 return c - '0';
741
742         if (c >= 'a' && c <= 'f')
743                 return c - 'a' + 10;
744
745         if (c >= 'A' && c <= 'F')
746                 return c - 'A' + 10;
747
748         return -1;
749 }
750
751 char octchar(int x) {
752         return '0' + (x & 7);
753 }
754
755 int unoctchar(char c) {
756
757         if (c >= '0' && c <= '7')
758                 return c - '0';
759
760         return -1;
761 }
762
763 char decchar(int x) {
764         return '0' + (x % 10);
765 }
766
767 int undecchar(char c) {
768
769         if (c >= '0' && c <= '9')
770                 return c - '0';
771
772         return -1;
773 }
774
775 char *cescape(const char *s) {
776         char *r, *t;
777         const char *f;
778
779         assert(s);
780
781         /* Does C style string escaping. */
782
783         if (!(r = new(char, strlen(s)*4 + 1)))
784                 return NULL;
785
786         for (f = s, t = r; *f; f++)
787
788                 switch (*f) {
789
790                 case '\a':
791                         *(t++) = '\\';
792                         *(t++) = 'a';
793                         break;
794                 case '\b':
795                         *(t++) = '\\';
796                         *(t++) = 'b';
797                         break;
798                 case '\f':
799                         *(t++) = '\\';
800                         *(t++) = 'f';
801                         break;
802                 case '\n':
803                         *(t++) = '\\';
804                         *(t++) = 'n';
805                         break;
806                 case '\r':
807                         *(t++) = '\\';
808                         *(t++) = 'r';
809                         break;
810                 case '\t':
811                         *(t++) = '\\';
812                         *(t++) = 't';
813                         break;
814                 case '\v':
815                         *(t++) = '\\';
816                         *(t++) = 'v';
817                         break;
818                 case '\\':
819                         *(t++) = '\\';
820                         *(t++) = '\\';
821                         break;
822                 case '"':
823                         *(t++) = '\\';
824                         *(t++) = '"';
825                         break;
826                 case '\'':
827                         *(t++) = '\\';
828                         *(t++) = '\'';
829                         break;
830
831                 default:
832                         /* For special chars we prefer octal over
833                          * hexadecimal encoding, simply because glib's
834                          * g_strescape() does the same */
835                         if ((*f < ' ') || (*f >= 127)) {
836                                 *(t++) = '\\';
837                                 *(t++) = octchar((unsigned char) *f >> 6);
838                                 *(t++) = octchar((unsigned char) *f >> 3);
839                                 *(t++) = octchar((unsigned char) *f);
840                         } else
841                                 *(t++) = *f;
842                         break;
843                 }
844
845         *t = 0;
846
847         return r;
848 }
849
850 char *cunescape(const char *s) {
851         char *r, *t;
852         const char *f;
853
854         assert(s);
855
856         /* Undoes C style string escaping */
857
858         if (!(r = new(char, strlen(s)+1)))
859                 return r;
860
861         for (f = s, t = r; *f; f++) {
862
863                 if (*f != '\\') {
864                         *(t++) = *f;
865                         continue;
866                 }
867
868                 f++;
869
870                 switch (*f) {
871
872                 case 'a':
873                         *(t++) = '\a';
874                         break;
875                 case 'b':
876                         *(t++) = '\b';
877                         break;
878                 case 'f':
879                         *(t++) = '\f';
880                         break;
881                 case 'n':
882                         *(t++) = '\n';
883                         break;
884                 case 'r':
885                         *(t++) = '\r';
886                         break;
887                 case 't':
888                         *(t++) = '\t';
889                         break;
890                 case 'v':
891                         *(t++) = '\v';
892                         break;
893                 case '\\':
894                         *(t++) = '\\';
895                         break;
896                 case '"':
897                         *(t++) = '"';
898                         break;
899                 case '\'':
900                         *(t++) = '\'';
901                         break;
902
903                 case 'x': {
904                         /* hexadecimal encoding */
905                         int a, b;
906
907                         if ((a = unhexchar(f[1])) < 0 ||
908                             (b = unhexchar(f[2])) < 0) {
909                                 /* Invalid escape code, let's take it literal then */
910                                 *(t++) = '\\';
911                                 *(t++) = 'x';
912                         } else {
913                                 *(t++) = (char) ((a << 4) | b);
914                                 f += 2;
915                         }
916
917                         break;
918                 }
919
920                 case '0':
921                 case '1':
922                 case '2':
923                 case '3':
924                 case '4':
925                 case '5':
926                 case '6':
927                 case '7': {
928                         /* octal encoding */
929                         int a, b, c;
930
931                         if ((a = unoctchar(f[0])) < 0 ||
932                             (b = unoctchar(f[1])) < 0 ||
933                             (c = unoctchar(f[2])) < 0) {
934                                 /* Invalid escape code, let's take it literal then */
935                                 *(t++) = '\\';
936                                 *(t++) = f[0];
937                         } else {
938                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
939                                 f += 2;
940                         }
941
942                         break;
943                 }
944
945                 case 0:
946                         /* premature end of string.*/
947                         *(t++) = '\\';
948                         goto finish;
949
950                 default:
951                         /* Invalid escape code, let's take it literal then */
952                         *(t++) = '\\';
953                         *(t++) = 'f';
954                         break;
955                 }
956         }
957
958 finish:
959         *t = 0;
960         return r;
961 }
962
963
964 char *xescape(const char *s, const char *bad) {
965         char *r, *t;
966         const char *f;
967
968         /* Escapes all chars in bad, in addition to \ and all special
969          * chars, in \xFF style escaping. May be reversed with
970          * cunescape. */
971
972         if (!(r = new(char, strlen(s)*4+1)))
973                 return NULL;
974
975         for (f = s, t = r; *f; f++) {
976
977                 if ((*f < ' ') || (*f >= 127) ||
978                     (*f == '\\') || strchr(bad, *f)) {
979                         *(t++) = '\\';
980                         *(t++) = 'x';
981                         *(t++) = hexchar(*f >> 4);
982                         *(t++) = hexchar(*f);
983                 } else
984                         *(t++) = *f;
985         }
986
987         *t = 0;
988
989         return r;
990 }
991
992 char *bus_path_escape(const char *s) {
993         char *r, *t;
994         const char *f;
995
996         assert(s);
997
998         /* Escapes all chars that D-Bus' object path cannot deal
999          * with. Can be reverse with bus_path_unescape() */
1000
1001         if (!(r = new(char, strlen(s)*3+1)))
1002                 return NULL;
1003
1004         for (f = s, t = r; *f; f++) {
1005
1006                 if (!(*f >= 'A' && *f <= 'Z') &&
1007                     !(*f >= 'a' && *f <= 'z') &&
1008                     !(*f >= '0' && *f <= '9')) {
1009                         *(t++) = '_';
1010                         *(t++) = hexchar(*f >> 4);
1011                         *(t++) = hexchar(*f);
1012                 } else
1013                         *(t++) = *f;
1014         }
1015
1016         *t = 0;
1017
1018         return r;
1019 }
1020
1021 char *bus_path_unescape(const char *s) {
1022         char *r, *t;
1023         const char *f;
1024
1025         assert(s);
1026
1027         if (!(r = new(char, strlen(s)+1)))
1028                 return NULL;
1029
1030         for (f = s, t = r; *f; f++) {
1031
1032                 if (*f == '_') {
1033                         int a, b;
1034
1035                         if ((a = unhexchar(f[1])) < 0 ||
1036                             (b = unhexchar(f[2])) < 0) {
1037                                 /* Invalid escape code, let's take it literal then */
1038                                 *(t++) = '_';
1039                         } else {
1040                                 *(t++) = (char) ((a << 4) | b);
1041                                 f += 2;
1042                         }
1043                 } else
1044                         *(t++) = *f;
1045         }
1046
1047         *t = 0;
1048
1049         return r;
1050 }
1051
1052 char *path_kill_slashes(char *path) {
1053         char *f, *t;
1054         bool slash = false;
1055
1056         /* Removes redundant inner and trailing slashes. Modifies the
1057          * passed string in-place.
1058          *
1059          * ///foo///bar/ becomes /foo/bar
1060          */
1061
1062         for (f = path, t = path; *f; f++) {
1063
1064                 if (*f == '/') {
1065                         slash = true;
1066                         continue;
1067                 }
1068
1069                 if (slash) {
1070                         slash = false;
1071                         *(t++) = '/';
1072                 }
1073
1074                 *(t++) = *f;
1075         }
1076
1077         /* Special rule, if we are talking of the root directory, a
1078         trailing slash is good */
1079
1080         if (t == path && slash)
1081                 *(t++) = '/';
1082
1083         *t = 0;
1084         return path;
1085 }
1086
1087 bool path_startswith(const char *path, const char *prefix) {
1088         assert(path);
1089         assert(prefix);
1090
1091         if ((path[0] == '/') != (prefix[0] == '/'))
1092                 return false;
1093
1094         for (;;) {
1095                 size_t a, b;
1096
1097                 path += strspn(path, "/");
1098                 prefix += strspn(prefix, "/");
1099
1100                 if (*prefix == 0)
1101                         return true;
1102
1103                 if (*path == 0)
1104                         return false;
1105
1106                 a = strcspn(path, "/");
1107                 b = strcspn(prefix, "/");
1108
1109                 if (a != b)
1110                         return false;
1111
1112                 if (memcmp(path, prefix, a) != 0)
1113                         return false;
1114
1115                 path += a;
1116                 prefix += b;
1117         }
1118 }
1119
1120 char *ascii_strlower(char *t) {
1121         char *p;
1122
1123         assert(t);
1124
1125         for (p = t; *p; p++)
1126                 if (*p >= 'A' && *p <= 'Z')
1127                         *p = *p - 'A' + 'a';
1128
1129         return t;
1130 }
1131
1132 bool ignore_file(const char *filename) {
1133         assert(filename);
1134
1135         return
1136                 filename[0] == '.' ||
1137                 endswith(filename, "~") ||
1138                 endswith(filename, ".rpmnew") ||
1139                 endswith(filename, ".rpmsave") ||
1140                 endswith(filename, ".rpmorig") ||
1141                 endswith(filename, ".dpkg-old") ||
1142                 endswith(filename, ".dpkg-new") ||
1143                 endswith(filename, ".swp");
1144 }
1145
1146 int fd_nonblock(int fd, bool nonblock) {
1147         int flags;
1148
1149         assert(fd >= 0);
1150
1151         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1152                 return -errno;
1153
1154         if (nonblock)
1155                 flags |= O_NONBLOCK;
1156         else
1157                 flags &= ~O_NONBLOCK;
1158
1159         if (fcntl(fd, F_SETFL, flags) < 0)
1160                 return -errno;
1161
1162         return 0;
1163 }
1164
1165 int fd_cloexec(int fd, bool cloexec) {
1166         int flags;
1167
1168         assert(fd >= 0);
1169
1170         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1171                 return -errno;
1172
1173         if (cloexec)
1174                 flags |= FD_CLOEXEC;
1175         else
1176                 flags &= ~FD_CLOEXEC;
1177
1178         if (fcntl(fd, F_SETFD, flags) < 0)
1179                 return -errno;
1180
1181         return 0;
1182 }
1183
1184 int close_all_fds(const int except[], unsigned n_except) {
1185         DIR *d;
1186         struct dirent *de;
1187         int r = 0;
1188
1189         if (!(d = opendir("/proc/self/fd")))
1190                 return -errno;
1191
1192         while ((de = readdir(d))) {
1193                 int fd = -1;
1194
1195                 if (de->d_name[0] == '.')
1196                         continue;
1197
1198                 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1199                         goto finish;
1200
1201                 if (fd < 3)
1202                         continue;
1203
1204                 if (fd == dirfd(d))
1205                         continue;
1206
1207                 if (except) {
1208                         bool found;
1209                         unsigned i;
1210
1211                         found = false;
1212                         for (i = 0; i < n_except; i++)
1213                                 if (except[i] == fd) {
1214                                         found = true;
1215                                         break;
1216                                 }
1217
1218                         if (found)
1219                                 continue;
1220                 }
1221
1222                 if ((r = close_nointr(fd)) < 0) {
1223                         /* Valgrind has its own FD and doesn't want to have it closed */
1224                         if (errno != EBADF)
1225                                 goto finish;
1226                 }
1227         }
1228
1229         r = 0;
1230
1231 finish:
1232         closedir(d);
1233         return r;
1234 }
1235
1236 bool chars_intersect(const char *a, const char *b) {
1237         const char *p;
1238
1239         /* Returns true if any of the chars in a are in b. */
1240         for (p = a; *p; p++)
1241                 if (strchr(b, *p))
1242                         return true;
1243
1244         return false;
1245 }
1246
1247 static const char *const ioprio_class_table[] = {
1248         [IOPRIO_CLASS_NONE] = "none",
1249         [IOPRIO_CLASS_RT] = "realtime",
1250         [IOPRIO_CLASS_BE] = "best-effort",
1251         [IOPRIO_CLASS_IDLE] = "idle"
1252 };
1253
1254 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
1255
1256 static const char *const sigchld_code_table[] = {
1257         [CLD_EXITED] = "exited",
1258         [CLD_KILLED] = "killed",
1259         [CLD_DUMPED] = "dumped",
1260         [CLD_TRAPPED] = "trapped",
1261         [CLD_STOPPED] = "stopped",
1262         [CLD_CONTINUED] = "continued",
1263 };
1264
1265 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
1266
1267 static const char *const log_facility_table[LOG_NFACILITIES] = {
1268         [LOG_FAC(LOG_KERN)] = "kern",
1269         [LOG_FAC(LOG_USER)] = "user",
1270         [LOG_FAC(LOG_MAIL)] = "mail",
1271         [LOG_FAC(LOG_DAEMON)] = "daemon",
1272         [LOG_FAC(LOG_AUTH)] = "auth",
1273         [LOG_FAC(LOG_SYSLOG)] = "syslog",
1274         [LOG_FAC(LOG_LPR)] = "lpr",
1275         [LOG_FAC(LOG_NEWS)] = "news",
1276         [LOG_FAC(LOG_UUCP)] = "uucp",
1277         [LOG_FAC(LOG_CRON)] = "cron",
1278         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
1279         [LOG_FAC(LOG_FTP)] = "ftp",
1280         [LOG_FAC(LOG_LOCAL0)] = "local0",
1281         [LOG_FAC(LOG_LOCAL1)] = "local1",
1282         [LOG_FAC(LOG_LOCAL2)] = "local2",
1283         [LOG_FAC(LOG_LOCAL3)] = "local3",
1284         [LOG_FAC(LOG_LOCAL4)] = "local4",
1285         [LOG_FAC(LOG_LOCAL5)] = "local5",
1286         [LOG_FAC(LOG_LOCAL6)] = "local6",
1287         [LOG_FAC(LOG_LOCAL7)] = "local7"
1288 };
1289
1290 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
1291
1292 static const char *const log_level_table[] = {
1293         [LOG_EMERG] = "emerg",
1294         [LOG_ALERT] = "alert",
1295         [LOG_CRIT] = "crit",
1296         [LOG_ERR] = "err",
1297         [LOG_WARNING] = "warning",
1298         [LOG_NOTICE] = "notice",
1299         [LOG_INFO] = "info",
1300         [LOG_DEBUG] = "debug"
1301 };
1302
1303 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
1304
1305 static const char* const sched_policy_table[] = {
1306         [SCHED_OTHER] = "other",
1307         [SCHED_BATCH] = "batch",
1308         [SCHED_IDLE] = "idle",
1309         [SCHED_FIFO] = "fifo",
1310         [SCHED_RR] = "rr"
1311 };
1312
1313 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
1314
1315 static const char* const rlimit_table[] = {
1316         [RLIMIT_CPU] = "LimitCPU",
1317         [RLIMIT_FSIZE] = "LimitFSIZE",
1318         [RLIMIT_DATA] = "LimitDATA",
1319         [RLIMIT_STACK] = "LimitSTACK",
1320         [RLIMIT_CORE] = "LimitCORE",
1321         [RLIMIT_RSS] = "LimitRSS",
1322         [RLIMIT_NOFILE] = "LimitNOFILE",
1323         [RLIMIT_AS] = "LimitAS",
1324         [RLIMIT_NPROC] = "LimitNPROC",
1325         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
1326         [RLIMIT_LOCKS] = "LimitLOCKS",
1327         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
1328         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
1329         [RLIMIT_NICE] = "LimitNICE",
1330         [RLIMIT_RTPRIO] = "LimitRTPRIO",
1331         [RLIMIT_RTTIME] = "LimitRTTIME"
1332 };
1333
1334 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);