chiark / gitweb /
dbus: expose shutdown helper via D-Bus
[elogind.git] / src / util.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
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 #include <linux/kd.h>
51 #include <dlfcn.h>
52 #include <sys/wait.h>
53
54 #include "macro.h"
55 #include "util.h"
56 #include "ioprio.h"
57 #include "missing.h"
58 #include "log.h"
59 #include "strv.h"
60 #include "label.h"
61 #include "exit-status.h"
62
63 bool streq_ptr(const char *a, const char *b) {
64
65         /* Like streq(), but tries to make sense of NULL pointers */
66
67         if (a && b)
68                 return streq(a, b);
69
70         if (!a && !b)
71                 return true;
72
73         return false;
74 }
75
76 usec_t now(clockid_t clock_id) {
77         struct timespec ts;
78
79         assert_se(clock_gettime(clock_id, &ts) == 0);
80
81         return timespec_load(&ts);
82 }
83
84 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
85         assert(ts);
86
87         ts->realtime = now(CLOCK_REALTIME);
88         ts->monotonic = now(CLOCK_MONOTONIC);
89
90         return ts;
91 }
92
93 usec_t timespec_load(const struct timespec *ts) {
94         assert(ts);
95
96         return
97                 (usec_t) ts->tv_sec * USEC_PER_SEC +
98                 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
99 }
100
101 struct timespec *timespec_store(struct timespec *ts, usec_t u)  {
102         assert(ts);
103
104         ts->tv_sec = (time_t) (u / USEC_PER_SEC);
105         ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
106
107         return ts;
108 }
109
110 usec_t timeval_load(const struct timeval *tv) {
111         assert(tv);
112
113         return
114                 (usec_t) tv->tv_sec * USEC_PER_SEC +
115                 (usec_t) tv->tv_usec;
116 }
117
118 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
119         assert(tv);
120
121         tv->tv_sec = (time_t) (u / USEC_PER_SEC);
122         tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
123
124         return tv;
125 }
126
127 bool endswith(const char *s, const char *postfix) {
128         size_t sl, pl;
129
130         assert(s);
131         assert(postfix);
132
133         sl = strlen(s);
134         pl = strlen(postfix);
135
136         if (pl == 0)
137                 return true;
138
139         if (sl < pl)
140                 return false;
141
142         return memcmp(s + sl - pl, postfix, pl) == 0;
143 }
144
145 bool startswith(const char *s, const char *prefix) {
146         size_t sl, pl;
147
148         assert(s);
149         assert(prefix);
150
151         sl = strlen(s);
152         pl = strlen(prefix);
153
154         if (pl == 0)
155                 return true;
156
157         if (sl < pl)
158                 return false;
159
160         return memcmp(s, prefix, pl) == 0;
161 }
162
163 bool startswith_no_case(const char *s, const char *prefix) {
164         size_t sl, pl;
165         unsigned i;
166
167         assert(s);
168         assert(prefix);
169
170         sl = strlen(s);
171         pl = strlen(prefix);
172
173         if (pl == 0)
174                 return true;
175
176         if (sl < pl)
177                 return false;
178
179         for(i = 0; i < pl; ++i) {
180                 if (tolower(s[i]) != tolower(prefix[i]))
181                         return false;
182         }
183
184         return true;
185 }
186
187 bool first_word(const char *s, const char *word) {
188         size_t sl, wl;
189
190         assert(s);
191         assert(word);
192
193         sl = strlen(s);
194         wl = strlen(word);
195
196         if (sl < wl)
197                 return false;
198
199         if (wl == 0)
200                 return true;
201
202         if (memcmp(s, word, wl) != 0)
203                 return false;
204
205         return s[wl] == 0 ||
206                 strchr(WHITESPACE, s[wl]);
207 }
208
209 int close_nointr(int fd) {
210         assert(fd >= 0);
211
212         for (;;) {
213                 int r;
214
215                 if ((r = close(fd)) >= 0)
216                         return r;
217
218                 if (errno != EINTR)
219                         return r;
220         }
221 }
222
223 void close_nointr_nofail(int fd) {
224         int saved_errno = errno;
225
226         /* like close_nointr() but cannot fail, and guarantees errno
227          * is unchanged */
228
229         assert_se(close_nointr(fd) == 0);
230
231         errno = saved_errno;
232 }
233
234 void close_many(const int fds[], unsigned n_fd) {
235         unsigned i;
236
237         for (i = 0; i < n_fd; i++)
238                 close_nointr_nofail(fds[i]);
239 }
240
241 int parse_boolean(const char *v) {
242         assert(v);
243
244         if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
245                 return 1;
246         else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
247                 return 0;
248
249         return -EINVAL;
250 }
251
252 int parse_pid(const char *s, pid_t* ret_pid) {
253         unsigned long ul;
254         pid_t pid;
255         int r;
256
257         assert(s);
258         assert(ret_pid);
259
260         if ((r = safe_atolu(s, &ul)) < 0)
261                 return r;
262
263         pid = (pid_t) ul;
264
265         if ((unsigned long) pid != ul)
266                 return -ERANGE;
267
268         if (pid <= 0)
269                 return -ERANGE;
270
271         *ret_pid = pid;
272         return 0;
273 }
274
275 int safe_atou(const char *s, unsigned *ret_u) {
276         char *x = NULL;
277         unsigned long l;
278
279         assert(s);
280         assert(ret_u);
281
282         errno = 0;
283         l = strtoul(s, &x, 0);
284
285         if (!x || *x || errno)
286                 return errno ? -errno : -EINVAL;
287
288         if ((unsigned long) (unsigned) l != l)
289                 return -ERANGE;
290
291         *ret_u = (unsigned) l;
292         return 0;
293 }
294
295 int safe_atoi(const char *s, int *ret_i) {
296         char *x = NULL;
297         long l;
298
299         assert(s);
300         assert(ret_i);
301
302         errno = 0;
303         l = strtol(s, &x, 0);
304
305         if (!x || *x || errno)
306                 return errno ? -errno : -EINVAL;
307
308         if ((long) (int) l != l)
309                 return -ERANGE;
310
311         *ret_i = (int) l;
312         return 0;
313 }
314
315 int safe_atollu(const char *s, long long unsigned *ret_llu) {
316         char *x = NULL;
317         unsigned long long l;
318
319         assert(s);
320         assert(ret_llu);
321
322         errno = 0;
323         l = strtoull(s, &x, 0);
324
325         if (!x || *x || errno)
326                 return errno ? -errno : -EINVAL;
327
328         *ret_llu = l;
329         return 0;
330 }
331
332 int safe_atolli(const char *s, long long int *ret_lli) {
333         char *x = NULL;
334         long long l;
335
336         assert(s);
337         assert(ret_lli);
338
339         errno = 0;
340         l = strtoll(s, &x, 0);
341
342         if (!x || *x || errno)
343                 return errno ? -errno : -EINVAL;
344
345         *ret_lli = l;
346         return 0;
347 }
348
349 /* Split a string into words. */
350 char *split(const char *c, size_t *l, const char *separator, char **state) {
351         char *current;
352
353         current = *state ? *state : (char*) c;
354
355         if (!*current || *c == 0)
356                 return NULL;
357
358         current += strspn(current, separator);
359         *l = strcspn(current, separator);
360         *state = current+*l;
361
362         return (char*) current;
363 }
364
365 /* Split a string into words, but consider strings enclosed in '' and
366  * "" as words even if they include spaces. */
367 char *split_quoted(const char *c, size_t *l, char **state) {
368         char *current, *e;
369         bool escaped = false;
370
371         current = *state ? *state : (char*) c;
372
373         if (!*current || *c == 0)
374                 return NULL;
375
376         current += strspn(current, WHITESPACE);
377
378         if (*current == '\'') {
379                 current ++;
380
381                 for (e = current; *e; e++) {
382                         if (escaped)
383                                 escaped = false;
384                         else if (*e == '\\')
385                                 escaped = true;
386                         else if (*e == '\'')
387                                 break;
388                 }
389
390                 *l = e-current;
391                 *state = *e == 0 ? e : e+1;
392         } else if (*current == '\"') {
393                 current ++;
394
395                 for (e = current; *e; e++) {
396                         if (escaped)
397                                 escaped = false;
398                         else if (*e == '\\')
399                                 escaped = true;
400                         else if (*e == '\"')
401                                 break;
402                 }
403
404                 *l = e-current;
405                 *state = *e == 0 ? e : e+1;
406         } else {
407                 for (e = current; *e; e++) {
408                         if (escaped)
409                                 escaped = false;
410                         else if (*e == '\\')
411                                 escaped = true;
412                         else if (strchr(WHITESPACE, *e))
413                                 break;
414                 }
415                 *l = e-current;
416                 *state = e;
417         }
418
419         return (char*) current;
420 }
421
422 char **split_path_and_make_absolute(const char *p) {
423         char **l;
424         assert(p);
425
426         if (!(l = strv_split(p, ":")))
427                 return NULL;
428
429         if (!strv_path_make_absolute_cwd(l)) {
430                 strv_free(l);
431                 return NULL;
432         }
433
434         return l;
435 }
436
437 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
438         int r;
439         FILE *f;
440         char fn[132], line[256], *p;
441         long unsigned ppid;
442
443         assert(pid >= 0);
444         assert(_ppid);
445
446         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
447         fn[sizeof(fn)-1] = 0;
448
449         if (!(f = fopen(fn, "r")))
450                 return -errno;
451
452         if (!(fgets(line, sizeof(line), f))) {
453                 r = -errno;
454                 fclose(f);
455                 return r;
456         }
457
458         fclose(f);
459
460         /* Let's skip the pid and comm fields. The latter is enclosed
461          * in () but does not escape any () in its value, so let's
462          * skip over it manually */
463
464         if (!(p = strrchr(line, ')')))
465                 return -EIO;
466
467         p++;
468
469         if (sscanf(p, " "
470                    "%*c "  /* state */
471                    "%lu ", /* ppid */
472                    &ppid) != 1)
473                 return -EIO;
474
475         if ((long unsigned) (pid_t) ppid != ppid)
476                 return -ERANGE;
477
478         *_ppid = (pid_t) ppid;
479
480         return 0;
481 }
482
483 int write_one_line_file(const char *fn, const char *line) {
484         FILE *f;
485         int r;
486
487         assert(fn);
488         assert(line);
489
490         if (!(f = fopen(fn, "we")))
491                 return -errno;
492
493         if (fputs(line, f) < 0) {
494                 r = -errno;
495                 goto finish;
496         }
497
498         r = 0;
499 finish:
500         fclose(f);
501         return r;
502 }
503
504 int read_one_line_file(const char *fn, char **line) {
505         FILE *f;
506         int r;
507         char t[LINE_MAX], *c;
508
509         assert(fn);
510         assert(line);
511
512         if (!(f = fopen(fn, "re")))
513                 return -errno;
514
515         if (!(fgets(t, sizeof(t), f))) {
516                 r = -errno;
517                 goto finish;
518         }
519
520         if (!(c = strdup(t))) {
521                 r = -ENOMEM;
522                 goto finish;
523         }
524
525         *line = c;
526         r = 0;
527
528 finish:
529         fclose(f);
530         return r;
531 }
532
533 int read_full_file(const char *fn, char **contents) {
534         FILE *f;
535         int r;
536         size_t n, l;
537         char *buf = NULL;
538         struct stat st;
539
540         if (!(f = fopen(fn, "re")))
541                 return -errno;
542
543         if (fstat(fileno(f), &st) < 0) {
544                 r = -errno;
545                 goto finish;
546         }
547
548         n = st.st_size > 0 ? st.st_size : LINE_MAX;
549         l = 0;
550
551         for (;;) {
552                 char *t;
553                 size_t k;
554
555                 if (!(t = realloc(buf, n+1))) {
556                         r = -ENOMEM;
557                         goto finish;
558                 }
559
560                 buf = t;
561                 k = fread(buf + l, 1, n - l, f);
562
563                 if (k <= 0) {
564                         if (ferror(f)) {
565                                 r = -errno;
566                                 goto finish;
567                         }
568
569                         break;
570                 }
571
572                 l += k;
573                 n *= 2;
574
575                 /* Safety check */
576                 if (n > 4*1024*1024) {
577                         r = -E2BIG;
578                         goto finish;
579                 }
580         }
581
582         if (buf)
583                 buf[l] = 0;
584         else if (!(buf = calloc(1, 1))) {
585                 r = -errno;
586                 goto finish;
587         }
588
589         *contents = buf;
590         buf = NULL;
591
592         r = 0;
593
594 finish:
595         fclose(f);
596         free(buf);
597
598         return r;
599 }
600
601 int parse_env_file(
602                 const char *fname,
603                 const char *separator, ...) {
604
605         int r = 0;
606         char *contents, *p;
607
608         assert(fname);
609         assert(separator);
610
611         if ((r = read_full_file(fname, &contents)) < 0)
612                 return r;
613
614         p = contents;
615         for (;;) {
616                 const char *key = NULL;
617
618                 p += strspn(p, separator);
619                 p += strspn(p, WHITESPACE);
620
621                 if (!*p)
622                         break;
623
624                 if (!strchr(COMMENTS, *p)) {
625                         va_list ap;
626                         char **value;
627
628                         va_start(ap, separator);
629                         while ((key = va_arg(ap, char *))) {
630                                 size_t n;
631                                 char *v;
632
633                                 value = va_arg(ap, char **);
634
635                                 n = strlen(key);
636                                 if (strncmp(p, key, n) != 0 ||
637                                     p[n] != '=')
638                                         continue;
639
640                                 p += n + 1;
641                                 n = strcspn(p, separator);
642
643                                 if (n >= 2 &&
644                                     strchr(QUOTES, p[0]) &&
645                                     p[n-1] == p[0])
646                                         v = strndup(p+1, n-2);
647                                 else
648                                         v = strndup(p, n);
649
650                                 if (!v) {
651                                         r = -ENOMEM;
652                                         va_end(ap);
653                                         goto fail;
654                                 }
655
656                                 if (v[0] == '\0') {
657                                         /* return empty value strings as NULL */
658                                         free(v);
659                                         v = NULL;
660                                 }
661
662                                 free(*value);
663                                 *value = v;
664
665                                 p += n;
666
667                                 r ++;
668                                 break;
669                         }
670                         va_end(ap);
671                 }
672
673                 if (!key)
674                         p += strcspn(p, separator);
675         }
676
677 fail:
678         free(contents);
679         return r;
680 }
681
682 char *truncate_nl(char *s) {
683         assert(s);
684
685         s[strcspn(s, NEWLINE)] = 0;
686         return s;
687 }
688
689 int get_process_name(pid_t pid, char **name) {
690         char *p;
691         int r;
692
693         assert(pid >= 1);
694         assert(name);
695
696         if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
697                 return -ENOMEM;
698
699         r = read_one_line_file(p, name);
700         free(p);
701
702         if (r < 0)
703                 return r;
704
705         truncate_nl(*name);
706         return 0;
707 }
708
709 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
710         char *p, *r, *k;
711         int c;
712         bool space = false;
713         size_t left;
714         FILE *f;
715
716         assert(pid >= 1);
717         assert(max_length > 0);
718         assert(line);
719
720         if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
721                 return -ENOMEM;
722
723         f = fopen(p, "r");
724         free(p);
725
726         if (!f)
727                 return -errno;
728
729         if (!(r = new(char, max_length))) {
730                 fclose(f);
731                 return -ENOMEM;
732         }
733
734         k = r;
735         left = max_length;
736         while ((c = getc(f)) != EOF) {
737
738                 if (isprint(c)) {
739                         if (space) {
740                                 if (left <= 4)
741                                         break;
742
743                                 *(k++) = ' ';
744                                 left--;
745                                 space = false;
746                         }
747
748                         if (left <= 4)
749                                 break;
750
751                         *(k++) = (char) c;
752                         left--;
753                 }  else
754                         space = true;
755         }
756
757         if (left <= 4) {
758                 size_t n = MIN(left-1, 3U);
759                 memcpy(k, "...", n);
760                 k[n] = 0;
761         } else
762                 *k = 0;
763
764         fclose(f);
765
766         /* Kernel threads have no argv[] */
767         if (r[0] == 0) {
768                 char *t;
769                 int h;
770
771                 free(r);
772
773                 if ((h = get_process_name(pid, &t)) < 0)
774                         return h;
775
776                 h = asprintf(&r, "[%s]", t);
777                 free(t);
778
779                 if (h < 0)
780                         return -ENOMEM;
781         }
782
783         *line = r;
784         return 0;
785 }
786
787 char *strnappend(const char *s, const char *suffix, size_t b) {
788         size_t a;
789         char *r;
790
791         if (!s && !suffix)
792                 return strdup("");
793
794         if (!s)
795                 return strndup(suffix, b);
796
797         if (!suffix)
798                 return strdup(s);
799
800         assert(s);
801         assert(suffix);
802
803         a = strlen(s);
804
805         if (!(r = new(char, a+b+1)))
806                 return NULL;
807
808         memcpy(r, s, a);
809         memcpy(r+a, suffix, b);
810         r[a+b] = 0;
811
812         return r;
813 }
814
815 char *strappend(const char *s, const char *suffix) {
816         return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
817 }
818
819 int readlink_malloc(const char *p, char **r) {
820         size_t l = 100;
821
822         assert(p);
823         assert(r);
824
825         for (;;) {
826                 char *c;
827                 ssize_t n;
828
829                 if (!(c = new(char, l)))
830                         return -ENOMEM;
831
832                 if ((n = readlink(p, c, l-1)) < 0) {
833                         int ret = -errno;
834                         free(c);
835                         return ret;
836                 }
837
838                 if ((size_t) n < l-1) {
839                         c[n] = 0;
840                         *r = c;
841                         return 0;
842                 }
843
844                 free(c);
845                 l *= 2;
846         }
847 }
848
849 int readlink_and_make_absolute(const char *p, char **r) {
850         char *target, *k;
851         int j;
852
853         assert(p);
854         assert(r);
855
856         if ((j = readlink_malloc(p, &target)) < 0)
857                 return j;
858
859         k = file_in_same_dir(p, target);
860         free(target);
861
862         if (!k)
863                 return -ENOMEM;
864
865         *r = k;
866         return 0;
867 }
868
869 int parent_of_path(const char *path, char **_r) {
870         const char *e, *a = NULL, *b = NULL, *p;
871         char *r;
872         bool slash = false;
873
874         assert(path);
875         assert(_r);
876
877         if (!*path)
878                 return -EINVAL;
879
880         for (e = path; *e; e++) {
881
882                 if (!slash && *e == '/') {
883                         a = b;
884                         b = e;
885                         slash = true;
886                 } else if (slash && *e != '/')
887                         slash = false;
888         }
889
890         if (*(e-1) == '/')
891                 p = a;
892         else
893                 p = b;
894
895         if (!p)
896                 return -EINVAL;
897
898         if (p == path)
899                 r = strdup("/");
900         else
901                 r = strndup(path, p-path);
902
903         if (!r)
904                 return -ENOMEM;
905
906         *_r = r;
907         return 0;
908 }
909
910
911 char *file_name_from_path(const char *p) {
912         char *r;
913
914         assert(p);
915
916         if ((r = strrchr(p, '/')))
917                 return r + 1;
918
919         return (char*) p;
920 }
921
922 bool path_is_absolute(const char *p) {
923         assert(p);
924
925         return p[0] == '/';
926 }
927
928 bool is_path(const char *p) {
929
930         return !!strchr(p, '/');
931 }
932
933 char *path_make_absolute(const char *p, const char *prefix) {
934         char *r;
935
936         assert(p);
937
938         /* Makes every item in the list an absolute path by prepending
939          * the prefix, if specified and necessary */
940
941         if (path_is_absolute(p) || !prefix)
942                 return strdup(p);
943
944         if (asprintf(&r, "%s/%s", prefix, p) < 0)
945                 return NULL;
946
947         return r;
948 }
949
950 char *path_make_absolute_cwd(const char *p) {
951         char *cwd, *r;
952
953         assert(p);
954
955         /* Similar to path_make_absolute(), but prefixes with the
956          * current working directory. */
957
958         if (path_is_absolute(p))
959                 return strdup(p);
960
961         if (!(cwd = get_current_dir_name()))
962                 return NULL;
963
964         r = path_make_absolute(p, cwd);
965         free(cwd);
966
967         return r;
968 }
969
970 char **strv_path_make_absolute_cwd(char **l) {
971         char **s;
972
973         /* Goes through every item in the string list and makes it
974          * absolute. This works in place and won't rollback any
975          * changes on failure. */
976
977         STRV_FOREACH(s, l) {
978                 char *t;
979
980                 if (!(t = path_make_absolute_cwd(*s)))
981                         return NULL;
982
983                 free(*s);
984                 *s = t;
985         }
986
987         return l;
988 }
989
990 char **strv_path_canonicalize(char **l) {
991         char **s;
992         unsigned k = 0;
993         bool enomem = false;
994
995         if (strv_isempty(l))
996                 return l;
997
998         /* Goes through every item in the string list and canonicalize
999          * the path. This works in place and won't rollback any
1000          * changes on failure. */
1001
1002         STRV_FOREACH(s, l) {
1003                 char *t, *u;
1004
1005                 t = path_make_absolute_cwd(*s);
1006                 free(*s);
1007
1008                 if (!t) {
1009                         enomem = true;
1010                         continue;
1011                 }
1012
1013                 errno = 0;
1014                 u = canonicalize_file_name(t);
1015                 free(t);
1016
1017                 if (!u) {
1018                         if (errno == ENOMEM || !errno)
1019                                 enomem = true;
1020
1021                         continue;
1022                 }
1023
1024                 l[k++] = u;
1025         }
1026
1027         l[k] = NULL;
1028
1029         if (enomem)
1030                 return NULL;
1031
1032         return l;
1033 }
1034
1035 int reset_all_signal_handlers(void) {
1036         int sig;
1037
1038         for (sig = 1; sig < _NSIG; sig++) {
1039                 struct sigaction sa;
1040
1041                 if (sig == SIGKILL || sig == SIGSTOP)
1042                         continue;
1043
1044                 zero(sa);
1045                 sa.sa_handler = SIG_DFL;
1046                 sa.sa_flags = SA_RESTART;
1047
1048                 /* On Linux the first two RT signals are reserved by
1049                  * glibc, and sigaction() will return EINVAL for them. */
1050                 if ((sigaction(sig, &sa, NULL) < 0))
1051                         if (errno != EINVAL)
1052                                 return -errno;
1053         }
1054
1055         return 0;
1056 }
1057
1058 char *strstrip(char *s) {
1059         char *e, *l = NULL;
1060
1061         /* Drops trailing whitespace. Modifies the string in
1062          * place. Returns pointer to first non-space character */
1063
1064         s += strspn(s, WHITESPACE);
1065
1066         for (e = s; *e; e++)
1067                 if (!strchr(WHITESPACE, *e))
1068                         l = e;
1069
1070         if (l)
1071                 *(l+1) = 0;
1072         else
1073                 *s = 0;
1074
1075         return s;
1076 }
1077
1078 char *delete_chars(char *s, const char *bad) {
1079         char *f, *t;
1080
1081         /* Drops all whitespace, regardless where in the string */
1082
1083         for (f = s, t = s; *f; f++) {
1084                 if (strchr(bad, *f))
1085                         continue;
1086
1087                 *(t++) = *f;
1088         }
1089
1090         *t = 0;
1091
1092         return s;
1093 }
1094
1095 char *file_in_same_dir(const char *path, const char *filename) {
1096         char *e, *r;
1097         size_t k;
1098
1099         assert(path);
1100         assert(filename);
1101
1102         /* This removes the last component of path and appends
1103          * filename, unless the latter is absolute anyway or the
1104          * former isn't */
1105
1106         if (path_is_absolute(filename))
1107                 return strdup(filename);
1108
1109         if (!(e = strrchr(path, '/')))
1110                 return strdup(filename);
1111
1112         k = strlen(filename);
1113         if (!(r = new(char, e-path+1+k+1)))
1114                 return NULL;
1115
1116         memcpy(r, path, e-path+1);
1117         memcpy(r+(e-path)+1, filename, k+1);
1118
1119         return r;
1120 }
1121
1122 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1123         struct stat st;
1124
1125         if (label_mkdir(path, mode) >= 0)
1126                 if (chmod_and_chown(path, mode, uid, gid) < 0)
1127                         return -errno;
1128
1129         if (lstat(path, &st) < 0)
1130                 return -errno;
1131
1132         if ((st.st_mode & 0777) != mode ||
1133             st.st_uid != uid ||
1134             st.st_gid != gid ||
1135             !S_ISDIR(st.st_mode)) {
1136                 errno = EEXIST;
1137                 return -errno;
1138         }
1139
1140         return 0;
1141 }
1142
1143
1144 int mkdir_parents(const char *path, mode_t mode) {
1145         const char *p, *e;
1146
1147         assert(path);
1148
1149         /* Creates every parent directory in the path except the last
1150          * component. */
1151
1152         p = path + strspn(path, "/");
1153         for (;;) {
1154                 int r;
1155                 char *t;
1156
1157                 e = p + strcspn(p, "/");
1158                 p = e + strspn(e, "/");
1159
1160                 /* Is this the last component? If so, then we're
1161                  * done */
1162                 if (*p == 0)
1163                         return 0;
1164
1165                 if (!(t = strndup(path, e - path)))
1166                         return -ENOMEM;
1167
1168                 r = label_mkdir(t, mode);
1169                 free(t);
1170
1171                 if (r < 0 && errno != EEXIST)
1172                         return -errno;
1173         }
1174 }
1175
1176 int mkdir_p(const char *path, mode_t mode) {
1177         int r;
1178
1179         /* Like mkdir -p */
1180
1181         if ((r = mkdir_parents(path, mode)) < 0)
1182                 return r;
1183
1184         if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1185                 return -errno;
1186
1187         return 0;
1188 }
1189
1190 int rmdir_parents(const char *path, const char *stop) {
1191         size_t l;
1192         int r = 0;
1193
1194         assert(path);
1195         assert(stop);
1196
1197         l = strlen(path);
1198
1199         /* Skip trailing slashes */
1200         while (l > 0 && path[l-1] == '/')
1201                 l--;
1202
1203         while (l > 0) {
1204                 char *t;
1205
1206                 /* Skip last component */
1207                 while (l > 0 && path[l-1] != '/')
1208                         l--;
1209
1210                 /* Skip trailing slashes */
1211                 while (l > 0 && path[l-1] == '/')
1212                         l--;
1213
1214                 if (l <= 0)
1215                         break;
1216
1217                 if (!(t = strndup(path, l)))
1218                         return -ENOMEM;
1219
1220                 if (path_startswith(stop, t)) {
1221                         free(t);
1222                         return 0;
1223                 }
1224
1225                 r = rmdir(t);
1226                 free(t);
1227
1228                 if (r < 0)
1229                         if (errno != ENOENT)
1230                                 return -errno;
1231         }
1232
1233         return 0;
1234 }
1235
1236
1237 char hexchar(int x) {
1238         static const char table[16] = "0123456789abcdef";
1239
1240         return table[x & 15];
1241 }
1242
1243 int unhexchar(char c) {
1244
1245         if (c >= '0' && c <= '9')
1246                 return c - '0';
1247
1248         if (c >= 'a' && c <= 'f')
1249                 return c - 'a' + 10;
1250
1251         if (c >= 'A' && c <= 'F')
1252                 return c - 'A' + 10;
1253
1254         return -1;
1255 }
1256
1257 char octchar(int x) {
1258         return '0' + (x & 7);
1259 }
1260
1261 int unoctchar(char c) {
1262
1263         if (c >= '0' && c <= '7')
1264                 return c - '0';
1265
1266         return -1;
1267 }
1268
1269 char decchar(int x) {
1270         return '0' + (x % 10);
1271 }
1272
1273 int undecchar(char c) {
1274
1275         if (c >= '0' && c <= '9')
1276                 return c - '0';
1277
1278         return -1;
1279 }
1280
1281 char *cescape(const char *s) {
1282         char *r, *t;
1283         const char *f;
1284
1285         assert(s);
1286
1287         /* Does C style string escaping. */
1288
1289         if (!(r = new(char, strlen(s)*4 + 1)))
1290                 return NULL;
1291
1292         for (f = s, t = r; *f; f++)
1293
1294                 switch (*f) {
1295
1296                 case '\a':
1297                         *(t++) = '\\';
1298                         *(t++) = 'a';
1299                         break;
1300                 case '\b':
1301                         *(t++) = '\\';
1302                         *(t++) = 'b';
1303                         break;
1304                 case '\f':
1305                         *(t++) = '\\';
1306                         *(t++) = 'f';
1307                         break;
1308                 case '\n':
1309                         *(t++) = '\\';
1310                         *(t++) = 'n';
1311                         break;
1312                 case '\r':
1313                         *(t++) = '\\';
1314                         *(t++) = 'r';
1315                         break;
1316                 case '\t':
1317                         *(t++) = '\\';
1318                         *(t++) = 't';
1319                         break;
1320                 case '\v':
1321                         *(t++) = '\\';
1322                         *(t++) = 'v';
1323                         break;
1324                 case '\\':
1325                         *(t++) = '\\';
1326                         *(t++) = '\\';
1327                         break;
1328                 case '"':
1329                         *(t++) = '\\';
1330                         *(t++) = '"';
1331                         break;
1332                 case '\'':
1333                         *(t++) = '\\';
1334                         *(t++) = '\'';
1335                         break;
1336
1337                 default:
1338                         /* For special chars we prefer octal over
1339                          * hexadecimal encoding, simply because glib's
1340                          * g_strescape() does the same */
1341                         if ((*f < ' ') || (*f >= 127)) {
1342                                 *(t++) = '\\';
1343                                 *(t++) = octchar((unsigned char) *f >> 6);
1344                                 *(t++) = octchar((unsigned char) *f >> 3);
1345                                 *(t++) = octchar((unsigned char) *f);
1346                         } else
1347                                 *(t++) = *f;
1348                         break;
1349                 }
1350
1351         *t = 0;
1352
1353         return r;
1354 }
1355
1356 char *cunescape_length(const char *s, size_t length) {
1357         char *r, *t;
1358         const char *f;
1359
1360         assert(s);
1361
1362         /* Undoes C style string escaping */
1363
1364         if (!(r = new(char, length+1)))
1365                 return r;
1366
1367         for (f = s, t = r; f < s + length; f++) {
1368
1369                 if (*f != '\\') {
1370                         *(t++) = *f;
1371                         continue;
1372                 }
1373
1374                 f++;
1375
1376                 switch (*f) {
1377
1378                 case 'a':
1379                         *(t++) = '\a';
1380                         break;
1381                 case 'b':
1382                         *(t++) = '\b';
1383                         break;
1384                 case 'f':
1385                         *(t++) = '\f';
1386                         break;
1387                 case 'n':
1388                         *(t++) = '\n';
1389                         break;
1390                 case 'r':
1391                         *(t++) = '\r';
1392                         break;
1393                 case 't':
1394                         *(t++) = '\t';
1395                         break;
1396                 case 'v':
1397                         *(t++) = '\v';
1398                         break;
1399                 case '\\':
1400                         *(t++) = '\\';
1401                         break;
1402                 case '"':
1403                         *(t++) = '"';
1404                         break;
1405                 case '\'':
1406                         *(t++) = '\'';
1407                         break;
1408
1409                 case 's':
1410                         /* This is an extension of the XDG syntax files */
1411                         *(t++) = ' ';
1412                         break;
1413
1414                 case 'x': {
1415                         /* hexadecimal encoding */
1416                         int a, b;
1417
1418                         if ((a = unhexchar(f[1])) < 0 ||
1419                             (b = unhexchar(f[2])) < 0) {
1420                                 /* Invalid escape code, let's take it literal then */
1421                                 *(t++) = '\\';
1422                                 *(t++) = 'x';
1423                         } else {
1424                                 *(t++) = (char) ((a << 4) | b);
1425                                 f += 2;
1426                         }
1427
1428                         break;
1429                 }
1430
1431                 case '0':
1432                 case '1':
1433                 case '2':
1434                 case '3':
1435                 case '4':
1436                 case '5':
1437                 case '6':
1438                 case '7': {
1439                         /* octal encoding */
1440                         int a, b, c;
1441
1442                         if ((a = unoctchar(f[0])) < 0 ||
1443                             (b = unoctchar(f[1])) < 0 ||
1444                             (c = unoctchar(f[2])) < 0) {
1445                                 /* Invalid escape code, let's take it literal then */
1446                                 *(t++) = '\\';
1447                                 *(t++) = f[0];
1448                         } else {
1449                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
1450                                 f += 2;
1451                         }
1452
1453                         break;
1454                 }
1455
1456                 case 0:
1457                         /* premature end of string.*/
1458                         *(t++) = '\\';
1459                         goto finish;
1460
1461                 default:
1462                         /* Invalid escape code, let's take it literal then */
1463                         *(t++) = '\\';
1464                         *(t++) = *f;
1465                         break;
1466                 }
1467         }
1468
1469 finish:
1470         *t = 0;
1471         return r;
1472 }
1473
1474 char *cunescape(const char *s) {
1475         return cunescape_length(s, strlen(s));
1476 }
1477
1478 char *xescape(const char *s, const char *bad) {
1479         char *r, *t;
1480         const char *f;
1481
1482         /* Escapes all chars in bad, in addition to \ and all special
1483          * chars, in \xFF style escaping. May be reversed with
1484          * cunescape. */
1485
1486         if (!(r = new(char, strlen(s)*4+1)))
1487                 return NULL;
1488
1489         for (f = s, t = r; *f; f++) {
1490
1491                 if ((*f < ' ') || (*f >= 127) ||
1492                     (*f == '\\') || strchr(bad, *f)) {
1493                         *(t++) = '\\';
1494                         *(t++) = 'x';
1495                         *(t++) = hexchar(*f >> 4);
1496                         *(t++) = hexchar(*f);
1497                 } else
1498                         *(t++) = *f;
1499         }
1500
1501         *t = 0;
1502
1503         return r;
1504 }
1505
1506 char *bus_path_escape(const char *s) {
1507         char *r, *t;
1508         const char *f;
1509
1510         assert(s);
1511
1512         /* Escapes all chars that D-Bus' object path cannot deal
1513          * with. Can be reverse with bus_path_unescape() */
1514
1515         if (!(r = new(char, strlen(s)*3+1)))
1516                 return NULL;
1517
1518         for (f = s, t = r; *f; f++) {
1519
1520                 if (!(*f >= 'A' && *f <= 'Z') &&
1521                     !(*f >= 'a' && *f <= 'z') &&
1522                     !(*f >= '0' && *f <= '9')) {
1523                         *(t++) = '_';
1524                         *(t++) = hexchar(*f >> 4);
1525                         *(t++) = hexchar(*f);
1526                 } else
1527                         *(t++) = *f;
1528         }
1529
1530         *t = 0;
1531
1532         return r;
1533 }
1534
1535 char *bus_path_unescape(const char *f) {
1536         char *r, *t;
1537
1538         assert(f);
1539
1540         if (!(r = strdup(f)))
1541                 return NULL;
1542
1543         for (t = r; *f; f++) {
1544
1545                 if (*f == '_') {
1546                         int a, b;
1547
1548                         if ((a = unhexchar(f[1])) < 0 ||
1549                             (b = unhexchar(f[2])) < 0) {
1550                                 /* Invalid escape code, let's take it literal then */
1551                                 *(t++) = '_';
1552                         } else {
1553                                 *(t++) = (char) ((a << 4) | b);
1554                                 f += 2;
1555                         }
1556                 } else
1557                         *(t++) = *f;
1558         }
1559
1560         *t = 0;
1561
1562         return r;
1563 }
1564
1565 char *path_kill_slashes(char *path) {
1566         char *f, *t;
1567         bool slash = false;
1568
1569         /* Removes redundant inner and trailing slashes. Modifies the
1570          * passed string in-place.
1571          *
1572          * ///foo///bar/ becomes /foo/bar
1573          */
1574
1575         for (f = path, t = path; *f; f++) {
1576
1577                 if (*f == '/') {
1578                         slash = true;
1579                         continue;
1580                 }
1581
1582                 if (slash) {
1583                         slash = false;
1584                         *(t++) = '/';
1585                 }
1586
1587                 *(t++) = *f;
1588         }
1589
1590         /* Special rule, if we are talking of the root directory, a
1591         trailing slash is good */
1592
1593         if (t == path && slash)
1594                 *(t++) = '/';
1595
1596         *t = 0;
1597         return path;
1598 }
1599
1600 bool path_startswith(const char *path, const char *prefix) {
1601         assert(path);
1602         assert(prefix);
1603
1604         if ((path[0] == '/') != (prefix[0] == '/'))
1605                 return false;
1606
1607         for (;;) {
1608                 size_t a, b;
1609
1610                 path += strspn(path, "/");
1611                 prefix += strspn(prefix, "/");
1612
1613                 if (*prefix == 0)
1614                         return true;
1615
1616                 if (*path == 0)
1617                         return false;
1618
1619                 a = strcspn(path, "/");
1620                 b = strcspn(prefix, "/");
1621
1622                 if (a != b)
1623                         return false;
1624
1625                 if (memcmp(path, prefix, a) != 0)
1626                         return false;
1627
1628                 path += a;
1629                 prefix += b;
1630         }
1631 }
1632
1633 bool path_equal(const char *a, const char *b) {
1634         assert(a);
1635         assert(b);
1636
1637         if ((a[0] == '/') != (b[0] == '/'))
1638                 return false;
1639
1640         for (;;) {
1641                 size_t j, k;
1642
1643                 a += strspn(a, "/");
1644                 b += strspn(b, "/");
1645
1646                 if (*a == 0 && *b == 0)
1647                         return true;
1648
1649                 if (*a == 0 || *b == 0)
1650                         return false;
1651
1652                 j = strcspn(a, "/");
1653                 k = strcspn(b, "/");
1654
1655                 if (j != k)
1656                         return false;
1657
1658                 if (memcmp(a, b, j) != 0)
1659                         return false;
1660
1661                 a += j;
1662                 b += k;
1663         }
1664 }
1665
1666 char *ascii_strlower(char *t) {
1667         char *p;
1668
1669         assert(t);
1670
1671         for (p = t; *p; p++)
1672                 if (*p >= 'A' && *p <= 'Z')
1673                         *p = *p - 'A' + 'a';
1674
1675         return t;
1676 }
1677
1678 bool ignore_file(const char *filename) {
1679         assert(filename);
1680
1681         return
1682                 filename[0] == '.' ||
1683                 streq(filename, "lost+found") ||
1684                 endswith(filename, "~") ||
1685                 endswith(filename, ".rpmnew") ||
1686                 endswith(filename, ".rpmsave") ||
1687                 endswith(filename, ".rpmorig") ||
1688                 endswith(filename, ".dpkg-old") ||
1689                 endswith(filename, ".dpkg-new") ||
1690                 endswith(filename, ".swp");
1691 }
1692
1693 int fd_nonblock(int fd, bool nonblock) {
1694         int flags;
1695
1696         assert(fd >= 0);
1697
1698         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1699                 return -errno;
1700
1701         if (nonblock)
1702                 flags |= O_NONBLOCK;
1703         else
1704                 flags &= ~O_NONBLOCK;
1705
1706         if (fcntl(fd, F_SETFL, flags) < 0)
1707                 return -errno;
1708
1709         return 0;
1710 }
1711
1712 int fd_cloexec(int fd, bool cloexec) {
1713         int flags;
1714
1715         assert(fd >= 0);
1716
1717         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1718                 return -errno;
1719
1720         if (cloexec)
1721                 flags |= FD_CLOEXEC;
1722         else
1723                 flags &= ~FD_CLOEXEC;
1724
1725         if (fcntl(fd, F_SETFD, flags) < 0)
1726                 return -errno;
1727
1728         return 0;
1729 }
1730
1731 int close_all_fds(const int except[], unsigned n_except) {
1732         DIR *d;
1733         struct dirent *de;
1734         int r = 0;
1735
1736         if (!(d = opendir("/proc/self/fd")))
1737                 return -errno;
1738
1739         while ((de = readdir(d))) {
1740                 int fd = -1;
1741
1742                 if (ignore_file(de->d_name))
1743                         continue;
1744
1745                 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1746                         goto finish;
1747
1748                 if (fd < 3)
1749                         continue;
1750
1751                 if (fd == dirfd(d))
1752                         continue;
1753
1754                 if (except) {
1755                         bool found;
1756                         unsigned i;
1757
1758                         found = false;
1759                         for (i = 0; i < n_except; i++)
1760                                 if (except[i] == fd) {
1761                                         found = true;
1762                                         break;
1763                                 }
1764
1765                         if (found)
1766                                 continue;
1767                 }
1768
1769                 if ((r = close_nointr(fd)) < 0) {
1770                         /* Valgrind has its own FD and doesn't want to have it closed */
1771                         if (errno != EBADF)
1772                                 goto finish;
1773                 }
1774         }
1775
1776         r = 0;
1777
1778 finish:
1779         closedir(d);
1780         return r;
1781 }
1782
1783 bool chars_intersect(const char *a, const char *b) {
1784         const char *p;
1785
1786         /* Returns true if any of the chars in a are in b. */
1787         for (p = a; *p; p++)
1788                 if (strchr(b, *p))
1789                         return true;
1790
1791         return false;
1792 }
1793
1794 char *format_timestamp(char *buf, size_t l, usec_t t) {
1795         struct tm tm;
1796         time_t sec;
1797
1798         assert(buf);
1799         assert(l > 0);
1800
1801         if (t <= 0)
1802                 return NULL;
1803
1804         sec = (time_t) (t / USEC_PER_SEC);
1805
1806         if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1807                 return NULL;
1808
1809         return buf;
1810 }
1811
1812 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1813         usec_t n, d;
1814
1815         n = now(CLOCK_REALTIME);
1816
1817         if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1818                 return NULL;
1819
1820         d = n - t;
1821
1822         if (d >= USEC_PER_YEAR)
1823                 snprintf(buf, l, "%llu years and %llu months ago",
1824                          (unsigned long long) (d / USEC_PER_YEAR),
1825                          (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1826         else if (d >= USEC_PER_MONTH)
1827                 snprintf(buf, l, "%llu months and %llu days ago",
1828                          (unsigned long long) (d / USEC_PER_MONTH),
1829                          (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1830         else if (d >= USEC_PER_WEEK)
1831                 snprintf(buf, l, "%llu weeks and %llu days ago",
1832                          (unsigned long long) (d / USEC_PER_WEEK),
1833                          (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1834         else if (d >= 2*USEC_PER_DAY)
1835                 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1836         else if (d >= 25*USEC_PER_HOUR)
1837                 snprintf(buf, l, "1 day and %lluh ago",
1838                          (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1839         else if (d >= 6*USEC_PER_HOUR)
1840                 snprintf(buf, l, "%lluh ago",
1841                          (unsigned long long) (d / USEC_PER_HOUR));
1842         else if (d >= USEC_PER_HOUR)
1843                 snprintf(buf, l, "%lluh %llumin ago",
1844                          (unsigned long long) (d / USEC_PER_HOUR),
1845                          (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1846         else if (d >= 5*USEC_PER_MINUTE)
1847                 snprintf(buf, l, "%llumin ago",
1848                          (unsigned long long) (d / USEC_PER_MINUTE));
1849         else if (d >= USEC_PER_MINUTE)
1850                 snprintf(buf, l, "%llumin %llus ago",
1851                          (unsigned long long) (d / USEC_PER_MINUTE),
1852                          (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1853         else if (d >= USEC_PER_SEC)
1854                 snprintf(buf, l, "%llus ago",
1855                          (unsigned long long) (d / USEC_PER_SEC));
1856         else if (d >= USEC_PER_MSEC)
1857                 snprintf(buf, l, "%llums ago",
1858                          (unsigned long long) (d / USEC_PER_MSEC));
1859         else if (d > 0)
1860                 snprintf(buf, l, "%lluus ago",
1861                          (unsigned long long) d);
1862         else
1863                 snprintf(buf, l, "now");
1864
1865         buf[l-1] = 0;
1866         return buf;
1867 }
1868
1869 char *format_timespan(char *buf, size_t l, usec_t t) {
1870         static const struct {
1871                 const char *suffix;
1872                 usec_t usec;
1873         } table[] = {
1874                 { "w", USEC_PER_WEEK },
1875                 { "d", USEC_PER_DAY },
1876                 { "h", USEC_PER_HOUR },
1877                 { "min", USEC_PER_MINUTE },
1878                 { "s", USEC_PER_SEC },
1879                 { "ms", USEC_PER_MSEC },
1880                 { "us", 1 },
1881         };
1882
1883         unsigned i;
1884         char *p = buf;
1885
1886         assert(buf);
1887         assert(l > 0);
1888
1889         if (t == (usec_t) -1)
1890                 return NULL;
1891
1892         if (t == 0) {
1893                 snprintf(p, l, "0");
1894                 p[l-1] = 0;
1895                 return p;
1896         }
1897
1898         /* The result of this function can be parsed with parse_usec */
1899
1900         for (i = 0; i < ELEMENTSOF(table); i++) {
1901                 int k;
1902                 size_t n;
1903
1904                 if (t < table[i].usec)
1905                         continue;
1906
1907                 if (l <= 1)
1908                         break;
1909
1910                 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1911                 n = MIN((size_t) k, l);
1912
1913                 l -= n;
1914                 p += n;
1915
1916                 t %= table[i].usec;
1917         }
1918
1919         *p = 0;
1920
1921         return buf;
1922 }
1923
1924 bool fstype_is_network(const char *fstype) {
1925         static const char * const table[] = {
1926                 "cifs",
1927                 "smbfs",
1928                 "ncpfs",
1929                 "nfs",
1930                 "nfs4",
1931                 "gfs",
1932                 "gfs2"
1933         };
1934
1935         unsigned i;
1936
1937         for (i = 0; i < ELEMENTSOF(table); i++)
1938                 if (streq(table[i], fstype))
1939                         return true;
1940
1941         return false;
1942 }
1943
1944 int chvt(int vt) {
1945         int fd, r = 0;
1946
1947         if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1948                 return -errno;
1949
1950         if (vt < 0) {
1951                 int tiocl[2] = {
1952                         TIOCL_GETKMSGREDIRECT,
1953                         0
1954                 };
1955
1956                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1957                         return -errno;
1958
1959                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1960         }
1961
1962         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1963                 r = -errno;
1964
1965         close_nointr_nofail(r);
1966         return r;
1967 }
1968
1969 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1970         struct termios old_termios, new_termios;
1971         char c;
1972         char line[1024];
1973
1974         assert(f);
1975         assert(ret);
1976
1977         if (tcgetattr(fileno(f), &old_termios) >= 0) {
1978                 new_termios = old_termios;
1979
1980                 new_termios.c_lflag &= ~ICANON;
1981                 new_termios.c_cc[VMIN] = 1;
1982                 new_termios.c_cc[VTIME] = 0;
1983
1984                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1985                         size_t k;
1986
1987                         k = fread(&c, 1, 1, f);
1988
1989                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1990
1991                         if (k <= 0)
1992                                 return -EIO;
1993
1994                         if (need_nl)
1995                                 *need_nl = c != '\n';
1996
1997                         *ret = c;
1998                         return 0;
1999                 }
2000         }
2001
2002         if (!(fgets(line, sizeof(line), f)))
2003                 return -EIO;
2004
2005         truncate_nl(line);
2006
2007         if (strlen(line) != 1)
2008                 return -EBADMSG;
2009
2010         if (need_nl)
2011                 *need_nl = false;
2012
2013         *ret = line[0];
2014         return 0;
2015 }
2016
2017 int ask(char *ret, const char *replies, const char *text, ...) {
2018         bool on_tty;
2019
2020         assert(ret);
2021         assert(replies);
2022         assert(text);
2023
2024         on_tty = isatty(STDOUT_FILENO);
2025
2026         for (;;) {
2027                 va_list ap;
2028                 char c;
2029                 int r;
2030                 bool need_nl = true;
2031
2032                 if (on_tty)
2033                         fputs("\x1B[1m", stdout);
2034
2035                 va_start(ap, text);
2036                 vprintf(text, ap);
2037                 va_end(ap);
2038
2039                 if (on_tty)
2040                         fputs("\x1B[0m", stdout);
2041
2042                 fflush(stdout);
2043
2044                 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2045
2046                         if (r == -EBADMSG) {
2047                                 puts("Bad input, please try again.");
2048                                 continue;
2049                         }
2050
2051                         putchar('\n');
2052                         return r;
2053                 }
2054
2055                 if (need_nl)
2056                         putchar('\n');
2057
2058                 if (strchr(replies, c)) {
2059                         *ret = c;
2060                         return 0;
2061                 }
2062
2063                 puts("Read unexpected character, please try again.");
2064         }
2065 }
2066
2067 int reset_terminal(int fd) {
2068         struct termios termios;
2069         int r = 0;
2070         long arg;
2071
2072         /* Set terminal to some sane defaults */
2073
2074         assert(fd >= 0);
2075
2076         /* We leave locked terminal attributes untouched, so that
2077          * Plymouth may set whatever it wants to set, and we don't
2078          * interfere with that. */
2079
2080         /* Disable exclusive mode, just in case */
2081         ioctl(fd, TIOCNXCL);
2082
2083         /* Enable console unicode mode */
2084         arg = K_UNICODE;
2085         ioctl(fd, KDSKBMODE, &arg);
2086
2087         if (tcgetattr(fd, &termios) < 0) {
2088                 r = -errno;
2089                 goto finish;
2090         }
2091
2092         /* We only reset the stuff that matters to the software. How
2093          * hardware is set up we don't touch assuming that somebody
2094          * else will do that for us */
2095
2096         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2097         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2098         termios.c_oflag |= ONLCR;
2099         termios.c_cflag |= CREAD;
2100         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2101
2102         termios.c_cc[VINTR]    =   03;  /* ^C */
2103         termios.c_cc[VQUIT]    =  034;  /* ^\ */
2104         termios.c_cc[VERASE]   = 0177;
2105         termios.c_cc[VKILL]    =  025;  /* ^X */
2106         termios.c_cc[VEOF]     =   04;  /* ^D */
2107         termios.c_cc[VSTART]   =  021;  /* ^Q */
2108         termios.c_cc[VSTOP]    =  023;  /* ^S */
2109         termios.c_cc[VSUSP]    =  032;  /* ^Z */
2110         termios.c_cc[VLNEXT]   =  026;  /* ^V */
2111         termios.c_cc[VWERASE]  =  027;  /* ^W */
2112         termios.c_cc[VREPRINT] =  022;  /* ^R */
2113         termios.c_cc[VEOL]     =    0;
2114         termios.c_cc[VEOL2]    =    0;
2115
2116         termios.c_cc[VTIME]  = 0;
2117         termios.c_cc[VMIN]   = 1;
2118
2119         if (tcsetattr(fd, TCSANOW, &termios) < 0)
2120                 r = -errno;
2121
2122 finish:
2123         /* Just in case, flush all crap out */
2124         tcflush(fd, TCIOFLUSH);
2125
2126         return r;
2127 }
2128
2129 int open_terminal(const char *name, int mode) {
2130         int fd, r;
2131
2132         if ((fd = open(name, mode)) < 0)
2133                 return -errno;
2134
2135         if ((r = isatty(fd)) < 0) {
2136                 close_nointr_nofail(fd);
2137                 return -errno;
2138         }
2139
2140         if (!r) {
2141                 close_nointr_nofail(fd);
2142                 return -ENOTTY;
2143         }
2144
2145         return fd;
2146 }
2147
2148 int flush_fd(int fd) {
2149         struct pollfd pollfd;
2150
2151         zero(pollfd);
2152         pollfd.fd = fd;
2153         pollfd.events = POLLIN;
2154
2155         for (;;) {
2156                 char buf[1024];
2157                 ssize_t l;
2158                 int r;
2159
2160                 if ((r = poll(&pollfd, 1, 0)) < 0) {
2161
2162                         if (errno == EINTR)
2163                                 continue;
2164
2165                         return -errno;
2166                 }
2167
2168                 if (r == 0)
2169                         return 0;
2170
2171                 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2172
2173                         if (errno == EINTR)
2174                                 continue;
2175
2176                         if (errno == EAGAIN)
2177                                 return 0;
2178
2179                         return -errno;
2180                 }
2181
2182                 if (l <= 0)
2183                         return 0;
2184         }
2185 }
2186
2187 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2188         int fd = -1, notify = -1, r, wd = -1;
2189
2190         assert(name);
2191
2192         /* We use inotify to be notified when the tty is closed. We
2193          * create the watch before checking if we can actually acquire
2194          * it, so that we don't lose any event.
2195          *
2196          * Note: strictly speaking this actually watches for the
2197          * device being closed, it does *not* really watch whether a
2198          * tty loses its controlling process. However, unless some
2199          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2200          * its tty otherwise this will not become a problem. As long
2201          * as the administrator makes sure not configure any service
2202          * on the same tty as an untrusted user this should not be a
2203          * problem. (Which he probably should not do anyway.) */
2204
2205         if (!fail && !force) {
2206                 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2207                         r = -errno;
2208                         goto fail;
2209                 }
2210
2211                 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2212                         r = -errno;
2213                         goto fail;
2214                 }
2215         }
2216
2217         for (;;) {
2218                 if (notify >= 0)
2219                         if ((r = flush_fd(notify)) < 0)
2220                                 goto fail;
2221
2222                 /* We pass here O_NOCTTY only so that we can check the return
2223                  * value TIOCSCTTY and have a reliable way to figure out if we
2224                  * successfully became the controlling process of the tty */
2225                 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2226                         return -errno;
2227
2228                 /* First, try to get the tty */
2229                 r = ioctl(fd, TIOCSCTTY, force);
2230
2231                 /* Sometimes it makes sense to ignore TIOCSCTTY
2232                  * returning EPERM, i.e. when very likely we already
2233                  * are have this controlling terminal. */
2234                 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2235                         r = 0;
2236
2237                 if (r < 0 && (force || fail || errno != EPERM)) {
2238                         r = -errno;
2239                         goto fail;
2240                 }
2241
2242                 if (r >= 0)
2243                         break;
2244
2245                 assert(!fail);
2246                 assert(!force);
2247                 assert(notify >= 0);
2248
2249                 for (;;) {
2250                         uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2251                         ssize_t l;
2252                         struct inotify_event *e;
2253
2254                         if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2255
2256                                 if (errno == EINTR)
2257                                         continue;
2258
2259                                 r = -errno;
2260                                 goto fail;
2261                         }
2262
2263                         e = (struct inotify_event*) inotify_buffer;
2264
2265                         while (l > 0) {
2266                                 size_t step;
2267
2268                                 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2269                                         r = -EIO;
2270                                         goto fail;
2271                                 }
2272
2273                                 step = sizeof(struct inotify_event) + e->len;
2274                                 assert(step <= (size_t) l);
2275
2276                                 e = (struct inotify_event*) ((uint8_t*) e + step);
2277                                 l -= step;
2278                         }
2279
2280                         break;
2281                 }
2282
2283                 /* We close the tty fd here since if the old session
2284                  * ended our handle will be dead. It's important that
2285                  * we do this after sleeping, so that we don't enter
2286                  * an endless loop. */
2287                 close_nointr_nofail(fd);
2288         }
2289
2290         if (notify >= 0)
2291                 close_nointr_nofail(notify);
2292
2293         if ((r = reset_terminal(fd)) < 0)
2294                 log_warning("Failed to reset terminal: %s", strerror(-r));
2295
2296         return fd;
2297
2298 fail:
2299         if (fd >= 0)
2300                 close_nointr_nofail(fd);
2301
2302         if (notify >= 0)
2303                 close_nointr_nofail(notify);
2304
2305         return r;
2306 }
2307
2308 int release_terminal(void) {
2309         int r = 0, fd;
2310         struct sigaction sa_old, sa_new;
2311
2312         if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2313                 return -errno;
2314
2315         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2316          * by our own TIOCNOTTY */
2317
2318         zero(sa_new);
2319         sa_new.sa_handler = SIG_IGN;
2320         sa_new.sa_flags = SA_RESTART;
2321         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2322
2323         if (ioctl(fd, TIOCNOTTY) < 0)
2324                 r = -errno;
2325
2326         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2327
2328         close_nointr_nofail(fd);
2329         return r;
2330 }
2331
2332 int sigaction_many(const struct sigaction *sa, ...) {
2333         va_list ap;
2334         int r = 0, sig;
2335
2336         va_start(ap, sa);
2337         while ((sig = va_arg(ap, int)) > 0)
2338                 if (sigaction(sig, sa, NULL) < 0)
2339                         r = -errno;
2340         va_end(ap);
2341
2342         return r;
2343 }
2344
2345 int ignore_signals(int sig, ...) {
2346         struct sigaction sa;
2347         va_list ap;
2348         int r = 0;
2349
2350         zero(sa);
2351         sa.sa_handler = SIG_IGN;
2352         sa.sa_flags = SA_RESTART;
2353
2354         if (sigaction(sig, &sa, NULL) < 0)
2355                 r = -errno;
2356
2357         va_start(ap, sig);
2358         while ((sig = va_arg(ap, int)) > 0)
2359                 if (sigaction(sig, &sa, NULL) < 0)
2360                         r = -errno;
2361         va_end(ap);
2362
2363         return r;
2364 }
2365
2366 int default_signals(int sig, ...) {
2367         struct sigaction sa;
2368         va_list ap;
2369         int r = 0;
2370
2371         zero(sa);
2372         sa.sa_handler = SIG_DFL;
2373         sa.sa_flags = SA_RESTART;
2374
2375         if (sigaction(sig, &sa, NULL) < 0)
2376                 r = -errno;
2377
2378         va_start(ap, sig);
2379         while ((sig = va_arg(ap, int)) > 0)
2380                 if (sigaction(sig, &sa, NULL) < 0)
2381                         r = -errno;
2382         va_end(ap);
2383
2384         return r;
2385 }
2386
2387 int close_pipe(int p[]) {
2388         int a = 0, b = 0;
2389
2390         assert(p);
2391
2392         if (p[0] >= 0) {
2393                 a = close_nointr(p[0]);
2394                 p[0] = -1;
2395         }
2396
2397         if (p[1] >= 0) {
2398                 b = close_nointr(p[1]);
2399                 p[1] = -1;
2400         }
2401
2402         return a < 0 ? a : b;
2403 }
2404
2405 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2406         uint8_t *p;
2407         ssize_t n = 0;
2408
2409         assert(fd >= 0);
2410         assert(buf);
2411
2412         p = buf;
2413
2414         while (nbytes > 0) {
2415                 ssize_t k;
2416
2417                 if ((k = read(fd, p, nbytes)) <= 0) {
2418
2419                         if (k < 0 && errno == EINTR)
2420                                 continue;
2421
2422                         if (k < 0 && errno == EAGAIN && do_poll) {
2423                                 struct pollfd pollfd;
2424
2425                                 zero(pollfd);
2426                                 pollfd.fd = fd;
2427                                 pollfd.events = POLLIN;
2428
2429                                 if (poll(&pollfd, 1, -1) < 0) {
2430                                         if (errno == EINTR)
2431                                                 continue;
2432
2433                                         return n > 0 ? n : -errno;
2434                                 }
2435
2436                                 if (pollfd.revents != POLLIN)
2437                                         return n > 0 ? n : -EIO;
2438
2439                                 continue;
2440                         }
2441
2442                         return n > 0 ? n : (k < 0 ? -errno : 0);
2443                 }
2444
2445                 p += k;
2446                 nbytes -= k;
2447                 n += k;
2448         }
2449
2450         return n;
2451 }
2452
2453 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2454         const uint8_t *p;
2455         ssize_t n = 0;
2456
2457         assert(fd >= 0);
2458         assert(buf);
2459
2460         p = buf;
2461
2462         while (nbytes > 0) {
2463                 ssize_t k;
2464
2465                 if ((k = write(fd, p, nbytes)) <= 0) {
2466
2467                         if (k < 0 && errno == EINTR)
2468                                 continue;
2469
2470                         if (k < 0 && errno == EAGAIN && do_poll) {
2471                                 struct pollfd pollfd;
2472
2473                                 zero(pollfd);
2474                                 pollfd.fd = fd;
2475                                 pollfd.events = POLLOUT;
2476
2477                                 if (poll(&pollfd, 1, -1) < 0) {
2478                                         if (errno == EINTR)
2479                                                 continue;
2480
2481                                         return n > 0 ? n : -errno;
2482                                 }
2483
2484                                 if (pollfd.revents != POLLOUT)
2485                                         return n > 0 ? n : -EIO;
2486
2487                                 continue;
2488                         }
2489
2490                         return n > 0 ? n : (k < 0 ? -errno : 0);
2491                 }
2492
2493                 p += k;
2494                 nbytes -= k;
2495                 n += k;
2496         }
2497
2498         return n;
2499 }
2500
2501 int path_is_mount_point(const char *t) {
2502         struct stat a, b;
2503         char *parent;
2504         int r;
2505
2506         if (lstat(t, &a) < 0) {
2507                 if (errno == ENOENT)
2508                         return 0;
2509
2510                 return -errno;
2511         }
2512
2513         if ((r = parent_of_path(t, &parent)) < 0)
2514                 return r;
2515
2516         r = lstat(parent, &b);
2517         free(parent);
2518
2519         if (r < 0)
2520                 return -errno;
2521
2522         return a.st_dev != b.st_dev;
2523 }
2524
2525 int parse_usec(const char *t, usec_t *usec) {
2526         static const struct {
2527                 const char *suffix;
2528                 usec_t usec;
2529         } table[] = {
2530                 { "sec", USEC_PER_SEC },
2531                 { "s", USEC_PER_SEC },
2532                 { "min", USEC_PER_MINUTE },
2533                 { "hr", USEC_PER_HOUR },
2534                 { "h", USEC_PER_HOUR },
2535                 { "d", USEC_PER_DAY },
2536                 { "w", USEC_PER_WEEK },
2537                 { "msec", USEC_PER_MSEC },
2538                 { "ms", USEC_PER_MSEC },
2539                 { "m", USEC_PER_MINUTE },
2540                 { "usec", 1ULL },
2541                 { "us", 1ULL },
2542                 { "", USEC_PER_SEC },
2543         };
2544
2545         const char *p;
2546         usec_t r = 0;
2547
2548         assert(t);
2549         assert(usec);
2550
2551         p = t;
2552         do {
2553                 long long l;
2554                 char *e;
2555                 unsigned i;
2556
2557                 errno = 0;
2558                 l = strtoll(p, &e, 10);
2559
2560                 if (errno != 0)
2561                         return -errno;
2562
2563                 if (l < 0)
2564                         return -ERANGE;
2565
2566                 if (e == p)
2567                         return -EINVAL;
2568
2569                 e += strspn(e, WHITESPACE);
2570
2571                 for (i = 0; i < ELEMENTSOF(table); i++)
2572                         if (startswith(e, table[i].suffix)) {
2573                                 r += (usec_t) l * table[i].usec;
2574                                 p = e + strlen(table[i].suffix);
2575                                 break;
2576                         }
2577
2578                 if (i >= ELEMENTSOF(table))
2579                         return -EINVAL;
2580
2581         } while (*p != 0);
2582
2583         *usec = r;
2584
2585         return 0;
2586 }
2587
2588 int make_stdio(int fd) {
2589         int r, s, t;
2590
2591         assert(fd >= 0);
2592
2593         r = dup2(fd, STDIN_FILENO);
2594         s = dup2(fd, STDOUT_FILENO);
2595         t = dup2(fd, STDERR_FILENO);
2596
2597         if (fd >= 3)
2598                 close_nointr_nofail(fd);
2599
2600         if (r < 0 || s < 0 || t < 0)
2601                 return -errno;
2602
2603         return 0;
2604 }
2605
2606 bool is_clean_exit(int code, int status) {
2607
2608         if (code == CLD_EXITED)
2609                 return status == 0;
2610
2611         /* If a daemon does not implement handlers for some of the
2612          * signals that's not considered an unclean shutdown */
2613         if (code == CLD_KILLED)
2614                 return
2615                         status == SIGHUP ||
2616                         status == SIGINT ||
2617                         status == SIGTERM ||
2618                         status == SIGPIPE;
2619
2620         return false;
2621 }
2622
2623 bool is_clean_exit_lsb(int code, int status) {
2624
2625         if (is_clean_exit(code, status))
2626                 return true;
2627
2628         return
2629                 code == CLD_EXITED &&
2630                 (status == EXIT_NOTINSTALLED || status == EXIT_NOTCONFIGURED);
2631 }
2632
2633 bool is_device_path(const char *path) {
2634
2635         /* Returns true on paths that refer to a device, either in
2636          * sysfs or in /dev */
2637
2638         return
2639                 path_startswith(path, "/dev/") ||
2640                 path_startswith(path, "/sys/");
2641 }
2642
2643 int dir_is_empty(const char *path) {
2644         DIR *d;
2645         int r;
2646         struct dirent buf, *de;
2647
2648         if (!(d = opendir(path)))
2649                 return -errno;
2650
2651         for (;;) {
2652                 if ((r = readdir_r(d, &buf, &de)) > 0) {
2653                         r = -r;
2654                         break;
2655                 }
2656
2657                 if (!de) {
2658                         r = 1;
2659                         break;
2660                 }
2661
2662                 if (!ignore_file(de->d_name)) {
2663                         r = 0;
2664                         break;
2665                 }
2666         }
2667
2668         closedir(d);
2669         return r;
2670 }
2671
2672 unsigned long long random_ull(void) {
2673         int fd;
2674         uint64_t ull;
2675         ssize_t r;
2676
2677         if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2678                 goto fallback;
2679
2680         r = loop_read(fd, &ull, sizeof(ull), true);
2681         close_nointr_nofail(fd);
2682
2683         if (r != sizeof(ull))
2684                 goto fallback;
2685
2686         return ull;
2687
2688 fallback:
2689         return random() * RAND_MAX + random();
2690 }
2691
2692 void rename_process(const char name[8]) {
2693         assert(name);
2694
2695         prctl(PR_SET_NAME, name);
2696
2697         /* This is a like a poor man's setproctitle(). The string
2698          * passed should fit in 7 chars (i.e. the length of
2699          * "systemd") */
2700
2701         if (program_invocation_name)
2702                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2703 }
2704
2705 void sigset_add_many(sigset_t *ss, ...) {
2706         va_list ap;
2707         int sig;
2708
2709         assert(ss);
2710
2711         va_start(ap, ss);
2712         while ((sig = va_arg(ap, int)) > 0)
2713                 assert_se(sigaddset(ss, sig) == 0);
2714         va_end(ap);
2715 }
2716
2717 char* gethostname_malloc(void) {
2718         struct utsname u;
2719
2720         assert_se(uname(&u) >= 0);
2721
2722         if (u.nodename[0])
2723                 return strdup(u.nodename);
2724
2725         return strdup(u.sysname);
2726 }
2727
2728 char* getlogname_malloc(void) {
2729         uid_t uid;
2730         long bufsize;
2731         char *buf, *name;
2732         struct passwd pwbuf, *pw = NULL;
2733         struct stat st;
2734
2735         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2736                 uid = st.st_uid;
2737         else
2738                 uid = getuid();
2739
2740         /* Shortcut things to avoid NSS lookups */
2741         if (uid == 0)
2742                 return strdup("root");
2743
2744         if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2745                 bufsize = 4096;
2746
2747         if (!(buf = malloc(bufsize)))
2748                 return NULL;
2749
2750         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2751                 name = strdup(pw->pw_name);
2752                 free(buf);
2753                 return name;
2754         }
2755
2756         free(buf);
2757
2758         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2759                 return NULL;
2760
2761         return name;
2762 }
2763
2764 int getttyname_malloc(char **r) {
2765         char path[PATH_MAX], *p, *c;
2766         int k;
2767
2768         assert(r);
2769
2770         if ((k = ttyname_r(STDIN_FILENO, path, sizeof(path))) != 0)
2771                 return -k;
2772
2773         char_array_0(path);
2774
2775         p = path;
2776         if (startswith(path, "/dev/"))
2777                 p += 5;
2778
2779         if (!(c = strdup(p)))
2780                 return -ENOMEM;
2781
2782         *r = c;
2783         return 0;
2784 }
2785
2786 static int rm_rf_children(int fd, bool only_dirs) {
2787         DIR *d;
2788         int ret = 0;
2789
2790         assert(fd >= 0);
2791
2792         /* This returns the first error we run into, but nevertheless
2793          * tries to go on */
2794
2795         if (!(d = fdopendir(fd))) {
2796                 close_nointr_nofail(fd);
2797
2798                 return errno == ENOENT ? 0 : -errno;
2799         }
2800
2801         for (;;) {
2802                 struct dirent buf, *de;
2803                 bool is_dir;
2804                 int r;
2805
2806                 if ((r = readdir_r(d, &buf, &de)) != 0) {
2807                         if (ret == 0)
2808                                 ret = -r;
2809                         break;
2810                 }
2811
2812                 if (!de)
2813                         break;
2814
2815                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2816                         continue;
2817
2818                 if (de->d_type == DT_UNKNOWN) {
2819                         struct stat st;
2820
2821                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2822                                 if (ret == 0 && errno != ENOENT)
2823                                         ret = -errno;
2824                                 continue;
2825                         }
2826
2827                         is_dir = S_ISDIR(st.st_mode);
2828                 } else
2829                         is_dir = de->d_type == DT_DIR;
2830
2831                 if (is_dir) {
2832                         int subdir_fd;
2833
2834                         if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2835                                 if (ret == 0 && errno != ENOENT)
2836                                         ret = -errno;
2837                                 continue;
2838                         }
2839
2840                         if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2841                                 if (ret == 0)
2842                                         ret = r;
2843                         }
2844
2845                         if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2846                                 if (ret == 0 && errno != ENOENT)
2847                                         ret = -errno;
2848                         }
2849                 } else  if (!only_dirs) {
2850
2851                         if (unlinkat(fd, de->d_name, 0) < 0) {
2852                                 if (ret == 0 && errno != ENOENT)
2853                                         ret = -errno;
2854                         }
2855                 }
2856         }
2857
2858         closedir(d);
2859
2860         return ret;
2861 }
2862
2863 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2864         int fd;
2865         int r;
2866
2867         assert(path);
2868
2869         if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2870
2871                 if (errno != ENOTDIR)
2872                         return -errno;
2873
2874                 if (delete_root && !only_dirs)
2875                         if (unlink(path) < 0)
2876                                 return -errno;
2877
2878                 return 0;
2879         }
2880
2881         r = rm_rf_children(fd, only_dirs);
2882
2883         if (delete_root)
2884                 if (rmdir(path) < 0) {
2885                         if (r == 0)
2886                                 r = -errno;
2887                 }
2888
2889         return r;
2890 }
2891
2892 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2893         assert(path);
2894
2895         /* Under the assumption that we are running privileged we
2896          * first change the access mode and only then hand out
2897          * ownership to avoid a window where access is too open. */
2898
2899         if (chmod(path, mode) < 0)
2900                 return -errno;
2901
2902         if (chown(path, uid, gid) < 0)
2903                 return -errno;
2904
2905         return 0;
2906 }
2907
2908 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2909         cpu_set_t *r;
2910         unsigned n = 1024;
2911
2912         /* Allocates the cpuset in the right size */
2913
2914         for (;;) {
2915                 if (!(r = CPU_ALLOC(n)))
2916                         return NULL;
2917
2918                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2919                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2920
2921                         if (ncpus)
2922                                 *ncpus = n;
2923
2924                         return r;
2925                 }
2926
2927                 CPU_FREE(r);
2928
2929                 if (errno != EINVAL)
2930                         return NULL;
2931
2932                 n *= 2;
2933         }
2934 }
2935
2936 void status_vprintf(const char *format, va_list ap) {
2937         char *s = NULL;
2938         int fd = -1;
2939
2940         assert(format);
2941
2942         /* This independent of logging, as status messages are
2943          * optional and go exclusively to the console. */
2944
2945         if (vasprintf(&s, format, ap) < 0)
2946                 goto finish;
2947
2948         if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2949                 goto finish;
2950
2951         write(fd, s, strlen(s));
2952
2953 finish:
2954         free(s);
2955
2956         if (fd >= 0)
2957                 close_nointr_nofail(fd);
2958 }
2959
2960 void status_printf(const char *format, ...) {
2961         va_list ap;
2962
2963         assert(format);
2964
2965         va_start(ap, format);
2966         status_vprintf(format, ap);
2967         va_end(ap);
2968 }
2969
2970 void status_welcome(void) {
2971
2972 #if defined(TARGET_FEDORA)
2973         char *r;
2974
2975         if (read_one_line_file("/etc/system-release", &r) < 0)
2976                 return;
2977
2978         truncate_nl(r);
2979
2980         /* This tries to mimic the color magic the old Red Hat sysinit
2981          * script did. */
2982
2983         if (startswith(r, "Red Hat"))
2984                 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r); /* Red for RHEL */
2985         else if (startswith(r, "Fedora"))
2986                 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r); /* Blue for Fedora */
2987         else
2988                 status_printf("Welcome to %s!\n", r);
2989
2990         free(r);
2991
2992 #elif defined(TARGET_SUSE)
2993         char *r;
2994
2995         if (read_one_line_file("/etc/SuSE-release", &r) < 0)
2996                 return;
2997
2998         truncate_nl(r);
2999
3000         status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r); /* Green for SUSE */
3001         free(r);
3002
3003 #elif defined(TARGET_GENTOO)
3004         char *r;
3005
3006         if (read_one_line_file("/etc/gentoo-release", &r) < 0)
3007                 return;
3008
3009         truncate_nl(r);
3010
3011         status_printf("Welcome to \x1B[1;34m%s\x1B[0m!\n", r); /* Light Blue for Gentoo */
3012
3013         free(r);
3014
3015 #elif defined(TARGET_DEBIAN)
3016         char *r;
3017
3018         if (read_one_line_file("/etc/debian_version", &r) < 0)
3019                 return;
3020
3021         truncate_nl(r);
3022
3023         status_printf("Welcome to Debian \x1B[1;31m%s\x1B[0m!\n", r); /* Light Red for Debian */
3024
3025         free(r);
3026 #elif defined(TARGET_ARCH)
3027         status_printf("Welcome to \x1B[1;36mArch Linux\x1B[0m!\n"); /* Cyan for Arch */
3028 #else
3029 #warning "You probably should add a welcome text logic here."
3030 #endif
3031 }
3032
3033 char *replace_env(const char *format, char **env) {
3034         enum {
3035                 WORD,
3036                 CURLY,
3037                 VARIABLE
3038         } state = WORD;
3039
3040         const char *e, *word = format;
3041         char *r = NULL, *k;
3042
3043         assert(format);
3044
3045         for (e = format; *e; e ++) {
3046
3047                 switch (state) {
3048
3049                 case WORD:
3050                         if (*e == '$')
3051                                 state = CURLY;
3052                         break;
3053
3054                 case CURLY:
3055                         if (*e == '{') {
3056                                 if (!(k = strnappend(r, word, e-word-1)))
3057                                         goto fail;
3058
3059                                 free(r);
3060                                 r = k;
3061
3062                                 word = e-1;
3063                                 state = VARIABLE;
3064
3065                         } else if (*e == '$') {
3066                                 if (!(k = strnappend(r, word, e-word)))
3067                                         goto fail;
3068
3069                                 free(r);
3070                                 r = k;
3071
3072                                 word = e+1;
3073                                 state = WORD;
3074                         } else
3075                                 state = WORD;
3076                         break;
3077
3078                 case VARIABLE:
3079                         if (*e == '}') {
3080                                 const char *t;
3081
3082                                 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3083                                         t = "";
3084
3085                                 if (!(k = strappend(r, t)))
3086                                         goto fail;
3087
3088                                 free(r);
3089                                 r = k;
3090
3091                                 word = e+1;
3092                                 state = WORD;
3093                         }
3094                         break;
3095                 }
3096         }
3097
3098         if (!(k = strnappend(r, word, e-word)))
3099                 goto fail;
3100
3101         free(r);
3102         return k;
3103
3104 fail:
3105         free(r);
3106         return NULL;
3107 }
3108
3109 char **replace_env_argv(char **argv, char **env) {
3110         char **r, **i;
3111         unsigned k = 0, l = 0;
3112
3113         l = strv_length(argv);
3114
3115         if (!(r = new(char*, l+1)))
3116                 return NULL;
3117
3118         STRV_FOREACH(i, argv) {
3119
3120                 /* If $FOO appears as single word, replace it by the split up variable */
3121                 if ((*i)[0] == '$' && (*i)[1] != '{') {
3122                         char *e;
3123                         char **w, **m;
3124                         unsigned q;
3125
3126                         if ((e = strv_env_get(env, *i+1))) {
3127
3128                                 if (!(m = strv_split_quoted(e))) {
3129                                         r[k] = NULL;
3130                                         strv_free(r);
3131                                         return NULL;
3132                                 }
3133                         } else
3134                                 m = NULL;
3135
3136                         q = strv_length(m);
3137                         l = l + q - 1;
3138
3139                         if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3140                                 r[k] = NULL;
3141                                 strv_free(r);
3142                                 strv_free(m);
3143                                 return NULL;
3144                         }
3145
3146                         r = w;
3147                         if (m) {
3148                                 memcpy(r + k, m, q * sizeof(char*));
3149                                 free(m);
3150                         }
3151
3152                         k += q;
3153                         continue;
3154                 }
3155
3156                 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3157                 if (!(r[k++] = replace_env(*i, env))) {
3158                         strv_free(r);
3159                         return NULL;
3160                 }
3161         }
3162
3163         r[k] = NULL;
3164         return r;
3165 }
3166
3167 int columns(void) {
3168         static __thread int parsed_columns = 0;
3169         const char *e;
3170
3171         if (parsed_columns > 0)
3172                 return parsed_columns;
3173
3174         if ((e = getenv("COLUMNS")))
3175                 parsed_columns = atoi(e);
3176
3177         if (parsed_columns <= 0) {
3178                 struct winsize ws;
3179                 zero(ws);
3180
3181                 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3182                         parsed_columns = ws.ws_col;
3183         }
3184
3185         if (parsed_columns <= 0)
3186                 parsed_columns = 80;
3187
3188         return parsed_columns;
3189 }
3190
3191 int running_in_chroot(void) {
3192         struct stat a, b;
3193
3194         zero(a);
3195         zero(b);
3196
3197         /* Only works as root */
3198
3199         if (stat("/proc/1/root", &a) < 0)
3200                 return -errno;
3201
3202         if (stat("/", &b) < 0)
3203                 return -errno;
3204
3205         return
3206                 a.st_dev != b.st_dev ||
3207                 a.st_ino != b.st_ino;
3208 }
3209
3210 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3211         size_t l, x;
3212         char *r;
3213
3214         assert(s);
3215         assert(percent <= 100);
3216         assert(length >= 3);
3217
3218         l = strlen(s);
3219
3220         if (l <= 3 || l <= length)
3221                 return strdup(s);
3222
3223         if (!(r = new0(char, length+1)))
3224                 return r;
3225
3226         x = (length * percent) / 100;
3227
3228         if (x > length - 3)
3229                 x = length - 3;
3230
3231         memcpy(r, s, x);
3232         r[x] = '.';
3233         r[x+1] = '.';
3234         r[x+2] = '.';
3235         memcpy(r + x + 3,
3236                s + l - (length - x - 3),
3237                length - x - 3);
3238
3239         return r;
3240 }
3241
3242 int touch(const char *path) {
3243         int fd;
3244
3245         assert(path);
3246
3247         if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0666)) < 0)
3248                 return -errno;
3249
3250         close_nointr_nofail(fd);
3251         return 0;
3252 }
3253
3254 char *unquote(const char *s, const char* quotes) {
3255         size_t l;
3256         assert(s);
3257
3258         if ((l = strlen(s)) < 2)
3259                 return strdup(s);
3260
3261         if (strchr(quotes, s[0]) && s[l-1] == s[0])
3262                 return strndup(s+1, l-2);
3263
3264         return strdup(s);
3265 }
3266
3267 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3268         assert(pid >= 1);
3269         assert(status);
3270
3271         for (;;) {
3272                 zero(*status);
3273
3274                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3275
3276                         if (errno == EINTR)
3277                                 continue;
3278
3279                         return -errno;
3280                 }
3281
3282                 return 0;
3283         }
3284 }
3285
3286 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3287         int r;
3288         siginfo_t status;
3289
3290         assert(name);
3291         assert(pid > 1);
3292
3293         if ((r = wait_for_terminate(pid, &status)) < 0) {
3294                 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3295                 return r;
3296         }
3297
3298         if (status.si_code == CLD_EXITED) {
3299                 if (status.si_status != 0) {
3300                         log_warning("%s failed with error code %i.", name, status.si_status);
3301                         return -EPROTO;
3302                 }
3303
3304                 log_debug("%s succeeded.", name);
3305                 return 0;
3306
3307         } else if (status.si_code == CLD_KILLED ||
3308                    status.si_code == CLD_DUMPED) {
3309
3310                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3311                 return -EPROTO;
3312         }
3313
3314         log_warning("%s failed due to unknown reason.", name);
3315         return -EPROTO;
3316
3317 }
3318
3319 void freeze(void) {
3320         for (;;)
3321                 pause();
3322 }
3323
3324 bool null_or_empty(struct stat *st) {
3325         assert(st);
3326
3327         if (S_ISREG(st->st_mode) && st->st_size <= 0)
3328                 return true;
3329
3330         if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3331                 return true;
3332
3333         return false;
3334 }
3335
3336 static const char *const ioprio_class_table[] = {
3337         [IOPRIO_CLASS_NONE] = "none",
3338         [IOPRIO_CLASS_RT] = "realtime",
3339         [IOPRIO_CLASS_BE] = "best-effort",
3340         [IOPRIO_CLASS_IDLE] = "idle"
3341 };
3342
3343 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
3344
3345 static const char *const sigchld_code_table[] = {
3346         [CLD_EXITED] = "exited",
3347         [CLD_KILLED] = "killed",
3348         [CLD_DUMPED] = "dumped",
3349         [CLD_TRAPPED] = "trapped",
3350         [CLD_STOPPED] = "stopped",
3351         [CLD_CONTINUED] = "continued",
3352 };
3353
3354 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3355
3356 static const char *const log_facility_table[LOG_NFACILITIES] = {
3357         [LOG_FAC(LOG_KERN)] = "kern",
3358         [LOG_FAC(LOG_USER)] = "user",
3359         [LOG_FAC(LOG_MAIL)] = "mail",
3360         [LOG_FAC(LOG_DAEMON)] = "daemon",
3361         [LOG_FAC(LOG_AUTH)] = "auth",
3362         [LOG_FAC(LOG_SYSLOG)] = "syslog",
3363         [LOG_FAC(LOG_LPR)] = "lpr",
3364         [LOG_FAC(LOG_NEWS)] = "news",
3365         [LOG_FAC(LOG_UUCP)] = "uucp",
3366         [LOG_FAC(LOG_CRON)] = "cron",
3367         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3368         [LOG_FAC(LOG_FTP)] = "ftp",
3369         [LOG_FAC(LOG_LOCAL0)] = "local0",
3370         [LOG_FAC(LOG_LOCAL1)] = "local1",
3371         [LOG_FAC(LOG_LOCAL2)] = "local2",
3372         [LOG_FAC(LOG_LOCAL3)] = "local3",
3373         [LOG_FAC(LOG_LOCAL4)] = "local4",
3374         [LOG_FAC(LOG_LOCAL5)] = "local5",
3375         [LOG_FAC(LOG_LOCAL6)] = "local6",
3376         [LOG_FAC(LOG_LOCAL7)] = "local7"
3377 };
3378
3379 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
3380
3381 static const char *const log_level_table[] = {
3382         [LOG_EMERG] = "emerg",
3383         [LOG_ALERT] = "alert",
3384         [LOG_CRIT] = "crit",
3385         [LOG_ERR] = "err",
3386         [LOG_WARNING] = "warning",
3387         [LOG_NOTICE] = "notice",
3388         [LOG_INFO] = "info",
3389         [LOG_DEBUG] = "debug"
3390 };
3391
3392 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
3393
3394 static const char* const sched_policy_table[] = {
3395         [SCHED_OTHER] = "other",
3396         [SCHED_BATCH] = "batch",
3397         [SCHED_IDLE] = "idle",
3398         [SCHED_FIFO] = "fifo",
3399         [SCHED_RR] = "rr"
3400 };
3401
3402 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
3403
3404 static const char* const rlimit_table[] = {
3405         [RLIMIT_CPU] = "LimitCPU",
3406         [RLIMIT_FSIZE] = "LimitFSIZE",
3407         [RLIMIT_DATA] = "LimitDATA",
3408         [RLIMIT_STACK] = "LimitSTACK",
3409         [RLIMIT_CORE] = "LimitCORE",
3410         [RLIMIT_RSS] = "LimitRSS",
3411         [RLIMIT_NOFILE] = "LimitNOFILE",
3412         [RLIMIT_AS] = "LimitAS",
3413         [RLIMIT_NPROC] = "LimitNPROC",
3414         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3415         [RLIMIT_LOCKS] = "LimitLOCKS",
3416         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3417         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3418         [RLIMIT_NICE] = "LimitNICE",
3419         [RLIMIT_RTPRIO] = "LimitRTPRIO",
3420         [RLIMIT_RTTIME] = "LimitRTTIME"
3421 };
3422
3423 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3424
3425 static const char* const ip_tos_table[] = {
3426         [IPTOS_LOWDELAY] = "low-delay",
3427         [IPTOS_THROUGHPUT] = "throughput",
3428         [IPTOS_RELIABILITY] = "reliability",
3429         [IPTOS_LOWCOST] = "low-cost",
3430 };
3431
3432 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
3433
3434 static const char *const signal_table[] = {
3435         [SIGHUP] = "HUP",
3436         [SIGINT] = "INT",
3437         [SIGQUIT] = "QUIT",
3438         [SIGILL] = "ILL",
3439         [SIGTRAP] = "TRAP",
3440         [SIGABRT] = "ABRT",
3441         [SIGBUS] = "BUS",
3442         [SIGFPE] = "FPE",
3443         [SIGKILL] = "KILL",
3444         [SIGUSR1] = "USR1",
3445         [SIGSEGV] = "SEGV",
3446         [SIGUSR2] = "USR2",
3447         [SIGPIPE] = "PIPE",
3448         [SIGALRM] = "ALRM",
3449         [SIGTERM] = "TERM",
3450 #ifdef SIGSTKFLT
3451         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
3452 #endif
3453         [SIGCHLD] = "CHLD",
3454         [SIGCONT] = "CONT",
3455         [SIGSTOP] = "STOP",
3456         [SIGTSTP] = "TSTP",
3457         [SIGTTIN] = "TTIN",
3458         [SIGTTOU] = "TTOU",
3459         [SIGURG] = "URG",
3460         [SIGXCPU] = "XCPU",
3461         [SIGXFSZ] = "XFSZ",
3462         [SIGVTALRM] = "VTALRM",
3463         [SIGPROF] = "PROF",
3464         [SIGWINCH] = "WINCH",
3465         [SIGIO] = "IO",
3466         [SIGPWR] = "PWR",
3467         [SIGSYS] = "SYS"
3468 };
3469
3470 DEFINE_STRING_TABLE_LOOKUP(signal, int);