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