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