chiark / gitweb /
util: move string enum mapping to the end
[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 #include <sys/capability.h>
54 #include <sys/time.h>
55 #include <linux/rtc.h>
56
57 #include "macro.h"
58 #include "util.h"
59 #include "ioprio.h"
60 #include "missing.h"
61 #include "log.h"
62 #include "strv.h"
63 #include "label.h"
64 #include "exit-status.h"
65 #include "hashmap.h"
66
67 size_t page_size(void) {
68         static __thread size_t pgsz = 0;
69         long r;
70
71         if (pgsz)
72                 return pgsz;
73
74         assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
75
76         pgsz = (size_t) r;
77
78         return pgsz;
79 }
80
81 bool streq_ptr(const char *a, const char *b) {
82
83         /* Like streq(), but tries to make sense of NULL pointers */
84
85         if (a && b)
86                 return streq(a, b);
87
88         if (!a && !b)
89                 return true;
90
91         return false;
92 }
93
94 usec_t now(clockid_t clock_id) {
95         struct timespec ts;
96
97         assert_se(clock_gettime(clock_id, &ts) == 0);
98
99         return timespec_load(&ts);
100 }
101
102 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
103         assert(ts);
104
105         ts->realtime = now(CLOCK_REALTIME);
106         ts->monotonic = now(CLOCK_MONOTONIC);
107
108         return ts;
109 }
110
111 usec_t timespec_load(const struct timespec *ts) {
112         assert(ts);
113
114         return
115                 (usec_t) ts->tv_sec * USEC_PER_SEC +
116                 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
117 }
118
119 struct timespec *timespec_store(struct timespec *ts, usec_t u)  {
120         assert(ts);
121
122         ts->tv_sec = (time_t) (u / USEC_PER_SEC);
123         ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
124
125         return ts;
126 }
127
128 usec_t timeval_load(const struct timeval *tv) {
129         assert(tv);
130
131         return
132                 (usec_t) tv->tv_sec * USEC_PER_SEC +
133                 (usec_t) tv->tv_usec;
134 }
135
136 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
137         assert(tv);
138
139         tv->tv_sec = (time_t) (u / USEC_PER_SEC);
140         tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
141
142         return tv;
143 }
144
145 bool endswith(const char *s, const char *postfix) {
146         size_t sl, pl;
147
148         assert(s);
149         assert(postfix);
150
151         sl = strlen(s);
152         pl = strlen(postfix);
153
154         if (pl == 0)
155                 return true;
156
157         if (sl < pl)
158                 return false;
159
160         return memcmp(s + sl - pl, postfix, pl) == 0;
161 }
162
163 bool startswith(const char *s, const char *prefix) {
164         size_t sl, pl;
165
166         assert(s);
167         assert(prefix);
168
169         sl = strlen(s);
170         pl = strlen(prefix);
171
172         if (pl == 0)
173                 return true;
174
175         if (sl < pl)
176                 return false;
177
178         return memcmp(s, prefix, pl) == 0;
179 }
180
181 bool startswith_no_case(const char *s, const char *prefix) {
182         size_t sl, pl;
183         unsigned i;
184
185         assert(s);
186         assert(prefix);
187
188         sl = strlen(s);
189         pl = strlen(prefix);
190
191         if (pl == 0)
192                 return true;
193
194         if (sl < pl)
195                 return false;
196
197         for(i = 0; i < pl; ++i) {
198                 if (tolower(s[i]) != tolower(prefix[i]))
199                         return false;
200         }
201
202         return true;
203 }
204
205 bool first_word(const char *s, const char *word) {
206         size_t sl, wl;
207
208         assert(s);
209         assert(word);
210
211         sl = strlen(s);
212         wl = strlen(word);
213
214         if (sl < wl)
215                 return false;
216
217         if (wl == 0)
218                 return true;
219
220         if (memcmp(s, word, wl) != 0)
221                 return false;
222
223         return s[wl] == 0 ||
224                 strchr(WHITESPACE, s[wl]);
225 }
226
227 int close_nointr(int fd) {
228         assert(fd >= 0);
229
230         for (;;) {
231                 int r;
232
233                 if ((r = close(fd)) >= 0)
234                         return r;
235
236                 if (errno != EINTR)
237                         return r;
238         }
239 }
240
241 void close_nointr_nofail(int fd) {
242         int saved_errno = errno;
243
244         /* like close_nointr() but cannot fail, and guarantees errno
245          * is unchanged */
246
247         assert_se(close_nointr(fd) == 0);
248
249         errno = saved_errno;
250 }
251
252 void close_many(const int fds[], unsigned n_fd) {
253         unsigned i;
254
255         for (i = 0; i < n_fd; i++)
256                 close_nointr_nofail(fds[i]);
257 }
258
259 int parse_boolean(const char *v) {
260         assert(v);
261
262         if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
263                 return 1;
264         else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
265                 return 0;
266
267         return -EINVAL;
268 }
269
270 int parse_pid(const char *s, pid_t* ret_pid) {
271         unsigned long ul = 0;
272         pid_t pid;
273         int r;
274
275         assert(s);
276         assert(ret_pid);
277
278         if ((r = safe_atolu(s, &ul)) < 0)
279                 return r;
280
281         pid = (pid_t) ul;
282
283         if ((unsigned long) pid != ul)
284                 return -ERANGE;
285
286         if (pid <= 0)
287                 return -ERANGE;
288
289         *ret_pid = pid;
290         return 0;
291 }
292
293 int safe_atou(const char *s, unsigned *ret_u) {
294         char *x = NULL;
295         unsigned long l;
296
297         assert(s);
298         assert(ret_u);
299
300         errno = 0;
301         l = strtoul(s, &x, 0);
302
303         if (!x || *x || errno)
304                 return errno ? -errno : -EINVAL;
305
306         if ((unsigned long) (unsigned) l != l)
307                 return -ERANGE;
308
309         *ret_u = (unsigned) l;
310         return 0;
311 }
312
313 int safe_atoi(const char *s, int *ret_i) {
314         char *x = NULL;
315         long l;
316
317         assert(s);
318         assert(ret_i);
319
320         errno = 0;
321         l = strtol(s, &x, 0);
322
323         if (!x || *x || errno)
324                 return errno ? -errno : -EINVAL;
325
326         if ((long) (int) l != l)
327                 return -ERANGE;
328
329         *ret_i = (int) l;
330         return 0;
331 }
332
333 int safe_atollu(const char *s, long long unsigned *ret_llu) {
334         char *x = NULL;
335         unsigned long long l;
336
337         assert(s);
338         assert(ret_llu);
339
340         errno = 0;
341         l = strtoull(s, &x, 0);
342
343         if (!x || *x || errno)
344                 return errno ? -errno : -EINVAL;
345
346         *ret_llu = l;
347         return 0;
348 }
349
350 int safe_atolli(const char *s, long long int *ret_lli) {
351         char *x = NULL;
352         long long l;
353
354         assert(s);
355         assert(ret_lli);
356
357         errno = 0;
358         l = strtoll(s, &x, 0);
359
360         if (!x || *x || errno)
361                 return errno ? -errno : -EINVAL;
362
363         *ret_lli = l;
364         return 0;
365 }
366
367 /* Split a string into words. */
368 char *split(const char *c, size_t *l, const char *separator, char **state) {
369         char *current;
370
371         current = *state ? *state : (char*) c;
372
373         if (!*current || *c == 0)
374                 return NULL;
375
376         current += strspn(current, separator);
377         *l = strcspn(current, separator);
378         *state = current+*l;
379
380         return (char*) current;
381 }
382
383 /* Split a string into words, but consider strings enclosed in '' and
384  * "" as words even if they include spaces. */
385 char *split_quoted(const char *c, size_t *l, char **state) {
386         char *current, *e;
387         bool escaped = false;
388
389         current = *state ? *state : (char*) c;
390
391         if (!*current || *c == 0)
392                 return NULL;
393
394         current += strspn(current, WHITESPACE);
395
396         if (*current == '\'') {
397                 current ++;
398
399                 for (e = current; *e; e++) {
400                         if (escaped)
401                                 escaped = false;
402                         else if (*e == '\\')
403                                 escaped = true;
404                         else if (*e == '\'')
405                                 break;
406                 }
407
408                 *l = e-current;
409                 *state = *e == 0 ? e : e+1;
410         } else if (*current == '\"') {
411                 current ++;
412
413                 for (e = current; *e; e++) {
414                         if (escaped)
415                                 escaped = false;
416                         else if (*e == '\\')
417                                 escaped = true;
418                         else if (*e == '\"')
419                                 break;
420                 }
421
422                 *l = e-current;
423                 *state = *e == 0 ? e : e+1;
424         } else {
425                 for (e = current; *e; e++) {
426                         if (escaped)
427                                 escaped = false;
428                         else if (*e == '\\')
429                                 escaped = true;
430                         else if (strchr(WHITESPACE, *e))
431                                 break;
432                 }
433                 *l = e-current;
434                 *state = e;
435         }
436
437         return (char*) current;
438 }
439
440 char **split_path_and_make_absolute(const char *p) {
441         char **l;
442         assert(p);
443
444         if (!(l = strv_split(p, ":")))
445                 return NULL;
446
447         if (!strv_path_make_absolute_cwd(l)) {
448                 strv_free(l);
449                 return NULL;
450         }
451
452         return l;
453 }
454
455 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
456         int r;
457         FILE *f;
458         char fn[PATH_MAX], line[LINE_MAX], *p;
459         long unsigned ppid;
460
461         assert(pid > 0);
462         assert(_ppid);
463
464         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
465         char_array_0(fn);
466
467         if (!(f = fopen(fn, "r")))
468                 return -errno;
469
470         if (!(fgets(line, sizeof(line), f))) {
471                 r = -errno;
472                 fclose(f);
473                 return r;
474         }
475
476         fclose(f);
477
478         /* Let's skip the pid and comm fields. The latter is enclosed
479          * in () but does not escape any () in its value, so let's
480          * skip over it manually */
481
482         if (!(p = strrchr(line, ')')))
483                 return -EIO;
484
485         p++;
486
487         if (sscanf(p, " "
488                    "%*c "  /* state */
489                    "%lu ", /* ppid */
490                    &ppid) != 1)
491                 return -EIO;
492
493         if ((long unsigned) (pid_t) ppid != ppid)
494                 return -ERANGE;
495
496         *_ppid = (pid_t) ppid;
497
498         return 0;
499 }
500
501 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
502         int r;
503         FILE *f;
504         char fn[PATH_MAX], line[LINE_MAX], *p;
505
506         assert(pid > 0);
507         assert(st);
508
509         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
510         char_array_0(fn);
511
512         if (!(f = fopen(fn, "r")))
513                 return -errno;
514
515         if (!(fgets(line, sizeof(line), f))) {
516                 r = -errno;
517                 fclose(f);
518                 return r;
519         }
520
521         fclose(f);
522
523         /* Let's skip the pid and comm fields. The latter is enclosed
524          * in () but does not escape any () in its value, so let's
525          * skip over it manually */
526
527         if (!(p = strrchr(line, ')')))
528                 return -EIO;
529
530         p++;
531
532         if (sscanf(p, " "
533                    "%*c "  /* state */
534                    "%*d "  /* ppid */
535                    "%*d "  /* pgrp */
536                    "%*d "  /* session */
537                    "%*d "  /* tty_nr */
538                    "%*d "  /* tpgid */
539                    "%*u "  /* flags */
540                    "%*u "  /* minflt */
541                    "%*u "  /* cminflt */
542                    "%*u "  /* majflt */
543                    "%*u "  /* cmajflt */
544                    "%*u "  /* utime */
545                    "%*u "  /* stime */
546                    "%*d "  /* cutime */
547                    "%*d "  /* cstime */
548                    "%*d "  /* priority */
549                    "%*d "  /* nice */
550                    "%*d "  /* num_threads */
551                    "%*d "  /* itrealvalue */
552                    "%llu "  /* starttime */,
553                    st) != 1)
554                 return -EIO;
555
556         return 0;
557 }
558
559 int write_one_line_file(const char *fn, const char *line) {
560         FILE *f;
561         int r;
562
563         assert(fn);
564         assert(line);
565
566         if (!(f = fopen(fn, "we")))
567                 return -errno;
568
569         if (fputs(line, f) < 0) {
570                 r = -errno;
571                 goto finish;
572         }
573
574         if (!endswith(line, "\n"))
575                 fputc('\n', f);
576
577         fflush(f);
578
579         if (ferror(f)) {
580                 if (errno != 0)
581                         r = -errno;
582                 else
583                         r = -EIO;
584         } else
585                 r = 0;
586
587 finish:
588         fclose(f);
589         return r;
590 }
591
592 int read_one_line_file(const char *fn, char **line) {
593         FILE *f;
594         int r;
595         char t[LINE_MAX], *c;
596
597         assert(fn);
598         assert(line);
599
600         if (!(f = fopen(fn, "re")))
601                 return -errno;
602
603         if (!(fgets(t, sizeof(t), f))) {
604                 r = -errno;
605                 goto finish;
606         }
607
608         if (!(c = strdup(t))) {
609                 r = -ENOMEM;
610                 goto finish;
611         }
612
613         truncate_nl(c);
614
615         *line = c;
616         r = 0;
617
618 finish:
619         fclose(f);
620         return r;
621 }
622
623 int read_full_file(const char *fn, char **contents) {
624         FILE *f;
625         int r;
626         size_t n, l;
627         char *buf = NULL;
628         struct stat st;
629
630         if (!(f = fopen(fn, "re")))
631                 return -errno;
632
633         if (fstat(fileno(f), &st) < 0) {
634                 r = -errno;
635                 goto finish;
636         }
637
638         n = st.st_size > 0 ? st.st_size : LINE_MAX;
639         l = 0;
640
641         for (;;) {
642                 char *t;
643                 size_t k;
644
645                 if (!(t = realloc(buf, n+1))) {
646                         r = -ENOMEM;
647                         goto finish;
648                 }
649
650                 buf = t;
651                 k = fread(buf + l, 1, n - l, f);
652
653                 if (k <= 0) {
654                         if (ferror(f)) {
655                                 r = -errno;
656                                 goto finish;
657                         }
658
659                         break;
660                 }
661
662                 l += k;
663                 n *= 2;
664
665                 /* Safety check */
666                 if (n > 4*1024*1024) {
667                         r = -E2BIG;
668                         goto finish;
669                 }
670         }
671
672         if (buf)
673                 buf[l] = 0;
674         else if (!(buf = calloc(1, 1))) {
675                 r = -errno;
676                 goto finish;
677         }
678
679         *contents = buf;
680         buf = NULL;
681
682         r = 0;
683
684 finish:
685         fclose(f);
686         free(buf);
687
688         return r;
689 }
690
691 int parse_env_file(
692                 const char *fname,
693                 const char *separator, ...) {
694
695         int r = 0;
696         char *contents, *p;
697
698         assert(fname);
699         assert(separator);
700
701         if ((r = read_full_file(fname, &contents)) < 0)
702                 return r;
703
704         p = contents;
705         for (;;) {
706                 const char *key = NULL;
707
708                 p += strspn(p, separator);
709                 p += strspn(p, WHITESPACE);
710
711                 if (!*p)
712                         break;
713
714                 if (!strchr(COMMENTS, *p)) {
715                         va_list ap;
716                         char **value;
717
718                         va_start(ap, separator);
719                         while ((key = va_arg(ap, char *))) {
720                                 size_t n;
721                                 char *v;
722
723                                 value = va_arg(ap, char **);
724
725                                 n = strlen(key);
726                                 if (strncmp(p, key, n) != 0 ||
727                                     p[n] != '=')
728                                         continue;
729
730                                 p += n + 1;
731                                 n = strcspn(p, separator);
732
733                                 if (n >= 2 &&
734                                     strchr(QUOTES, p[0]) &&
735                                     p[n-1] == p[0])
736                                         v = strndup(p+1, n-2);
737                                 else
738                                         v = strndup(p, n);
739
740                                 if (!v) {
741                                         r = -ENOMEM;
742                                         va_end(ap);
743                                         goto fail;
744                                 }
745
746                                 if (v[0] == '\0') {
747                                         /* return empty value strings as NULL */
748                                         free(v);
749                                         v = NULL;
750                                 }
751
752                                 free(*value);
753                                 *value = v;
754
755                                 p += n;
756
757                                 r ++;
758                                 break;
759                         }
760                         va_end(ap);
761                 }
762
763                 if (!key)
764                         p += strcspn(p, separator);
765         }
766
767 fail:
768         free(contents);
769         return r;
770 }
771
772 int load_env_file(
773                 const char *fname,
774                 char ***rl) {
775
776         FILE *f;
777         char **m = 0;
778         int r;
779
780         assert(fname);
781         assert(rl);
782
783         if (!(f = fopen(fname, "re")))
784                 return -errno;
785
786         while (!feof(f)) {
787                 char l[LINE_MAX], *p, *u;
788                 char **t;
789
790                 if (!fgets(l, sizeof(l), f)) {
791                         if (feof(f))
792                                 break;
793
794                         r = -errno;
795                         goto finish;
796                 }
797
798                 p = strstrip(l);
799
800                 if (!*p)
801                         continue;
802
803                 if (strchr(COMMENTS, *p))
804                         continue;
805
806                 if (!(u = normalize_env_assignment(p))) {
807                         log_error("Out of memory");
808                         r = -ENOMEM;
809                         goto finish;
810                 }
811
812                 t = strv_append(m, u);
813                 free(u);
814
815                 if (!t) {
816                         log_error("Out of memory");
817                         r = -ENOMEM;
818                         goto finish;
819                 }
820
821                 strv_free(m);
822                 m = t;
823         }
824
825         r = 0;
826
827         *rl = m;
828         m = NULL;
829
830 finish:
831         if (f)
832                 fclose(f);
833
834         strv_free(m);
835
836         return r;
837 }
838
839 int write_env_file(const char *fname, char **l) {
840
841         char **i;
842         FILE *f;
843         int r;
844
845         f = fopen(fname, "we");
846         if (!f)
847                 return -errno;
848
849         STRV_FOREACH(i, l) {
850                 fputs(*i, f);
851                 fputc('\n', f);
852         }
853
854         fflush(f);
855
856         r = ferror(f) ? -errno : 0;
857         fclose(f);
858
859         return r;
860 }
861
862 char *truncate_nl(char *s) {
863         assert(s);
864
865         s[strcspn(s, NEWLINE)] = 0;
866         return s;
867 }
868
869 int get_process_name(pid_t pid, char **name) {
870         char *p;
871         int r;
872
873         assert(pid >= 1);
874         assert(name);
875
876         if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
877                 return -ENOMEM;
878
879         r = read_one_line_file(p, name);
880         free(p);
881
882         if (r < 0)
883                 return r;
884
885         return 0;
886 }
887
888 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
889         char *p, *r, *k;
890         int c;
891         bool space = false;
892         size_t left;
893         FILE *f;
894
895         assert(pid >= 1);
896         assert(max_length > 0);
897         assert(line);
898
899         if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
900                 return -ENOMEM;
901
902         f = fopen(p, "r");
903         free(p);
904
905         if (!f)
906                 return -errno;
907
908         if (!(r = new(char, max_length))) {
909                 fclose(f);
910                 return -ENOMEM;
911         }
912
913         k = r;
914         left = max_length;
915         while ((c = getc(f)) != EOF) {
916
917                 if (isprint(c)) {
918                         if (space) {
919                                 if (left <= 4)
920                                         break;
921
922                                 *(k++) = ' ';
923                                 left--;
924                                 space = false;
925                         }
926
927                         if (left <= 4)
928                                 break;
929
930                         *(k++) = (char) c;
931                         left--;
932                 }  else
933                         space = true;
934         }
935
936         if (left <= 4) {
937                 size_t n = MIN(left-1, 3U);
938                 memcpy(k, "...", n);
939                 k[n] = 0;
940         } else
941                 *k = 0;
942
943         fclose(f);
944
945         /* Kernel threads have no argv[] */
946         if (r[0] == 0) {
947                 char *t;
948                 int h;
949
950                 free(r);
951
952                 if ((h = get_process_name(pid, &t)) < 0)
953                         return h;
954
955                 h = asprintf(&r, "[%s]", t);
956                 free(t);
957
958                 if (h < 0)
959                         return -ENOMEM;
960         }
961
962         *line = r;
963         return 0;
964 }
965
966 char *strnappend(const char *s, const char *suffix, size_t b) {
967         size_t a;
968         char *r;
969
970         if (!s && !suffix)
971                 return strdup("");
972
973         if (!s)
974                 return strndup(suffix, b);
975
976         if (!suffix)
977                 return strdup(s);
978
979         assert(s);
980         assert(suffix);
981
982         a = strlen(s);
983
984         if (!(r = new(char, a+b+1)))
985                 return NULL;
986
987         memcpy(r, s, a);
988         memcpy(r+a, suffix, b);
989         r[a+b] = 0;
990
991         return r;
992 }
993
994 char *strappend(const char *s, const char *suffix) {
995         return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
996 }
997
998 int readlink_malloc(const char *p, char **r) {
999         size_t l = 100;
1000
1001         assert(p);
1002         assert(r);
1003
1004         for (;;) {
1005                 char *c;
1006                 ssize_t n;
1007
1008                 if (!(c = new(char, l)))
1009                         return -ENOMEM;
1010
1011                 if ((n = readlink(p, c, l-1)) < 0) {
1012                         int ret = -errno;
1013                         free(c);
1014                         return ret;
1015                 }
1016
1017                 if ((size_t) n < l-1) {
1018                         c[n] = 0;
1019                         *r = c;
1020                         return 0;
1021                 }
1022
1023                 free(c);
1024                 l *= 2;
1025         }
1026 }
1027
1028 int readlink_and_make_absolute(const char *p, char **r) {
1029         char *target, *k;
1030         int j;
1031
1032         assert(p);
1033         assert(r);
1034
1035         if ((j = readlink_malloc(p, &target)) < 0)
1036                 return j;
1037
1038         k = file_in_same_dir(p, target);
1039         free(target);
1040
1041         if (!k)
1042                 return -ENOMEM;
1043
1044         *r = k;
1045         return 0;
1046 }
1047
1048 int parent_of_path(const char *path, char **_r) {
1049         const char *e, *a = NULL, *b = NULL, *p;
1050         char *r;
1051         bool slash = false;
1052
1053         assert(path);
1054         assert(_r);
1055
1056         if (!*path)
1057                 return -EINVAL;
1058
1059         for (e = path; *e; e++) {
1060
1061                 if (!slash && *e == '/') {
1062                         a = b;
1063                         b = e;
1064                         slash = true;
1065                 } else if (slash && *e != '/')
1066                         slash = false;
1067         }
1068
1069         if (*(e-1) == '/')
1070                 p = a;
1071         else
1072                 p = b;
1073
1074         if (!p)
1075                 return -EINVAL;
1076
1077         if (p == path)
1078                 r = strdup("/");
1079         else
1080                 r = strndup(path, p-path);
1081
1082         if (!r)
1083                 return -ENOMEM;
1084
1085         *_r = r;
1086         return 0;
1087 }
1088
1089
1090 char *file_name_from_path(const char *p) {
1091         char *r;
1092
1093         assert(p);
1094
1095         if ((r = strrchr(p, '/')))
1096                 return r + 1;
1097
1098         return (char*) p;
1099 }
1100
1101 bool path_is_absolute(const char *p) {
1102         assert(p);
1103
1104         return p[0] == '/';
1105 }
1106
1107 bool is_path(const char *p) {
1108
1109         return !!strchr(p, '/');
1110 }
1111
1112 char *path_make_absolute(const char *p, const char *prefix) {
1113         char *r;
1114
1115         assert(p);
1116
1117         /* Makes every item in the list an absolute path by prepending
1118          * the prefix, if specified and necessary */
1119
1120         if (path_is_absolute(p) || !prefix)
1121                 return strdup(p);
1122
1123         if (asprintf(&r, "%s/%s", prefix, p) < 0)
1124                 return NULL;
1125
1126         return r;
1127 }
1128
1129 char *path_make_absolute_cwd(const char *p) {
1130         char *cwd, *r;
1131
1132         assert(p);
1133
1134         /* Similar to path_make_absolute(), but prefixes with the
1135          * current working directory. */
1136
1137         if (path_is_absolute(p))
1138                 return strdup(p);
1139
1140         if (!(cwd = get_current_dir_name()))
1141                 return NULL;
1142
1143         r = path_make_absolute(p, cwd);
1144         free(cwd);
1145
1146         return r;
1147 }
1148
1149 char **strv_path_make_absolute_cwd(char **l) {
1150         char **s;
1151
1152         /* Goes through every item in the string list and makes it
1153          * absolute. This works in place and won't rollback any
1154          * changes on failure. */
1155
1156         STRV_FOREACH(s, l) {
1157                 char *t;
1158
1159                 if (!(t = path_make_absolute_cwd(*s)))
1160                         return NULL;
1161
1162                 free(*s);
1163                 *s = t;
1164         }
1165
1166         return l;
1167 }
1168
1169 char **strv_path_canonicalize(char **l) {
1170         char **s;
1171         unsigned k = 0;
1172         bool enomem = false;
1173
1174         if (strv_isempty(l))
1175                 return l;
1176
1177         /* Goes through every item in the string list and canonicalize
1178          * the path. This works in place and won't rollback any
1179          * changes on failure. */
1180
1181         STRV_FOREACH(s, l) {
1182                 char *t, *u;
1183
1184                 t = path_make_absolute_cwd(*s);
1185                 free(*s);
1186
1187                 if (!t) {
1188                         enomem = true;
1189                         continue;
1190                 }
1191
1192                 errno = 0;
1193                 u = canonicalize_file_name(t);
1194                 free(t);
1195
1196                 if (!u) {
1197                         if (errno == ENOMEM || !errno)
1198                                 enomem = true;
1199
1200                         continue;
1201                 }
1202
1203                 l[k++] = u;
1204         }
1205
1206         l[k] = NULL;
1207
1208         if (enomem)
1209                 return NULL;
1210
1211         return l;
1212 }
1213
1214 char **strv_path_remove_empty(char **l) {
1215         char **f, **t;
1216
1217         if (!l)
1218                 return NULL;
1219
1220         for (f = t = l; *f; f++) {
1221
1222                 if (dir_is_empty(*f) > 0) {
1223                         free(*f);
1224                         continue;
1225                 }
1226
1227                 *(t++) = *f;
1228         }
1229
1230         *t = NULL;
1231         return l;
1232 }
1233
1234 int reset_all_signal_handlers(void) {
1235         int sig;
1236
1237         for (sig = 1; sig < _NSIG; sig++) {
1238                 struct sigaction sa;
1239
1240                 if (sig == SIGKILL || sig == SIGSTOP)
1241                         continue;
1242
1243                 zero(sa);
1244                 sa.sa_handler = SIG_DFL;
1245                 sa.sa_flags = SA_RESTART;
1246
1247                 /* On Linux the first two RT signals are reserved by
1248                  * glibc, and sigaction() will return EINVAL for them. */
1249                 if ((sigaction(sig, &sa, NULL) < 0))
1250                         if (errno != EINVAL)
1251                                 return -errno;
1252         }
1253
1254         return 0;
1255 }
1256
1257 char *strstrip(char *s) {
1258         char *e, *l = NULL;
1259
1260         /* Drops trailing whitespace. Modifies the string in
1261          * place. Returns pointer to first non-space character */
1262
1263         s += strspn(s, WHITESPACE);
1264
1265         for (e = s; *e; e++)
1266                 if (!strchr(WHITESPACE, *e))
1267                         l = e;
1268
1269         if (l)
1270                 *(l+1) = 0;
1271         else
1272                 *s = 0;
1273
1274         return s;
1275 }
1276
1277 char *delete_chars(char *s, const char *bad) {
1278         char *f, *t;
1279
1280         /* Drops all whitespace, regardless where in the string */
1281
1282         for (f = s, t = s; *f; f++) {
1283                 if (strchr(bad, *f))
1284                         continue;
1285
1286                 *(t++) = *f;
1287         }
1288
1289         *t = 0;
1290
1291         return s;
1292 }
1293
1294 char *file_in_same_dir(const char *path, const char *filename) {
1295         char *e, *r;
1296         size_t k;
1297
1298         assert(path);
1299         assert(filename);
1300
1301         /* This removes the last component of path and appends
1302          * filename, unless the latter is absolute anyway or the
1303          * former isn't */
1304
1305         if (path_is_absolute(filename))
1306                 return strdup(filename);
1307
1308         if (!(e = strrchr(path, '/')))
1309                 return strdup(filename);
1310
1311         k = strlen(filename);
1312         if (!(r = new(char, e-path+1+k+1)))
1313                 return NULL;
1314
1315         memcpy(r, path, e-path+1);
1316         memcpy(r+(e-path)+1, filename, k+1);
1317
1318         return r;
1319 }
1320
1321 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1322         struct stat st;
1323
1324         if (label_mkdir(path, mode) >= 0)
1325                 if (chmod_and_chown(path, mode, uid, gid) < 0)
1326                         return -errno;
1327
1328         if (lstat(path, &st) < 0)
1329                 return -errno;
1330
1331         if ((st.st_mode & 0777) != mode ||
1332             st.st_uid != uid ||
1333             st.st_gid != gid ||
1334             !S_ISDIR(st.st_mode)) {
1335                 errno = EEXIST;
1336                 return -errno;
1337         }
1338
1339         return 0;
1340 }
1341
1342
1343 int mkdir_parents(const char *path, mode_t mode) {
1344         const char *p, *e;
1345
1346         assert(path);
1347
1348         /* Creates every parent directory in the path except the last
1349          * component. */
1350
1351         p = path + strspn(path, "/");
1352         for (;;) {
1353                 int r;
1354                 char *t;
1355
1356                 e = p + strcspn(p, "/");
1357                 p = e + strspn(e, "/");
1358
1359                 /* Is this the last component? If so, then we're
1360                  * done */
1361                 if (*p == 0)
1362                         return 0;
1363
1364                 if (!(t = strndup(path, e - path)))
1365                         return -ENOMEM;
1366
1367                 r = label_mkdir(t, mode);
1368                 free(t);
1369
1370                 if (r < 0 && errno != EEXIST)
1371                         return -errno;
1372         }
1373 }
1374
1375 int mkdir_p(const char *path, mode_t mode) {
1376         int r;
1377
1378         /* Like mkdir -p */
1379
1380         if ((r = mkdir_parents(path, mode)) < 0)
1381                 return r;
1382
1383         if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1384                 return -errno;
1385
1386         return 0;
1387 }
1388
1389 int rmdir_parents(const char *path, const char *stop) {
1390         size_t l;
1391         int r = 0;
1392
1393         assert(path);
1394         assert(stop);
1395
1396         l = strlen(path);
1397
1398         /* Skip trailing slashes */
1399         while (l > 0 && path[l-1] == '/')
1400                 l--;
1401
1402         while (l > 0) {
1403                 char *t;
1404
1405                 /* Skip last component */
1406                 while (l > 0 && path[l-1] != '/')
1407                         l--;
1408
1409                 /* Skip trailing slashes */
1410                 while (l > 0 && path[l-1] == '/')
1411                         l--;
1412
1413                 if (l <= 0)
1414                         break;
1415
1416                 if (!(t = strndup(path, l)))
1417                         return -ENOMEM;
1418
1419                 if (path_startswith(stop, t)) {
1420                         free(t);
1421                         return 0;
1422                 }
1423
1424                 r = rmdir(t);
1425                 free(t);
1426
1427                 if (r < 0)
1428                         if (errno != ENOENT)
1429                                 return -errno;
1430         }
1431
1432         return 0;
1433 }
1434
1435
1436 char hexchar(int x) {
1437         static const char table[16] = "0123456789abcdef";
1438
1439         return table[x & 15];
1440 }
1441
1442 int unhexchar(char c) {
1443
1444         if (c >= '0' && c <= '9')
1445                 return c - '0';
1446
1447         if (c >= 'a' && c <= 'f')
1448                 return c - 'a' + 10;
1449
1450         if (c >= 'A' && c <= 'F')
1451                 return c - 'A' + 10;
1452
1453         return -1;
1454 }
1455
1456 char octchar(int x) {
1457         return '0' + (x & 7);
1458 }
1459
1460 int unoctchar(char c) {
1461
1462         if (c >= '0' && c <= '7')
1463                 return c - '0';
1464
1465         return -1;
1466 }
1467
1468 char decchar(int x) {
1469         return '0' + (x % 10);
1470 }
1471
1472 int undecchar(char c) {
1473
1474         if (c >= '0' && c <= '9')
1475                 return c - '0';
1476
1477         return -1;
1478 }
1479
1480 char *cescape(const char *s) {
1481         char *r, *t;
1482         const char *f;
1483
1484         assert(s);
1485
1486         /* Does C style string escaping. */
1487
1488         if (!(r = new(char, strlen(s)*4 + 1)))
1489                 return NULL;
1490
1491         for (f = s, t = r; *f; f++)
1492
1493                 switch (*f) {
1494
1495                 case '\a':
1496                         *(t++) = '\\';
1497                         *(t++) = 'a';
1498                         break;
1499                 case '\b':
1500                         *(t++) = '\\';
1501                         *(t++) = 'b';
1502                         break;
1503                 case '\f':
1504                         *(t++) = '\\';
1505                         *(t++) = 'f';
1506                         break;
1507                 case '\n':
1508                         *(t++) = '\\';
1509                         *(t++) = 'n';
1510                         break;
1511                 case '\r':
1512                         *(t++) = '\\';
1513                         *(t++) = 'r';
1514                         break;
1515                 case '\t':
1516                         *(t++) = '\\';
1517                         *(t++) = 't';
1518                         break;
1519                 case '\v':
1520                         *(t++) = '\\';
1521                         *(t++) = 'v';
1522                         break;
1523                 case '\\':
1524                         *(t++) = '\\';
1525                         *(t++) = '\\';
1526                         break;
1527                 case '"':
1528                         *(t++) = '\\';
1529                         *(t++) = '"';
1530                         break;
1531                 case '\'':
1532                         *(t++) = '\\';
1533                         *(t++) = '\'';
1534                         break;
1535
1536                 default:
1537                         /* For special chars we prefer octal over
1538                          * hexadecimal encoding, simply because glib's
1539                          * g_strescape() does the same */
1540                         if ((*f < ' ') || (*f >= 127)) {
1541                                 *(t++) = '\\';
1542                                 *(t++) = octchar((unsigned char) *f >> 6);
1543                                 *(t++) = octchar((unsigned char) *f >> 3);
1544                                 *(t++) = octchar((unsigned char) *f);
1545                         } else
1546                                 *(t++) = *f;
1547                         break;
1548                 }
1549
1550         *t = 0;
1551
1552         return r;
1553 }
1554
1555 char *cunescape_length(const char *s, size_t length) {
1556         char *r, *t;
1557         const char *f;
1558
1559         assert(s);
1560
1561         /* Undoes C style string escaping */
1562
1563         if (!(r = new(char, length+1)))
1564                 return r;
1565
1566         for (f = s, t = r; f < s + length; f++) {
1567
1568                 if (*f != '\\') {
1569                         *(t++) = *f;
1570                         continue;
1571                 }
1572
1573                 f++;
1574
1575                 switch (*f) {
1576
1577                 case 'a':
1578                         *(t++) = '\a';
1579                         break;
1580                 case 'b':
1581                         *(t++) = '\b';
1582                         break;
1583                 case 'f':
1584                         *(t++) = '\f';
1585                         break;
1586                 case 'n':
1587                         *(t++) = '\n';
1588                         break;
1589                 case 'r':
1590                         *(t++) = '\r';
1591                         break;
1592                 case 't':
1593                         *(t++) = '\t';
1594                         break;
1595                 case 'v':
1596                         *(t++) = '\v';
1597                         break;
1598                 case '\\':
1599                         *(t++) = '\\';
1600                         break;
1601                 case '"':
1602                         *(t++) = '"';
1603                         break;
1604                 case '\'':
1605                         *(t++) = '\'';
1606                         break;
1607
1608                 case 's':
1609                         /* This is an extension of the XDG syntax files */
1610                         *(t++) = ' ';
1611                         break;
1612
1613                 case 'x': {
1614                         /* hexadecimal encoding */
1615                         int a, b;
1616
1617                         if ((a = unhexchar(f[1])) < 0 ||
1618                             (b = unhexchar(f[2])) < 0) {
1619                                 /* Invalid escape code, let's take it literal then */
1620                                 *(t++) = '\\';
1621                                 *(t++) = 'x';
1622                         } else {
1623                                 *(t++) = (char) ((a << 4) | b);
1624                                 f += 2;
1625                         }
1626
1627                         break;
1628                 }
1629
1630                 case '0':
1631                 case '1':
1632                 case '2':
1633                 case '3':
1634                 case '4':
1635                 case '5':
1636                 case '6':
1637                 case '7': {
1638                         /* octal encoding */
1639                         int a, b, c;
1640
1641                         if ((a = unoctchar(f[0])) < 0 ||
1642                             (b = unoctchar(f[1])) < 0 ||
1643                             (c = unoctchar(f[2])) < 0) {
1644                                 /* Invalid escape code, let's take it literal then */
1645                                 *(t++) = '\\';
1646                                 *(t++) = f[0];
1647                         } else {
1648                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
1649                                 f += 2;
1650                         }
1651
1652                         break;
1653                 }
1654
1655                 case 0:
1656                         /* premature end of string.*/
1657                         *(t++) = '\\';
1658                         goto finish;
1659
1660                 default:
1661                         /* Invalid escape code, let's take it literal then */
1662                         *(t++) = '\\';
1663                         *(t++) = *f;
1664                         break;
1665                 }
1666         }
1667
1668 finish:
1669         *t = 0;
1670         return r;
1671 }
1672
1673 char *cunescape(const char *s) {
1674         return cunescape_length(s, strlen(s));
1675 }
1676
1677 char *xescape(const char *s, const char *bad) {
1678         char *r, *t;
1679         const char *f;
1680
1681         /* Escapes all chars in bad, in addition to \ and all special
1682          * chars, in \xFF style escaping. May be reversed with
1683          * cunescape. */
1684
1685         if (!(r = new(char, strlen(s)*4+1)))
1686                 return NULL;
1687
1688         for (f = s, t = r; *f; f++) {
1689
1690                 if ((*f < ' ') || (*f >= 127) ||
1691                     (*f == '\\') || strchr(bad, *f)) {
1692                         *(t++) = '\\';
1693                         *(t++) = 'x';
1694                         *(t++) = hexchar(*f >> 4);
1695                         *(t++) = hexchar(*f);
1696                 } else
1697                         *(t++) = *f;
1698         }
1699
1700         *t = 0;
1701
1702         return r;
1703 }
1704
1705 char *bus_path_escape(const char *s) {
1706         char *r, *t;
1707         const char *f;
1708
1709         assert(s);
1710
1711         /* Escapes all chars that D-Bus' object path cannot deal
1712          * with. Can be reverse with bus_path_unescape() */
1713
1714         if (!(r = new(char, strlen(s)*3+1)))
1715                 return NULL;
1716
1717         for (f = s, t = r; *f; f++) {
1718
1719                 if (!(*f >= 'A' && *f <= 'Z') &&
1720                     !(*f >= 'a' && *f <= 'z') &&
1721                     !(*f >= '0' && *f <= '9')) {
1722                         *(t++) = '_';
1723                         *(t++) = hexchar(*f >> 4);
1724                         *(t++) = hexchar(*f);
1725                 } else
1726                         *(t++) = *f;
1727         }
1728
1729         *t = 0;
1730
1731         return r;
1732 }
1733
1734 char *bus_path_unescape(const char *f) {
1735         char *r, *t;
1736
1737         assert(f);
1738
1739         if (!(r = strdup(f)))
1740                 return NULL;
1741
1742         for (t = r; *f; f++) {
1743
1744                 if (*f == '_') {
1745                         int a, b;
1746
1747                         if ((a = unhexchar(f[1])) < 0 ||
1748                             (b = unhexchar(f[2])) < 0) {
1749                                 /* Invalid escape code, let's take it literal then */
1750                                 *(t++) = '_';
1751                         } else {
1752                                 *(t++) = (char) ((a << 4) | b);
1753                                 f += 2;
1754                         }
1755                 } else
1756                         *(t++) = *f;
1757         }
1758
1759         *t = 0;
1760
1761         return r;
1762 }
1763
1764 char *path_kill_slashes(char *path) {
1765         char *f, *t;
1766         bool slash = false;
1767
1768         /* Removes redundant inner and trailing slashes. Modifies the
1769          * passed string in-place.
1770          *
1771          * ///foo///bar/ becomes /foo/bar
1772          */
1773
1774         for (f = path, t = path; *f; f++) {
1775
1776                 if (*f == '/') {
1777                         slash = true;
1778                         continue;
1779                 }
1780
1781                 if (slash) {
1782                         slash = false;
1783                         *(t++) = '/';
1784                 }
1785
1786                 *(t++) = *f;
1787         }
1788
1789         /* Special rule, if we are talking of the root directory, a
1790         trailing slash is good */
1791
1792         if (t == path && slash)
1793                 *(t++) = '/';
1794
1795         *t = 0;
1796         return path;
1797 }
1798
1799 bool path_startswith(const char *path, const char *prefix) {
1800         assert(path);
1801         assert(prefix);
1802
1803         if ((path[0] == '/') != (prefix[0] == '/'))
1804                 return false;
1805
1806         for (;;) {
1807                 size_t a, b;
1808
1809                 path += strspn(path, "/");
1810                 prefix += strspn(prefix, "/");
1811
1812                 if (*prefix == 0)
1813                         return true;
1814
1815                 if (*path == 0)
1816                         return false;
1817
1818                 a = strcspn(path, "/");
1819                 b = strcspn(prefix, "/");
1820
1821                 if (a != b)
1822                         return false;
1823
1824                 if (memcmp(path, prefix, a) != 0)
1825                         return false;
1826
1827                 path += a;
1828                 prefix += b;
1829         }
1830 }
1831
1832 bool path_equal(const char *a, const char *b) {
1833         assert(a);
1834         assert(b);
1835
1836         if ((a[0] == '/') != (b[0] == '/'))
1837                 return false;
1838
1839         for (;;) {
1840                 size_t j, k;
1841
1842                 a += strspn(a, "/");
1843                 b += strspn(b, "/");
1844
1845                 if (*a == 0 && *b == 0)
1846                         return true;
1847
1848                 if (*a == 0 || *b == 0)
1849                         return false;
1850
1851                 j = strcspn(a, "/");
1852                 k = strcspn(b, "/");
1853
1854                 if (j != k)
1855                         return false;
1856
1857                 if (memcmp(a, b, j) != 0)
1858                         return false;
1859
1860                 a += j;
1861                 b += k;
1862         }
1863 }
1864
1865 char *ascii_strlower(char *t) {
1866         char *p;
1867
1868         assert(t);
1869
1870         for (p = t; *p; p++)
1871                 if (*p >= 'A' && *p <= 'Z')
1872                         *p = *p - 'A' + 'a';
1873
1874         return t;
1875 }
1876
1877 bool ignore_file(const char *filename) {
1878         assert(filename);
1879
1880         return
1881                 filename[0] == '.' ||
1882                 streq(filename, "lost+found") ||
1883                 streq(filename, "aquota.user") ||
1884                 streq(filename, "aquota.group") ||
1885                 endswith(filename, "~") ||
1886                 endswith(filename, ".rpmnew") ||
1887                 endswith(filename, ".rpmsave") ||
1888                 endswith(filename, ".rpmorig") ||
1889                 endswith(filename, ".dpkg-old") ||
1890                 endswith(filename, ".dpkg-new") ||
1891                 endswith(filename, ".swp");
1892 }
1893
1894 int fd_nonblock(int fd, bool nonblock) {
1895         int flags;
1896
1897         assert(fd >= 0);
1898
1899         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1900                 return -errno;
1901
1902         if (nonblock)
1903                 flags |= O_NONBLOCK;
1904         else
1905                 flags &= ~O_NONBLOCK;
1906
1907         if (fcntl(fd, F_SETFL, flags) < 0)
1908                 return -errno;
1909
1910         return 0;
1911 }
1912
1913 int fd_cloexec(int fd, bool cloexec) {
1914         int flags;
1915
1916         assert(fd >= 0);
1917
1918         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1919                 return -errno;
1920
1921         if (cloexec)
1922                 flags |= FD_CLOEXEC;
1923         else
1924                 flags &= ~FD_CLOEXEC;
1925
1926         if (fcntl(fd, F_SETFD, flags) < 0)
1927                 return -errno;
1928
1929         return 0;
1930 }
1931
1932 int close_all_fds(const int except[], unsigned n_except) {
1933         DIR *d;
1934         struct dirent *de;
1935         int r = 0;
1936
1937         if (!(d = opendir("/proc/self/fd")))
1938                 return -errno;
1939
1940         while ((de = readdir(d))) {
1941                 int fd = -1;
1942
1943                 if (ignore_file(de->d_name))
1944                         continue;
1945
1946                 if (safe_atoi(de->d_name, &fd) < 0)
1947                         /* Let's better ignore this, just in case */
1948                         continue;
1949
1950                 if (fd < 3)
1951                         continue;
1952
1953                 if (fd == dirfd(d))
1954                         continue;
1955
1956                 if (except) {
1957                         bool found;
1958                         unsigned i;
1959
1960                         found = false;
1961                         for (i = 0; i < n_except; i++)
1962                                 if (except[i] == fd) {
1963                                         found = true;
1964                                         break;
1965                                 }
1966
1967                         if (found)
1968                                 continue;
1969                 }
1970
1971                 if (close_nointr(fd) < 0) {
1972                         /* Valgrind has its own FD and doesn't want to have it closed */
1973                         if (errno != EBADF && r == 0)
1974                                 r = -errno;
1975                 }
1976         }
1977
1978         closedir(d);
1979         return r;
1980 }
1981
1982 bool chars_intersect(const char *a, const char *b) {
1983         const char *p;
1984
1985         /* Returns true if any of the chars in a are in b. */
1986         for (p = a; *p; p++)
1987                 if (strchr(b, *p))
1988                         return true;
1989
1990         return false;
1991 }
1992
1993 char *format_timestamp(char *buf, size_t l, usec_t t) {
1994         struct tm tm;
1995         time_t sec;
1996
1997         assert(buf);
1998         assert(l > 0);
1999
2000         if (t <= 0)
2001                 return NULL;
2002
2003         sec = (time_t) (t / USEC_PER_SEC);
2004
2005         if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2006                 return NULL;
2007
2008         return buf;
2009 }
2010
2011 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2012         usec_t n, d;
2013
2014         n = now(CLOCK_REALTIME);
2015
2016         if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2017                 return NULL;
2018
2019         d = n - t;
2020
2021         if (d >= USEC_PER_YEAR)
2022                 snprintf(buf, l, "%llu years and %llu months ago",
2023                          (unsigned long long) (d / USEC_PER_YEAR),
2024                          (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2025         else if (d >= USEC_PER_MONTH)
2026                 snprintf(buf, l, "%llu months and %llu days ago",
2027                          (unsigned long long) (d / USEC_PER_MONTH),
2028                          (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2029         else if (d >= USEC_PER_WEEK)
2030                 snprintf(buf, l, "%llu weeks and %llu days ago",
2031                          (unsigned long long) (d / USEC_PER_WEEK),
2032                          (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2033         else if (d >= 2*USEC_PER_DAY)
2034                 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2035         else if (d >= 25*USEC_PER_HOUR)
2036                 snprintf(buf, l, "1 day and %lluh ago",
2037                          (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2038         else if (d >= 6*USEC_PER_HOUR)
2039                 snprintf(buf, l, "%lluh ago",
2040                          (unsigned long long) (d / USEC_PER_HOUR));
2041         else if (d >= USEC_PER_HOUR)
2042                 snprintf(buf, l, "%lluh %llumin ago",
2043                          (unsigned long long) (d / USEC_PER_HOUR),
2044                          (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2045         else if (d >= 5*USEC_PER_MINUTE)
2046                 snprintf(buf, l, "%llumin ago",
2047                          (unsigned long long) (d / USEC_PER_MINUTE));
2048         else if (d >= USEC_PER_MINUTE)
2049                 snprintf(buf, l, "%llumin %llus ago",
2050                          (unsigned long long) (d / USEC_PER_MINUTE),
2051                          (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2052         else if (d >= USEC_PER_SEC)
2053                 snprintf(buf, l, "%llus ago",
2054                          (unsigned long long) (d / USEC_PER_SEC));
2055         else if (d >= USEC_PER_MSEC)
2056                 snprintf(buf, l, "%llums ago",
2057                          (unsigned long long) (d / USEC_PER_MSEC));
2058         else if (d > 0)
2059                 snprintf(buf, l, "%lluus ago",
2060                          (unsigned long long) d);
2061         else
2062                 snprintf(buf, l, "now");
2063
2064         buf[l-1] = 0;
2065         return buf;
2066 }
2067
2068 char *format_timespan(char *buf, size_t l, usec_t t) {
2069         static const struct {
2070                 const char *suffix;
2071                 usec_t usec;
2072         } table[] = {
2073                 { "w", USEC_PER_WEEK },
2074                 { "d", USEC_PER_DAY },
2075                 { "h", USEC_PER_HOUR },
2076                 { "min", USEC_PER_MINUTE },
2077                 { "s", USEC_PER_SEC },
2078                 { "ms", USEC_PER_MSEC },
2079                 { "us", 1 },
2080         };
2081
2082         unsigned i;
2083         char *p = buf;
2084
2085         assert(buf);
2086         assert(l > 0);
2087
2088         if (t == (usec_t) -1)
2089                 return NULL;
2090
2091         if (t == 0) {
2092                 snprintf(p, l, "0");
2093                 p[l-1] = 0;
2094                 return p;
2095         }
2096
2097         /* The result of this function can be parsed with parse_usec */
2098
2099         for (i = 0; i < ELEMENTSOF(table); i++) {
2100                 int k;
2101                 size_t n;
2102
2103                 if (t < table[i].usec)
2104                         continue;
2105
2106                 if (l <= 1)
2107                         break;
2108
2109                 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2110                 n = MIN((size_t) k, l);
2111
2112                 l -= n;
2113                 p += n;
2114
2115                 t %= table[i].usec;
2116         }
2117
2118         *p = 0;
2119
2120         return buf;
2121 }
2122
2123 bool fstype_is_network(const char *fstype) {
2124         static const char * const table[] = {
2125                 "cifs",
2126                 "smbfs",
2127                 "ncpfs",
2128                 "nfs",
2129                 "nfs4",
2130                 "gfs",
2131                 "gfs2"
2132         };
2133
2134         unsigned i;
2135
2136         for (i = 0; i < ELEMENTSOF(table); i++)
2137                 if (streq(table[i], fstype))
2138                         return true;
2139
2140         return false;
2141 }
2142
2143 int chvt(int vt) {
2144         int fd, r = 0;
2145
2146         if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2147                 return -errno;
2148
2149         if (vt < 0) {
2150                 int tiocl[2] = {
2151                         TIOCL_GETKMSGREDIRECT,
2152                         0
2153                 };
2154
2155                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2156                         return -errno;
2157
2158                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2159         }
2160
2161         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2162                 r = -errno;
2163
2164         close_nointr_nofail(r);
2165         return r;
2166 }
2167
2168 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2169         struct termios old_termios, new_termios;
2170         char c;
2171         char line[LINE_MAX];
2172
2173         assert(f);
2174         assert(ret);
2175
2176         if (tcgetattr(fileno(f), &old_termios) >= 0) {
2177                 new_termios = old_termios;
2178
2179                 new_termios.c_lflag &= ~ICANON;
2180                 new_termios.c_cc[VMIN] = 1;
2181                 new_termios.c_cc[VTIME] = 0;
2182
2183                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2184                         size_t k;
2185
2186                         k = fread(&c, 1, 1, f);
2187
2188                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2189
2190                         if (k <= 0)
2191                                 return -EIO;
2192
2193                         if (need_nl)
2194                                 *need_nl = c != '\n';
2195
2196                         *ret = c;
2197                         return 0;
2198                 }
2199         }
2200
2201         if (!(fgets(line, sizeof(line), f)))
2202                 return -EIO;
2203
2204         truncate_nl(line);
2205
2206         if (strlen(line) != 1)
2207                 return -EBADMSG;
2208
2209         if (need_nl)
2210                 *need_nl = false;
2211
2212         *ret = line[0];
2213         return 0;
2214 }
2215
2216 int ask(char *ret, const char *replies, const char *text, ...) {
2217         bool on_tty;
2218
2219         assert(ret);
2220         assert(replies);
2221         assert(text);
2222
2223         on_tty = isatty(STDOUT_FILENO);
2224
2225         for (;;) {
2226                 va_list ap;
2227                 char c;
2228                 int r;
2229                 bool need_nl = true;
2230
2231                 if (on_tty)
2232                         fputs("\x1B[1m", stdout);
2233
2234                 va_start(ap, text);
2235                 vprintf(text, ap);
2236                 va_end(ap);
2237
2238                 if (on_tty)
2239                         fputs("\x1B[0m", stdout);
2240
2241                 fflush(stdout);
2242
2243                 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2244
2245                         if (r == -EBADMSG) {
2246                                 puts("Bad input, please try again.");
2247                                 continue;
2248                         }
2249
2250                         putchar('\n');
2251                         return r;
2252                 }
2253
2254                 if (need_nl)
2255                         putchar('\n');
2256
2257                 if (strchr(replies, c)) {
2258                         *ret = c;
2259                         return 0;
2260                 }
2261
2262                 puts("Read unexpected character, please try again.");
2263         }
2264 }
2265
2266 int reset_terminal_fd(int fd) {
2267         struct termios termios;
2268         int r = 0;
2269         long arg;
2270
2271         /* Set terminal to some sane defaults */
2272
2273         assert(fd >= 0);
2274
2275         /* We leave locked terminal attributes untouched, so that
2276          * Plymouth may set whatever it wants to set, and we don't
2277          * interfere with that. */
2278
2279         /* Disable exclusive mode, just in case */
2280         ioctl(fd, TIOCNXCL);
2281
2282         /* Enable console unicode mode */
2283         arg = K_UNICODE;
2284         ioctl(fd, KDSKBMODE, &arg);
2285
2286         if (tcgetattr(fd, &termios) < 0) {
2287                 r = -errno;
2288                 goto finish;
2289         }
2290
2291         /* We only reset the stuff that matters to the software. How
2292          * hardware is set up we don't touch assuming that somebody
2293          * else will do that for us */
2294
2295         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2296         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2297         termios.c_oflag |= ONLCR;
2298         termios.c_cflag |= CREAD;
2299         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2300
2301         termios.c_cc[VINTR]    =   03;  /* ^C */
2302         termios.c_cc[VQUIT]    =  034;  /* ^\ */
2303         termios.c_cc[VERASE]   = 0177;
2304         termios.c_cc[VKILL]    =  025;  /* ^X */
2305         termios.c_cc[VEOF]     =   04;  /* ^D */
2306         termios.c_cc[VSTART]   =  021;  /* ^Q */
2307         termios.c_cc[VSTOP]    =  023;  /* ^S */
2308         termios.c_cc[VSUSP]    =  032;  /* ^Z */
2309         termios.c_cc[VLNEXT]   =  026;  /* ^V */
2310         termios.c_cc[VWERASE]  =  027;  /* ^W */
2311         termios.c_cc[VREPRINT] =  022;  /* ^R */
2312         termios.c_cc[VEOL]     =    0;
2313         termios.c_cc[VEOL2]    =    0;
2314
2315         termios.c_cc[VTIME]  = 0;
2316         termios.c_cc[VMIN]   = 1;
2317
2318         if (tcsetattr(fd, TCSANOW, &termios) < 0)
2319                 r = -errno;
2320
2321 finish:
2322         /* Just in case, flush all crap out */
2323         tcflush(fd, TCIOFLUSH);
2324
2325         return r;
2326 }
2327
2328 int reset_terminal(const char *name) {
2329         int fd, r;
2330
2331         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2332         if (fd < 0)
2333                 return fd;
2334
2335         r = reset_terminal_fd(fd);
2336         close_nointr_nofail(fd);
2337
2338         return r;
2339 }
2340
2341 int open_terminal(const char *name, int mode) {
2342         int fd, r;
2343         unsigned c = 0;
2344
2345         /*
2346          * If a TTY is in the process of being closed opening it might
2347          * cause EIO. This is horribly awful, but unlikely to be
2348          * changed in the kernel. Hence we work around this problem by
2349          * retrying a couple of times.
2350          *
2351          * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2352          */
2353
2354         for (;;) {
2355                 if ((fd = open(name, mode)) >= 0)
2356                         break;
2357
2358                 if (errno != EIO)
2359                         return -errno;
2360
2361                 if (c >= 20)
2362                         return -errno;
2363
2364                 usleep(50 * USEC_PER_MSEC);
2365                 c++;
2366         }
2367
2368         if (fd < 0)
2369                 return -errno;
2370
2371         if ((r = isatty(fd)) < 0) {
2372                 close_nointr_nofail(fd);
2373                 return -errno;
2374         }
2375
2376         if (!r) {
2377                 close_nointr_nofail(fd);
2378                 return -ENOTTY;
2379         }
2380
2381         return fd;
2382 }
2383
2384 int flush_fd(int fd) {
2385         struct pollfd pollfd;
2386
2387         zero(pollfd);
2388         pollfd.fd = fd;
2389         pollfd.events = POLLIN;
2390
2391         for (;;) {
2392                 char buf[LINE_MAX];
2393                 ssize_t l;
2394                 int r;
2395
2396                 if ((r = poll(&pollfd, 1, 0)) < 0) {
2397
2398                         if (errno == EINTR)
2399                                 continue;
2400
2401                         return -errno;
2402                 }
2403
2404                 if (r == 0)
2405                         return 0;
2406
2407                 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2408
2409                         if (errno == EINTR)
2410                                 continue;
2411
2412                         if (errno == EAGAIN)
2413                                 return 0;
2414
2415                         return -errno;
2416                 }
2417
2418                 if (l <= 0)
2419                         return 0;
2420         }
2421 }
2422
2423 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2424         int fd = -1, notify = -1, r, wd = -1;
2425
2426         assert(name);
2427
2428         /* We use inotify to be notified when the tty is closed. We
2429          * create the watch before checking if we can actually acquire
2430          * it, so that we don't lose any event.
2431          *
2432          * Note: strictly speaking this actually watches for the
2433          * device being closed, it does *not* really watch whether a
2434          * tty loses its controlling process. However, unless some
2435          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2436          * its tty otherwise this will not become a problem. As long
2437          * as the administrator makes sure not configure any service
2438          * on the same tty as an untrusted user this should not be a
2439          * problem. (Which he probably should not do anyway.) */
2440
2441         if (!fail && !force) {
2442                 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2443                         r = -errno;
2444                         goto fail;
2445                 }
2446
2447                 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2448                         r = -errno;
2449                         goto fail;
2450                 }
2451         }
2452
2453         for (;;) {
2454                 if (notify >= 0)
2455                         if ((r = flush_fd(notify)) < 0)
2456                                 goto fail;
2457
2458                 /* We pass here O_NOCTTY only so that we can check the return
2459                  * value TIOCSCTTY and have a reliable way to figure out if we
2460                  * successfully became the controlling process of the tty */
2461                 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2462                         return fd;
2463
2464                 /* First, try to get the tty */
2465                 r = ioctl(fd, TIOCSCTTY, force);
2466
2467                 /* Sometimes it makes sense to ignore TIOCSCTTY
2468                  * returning EPERM, i.e. when very likely we already
2469                  * are have this controlling terminal. */
2470                 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2471                         r = 0;
2472
2473                 if (r < 0 && (force || fail || errno != EPERM)) {
2474                         r = -errno;
2475                         goto fail;
2476                 }
2477
2478                 if (r >= 0)
2479                         break;
2480
2481                 assert(!fail);
2482                 assert(!force);
2483                 assert(notify >= 0);
2484
2485                 for (;;) {
2486                         uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2487                         ssize_t l;
2488                         struct inotify_event *e;
2489
2490                         if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2491
2492                                 if (errno == EINTR)
2493                                         continue;
2494
2495                                 r = -errno;
2496                                 goto fail;
2497                         }
2498
2499                         e = (struct inotify_event*) inotify_buffer;
2500
2501                         while (l > 0) {
2502                                 size_t step;
2503
2504                                 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2505                                         r = -EIO;
2506                                         goto fail;
2507                                 }
2508
2509                                 step = sizeof(struct inotify_event) + e->len;
2510                                 assert(step <= (size_t) l);
2511
2512                                 e = (struct inotify_event*) ((uint8_t*) e + step);
2513                                 l -= step;
2514                         }
2515
2516                         break;
2517                 }
2518
2519                 /* We close the tty fd here since if the old session
2520                  * ended our handle will be dead. It's important that
2521                  * we do this after sleeping, so that we don't enter
2522                  * an endless loop. */
2523                 close_nointr_nofail(fd);
2524         }
2525
2526         if (notify >= 0)
2527                 close_nointr_nofail(notify);
2528
2529         if ((r = reset_terminal_fd(fd)) < 0)
2530                 log_warning("Failed to reset terminal: %s", strerror(-r));
2531
2532         return fd;
2533
2534 fail:
2535         if (fd >= 0)
2536                 close_nointr_nofail(fd);
2537
2538         if (notify >= 0)
2539                 close_nointr_nofail(notify);
2540
2541         return r;
2542 }
2543
2544 int release_terminal(void) {
2545         int r = 0, fd;
2546         struct sigaction sa_old, sa_new;
2547
2548         if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2549                 return -errno;
2550
2551         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2552          * by our own TIOCNOTTY */
2553
2554         zero(sa_new);
2555         sa_new.sa_handler = SIG_IGN;
2556         sa_new.sa_flags = SA_RESTART;
2557         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2558
2559         if (ioctl(fd, TIOCNOTTY) < 0)
2560                 r = -errno;
2561
2562         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2563
2564         close_nointr_nofail(fd);
2565         return r;
2566 }
2567
2568 int sigaction_many(const struct sigaction *sa, ...) {
2569         va_list ap;
2570         int r = 0, sig;
2571
2572         va_start(ap, sa);
2573         while ((sig = va_arg(ap, int)) > 0)
2574                 if (sigaction(sig, sa, NULL) < 0)
2575                         r = -errno;
2576         va_end(ap);
2577
2578         return r;
2579 }
2580
2581 int ignore_signals(int sig, ...) {
2582         struct sigaction sa;
2583         va_list ap;
2584         int r = 0;
2585
2586         zero(sa);
2587         sa.sa_handler = SIG_IGN;
2588         sa.sa_flags = SA_RESTART;
2589
2590         if (sigaction(sig, &sa, NULL) < 0)
2591                 r = -errno;
2592
2593         va_start(ap, sig);
2594         while ((sig = va_arg(ap, int)) > 0)
2595                 if (sigaction(sig, &sa, NULL) < 0)
2596                         r = -errno;
2597         va_end(ap);
2598
2599         return r;
2600 }
2601
2602 int default_signals(int sig, ...) {
2603         struct sigaction sa;
2604         va_list ap;
2605         int r = 0;
2606
2607         zero(sa);
2608         sa.sa_handler = SIG_DFL;
2609         sa.sa_flags = SA_RESTART;
2610
2611         if (sigaction(sig, &sa, NULL) < 0)
2612                 r = -errno;
2613
2614         va_start(ap, sig);
2615         while ((sig = va_arg(ap, int)) > 0)
2616                 if (sigaction(sig, &sa, NULL) < 0)
2617                         r = -errno;
2618         va_end(ap);
2619
2620         return r;
2621 }
2622
2623 int close_pipe(int p[]) {
2624         int a = 0, b = 0;
2625
2626         assert(p);
2627
2628         if (p[0] >= 0) {
2629                 a = close_nointr(p[0]);
2630                 p[0] = -1;
2631         }
2632
2633         if (p[1] >= 0) {
2634                 b = close_nointr(p[1]);
2635                 p[1] = -1;
2636         }
2637
2638         return a < 0 ? a : b;
2639 }
2640
2641 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2642         uint8_t *p;
2643         ssize_t n = 0;
2644
2645         assert(fd >= 0);
2646         assert(buf);
2647
2648         p = buf;
2649
2650         while (nbytes > 0) {
2651                 ssize_t k;
2652
2653                 if ((k = read(fd, p, nbytes)) <= 0) {
2654
2655                         if (k < 0 && errno == EINTR)
2656                                 continue;
2657
2658                         if (k < 0 && errno == EAGAIN && do_poll) {
2659                                 struct pollfd pollfd;
2660
2661                                 zero(pollfd);
2662                                 pollfd.fd = fd;
2663                                 pollfd.events = POLLIN;
2664
2665                                 if (poll(&pollfd, 1, -1) < 0) {
2666                                         if (errno == EINTR)
2667                                                 continue;
2668
2669                                         return n > 0 ? n : -errno;
2670                                 }
2671
2672                                 if (pollfd.revents != POLLIN)
2673                                         return n > 0 ? n : -EIO;
2674
2675                                 continue;
2676                         }
2677
2678                         return n > 0 ? n : (k < 0 ? -errno : 0);
2679                 }
2680
2681                 p += k;
2682                 nbytes -= k;
2683                 n += k;
2684         }
2685
2686         return n;
2687 }
2688
2689 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2690         const uint8_t *p;
2691         ssize_t n = 0;
2692
2693         assert(fd >= 0);
2694         assert(buf);
2695
2696         p = buf;
2697
2698         while (nbytes > 0) {
2699                 ssize_t k;
2700
2701                 if ((k = write(fd, p, nbytes)) <= 0) {
2702
2703                         if (k < 0 && errno == EINTR)
2704                                 continue;
2705
2706                         if (k < 0 && errno == EAGAIN && do_poll) {
2707                                 struct pollfd pollfd;
2708
2709                                 zero(pollfd);
2710                                 pollfd.fd = fd;
2711                                 pollfd.events = POLLOUT;
2712
2713                                 if (poll(&pollfd, 1, -1) < 0) {
2714                                         if (errno == EINTR)
2715                                                 continue;
2716
2717                                         return n > 0 ? n : -errno;
2718                                 }
2719
2720                                 if (pollfd.revents != POLLOUT)
2721                                         return n > 0 ? n : -EIO;
2722
2723                                 continue;
2724                         }
2725
2726                         return n > 0 ? n : (k < 0 ? -errno : 0);
2727                 }
2728
2729                 p += k;
2730                 nbytes -= k;
2731                 n += k;
2732         }
2733
2734         return n;
2735 }
2736
2737 int path_is_mount_point(const char *t) {
2738         struct stat a, b;
2739         char *parent;
2740         int r;
2741
2742         if (lstat(t, &a) < 0) {
2743                 if (errno == ENOENT)
2744                         return 0;
2745
2746                 return -errno;
2747         }
2748
2749         if ((r = parent_of_path(t, &parent)) < 0)
2750                 return r;
2751
2752         r = lstat(parent, &b);
2753         free(parent);
2754
2755         if (r < 0)
2756                 return -errno;
2757
2758         return a.st_dev != b.st_dev;
2759 }
2760
2761 int parse_usec(const char *t, usec_t *usec) {
2762         static const struct {
2763                 const char *suffix;
2764                 usec_t usec;
2765         } table[] = {
2766                 { "sec", USEC_PER_SEC },
2767                 { "s", USEC_PER_SEC },
2768                 { "min", USEC_PER_MINUTE },
2769                 { "hr", USEC_PER_HOUR },
2770                 { "h", USEC_PER_HOUR },
2771                 { "d", USEC_PER_DAY },
2772                 { "w", USEC_PER_WEEK },
2773                 { "msec", USEC_PER_MSEC },
2774                 { "ms", USEC_PER_MSEC },
2775                 { "m", USEC_PER_MINUTE },
2776                 { "usec", 1ULL },
2777                 { "us", 1ULL },
2778                 { "", USEC_PER_SEC },
2779         };
2780
2781         const char *p;
2782         usec_t r = 0;
2783
2784         assert(t);
2785         assert(usec);
2786
2787         p = t;
2788         do {
2789                 long long l;
2790                 char *e;
2791                 unsigned i;
2792
2793                 errno = 0;
2794                 l = strtoll(p, &e, 10);
2795
2796                 if (errno != 0)
2797                         return -errno;
2798
2799                 if (l < 0)
2800                         return -ERANGE;
2801
2802                 if (e == p)
2803                         return -EINVAL;
2804
2805                 e += strspn(e, WHITESPACE);
2806
2807                 for (i = 0; i < ELEMENTSOF(table); i++)
2808                         if (startswith(e, table[i].suffix)) {
2809                                 r += (usec_t) l * table[i].usec;
2810                                 p = e + strlen(table[i].suffix);
2811                                 break;
2812                         }
2813
2814                 if (i >= ELEMENTSOF(table))
2815                         return -EINVAL;
2816
2817         } while (*p != 0);
2818
2819         *usec = r;
2820
2821         return 0;
2822 }
2823
2824 int make_stdio(int fd) {
2825         int r, s, t;
2826
2827         assert(fd >= 0);
2828
2829         r = dup2(fd, STDIN_FILENO);
2830         s = dup2(fd, STDOUT_FILENO);
2831         t = dup2(fd, STDERR_FILENO);
2832
2833         if (fd >= 3)
2834                 close_nointr_nofail(fd);
2835
2836         if (r < 0 || s < 0 || t < 0)
2837                 return -errno;
2838
2839         return 0;
2840 }
2841
2842 int make_null_stdio(void) {
2843         int null_fd;
2844
2845         if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2846                 return -errno;
2847
2848         return make_stdio(null_fd);
2849 }
2850
2851 bool is_device_path(const char *path) {
2852
2853         /* Returns true on paths that refer to a device, either in
2854          * sysfs or in /dev */
2855
2856         return
2857                 path_startswith(path, "/dev/") ||
2858                 path_startswith(path, "/sys/");
2859 }
2860
2861 int dir_is_empty(const char *path) {
2862         DIR *d;
2863         int r;
2864         struct dirent buf, *de;
2865
2866         if (!(d = opendir(path)))
2867                 return -errno;
2868
2869         for (;;) {
2870                 if ((r = readdir_r(d, &buf, &de)) > 0) {
2871                         r = -r;
2872                         break;
2873                 }
2874
2875                 if (!de) {
2876                         r = 1;
2877                         break;
2878                 }
2879
2880                 if (!ignore_file(de->d_name)) {
2881                         r = 0;
2882                         break;
2883                 }
2884         }
2885
2886         closedir(d);
2887         return r;
2888 }
2889
2890 unsigned long long random_ull(void) {
2891         int fd;
2892         uint64_t ull;
2893         ssize_t r;
2894
2895         if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2896                 goto fallback;
2897
2898         r = loop_read(fd, &ull, sizeof(ull), true);
2899         close_nointr_nofail(fd);
2900
2901         if (r != sizeof(ull))
2902                 goto fallback;
2903
2904         return ull;
2905
2906 fallback:
2907         return random() * RAND_MAX + random();
2908 }
2909
2910 void rename_process(const char name[8]) {
2911         assert(name);
2912
2913         prctl(PR_SET_NAME, name);
2914
2915         /* This is a like a poor man's setproctitle(). The string
2916          * passed should fit in 7 chars (i.e. the length of
2917          * "systemd") */
2918
2919         if (program_invocation_name)
2920                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2921 }
2922
2923 void sigset_add_many(sigset_t *ss, ...) {
2924         va_list ap;
2925         int sig;
2926
2927         assert(ss);
2928
2929         va_start(ap, ss);
2930         while ((sig = va_arg(ap, int)) > 0)
2931                 assert_se(sigaddset(ss, sig) == 0);
2932         va_end(ap);
2933 }
2934
2935 char* gethostname_malloc(void) {
2936         struct utsname u;
2937
2938         assert_se(uname(&u) >= 0);
2939
2940         if (u.nodename[0])
2941                 return strdup(u.nodename);
2942
2943         return strdup(u.sysname);
2944 }
2945
2946 char* getlogname_malloc(void) {
2947         uid_t uid;
2948         long bufsize;
2949         char *buf, *name;
2950         struct passwd pwbuf, *pw = NULL;
2951         struct stat st;
2952
2953         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2954                 uid = st.st_uid;
2955         else
2956                 uid = getuid();
2957
2958         /* Shortcut things to avoid NSS lookups */
2959         if (uid == 0)
2960                 return strdup("root");
2961
2962         if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2963                 bufsize = 4096;
2964
2965         if (!(buf = malloc(bufsize)))
2966                 return NULL;
2967
2968         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2969                 name = strdup(pw->pw_name);
2970                 free(buf);
2971                 return name;
2972         }
2973
2974         free(buf);
2975
2976         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2977                 return NULL;
2978
2979         return name;
2980 }
2981
2982 int getttyname_malloc(int fd, char **r) {
2983         char path[PATH_MAX], *c;
2984         int k;
2985
2986         assert(r);
2987
2988         if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
2989                 return -k;
2990
2991         char_array_0(path);
2992
2993         if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
2994                 return -ENOMEM;
2995
2996         *r = c;
2997         return 0;
2998 }
2999
3000 int getttyname_harder(int fd, char **r) {
3001         int k;
3002         char *s;
3003
3004         if ((k = getttyname_malloc(fd, &s)) < 0)
3005                 return k;
3006
3007         if (streq(s, "tty")) {
3008                 free(s);
3009                 return get_ctty(r, NULL);
3010         }
3011
3012         *r = s;
3013         return 0;
3014 }
3015
3016 int get_ctty_devnr(dev_t *d) {
3017         int k;
3018         char line[LINE_MAX], *p;
3019         unsigned long ttynr;
3020         FILE *f;
3021
3022         if (!(f = fopen("/proc/self/stat", "r")))
3023                 return -errno;
3024
3025         if (!(fgets(line, sizeof(line), f))) {
3026                 k = -errno;
3027                 fclose(f);
3028                 return k;
3029         }
3030
3031         fclose(f);
3032
3033         if (!(p = strrchr(line, ')')))
3034                 return -EIO;
3035
3036         p++;
3037
3038         if (sscanf(p, " "
3039                    "%*c "  /* state */
3040                    "%*d "  /* ppid */
3041                    "%*d "  /* pgrp */
3042                    "%*d "  /* session */
3043                    "%lu ", /* ttynr */
3044                    &ttynr) != 1)
3045                 return -EIO;
3046
3047         *d = (dev_t) ttynr;
3048         return 0;
3049 }
3050
3051 int get_ctty(char **r, dev_t *_devnr) {
3052         int k;
3053         char fn[PATH_MAX], *s, *b, *p;
3054         dev_t devnr;
3055
3056         assert(r);
3057
3058         if ((k = get_ctty_devnr(&devnr)) < 0)
3059                 return k;
3060
3061         snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3062         char_array_0(fn);
3063
3064         if ((k = readlink_malloc(fn, &s)) < 0) {
3065
3066                 if (k != -ENOENT)
3067                         return k;
3068
3069                 /* This is an ugly hack */
3070                 if (major(devnr) == 136) {
3071                         if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3072                                 return -ENOMEM;
3073
3074                         *r = b;
3075                         if (_devnr)
3076                                 *_devnr = devnr;
3077
3078                         return 0;
3079                 }
3080
3081                 /* Probably something like the ptys which have no
3082                  * symlink in /dev/char. Let's return something
3083                  * vaguely useful. */
3084
3085                 if (!(b = strdup(fn + 5)))
3086                         return -ENOMEM;
3087
3088                 *r = b;
3089                 if (_devnr)
3090                         *_devnr = devnr;
3091
3092                 return 0;
3093         }
3094
3095         if (startswith(s, "/dev/"))
3096                 p = s + 5;
3097         else if (startswith(s, "../"))
3098                 p = s + 3;
3099         else
3100                 p = s;
3101
3102         b = strdup(p);
3103         free(s);
3104
3105         if (!b)
3106                 return -ENOMEM;
3107
3108         *r = b;
3109         if (_devnr)
3110                 *_devnr = devnr;
3111
3112         return 0;
3113 }
3114
3115 static int rm_rf_children(int fd, bool only_dirs) {
3116         DIR *d;
3117         int ret = 0;
3118
3119         assert(fd >= 0);
3120
3121         /* This returns the first error we run into, but nevertheless
3122          * tries to go on */
3123
3124         if (!(d = fdopendir(fd))) {
3125                 close_nointr_nofail(fd);
3126
3127                 return errno == ENOENT ? 0 : -errno;
3128         }
3129
3130         for (;;) {
3131                 struct dirent buf, *de;
3132                 bool is_dir;
3133                 int r;
3134
3135                 if ((r = readdir_r(d, &buf, &de)) != 0) {
3136                         if (ret == 0)
3137                                 ret = -r;
3138                         break;
3139                 }
3140
3141                 if (!de)
3142                         break;
3143
3144                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3145                         continue;
3146
3147                 if (de->d_type == DT_UNKNOWN) {
3148                         struct stat st;
3149
3150                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3151                                 if (ret == 0 && errno != ENOENT)
3152                                         ret = -errno;
3153                                 continue;
3154                         }
3155
3156                         is_dir = S_ISDIR(st.st_mode);
3157                 } else
3158                         is_dir = de->d_type == DT_DIR;
3159
3160                 if (is_dir) {
3161                         int subdir_fd;
3162
3163                         if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3164                                 if (ret == 0 && errno != ENOENT)
3165                                         ret = -errno;
3166                                 continue;
3167                         }
3168
3169                         if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3170                                 if (ret == 0)
3171                                         ret = r;
3172                         }
3173
3174                         if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3175                                 if (ret == 0 && errno != ENOENT)
3176                                         ret = -errno;
3177                         }
3178                 } else  if (!only_dirs) {
3179
3180                         if (unlinkat(fd, de->d_name, 0) < 0) {
3181                                 if (ret == 0 && errno != ENOENT)
3182                                         ret = -errno;
3183                         }
3184                 }
3185         }
3186
3187         closedir(d);
3188
3189         return ret;
3190 }
3191
3192 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3193         int fd;
3194         int r;
3195
3196         assert(path);
3197
3198         if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3199
3200                 if (errno != ENOTDIR)
3201                         return -errno;
3202
3203                 if (delete_root && !only_dirs)
3204                         if (unlink(path) < 0)
3205                                 return -errno;
3206
3207                 return 0;
3208         }
3209
3210         r = rm_rf_children(fd, only_dirs);
3211
3212         if (delete_root)
3213                 if (rmdir(path) < 0) {
3214                         if (r == 0)
3215                                 r = -errno;
3216                 }
3217
3218         return r;
3219 }
3220
3221 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3222         assert(path);
3223
3224         /* Under the assumption that we are running privileged we
3225          * first change the access mode and only then hand out
3226          * ownership to avoid a window where access is too open. */
3227
3228         if (chmod(path, mode) < 0)
3229                 return -errno;
3230
3231         if (chown(path, uid, gid) < 0)
3232                 return -errno;
3233
3234         return 0;
3235 }
3236
3237 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3238         cpu_set_t *r;
3239         unsigned n = 1024;
3240
3241         /* Allocates the cpuset in the right size */
3242
3243         for (;;) {
3244                 if (!(r = CPU_ALLOC(n)))
3245                         return NULL;
3246
3247                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3248                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3249
3250                         if (ncpus)
3251                                 *ncpus = n;
3252
3253                         return r;
3254                 }
3255
3256                 CPU_FREE(r);
3257
3258                 if (errno != EINVAL)
3259                         return NULL;
3260
3261                 n *= 2;
3262         }
3263 }
3264
3265 void status_vprintf(const char *format, va_list ap) {
3266         char *s = NULL;
3267         int fd = -1;
3268
3269         assert(format);
3270
3271         /* This independent of logging, as status messages are
3272          * optional and go exclusively to the console. */
3273
3274         if (vasprintf(&s, format, ap) < 0)
3275                 goto finish;
3276
3277         if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3278                 goto finish;
3279
3280         write(fd, s, strlen(s));
3281
3282 finish:
3283         free(s);
3284
3285         if (fd >= 0)
3286                 close_nointr_nofail(fd);
3287 }
3288
3289 void status_printf(const char *format, ...) {
3290         va_list ap;
3291
3292         assert(format);
3293
3294         va_start(ap, format);
3295         status_vprintf(format, ap);
3296         va_end(ap);
3297 }
3298
3299 void status_welcome(void) {
3300         char *pretty_name = NULL, *ansi_color = NULL;
3301         const char *const_pretty = NULL, *const_color = NULL;
3302         int r;
3303
3304         if ((r = parse_env_file("/etc/os-release", NEWLINE,
3305                                 "PRETTY_NAME", &pretty_name,
3306                                 "ANSI_COLOR", &ansi_color,
3307                                 NULL)) < 0) {
3308
3309                 if (r != -ENOENT)
3310                         log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3311         }
3312
3313 #if defined(TARGET_FEDORA)
3314         if (!pretty_name) {
3315                 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3316
3317                         if (r != -ENOENT)
3318                                 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3319                 }
3320         }
3321
3322         if (!ansi_color && pretty_name) {
3323
3324                 /* This tries to mimic the color magic the old Red Hat sysinit
3325                  * script did. */
3326
3327                 if (startswith(pretty_name, "Red Hat"))
3328                         const_color = "0;31"; /* Red for RHEL */
3329                 else if (startswith(pretty_name, "Fedora"))
3330                         const_color = "0;34"; /* Blue for Fedora */
3331         }
3332
3333 #elif defined(TARGET_SUSE)
3334
3335         if (!pretty_name) {
3336                 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3337
3338                         if (r != -ENOENT)
3339                                 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3340                 }
3341         }
3342
3343         if (!ansi_color)
3344                 const_color = "0;32"; /* Green for openSUSE */
3345
3346 #elif defined(TARGET_GENTOO)
3347
3348         if (!pretty_name) {
3349                 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3350
3351                         if (r != -ENOENT)
3352                                 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3353                 }
3354         }
3355
3356         if (!ansi_color)
3357                 const_color = "1;34"; /* Light Blue for Gentoo */
3358
3359 #elif defined(TARGET_ALTLINUX)
3360
3361         if (!pretty_name) {
3362                 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3363
3364                         if (r != -ENOENT)
3365                                 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3366                 }
3367         }
3368
3369         if (!ansi_color)
3370                 const_color = "0;36"; /* Cyan for ALTLinux */
3371
3372
3373 #elif defined(TARGET_DEBIAN)
3374
3375         if (!pretty_name) {
3376                 char *version;
3377
3378                 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3379
3380                         if (r != -ENOENT)
3381                                 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3382                 } else {
3383                         pretty_name = strappend("Debian ", version);
3384                         free(version);
3385
3386                         if (!pretty_name)
3387                                 log_warning("Failed to allocate Debian version string.");
3388                 }
3389         }
3390
3391         if (!ansi_color)
3392                 const_color = "1;31"; /* Light Red for Debian */
3393
3394 #elif defined(TARGET_UBUNTU)
3395
3396         if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3397                                 "DISTRIB_DESCRIPTION", &pretty_name,
3398                                 NULL)) < 0) {
3399
3400                 if (r != -ENOENT)
3401                         log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3402         }
3403
3404         if (!ansi_color)
3405                 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3406
3407 #elif defined(TARGET_MANDRIVA)
3408
3409         if (!pretty_name) {
3410                 char *s, *p;
3411
3412                 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3413                         if (r != -ENOENT)
3414                                 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3415                 } else {
3416                         p = strstr(s, " release ");
3417                         if (p) {
3418                                 *p = '\0';
3419                                 p += 9;
3420                                 p[strcspn(p, " ")] = '\0';
3421
3422                                 /* This corresponds to standard rc.sysinit */
3423                                 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3424                                         const_color = "1;36";
3425                                 else
3426                                         log_warning("Failed to allocate Mandriva version string.");
3427                         } else
3428                                 log_warning("Failed to parse /etc/mandriva-release");
3429                         free(s);
3430                 }
3431         }
3432 #elif defined(TARGET_MEEGO)
3433
3434         if (!pretty_name) {
3435                 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3436
3437                         if (r != -ENOENT)
3438                                 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3439                 }
3440         }
3441
3442        if (!ansi_color)
3443                const_color = "1;35"; /* Bright Magenta for MeeGo */
3444 #endif
3445
3446         if (!pretty_name && !const_pretty)
3447                 const_pretty = "Linux";
3448
3449         if (!ansi_color && !const_color)
3450                 const_color = "1";
3451
3452         status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3453                       const_color ? const_color : ansi_color,
3454                       const_pretty ? const_pretty : pretty_name);
3455
3456         free(ansi_color);
3457         free(pretty_name);
3458 }
3459
3460 char *replace_env(const char *format, char **env) {
3461         enum {
3462                 WORD,
3463                 CURLY,
3464                 VARIABLE
3465         } state = WORD;
3466
3467         const char *e, *word = format;
3468         char *r = NULL, *k;
3469
3470         assert(format);
3471
3472         for (e = format; *e; e ++) {
3473
3474                 switch (state) {
3475
3476                 case WORD:
3477                         if (*e == '$')
3478                                 state = CURLY;
3479                         break;
3480
3481                 case CURLY:
3482                         if (*e == '{') {
3483                                 if (!(k = strnappend(r, word, e-word-1)))
3484                                         goto fail;
3485
3486                                 free(r);
3487                                 r = k;
3488
3489                                 word = e-1;
3490                                 state = VARIABLE;
3491
3492                         } else if (*e == '$') {
3493                                 if (!(k = strnappend(r, word, e-word)))
3494                                         goto fail;
3495
3496                                 free(r);
3497                                 r = k;
3498
3499                                 word = e+1;
3500                                 state = WORD;
3501                         } else
3502                                 state = WORD;
3503                         break;
3504
3505                 case VARIABLE:
3506                         if (*e == '}') {
3507                                 const char *t;
3508
3509                                 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3510                                         t = "";
3511
3512                                 if (!(k = strappend(r, t)))
3513                                         goto fail;
3514
3515                                 free(r);
3516                                 r = k;
3517
3518                                 word = e+1;
3519                                 state = WORD;
3520                         }
3521                         break;
3522                 }
3523         }
3524
3525         if (!(k = strnappend(r, word, e-word)))
3526                 goto fail;
3527
3528         free(r);
3529         return k;
3530
3531 fail:
3532         free(r);
3533         return NULL;
3534 }
3535
3536 char **replace_env_argv(char **argv, char **env) {
3537         char **r, **i;
3538         unsigned k = 0, l = 0;
3539
3540         l = strv_length(argv);
3541
3542         if (!(r = new(char*, l+1)))
3543                 return NULL;
3544
3545         STRV_FOREACH(i, argv) {
3546
3547                 /* If $FOO appears as single word, replace it by the split up variable */
3548                 if ((*i)[0] == '$' && (*i)[1] != '{') {
3549                         char *e;
3550                         char **w, **m;
3551                         unsigned q;
3552
3553                         if ((e = strv_env_get(env, *i+1))) {
3554
3555                                 if (!(m = strv_split_quoted(e))) {
3556                                         r[k] = NULL;
3557                                         strv_free(r);
3558                                         return NULL;
3559                                 }
3560                         } else
3561                                 m = NULL;
3562
3563                         q = strv_length(m);
3564                         l = l + q - 1;
3565
3566                         if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3567                                 r[k] = NULL;
3568                                 strv_free(r);
3569                                 strv_free(m);
3570                                 return NULL;
3571                         }
3572
3573                         r = w;
3574                         if (m) {
3575                                 memcpy(r + k, m, q * sizeof(char*));
3576                                 free(m);
3577                         }
3578
3579                         k += q;
3580                         continue;
3581                 }
3582
3583                 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3584                 if (!(r[k++] = replace_env(*i, env))) {
3585                         strv_free(r);
3586                         return NULL;
3587                 }
3588         }
3589
3590         r[k] = NULL;
3591         return r;
3592 }
3593
3594 int columns(void) {
3595         static __thread int parsed_columns = 0;
3596         const char *e;
3597
3598         if (parsed_columns > 0)
3599                 return parsed_columns;
3600
3601         if ((e = getenv("COLUMNS")))
3602                 parsed_columns = atoi(e);
3603
3604         if (parsed_columns <= 0) {
3605                 struct winsize ws;
3606                 zero(ws);
3607
3608                 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3609                         parsed_columns = ws.ws_col;
3610         }
3611
3612         if (parsed_columns <= 0)
3613                 parsed_columns = 80;
3614
3615         return parsed_columns;
3616 }
3617
3618 int running_in_chroot(void) {
3619         struct stat a, b;
3620
3621         zero(a);
3622         zero(b);
3623
3624         /* Only works as root */
3625
3626         if (stat("/proc/1/root", &a) < 0)
3627                 return -errno;
3628
3629         if (stat("/", &b) < 0)
3630                 return -errno;
3631
3632         return
3633                 a.st_dev != b.st_dev ||
3634                 a.st_ino != b.st_ino;
3635 }
3636
3637 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3638         size_t l, x;
3639         char *r;
3640
3641         assert(s);
3642         assert(percent <= 100);
3643         assert(length >= 3);
3644
3645         l = strlen(s);
3646
3647         if (l <= 3 || l <= length)
3648                 return strdup(s);
3649
3650         if (!(r = new0(char, length+1)))
3651                 return r;
3652
3653         x = (length * percent) / 100;
3654
3655         if (x > length - 3)
3656                 x = length - 3;
3657
3658         memcpy(r, s, x);
3659         r[x] = '.';
3660         r[x+1] = '.';
3661         r[x+2] = '.';
3662         memcpy(r + x + 3,
3663                s + l - (length - x - 3),
3664                length - x - 3);
3665
3666         return r;
3667 }
3668
3669 int touch(const char *path) {
3670         int fd;
3671
3672         assert(path);
3673
3674         if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3675                 return -errno;
3676
3677         close_nointr_nofail(fd);
3678         return 0;
3679 }
3680
3681 char *unquote(const char *s, const char* quotes) {
3682         size_t l;
3683         assert(s);
3684
3685         if ((l = strlen(s)) < 2)
3686                 return strdup(s);
3687
3688         if (strchr(quotes, s[0]) && s[l-1] == s[0])
3689                 return strndup(s+1, l-2);
3690
3691         return strdup(s);
3692 }
3693
3694 char *normalize_env_assignment(const char *s) {
3695         char *name, *value, *p, *r;
3696
3697         p = strchr(s, '=');
3698
3699         if (!p) {
3700                 if (!(r = strdup(s)))
3701                         return NULL;
3702
3703                 return strstrip(r);
3704         }
3705
3706         if (!(name = strndup(s, p - s)))
3707                 return NULL;
3708
3709         if (!(p = strdup(p+1))) {
3710                 free(name);
3711                 return NULL;
3712         }
3713
3714         value = unquote(strstrip(p), QUOTES);
3715         free(p);
3716
3717         if (!value) {
3718                 free(name);
3719                 return NULL;
3720         }
3721
3722         if (asprintf(&r, "%s=%s", name, value) < 0)
3723                 r = NULL;
3724
3725         free(value);
3726         free(name);
3727
3728         return r;
3729 }
3730
3731 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3732         assert(pid >= 1);
3733         assert(status);
3734
3735         for (;;) {
3736                 zero(*status);
3737
3738                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3739
3740                         if (errno == EINTR)
3741                                 continue;
3742
3743                         return -errno;
3744                 }
3745
3746                 return 0;
3747         }
3748 }
3749
3750 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3751         int r;
3752         siginfo_t status;
3753
3754         assert(name);
3755         assert(pid > 1);
3756
3757         if ((r = wait_for_terminate(pid, &status)) < 0) {
3758                 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3759                 return r;
3760         }
3761
3762         if (status.si_code == CLD_EXITED) {
3763                 if (status.si_status != 0) {
3764                         log_warning("%s failed with error code %i.", name, status.si_status);
3765                         return status.si_status;
3766                 }
3767
3768                 log_debug("%s succeeded.", name);
3769                 return 0;
3770
3771         } else if (status.si_code == CLD_KILLED ||
3772                    status.si_code == CLD_DUMPED) {
3773
3774                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3775                 return -EPROTO;
3776         }
3777
3778         log_warning("%s failed due to unknown reason.", name);
3779         return -EPROTO;
3780
3781 }
3782
3783 void freeze(void) {
3784
3785         /* Make sure nobody waits for us on a socket anymore */
3786         close_all_fds(NULL, 0);
3787
3788         sync();
3789
3790         for (;;)
3791                 pause();
3792 }
3793
3794 bool null_or_empty(struct stat *st) {
3795         assert(st);
3796
3797         if (S_ISREG(st->st_mode) && st->st_size <= 0)
3798                 return true;
3799
3800         if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3801                 return true;
3802
3803         return false;
3804 }
3805
3806 DIR *xopendirat(int fd, const char *name, int flags) {
3807         int nfd;
3808         DIR *d;
3809
3810         if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3811                 return NULL;
3812
3813         if (!(d = fdopendir(nfd))) {
3814                 close_nointr_nofail(nfd);
3815                 return NULL;
3816         }
3817
3818         return d;
3819 }
3820
3821 int signal_from_string_try_harder(const char *s) {
3822         int signo;
3823         assert(s);
3824
3825         if ((signo = signal_from_string(s)) <= 0)
3826                 if (startswith(s, "SIG"))
3827                         return signal_from_string(s+3);
3828
3829         return signo;
3830 }
3831
3832 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3833
3834         assert(f);
3835         assert(name);
3836         assert(t);
3837
3838         if (!dual_timestamp_is_set(t))
3839                 return;
3840
3841         fprintf(f, "%s=%llu %llu\n",
3842                 name,
3843                 (unsigned long long) t->realtime,
3844                 (unsigned long long) t->monotonic);
3845 }
3846
3847 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3848         unsigned long long a, b;
3849
3850         assert(value);
3851         assert(t);
3852
3853         if (sscanf(value, "%lli %llu", &a, &b) != 2)
3854                 log_debug("Failed to parse finish timestamp value %s", value);
3855         else {
3856                 t->realtime = a;
3857                 t->monotonic = b;
3858         }
3859 }
3860
3861 char *fstab_node_to_udev_node(const char *p) {
3862         char *dn, *t, *u;
3863         int r;
3864
3865         /* FIXME: to follow udev's logic 100% we need to leave valid
3866          * UTF8 chars unescaped */
3867
3868         if (startswith(p, "LABEL=")) {
3869
3870                 if (!(u = unquote(p+6, "\"\'")))
3871                         return NULL;
3872
3873                 t = xescape(u, "/ ");
3874                 free(u);
3875
3876                 if (!t)
3877                         return NULL;
3878
3879                 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3880                 free(t);
3881
3882                 if (r < 0)
3883                         return NULL;
3884
3885                 return dn;
3886         }
3887
3888         if (startswith(p, "UUID=")) {
3889
3890                 if (!(u = unquote(p+5, "\"\'")))
3891                         return NULL;
3892
3893                 t = xescape(u, "/ ");
3894                 free(u);
3895
3896                 if (!t)
3897                         return NULL;
3898
3899                 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
3900                 free(t);
3901
3902                 if (r < 0)
3903                         return NULL;
3904
3905                 return dn;
3906         }
3907
3908         return strdup(p);
3909 }
3910
3911 void filter_environ(const char *prefix) {
3912         int i, j;
3913         assert(prefix);
3914
3915         if (!environ)
3916                 return;
3917
3918         for (i = 0, j = 0; environ[i]; i++) {
3919
3920                 if (startswith(environ[i], prefix))
3921                         continue;
3922
3923                 environ[j++] = environ[i];
3924         }
3925
3926         environ[j] = NULL;
3927 }
3928
3929 bool tty_is_vc(const char *tty) {
3930         assert(tty);
3931
3932         if (startswith(tty, "/dev/"))
3933                 tty += 5;
3934
3935         return startswith(tty, "tty") &&
3936                 tty[3] >= '0' && tty[3] <= '9';
3937 }
3938
3939 const char *default_term_for_tty(const char *tty) {
3940         char *active = NULL;
3941         const char *term;
3942
3943         assert(tty);
3944
3945         if (startswith(tty, "/dev/"))
3946                 tty += 5;
3947
3948         /* Resolve where /dev/console is pointing when determining
3949          * TERM */
3950         if (streq(tty, "console"))
3951                 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3952                         /* If multiple log outputs are configured the
3953                          * last one is what /dev/console points to */
3954                         if ((tty = strrchr(active, ' ')))
3955                                 tty++;
3956                         else
3957                                 tty = active;
3958                 }
3959
3960         term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
3961         free(active);
3962
3963         return term;
3964 }
3965
3966 /* Returns a short identifier for the various VM implementations */
3967 int detect_vm(const char **id) {
3968
3969 #if defined(__i386__) || defined(__x86_64__)
3970
3971         /* Both CPUID and DMI are x86 specific interfaces... */
3972
3973         static const char *const dmi_vendors[] = {
3974                 "/sys/class/dmi/id/sys_vendor",
3975                 "/sys/class/dmi/id/board_vendor",
3976                 "/sys/class/dmi/id/bios_vendor"
3977         };
3978
3979         static const char dmi_vendor_table[] =
3980                 "QEMU\0"                  "qemu\0"
3981                 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3982                 "VMware\0"                "vmware\0"
3983                 "VMW\0"                   "vmware\0"
3984                 "Microsoft Corporation\0" "microsoft\0"
3985                 "innotek GmbH\0"          "oracle\0"
3986                 "Xen\0"                   "xen\0"
3987                 "Bochs\0"                 "bochs\0";
3988
3989         static const char cpuid_vendor_table[] =
3990                 "XenVMMXenVMM\0"          "xen\0"
3991                 "KVMKVMKVM\0"             "kvm\0"
3992                 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3993                 "VMwareVMware\0"          "vmware\0"
3994                 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
3995                 "Microsoft Hv\0"          "microsoft\0";
3996
3997         uint32_t eax, ecx;
3998         union {
3999                 uint32_t sig32[3];
4000                 char text[13];
4001         } sig;
4002         unsigned i;
4003         const char *j, *k;
4004         bool hypervisor;
4005
4006         /* http://lwn.net/Articles/301888/ */
4007         zero(sig);
4008
4009 #if defined (__i386__)
4010 #define REG_a "eax"
4011 #define REG_b "ebx"
4012 #elif defined (__amd64__)
4013 #define REG_a "rax"
4014 #define REG_b "rbx"
4015 #endif
4016
4017         /* First detect whether there is a hypervisor */
4018         eax = 1;
4019         __asm__ __volatile__ (
4020                 /* ebx/rbx is being used for PIC! */
4021                 "  push %%"REG_b"         \n\t"
4022                 "  cpuid                  \n\t"
4023                 "  pop %%"REG_b"          \n\t"
4024
4025                 : "=a" (eax), "=c" (ecx)
4026                 : "0" (eax)
4027         );
4028
4029         hypervisor = !!(ecx & 0x80000000U);
4030
4031         if (hypervisor) {
4032
4033                 /* There is a hypervisor, see what it is */
4034                 eax = 0x40000000U;
4035                 __asm__ __volatile__ (
4036                         /* ebx/rbx is being used for PIC! */
4037                         "  push %%"REG_b"         \n\t"
4038                         "  cpuid                  \n\t"
4039                         "  mov %%ebx, %1          \n\t"
4040                         "  pop %%"REG_b"          \n\t"
4041
4042                         : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
4043                         : "0" (eax)
4044                 );
4045
4046                 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
4047                         if (streq(sig.text, j)) {
4048
4049                                 if (id)
4050                                         *id = k;
4051
4052                                 return 1;
4053                         }
4054         }
4055
4056         for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
4057                 char *s;
4058                 int r;
4059                 const char *found = NULL;
4060
4061                 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
4062                         if (r != -ENOENT)
4063                                 return r;
4064
4065                         continue;
4066                 }
4067
4068                 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
4069                         if (startswith(s, j))
4070                                 found = k;
4071                 free(s);
4072
4073                 if (found) {
4074                         if (id)
4075                                 *id = found;
4076
4077                         return 1;
4078                 }
4079         }
4080
4081         if (hypervisor) {
4082                 if (id)
4083                         *id = "other";
4084
4085                 return 1;
4086         }
4087
4088 #endif
4089         return 0;
4090 }
4091
4092 int detect_container(const char **id) {
4093         FILE *f;
4094
4095         /* Unfortunately many of these operations require root access
4096          * in one way or another */
4097
4098         if (geteuid() != 0)
4099                 return -EPERM;
4100
4101         if (running_in_chroot() > 0) {
4102
4103                 if (id)
4104                         *id = "chroot";
4105
4106                 return 1;
4107         }
4108
4109         /* /proc/vz exists in container and outside of the container,
4110          * /proc/bc only outside of the container. */
4111         if (access("/proc/vz", F_OK) >= 0 &&
4112             access("/proc/bc", F_OK) < 0) {
4113
4114                 if (id)
4115                         *id = "openvz";
4116
4117                 return 1;
4118         }
4119
4120         if ((f = fopen("/proc/self/cgroup", "r"))) {
4121
4122                 for (;;) {
4123                         char line[LINE_MAX], *p;
4124
4125                         if (!fgets(line, sizeof(line), f))
4126                                 break;
4127
4128                         if (!(p = strchr(strstrip(line), ':')))
4129                                 continue;
4130
4131                         if (strncmp(p, ":ns:", 4))
4132                                 continue;
4133
4134                         if (!streq(p, ":ns:/")) {
4135                                 fclose(f);
4136
4137                                 if (id)
4138                                         *id = "pidns";
4139
4140                                 return 1;
4141                         }
4142                 }
4143
4144                 fclose(f);
4145         }
4146
4147         return 0;
4148 }
4149
4150 /* Returns a short identifier for the various VM/container implementations */
4151 int detect_virtualization(const char **id) {
4152         static __thread const char *cached_id = NULL;
4153         const char *_id;
4154         int r;
4155
4156         if (cached_id) {
4157
4158                 if (cached_id == (const char*) -1)
4159                         return 0;
4160
4161                 if (id)
4162                         *id = cached_id;
4163
4164                 return 1;
4165         }
4166
4167         if ((r = detect_container(&_id)) != 0)
4168                 goto finish;
4169
4170         r = detect_vm(&_id);
4171
4172 finish:
4173         if (r > 0) {
4174                 cached_id = _id;
4175
4176                 if (id)
4177                         *id = _id;
4178         } else if (r == 0)
4179                 cached_id = (const char*) -1;
4180
4181         return r;
4182 }
4183
4184 bool dirent_is_file(struct dirent *de) {
4185         assert(de);
4186
4187         if (ignore_file(de->d_name))
4188                 return false;
4189
4190         if (de->d_type != DT_REG &&
4191             de->d_type != DT_LNK &&
4192             de->d_type != DT_UNKNOWN)
4193                 return false;
4194
4195         return true;
4196 }
4197
4198 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4199         DIR *_d = NULL;
4200         struct dirent *de;
4201         Hashmap *pids = NULL;
4202
4203         assert(directory);
4204
4205         /* Executes all binaries in a directory in parallel and waits
4206          * until all they all finished. */
4207
4208         if (!d) {
4209                 if (!(_d = opendir(directory))) {
4210
4211                         if (errno == ENOENT)
4212                                 return;
4213
4214                         log_error("Failed to enumerate directory %s: %m", directory);
4215                         return;
4216                 }
4217
4218                 d = _d;
4219         }
4220
4221         if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4222                 log_error("Failed to allocate set.");
4223                 goto finish;
4224         }
4225
4226         while ((de = readdir(d))) {
4227                 char *path;
4228                 pid_t pid;
4229                 int k;
4230
4231                 if (!dirent_is_file(de))
4232                         continue;
4233
4234                 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4235                         log_error("Out of memory");
4236                         continue;
4237                 }
4238
4239                 if ((pid = fork()) < 0) {
4240                         log_error("Failed to fork: %m");
4241                         free(path);
4242                         continue;
4243                 }
4244
4245                 if (pid == 0) {
4246                         char *_argv[2];
4247                         /* Child */
4248
4249                         if (!argv) {
4250                                 _argv[0] = path;
4251                                 _argv[1] = NULL;
4252                                 argv = _argv;
4253                         } else
4254                                 if (!argv[0])
4255                                         argv[0] = path;
4256
4257                         execv(path, argv);
4258
4259                         log_error("Failed to execute %s: %m", path);
4260                         _exit(EXIT_FAILURE);
4261                 }
4262
4263                 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4264
4265                 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4266                         log_error("Failed to add PID to set: %s", strerror(-k));
4267                         free(path);
4268                 }
4269         }
4270
4271         while (!hashmap_isempty(pids)) {
4272                 siginfo_t si;
4273                 char *path;
4274
4275                 zero(si);
4276                 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4277
4278                         if (errno == EINTR)
4279                                 continue;
4280
4281                         log_error("waitid() failed: %m");
4282                         goto finish;
4283                 }
4284
4285                 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4286                         if (!is_clean_exit(si.si_code, si.si_status)) {
4287                                 if (si.si_code == CLD_EXITED)
4288                                         log_error("%s exited with exit status %i.", path, si.si_status);
4289                                 else
4290                                         log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4291                         } else
4292                                 log_debug("%s exited successfully.", path);
4293
4294                         free(path);
4295                 }
4296         }
4297
4298 finish:
4299         if (_d)
4300                 closedir(_d);
4301
4302         if (pids)
4303                 hashmap_free_free(pids);
4304 }
4305
4306 int kill_and_sigcont(pid_t pid, int sig) {
4307         int r;
4308
4309         r = kill(pid, sig) < 0 ? -errno : 0;
4310
4311         if (r >= 0)
4312                 kill(pid, SIGCONT);
4313
4314         return r;
4315 }
4316
4317 bool nulstr_contains(const char*nulstr, const char *needle) {
4318         const char *i;
4319
4320         if (!nulstr)
4321                 return false;
4322
4323         NULSTR_FOREACH(i, nulstr)
4324                 if (streq(i, needle))
4325                         return true;
4326
4327         return false;
4328 }
4329
4330 bool plymouth_running(void) {
4331         return access("/run/plymouth/pid", F_OK) >= 0;
4332 }
4333
4334 void parse_syslog_priority(char **p, int *priority) {
4335         int a = 0, b = 0, c = 0;
4336         int k;
4337
4338         assert(p);
4339         assert(*p);
4340         assert(priority);
4341
4342         if ((*p)[0] != '<')
4343                 return;
4344
4345         if (!strchr(*p, '>'))
4346                 return;
4347
4348         if ((*p)[2] == '>') {
4349                 c = undecchar((*p)[1]);
4350                 k = 3;
4351         } else if ((*p)[3] == '>') {
4352                 b = undecchar((*p)[1]);
4353                 c = undecchar((*p)[2]);
4354                 k = 4;
4355         } else if ((*p)[4] == '>') {
4356                 a = undecchar((*p)[1]);
4357                 b = undecchar((*p)[2]);
4358                 c = undecchar((*p)[3]);
4359                 k = 5;
4360         } else
4361                 return;
4362
4363         if (a < 0 || b < 0 || c < 0)
4364                 return;
4365
4366         *priority = a*100+b*10+c;
4367         *p += k;
4368 }
4369
4370 int have_effective_cap(int value) {
4371         cap_t cap;
4372         cap_flag_value_t fv;
4373         int r;
4374
4375         if (!(cap = cap_get_proc()))
4376                 return -errno;
4377
4378         if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4379                 r = -errno;
4380         else
4381                 r = fv == CAP_SET;
4382
4383         cap_free(cap);
4384         return r;
4385 }
4386
4387 char* strshorten(char *s, size_t l) {
4388         assert(s);
4389
4390         if (l < strlen(s))
4391                 s[l] = 0;
4392
4393         return s;
4394 }
4395
4396 static bool hostname_valid_char(char c) {
4397         return
4398                 (c >= 'a' && c <= 'z') ||
4399                 (c >= 'A' && c <= 'Z') ||
4400                 (c >= '0' && c <= '9') ||
4401                 c == '-' ||
4402                 c == '_' ||
4403                 c == '.';
4404 }
4405
4406 bool hostname_is_valid(const char *s) {
4407         const char *p;
4408
4409         if (isempty(s))
4410                 return false;
4411
4412         for (p = s; *p; p++)
4413                 if (!hostname_valid_char(*p))
4414                         return false;
4415
4416         if (p-s > HOST_NAME_MAX)
4417                 return false;
4418
4419         return true;
4420 }
4421
4422 char* hostname_cleanup(char *s) {
4423         char *p, *d;
4424
4425         for (p = s, d = s; *p; p++)
4426                 if ((*p >= 'a' && *p <= 'z') ||
4427                     (*p >= 'A' && *p <= 'Z') ||
4428                     (*p >= '0' && *p <= '9') ||
4429                     *p == '-' ||
4430                     *p == '_' ||
4431                     *p == '.')
4432                         *(d++) = *p;
4433
4434         *d = 0;
4435
4436         strshorten(s, HOST_NAME_MAX);
4437         return s;
4438 }
4439
4440 int pipe_eof(int fd) {
4441         struct pollfd pollfd;
4442         int r;
4443
4444         zero(pollfd);
4445         pollfd.fd = fd;
4446         pollfd.events = POLLIN|POLLHUP;
4447
4448         r = poll(&pollfd, 1, 0);
4449         if (r < 0)
4450                 return -errno;
4451
4452         if (r == 0)
4453                 return 0;
4454
4455         return pollfd.revents & POLLHUP;
4456 }
4457
4458 int terminal_vhangup_fd(int fd) {
4459         if (ioctl(fd, TIOCVHANGUP) < 0)
4460                 return -errno;
4461
4462         return 0;
4463 }
4464
4465 int terminal_vhangup(const char *name) {
4466         int fd, r;
4467
4468         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4469         if (fd < 0)
4470                 return fd;
4471
4472         r = terminal_vhangup_fd(fd);
4473         close_nointr_nofail(fd);
4474
4475         return r;
4476 }
4477
4478 int vt_disallocate(const char *name) {
4479         int fd, r;
4480         unsigned u;
4481
4482         /* Deallocate the VT if possible. If not possible
4483          * (i.e. because it is the active one), at least clear it
4484          * entirely (including the scrollback buffer) */
4485
4486         if (!startswith(name, "/dev/"))
4487                 return -EINVAL;
4488
4489         if (!tty_is_vc(name)) {
4490                 /* So this is not a VT. I guess we cannot deallocate
4491                  * it then. But let's at least clear the screen */
4492
4493                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4494                 if (fd < 0)
4495                         return fd;
4496
4497                 loop_write(fd, "\033[H\033[2J", 7, false); /* clear screen */
4498                 close_nointr_nofail(fd);
4499
4500                 return 0;
4501         }
4502
4503         if (!startswith(name, "/dev/tty"))
4504                 return -EINVAL;
4505
4506         r = safe_atou(name+8, &u);
4507         if (r < 0)
4508                 return r;
4509
4510         if (u <= 0)
4511                 return -EINVAL;
4512
4513         /* Try to deallocate */
4514         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4515         if (fd < 0)
4516                 return fd;
4517
4518         r = ioctl(fd, VT_DISALLOCATE, u);
4519         close_nointr_nofail(fd);
4520
4521         if (r >= 0)
4522                 return 0;
4523
4524         if (errno != EBUSY)
4525                 return -errno;
4526
4527         /* Couldn't deallocate, so let's clear it fully with
4528          * scrollback */
4529         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4530         if (fd < 0)
4531                 return fd;
4532
4533         /* Requires Linux 2.6.40 */
4534         loop_write(fd, "\033[H\033[3J", 7, false); /* clear screen including scrollback */
4535         close_nointr_nofail(fd);
4536
4537         return 0;
4538 }
4539
4540
4541 static int file_is_conf(const struct dirent *d, const char *suffix) {
4542         assert(d);
4543
4544         if (ignore_file(d->d_name))
4545                 return 0;
4546
4547         if (d->d_type != DT_REG &&
4548             d->d_type != DT_LNK &&
4549             d->d_type != DT_UNKNOWN)
4550                 return 0;
4551
4552         return endswith(d->d_name, suffix);
4553 }
4554
4555 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4556         DIR *dir;
4557         struct dirent *de;
4558         int r = 0;
4559
4560         dir = opendir(path);
4561         if (!dir) {
4562                 if (errno == ENOENT)
4563                         return 0;
4564                 return -errno;
4565         }
4566
4567         for (de = readdir(dir); de; de = readdir(dir)) {
4568                 char *p, *f;
4569                 const char *base;
4570
4571                 if (!file_is_conf(de, suffix))
4572                         continue;
4573
4574                 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4575                         r = -ENOMEM;
4576                         goto finish;
4577                 }
4578
4579                 f = canonicalize_file_name(p);
4580                 if (!f) {
4581                         log_error("Failed to canonicalize file name '%s': %m", p);
4582                         free(p);
4583                         continue;
4584                 }
4585                 free(p);
4586
4587                 log_debug("found: %s\n", f);
4588                 base = f + strlen(path) + 1;
4589                 if (hashmap_put(h, base, f) <= 0)
4590                         free(f);
4591         }
4592
4593 finish:
4594         closedir(dir);
4595         return r;
4596 }
4597
4598 static int base_cmp(const void *a, const void *b) {
4599         const char *s1, *s2;
4600
4601         s1 = *(char * const *)a;
4602         s2 = *(char * const *)b;
4603         return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4604 }
4605
4606 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
4607         Hashmap *fh = NULL;
4608         char **dirs = NULL;
4609         char **files = NULL;
4610         char **p;
4611         va_list ap;
4612         int r = 0;
4613
4614         va_start(ap, dir);
4615         dirs = strv_new_ap(dir, ap);
4616         va_end(ap);
4617         if (!dirs) {
4618                 r = -ENOMEM;
4619                 goto finish;
4620         }
4621         if (!strv_path_canonicalize(dirs)) {
4622                 r = -ENOMEM;
4623                 goto finish;
4624         }
4625         if (!strv_uniq(dirs)) {
4626                 r = -ENOMEM;
4627                 goto finish;
4628         }
4629
4630         fh = hashmap_new(string_hash_func, string_compare_func);
4631         if (!fh) {
4632                 r = -ENOMEM;
4633                 goto finish;
4634         }
4635
4636         STRV_FOREACH(p, dirs) {
4637                 if (files_add(fh, *p, suffix) < 0) {
4638                         log_error("Failed to search for files.");
4639                         r = -EINVAL;
4640                         goto finish;
4641                 }
4642         }
4643
4644         files = hashmap_get_strv(fh);
4645         if (files == NULL) {
4646                 log_error("Failed to compose list of files.");
4647                 r = -ENOMEM;
4648                 goto finish;
4649         }
4650
4651         qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
4652 finish:
4653         strv_free(dirs);
4654         hashmap_free(fh);
4655         *strv = files;
4656         return r;
4657 }
4658
4659 bool hwclock_is_localtime(void) {
4660         FILE *f;
4661         char line[LINE_MAX];
4662         bool local = false;
4663
4664         /*
4665          * The third line of adjtime is "UTC" or "LOCAL" or nothing.
4666          *   # /etc/adjtime
4667          *   0.0 0 0.0
4668          *   0
4669          *   UTC
4670          */
4671         f = fopen("/etc/adjtime", "re");
4672         if (f) {
4673                 if (fgets(line, sizeof(line), f) &&
4674                     fgets(line, sizeof(line), f) &&
4675                     fgets(line, sizeof(line), f) ) {
4676                             if (!strcmp(line, "LOCAL\n"))
4677                                  local = true;
4678                 }
4679                 fclose(f);
4680         }
4681         return local;
4682 }
4683
4684 int hwclock_apply_localtime_delta(void) {
4685         const struct timeval *tv_null = NULL;
4686         struct timeval tv;
4687         struct tm *tm;
4688         int minuteswest;
4689         struct timezone tz;
4690
4691         gettimeofday(&tv, NULL);
4692         tm = localtime(&tv.tv_sec);
4693         minuteswest = tm->tm_gmtoff / 60;
4694
4695         tz.tz_minuteswest = -minuteswest;
4696         tz.tz_dsttime = 0; /* DST_NONE*/
4697
4698         /*
4699          * If the hardware clock does not run in UTC, but in local time:
4700          * The very first time we set the kernel's timezone, it will warp
4701          * the clock so that it runs in UTC instead of local time.
4702          */
4703         if (settimeofday(tv_null, &tz) < 0)
4704                 return -errno;
4705         else
4706                 return minuteswest;
4707 }
4708
4709 int hwclock_get_time(struct tm *tm) {
4710         int fd;
4711         int err = 0;
4712
4713         fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4714         if (fd < 0)
4715                 return -errno;
4716         if (ioctl(fd, RTC_RD_TIME, tm) < 0)
4717                 err = -errno;
4718         close(fd);
4719
4720         return err;
4721 }
4722
4723 int hwclock_set_time(const struct tm *tm) {
4724         int fd;
4725         int err = 0;
4726
4727         fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4728         if (fd < 0)
4729                 return -errno;
4730         if (ioctl(fd, RTC_SET_TIME, tm) < 0)
4731                 err = -errno;
4732         close(fd);
4733
4734         return err;
4735 }
4736
4737 static const char *const ioprio_class_table[] = {
4738         [IOPRIO_CLASS_NONE] = "none",
4739         [IOPRIO_CLASS_RT] = "realtime",
4740         [IOPRIO_CLASS_BE] = "best-effort",
4741         [IOPRIO_CLASS_IDLE] = "idle"
4742 };
4743
4744 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
4745
4746 static const char *const sigchld_code_table[] = {
4747         [CLD_EXITED] = "exited",
4748         [CLD_KILLED] = "killed",
4749         [CLD_DUMPED] = "dumped",
4750         [CLD_TRAPPED] = "trapped",
4751         [CLD_STOPPED] = "stopped",
4752         [CLD_CONTINUED] = "continued",
4753 };
4754
4755 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4756
4757 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4758         [LOG_FAC(LOG_KERN)] = "kern",
4759         [LOG_FAC(LOG_USER)] = "user",
4760         [LOG_FAC(LOG_MAIL)] = "mail",
4761         [LOG_FAC(LOG_DAEMON)] = "daemon",
4762         [LOG_FAC(LOG_AUTH)] = "auth",
4763         [LOG_FAC(LOG_SYSLOG)] = "syslog",
4764         [LOG_FAC(LOG_LPR)] = "lpr",
4765         [LOG_FAC(LOG_NEWS)] = "news",
4766         [LOG_FAC(LOG_UUCP)] = "uucp",
4767         [LOG_FAC(LOG_CRON)] = "cron",
4768         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4769         [LOG_FAC(LOG_FTP)] = "ftp",
4770         [LOG_FAC(LOG_LOCAL0)] = "local0",
4771         [LOG_FAC(LOG_LOCAL1)] = "local1",
4772         [LOG_FAC(LOG_LOCAL2)] = "local2",
4773         [LOG_FAC(LOG_LOCAL3)] = "local3",
4774         [LOG_FAC(LOG_LOCAL4)] = "local4",
4775         [LOG_FAC(LOG_LOCAL5)] = "local5",
4776         [LOG_FAC(LOG_LOCAL6)] = "local6",
4777         [LOG_FAC(LOG_LOCAL7)] = "local7"
4778 };
4779
4780 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
4781
4782 static const char *const log_level_table[] = {
4783         [LOG_EMERG] = "emerg",
4784         [LOG_ALERT] = "alert",
4785         [LOG_CRIT] = "crit",
4786         [LOG_ERR] = "err",
4787         [LOG_WARNING] = "warning",
4788         [LOG_NOTICE] = "notice",
4789         [LOG_INFO] = "info",
4790         [LOG_DEBUG] = "debug"
4791 };
4792
4793 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
4794
4795 static const char* const sched_policy_table[] = {
4796         [SCHED_OTHER] = "other",
4797         [SCHED_BATCH] = "batch",
4798         [SCHED_IDLE] = "idle",
4799         [SCHED_FIFO] = "fifo",
4800         [SCHED_RR] = "rr"
4801 };
4802
4803 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
4804
4805 static const char* const rlimit_table[] = {
4806         [RLIMIT_CPU] = "LimitCPU",
4807         [RLIMIT_FSIZE] = "LimitFSIZE",
4808         [RLIMIT_DATA] = "LimitDATA",
4809         [RLIMIT_STACK] = "LimitSTACK",
4810         [RLIMIT_CORE] = "LimitCORE",
4811         [RLIMIT_RSS] = "LimitRSS",
4812         [RLIMIT_NOFILE] = "LimitNOFILE",
4813         [RLIMIT_AS] = "LimitAS",
4814         [RLIMIT_NPROC] = "LimitNPROC",
4815         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4816         [RLIMIT_LOCKS] = "LimitLOCKS",
4817         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4818         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4819         [RLIMIT_NICE] = "LimitNICE",
4820         [RLIMIT_RTPRIO] = "LimitRTPRIO",
4821         [RLIMIT_RTTIME] = "LimitRTTIME"
4822 };
4823
4824 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4825
4826 static const char* const ip_tos_table[] = {
4827         [IPTOS_LOWDELAY] = "low-delay",
4828         [IPTOS_THROUGHPUT] = "throughput",
4829         [IPTOS_RELIABILITY] = "reliability",
4830         [IPTOS_LOWCOST] = "low-cost",
4831 };
4832
4833 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
4834
4835 static const char *const signal_table[] = {
4836         [SIGHUP] = "HUP",
4837         [SIGINT] = "INT",
4838         [SIGQUIT] = "QUIT",
4839         [SIGILL] = "ILL",
4840         [SIGTRAP] = "TRAP",
4841         [SIGABRT] = "ABRT",
4842         [SIGBUS] = "BUS",
4843         [SIGFPE] = "FPE",
4844         [SIGKILL] = "KILL",
4845         [SIGUSR1] = "USR1",
4846         [SIGSEGV] = "SEGV",
4847         [SIGUSR2] = "USR2",
4848         [SIGPIPE] = "PIPE",
4849         [SIGALRM] = "ALRM",
4850         [SIGTERM] = "TERM",
4851 #ifdef SIGSTKFLT
4852         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
4853 #endif
4854         [SIGCHLD] = "CHLD",
4855         [SIGCONT] = "CONT",
4856         [SIGSTOP] = "STOP",
4857         [SIGTSTP] = "TSTP",
4858         [SIGTTIN] = "TTIN",
4859         [SIGTTOU] = "TTOU",
4860         [SIGURG] = "URG",
4861         [SIGXCPU] = "XCPU",
4862         [SIGXFSZ] = "XFSZ",
4863         [SIGVTALRM] = "VTALRM",
4864         [SIGPROF] = "PROF",
4865         [SIGWINCH] = "WINCH",
4866         [SIGIO] = "IO",
4867         [SIGPWR] = "PWR",
4868         [SIGSYS] = "SYS"
4869 };
4870
4871 DEFINE_STRING_TABLE_LOOKUP(signal, int);