chiark / gitweb /
man: add initial version of daemon(7)
[elogind.git] / src / 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 #include <libgen.h>
45 #include <ctype.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
48 #include <pwd.h>
49
50 #include "macro.h"
51 #include "util.h"
52 #include "ioprio.h"
53 #include "missing.h"
54 #include "log.h"
55 #include "strv.h"
56
57 bool streq_ptr(const char *a, const char *b) {
58
59         /* Like streq(), but tries to make sense of NULL pointers */
60
61         if (a && b)
62                 return streq(a, b);
63
64         if (!a && !b)
65                 return true;
66
67         return false;
68 }
69
70 usec_t now(clockid_t clock_id) {
71         struct timespec ts;
72
73         assert_se(clock_gettime(clock_id, &ts) == 0);
74
75         return timespec_load(&ts);
76 }
77
78 timestamp* timestamp_get(timestamp *ts) {
79         assert(ts);
80
81         ts->realtime = now(CLOCK_REALTIME);
82         ts->monotonic = now(CLOCK_MONOTONIC);
83
84         return ts;
85 }
86
87 usec_t timespec_load(const struct timespec *ts) {
88         assert(ts);
89
90         return
91                 (usec_t) ts->tv_sec * USEC_PER_SEC +
92                 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
93 }
94
95 struct timespec *timespec_store(struct timespec *ts, usec_t u)  {
96         assert(ts);
97
98         ts->tv_sec = (time_t) (u / USEC_PER_SEC);
99         ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
100
101         return ts;
102 }
103
104 usec_t timeval_load(const struct timeval *tv) {
105         assert(tv);
106
107         return
108                 (usec_t) tv->tv_sec * USEC_PER_SEC +
109                 (usec_t) tv->tv_usec;
110 }
111
112 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
113         assert(tv);
114
115         tv->tv_sec = (time_t) (u / USEC_PER_SEC);
116         tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
117
118         return tv;
119 }
120
121 bool endswith(const char *s, const char *postfix) {
122         size_t sl, pl;
123
124         assert(s);
125         assert(postfix);
126
127         sl = strlen(s);
128         pl = strlen(postfix);
129
130         if (pl == 0)
131                 return true;
132
133         if (sl < pl)
134                 return false;
135
136         return memcmp(s + sl - pl, postfix, pl) == 0;
137 }
138
139 bool startswith(const char *s, const char *prefix) {
140         size_t sl, pl;
141
142         assert(s);
143         assert(prefix);
144
145         sl = strlen(s);
146         pl = strlen(prefix);
147
148         if (pl == 0)
149                 return true;
150
151         if (sl < pl)
152                 return false;
153
154         return memcmp(s, prefix, pl) == 0;
155 }
156
157 bool startswith_no_case(const char *s, const char *prefix) {
158         size_t sl, pl;
159         unsigned i;
160
161         assert(s);
162         assert(prefix);
163
164         sl = strlen(s);
165         pl = strlen(prefix);
166
167         if (pl == 0)
168                 return true;
169
170         if (sl < pl)
171                 return false;
172
173         for(i = 0; i < pl; ++i) {
174                 if (tolower(s[i]) != tolower(prefix[i]))
175                         return false;
176         }
177
178         return true;
179 }
180
181 bool first_word(const char *s, const char *word) {
182         size_t sl, wl;
183
184         assert(s);
185         assert(word);
186
187         sl = strlen(s);
188         wl = strlen(word);
189
190         if (sl < wl)
191                 return false;
192
193         if (wl == 0)
194                 return true;
195
196         if (memcmp(s, word, wl) != 0)
197                 return false;
198
199         return s[wl] == 0 ||
200                 strchr(WHITESPACE, s[wl]);
201 }
202
203 int close_nointr(int fd) {
204         assert(fd >= 0);
205
206         for (;;) {
207                 int r;
208
209                 if ((r = close(fd)) >= 0)
210                         return r;
211
212                 if (errno != EINTR)
213                         return r;
214         }
215 }
216
217 void close_nointr_nofail(int fd) {
218         int saved_errno = errno;
219
220         /* like close_nointr() but cannot fail, and guarantees errno
221          * is unchanged */
222
223         assert_se(close_nointr(fd) == 0);
224
225         errno = saved_errno;
226 }
227
228 void close_many(const int fds[], unsigned n_fd) {
229         unsigned i;
230
231         for (i = 0; i < n_fd; i++)
232                 close_nointr_nofail(fds[i]);
233 }
234
235 int parse_boolean(const char *v) {
236         assert(v);
237
238         if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
239                 return 1;
240         else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
241                 return 0;
242
243         return -EINVAL;
244 }
245
246 int parse_pid(const char *s, pid_t* ret_pid) {
247         unsigned long ul;
248         pid_t pid;
249         int r;
250
251         assert(s);
252         assert(ret_pid);
253
254         if ((r = safe_atolu(s, &ul)) < 0)
255                 return r;
256
257         pid = (pid_t) ul;
258
259         if ((unsigned long) pid != ul)
260                 return -ERANGE;
261
262         if (pid <= 0)
263                 return -ERANGE;
264
265         *ret_pid = pid;
266         return 0;
267 }
268
269 int safe_atou(const char *s, unsigned *ret_u) {
270         char *x = NULL;
271         unsigned long l;
272
273         assert(s);
274         assert(ret_u);
275
276         errno = 0;
277         l = strtoul(s, &x, 0);
278
279         if (!x || *x || errno)
280                 return errno ? -errno : -EINVAL;
281
282         if ((unsigned long) (unsigned) l != l)
283                 return -ERANGE;
284
285         *ret_u = (unsigned) l;
286         return 0;
287 }
288
289 int safe_atoi(const char *s, int *ret_i) {
290         char *x = NULL;
291         long l;
292
293         assert(s);
294         assert(ret_i);
295
296         errno = 0;
297         l = strtol(s, &x, 0);
298
299         if (!x || *x || errno)
300                 return errno ? -errno : -EINVAL;
301
302         if ((long) (int) l != l)
303                 return -ERANGE;
304
305         *ret_i = (int) l;
306         return 0;
307 }
308
309 int safe_atolu(const char *s, long unsigned *ret_lu) {
310         char *x = NULL;
311         unsigned long l;
312
313         assert(s);
314         assert(ret_lu);
315
316         errno = 0;
317         l = strtoul(s, &x, 0);
318
319         if (!x || *x || errno)
320                 return errno ? -errno : -EINVAL;
321
322         *ret_lu = l;
323         return 0;
324 }
325
326 int safe_atoli(const char *s, long int *ret_li) {
327         char *x = NULL;
328         long l;
329
330         assert(s);
331         assert(ret_li);
332
333         errno = 0;
334         l = strtol(s, &x, 0);
335
336         if (!x || *x || errno)
337                 return errno ? -errno : -EINVAL;
338
339         *ret_li = l;
340         return 0;
341 }
342
343 int safe_atollu(const char *s, long long unsigned *ret_llu) {
344         char *x = NULL;
345         unsigned long long l;
346
347         assert(s);
348         assert(ret_llu);
349
350         errno = 0;
351         l = strtoull(s, &x, 0);
352
353         if (!x || *x || errno)
354                 return errno ? -errno : -EINVAL;
355
356         *ret_llu = l;
357         return 0;
358 }
359
360 int safe_atolli(const char *s, long long int *ret_lli) {
361         char *x = NULL;
362         long long l;
363
364         assert(s);
365         assert(ret_lli);
366
367         errno = 0;
368         l = strtoll(s, &x, 0);
369
370         if (!x || *x || errno)
371                 return errno ? -errno : -EINVAL;
372
373         *ret_lli = l;
374         return 0;
375 }
376
377 /* Split a string into words. */
378 char *split(const char *c, size_t *l, const char *separator, char **state) {
379         char *current;
380
381         current = *state ? *state : (char*) c;
382
383         if (!*current || *c == 0)
384                 return NULL;
385
386         current += strspn(current, separator);
387         *l = strcspn(current, separator);
388         *state = current+*l;
389
390         return (char*) current;
391 }
392
393 /* Split a string into words, but consider strings enclosed in '' and
394  * "" as words even if they include spaces. */
395 char *split_quoted(const char *c, size_t *l, char **state) {
396         char *current;
397
398         current = *state ? *state : (char*) c;
399
400         if (!*current || *c == 0)
401                 return NULL;
402
403         current += strspn(current, WHITESPACE);
404
405         if (*current == '\'') {
406                 current ++;
407                 *l = strcspn(current, "'");
408                 *state = current+*l;
409
410                 if (**state == '\'')
411                         (*state)++;
412         } else if (*current == '\"') {
413                 current ++;
414                 *l = strcspn(current, "\"");
415                 *state = current+*l;
416
417                 if (**state == '\"')
418                         (*state)++;
419         } else {
420                 *l = strcspn(current, WHITESPACE);
421                 *state = current+*l;
422         }
423
424         /* FIXME: Cannot deal with strings that have spaces AND ticks
425          * in them */
426
427         return (char*) current;
428 }
429
430 char **split_path_and_make_absolute(const char *p) {
431         char **l;
432         assert(p);
433
434         if (!(l = strv_split(p, ":")))
435                 return NULL;
436
437         if (!strv_path_make_absolute_cwd(l)) {
438                 strv_free(l);
439                 return NULL;
440         }
441
442         return l;
443 }
444
445 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
446         int r;
447         FILE *f;
448         char fn[132], line[256], *p;
449         long unsigned ppid;
450
451         assert(pid >= 0);
452         assert(_ppid);
453
454         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
455         fn[sizeof(fn)-1] = 0;
456
457         if (!(f = fopen(fn, "r")))
458                 return -errno;
459
460         if (!(fgets(line, sizeof(line), f))) {
461                 r = -errno;
462                 fclose(f);
463                 return r;
464         }
465
466         fclose(f);
467
468         /* Let's skip the pid and comm fields. The latter is enclosed
469          * in () but does not escape any () in its value, so let's
470          * skip over it manually */
471
472         if (!(p = strrchr(line, ')')))
473                 return -EIO;
474
475         p++;
476
477         if (sscanf(p, " "
478                    "%*c "  /* state */
479                    "%lu ", /* ppid */
480                    &ppid) != 1)
481                 return -EIO;
482
483         if ((long unsigned) (pid_t) ppid != ppid)
484                 return -ERANGE;
485
486         *_ppid = (pid_t) ppid;
487
488         return 0;
489 }
490
491 int write_one_line_file(const char *fn, const char *line) {
492         FILE *f;
493         int r;
494
495         assert(fn);
496         assert(line);
497
498         if (!(f = fopen(fn, "we")))
499                 return -errno;
500
501         if (fputs(line, f) < 0) {
502                 r = -errno;
503                 goto finish;
504         }
505
506         r = 0;
507 finish:
508         fclose(f);
509         return r;
510 }
511
512 int read_one_line_file(const char *fn, char **line) {
513         FILE *f;
514         int r;
515         char t[2048], *c;
516
517         assert(fn);
518         assert(line);
519
520         if (!(f = fopen(fn, "re")))
521                 return -errno;
522
523         if (!(fgets(t, sizeof(t), f))) {
524                 r = -errno;
525                 goto finish;
526         }
527
528         if (!(c = strdup(t))) {
529                 r = -ENOMEM;
530                 goto finish;
531         }
532
533         *line = c;
534         r = 0;
535
536 finish:
537         fclose(f);
538         return r;
539 }
540
541 char *truncate_nl(char *s) {
542         assert(s);
543
544         s[strcspn(s, NEWLINE)] = 0;
545         return s;
546 }
547
548 int get_process_name(pid_t pid, char **name) {
549         char *p;
550         int r;
551
552         assert(pid >= 1);
553         assert(name);
554
555         if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
556                 return -ENOMEM;
557
558         r = read_one_line_file(p, name);
559         free(p);
560
561         if (r < 0)
562                 return r;
563
564         truncate_nl(*name);
565         return 0;
566 }
567
568 char *strappend(const char *s, const char *suffix) {
569         size_t a, b;
570         char *r;
571
572         assert(s);
573         assert(suffix);
574
575         a = strlen(s);
576         b = strlen(suffix);
577
578         if (!(r = new(char, a+b+1)))
579                 return NULL;
580
581         memcpy(r, s, a);
582         memcpy(r+a, suffix, b);
583         r[a+b] = 0;
584
585         return r;
586 }
587
588 int readlink_malloc(const char *p, char **r) {
589         size_t l = 100;
590
591         assert(p);
592         assert(r);
593
594         for (;;) {
595                 char *c;
596                 ssize_t n;
597
598                 if (!(c = new(char, l)))
599                         return -ENOMEM;
600
601                 if ((n = readlink(p, c, l-1)) < 0) {
602                         int ret = -errno;
603                         free(c);
604                         return ret;
605                 }
606
607                 if ((size_t) n < l-1) {
608                         c[n] = 0;
609                         *r = c;
610                         return 0;
611                 }
612
613                 free(c);
614                 l *= 2;
615         }
616 }
617
618 int readlink_and_make_absolute(const char *p, char **r) {
619         char *target, *k;
620         int j;
621
622         assert(p);
623         assert(r);
624
625         if ((j = readlink_malloc(p, &target)) < 0)
626                 return j;
627
628         k = file_in_same_dir(p, target);
629         free(target);
630
631         if (!k)
632                 return -ENOMEM;
633
634         *r = k;
635         return 0;
636 }
637
638 char *file_name_from_path(const char *p) {
639         char *r;
640
641         assert(p);
642
643         if ((r = strrchr(p, '/')))
644                 return r + 1;
645
646         return (char*) p;
647 }
648
649 bool path_is_absolute(const char *p) {
650         assert(p);
651
652         return p[0] == '/';
653 }
654
655 bool is_path(const char *p) {
656
657         return !!strchr(p, '/');
658 }
659
660 char *path_make_absolute(const char *p, const char *prefix) {
661         char *r;
662
663         assert(p);
664
665         /* Makes every item in the list an absolute path by prepending
666          * the prefix, if specified and necessary */
667
668         if (path_is_absolute(p) || !prefix)
669                 return strdup(p);
670
671         if (asprintf(&r, "%s/%s", prefix, p) < 0)
672                 return NULL;
673
674         return r;
675 }
676
677 char *path_make_absolute_cwd(const char *p) {
678         char *cwd, *r;
679
680         assert(p);
681
682         /* Similar to path_make_absolute(), but prefixes with the
683          * current working directory. */
684
685         if (path_is_absolute(p))
686                 return strdup(p);
687
688         if (!(cwd = get_current_dir_name()))
689                 return NULL;
690
691         r = path_make_absolute(p, cwd);
692         free(cwd);
693
694         return r;
695 }
696
697 char **strv_path_make_absolute_cwd(char **l) {
698         char **s;
699
700         /* Goes through every item in the string list and makes it
701          * absolute. This works in place and won't rollback any
702          * changes on failure. */
703
704         STRV_FOREACH(s, l) {
705                 char *t;
706
707                 if (!(t = path_make_absolute_cwd(*s)))
708                         return NULL;
709
710                 free(*s);
711                 *s = t;
712         }
713
714         return l;
715 }
716
717 char **strv_path_canonicalize(char **l) {
718         char **s;
719         unsigned k = 0;
720         bool enomem = false;
721
722         if (strv_isempty(l))
723                 return l;
724
725         /* Goes through every item in the string list and canonicalize
726          * the path. This works in place and won't rollback any
727          * changes on failure. */
728
729         STRV_FOREACH(s, l) {
730                 char *t, *u;
731
732                 t = path_make_absolute_cwd(*s);
733                 free(*s);
734
735                 if (!t) {
736                         enomem = true;
737                         continue;
738                 }
739
740                 errno = 0;
741                 u = canonicalize_file_name(t);
742                 free(t);
743
744                 if (!u) {
745                         if (errno == ENOMEM || !errno)
746                                 enomem = true;
747
748                         continue;
749                 }
750
751                 l[k++] = u;
752         }
753
754         l[k] = NULL;
755
756         if (enomem)
757                 return NULL;
758
759         return l;
760 }
761
762 int reset_all_signal_handlers(void) {
763         int sig;
764
765         for (sig = 1; sig < _NSIG; sig++) {
766                 struct sigaction sa;
767
768                 if (sig == SIGKILL || sig == SIGSTOP)
769                         continue;
770
771                 zero(sa);
772                 sa.sa_handler = SIG_DFL;
773                 sa.sa_flags = SA_RESTART;
774
775                 /* On Linux the first two RT signals are reserved by
776                  * glibc, and sigaction() will return EINVAL for them. */
777                 if ((sigaction(sig, &sa, NULL) < 0))
778                         if (errno != EINVAL)
779                                 return -errno;
780         }
781
782         return 0;
783 }
784
785 char *strstrip(char *s) {
786         char *e, *l = NULL;
787
788         /* Drops trailing whitespace. Modifies the string in
789          * place. Returns pointer to first non-space character */
790
791         s += strspn(s, WHITESPACE);
792
793         for (e = s; *e; e++)
794                 if (!strchr(WHITESPACE, *e))
795                         l = e;
796
797         if (l)
798                 *(l+1) = 0;
799         else
800                 *s = 0;
801
802         return s;
803 }
804
805 char *delete_chars(char *s, const char *bad) {
806         char *f, *t;
807
808         /* Drops all whitespace, regardless where in the string */
809
810         for (f = s, t = s; *f; f++) {
811                 if (strchr(bad, *f))
812                         continue;
813
814                 *(t++) = *f;
815         }
816
817         *t = 0;
818
819         return s;
820 }
821
822 char *file_in_same_dir(const char *path, const char *filename) {
823         char *e, *r;
824         size_t k;
825
826         assert(path);
827         assert(filename);
828
829         /* This removes the last component of path and appends
830          * filename, unless the latter is absolute anyway or the
831          * former isn't */
832
833         if (path_is_absolute(filename))
834                 return strdup(filename);
835
836         if (!(e = strrchr(path, '/')))
837                 return strdup(filename);
838
839         k = strlen(filename);
840         if (!(r = new(char, e-path+1+k+1)))
841                 return NULL;
842
843         memcpy(r, path, e-path+1);
844         memcpy(r+(e-path)+1, filename, k+1);
845
846         return r;
847 }
848
849 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
850         struct stat st;
851
852         if (mkdir(path, mode) >= 0)
853                 if (chmod_and_chown(path, mode, uid, gid) < 0)
854                         return -errno;
855
856         if (lstat(path, &st) < 0)
857                 return -errno;
858
859         if ((st.st_mode & 0777) != mode ||
860             st.st_uid != uid ||
861             st.st_gid != gid ||
862             !S_ISDIR(st.st_mode)) {
863                 errno = EEXIST;
864                 return -errno;
865         }
866
867         return 0;
868 }
869
870
871 int mkdir_parents(const char *path, mode_t mode) {
872         const char *p, *e;
873
874         assert(path);
875
876         /* Creates every parent directory in the path except the last
877          * component. */
878
879         p = path + strspn(path, "/");
880         for (;;) {
881                 int r;
882                 char *t;
883
884                 e = p + strcspn(p, "/");
885                 p = e + strspn(e, "/");
886
887                 /* Is this the last component? If so, then we're
888                  * done */
889                 if (*p == 0)
890                         return 0;
891
892                 if (!(t = strndup(path, e - path)))
893                         return -ENOMEM;
894
895                 r = mkdir(t, mode);
896
897                 free(t);
898
899                 if (r < 0 && errno != EEXIST)
900                         return -errno;
901         }
902 }
903
904 int mkdir_p(const char *path, mode_t mode) {
905         int r;
906
907         /* Like mkdir -p */
908
909         if ((r = mkdir_parents(path, mode)) < 0)
910                 return r;
911
912         if (mkdir(path, mode) < 0)
913                 return -errno;
914
915         return 0;
916 }
917
918 int rmdir_parents(const char *path, const char *stop) {
919         size_t l;
920         int r = 0;
921
922         assert(path);
923         assert(stop);
924
925         l = strlen(path);
926
927         /* Skip trailing slashes */
928         while (l > 0 && path[l-1] == '/')
929                 l--;
930
931         while (l > 0) {
932                 char *t;
933
934                 /* Skip last component */
935                 while (l > 0 && path[l-1] != '/')
936                         l--;
937
938                 /* Skip trailing slashes */
939                 while (l > 0 && path[l-1] == '/')
940                         l--;
941
942                 if (l <= 0)
943                         break;
944
945                 if (!(t = strndup(path, l)))
946                         return -ENOMEM;
947
948                 if (path_startswith(stop, t)) {
949                         free(t);
950                         return 0;
951                 }
952
953                 r = rmdir(t);
954                 free(t);
955
956                 if (r < 0)
957                         if (errno != ENOENT)
958                                 return -errno;
959         }
960
961         return 0;
962 }
963
964
965 char hexchar(int x) {
966         static const char table[16] = "0123456789abcdef";
967
968         return table[x & 15];
969 }
970
971 int unhexchar(char c) {
972
973         if (c >= '0' && c <= '9')
974                 return c - '0';
975
976         if (c >= 'a' && c <= 'f')
977                 return c - 'a' + 10;
978
979         if (c >= 'A' && c <= 'F')
980                 return c - 'A' + 10;
981
982         return -1;
983 }
984
985 char octchar(int x) {
986         return '0' + (x & 7);
987 }
988
989 int unoctchar(char c) {
990
991         if (c >= '0' && c <= '7')
992                 return c - '0';
993
994         return -1;
995 }
996
997 char decchar(int x) {
998         return '0' + (x % 10);
999 }
1000
1001 int undecchar(char c) {
1002
1003         if (c >= '0' && c <= '9')
1004                 return c - '0';
1005
1006         return -1;
1007 }
1008
1009 char *cescape(const char *s) {
1010         char *r, *t;
1011         const char *f;
1012
1013         assert(s);
1014
1015         /* Does C style string escaping. */
1016
1017         if (!(r = new(char, strlen(s)*4 + 1)))
1018                 return NULL;
1019
1020         for (f = s, t = r; *f; f++)
1021
1022                 switch (*f) {
1023
1024                 case '\a':
1025                         *(t++) = '\\';
1026                         *(t++) = 'a';
1027                         break;
1028                 case '\b':
1029                         *(t++) = '\\';
1030                         *(t++) = 'b';
1031                         break;
1032                 case '\f':
1033                         *(t++) = '\\';
1034                         *(t++) = 'f';
1035                         break;
1036                 case '\n':
1037                         *(t++) = '\\';
1038                         *(t++) = 'n';
1039                         break;
1040                 case '\r':
1041                         *(t++) = '\\';
1042                         *(t++) = 'r';
1043                         break;
1044                 case '\t':
1045                         *(t++) = '\\';
1046                         *(t++) = 't';
1047                         break;
1048                 case '\v':
1049                         *(t++) = '\\';
1050                         *(t++) = 'v';
1051                         break;
1052                 case '\\':
1053                         *(t++) = '\\';
1054                         *(t++) = '\\';
1055                         break;
1056                 case '"':
1057                         *(t++) = '\\';
1058                         *(t++) = '"';
1059                         break;
1060                 case '\'':
1061                         *(t++) = '\\';
1062                         *(t++) = '\'';
1063                         break;
1064
1065                 default:
1066                         /* For special chars we prefer octal over
1067                          * hexadecimal encoding, simply because glib's
1068                          * g_strescape() does the same */
1069                         if ((*f < ' ') || (*f >= 127)) {
1070                                 *(t++) = '\\';
1071                                 *(t++) = octchar((unsigned char) *f >> 6);
1072                                 *(t++) = octchar((unsigned char) *f >> 3);
1073                                 *(t++) = octchar((unsigned char) *f);
1074                         } else
1075                                 *(t++) = *f;
1076                         break;
1077                 }
1078
1079         *t = 0;
1080
1081         return r;
1082 }
1083
1084 char *cunescape(const char *s) {
1085         char *r, *t;
1086         const char *f;
1087
1088         assert(s);
1089
1090         /* Undoes C style string escaping */
1091
1092         if (!(r = new(char, strlen(s)+1)))
1093                 return r;
1094
1095         for (f = s, t = r; *f; f++) {
1096
1097                 if (*f != '\\') {
1098                         *(t++) = *f;
1099                         continue;
1100                 }
1101
1102                 f++;
1103
1104                 switch (*f) {
1105
1106                 case 'a':
1107                         *(t++) = '\a';
1108                         break;
1109                 case 'b':
1110                         *(t++) = '\b';
1111                         break;
1112                 case 'f':
1113                         *(t++) = '\f';
1114                         break;
1115                 case 'n':
1116                         *(t++) = '\n';
1117                         break;
1118                 case 'r':
1119                         *(t++) = '\r';
1120                         break;
1121                 case 't':
1122                         *(t++) = '\t';
1123                         break;
1124                 case 'v':
1125                         *(t++) = '\v';
1126                         break;
1127                 case '\\':
1128                         *(t++) = '\\';
1129                         break;
1130                 case '"':
1131                         *(t++) = '"';
1132                         break;
1133                 case '\'':
1134                         *(t++) = '\'';
1135                         break;
1136
1137                 case 'x': {
1138                         /* hexadecimal encoding */
1139                         int a, b;
1140
1141                         if ((a = unhexchar(f[1])) < 0 ||
1142                             (b = unhexchar(f[2])) < 0) {
1143                                 /* Invalid escape code, let's take it literal then */
1144                                 *(t++) = '\\';
1145                                 *(t++) = 'x';
1146                         } else {
1147                                 *(t++) = (char) ((a << 4) | b);
1148                                 f += 2;
1149                         }
1150
1151                         break;
1152                 }
1153
1154                 case '0':
1155                 case '1':
1156                 case '2':
1157                 case '3':
1158                 case '4':
1159                 case '5':
1160                 case '6':
1161                 case '7': {
1162                         /* octal encoding */
1163                         int a, b, c;
1164
1165                         if ((a = unoctchar(f[0])) < 0 ||
1166                             (b = unoctchar(f[1])) < 0 ||
1167                             (c = unoctchar(f[2])) < 0) {
1168                                 /* Invalid escape code, let's take it literal then */
1169                                 *(t++) = '\\';
1170                                 *(t++) = f[0];
1171                         } else {
1172                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
1173                                 f += 2;
1174                         }
1175
1176                         break;
1177                 }
1178
1179                 case 0:
1180                         /* premature end of string.*/
1181                         *(t++) = '\\';
1182                         goto finish;
1183
1184                 default:
1185                         /* Invalid escape code, let's take it literal then */
1186                         *(t++) = '\\';
1187                         *(t++) = 'f';
1188                         break;
1189                 }
1190         }
1191
1192 finish:
1193         *t = 0;
1194         return r;
1195 }
1196
1197
1198 char *xescape(const char *s, const char *bad) {
1199         char *r, *t;
1200         const char *f;
1201
1202         /* Escapes all chars in bad, in addition to \ and all special
1203          * chars, in \xFF style escaping. May be reversed with
1204          * cunescape. */
1205
1206         if (!(r = new(char, strlen(s)*4+1)))
1207                 return NULL;
1208
1209         for (f = s, t = r; *f; f++) {
1210
1211                 if ((*f < ' ') || (*f >= 127) ||
1212                     (*f == '\\') || strchr(bad, *f)) {
1213                         *(t++) = '\\';
1214                         *(t++) = 'x';
1215                         *(t++) = hexchar(*f >> 4);
1216                         *(t++) = hexchar(*f);
1217                 } else
1218                         *(t++) = *f;
1219         }
1220
1221         *t = 0;
1222
1223         return r;
1224 }
1225
1226 char *bus_path_escape(const char *s) {
1227         char *r, *t;
1228         const char *f;
1229
1230         assert(s);
1231
1232         /* Escapes all chars that D-Bus' object path cannot deal
1233          * with. Can be reverse with bus_path_unescape() */
1234
1235         if (!(r = new(char, strlen(s)*3+1)))
1236                 return NULL;
1237
1238         for (f = s, t = r; *f; f++) {
1239
1240                 if (!(*f >= 'A' && *f <= 'Z') &&
1241                     !(*f >= 'a' && *f <= 'z') &&
1242                     !(*f >= '0' && *f <= '9')) {
1243                         *(t++) = '_';
1244                         *(t++) = hexchar(*f >> 4);
1245                         *(t++) = hexchar(*f);
1246                 } else
1247                         *(t++) = *f;
1248         }
1249
1250         *t = 0;
1251
1252         return r;
1253 }
1254
1255 char *bus_path_unescape(const char *f) {
1256         char *r, *t;
1257
1258         assert(f);
1259
1260         if (!(r = strdup(f)))
1261                 return NULL;
1262
1263         for (t = r; *f; f++) {
1264
1265                 if (*f == '_') {
1266                         int a, b;
1267
1268                         if ((a = unhexchar(f[1])) < 0 ||
1269                             (b = unhexchar(f[2])) < 0) {
1270                                 /* Invalid escape code, let's take it literal then */
1271                                 *(t++) = '_';
1272                         } else {
1273                                 *(t++) = (char) ((a << 4) | b);
1274                                 f += 2;
1275                         }
1276                 } else
1277                         *(t++) = *f;
1278         }
1279
1280         *t = 0;
1281
1282         return r;
1283 }
1284
1285 char *path_kill_slashes(char *path) {
1286         char *f, *t;
1287         bool slash = false;
1288
1289         /* Removes redundant inner and trailing slashes. Modifies the
1290          * passed string in-place.
1291          *
1292          * ///foo///bar/ becomes /foo/bar
1293          */
1294
1295         for (f = path, t = path; *f; f++) {
1296
1297                 if (*f == '/') {
1298                         slash = true;
1299                         continue;
1300                 }
1301
1302                 if (slash) {
1303                         slash = false;
1304                         *(t++) = '/';
1305                 }
1306
1307                 *(t++) = *f;
1308         }
1309
1310         /* Special rule, if we are talking of the root directory, a
1311         trailing slash is good */
1312
1313         if (t == path && slash)
1314                 *(t++) = '/';
1315
1316         *t = 0;
1317         return path;
1318 }
1319
1320 bool path_startswith(const char *path, const char *prefix) {
1321         assert(path);
1322         assert(prefix);
1323
1324         if ((path[0] == '/') != (prefix[0] == '/'))
1325                 return false;
1326
1327         for (;;) {
1328                 size_t a, b;
1329
1330                 path += strspn(path, "/");
1331                 prefix += strspn(prefix, "/");
1332
1333                 if (*prefix == 0)
1334                         return true;
1335
1336                 if (*path == 0)
1337                         return false;
1338
1339                 a = strcspn(path, "/");
1340                 b = strcspn(prefix, "/");
1341
1342                 if (a != b)
1343                         return false;
1344
1345                 if (memcmp(path, prefix, a) != 0)
1346                         return false;
1347
1348                 path += a;
1349                 prefix += b;
1350         }
1351 }
1352
1353 bool path_equal(const char *a, const char *b) {
1354         assert(a);
1355         assert(b);
1356
1357         if ((a[0] == '/') != (b[0] == '/'))
1358                 return false;
1359
1360         for (;;) {
1361                 size_t j, k;
1362
1363                 a += strspn(a, "/");
1364                 b += strspn(b, "/");
1365
1366                 if (*a == 0 && *b == 0)
1367                         return true;
1368
1369                 if (*a == 0 || *b == 0)
1370                         return false;
1371
1372                 j = strcspn(a, "/");
1373                 k = strcspn(b, "/");
1374
1375                 if (j != k)
1376                         return false;
1377
1378                 if (memcmp(a, b, j) != 0)
1379                         return false;
1380
1381                 a += j;
1382                 b += k;
1383         }
1384 }
1385
1386 char *ascii_strlower(char *t) {
1387         char *p;
1388
1389         assert(t);
1390
1391         for (p = t; *p; p++)
1392                 if (*p >= 'A' && *p <= 'Z')
1393                         *p = *p - 'A' + 'a';
1394
1395         return t;
1396 }
1397
1398 bool ignore_file(const char *filename) {
1399         assert(filename);
1400
1401         return
1402                 filename[0] == '.' ||
1403                 streq(filename, "lost+found") ||
1404                 endswith(filename, "~") ||
1405                 endswith(filename, ".rpmnew") ||
1406                 endswith(filename, ".rpmsave") ||
1407                 endswith(filename, ".rpmorig") ||
1408                 endswith(filename, ".dpkg-old") ||
1409                 endswith(filename, ".dpkg-new") ||
1410                 endswith(filename, ".swp");
1411 }
1412
1413 int fd_nonblock(int fd, bool nonblock) {
1414         int flags;
1415
1416         assert(fd >= 0);
1417
1418         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1419                 return -errno;
1420
1421         if (nonblock)
1422                 flags |= O_NONBLOCK;
1423         else
1424                 flags &= ~O_NONBLOCK;
1425
1426         if (fcntl(fd, F_SETFL, flags) < 0)
1427                 return -errno;
1428
1429         return 0;
1430 }
1431
1432 int fd_cloexec(int fd, bool cloexec) {
1433         int flags;
1434
1435         assert(fd >= 0);
1436
1437         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1438                 return -errno;
1439
1440         if (cloexec)
1441                 flags |= FD_CLOEXEC;
1442         else
1443                 flags &= ~FD_CLOEXEC;
1444
1445         if (fcntl(fd, F_SETFD, flags) < 0)
1446                 return -errno;
1447
1448         return 0;
1449 }
1450
1451 int close_all_fds(const int except[], unsigned n_except) {
1452         DIR *d;
1453         struct dirent *de;
1454         int r = 0;
1455
1456         if (!(d = opendir("/proc/self/fd")))
1457                 return -errno;
1458
1459         while ((de = readdir(d))) {
1460                 int fd = -1;
1461
1462                 if (ignore_file(de->d_name))
1463                         continue;
1464
1465                 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1466                         goto finish;
1467
1468                 if (fd < 3)
1469                         continue;
1470
1471                 if (fd == dirfd(d))
1472                         continue;
1473
1474                 if (except) {
1475                         bool found;
1476                         unsigned i;
1477
1478                         found = false;
1479                         for (i = 0; i < n_except; i++)
1480                                 if (except[i] == fd) {
1481                                         found = true;
1482                                         break;
1483                                 }
1484
1485                         if (found)
1486                                 continue;
1487                 }
1488
1489                 if ((r = close_nointr(fd)) < 0) {
1490                         /* Valgrind has its own FD and doesn't want to have it closed */
1491                         if (errno != EBADF)
1492                                 goto finish;
1493                 }
1494         }
1495
1496         r = 0;
1497
1498 finish:
1499         closedir(d);
1500         return r;
1501 }
1502
1503 bool chars_intersect(const char *a, const char *b) {
1504         const char *p;
1505
1506         /* Returns true if any of the chars in a are in b. */
1507         for (p = a; *p; p++)
1508                 if (strchr(b, *p))
1509                         return true;
1510
1511         return false;
1512 }
1513
1514 char *format_timestamp(char *buf, size_t l, usec_t t) {
1515         struct tm tm;
1516         time_t sec;
1517
1518         assert(buf);
1519         assert(l > 0);
1520
1521         if (t <= 0)
1522                 return NULL;
1523
1524         sec = (time_t) (t / USEC_PER_SEC);
1525
1526         if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1527                 return NULL;
1528
1529         return buf;
1530 }
1531
1532 char *format_timespan(char *buf, size_t l, usec_t t) {
1533         static const struct {
1534                 const char *suffix;
1535                 usec_t usec;
1536         } table[] = {
1537                 { "w", USEC_PER_WEEK },
1538                 { "d", USEC_PER_DAY },
1539                 { "h", USEC_PER_HOUR },
1540                 { "min", USEC_PER_MINUTE },
1541                 { "s", USEC_PER_SEC },
1542                 { "ms", USEC_PER_MSEC },
1543                 { "us", 1 },
1544         };
1545
1546         unsigned i;
1547         char *p = buf;
1548
1549         assert(buf);
1550         assert(l > 0);
1551
1552         if (t == (usec_t) -1)
1553                 return NULL;
1554
1555         /* The result of this function can be parsed with parse_usec */
1556
1557         for (i = 0; i < ELEMENTSOF(table); i++) {
1558                 int k;
1559                 size_t n;
1560
1561                 if (t < table[i].usec)
1562                         continue;
1563
1564                 if (l <= 1)
1565                         break;
1566
1567                 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1568                 n = MIN((size_t) k, l);
1569
1570                 l -= n;
1571                 p += n;
1572
1573                 t %= table[i].usec;
1574         }
1575
1576         *p = 0;
1577
1578         return buf;
1579 }
1580
1581 bool fstype_is_network(const char *fstype) {
1582         static const char * const table[] = {
1583                 "cifs",
1584                 "smbfs",
1585                 "ncpfs",
1586                 "nfs",
1587                 "nfs4",
1588                 "gfs",
1589                 "gfs2"
1590         };
1591
1592         unsigned i;
1593
1594         for (i = 0; i < ELEMENTSOF(table); i++)
1595                 if (streq(table[i], fstype))
1596                         return true;
1597
1598         return false;
1599 }
1600
1601 int chvt(int vt) {
1602         int fd, r = 0;
1603
1604         if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1605                 return -errno;
1606
1607         if (vt < 0) {
1608                 int tiocl[2] = {
1609                         TIOCL_GETKMSGREDIRECT,
1610                         0
1611                 };
1612
1613                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1614                         return -errno;
1615
1616                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1617         }
1618
1619         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1620                 r = -errno;
1621
1622         close_nointr_nofail(r);
1623         return r;
1624 }
1625
1626 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1627         struct termios old_termios, new_termios;
1628         char c;
1629         char line[1024];
1630
1631         assert(f);
1632         assert(ret);
1633
1634         if (tcgetattr(fileno(f), &old_termios) >= 0) {
1635                 new_termios = old_termios;
1636
1637                 new_termios.c_lflag &= ~ICANON;
1638                 new_termios.c_cc[VMIN] = 1;
1639                 new_termios.c_cc[VTIME] = 0;
1640
1641                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1642                         size_t k;
1643
1644                         k = fread(&c, 1, 1, f);
1645
1646                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1647
1648                         if (k <= 0)
1649                                 return -EIO;
1650
1651                         if (need_nl)
1652                                 *need_nl = c != '\n';
1653
1654                         *ret = c;
1655                         return 0;
1656                 }
1657         }
1658
1659         if (!(fgets(line, sizeof(line), f)))
1660                 return -EIO;
1661
1662         truncate_nl(line);
1663
1664         if (strlen(line) != 1)
1665                 return -EBADMSG;
1666
1667         if (need_nl)
1668                 *need_nl = false;
1669
1670         *ret = line[0];
1671         return 0;
1672 }
1673
1674 int ask(char *ret, const char *replies, const char *text, ...) {
1675         assert(ret);
1676         assert(replies);
1677         assert(text);
1678
1679         for (;;) {
1680                 va_list ap;
1681                 char c;
1682                 int r;
1683                 bool need_nl = true;
1684
1685                 fputs("\x1B[1m", stdout);
1686
1687                 va_start(ap, text);
1688                 vprintf(text, ap);
1689                 va_end(ap);
1690
1691                 fputs("\x1B[0m", stdout);
1692
1693                 fflush(stdout);
1694
1695                 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1696
1697                         if (r == -EBADMSG) {
1698                                 puts("Bad input, please try again.");
1699                                 continue;
1700                         }
1701
1702                         putchar('\n');
1703                         return r;
1704                 }
1705
1706                 if (need_nl)
1707                         putchar('\n');
1708
1709                 if (strchr(replies, c)) {
1710                         *ret = c;
1711                         return 0;
1712                 }
1713
1714                 puts("Read unexpected character, please try again.");
1715         }
1716 }
1717
1718 int reset_terminal(int fd) {
1719         struct termios termios;
1720         int r = 0;
1721
1722         assert(fd >= 0);
1723
1724         /* Set terminal to some sane defaults */
1725
1726         if (tcgetattr(fd, &termios) < 0) {
1727                 r = -errno;
1728                 goto finish;
1729         }
1730
1731         /* We only reset the stuff that matters to the software. How
1732          * hardware is set up we don't touch assuming that somebody
1733          * else will do that for us */
1734
1735         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1736         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1737         termios.c_oflag |= ONLCR;
1738         termios.c_cflag |= CREAD;
1739         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1740
1741         termios.c_cc[VINTR]    =   03;  /* ^C */
1742         termios.c_cc[VQUIT]    =  034;  /* ^\ */
1743         termios.c_cc[VERASE]   = 0177;
1744         termios.c_cc[VKILL]    =  025;  /* ^X */
1745         termios.c_cc[VEOF]     =   04;  /* ^D */
1746         termios.c_cc[VSTART]   =  021;  /* ^Q */
1747         termios.c_cc[VSTOP]    =  023;  /* ^S */
1748         termios.c_cc[VSUSP]    =  032;  /* ^Z */
1749         termios.c_cc[VLNEXT]   =  026;  /* ^V */
1750         termios.c_cc[VWERASE]  =  027;  /* ^W */
1751         termios.c_cc[VREPRINT] =  022;  /* ^R */
1752         termios.c_cc[VEOL]     =    0;
1753         termios.c_cc[VEOL2]    =    0;
1754
1755         termios.c_cc[VTIME]  = 0;
1756         termios.c_cc[VMIN]   = 1;
1757
1758         if (tcsetattr(fd, TCSANOW, &termios) < 0)
1759                 r = -errno;
1760
1761 finish:
1762         /* Just in case, flush all crap out */
1763         tcflush(fd, TCIOFLUSH);
1764
1765         return r;
1766 }
1767
1768 int open_terminal(const char *name, int mode) {
1769         int fd, r;
1770
1771         if ((fd = open(name, mode)) < 0)
1772                 return -errno;
1773
1774         if ((r = isatty(fd)) < 0) {
1775                 close_nointr_nofail(fd);
1776                 return -errno;
1777         }
1778
1779         if (!r) {
1780                 close_nointr_nofail(fd);
1781                 return -ENOTTY;
1782         }
1783
1784         return fd;
1785 }
1786
1787 int flush_fd(int fd) {
1788         struct pollfd pollfd;
1789
1790         zero(pollfd);
1791         pollfd.fd = fd;
1792         pollfd.events = POLLIN;
1793
1794         for (;;) {
1795                 char buf[1024];
1796                 ssize_t l;
1797                 int r;
1798
1799                 if ((r = poll(&pollfd, 1, 0)) < 0) {
1800
1801                         if (errno == EINTR)
1802                                 continue;
1803
1804                         return -errno;
1805                 }
1806
1807                 if (r == 0)
1808                         return 0;
1809
1810                 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1811
1812                         if (errno == EINTR)
1813                                 continue;
1814
1815                         if (errno == EAGAIN)
1816                                 return 0;
1817
1818                         return -errno;
1819                 }
1820
1821                 if (l <= 0)
1822                         return 0;
1823         }
1824 }
1825
1826 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1827         int fd = -1, notify = -1, r, wd = -1;
1828
1829         assert(name);
1830
1831         /* We use inotify to be notified when the tty is closed. We
1832          * create the watch before checking if we can actually acquire
1833          * it, so that we don't lose any event.
1834          *
1835          * Note: strictly speaking this actually watches for the
1836          * device being closed, it does *not* really watch whether a
1837          * tty loses its controlling process. However, unless some
1838          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1839          * its tty otherwise this will not become a problem. As long
1840          * as the administrator makes sure not configure any service
1841          * on the same tty as an untrusted user this should not be a
1842          * problem. (Which he probably should not do anyway.) */
1843
1844         if (!fail && !force) {
1845                 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1846                         r = -errno;
1847                         goto fail;
1848                 }
1849
1850                 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1851                         r = -errno;
1852                         goto fail;
1853                 }
1854         }
1855
1856         for (;;) {
1857                 if (notify >= 0)
1858                         if ((r = flush_fd(notify)) < 0)
1859                                 goto fail;
1860
1861                 /* We pass here O_NOCTTY only so that we can check the return
1862                  * value TIOCSCTTY and have a reliable way to figure out if we
1863                  * successfully became the controlling process of the tty */
1864                 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1865                         return -errno;
1866
1867                 /* First, try to get the tty */
1868                 r = ioctl(fd, TIOCSCTTY, force);
1869
1870                 /* Sometimes it makes sense to ignore TIOCSCTTY
1871                  * returning EPERM, i.e. when very likely we already
1872                  * are have this controlling terminal. */
1873                 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
1874                         r = 0;
1875
1876                 if (r < 0 && (force || fail || errno != EPERM)) {
1877                         r = -errno;
1878                         goto fail;
1879                 }
1880
1881                 if (r >= 0)
1882                         break;
1883
1884                 assert(!fail);
1885                 assert(!force);
1886                 assert(notify >= 0);
1887
1888                 for (;;) {
1889                         struct inotify_event e;
1890                         ssize_t l;
1891
1892                         if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1893
1894                                 if (l < 0) {
1895
1896                                         if (errno == EINTR)
1897                                                 continue;
1898
1899                                         r = -errno;
1900                                 } else
1901                                         r = -EIO;
1902
1903                                 goto fail;
1904                         }
1905
1906                         if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1907                                 r = -errno;
1908                                 goto fail;
1909                         }
1910
1911                         break;
1912                 }
1913
1914                 /* We close the tty fd here since if the old session
1915                  * ended our handle will be dead. It's important that
1916                  * we do this after sleeping, so that we don't enter
1917                  * an endless loop. */
1918                 close_nointr_nofail(fd);
1919         }
1920
1921         if (notify >= 0)
1922                 close_nointr_nofail(notify);
1923
1924         if ((r = reset_terminal(fd)) < 0)
1925                 log_warning("Failed to reset terminal: %s", strerror(-r));
1926
1927         return fd;
1928
1929 fail:
1930         if (fd >= 0)
1931                 close_nointr_nofail(fd);
1932
1933         if (notify >= 0)
1934                 close_nointr_nofail(notify);
1935
1936         return r;
1937 }
1938
1939 int release_terminal(void) {
1940         int r = 0, fd;
1941         struct sigaction sa_old, sa_new;
1942
1943         if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
1944                 return -errno;
1945
1946         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1947          * by our own TIOCNOTTY */
1948
1949         zero(sa_new);
1950         sa_new.sa_handler = SIG_IGN;
1951         sa_new.sa_flags = SA_RESTART;
1952         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1953
1954         if (ioctl(fd, TIOCNOTTY) < 0)
1955                 r = -errno;
1956
1957         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1958
1959         close_nointr_nofail(fd);
1960         return r;
1961 }
1962
1963 int sigaction_many(const struct sigaction *sa, ...) {
1964         va_list ap;
1965         int r = 0, sig;
1966
1967         va_start(ap, sa);
1968         while ((sig = va_arg(ap, int)) > 0)
1969                 if (sigaction(sig, sa, NULL) < 0)
1970                         r = -errno;
1971         va_end(ap);
1972
1973         return r;
1974 }
1975
1976 int ignore_signals(int sig, ...) {
1977         struct sigaction sa;
1978         va_list ap;
1979         int r = 0;
1980
1981         zero(sa);
1982         sa.sa_handler = SIG_IGN;
1983         sa.sa_flags = SA_RESTART;
1984
1985         if (sigaction(sig, &sa, NULL) < 0)
1986                 r = -errno;
1987
1988         va_start(ap, sig);
1989         while ((sig = va_arg(ap, int)) > 0)
1990                 if (sigaction(sig, &sa, NULL) < 0)
1991                         r = -errno;
1992         va_end(ap);
1993
1994         return r;
1995 }
1996
1997 int default_signals(int sig, ...) {
1998         struct sigaction sa;
1999         va_list ap;
2000         int r = 0;
2001
2002         zero(sa);
2003         sa.sa_handler = SIG_DFL;
2004         sa.sa_flags = SA_RESTART;
2005
2006         if (sigaction(sig, &sa, NULL) < 0)
2007                 r = -errno;
2008
2009         va_start(ap, sig);
2010         while ((sig = va_arg(ap, int)) > 0)
2011                 if (sigaction(sig, &sa, NULL) < 0)
2012                         r = -errno;
2013         va_end(ap);
2014
2015         return r;
2016 }
2017
2018 int close_pipe(int p[]) {
2019         int a = 0, b = 0;
2020
2021         assert(p);
2022
2023         if (p[0] >= 0) {
2024                 a = close_nointr(p[0]);
2025                 p[0] = -1;
2026         }
2027
2028         if (p[1] >= 0) {
2029                 b = close_nointr(p[1]);
2030                 p[1] = -1;
2031         }
2032
2033         return a < 0 ? a : b;
2034 }
2035
2036 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2037         uint8_t *p;
2038         ssize_t n = 0;
2039
2040         assert(fd >= 0);
2041         assert(buf);
2042
2043         p = buf;
2044
2045         while (nbytes > 0) {
2046                 ssize_t k;
2047
2048                 if ((k = read(fd, p, nbytes)) <= 0) {
2049
2050                         if (k < 0 && errno == EINTR)
2051                                 continue;
2052
2053                         if (k < 0 && errno == EAGAIN && do_poll) {
2054                                 struct pollfd pollfd;
2055
2056                                 zero(pollfd);
2057                                 pollfd.fd = fd;
2058                                 pollfd.events = POLLIN;
2059
2060                                 if (poll(&pollfd, 1, -1) < 0) {
2061                                         if (errno == EINTR)
2062                                                 continue;
2063
2064                                         return n > 0 ? n : -errno;
2065                                 }
2066
2067                                 if (pollfd.revents != POLLIN)
2068                                         return n > 0 ? n : -EIO;
2069
2070                                 continue;
2071                         }
2072
2073                         return n > 0 ? n : (k < 0 ? -errno : 0);
2074                 }
2075
2076                 p += k;
2077                 nbytes -= k;
2078                 n += k;
2079         }
2080
2081         return n;
2082 }
2083
2084 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2085         const uint8_t *p;
2086         ssize_t n = 0;
2087
2088         assert(fd >= 0);
2089         assert(buf);
2090
2091         p = buf;
2092
2093         while (nbytes > 0) {
2094                 ssize_t k;
2095
2096                 if ((k = write(fd, p, nbytes)) <= 0) {
2097
2098                         if (k < 0 && errno == EINTR)
2099                                 continue;
2100
2101                         if (k < 0 && errno == EAGAIN && do_poll) {
2102                                 struct pollfd pollfd;
2103
2104                                 zero(pollfd);
2105                                 pollfd.fd = fd;
2106                                 pollfd.events = POLLOUT;
2107
2108                                 if (poll(&pollfd, 1, -1) < 0) {
2109                                         if (errno == EINTR)
2110                                                 continue;
2111
2112                                         return n > 0 ? n : -errno;
2113                                 }
2114
2115                                 if (pollfd.revents != POLLOUT)
2116                                         return n > 0 ? n : -EIO;
2117
2118                                 continue;
2119                         }
2120
2121                         return n > 0 ? n : (k < 0 ? -errno : 0);
2122                 }
2123
2124                 p += k;
2125                 nbytes -= k;
2126                 n += k;
2127         }
2128
2129         return n;
2130 }
2131
2132 int path_is_mount_point(const char *t) {
2133         struct stat a, b;
2134         char *copy;
2135
2136         if (lstat(t, &a) < 0) {
2137
2138                 if (errno == ENOENT)
2139                         return 0;
2140
2141                 return -errno;
2142         }
2143
2144         if (!(copy = strdup(t)))
2145                 return -ENOMEM;
2146
2147         if (lstat(dirname(copy), &b) < 0) {
2148                 free(copy);
2149                 return -errno;
2150         }
2151
2152         free(copy);
2153
2154         return a.st_dev != b.st_dev;
2155 }
2156
2157 int parse_usec(const char *t, usec_t *usec) {
2158         static const struct {
2159                 const char *suffix;
2160                 usec_t usec;
2161         } table[] = {
2162                 { "sec", USEC_PER_SEC },
2163                 { "s", USEC_PER_SEC },
2164                 { "min", USEC_PER_MINUTE },
2165                 { "hr", USEC_PER_HOUR },
2166                 { "h", USEC_PER_HOUR },
2167                 { "d", USEC_PER_DAY },
2168                 { "w", USEC_PER_WEEK },
2169                 { "msec", USEC_PER_MSEC },
2170                 { "ms", USEC_PER_MSEC },
2171                 { "m", USEC_PER_MINUTE },
2172                 { "usec", 1ULL },
2173                 { "us", 1ULL },
2174                 { "", USEC_PER_SEC },
2175         };
2176
2177         const char *p;
2178         usec_t r = 0;
2179
2180         assert(t);
2181         assert(usec);
2182
2183         p = t;
2184         do {
2185                 long long l;
2186                 char *e;
2187                 unsigned i;
2188
2189                 errno = 0;
2190                 l = strtoll(p, &e, 10);
2191
2192                 if (errno != 0)
2193                         return -errno;
2194
2195                 if (l < 0)
2196                         return -ERANGE;
2197
2198                 if (e == p)
2199                         return -EINVAL;
2200
2201                 e += strspn(e, WHITESPACE);
2202
2203                 for (i = 0; i < ELEMENTSOF(table); i++)
2204                         if (startswith(e, table[i].suffix)) {
2205                                 r += (usec_t) l * table[i].usec;
2206                                 p = e + strlen(table[i].suffix);
2207                                 break;
2208                         }
2209
2210                 if (i >= ELEMENTSOF(table))
2211                         return -EINVAL;
2212
2213         } while (*p != 0);
2214
2215         *usec = r;
2216
2217         return 0;
2218 }
2219
2220 int make_stdio(int fd) {
2221         int r, s, t;
2222
2223         assert(fd >= 0);
2224
2225         r = dup2(fd, STDIN_FILENO);
2226         s = dup2(fd, STDOUT_FILENO);
2227         t = dup2(fd, STDERR_FILENO);
2228
2229         if (fd >= 3)
2230                 close_nointr_nofail(fd);
2231
2232         if (r < 0 || s < 0 || t < 0)
2233                 return -errno;
2234
2235         return 0;
2236 }
2237
2238 bool is_clean_exit(int code, int status) {
2239
2240         if (code == CLD_EXITED)
2241                 return status == 0;
2242
2243         /* If a daemon does not implement handlers for some of the
2244          * signals that's not considered an unclean shutdown */
2245         if (code == CLD_KILLED)
2246                 return
2247                         status == SIGHUP ||
2248                         status == SIGINT ||
2249                         status == SIGTERM ||
2250                         status == SIGPIPE;
2251
2252         return false;
2253 }
2254
2255 bool is_device_path(const char *path) {
2256
2257         /* Returns true on paths that refer to a device, either in
2258          * sysfs or in /dev */
2259
2260         return
2261                 path_startswith(path, "/dev/") ||
2262                 path_startswith(path, "/sys/");
2263 }
2264
2265 int dir_is_empty(const char *path) {
2266         DIR *d;
2267         int r;
2268         struct dirent buf, *de;
2269
2270         if (!(d = opendir(path)))
2271                 return -errno;
2272
2273         for (;;) {
2274                 if ((r = readdir_r(d, &buf, &de)) > 0) {
2275                         r = -r;
2276                         break;
2277                 }
2278
2279                 if (!de) {
2280                         r = 1;
2281                         break;
2282                 }
2283
2284                 if (!ignore_file(de->d_name)) {
2285                         r = 0;
2286                         break;
2287                 }
2288         }
2289
2290         closedir(d);
2291         return r;
2292 }
2293
2294 unsigned long long random_ull(void) {
2295         int fd;
2296         uint64_t ull;
2297         ssize_t r;
2298
2299         if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2300                 goto fallback;
2301
2302         r = loop_read(fd, &ull, sizeof(ull), true);
2303         close_nointr_nofail(fd);
2304
2305         if (r != sizeof(ull))
2306                 goto fallback;
2307
2308         return ull;
2309
2310 fallback:
2311         return random() * RAND_MAX + random();
2312 }
2313
2314 void rename_process(const char name[8]) {
2315         assert(name);
2316
2317         prctl(PR_SET_NAME, name);
2318
2319         /* This is a like a poor man's setproctitle(). The string
2320          * passed should fit in 7 chars (i.e. the length of
2321          * "systemd") */
2322
2323         if (program_invocation_name)
2324                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2325 }
2326
2327 void sigset_add_many(sigset_t *ss, ...) {
2328         va_list ap;
2329         int sig;
2330
2331         assert(ss);
2332
2333         va_start(ap, ss);
2334         while ((sig = va_arg(ap, int)) > 0)
2335                 assert_se(sigaddset(ss, sig) == 0);
2336         va_end(ap);
2337 }
2338
2339 char* gethostname_malloc(void) {
2340         struct utsname u;
2341
2342         assert_se(uname(&u) >= 0);
2343
2344         if (u.nodename[0])
2345                 return strdup(u.nodename);
2346
2347         return strdup(u.sysname);
2348 }
2349
2350 int getmachineid_malloc(char **b) {
2351         int r;
2352
2353         assert(b);
2354
2355         if ((r = read_one_line_file("/var/lib/dbus/machine-id", b)) < 0)
2356                 return r;
2357
2358         strstrip(*b);
2359         return 0;
2360 }
2361
2362 char* getlogname_malloc(void) {
2363         uid_t uid;
2364         long bufsize;
2365         char *buf, *name;
2366         struct passwd pwbuf, *pw = NULL;
2367         struct stat st;
2368
2369         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2370                 uid = st.st_uid;
2371         else
2372                 uid = getuid();
2373
2374         /* Shortcut things to avoid NSS lookups */
2375         if (uid == 0)
2376                 return strdup("root");
2377
2378         if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2379                 bufsize = 4096;
2380
2381         if (!(buf = malloc(bufsize)))
2382                 return NULL;
2383
2384         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2385                 name = strdup(pw->pw_name);
2386                 free(buf);
2387                 return name;
2388         }
2389
2390         free(buf);
2391
2392         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2393                 return NULL;
2394
2395         return name;
2396 }
2397
2398 int getttyname_malloc(char **r) {
2399         char path[PATH_MAX], *p, *c;
2400
2401         assert(r);
2402
2403         if (ttyname_r(STDIN_FILENO, path, sizeof(path)) < 0)
2404                 return -errno;
2405
2406         char_array_0(path);
2407
2408         p = path;
2409         if (startswith(path, "/dev/"))
2410                 p += 5;
2411
2412         if (!(c = strdup(p)))
2413                 return -ENOMEM;
2414
2415         *r = c;
2416         return 0;
2417 }
2418
2419 static int rm_rf_children(int fd, bool only_dirs) {
2420         DIR *d;
2421         int ret = 0;
2422
2423         assert(fd >= 0);
2424
2425         /* This returns the first error we run into, but nevertheless
2426          * tries to go on */
2427
2428         if (!(d = fdopendir(fd))) {
2429                 close_nointr_nofail(fd);
2430                 return -errno;
2431         }
2432
2433         for (;;) {
2434                 struct dirent buf, *de;
2435                 bool is_dir;
2436                 int r;
2437
2438                 if ((r = readdir_r(d, &buf, &de)) != 0) {
2439                         if (ret == 0)
2440                                 ret = -r;
2441                         break;
2442                 }
2443
2444                 if (!de)
2445                         break;
2446
2447                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2448                         continue;
2449
2450                 if (de->d_type == DT_UNKNOWN) {
2451                         struct stat st;
2452
2453                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2454                                 if (ret == 0)
2455                                         ret = -errno;
2456                                 continue;
2457                         }
2458
2459                         is_dir = S_ISDIR(st.st_mode);
2460                 } else
2461                         is_dir = de->d_type == DT_DIR;
2462
2463                 if (is_dir) {
2464                         int subdir_fd;
2465
2466                         if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2467                                 if (ret == 0)
2468                                         ret = -errno;
2469                                 continue;
2470                         }
2471
2472                         if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2473                                 if (ret == 0)
2474                                         ret = r;
2475                         }
2476
2477                         if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2478                                 if (ret == 0)
2479                                         ret = -errno;
2480                         }
2481                 } else  if (!only_dirs) {
2482
2483                         if (unlinkat(fd, de->d_name, 0) < 0) {
2484                                 if (ret == 0)
2485                                         ret = -errno;
2486                         }
2487                 }
2488         }
2489
2490         closedir(d);
2491
2492         return ret;
2493 }
2494
2495 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2496         int fd;
2497         int r;
2498
2499         assert(path);
2500
2501         if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2502
2503                 if (errno != ENOTDIR)
2504                         return -errno;
2505
2506                 if (delete_root && !only_dirs)
2507                         if (unlink(path) < 0)
2508                                 return -errno;
2509
2510                 return 0;
2511         }
2512
2513         r = rm_rf_children(fd, only_dirs);
2514
2515         if (delete_root)
2516                 if (rmdir(path) < 0) {
2517                         if (r == 0)
2518                                 r = -errno;
2519                 }
2520
2521         return r;
2522 }
2523
2524 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2525         assert(path);
2526
2527         /* Under the assumption that we are running privileged we
2528          * first change the access mode and only then hand out
2529          * ownership to avoid a window where access is too open. */
2530
2531         if (chmod(path, mode) < 0)
2532                 return -errno;
2533
2534         if (chown(path, uid, gid) < 0)
2535                 return -errno;
2536
2537         return 0;
2538 }
2539
2540 static const char *const ioprio_class_table[] = {
2541         [IOPRIO_CLASS_NONE] = "none",
2542         [IOPRIO_CLASS_RT] = "realtime",
2543         [IOPRIO_CLASS_BE] = "best-effort",
2544         [IOPRIO_CLASS_IDLE] = "idle"
2545 };
2546
2547 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2548
2549 static const char *const sigchld_code_table[] = {
2550         [CLD_EXITED] = "exited",
2551         [CLD_KILLED] = "killed",
2552         [CLD_DUMPED] = "dumped",
2553         [CLD_TRAPPED] = "trapped",
2554         [CLD_STOPPED] = "stopped",
2555         [CLD_CONTINUED] = "continued",
2556 };
2557
2558 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2559
2560 static const char *const log_facility_table[LOG_NFACILITIES] = {
2561         [LOG_FAC(LOG_KERN)] = "kern",
2562         [LOG_FAC(LOG_USER)] = "user",
2563         [LOG_FAC(LOG_MAIL)] = "mail",
2564         [LOG_FAC(LOG_DAEMON)] = "daemon",
2565         [LOG_FAC(LOG_AUTH)] = "auth",
2566         [LOG_FAC(LOG_SYSLOG)] = "syslog",
2567         [LOG_FAC(LOG_LPR)] = "lpr",
2568         [LOG_FAC(LOG_NEWS)] = "news",
2569         [LOG_FAC(LOG_UUCP)] = "uucp",
2570         [LOG_FAC(LOG_CRON)] = "cron",
2571         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2572         [LOG_FAC(LOG_FTP)] = "ftp",
2573         [LOG_FAC(LOG_LOCAL0)] = "local0",
2574         [LOG_FAC(LOG_LOCAL1)] = "local1",
2575         [LOG_FAC(LOG_LOCAL2)] = "local2",
2576         [LOG_FAC(LOG_LOCAL3)] = "local3",
2577         [LOG_FAC(LOG_LOCAL4)] = "local4",
2578         [LOG_FAC(LOG_LOCAL5)] = "local5",
2579         [LOG_FAC(LOG_LOCAL6)] = "local6",
2580         [LOG_FAC(LOG_LOCAL7)] = "local7"
2581 };
2582
2583 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2584
2585 static const char *const log_level_table[] = {
2586         [LOG_EMERG] = "emerg",
2587         [LOG_ALERT] = "alert",
2588         [LOG_CRIT] = "crit",
2589         [LOG_ERR] = "err",
2590         [LOG_WARNING] = "warning",
2591         [LOG_NOTICE] = "notice",
2592         [LOG_INFO] = "info",
2593         [LOG_DEBUG] = "debug"
2594 };
2595
2596 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2597
2598 static const char* const sched_policy_table[] = {
2599         [SCHED_OTHER] = "other",
2600         [SCHED_BATCH] = "batch",
2601         [SCHED_IDLE] = "idle",
2602         [SCHED_FIFO] = "fifo",
2603         [SCHED_RR] = "rr"
2604 };
2605
2606 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2607
2608 static const char* const rlimit_table[] = {
2609         [RLIMIT_CPU] = "LimitCPU",
2610         [RLIMIT_FSIZE] = "LimitFSIZE",
2611         [RLIMIT_DATA] = "LimitDATA",
2612         [RLIMIT_STACK] = "LimitSTACK",
2613         [RLIMIT_CORE] = "LimitCORE",
2614         [RLIMIT_RSS] = "LimitRSS",
2615         [RLIMIT_NOFILE] = "LimitNOFILE",
2616         [RLIMIT_AS] = "LimitAS",
2617         [RLIMIT_NPROC] = "LimitNPROC",
2618         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2619         [RLIMIT_LOCKS] = "LimitLOCKS",
2620         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2621         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2622         [RLIMIT_NICE] = "LimitNICE",
2623         [RLIMIT_RTPRIO] = "LimitRTPRIO",
2624         [RLIMIT_RTTIME] = "LimitRTTIME"
2625 };
2626
2627 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);