chiark / gitweb /
build-sys: automatically figure out names of dbus/syslog services
[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 int mkdir_p(const char *path, mode_t mode) {
732         int r;
733
734         /* Like mkdir -p */
735
736         if ((r = mkdir_parents(path, mode)) < 0)
737                 return r;
738
739         if (mkdir(path, mode) < 0)
740                 return -errno;
741
742         return 0;
743 }
744
745 char hexchar(int x) {
746         static const char table[16] = "0123456789abcdef";
747
748         return table[x & 15];
749 }
750
751 int unhexchar(char c) {
752
753         if (c >= '0' && c <= '9')
754                 return c - '0';
755
756         if (c >= 'a' && c <= 'f')
757                 return c - 'a' + 10;
758
759         if (c >= 'A' && c <= 'F')
760                 return c - 'A' + 10;
761
762         return -1;
763 }
764
765 char octchar(int x) {
766         return '0' + (x & 7);
767 }
768
769 int unoctchar(char c) {
770
771         if (c >= '0' && c <= '7')
772                 return c - '0';
773
774         return -1;
775 }
776
777 char decchar(int x) {
778         return '0' + (x % 10);
779 }
780
781 int undecchar(char c) {
782
783         if (c >= '0' && c <= '9')
784                 return c - '0';
785
786         return -1;
787 }
788
789 char *cescape(const char *s) {
790         char *r, *t;
791         const char *f;
792
793         assert(s);
794
795         /* Does C style string escaping. */
796
797         if (!(r = new(char, strlen(s)*4 + 1)))
798                 return NULL;
799
800         for (f = s, t = r; *f; f++)
801
802                 switch (*f) {
803
804                 case '\a':
805                         *(t++) = '\\';
806                         *(t++) = 'a';
807                         break;
808                 case '\b':
809                         *(t++) = '\\';
810                         *(t++) = 'b';
811                         break;
812                 case '\f':
813                         *(t++) = '\\';
814                         *(t++) = 'f';
815                         break;
816                 case '\n':
817                         *(t++) = '\\';
818                         *(t++) = 'n';
819                         break;
820                 case '\r':
821                         *(t++) = '\\';
822                         *(t++) = 'r';
823                         break;
824                 case '\t':
825                         *(t++) = '\\';
826                         *(t++) = 't';
827                         break;
828                 case '\v':
829                         *(t++) = '\\';
830                         *(t++) = 'v';
831                         break;
832                 case '\\':
833                         *(t++) = '\\';
834                         *(t++) = '\\';
835                         break;
836                 case '"':
837                         *(t++) = '\\';
838                         *(t++) = '"';
839                         break;
840                 case '\'':
841                         *(t++) = '\\';
842                         *(t++) = '\'';
843                         break;
844
845                 default:
846                         /* For special chars we prefer octal over
847                          * hexadecimal encoding, simply because glib's
848                          * g_strescape() does the same */
849                         if ((*f < ' ') || (*f >= 127)) {
850                                 *(t++) = '\\';
851                                 *(t++) = octchar((unsigned char) *f >> 6);
852                                 *(t++) = octchar((unsigned char) *f >> 3);
853                                 *(t++) = octchar((unsigned char) *f);
854                         } else
855                                 *(t++) = *f;
856                         break;
857                 }
858
859         *t = 0;
860
861         return r;
862 }
863
864 char *cunescape(const char *s) {
865         char *r, *t;
866         const char *f;
867
868         assert(s);
869
870         /* Undoes C style string escaping */
871
872         if (!(r = new(char, strlen(s)+1)))
873                 return r;
874
875         for (f = s, t = r; *f; f++) {
876
877                 if (*f != '\\') {
878                         *(t++) = *f;
879                         continue;
880                 }
881
882                 f++;
883
884                 switch (*f) {
885
886                 case 'a':
887                         *(t++) = '\a';
888                         break;
889                 case 'b':
890                         *(t++) = '\b';
891                         break;
892                 case 'f':
893                         *(t++) = '\f';
894                         break;
895                 case 'n':
896                         *(t++) = '\n';
897                         break;
898                 case 'r':
899                         *(t++) = '\r';
900                         break;
901                 case 't':
902                         *(t++) = '\t';
903                         break;
904                 case 'v':
905                         *(t++) = '\v';
906                         break;
907                 case '\\':
908                         *(t++) = '\\';
909                         break;
910                 case '"':
911                         *(t++) = '"';
912                         break;
913                 case '\'':
914                         *(t++) = '\'';
915                         break;
916
917                 case 'x': {
918                         /* hexadecimal encoding */
919                         int a, b;
920
921                         if ((a = unhexchar(f[1])) < 0 ||
922                             (b = unhexchar(f[2])) < 0) {
923                                 /* Invalid escape code, let's take it literal then */
924                                 *(t++) = '\\';
925                                 *(t++) = 'x';
926                         } else {
927                                 *(t++) = (char) ((a << 4) | b);
928                                 f += 2;
929                         }
930
931                         break;
932                 }
933
934                 case '0':
935                 case '1':
936                 case '2':
937                 case '3':
938                 case '4':
939                 case '5':
940                 case '6':
941                 case '7': {
942                         /* octal encoding */
943                         int a, b, c;
944
945                         if ((a = unoctchar(f[0])) < 0 ||
946                             (b = unoctchar(f[1])) < 0 ||
947                             (c = unoctchar(f[2])) < 0) {
948                                 /* Invalid escape code, let's take it literal then */
949                                 *(t++) = '\\';
950                                 *(t++) = f[0];
951                         } else {
952                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
953                                 f += 2;
954                         }
955
956                         break;
957                 }
958
959                 case 0:
960                         /* premature end of string.*/
961                         *(t++) = '\\';
962                         goto finish;
963
964                 default:
965                         /* Invalid escape code, let's take it literal then */
966                         *(t++) = '\\';
967                         *(t++) = 'f';
968                         break;
969                 }
970         }
971
972 finish:
973         *t = 0;
974         return r;
975 }
976
977
978 char *xescape(const char *s, const char *bad) {
979         char *r, *t;
980         const char *f;
981
982         /* Escapes all chars in bad, in addition to \ and all special
983          * chars, in \xFF style escaping. May be reversed with
984          * cunescape. */
985
986         if (!(r = new(char, strlen(s)*4+1)))
987                 return NULL;
988
989         for (f = s, t = r; *f; f++) {
990
991                 if ((*f < ' ') || (*f >= 127) ||
992                     (*f == '\\') || strchr(bad, *f)) {
993                         *(t++) = '\\';
994                         *(t++) = 'x';
995                         *(t++) = hexchar(*f >> 4);
996                         *(t++) = hexchar(*f);
997                 } else
998                         *(t++) = *f;
999         }
1000
1001         *t = 0;
1002
1003         return r;
1004 }
1005
1006 char *bus_path_escape(const char *s) {
1007         char *r, *t;
1008         const char *f;
1009
1010         assert(s);
1011
1012         /* Escapes all chars that D-Bus' object path cannot deal
1013          * with. Can be reverse with bus_path_unescape() */
1014
1015         if (!(r = new(char, strlen(s)*3+1)))
1016                 return NULL;
1017
1018         for (f = s, t = r; *f; f++) {
1019
1020                 if (!(*f >= 'A' && *f <= 'Z') &&
1021                     !(*f >= 'a' && *f <= 'z') &&
1022                     !(*f >= '0' && *f <= '9')) {
1023                         *(t++) = '_';
1024                         *(t++) = hexchar(*f >> 4);
1025                         *(t++) = hexchar(*f);
1026                 } else
1027                         *(t++) = *f;
1028         }
1029
1030         *t = 0;
1031
1032         return r;
1033 }
1034
1035 char *bus_path_unescape(const char *s) {
1036         char *r, *t;
1037         const char *f;
1038
1039         assert(s);
1040
1041         if (!(r = new(char, strlen(s)+1)))
1042                 return NULL;
1043
1044         for (f = s, t = r; *f; f++) {
1045
1046                 if (*f == '_') {
1047                         int a, b;
1048
1049                         if ((a = unhexchar(f[1])) < 0 ||
1050                             (b = unhexchar(f[2])) < 0) {
1051                                 /* Invalid escape code, let's take it literal then */
1052                                 *(t++) = '_';
1053                         } else {
1054                                 *(t++) = (char) ((a << 4) | b);
1055                                 f += 2;
1056                         }
1057                 } else
1058                         *(t++) = *f;
1059         }
1060
1061         *t = 0;
1062
1063         return r;
1064 }
1065
1066 char *path_kill_slashes(char *path) {
1067         char *f, *t;
1068         bool slash = false;
1069
1070         /* Removes redundant inner and trailing slashes. Modifies the
1071          * passed string in-place.
1072          *
1073          * ///foo///bar/ becomes /foo/bar
1074          */
1075
1076         for (f = path, t = path; *f; f++) {
1077
1078                 if (*f == '/') {
1079                         slash = true;
1080                         continue;
1081                 }
1082
1083                 if (slash) {
1084                         slash = false;
1085                         *(t++) = '/';
1086                 }
1087
1088                 *(t++) = *f;
1089         }
1090
1091         /* Special rule, if we are talking of the root directory, a
1092         trailing slash is good */
1093
1094         if (t == path && slash)
1095                 *(t++) = '/';
1096
1097         *t = 0;
1098         return path;
1099 }
1100
1101 bool path_startswith(const char *path, const char *prefix) {
1102         assert(path);
1103         assert(prefix);
1104
1105         if ((path[0] == '/') != (prefix[0] == '/'))
1106                 return false;
1107
1108         for (;;) {
1109                 size_t a, b;
1110
1111                 path += strspn(path, "/");
1112                 prefix += strspn(prefix, "/");
1113
1114                 if (*prefix == 0)
1115                         return true;
1116
1117                 if (*path == 0)
1118                         return false;
1119
1120                 a = strcspn(path, "/");
1121                 b = strcspn(prefix, "/");
1122
1123                 if (a != b)
1124                         return false;
1125
1126                 if (memcmp(path, prefix, a) != 0)
1127                         return false;
1128
1129                 path += a;
1130                 prefix += b;
1131         }
1132 }
1133
1134 char *ascii_strlower(char *t) {
1135         char *p;
1136
1137         assert(t);
1138
1139         for (p = t; *p; p++)
1140                 if (*p >= 'A' && *p <= 'Z')
1141                         *p = *p - 'A' + 'a';
1142
1143         return t;
1144 }
1145
1146 bool ignore_file(const char *filename) {
1147         assert(filename);
1148
1149         return
1150                 filename[0] == '.' ||
1151                 endswith(filename, "~") ||
1152                 endswith(filename, ".rpmnew") ||
1153                 endswith(filename, ".rpmsave") ||
1154                 endswith(filename, ".rpmorig") ||
1155                 endswith(filename, ".dpkg-old") ||
1156                 endswith(filename, ".dpkg-new") ||
1157                 endswith(filename, ".swp");
1158 }
1159
1160 int fd_nonblock(int fd, bool nonblock) {
1161         int flags;
1162
1163         assert(fd >= 0);
1164
1165         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1166                 return -errno;
1167
1168         if (nonblock)
1169                 flags |= O_NONBLOCK;
1170         else
1171                 flags &= ~O_NONBLOCK;
1172
1173         if (fcntl(fd, F_SETFL, flags) < 0)
1174                 return -errno;
1175
1176         return 0;
1177 }
1178
1179 int fd_cloexec(int fd, bool cloexec) {
1180         int flags;
1181
1182         assert(fd >= 0);
1183
1184         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1185                 return -errno;
1186
1187         if (cloexec)
1188                 flags |= FD_CLOEXEC;
1189         else
1190                 flags &= ~FD_CLOEXEC;
1191
1192         if (fcntl(fd, F_SETFD, flags) < 0)
1193                 return -errno;
1194
1195         return 0;
1196 }
1197
1198 int close_all_fds(const int except[], unsigned n_except) {
1199         DIR *d;
1200         struct dirent *de;
1201         int r = 0;
1202
1203         if (!(d = opendir("/proc/self/fd")))
1204                 return -errno;
1205
1206         while ((de = readdir(d))) {
1207                 int fd = -1;
1208
1209                 if (de->d_name[0] == '.')
1210                         continue;
1211
1212                 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1213                         goto finish;
1214
1215                 if (fd < 3)
1216                         continue;
1217
1218                 if (fd == dirfd(d))
1219                         continue;
1220
1221                 if (except) {
1222                         bool found;
1223                         unsigned i;
1224
1225                         found = false;
1226                         for (i = 0; i < n_except; i++)
1227                                 if (except[i] == fd) {
1228                                         found = true;
1229                                         break;
1230                                 }
1231
1232                         if (found)
1233                                 continue;
1234                 }
1235
1236                 if ((r = close_nointr(fd)) < 0) {
1237                         /* Valgrind has its own FD and doesn't want to have it closed */
1238                         if (errno != EBADF)
1239                                 goto finish;
1240                 }
1241         }
1242
1243         r = 0;
1244
1245 finish:
1246         closedir(d);
1247         return r;
1248 }
1249
1250 bool chars_intersect(const char *a, const char *b) {
1251         const char *p;
1252
1253         /* Returns true if any of the chars in a are in b. */
1254         for (p = a; *p; p++)
1255                 if (strchr(b, *p))
1256                         return true;
1257
1258         return false;
1259 }
1260
1261 char *format_timestamp(char *buf, size_t l, usec_t t) {
1262         struct tm tm;
1263         time_t sec;
1264
1265         assert(buf);
1266         assert(l > 0);
1267
1268         if (t <= 0)
1269                 return NULL;
1270
1271         sec = (time_t) t / USEC_PER_SEC;
1272
1273         if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1274                 return NULL;
1275
1276         return buf;
1277 }
1278
1279 static const char *const ioprio_class_table[] = {
1280         [IOPRIO_CLASS_NONE] = "none",
1281         [IOPRIO_CLASS_RT] = "realtime",
1282         [IOPRIO_CLASS_BE] = "best-effort",
1283         [IOPRIO_CLASS_IDLE] = "idle"
1284 };
1285
1286 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
1287
1288 static const char *const sigchld_code_table[] = {
1289         [CLD_EXITED] = "exited",
1290         [CLD_KILLED] = "killed",
1291         [CLD_DUMPED] = "dumped",
1292         [CLD_TRAPPED] = "trapped",
1293         [CLD_STOPPED] = "stopped",
1294         [CLD_CONTINUED] = "continued",
1295 };
1296
1297 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
1298
1299 static const char *const log_facility_table[LOG_NFACILITIES] = {
1300         [LOG_FAC(LOG_KERN)] = "kern",
1301         [LOG_FAC(LOG_USER)] = "user",
1302         [LOG_FAC(LOG_MAIL)] = "mail",
1303         [LOG_FAC(LOG_DAEMON)] = "daemon",
1304         [LOG_FAC(LOG_AUTH)] = "auth",
1305         [LOG_FAC(LOG_SYSLOG)] = "syslog",
1306         [LOG_FAC(LOG_LPR)] = "lpr",
1307         [LOG_FAC(LOG_NEWS)] = "news",
1308         [LOG_FAC(LOG_UUCP)] = "uucp",
1309         [LOG_FAC(LOG_CRON)] = "cron",
1310         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
1311         [LOG_FAC(LOG_FTP)] = "ftp",
1312         [LOG_FAC(LOG_LOCAL0)] = "local0",
1313         [LOG_FAC(LOG_LOCAL1)] = "local1",
1314         [LOG_FAC(LOG_LOCAL2)] = "local2",
1315         [LOG_FAC(LOG_LOCAL3)] = "local3",
1316         [LOG_FAC(LOG_LOCAL4)] = "local4",
1317         [LOG_FAC(LOG_LOCAL5)] = "local5",
1318         [LOG_FAC(LOG_LOCAL6)] = "local6",
1319         [LOG_FAC(LOG_LOCAL7)] = "local7"
1320 };
1321
1322 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
1323
1324 static const char *const log_level_table[] = {
1325         [LOG_EMERG] = "emerg",
1326         [LOG_ALERT] = "alert",
1327         [LOG_CRIT] = "crit",
1328         [LOG_ERR] = "err",
1329         [LOG_WARNING] = "warning",
1330         [LOG_NOTICE] = "notice",
1331         [LOG_INFO] = "info",
1332         [LOG_DEBUG] = "debug"
1333 };
1334
1335 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
1336
1337 static const char* const sched_policy_table[] = {
1338         [SCHED_OTHER] = "other",
1339         [SCHED_BATCH] = "batch",
1340         [SCHED_IDLE] = "idle",
1341         [SCHED_FIFO] = "fifo",
1342         [SCHED_RR] = "rr"
1343 };
1344
1345 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
1346
1347 static const char* const rlimit_table[] = {
1348         [RLIMIT_CPU] = "LimitCPU",
1349         [RLIMIT_FSIZE] = "LimitFSIZE",
1350         [RLIMIT_DATA] = "LimitDATA",
1351         [RLIMIT_STACK] = "LimitSTACK",
1352         [RLIMIT_CORE] = "LimitCORE",
1353         [RLIMIT_RSS] = "LimitRSS",
1354         [RLIMIT_NOFILE] = "LimitNOFILE",
1355         [RLIMIT_AS] = "LimitAS",
1356         [RLIMIT_NPROC] = "LimitNPROC",
1357         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
1358         [RLIMIT_LOCKS] = "LimitLOCKS",
1359         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
1360         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
1361         [RLIMIT_NICE] = "LimitNICE",
1362         [RLIMIT_RTPRIO] = "LimitRTPRIO",
1363         [RLIMIT_RTTIME] = "LimitRTTIME"
1364 };
1365
1366 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);