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