chiark / gitweb /
load-fragment: simplify fragment loading code by using macros
[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 #include <sys/ioctl.h>
38 #include <linux/vt.h>
39 #include <linux/tiocl.h>
40 #include <termios.h>
41 #include <stdarg.h>
42 #include <sys/inotify.h>
43 #include <sys/poll.h>
44
45 #include "macro.h"
46 #include "util.h"
47 #include "ioprio.h"
48 #include "missing.h"
49 #include "log.h"
50 #include "strv.h"
51
52 bool streq_ptr(const char *a, const char *b) {
53
54         /* Like streq(), but tries to make sense of NULL pointers */
55
56         if (a && b)
57                 return streq(a, b);
58
59         if (!a && !b)
60                 return true;
61
62         return false;
63 }
64
65 usec_t now(clockid_t clock_id) {
66         struct timespec ts;
67
68         assert_se(clock_gettime(clock_id, &ts) == 0);
69
70         return timespec_load(&ts);
71 }
72
73 usec_t timespec_load(const struct timespec *ts) {
74         assert(ts);
75
76         return
77                 (usec_t) ts->tv_sec * USEC_PER_SEC +
78                 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
79 }
80
81 struct timespec *timespec_store(struct timespec *ts, usec_t u)  {
82         assert(ts);
83
84         ts->tv_sec = (time_t) (u / USEC_PER_SEC);
85         ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
86
87         return ts;
88 }
89
90 usec_t timeval_load(const struct timeval *tv) {
91         assert(tv);
92
93         return
94                 (usec_t) tv->tv_sec * USEC_PER_SEC +
95                 (usec_t) tv->tv_usec;
96 }
97
98 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
99         assert(tv);
100
101         tv->tv_sec = (time_t) (u / USEC_PER_SEC);
102         tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
103
104         return tv;
105 }
106
107 bool endswith(const char *s, const char *postfix) {
108         size_t sl, pl;
109
110         assert(s);
111         assert(postfix);
112
113         sl = strlen(s);
114         pl = strlen(postfix);
115
116         if (sl < pl)
117                 return false;
118
119         return memcmp(s + sl - pl, postfix, pl) == 0;
120 }
121
122 bool startswith(const char *s, const char *prefix) {
123         size_t sl, pl;
124
125         assert(s);
126         assert(prefix);
127
128         sl = strlen(s);
129         pl = strlen(prefix);
130
131         if (sl < pl)
132                 return false;
133
134         return memcmp(s, prefix, pl) == 0;
135 }
136
137 bool first_word(const char *s, const char *word) {
138         size_t sl, wl;
139
140         assert(s);
141         assert(word);
142
143         sl = strlen(s);
144         wl = strlen(word);
145
146         if (sl < wl)
147                 return false;
148
149         if (memcmp(s, word, wl) != 0)
150                 return false;
151
152         return (s[wl] == 0 ||
153                 strchr(WHITESPACE, s[wl]));
154 }
155
156 int close_nointr(int fd) {
157         assert(fd >= 0);
158
159         for (;;) {
160                 int r;
161
162                 if ((r = close(fd)) >= 0)
163                         return r;
164
165                 if (errno != EINTR)
166                         return r;
167         }
168 }
169
170 void close_nointr_nofail(int fd) {
171         int saved_errno = errno;
172
173         /* like close_nointr() but cannot fail, and guarantees errno
174          * is unchanged */
175
176         assert_se(close_nointr(fd) == 0);
177
178         errno = saved_errno;
179 }
180
181 int parse_boolean(const char *v) {
182         assert(v);
183
184         if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
185                 return 1;
186         else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
187                 return 0;
188
189         return -EINVAL;
190 }
191
192 int safe_atou(const char *s, unsigned *ret_u) {
193         char *x = NULL;
194         unsigned long l;
195
196         assert(s);
197         assert(ret_u);
198
199         errno = 0;
200         l = strtoul(s, &x, 0);
201
202         if (!x || *x || errno)
203                 return errno ? -errno : -EINVAL;
204
205         if ((unsigned long) (unsigned) l != l)
206                 return -ERANGE;
207
208         *ret_u = (unsigned) l;
209         return 0;
210 }
211
212 int safe_atoi(const char *s, int *ret_i) {
213         char *x = NULL;
214         long l;
215
216         assert(s);
217         assert(ret_i);
218
219         errno = 0;
220         l = strtol(s, &x, 0);
221
222         if (!x || *x || errno)
223                 return errno ? -errno : -EINVAL;
224
225         if ((long) (int) l != l)
226                 return -ERANGE;
227
228         *ret_i = (int) l;
229         return 0;
230 }
231
232 int safe_atolu(const char *s, long unsigned *ret_lu) {
233         char *x = NULL;
234         unsigned long l;
235
236         assert(s);
237         assert(ret_lu);
238
239         errno = 0;
240         l = strtoul(s, &x, 0);
241
242         if (!x || *x || errno)
243                 return errno ? -errno : -EINVAL;
244
245         *ret_lu = l;
246         return 0;
247 }
248
249 int safe_atoli(const char *s, long int *ret_li) {
250         char *x = NULL;
251         long l;
252
253         assert(s);
254         assert(ret_li);
255
256         errno = 0;
257         l = strtol(s, &x, 0);
258
259         if (!x || *x || errno)
260                 return errno ? -errno : -EINVAL;
261
262         *ret_li = l;
263         return 0;
264 }
265
266 int safe_atollu(const char *s, long long unsigned *ret_llu) {
267         char *x = NULL;
268         unsigned long long l;
269
270         assert(s);
271         assert(ret_llu);
272
273         errno = 0;
274         l = strtoull(s, &x, 0);
275
276         if (!x || *x || errno)
277                 return errno ? -errno : -EINVAL;
278
279         *ret_llu = l;
280         return 0;
281 }
282
283 int safe_atolli(const char *s, long long int *ret_lli) {
284         char *x = NULL;
285         long long l;
286
287         assert(s);
288         assert(ret_lli);
289
290         errno = 0;
291         l = strtoll(s, &x, 0);
292
293         if (!x || *x || errno)
294                 return errno ? -errno : -EINVAL;
295
296         *ret_lli = l;
297         return 0;
298 }
299
300 /* Split a string into words. */
301 char *split(const char *c, size_t *l, const char *separator, char **state) {
302         char *current;
303
304         current = *state ? *state : (char*) c;
305
306         if (!*current || *c == 0)
307                 return NULL;
308
309         current += strspn(current, separator);
310         *l = strcspn(current, separator);
311         *state = current+*l;
312
313         return (char*) current;
314 }
315
316 /* Split a string into words, but consider strings enclosed in '' and
317  * "" as words even if they include spaces. */
318 char *split_quoted(const char *c, size_t *l, char **state) {
319         char *current;
320
321         current = *state ? *state : (char*) c;
322
323         if (!*current || *c == 0)
324                 return NULL;
325
326         current += strspn(current, WHITESPACE);
327
328         if (*current == '\'') {
329                 current ++;
330                 *l = strcspn(current, "'");
331                 *state = current+*l;
332
333                 if (**state == '\'')
334                         (*state)++;
335         } else if (*current == '\"') {
336                 current ++;
337                 *l = strcspn(current, "\"");
338                 *state = current+*l;
339
340                 if (**state == '\"')
341                         (*state)++;
342         } else {
343                 *l = strcspn(current, WHITESPACE);
344                 *state = current+*l;
345         }
346
347         /* FIXME: Cannot deal with strings that have spaces AND ticks
348          * in them */
349
350         return (char*) current;
351 }
352
353 char **split_path_and_make_absolute(const char *p) {
354         char **l;
355         assert(p);
356
357         if (!(l = strv_split(p, ":")))
358                 return NULL;
359
360         if (!strv_path_make_absolute_cwd(l)) {
361                 strv_free(l);
362                 return NULL;
363         }
364
365         return l;
366 }
367
368 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
369         int r;
370         FILE *f;
371         char fn[132], line[256], *p;
372         long long unsigned ppid;
373
374         assert(pid >= 0);
375         assert(_ppid);
376
377         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%llu/stat", (unsigned long long) pid) < (int) (sizeof(fn)-1));
378         fn[sizeof(fn)-1] = 0;
379
380         if (!(f = fopen(fn, "r")))
381                 return -errno;
382
383         if (!(fgets(line, sizeof(line), f))) {
384                 r = -errno;
385                 fclose(f);
386                 return r;
387         }
388
389         fclose(f);
390
391         /* Let's skip the pid and comm fields. The latter is enclosed
392          * in () but does not escape any () in its value, so let's
393          * skip over it manually */
394
395         if (!(p = strrchr(line, ')')))
396                 return -EIO;
397
398         p++;
399
400         if (sscanf(p, " "
401                    "%*c "  /* state */
402                    "%llu ", /* ppid */
403                    &ppid) != 1)
404                 return -EIO;
405
406         if ((long long unsigned) (pid_t) ppid != ppid)
407                 return -ERANGE;
408
409         *_ppid = (pid_t) ppid;
410
411         return 0;
412 }
413
414 int write_one_line_file(const char *fn, const char *line) {
415         FILE *f;
416         int r;
417
418         assert(fn);
419         assert(line);
420
421         if (!(f = fopen(fn, "we")))
422                 return -errno;
423
424         if (fputs(line, f) < 0) {
425                 r = -errno;
426                 goto finish;
427         }
428
429         r = 0;
430 finish:
431         fclose(f);
432         return r;
433 }
434
435 int read_one_line_file(const char *fn, char **line) {
436         FILE *f;
437         int r;
438         char t[2048], *c;
439
440         assert(fn);
441         assert(line);
442
443         if (!(f = fopen(fn, "re")))
444                 return -errno;
445
446         if (!(fgets(t, sizeof(t), f))) {
447                 r = -errno;
448                 goto finish;
449         }
450
451         if (!(c = strdup(t))) {
452                 r = -ENOMEM;
453                 goto finish;
454         }
455
456         *line = c;
457         r = 0;
458
459 finish:
460         fclose(f);
461         return r;
462 }
463
464 char *truncate_nl(char *s) {
465         assert(s);
466
467         s[strcspn(s, NEWLINE)] = 0;
468         return s;
469 }
470
471 int get_process_name(pid_t pid, char **name) {
472         char *p;
473         int r;
474
475         assert(pid >= 1);
476         assert(name);
477
478         if (asprintf(&p, "/proc/%llu/comm", (unsigned long long) pid) < 0)
479                 return -ENOMEM;
480
481         r = read_one_line_file(p, name);
482         free(p);
483
484         if (r < 0)
485                 return r;
486
487         truncate_nl(*name);
488         return 0;
489 }
490
491 char *strappend(const char *s, const char *suffix) {
492         size_t a, b;
493         char *r;
494
495         assert(s);
496         assert(suffix);
497
498         a = strlen(s);
499         b = strlen(suffix);
500
501         if (!(r = new(char, a+b+1)))
502                 return NULL;
503
504         memcpy(r, s, a);
505         memcpy(r+a, suffix, b);
506         r[a+b] = 0;
507
508         return r;
509 }
510
511 int readlink_malloc(const char *p, char **r) {
512         size_t l = 100;
513
514         assert(p);
515         assert(r);
516
517         for (;;) {
518                 char *c;
519                 ssize_t n;
520
521                 if (!(c = new(char, l)))
522                         return -ENOMEM;
523
524                 if ((n = readlink(p, c, l-1)) < 0) {
525                         int ret = -errno;
526                         free(c);
527                         return ret;
528                 }
529
530                 if ((size_t) n < l-1) {
531                         c[n] = 0;
532                         *r = c;
533                         return 0;
534                 }
535
536                 free(c);
537                 l *= 2;
538         }
539 }
540
541 char *file_name_from_path(const char *p) {
542         char *r;
543
544         assert(p);
545
546         if ((r = strrchr(p, '/')))
547                 return r + 1;
548
549         return (char*) p;
550 }
551
552 bool path_is_absolute(const char *p) {
553         assert(p);
554
555         return p[0] == '/';
556 }
557
558 bool is_path(const char *p) {
559
560         return !!strchr(p, '/');
561 }
562
563 char *path_make_absolute(const char *p, const char *prefix) {
564         char *r;
565
566         assert(p);
567
568         /* Makes every item in the list an absolute path by prepending
569          * the prefix, if specified and necessary */
570
571         if (path_is_absolute(p) || !prefix)
572                 return strdup(p);
573
574         if (asprintf(&r, "%s/%s", prefix, p) < 0)
575                 return NULL;
576
577         return r;
578 }
579
580 char *path_make_absolute_cwd(const char *p) {
581         char *cwd, *r;
582
583         assert(p);
584
585         /* Similar to path_make_absolute(), but prefixes with the
586          * current working directory. */
587
588         if (path_is_absolute(p))
589                 return strdup(p);
590
591         if (!(cwd = get_current_dir_name()))
592                 return NULL;
593
594         r = path_make_absolute(p, cwd);
595         free(cwd);
596
597         return r;
598 }
599
600 char **strv_path_make_absolute_cwd(char **l) {
601         char **s;
602
603         /* Goes through every item in the string list and makes it
604          * absolute. This works in place and won't rollback any
605          * changes on failure. */
606
607         STRV_FOREACH(s, l) {
608                 char *t;
609
610                 if (!(t = path_make_absolute_cwd(*s)))
611                         return NULL;
612
613                 free(*s);
614                 *s = t;
615         }
616
617         return l;
618 }
619
620 int reset_all_signal_handlers(void) {
621         int sig;
622
623         for (sig = 1; sig < _NSIG; sig++) {
624                 struct sigaction sa;
625
626                 if (sig == SIGKILL || sig == SIGSTOP)
627                         continue;
628
629                 zero(sa);
630                 sa.sa_handler = SIG_DFL;
631                 sa.sa_flags = SA_RESTART;
632
633                 /* On Linux the first two RT signals are reserved by
634                  * glibc, and sigaction() will return EINVAL for them. */
635                 if ((sigaction(sig, &sa, NULL) < 0))
636                         if (errno != EINVAL)
637                                 return -errno;
638         }
639
640         return 0;
641 }
642
643 char *strstrip(char *s) {
644         char *e, *l = NULL;
645
646         /* Drops trailing whitespace. Modifies the string in
647          * place. Returns pointer to first non-space character */
648
649         s += strspn(s, WHITESPACE);
650
651         for (e = s; *e; e++)
652                 if (!strchr(WHITESPACE, *e))
653                         l = e;
654
655         if (l)
656                 *(l+1) = 0;
657         else
658                 *s = 0;
659
660         return s;
661
662 }
663
664 char *delete_chars(char *s, const char *bad) {
665         char *f, *t;
666
667         /* Drops all whitespace, regardless where in the string */
668
669         for (f = s, t = s; *f; f++) {
670                 if (strchr(bad, *f))
671                         continue;
672
673                 *(t++) = *f;
674         }
675
676         *t = 0;
677
678         return s;
679 }
680
681 char *file_in_same_dir(const char *path, const char *filename) {
682         char *e, *r;
683         size_t k;
684
685         assert(path);
686         assert(filename);
687
688         /* This removes the last component of path and appends
689          * filename, unless the latter is absolute anyway or the
690          * former isn't */
691
692         if (path_is_absolute(filename))
693                 return strdup(filename);
694
695         if (!(e = strrchr(path, '/')))
696                 return strdup(filename);
697
698         k = strlen(filename);
699         if (!(r = new(char, e-path+1+k+1)))
700                 return NULL;
701
702         memcpy(r, path, e-path+1);
703         memcpy(r+(e-path)+1, filename, k+1);
704
705         return r;
706 }
707
708 int mkdir_parents(const char *path, mode_t mode) {
709         const char *p, *e;
710
711         assert(path);
712
713         /* Creates every parent directory in the path except the last
714          * component. */
715
716         p = path + strspn(path, "/");
717         for (;;) {
718                 int r;
719                 char *t;
720
721                 e = p + strcspn(p, "/");
722                 p = e + strspn(e, "/");
723
724                 /* Is this the last component? If so, then we're
725                  * done */
726                 if (*p == 0)
727                         return 0;
728
729                 if (!(t = strndup(path, e - path)))
730                         return -ENOMEM;
731
732                 r = mkdir(t, mode);
733
734                 free(t);
735
736                 if (r < 0 && errno != EEXIST)
737                         return -errno;
738         }
739 }
740
741 int mkdir_p(const char *path, mode_t mode) {
742         int r;
743
744         /* Like mkdir -p */
745
746         if ((r = mkdir_parents(path, mode)) < 0)
747                 return r;
748
749         if (mkdir(path, mode) < 0)
750                 return -errno;
751
752         return 0;
753 }
754
755 char hexchar(int x) {
756         static const char table[16] = "0123456789abcdef";
757
758         return table[x & 15];
759 }
760
761 int unhexchar(char c) {
762
763         if (c >= '0' && c <= '9')
764                 return c - '0';
765
766         if (c >= 'a' && c <= 'f')
767                 return c - 'a' + 10;
768
769         if (c >= 'A' && c <= 'F')
770                 return c - 'A' + 10;
771
772         return -1;
773 }
774
775 char octchar(int x) {
776         return '0' + (x & 7);
777 }
778
779 int unoctchar(char c) {
780
781         if (c >= '0' && c <= '7')
782                 return c - '0';
783
784         return -1;
785 }
786
787 char decchar(int x) {
788         return '0' + (x % 10);
789 }
790
791 int undecchar(char c) {
792
793         if (c >= '0' && c <= '9')
794                 return c - '0';
795
796         return -1;
797 }
798
799 char *cescape(const char *s) {
800         char *r, *t;
801         const char *f;
802
803         assert(s);
804
805         /* Does C style string escaping. */
806
807         if (!(r = new(char, strlen(s)*4 + 1)))
808                 return NULL;
809
810         for (f = s, t = r; *f; f++)
811
812                 switch (*f) {
813
814                 case '\a':
815                         *(t++) = '\\';
816                         *(t++) = 'a';
817                         break;
818                 case '\b':
819                         *(t++) = '\\';
820                         *(t++) = 'b';
821                         break;
822                 case '\f':
823                         *(t++) = '\\';
824                         *(t++) = 'f';
825                         break;
826                 case '\n':
827                         *(t++) = '\\';
828                         *(t++) = 'n';
829                         break;
830                 case '\r':
831                         *(t++) = '\\';
832                         *(t++) = 'r';
833                         break;
834                 case '\t':
835                         *(t++) = '\\';
836                         *(t++) = 't';
837                         break;
838                 case '\v':
839                         *(t++) = '\\';
840                         *(t++) = 'v';
841                         break;
842                 case '\\':
843                         *(t++) = '\\';
844                         *(t++) = '\\';
845                         break;
846                 case '"':
847                         *(t++) = '\\';
848                         *(t++) = '"';
849                         break;
850                 case '\'':
851                         *(t++) = '\\';
852                         *(t++) = '\'';
853                         break;
854
855                 default:
856                         /* For special chars we prefer octal over
857                          * hexadecimal encoding, simply because glib's
858                          * g_strescape() does the same */
859                         if ((*f < ' ') || (*f >= 127)) {
860                                 *(t++) = '\\';
861                                 *(t++) = octchar((unsigned char) *f >> 6);
862                                 *(t++) = octchar((unsigned char) *f >> 3);
863                                 *(t++) = octchar((unsigned char) *f);
864                         } else
865                                 *(t++) = *f;
866                         break;
867                 }
868
869         *t = 0;
870
871         return r;
872 }
873
874 char *cunescape(const char *s) {
875         char *r, *t;
876         const char *f;
877
878         assert(s);
879
880         /* Undoes C style string escaping */
881
882         if (!(r = new(char, strlen(s)+1)))
883                 return r;
884
885         for (f = s, t = r; *f; f++) {
886
887                 if (*f != '\\') {
888                         *(t++) = *f;
889                         continue;
890                 }
891
892                 f++;
893
894                 switch (*f) {
895
896                 case 'a':
897                         *(t++) = '\a';
898                         break;
899                 case 'b':
900                         *(t++) = '\b';
901                         break;
902                 case 'f':
903                         *(t++) = '\f';
904                         break;
905                 case 'n':
906                         *(t++) = '\n';
907                         break;
908                 case 'r':
909                         *(t++) = '\r';
910                         break;
911                 case 't':
912                         *(t++) = '\t';
913                         break;
914                 case 'v':
915                         *(t++) = '\v';
916                         break;
917                 case '\\':
918                         *(t++) = '\\';
919                         break;
920                 case '"':
921                         *(t++) = '"';
922                         break;
923                 case '\'':
924                         *(t++) = '\'';
925                         break;
926
927                 case 'x': {
928                         /* hexadecimal encoding */
929                         int a, b;
930
931                         if ((a = unhexchar(f[1])) < 0 ||
932                             (b = unhexchar(f[2])) < 0) {
933                                 /* Invalid escape code, let's take it literal then */
934                                 *(t++) = '\\';
935                                 *(t++) = 'x';
936                         } else {
937                                 *(t++) = (char) ((a << 4) | b);
938                                 f += 2;
939                         }
940
941                         break;
942                 }
943
944                 case '0':
945                 case '1':
946                 case '2':
947                 case '3':
948                 case '4':
949                 case '5':
950                 case '6':
951                 case '7': {
952                         /* octal encoding */
953                         int a, b, c;
954
955                         if ((a = unoctchar(f[0])) < 0 ||
956                             (b = unoctchar(f[1])) < 0 ||
957                             (c = unoctchar(f[2])) < 0) {
958                                 /* Invalid escape code, let's take it literal then */
959                                 *(t++) = '\\';
960                                 *(t++) = f[0];
961                         } else {
962                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
963                                 f += 2;
964                         }
965
966                         break;
967                 }
968
969                 case 0:
970                         /* premature end of string.*/
971                         *(t++) = '\\';
972                         goto finish;
973
974                 default:
975                         /* Invalid escape code, let's take it literal then */
976                         *(t++) = '\\';
977                         *(t++) = 'f';
978                         break;
979                 }
980         }
981
982 finish:
983         *t = 0;
984         return r;
985 }
986
987
988 char *xescape(const char *s, const char *bad) {
989         char *r, *t;
990         const char *f;
991
992         /* Escapes all chars in bad, in addition to \ and all special
993          * chars, in \xFF style escaping. May be reversed with
994          * cunescape. */
995
996         if (!(r = new(char, strlen(s)*4+1)))
997                 return NULL;
998
999         for (f = s, t = r; *f; f++) {
1000
1001                 if ((*f < ' ') || (*f >= 127) ||
1002                     (*f == '\\') || strchr(bad, *f)) {
1003                         *(t++) = '\\';
1004                         *(t++) = 'x';
1005                         *(t++) = hexchar(*f >> 4);
1006                         *(t++) = hexchar(*f);
1007                 } else
1008                         *(t++) = *f;
1009         }
1010
1011         *t = 0;
1012
1013         return r;
1014 }
1015
1016 char *bus_path_escape(const char *s) {
1017         char *r, *t;
1018         const char *f;
1019
1020         assert(s);
1021
1022         /* Escapes all chars that D-Bus' object path cannot deal
1023          * with. Can be reverse with bus_path_unescape() */
1024
1025         if (!(r = new(char, strlen(s)*3+1)))
1026                 return NULL;
1027
1028         for (f = s, t = r; *f; f++) {
1029
1030                 if (!(*f >= 'A' && *f <= 'Z') &&
1031                     !(*f >= 'a' && *f <= 'z') &&
1032                     !(*f >= '0' && *f <= '9')) {
1033                         *(t++) = '_';
1034                         *(t++) = hexchar(*f >> 4);
1035                         *(t++) = hexchar(*f);
1036                 } else
1037                         *(t++) = *f;
1038         }
1039
1040         *t = 0;
1041
1042         return r;
1043 }
1044
1045 char *bus_path_unescape(const char *s) {
1046         char *r, *t;
1047         const char *f;
1048
1049         assert(s);
1050
1051         if (!(r = new(char, strlen(s)+1)))
1052                 return NULL;
1053
1054         for (f = s, t = r; *f; f++) {
1055
1056                 if (*f == '_') {
1057                         int a, b;
1058
1059                         if ((a = unhexchar(f[1])) < 0 ||
1060                             (b = unhexchar(f[2])) < 0) {
1061                                 /* Invalid escape code, let's take it literal then */
1062                                 *(t++) = '_';
1063                         } else {
1064                                 *(t++) = (char) ((a << 4) | b);
1065                                 f += 2;
1066                         }
1067                 } else
1068                         *(t++) = *f;
1069         }
1070
1071         *t = 0;
1072
1073         return r;
1074 }
1075
1076 char *path_kill_slashes(char *path) {
1077         char *f, *t;
1078         bool slash = false;
1079
1080         /* Removes redundant inner and trailing slashes. Modifies the
1081          * passed string in-place.
1082          *
1083          * ///foo///bar/ becomes /foo/bar
1084          */
1085
1086         for (f = path, t = path; *f; f++) {
1087
1088                 if (*f == '/') {
1089                         slash = true;
1090                         continue;
1091                 }
1092
1093                 if (slash) {
1094                         slash = false;
1095                         *(t++) = '/';
1096                 }
1097
1098                 *(t++) = *f;
1099         }
1100
1101         /* Special rule, if we are talking of the root directory, a
1102         trailing slash is good */
1103
1104         if (t == path && slash)
1105                 *(t++) = '/';
1106
1107         *t = 0;
1108         return path;
1109 }
1110
1111 bool path_startswith(const char *path, const char *prefix) {
1112         assert(path);
1113         assert(prefix);
1114
1115         if ((path[0] == '/') != (prefix[0] == '/'))
1116                 return false;
1117
1118         for (;;) {
1119                 size_t a, b;
1120
1121                 path += strspn(path, "/");
1122                 prefix += strspn(prefix, "/");
1123
1124                 if (*prefix == 0)
1125                         return true;
1126
1127                 if (*path == 0)
1128                         return false;
1129
1130                 a = strcspn(path, "/");
1131                 b = strcspn(prefix, "/");
1132
1133                 if (a != b)
1134                         return false;
1135
1136                 if (memcmp(path, prefix, a) != 0)
1137                         return false;
1138
1139                 path += a;
1140                 prefix += b;
1141         }
1142 }
1143
1144 char *ascii_strlower(char *t) {
1145         char *p;
1146
1147         assert(t);
1148
1149         for (p = t; *p; p++)
1150                 if (*p >= 'A' && *p <= 'Z')
1151                         *p = *p - 'A' + 'a';
1152
1153         return t;
1154 }
1155
1156 bool ignore_file(const char *filename) {
1157         assert(filename);
1158
1159         return
1160                 filename[0] == '.' ||
1161                 endswith(filename, "~") ||
1162                 endswith(filename, ".rpmnew") ||
1163                 endswith(filename, ".rpmsave") ||
1164                 endswith(filename, ".rpmorig") ||
1165                 endswith(filename, ".dpkg-old") ||
1166                 endswith(filename, ".dpkg-new") ||
1167                 endswith(filename, ".swp");
1168 }
1169
1170 int fd_nonblock(int fd, bool nonblock) {
1171         int flags;
1172
1173         assert(fd >= 0);
1174
1175         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1176                 return -errno;
1177
1178         if (nonblock)
1179                 flags |= O_NONBLOCK;
1180         else
1181                 flags &= ~O_NONBLOCK;
1182
1183         if (fcntl(fd, F_SETFL, flags) < 0)
1184                 return -errno;
1185
1186         return 0;
1187 }
1188
1189 int fd_cloexec(int fd, bool cloexec) {
1190         int flags;
1191
1192         assert(fd >= 0);
1193
1194         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1195                 return -errno;
1196
1197         if (cloexec)
1198                 flags |= FD_CLOEXEC;
1199         else
1200                 flags &= ~FD_CLOEXEC;
1201
1202         if (fcntl(fd, F_SETFD, flags) < 0)
1203                 return -errno;
1204
1205         return 0;
1206 }
1207
1208 int close_all_fds(const int except[], unsigned n_except) {
1209         DIR *d;
1210         struct dirent *de;
1211         int r = 0;
1212
1213         if (!(d = opendir("/proc/self/fd")))
1214                 return -errno;
1215
1216         while ((de = readdir(d))) {
1217                 int fd = -1;
1218
1219                 if (de->d_name[0] == '.')
1220                         continue;
1221
1222                 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1223                         goto finish;
1224
1225                 if (fd < 3)
1226                         continue;
1227
1228                 if (fd == dirfd(d))
1229                         continue;
1230
1231                 if (except) {
1232                         bool found;
1233                         unsigned i;
1234
1235                         found = false;
1236                         for (i = 0; i < n_except; i++)
1237                                 if (except[i] == fd) {
1238                                         found = true;
1239                                         break;
1240                                 }
1241
1242                         if (found)
1243                                 continue;
1244                 }
1245
1246                 if ((r = close_nointr(fd)) < 0) {
1247                         /* Valgrind has its own FD and doesn't want to have it closed */
1248                         if (errno != EBADF)
1249                                 goto finish;
1250                 }
1251         }
1252
1253         r = 0;
1254
1255 finish:
1256         closedir(d);
1257         return r;
1258 }
1259
1260 bool chars_intersect(const char *a, const char *b) {
1261         const char *p;
1262
1263         /* Returns true if any of the chars in a are in b. */
1264         for (p = a; *p; p++)
1265                 if (strchr(b, *p))
1266                         return true;
1267
1268         return false;
1269 }
1270
1271 char *format_timestamp(char *buf, size_t l, usec_t t) {
1272         struct tm tm;
1273         time_t sec;
1274
1275         assert(buf);
1276         assert(l > 0);
1277
1278         if (t <= 0)
1279                 return NULL;
1280
1281         sec = (time_t) t / USEC_PER_SEC;
1282
1283         if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1284                 return NULL;
1285
1286         return buf;
1287 }
1288
1289 bool fstype_is_network(const char *fstype) {
1290         static const char * const table[] = {
1291                 "cifs",
1292                 "smbfs",
1293                 "ncpfs",
1294                 "nfs",
1295                 "nfs4"
1296         };
1297
1298         unsigned i;
1299
1300         for (i = 0; i < ELEMENTSOF(table); i++)
1301                 if (streq(table[i], fstype))
1302                         return true;
1303
1304         return false;
1305 }
1306
1307 int chvt(int vt) {
1308         int fd, r = 0;
1309
1310         if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1311                 return -errno;
1312
1313         if (vt < 0) {
1314                 int tiocl[2] = {
1315                         TIOCL_GETKMSGREDIRECT,
1316                         0
1317                 };
1318
1319                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1320                         return -errno;
1321
1322                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1323         }
1324
1325         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1326                 r = -errno;
1327
1328         close_nointr(r);
1329         return r;
1330 }
1331
1332 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1333         struct termios old_termios, new_termios;
1334         char c;
1335         char line[1024];
1336
1337         assert(f);
1338         assert(ret);
1339
1340         if (tcgetattr(fileno(f), &old_termios) >= 0) {
1341                 new_termios = old_termios;
1342
1343                 new_termios.c_lflag &= ~ICANON;
1344                 new_termios.c_cc[VMIN] = 1;
1345                 new_termios.c_cc[VTIME] = 0;
1346
1347                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1348                         size_t k;
1349
1350                         k = fread(&c, 1, 1, f);
1351
1352                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1353
1354                         if (k <= 0)
1355                                 return -EIO;
1356
1357                         if (need_nl)
1358                                 *need_nl = c != '\n';
1359
1360                         *ret = c;
1361                         return 0;
1362                 }
1363         }
1364
1365         if (!(fgets(line, sizeof(line), f)))
1366                 return -EIO;
1367
1368         truncate_nl(line);
1369
1370         if (strlen(line) != 1)
1371                 return -EBADMSG;
1372
1373         if (need_nl)
1374                 *need_nl = false;
1375
1376         *ret = line[0];
1377         return 0;
1378 }
1379
1380 int ask(char *ret, const char *replies, const char *text, ...) {
1381         assert(ret);
1382         assert(replies);
1383         assert(text);
1384
1385         for (;;) {
1386                 va_list ap;
1387                 char c;
1388                 int r;
1389                 bool need_nl = true;
1390
1391                 va_start(ap, text);
1392                 vprintf(text, ap);
1393                 va_end(ap);
1394
1395                 fflush(stdout);
1396
1397                 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1398
1399                         if (r == -EBADMSG) {
1400                                 puts("Bad input, please try again.");
1401                                 continue;
1402                         }
1403
1404                         putchar('\n');
1405                         return r;
1406                 }
1407
1408                 if (need_nl)
1409                         putchar('\n');
1410
1411                 if (strchr(replies, c)) {
1412                         *ret = c;
1413                         return 0;
1414                 }
1415
1416                 puts("Read unexpected character, please try again.");
1417         }
1418 }
1419
1420 int reset_terminal(int fd) {
1421         struct termios termios;
1422         int r = 0;
1423
1424         assert(fd >= 0);
1425
1426         /* Set terminal up for job control */
1427
1428         if (tcgetattr(fd, &termios) < 0) {
1429                 r = -errno;
1430                 goto finish;
1431         }
1432
1433         termios.c_iflag &= ~(IGNBRK | BRKINT);
1434         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1435         termios.c_oflag |= ONLCR;
1436         termios.c_cflag |= CREAD;
1437         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1438
1439         termios.c_cc[VINTR]    =   03;  /* ^C */
1440         termios.c_cc[VQUIT]    =  034;  /* ^\ */
1441         termios.c_cc[VERASE]   = 0177;
1442         termios.c_cc[VKILL]    =  025;  /* ^X */
1443         termios.c_cc[VEOF]     =   04;  /* ^D */
1444         termios.c_cc[VSTART]   =  021;  /* ^Q */
1445         termios.c_cc[VSTOP]    =  023;  /* ^S */
1446         termios.c_cc[VSUSP]    =  032;  /* ^Z */
1447         termios.c_cc[VLNEXT]   =  026;  /* ^V */
1448         termios.c_cc[VWERASE]  =  027;  /* ^W */
1449         termios.c_cc[VREPRINT] =  022;  /* ^R */
1450
1451         termios.c_cc[VTIME]  = 0;
1452         termios.c_cc[VMIN]   = 1;
1453
1454         if (tcsetattr(fd, TCSANOW, &termios) < 0)
1455                 r = -errno;
1456
1457 finish:
1458         /* Just in case, flush all crap out */
1459         tcflush(fd, TCIOFLUSH);
1460
1461         return r;
1462 }
1463
1464 int open_terminal(const char *name, int mode) {
1465         int fd, r;
1466
1467         if ((fd = open(name, mode)) < 0)
1468                 return -errno;
1469
1470         if ((r = isatty(fd)) < 0) {
1471                 close_nointr_nofail(fd);
1472                 return -errno;
1473         }
1474
1475         if (!r) {
1476                 close_nointr_nofail(fd);
1477                 return -ENOTTY;
1478         }
1479
1480         return fd;
1481 }
1482
1483 int flush_fd(int fd) {
1484         struct pollfd pollfd;
1485
1486         zero(pollfd);
1487         pollfd.fd = fd;
1488         pollfd.events = POLLIN;
1489
1490         for (;;) {
1491                 char buf[1024];
1492                 ssize_t l;
1493                 int r;
1494
1495                 if ((r = poll(&pollfd, 1, 0)) < 0) {
1496
1497                         if (errno == EINTR)
1498                                 continue;
1499
1500                         return -errno;
1501                 }
1502
1503                 if (r == 0)
1504                         return 0;
1505
1506                 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1507
1508                         if (errno == EINTR)
1509                                 continue;
1510
1511                         if (errno == EAGAIN)
1512                                 return 0;
1513
1514                         return -errno;
1515                 }
1516
1517                 if (l <= 0)
1518                         return 0;
1519         }
1520 }
1521
1522 int acquire_terminal(const char *name, bool fail, bool force) {
1523         int fd = -1, notify = -1, r, wd;
1524
1525         assert(name);
1526
1527         /* We use inotify to be notified when the tty is closed. We
1528          * create the watch before checking if we can actually acquire
1529          * it, so that we don't lose any event.
1530          *
1531          * Note: strictly speaking this actually watches for the
1532          * device being closed, it does *not* really watch whether a
1533          * tty loses its controlling process. However, unless some
1534          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1535          * its tty otherwise this will not become a problem. As long
1536          * as the administrator makes sure not configure any service
1537          * on the same tty as an untrusted user this should not be a
1538          * problem. (Which he probably should not do anyway.) */
1539
1540         if (!fail && !force) {
1541                 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1542                         r = -errno;
1543                         goto fail;
1544                 }
1545
1546                 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1547                         r = -errno;
1548                         goto fail;
1549                 }
1550         }
1551
1552         for (;;) {
1553                 if ((r = flush_fd(notify)) < 0)
1554                         goto fail;
1555
1556                 /* We pass here O_NOCTTY only so that we can check the return
1557                  * value TIOCSCTTY and have a reliable way to figure out if we
1558                  * successfully became the controlling process of the tty */
1559                 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1560                         return -errno;
1561
1562                 /* First, try to get the tty */
1563                 if ((r = ioctl(fd, TIOCSCTTY, force)) < 0 &&
1564                     (force || fail || errno != EPERM)) {
1565                         r = -errno;
1566                         goto fail;
1567                 }
1568
1569                 if (r >= 0)
1570                         break;
1571
1572                 assert(!fail);
1573                 assert(!force);
1574                 assert(notify >= 0);
1575
1576                 for (;;) {
1577                         struct inotify_event e;
1578                         ssize_t l;
1579
1580                         if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1581
1582                                 if (l < 0) {
1583
1584                                         if (errno == EINTR)
1585                                                 continue;
1586
1587                                         r = -errno;
1588                                 } else
1589                                         r = -EIO;
1590
1591                                 goto fail;
1592                         }
1593
1594                         if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1595                                 r = -errno;
1596                                 goto fail;
1597                         }
1598
1599                         break;
1600                 }
1601
1602                 /* We close the tty fd here since if the old session
1603                  * ended our handle will be dead. It's important that
1604                  * we do this after sleeping, so that we don't enter
1605                  * an endless loop. */
1606                 close_nointr_nofail(fd);
1607         }
1608
1609         if (notify >= 0)
1610                 close_nointr(notify);
1611
1612         if ((r = reset_terminal(fd)) < 0)
1613                 log_warning("Failed to reset terminal: %s", strerror(-r));
1614
1615         return fd;
1616
1617 fail:
1618         if (fd >= 0)
1619                 close_nointr(fd);
1620
1621         if (notify >= 0)
1622                 close_nointr(notify);
1623
1624         return r;
1625 }
1626
1627 int release_terminal(void) {
1628         int r = 0, fd;
1629
1630         if ((fd = open("/dev/tty", O_RDWR)) < 0)
1631                 return -errno;
1632
1633         if (ioctl(fd, TIOCNOTTY) < 0)
1634                 r = -errno;
1635
1636         close_nointr_nofail(fd);
1637         return r;
1638 }
1639
1640 static const char *const ioprio_class_table[] = {
1641         [IOPRIO_CLASS_NONE] = "none",
1642         [IOPRIO_CLASS_RT] = "realtime",
1643         [IOPRIO_CLASS_BE] = "best-effort",
1644         [IOPRIO_CLASS_IDLE] = "idle"
1645 };
1646
1647 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
1648
1649 static const char *const sigchld_code_table[] = {
1650         [CLD_EXITED] = "exited",
1651         [CLD_KILLED] = "killed",
1652         [CLD_DUMPED] = "dumped",
1653         [CLD_TRAPPED] = "trapped",
1654         [CLD_STOPPED] = "stopped",
1655         [CLD_CONTINUED] = "continued",
1656 };
1657
1658 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
1659
1660 static const char *const log_facility_table[LOG_NFACILITIES] = {
1661         [LOG_FAC(LOG_KERN)] = "kern",
1662         [LOG_FAC(LOG_USER)] = "user",
1663         [LOG_FAC(LOG_MAIL)] = "mail",
1664         [LOG_FAC(LOG_DAEMON)] = "daemon",
1665         [LOG_FAC(LOG_AUTH)] = "auth",
1666         [LOG_FAC(LOG_SYSLOG)] = "syslog",
1667         [LOG_FAC(LOG_LPR)] = "lpr",
1668         [LOG_FAC(LOG_NEWS)] = "news",
1669         [LOG_FAC(LOG_UUCP)] = "uucp",
1670         [LOG_FAC(LOG_CRON)] = "cron",
1671         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
1672         [LOG_FAC(LOG_FTP)] = "ftp",
1673         [LOG_FAC(LOG_LOCAL0)] = "local0",
1674         [LOG_FAC(LOG_LOCAL1)] = "local1",
1675         [LOG_FAC(LOG_LOCAL2)] = "local2",
1676         [LOG_FAC(LOG_LOCAL3)] = "local3",
1677         [LOG_FAC(LOG_LOCAL4)] = "local4",
1678         [LOG_FAC(LOG_LOCAL5)] = "local5",
1679         [LOG_FAC(LOG_LOCAL6)] = "local6",
1680         [LOG_FAC(LOG_LOCAL7)] = "local7"
1681 };
1682
1683 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
1684
1685 static const char *const log_level_table[] = {
1686         [LOG_EMERG] = "emerg",
1687         [LOG_ALERT] = "alert",
1688         [LOG_CRIT] = "crit",
1689         [LOG_ERR] = "err",
1690         [LOG_WARNING] = "warning",
1691         [LOG_NOTICE] = "notice",
1692         [LOG_INFO] = "info",
1693         [LOG_DEBUG] = "debug"
1694 };
1695
1696 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
1697
1698 static const char* const sched_policy_table[] = {
1699         [SCHED_OTHER] = "other",
1700         [SCHED_BATCH] = "batch",
1701         [SCHED_IDLE] = "idle",
1702         [SCHED_FIFO] = "fifo",
1703         [SCHED_RR] = "rr"
1704 };
1705
1706 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
1707
1708 static const char* const rlimit_table[] = {
1709         [RLIMIT_CPU] = "LimitCPU",
1710         [RLIMIT_FSIZE] = "LimitFSIZE",
1711         [RLIMIT_DATA] = "LimitDATA",
1712         [RLIMIT_STACK] = "LimitSTACK",
1713         [RLIMIT_CORE] = "LimitCORE",
1714         [RLIMIT_RSS] = "LimitRSS",
1715         [RLIMIT_NOFILE] = "LimitNOFILE",
1716         [RLIMIT_AS] = "LimitAS",
1717         [RLIMIT_NPROC] = "LimitNPROC",
1718         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
1719         [RLIMIT_LOCKS] = "LimitLOCKS",
1720         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
1721         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
1722         [RLIMIT_NICE] = "LimitNICE",
1723         [RLIMIT_RTPRIO] = "LimitRTPRIO",
1724         [RLIMIT_RTTIME] = "LimitRTTIME"
1725 };
1726
1727 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);