chiark / gitweb /
logind: add support for automatic suspend/hibernate/shutdown on idle
[elogind.git] / src / shared / 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 Lesser General Public License as published by
10   the Free Software Foundation; either version 2.1 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   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser 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/time.h>
54 #include <glob.h>
55 #include <grp.h>
56 #include <sys/mman.h>
57 #include <sys/vfs.h>
58 #include <linux/magic.h>
59 #include <limits.h>
60 #include <langinfo.h>
61 #include <locale.h>
62
63 #include "macro.h"
64 #include "util.h"
65 #include "ioprio.h"
66 #include "missing.h"
67 #include "log.h"
68 #include "strv.h"
69 #include "label.h"
70 #include "path-util.h"
71 #include "exit-status.h"
72 #include "hashmap.h"
73
74 int saved_argc = 0;
75 char **saved_argv = NULL;
76
77 static volatile unsigned cached_columns = 0;
78 static volatile unsigned cached_lines = 0;
79
80 bool is_efiboot(void) {
81         return access("/sys/firmware/efi", F_OK) >= 0;
82 }
83
84 size_t page_size(void) {
85         static __thread size_t pgsz = 0;
86         long r;
87
88         if (_likely_(pgsz > 0))
89                 return pgsz;
90
91         r = sysconf(_SC_PAGESIZE);
92         assert(r > 0);
93
94         pgsz = (size_t) r;
95         return pgsz;
96 }
97
98 bool streq_ptr(const char *a, const char *b) {
99
100         /* Like streq(), but tries to make sense of NULL pointers */
101
102         if (a && b)
103                 return streq(a, b);
104
105         if (!a && !b)
106                 return true;
107
108         return false;
109 }
110
111 char* endswith(const char *s, const char *postfix) {
112         size_t sl, pl;
113
114         assert(s);
115         assert(postfix);
116
117         sl = strlen(s);
118         pl = strlen(postfix);
119
120         if (pl == 0)
121                 return (char*) s + sl;
122
123         if (sl < pl)
124                 return NULL;
125
126         if (memcmp(s + sl - pl, postfix, pl) != 0)
127                 return NULL;
128
129         return (char*) s + sl - pl;
130 }
131
132 char* startswith(const char *s, const char *prefix) {
133         const char *a, *b;
134
135         assert(s);
136         assert(prefix);
137
138         a = s, b = prefix;
139         for (;;) {
140                 if (*b == 0)
141                         return (char*) a;
142                 if (*a != *b)
143                         return NULL;
144
145                 a++, b++;
146         }
147 }
148
149 char* startswith_no_case(const char *s, const char *prefix) {
150         const char *a, *b;
151
152         assert(s);
153         assert(prefix);
154
155         a = s, b = prefix;
156         for (;;) {
157                 if (*b == 0)
158                         return (char*) a;
159                 if (tolower(*a) != tolower(*b))
160                         return NULL;
161
162                 a++, b++;
163         }
164 }
165
166 bool first_word(const char *s, const char *word) {
167         size_t sl, wl;
168
169         assert(s);
170         assert(word);
171
172         sl = strlen(s);
173         wl = strlen(word);
174
175         if (sl < wl)
176                 return false;
177
178         if (wl == 0)
179                 return true;
180
181         if (memcmp(s, word, wl) != 0)
182                 return false;
183
184         return s[wl] == 0 ||
185                 strchr(WHITESPACE, s[wl]);
186 }
187
188 int close_nointr(int fd) {
189         assert(fd >= 0);
190
191         for (;;) {
192                 int r;
193
194                 r = close(fd);
195                 if (r >= 0)
196                         return r;
197
198                 if (errno != EINTR)
199                         return -errno;
200         }
201 }
202
203 void close_nointr_nofail(int fd) {
204         int saved_errno = errno;
205
206         /* like close_nointr() but cannot fail, and guarantees errno
207          * is unchanged */
208
209         assert_se(close_nointr(fd) == 0);
210
211         errno = saved_errno;
212 }
213
214 void close_many(const int fds[], unsigned n_fd) {
215         unsigned i;
216
217         for (i = 0; i < n_fd; i++)
218                 close_nointr_nofail(fds[i]);
219 }
220
221 int parse_boolean(const char *v) {
222         assert(v);
223
224         if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
225                 return 1;
226         else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
227                 return 0;
228
229         return -EINVAL;
230 }
231
232 int parse_pid(const char *s, pid_t* ret_pid) {
233         unsigned long ul = 0;
234         pid_t pid;
235         int r;
236
237         assert(s);
238         assert(ret_pid);
239
240         r = safe_atolu(s, &ul);
241         if (r < 0)
242                 return r;
243
244         pid = (pid_t) ul;
245
246         if ((unsigned long) pid != ul)
247                 return -ERANGE;
248
249         if (pid <= 0)
250                 return -ERANGE;
251
252         *ret_pid = pid;
253         return 0;
254 }
255
256 int parse_uid(const char *s, uid_t* ret_uid) {
257         unsigned long ul = 0;
258         uid_t uid;
259         int r;
260
261         assert(s);
262         assert(ret_uid);
263
264         r = safe_atolu(s, &ul);
265         if (r < 0)
266                 return r;
267
268         uid = (uid_t) ul;
269
270         if ((unsigned long) uid != ul)
271                 return -ERANGE;
272
273         *ret_uid = uid;
274         return 0;
275 }
276
277 int safe_atou(const char *s, unsigned *ret_u) {
278         char *x = NULL;
279         unsigned long l;
280
281         assert(s);
282         assert(ret_u);
283
284         errno = 0;
285         l = strtoul(s, &x, 0);
286
287         if (!x || x == s || *x || errno)
288                 return errno ? -errno : -EINVAL;
289
290         if ((unsigned long) (unsigned) l != l)
291                 return -ERANGE;
292
293         *ret_u = (unsigned) l;
294         return 0;
295 }
296
297 int safe_atoi(const char *s, int *ret_i) {
298         char *x = NULL;
299         long l;
300
301         assert(s);
302         assert(ret_i);
303
304         errno = 0;
305         l = strtol(s, &x, 0);
306
307         if (!x || x == s || *x || errno)
308                 return errno ? -errno : -EINVAL;
309
310         if ((long) (int) l != l)
311                 return -ERANGE;
312
313         *ret_i = (int) l;
314         return 0;
315 }
316
317 int safe_atollu(const char *s, long long unsigned *ret_llu) {
318         char *x = NULL;
319         unsigned long long l;
320
321         assert(s);
322         assert(ret_llu);
323
324         errno = 0;
325         l = strtoull(s, &x, 0);
326
327         if (!x || x == s || *x || errno)
328                 return errno ? -errno : -EINVAL;
329
330         *ret_llu = l;
331         return 0;
332 }
333
334 int safe_atolli(const char *s, long long int *ret_lli) {
335         char *x = NULL;
336         long long l;
337
338         assert(s);
339         assert(ret_lli);
340
341         errno = 0;
342         l = strtoll(s, &x, 0);
343
344         if (!x || x == s || *x || errno)
345                 return errno ? -errno : -EINVAL;
346
347         *ret_lli = l;
348         return 0;
349 }
350
351 /* Split a string into words. */
352 char *split(const char *c, size_t *l, const char *separator, char **state) {
353         char *current;
354
355         current = *state ? *state : (char*) c;
356
357         if (!*current || *c == 0)
358                 return NULL;
359
360         current += strspn(current, separator);
361         *l = strcspn(current, separator);
362         *state = current+*l;
363
364         return (char*) current;
365 }
366
367 /* Split a string into words, but consider strings enclosed in '' and
368  * "" as words even if they include spaces. */
369 char *split_quoted(const char *c, size_t *l, char **state) {
370         char *current, *e;
371         bool escaped = false;
372
373         current = *state ? *state : (char*) c;
374
375         if (!*current || *c == 0)
376                 return NULL;
377
378         current += strspn(current, WHITESPACE);
379
380         if (*current == '\'') {
381                 current ++;
382
383                 for (e = current; *e; e++) {
384                         if (escaped)
385                                 escaped = false;
386                         else if (*e == '\\')
387                                 escaped = true;
388                         else if (*e == '\'')
389                                 break;
390                 }
391
392                 *l = e-current;
393                 *state = *e == 0 ? e : e+1;
394         } else if (*current == '\"') {
395                 current ++;
396
397                 for (e = current; *e; e++) {
398                         if (escaped)
399                                 escaped = false;
400                         else if (*e == '\\')
401                                 escaped = true;
402                         else if (*e == '\"')
403                                 break;
404                 }
405
406                 *l = e-current;
407                 *state = *e == 0 ? e : e+1;
408         } else {
409                 for (e = current; *e; e++) {
410                         if (escaped)
411                                 escaped = false;
412                         else if (*e == '\\')
413                                 escaped = true;
414                         else if (strchr(WHITESPACE, *e))
415                                 break;
416                 }
417                 *l = e-current;
418                 *state = e;
419         }
420
421         return (char*) current;
422 }
423
424 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
425         int r;
426         _cleanup_fclose_ FILE *f = NULL;
427         char fn[PATH_MAX], line[LINE_MAX], *p;
428         long unsigned ppid;
429
430         assert(pid > 0);
431         assert(_ppid);
432
433         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
434         char_array_0(fn);
435
436         f = fopen(fn, "re");
437         if (!f)
438                 return -errno;
439
440         if (!fgets(line, sizeof(line), f)) {
441                 r = feof(f) ? -EIO : -errno;
442                 fclose(f);
443                 return r;
444         }
445
446         /* Let's skip the pid and comm fields. The latter is enclosed
447          * in () but does not escape any () in its value, so let's
448          * skip over it manually */
449
450         p = strrchr(line, ')');
451         if (!p)
452                 return -EIO;
453
454         p++;
455
456         if (sscanf(p, " "
457                    "%*c "  /* state */
458                    "%lu ", /* ppid */
459                    &ppid) != 1)
460                 return -EIO;
461
462         if ((long unsigned) (pid_t) ppid != ppid)
463                 return -ERANGE;
464
465         *_ppid = (pid_t) ppid;
466
467         return 0;
468 }
469
470 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
471         _cleanup_fclose_ FILE *f = NULL;
472         char fn[PATH_MAX], line[LINE_MAX], *p;
473
474         assert(pid > 0);
475         assert(st);
476
477         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
478         char_array_0(fn);
479
480         f = fopen(fn, "re");
481         if (!f)
482                 return -errno;
483
484         if (!fgets(line, sizeof(line), f)) {
485                 if (ferror(f))
486                         return -errno;
487
488                 return -EIO;
489         }
490
491         /* Let's skip the pid and comm fields. The latter is enclosed
492          * in () but does not escape any () in its value, so let's
493          * skip over it manually */
494
495         p = strrchr(line, ')');
496         if (!p)
497                 return -EIO;
498
499         p++;
500
501         if (sscanf(p, " "
502                    "%*c "  /* state */
503                    "%*d "  /* ppid */
504                    "%*d "  /* pgrp */
505                    "%*d "  /* session */
506                    "%*d "  /* tty_nr */
507                    "%*d "  /* tpgid */
508                    "%*u "  /* flags */
509                    "%*u "  /* minflt */
510                    "%*u "  /* cminflt */
511                    "%*u "  /* majflt */
512                    "%*u "  /* cmajflt */
513                    "%*u "  /* utime */
514                    "%*u "  /* stime */
515                    "%*d "  /* cutime */
516                    "%*d "  /* cstime */
517                    "%*d "  /* priority */
518                    "%*d "  /* nice */
519                    "%*d "  /* num_threads */
520                    "%*d "  /* itrealvalue */
521                    "%llu "  /* starttime */,
522                    st) != 1)
523                 return -EIO;
524
525         return 0;
526 }
527
528 int write_one_line_file(const char *fn, const char *line) {
529         _cleanup_fclose_ FILE *f = NULL;
530
531         assert(fn);
532         assert(line);
533
534         f = fopen(fn, "we");
535         if (!f)
536                 return -errno;
537
538         errno = 0;
539         if (fputs(line, f) < 0)
540                 return errno ? -errno : -EIO;
541
542         if (!endswith(line, "\n"))
543                 fputc('\n', f);
544
545         fflush(f);
546
547         if (ferror(f))
548                 return errno ? -errno : -EIO;
549
550         return 0;
551 }
552
553 int fchmod_umask(int fd, mode_t m) {
554         mode_t u;
555         int r;
556
557         u = umask(0777);
558         r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
559         umask(u);
560
561         return r;
562 }
563
564 int write_one_line_file_atomic(const char *fn, const char *line) {
565         FILE *f;
566         int r;
567         char *p;
568
569         assert(fn);
570         assert(line);
571
572         r = fopen_temporary(fn, &f, &p);
573         if (r < 0)
574                 return r;
575
576         fchmod_umask(fileno(f), 0644);
577
578         errno = 0;
579         if (fputs(line, f) < 0) {
580                 r = -errno;
581                 goto finish;
582         }
583
584         if (!endswith(line, "\n"))
585                 fputc('\n', f);
586
587         fflush(f);
588
589         if (ferror(f)) {
590                 if (errno != 0)
591                         r = -errno;
592                 else
593                         r = -EIO;
594         } else {
595                 if (rename(p, fn) < 0)
596                         r = -errno;
597                 else
598                         r = 0;
599         }
600
601 finish:
602         if (r < 0)
603                 unlink(p);
604
605         fclose(f);
606         free(p);
607
608         return r;
609 }
610
611 int read_one_line_file(const char *fn, char **line) {
612         _cleanup_fclose_ FILE *f = NULL;
613         char t[LINE_MAX], *c;
614
615         assert(fn);
616         assert(line);
617
618         f = fopen(fn, "re");
619         if (!f)
620                 return -errno;
621
622         if (!fgets(t, sizeof(t), f)) {
623
624                 if (ferror(f))
625                         return errno ? -errno : -EIO;
626
627                 t[0] = 0;
628         }
629
630         c = strdup(t);
631         if (!c)
632                 return -ENOMEM;
633         truncate_nl(c);
634
635         *line = c;
636         return 0;
637 }
638
639 int read_full_file(const char *fn, char **contents, size_t *size) {
640         _cleanup_fclose_ FILE *f = NULL;
641         size_t n, l;
642         _cleanup_free_ char *buf = NULL;
643         struct stat st;
644
645         f = fopen(fn, "re");
646         if (!f)
647                 return -errno;
648
649         if (fstat(fileno(f), &st) < 0)
650                 return -errno;
651
652         /* Safety check */
653         if (st.st_size > 4*1024*1024)
654                 return -E2BIG;
655
656         n = st.st_size > 0 ? st.st_size : LINE_MAX;
657         l = 0;
658
659         for (;;) {
660                 char *t;
661                 size_t k;
662
663                 t = realloc(buf, n+1);
664                 if (!t)
665                         return -ENOMEM;
666
667                 buf = t;
668                 k = fread(buf + l, 1, n - l, f);
669
670                 if (k <= 0) {
671                         if (ferror(f))
672                                 return -errno;
673
674                         break;
675                 }
676
677                 l += k;
678                 n *= 2;
679
680                 /* Safety check */
681                 if (n > 4*1024*1024)
682                         return -E2BIG;
683         }
684
685         buf[l] = 0;
686         *contents = buf;
687         buf = NULL;
688
689         if (size)
690                 *size = l;
691
692         return 0;
693 }
694
695 int parse_env_file(
696                 const char *fname,
697                 const char *separator, ...) {
698
699         int r = 0;
700         char *contents = NULL, *p;
701
702         assert(fname);
703         assert(separator);
704
705         if ((r = read_full_file(fname, &contents, NULL)) < 0)
706                 return r;
707
708         p = contents;
709         for (;;) {
710                 const char *key = NULL;
711
712                 p += strspn(p, separator);
713                 p += strspn(p, WHITESPACE);
714
715                 if (!*p)
716                         break;
717
718                 if (!strchr(COMMENTS, *p)) {
719                         va_list ap;
720                         char **value;
721
722                         va_start(ap, separator);
723                         while ((key = va_arg(ap, char *))) {
724                                 size_t n;
725                                 char *v;
726
727                                 value = va_arg(ap, char **);
728
729                                 n = strlen(key);
730                                 if (strncmp(p, key, n) != 0 ||
731                                     p[n] != '=')
732                                         continue;
733
734                                 p += n + 1;
735                                 n = strcspn(p, separator);
736
737                                 if (n >= 2 &&
738                                     strchr(QUOTES, p[0]) &&
739                                     p[n-1] == p[0])
740                                         v = strndup(p+1, n-2);
741                                 else
742                                         v = strndup(p, n);
743
744                                 if (!v) {
745                                         r = -ENOMEM;
746                                         va_end(ap);
747                                         goto fail;
748                                 }
749
750                                 if (v[0] == '\0') {
751                                         /* return empty value strings as NULL */
752                                         free(v);
753                                         v = NULL;
754                                 }
755
756                                 free(*value);
757                                 *value = v;
758
759                                 p += n;
760
761                                 r ++;
762                                 break;
763                         }
764                         va_end(ap);
765                 }
766
767                 if (!key)
768                         p += strcspn(p, separator);
769         }
770
771 fail:
772         free(contents);
773         return r;
774 }
775
776 int load_env_file(
777                 const char *fname,
778                 char ***rl) {
779
780         FILE *f;
781         char **m = NULL;
782         int r;
783
784         assert(fname);
785         assert(rl);
786
787         if (!(f = fopen(fname, "re")))
788                 return -errno;
789
790         while (!feof(f)) {
791                 char l[LINE_MAX], *p, *u;
792                 char **t;
793
794                 if (!fgets(l, sizeof(l), f)) {
795                         if (feof(f))
796                                 break;
797
798                         r = -errno;
799                         goto finish;
800                 }
801
802                 p = strstrip(l);
803
804                 if (!*p)
805                         continue;
806
807                 if (strchr(COMMENTS, *p))
808                         continue;
809
810                 if (!(u = normalize_env_assignment(p))) {
811                         r = log_oom();
812                         goto finish;
813                 }
814
815                 t = strv_append(m, u);
816                 free(u);
817
818                 if (!t) {
819                         r = log_oom();
820                         goto finish;
821                 }
822
823                 strv_free(m);
824                 m = t;
825         }
826
827         r = 0;
828
829         *rl = m;
830         m = NULL;
831
832 finish:
833         if (f)
834                 fclose(f);
835
836         strv_free(m);
837
838         return r;
839 }
840
841 int write_env_file(const char *fname, char **l) {
842         char **i, *p;
843         FILE *f;
844         int r;
845
846         r = fopen_temporary(fname, &f, &p);
847         if (r < 0)
848                 return r;
849
850         fchmod_umask(fileno(f), 0644);
851
852         errno = 0;
853         STRV_FOREACH(i, l) {
854                 fputs(*i, f);
855                 fputc('\n', f);
856         }
857
858         fflush(f);
859
860         if (ferror(f)) {
861                 if (errno != 0)
862                         r = -errno;
863                 else
864                         r = -EIO;
865         } else {
866                 if (rename(p, fname) < 0)
867                         r = -errno;
868                 else
869                         r = 0;
870         }
871
872         if (r < 0)
873                 unlink(p);
874
875         fclose(f);
876         free(p);
877
878         return r;
879 }
880
881 char *truncate_nl(char *s) {
882         assert(s);
883
884         s[strcspn(s, NEWLINE)] = 0;
885         return s;
886 }
887
888 int get_process_comm(pid_t pid, char **name) {
889         int r;
890
891         assert(name);
892
893         if (pid == 0)
894                 r = read_one_line_file("/proc/self/comm", name);
895         else {
896                 char *p;
897                 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
898                         return -ENOMEM;
899
900                 r = read_one_line_file(p, name);
901                 free(p);
902         }
903
904         return r;
905 }
906
907 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
908         char *r, *k;
909         int c;
910         bool space = false;
911         size_t left;
912         FILE *f;
913
914         assert(max_length > 0);
915         assert(line);
916
917         if (pid == 0)
918                 f = fopen("/proc/self/cmdline", "re");
919         else {
920                 char *p;
921                 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
922                         return -ENOMEM;
923
924                 f = fopen(p, "re");
925                 free(p);
926         }
927
928         if (!f)
929                 return -errno;
930
931         r = new(char, max_length);
932         if (!r) {
933                 fclose(f);
934                 return -ENOMEM;
935         }
936
937         k = r;
938         left = max_length;
939         while ((c = getc(f)) != EOF) {
940
941                 if (isprint(c)) {
942                         if (space) {
943                                 if (left <= 4)
944                                         break;
945
946                                 *(k++) = ' ';
947                                 left--;
948                                 space = false;
949                         }
950
951                         if (left <= 4)
952                                 break;
953
954                         *(k++) = (char) c;
955                         left--;
956                 }  else
957                         space = true;
958         }
959
960         if (left <= 4) {
961                 size_t n = MIN(left-1, 3U);
962                 memcpy(k, "...", n);
963                 k[n] = 0;
964         } else
965                 *k = 0;
966
967         fclose(f);
968
969         /* Kernel threads have no argv[] */
970         if (r[0] == 0) {
971                 char *t;
972                 int h;
973
974                 free(r);
975
976                 if (!comm_fallback)
977                         return -ENOENT;
978
979                 h = get_process_comm(pid, &t);
980                 if (h < 0)
981                         return h;
982
983                 r = strjoin("[", t, "]", NULL);
984                 free(t);
985
986                 if (!r)
987                         return -ENOMEM;
988         }
989
990         *line = r;
991         return 0;
992 }
993
994 int is_kernel_thread(pid_t pid) {
995         char *p;
996         size_t count;
997         char c;
998         bool eof;
999         FILE *f;
1000
1001         if (pid == 0)
1002                 return 0;
1003
1004         if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1005                 return -ENOMEM;
1006
1007         f = fopen(p, "re");
1008         free(p);
1009
1010         if (!f)
1011                 return -errno;
1012
1013         count = fread(&c, 1, 1, f);
1014         eof = feof(f);
1015         fclose(f);
1016
1017         /* Kernel threads have an empty cmdline */
1018
1019         if (count <= 0)
1020                 return eof ? 1 : -errno;
1021
1022         return 0;
1023 }
1024
1025 int get_process_exe(pid_t pid, char **name) {
1026         int r;
1027
1028         assert(name);
1029
1030         if (pid == 0)
1031                 r = readlink_malloc("/proc/self/exe", name);
1032         else {
1033                 char *p;
1034                 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1035                         return -ENOMEM;
1036
1037                 r = readlink_malloc(p, name);
1038                 free(p);
1039         }
1040
1041         return r;
1042 }
1043
1044 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1045         char *p;
1046         FILE *f;
1047         int r;
1048
1049         assert(uid);
1050
1051         if (pid == 0)
1052                 return getuid();
1053
1054         if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1055                 return -ENOMEM;
1056
1057         f = fopen(p, "re");
1058         free(p);
1059
1060         if (!f)
1061                 return -errno;
1062
1063         while (!feof(f)) {
1064                 char line[LINE_MAX], *l;
1065
1066                 if (!fgets(line, sizeof(line), f)) {
1067                         if (feof(f))
1068                                 break;
1069
1070                         r = -errno;
1071                         goto finish;
1072                 }
1073
1074                 l = strstrip(line);
1075
1076                 if (startswith(l, field)) {
1077                         l += strlen(field);
1078                         l += strspn(l, WHITESPACE);
1079
1080                         l[strcspn(l, WHITESPACE)] = 0;
1081
1082                         r = parse_uid(l, uid);
1083                         goto finish;
1084                 }
1085         }
1086
1087         r = -EIO;
1088
1089 finish:
1090         fclose(f);
1091
1092         return r;
1093 }
1094
1095 int get_process_uid(pid_t pid, uid_t *uid) {
1096         return get_process_id(pid, "Uid:", uid);
1097 }
1098
1099 int get_process_gid(pid_t pid, gid_t *gid) {
1100         return get_process_id(pid, "Gid:", gid);
1101 }
1102
1103 char *strnappend(const char *s, const char *suffix, size_t b) {
1104         size_t a;
1105         char *r;
1106
1107         if (!s && !suffix)
1108                 return strdup("");
1109
1110         if (!s)
1111                 return strndup(suffix, b);
1112
1113         if (!suffix)
1114                 return strdup(s);
1115
1116         assert(s);
1117         assert(suffix);
1118
1119         a = strlen(s);
1120         if (b > ((size_t) -1) - a)
1121                 return NULL;
1122
1123         r = new(char, a+b+1);
1124         if (!r)
1125                 return NULL;
1126
1127         memcpy(r, s, a);
1128         memcpy(r+a, suffix, b);
1129         r[a+b] = 0;
1130
1131         return r;
1132 }
1133
1134 char *strappend(const char *s, const char *suffix) {
1135         return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1136 }
1137
1138 int readlink_malloc(const char *p, char **r) {
1139         size_t l = 100;
1140
1141         assert(p);
1142         assert(r);
1143
1144         for (;;) {
1145                 char *c;
1146                 ssize_t n;
1147
1148                 if (!(c = new(char, l)))
1149                         return -ENOMEM;
1150
1151                 if ((n = readlink(p, c, l-1)) < 0) {
1152                         int ret = -errno;
1153                         free(c);
1154                         return ret;
1155                 }
1156
1157                 if ((size_t) n < l-1) {
1158                         c[n] = 0;
1159                         *r = c;
1160                         return 0;
1161                 }
1162
1163                 free(c);
1164                 l *= 2;
1165         }
1166 }
1167
1168 int readlink_and_make_absolute(const char *p, char **r) {
1169         char *target, *k;
1170         int j;
1171
1172         assert(p);
1173         assert(r);
1174
1175         if ((j = readlink_malloc(p, &target)) < 0)
1176                 return j;
1177
1178         k = file_in_same_dir(p, target);
1179         free(target);
1180
1181         if (!k)
1182                 return -ENOMEM;
1183
1184         *r = k;
1185         return 0;
1186 }
1187
1188 int readlink_and_canonicalize(const char *p, char **r) {
1189         char *t, *s;
1190         int j;
1191
1192         assert(p);
1193         assert(r);
1194
1195         j = readlink_and_make_absolute(p, &t);
1196         if (j < 0)
1197                 return j;
1198
1199         s = canonicalize_file_name(t);
1200         if (s) {
1201                 free(t);
1202                 *r = s;
1203         } else
1204                 *r = t;
1205
1206         path_kill_slashes(*r);
1207
1208         return 0;
1209 }
1210
1211 int reset_all_signal_handlers(void) {
1212         int sig;
1213
1214         for (sig = 1; sig < _NSIG; sig++) {
1215                 struct sigaction sa;
1216
1217                 if (sig == SIGKILL || sig == SIGSTOP)
1218                         continue;
1219
1220                 zero(sa);
1221                 sa.sa_handler = SIG_DFL;
1222                 sa.sa_flags = SA_RESTART;
1223
1224                 /* On Linux the first two RT signals are reserved by
1225                  * glibc, and sigaction() will return EINVAL for them. */
1226                 if ((sigaction(sig, &sa, NULL) < 0))
1227                         if (errno != EINVAL)
1228                                 return -errno;
1229         }
1230
1231         return 0;
1232 }
1233
1234 char *strstrip(char *s) {
1235         char *e;
1236
1237         /* Drops trailing whitespace. Modifies the string in
1238          * place. Returns pointer to first non-space character */
1239
1240         s += strspn(s, WHITESPACE);
1241
1242         for (e = strchr(s, 0); e > s; e --)
1243                 if (!strchr(WHITESPACE, e[-1]))
1244                         break;
1245
1246         *e = 0;
1247
1248         return s;
1249 }
1250
1251 char *delete_chars(char *s, const char *bad) {
1252         char *f, *t;
1253
1254         /* Drops all whitespace, regardless where in the string */
1255
1256         for (f = s, t = s; *f; f++) {
1257                 if (strchr(bad, *f))
1258                         continue;
1259
1260                 *(t++) = *f;
1261         }
1262
1263         *t = 0;
1264
1265         return s;
1266 }
1267
1268 bool in_charset(const char *s, const char* charset) {
1269         const char *i;
1270
1271         assert(s);
1272         assert(charset);
1273
1274         for (i = s; *i; i++)
1275                 if (!strchr(charset, *i))
1276                         return false;
1277
1278         return true;
1279 }
1280
1281 char *file_in_same_dir(const char *path, const char *filename) {
1282         char *e, *r;
1283         size_t k;
1284
1285         assert(path);
1286         assert(filename);
1287
1288         /* This removes the last component of path and appends
1289          * filename, unless the latter is absolute anyway or the
1290          * former isn't */
1291
1292         if (path_is_absolute(filename))
1293                 return strdup(filename);
1294
1295         if (!(e = strrchr(path, '/')))
1296                 return strdup(filename);
1297
1298         k = strlen(filename);
1299         if (!(r = new(char, e-path+1+k+1)))
1300                 return NULL;
1301
1302         memcpy(r, path, e-path+1);
1303         memcpy(r+(e-path)+1, filename, k+1);
1304
1305         return r;
1306 }
1307
1308 int rmdir_parents(const char *path, const char *stop) {
1309         size_t l;
1310         int r = 0;
1311
1312         assert(path);
1313         assert(stop);
1314
1315         l = strlen(path);
1316
1317         /* Skip trailing slashes */
1318         while (l > 0 && path[l-1] == '/')
1319                 l--;
1320
1321         while (l > 0) {
1322                 char *t;
1323
1324                 /* Skip last component */
1325                 while (l > 0 && path[l-1] != '/')
1326                         l--;
1327
1328                 /* Skip trailing slashes */
1329                 while (l > 0 && path[l-1] == '/')
1330                         l--;
1331
1332                 if (l <= 0)
1333                         break;
1334
1335                 if (!(t = strndup(path, l)))
1336                         return -ENOMEM;
1337
1338                 if (path_startswith(stop, t)) {
1339                         free(t);
1340                         return 0;
1341                 }
1342
1343                 r = rmdir(t);
1344                 free(t);
1345
1346                 if (r < 0)
1347                         if (errno != ENOENT)
1348                                 return -errno;
1349         }
1350
1351         return 0;
1352 }
1353
1354
1355 char hexchar(int x) {
1356         static const char table[16] = "0123456789abcdef";
1357
1358         return table[x & 15];
1359 }
1360
1361 int unhexchar(char c) {
1362
1363         if (c >= '0' && c <= '9')
1364                 return c - '0';
1365
1366         if (c >= 'a' && c <= 'f')
1367                 return c - 'a' + 10;
1368
1369         if (c >= 'A' && c <= 'F')
1370                 return c - 'A' + 10;
1371
1372         return -1;
1373 }
1374
1375 char octchar(int x) {
1376         return '0' + (x & 7);
1377 }
1378
1379 int unoctchar(char c) {
1380
1381         if (c >= '0' && c <= '7')
1382                 return c - '0';
1383
1384         return -1;
1385 }
1386
1387 char decchar(int x) {
1388         return '0' + (x % 10);
1389 }
1390
1391 int undecchar(char c) {
1392
1393         if (c >= '0' && c <= '9')
1394                 return c - '0';
1395
1396         return -1;
1397 }
1398
1399 char *cescape(const char *s) {
1400         char *r, *t;
1401         const char *f;
1402
1403         assert(s);
1404
1405         /* Does C style string escaping. */
1406
1407         r = new(char, strlen(s)*4 + 1);
1408         if (!r)
1409                 return NULL;
1410
1411         for (f = s, t = r; *f; f++)
1412
1413                 switch (*f) {
1414
1415                 case '\a':
1416                         *(t++) = '\\';
1417                         *(t++) = 'a';
1418                         break;
1419                 case '\b':
1420                         *(t++) = '\\';
1421                         *(t++) = 'b';
1422                         break;
1423                 case '\f':
1424                         *(t++) = '\\';
1425                         *(t++) = 'f';
1426                         break;
1427                 case '\n':
1428                         *(t++) = '\\';
1429                         *(t++) = 'n';
1430                         break;
1431                 case '\r':
1432                         *(t++) = '\\';
1433                         *(t++) = 'r';
1434                         break;
1435                 case '\t':
1436                         *(t++) = '\\';
1437                         *(t++) = 't';
1438                         break;
1439                 case '\v':
1440                         *(t++) = '\\';
1441                         *(t++) = 'v';
1442                         break;
1443                 case '\\':
1444                         *(t++) = '\\';
1445                         *(t++) = '\\';
1446                         break;
1447                 case '"':
1448                         *(t++) = '\\';
1449                         *(t++) = '"';
1450                         break;
1451                 case '\'':
1452                         *(t++) = '\\';
1453                         *(t++) = '\'';
1454                         break;
1455
1456                 default:
1457                         /* For special chars we prefer octal over
1458                          * hexadecimal encoding, simply because glib's
1459                          * g_strescape() does the same */
1460                         if ((*f < ' ') || (*f >= 127)) {
1461                                 *(t++) = '\\';
1462                                 *(t++) = octchar((unsigned char) *f >> 6);
1463                                 *(t++) = octchar((unsigned char) *f >> 3);
1464                                 *(t++) = octchar((unsigned char) *f);
1465                         } else
1466                                 *(t++) = *f;
1467                         break;
1468                 }
1469
1470         *t = 0;
1471
1472         return r;
1473 }
1474
1475 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1476         char *r, *t;
1477         const char *f;
1478         size_t pl;
1479
1480         assert(s);
1481
1482         /* Undoes C style string escaping, and optionally prefixes it. */
1483
1484         pl = prefix ? strlen(prefix) : 0;
1485
1486         r = new(char, pl+length+1);
1487         if (!r)
1488                 return r;
1489
1490         if (prefix)
1491                 memcpy(r, prefix, pl);
1492
1493         for (f = s, t = r + pl; f < s + length; f++) {
1494
1495                 if (*f != '\\') {
1496                         *(t++) = *f;
1497                         continue;
1498                 }
1499
1500                 f++;
1501
1502                 switch (*f) {
1503
1504                 case 'a':
1505                         *(t++) = '\a';
1506                         break;
1507                 case 'b':
1508                         *(t++) = '\b';
1509                         break;
1510                 case 'f':
1511                         *(t++) = '\f';
1512                         break;
1513                 case 'n':
1514                         *(t++) = '\n';
1515                         break;
1516                 case 'r':
1517                         *(t++) = '\r';
1518                         break;
1519                 case 't':
1520                         *(t++) = '\t';
1521                         break;
1522                 case 'v':
1523                         *(t++) = '\v';
1524                         break;
1525                 case '\\':
1526                         *(t++) = '\\';
1527                         break;
1528                 case '"':
1529                         *(t++) = '"';
1530                         break;
1531                 case '\'':
1532                         *(t++) = '\'';
1533                         break;
1534
1535                 case 's':
1536                         /* This is an extension of the XDG syntax files */
1537                         *(t++) = ' ';
1538                         break;
1539
1540                 case 'x': {
1541                         /* hexadecimal encoding */
1542                         int a, b;
1543
1544                         a = unhexchar(f[1]);
1545                         b = unhexchar(f[2]);
1546
1547                         if (a < 0 || b < 0) {
1548                                 /* Invalid escape code, let's take it literal then */
1549                                 *(t++) = '\\';
1550                                 *(t++) = 'x';
1551                         } else {
1552                                 *(t++) = (char) ((a << 4) | b);
1553                                 f += 2;
1554                         }
1555
1556                         break;
1557                 }
1558
1559                 case '0':
1560                 case '1':
1561                 case '2':
1562                 case '3':
1563                 case '4':
1564                 case '5':
1565                 case '6':
1566                 case '7': {
1567                         /* octal encoding */
1568                         int a, b, c;
1569
1570                         a = unoctchar(f[0]);
1571                         b = unoctchar(f[1]);
1572                         c = unoctchar(f[2]);
1573
1574                         if (a < 0 || b < 0 || c < 0) {
1575                                 /* Invalid escape code, let's take it literal then */
1576                                 *(t++) = '\\';
1577                                 *(t++) = f[0];
1578                         } else {
1579                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
1580                                 f += 2;
1581                         }
1582
1583                         break;
1584                 }
1585
1586                 case 0:
1587                         /* premature end of string.*/
1588                         *(t++) = '\\';
1589                         goto finish;
1590
1591                 default:
1592                         /* Invalid escape code, let's take it literal then */
1593                         *(t++) = '\\';
1594                         *(t++) = *f;
1595                         break;
1596                 }
1597         }
1598
1599 finish:
1600         *t = 0;
1601         return r;
1602 }
1603
1604 char *cunescape_length(const char *s, size_t length) {
1605         return cunescape_length_with_prefix(s, length, NULL);
1606 }
1607
1608 char *cunescape(const char *s) {
1609         assert(s);
1610
1611         return cunescape_length(s, strlen(s));
1612 }
1613
1614 char *xescape(const char *s, const char *bad) {
1615         char *r, *t;
1616         const char *f;
1617
1618         /* Escapes all chars in bad, in addition to \ and all special
1619          * chars, in \xFF style escaping. May be reversed with
1620          * cunescape. */
1621
1622         r = new(char, strlen(s) * 4 + 1);
1623         if (!r)
1624                 return NULL;
1625
1626         for (f = s, t = r; *f; f++) {
1627
1628                 if ((*f < ' ') || (*f >= 127) ||
1629                     (*f == '\\') || strchr(bad, *f)) {
1630                         *(t++) = '\\';
1631                         *(t++) = 'x';
1632                         *(t++) = hexchar(*f >> 4);
1633                         *(t++) = hexchar(*f);
1634                 } else
1635                         *(t++) = *f;
1636         }
1637
1638         *t = 0;
1639
1640         return r;
1641 }
1642
1643 char *bus_path_escape(const char *s) {
1644         char *r, *t;
1645         const char *f;
1646
1647         assert(s);
1648
1649         /* Escapes all chars that D-Bus' object path cannot deal
1650          * with. Can be reverse with bus_path_unescape() */
1651
1652         if (!(r = new(char, strlen(s)*3+1)))
1653                 return NULL;
1654
1655         for (f = s, t = r; *f; f++) {
1656
1657                 if (!(*f >= 'A' && *f <= 'Z') &&
1658                     !(*f >= 'a' && *f <= 'z') &&
1659                     !(*f >= '0' && *f <= '9')) {
1660                         *(t++) = '_';
1661                         *(t++) = hexchar(*f >> 4);
1662                         *(t++) = hexchar(*f);
1663                 } else
1664                         *(t++) = *f;
1665         }
1666
1667         *t = 0;
1668
1669         return r;
1670 }
1671
1672 char *bus_path_unescape(const char *f) {
1673         char *r, *t;
1674
1675         assert(f);
1676
1677         if (!(r = strdup(f)))
1678                 return NULL;
1679
1680         for (t = r; *f; f++) {
1681
1682                 if (*f == '_') {
1683                         int a, b;
1684
1685                         if ((a = unhexchar(f[1])) < 0 ||
1686                             (b = unhexchar(f[2])) < 0) {
1687                                 /* Invalid escape code, let's take it literal then */
1688                                 *(t++) = '_';
1689                         } else {
1690                                 *(t++) = (char) ((a << 4) | b);
1691                                 f += 2;
1692                         }
1693                 } else
1694                         *(t++) = *f;
1695         }
1696
1697         *t = 0;
1698
1699         return r;
1700 }
1701
1702 char *ascii_strlower(char *t) {
1703         char *p;
1704
1705         assert(t);
1706
1707         for (p = t; *p; p++)
1708                 if (*p >= 'A' && *p <= 'Z')
1709                         *p = *p - 'A' + 'a';
1710
1711         return t;
1712 }
1713
1714 static bool ignore_file_allow_backup(const char *filename) {
1715         assert(filename);
1716
1717         return
1718                 filename[0] == '.' ||
1719                 streq(filename, "lost+found") ||
1720                 streq(filename, "aquota.user") ||
1721                 streq(filename, "aquota.group") ||
1722                 endswith(filename, ".rpmnew") ||
1723                 endswith(filename, ".rpmsave") ||
1724                 endswith(filename, ".rpmorig") ||
1725                 endswith(filename, ".dpkg-old") ||
1726                 endswith(filename, ".dpkg-new") ||
1727                 endswith(filename, ".swp");
1728 }
1729
1730 bool ignore_file(const char *filename) {
1731         assert(filename);
1732
1733         if (endswith(filename, "~"))
1734                 return false;
1735
1736         return ignore_file_allow_backup(filename);
1737 }
1738
1739 int fd_nonblock(int fd, bool nonblock) {
1740         int flags;
1741
1742         assert(fd >= 0);
1743
1744         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1745                 return -errno;
1746
1747         if (nonblock)
1748                 flags |= O_NONBLOCK;
1749         else
1750                 flags &= ~O_NONBLOCK;
1751
1752         if (fcntl(fd, F_SETFL, flags) < 0)
1753                 return -errno;
1754
1755         return 0;
1756 }
1757
1758 int fd_cloexec(int fd, bool cloexec) {
1759         int flags;
1760
1761         assert(fd >= 0);
1762
1763         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1764                 return -errno;
1765
1766         if (cloexec)
1767                 flags |= FD_CLOEXEC;
1768         else
1769                 flags &= ~FD_CLOEXEC;
1770
1771         if (fcntl(fd, F_SETFD, flags) < 0)
1772                 return -errno;
1773
1774         return 0;
1775 }
1776
1777 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1778         unsigned i;
1779
1780         assert(n_fdset == 0 || fdset);
1781
1782         for (i = 0; i < n_fdset; i++)
1783                 if (fdset[i] == fd)
1784                         return true;
1785
1786         return false;
1787 }
1788
1789 int close_all_fds(const int except[], unsigned n_except) {
1790         DIR *d;
1791         struct dirent *de;
1792         int r = 0;
1793
1794         assert(n_except == 0 || except);
1795
1796         d = opendir("/proc/self/fd");
1797         if (!d) {
1798                 int fd;
1799                 struct rlimit rl;
1800
1801                 /* When /proc isn't available (for example in chroots)
1802                  * the fallback is brute forcing through the fd
1803                  * table */
1804
1805                 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1806                 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1807
1808                         if (fd_in_set(fd, except, n_except))
1809                                 continue;
1810
1811                         if (close_nointr(fd) < 0)
1812                                 if (errno != EBADF && r == 0)
1813                                         r = -errno;
1814                 }
1815
1816                 return r;
1817         }
1818
1819         while ((de = readdir(d))) {
1820                 int fd = -1;
1821
1822                 if (ignore_file(de->d_name))
1823                         continue;
1824
1825                 if (safe_atoi(de->d_name, &fd) < 0)
1826                         /* Let's better ignore this, just in case */
1827                         continue;
1828
1829                 if (fd < 3)
1830                         continue;
1831
1832                 if (fd == dirfd(d))
1833                         continue;
1834
1835                 if (fd_in_set(fd, except, n_except))
1836                         continue;
1837
1838                 if (close_nointr(fd) < 0) {
1839                         /* Valgrind has its own FD and doesn't want to have it closed */
1840                         if (errno != EBADF && r == 0)
1841                                 r = -errno;
1842                 }
1843         }
1844
1845         closedir(d);
1846         return r;
1847 }
1848
1849 bool chars_intersect(const char *a, const char *b) {
1850         const char *p;
1851
1852         /* Returns true if any of the chars in a are in b. */
1853         for (p = a; *p; p++)
1854                 if (strchr(b, *p))
1855                         return true;
1856
1857         return false;
1858 }
1859
1860 bool fstype_is_network(const char *fstype) {
1861         static const char table[] =
1862                 "cifs\0"
1863                 "smbfs\0"
1864                 "ncpfs\0"
1865                 "nfs\0"
1866                 "nfs4\0"
1867                 "gfs\0"
1868                 "gfs2\0";
1869
1870         return nulstr_contains(table, fstype);
1871 }
1872
1873 int chvt(int vt) {
1874         _cleanup_close_ int fd;
1875
1876         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1877         if (fd < 0)
1878                 return -errno;
1879
1880         if (vt < 0) {
1881                 int tiocl[2] = {
1882                         TIOCL_GETKMSGREDIRECT,
1883                         0
1884                 };
1885
1886                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1887                         return -errno;
1888
1889                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1890         }
1891
1892         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1893                 return -errno;
1894
1895         return 0;
1896 }
1897
1898 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1899         struct termios old_termios, new_termios;
1900         char c;
1901         char line[LINE_MAX];
1902
1903         assert(f);
1904         assert(ret);
1905
1906         if (tcgetattr(fileno(f), &old_termios) >= 0) {
1907                 new_termios = old_termios;
1908
1909                 new_termios.c_lflag &= ~ICANON;
1910                 new_termios.c_cc[VMIN] = 1;
1911                 new_termios.c_cc[VTIME] = 0;
1912
1913                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1914                         size_t k;
1915
1916                         if (t != (usec_t) -1) {
1917                                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1918                                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1919                                         return -ETIMEDOUT;
1920                                 }
1921                         }
1922
1923                         k = fread(&c, 1, 1, f);
1924
1925                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1926
1927                         if (k <= 0)
1928                                 return -EIO;
1929
1930                         if (need_nl)
1931                                 *need_nl = c != '\n';
1932
1933                         *ret = c;
1934                         return 0;
1935                 }
1936         }
1937
1938         if (t != (usec_t) -1)
1939                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1940                         return -ETIMEDOUT;
1941
1942         if (!fgets(line, sizeof(line), f))
1943                 return -EIO;
1944
1945         truncate_nl(line);
1946
1947         if (strlen(line) != 1)
1948                 return -EBADMSG;
1949
1950         if (need_nl)
1951                 *need_nl = false;
1952
1953         *ret = line[0];
1954         return 0;
1955 }
1956
1957 int ask(char *ret, const char *replies, const char *text, ...) {
1958
1959         assert(ret);
1960         assert(replies);
1961         assert(text);
1962
1963         for (;;) {
1964                 va_list ap;
1965                 char c;
1966                 int r;
1967                 bool need_nl = true;
1968
1969                 if (on_tty())
1970                         fputs(ANSI_HIGHLIGHT_ON, stdout);
1971
1972                 va_start(ap, text);
1973                 vprintf(text, ap);
1974                 va_end(ap);
1975
1976                 if (on_tty())
1977                         fputs(ANSI_HIGHLIGHT_OFF, stdout);
1978
1979                 fflush(stdout);
1980
1981                 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1982                 if (r < 0) {
1983
1984                         if (r == -EBADMSG) {
1985                                 puts("Bad input, please try again.");
1986                                 continue;
1987                         }
1988
1989                         putchar('\n');
1990                         return r;
1991                 }
1992
1993                 if (need_nl)
1994                         putchar('\n');
1995
1996                 if (strchr(replies, c)) {
1997                         *ret = c;
1998                         return 0;
1999                 }
2000
2001                 puts("Read unexpected character, please try again.");
2002         }
2003 }
2004
2005 int reset_terminal_fd(int fd, bool switch_to_text) {
2006         struct termios termios;
2007         int r = 0;
2008
2009         /* Set terminal to some sane defaults */
2010
2011         assert(fd >= 0);
2012
2013         /* We leave locked terminal attributes untouched, so that
2014          * Plymouth may set whatever it wants to set, and we don't
2015          * interfere with that. */
2016
2017         /* Disable exclusive mode, just in case */
2018         ioctl(fd, TIOCNXCL);
2019
2020         /* Switch to text mode */
2021         if (switch_to_text)
2022                 ioctl(fd, KDSETMODE, KD_TEXT);
2023
2024         /* Enable console unicode mode */
2025         ioctl(fd, KDSKBMODE, K_UNICODE);
2026
2027         if (tcgetattr(fd, &termios) < 0) {
2028                 r = -errno;
2029                 goto finish;
2030         }
2031
2032         /* We only reset the stuff that matters to the software. How
2033          * hardware is set up we don't touch assuming that somebody
2034          * else will do that for us */
2035
2036         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2037         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2038         termios.c_oflag |= ONLCR;
2039         termios.c_cflag |= CREAD;
2040         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2041
2042         termios.c_cc[VINTR]    =   03;  /* ^C */
2043         termios.c_cc[VQUIT]    =  034;  /* ^\ */
2044         termios.c_cc[VERASE]   = 0177;
2045         termios.c_cc[VKILL]    =  025;  /* ^X */
2046         termios.c_cc[VEOF]     =   04;  /* ^D */
2047         termios.c_cc[VSTART]   =  021;  /* ^Q */
2048         termios.c_cc[VSTOP]    =  023;  /* ^S */
2049         termios.c_cc[VSUSP]    =  032;  /* ^Z */
2050         termios.c_cc[VLNEXT]   =  026;  /* ^V */
2051         termios.c_cc[VWERASE]  =  027;  /* ^W */
2052         termios.c_cc[VREPRINT] =  022;  /* ^R */
2053         termios.c_cc[VEOL]     =    0;
2054         termios.c_cc[VEOL2]    =    0;
2055
2056         termios.c_cc[VTIME]  = 0;
2057         termios.c_cc[VMIN]   = 1;
2058
2059         if (tcsetattr(fd, TCSANOW, &termios) < 0)
2060                 r = -errno;
2061
2062 finish:
2063         /* Just in case, flush all crap out */
2064         tcflush(fd, TCIOFLUSH);
2065
2066         return r;
2067 }
2068
2069 int reset_terminal(const char *name) {
2070         int fd, r;
2071
2072         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2073         if (fd < 0)
2074                 return fd;
2075
2076         r = reset_terminal_fd(fd, true);
2077         close_nointr_nofail(fd);
2078
2079         return r;
2080 }
2081
2082 int open_terminal(const char *name, int mode) {
2083         int fd, r;
2084         unsigned c = 0;
2085
2086         /*
2087          * If a TTY is in the process of being closed opening it might
2088          * cause EIO. This is horribly awful, but unlikely to be
2089          * changed in the kernel. Hence we work around this problem by
2090          * retrying a couple of times.
2091          *
2092          * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2093          */
2094
2095         for (;;) {
2096                 fd = open(name, mode);
2097                 if (fd >= 0)
2098                         break;
2099
2100                 if (errno != EIO)
2101                         return -errno;
2102
2103                 /* Max 1s in total */
2104                 if (c >= 20)
2105                         return -errno;
2106
2107                 usleep(50 * USEC_PER_MSEC);
2108                 c++;
2109         }
2110
2111         if (fd < 0)
2112                 return -errno;
2113
2114         r = isatty(fd);
2115         if (r < 0) {
2116                 close_nointr_nofail(fd);
2117                 return -errno;
2118         }
2119
2120         if (!r) {
2121                 close_nointr_nofail(fd);
2122                 return -ENOTTY;
2123         }
2124
2125         return fd;
2126 }
2127
2128 int flush_fd(int fd) {
2129         struct pollfd pollfd;
2130
2131         zero(pollfd);
2132         pollfd.fd = fd;
2133         pollfd.events = POLLIN;
2134
2135         for (;;) {
2136                 char buf[LINE_MAX];
2137                 ssize_t l;
2138                 int r;
2139
2140                 if ((r = poll(&pollfd, 1, 0)) < 0) {
2141
2142                         if (errno == EINTR)
2143                                 continue;
2144
2145                         return -errno;
2146                 }
2147
2148                 if (r == 0)
2149                         return 0;
2150
2151                 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2152
2153                         if (errno == EINTR)
2154                                 continue;
2155
2156                         if (errno == EAGAIN)
2157                                 return 0;
2158
2159                         return -errno;
2160                 }
2161
2162                 if (l <= 0)
2163                         return 0;
2164         }
2165 }
2166
2167 int acquire_terminal(
2168                 const char *name,
2169                 bool fail,
2170                 bool force,
2171                 bool ignore_tiocstty_eperm,
2172                 usec_t timeout) {
2173
2174         int fd = -1, notify = -1, r = 0, wd = -1;
2175         usec_t ts = 0;
2176         struct sigaction sa_old, sa_new;
2177
2178         assert(name);
2179
2180         /* We use inotify to be notified when the tty is closed. We
2181          * create the watch before checking if we can actually acquire
2182          * it, so that we don't lose any event.
2183          *
2184          * Note: strictly speaking this actually watches for the
2185          * device being closed, it does *not* really watch whether a
2186          * tty loses its controlling process. However, unless some
2187          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2188          * its tty otherwise this will not become a problem. As long
2189          * as the administrator makes sure not configure any service
2190          * on the same tty as an untrusted user this should not be a
2191          * problem. (Which he probably should not do anyway.) */
2192
2193         if (timeout != (usec_t) -1)
2194                 ts = now(CLOCK_MONOTONIC);
2195
2196         if (!fail && !force) {
2197                 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2198                 if (notify < 0) {
2199                         r = -errno;
2200                         goto fail;
2201                 }
2202
2203                 wd = inotify_add_watch(notify, name, IN_CLOSE);
2204                 if (wd < 0) {
2205                         r = -errno;
2206                         goto fail;
2207                 }
2208         }
2209
2210         for (;;) {
2211                 if (notify >= 0) {
2212                         r = flush_fd(notify);
2213                         if (r < 0)
2214                                 goto fail;
2215                 }
2216
2217                 /* We pass here O_NOCTTY only so that we can check the return
2218                  * value TIOCSCTTY and have a reliable way to figure out if we
2219                  * successfully became the controlling process of the tty */
2220                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2221                 if (fd < 0)
2222                         return fd;
2223
2224                 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2225                  * if we already own the tty. */
2226                 zero(sa_new);
2227                 sa_new.sa_handler = SIG_IGN;
2228                 sa_new.sa_flags = SA_RESTART;
2229                 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2230
2231                 /* First, try to get the tty */
2232                 if (ioctl(fd, TIOCSCTTY, force) < 0)
2233                         r = -errno;
2234
2235                 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2236
2237                 /* Sometimes it makes sense to ignore TIOCSCTTY
2238                  * returning EPERM, i.e. when very likely we already
2239                  * are have this controlling terminal. */
2240                 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2241                         r = 0;
2242
2243                 if (r < 0 && (force || fail || r != -EPERM)) {
2244                         goto fail;
2245                 }
2246
2247                 if (r >= 0)
2248                         break;
2249
2250                 assert(!fail);
2251                 assert(!force);
2252                 assert(notify >= 0);
2253
2254                 for (;;) {
2255                         uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2256                         ssize_t l;
2257                         struct inotify_event *e;
2258
2259                         if (timeout != (usec_t) -1) {
2260                                 usec_t n;
2261
2262                                 n = now(CLOCK_MONOTONIC);
2263                                 if (ts + timeout < n) {
2264                                         r = -ETIMEDOUT;
2265                                         goto fail;
2266                                 }
2267
2268                                 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2269                                 if (r < 0)
2270                                         goto fail;
2271
2272                                 if (r == 0) {
2273                                         r = -ETIMEDOUT;
2274                                         goto fail;
2275                                 }
2276                         }
2277
2278                         l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2279                         if (l < 0) {
2280
2281                                 if (errno == EINTR || errno == EAGAIN)
2282                                         continue;
2283
2284                                 r = -errno;
2285                                 goto fail;
2286                         }
2287
2288                         e = (struct inotify_event*) inotify_buffer;
2289
2290                         while (l > 0) {
2291                                 size_t step;
2292
2293                                 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2294                                         r = -EIO;
2295                                         goto fail;
2296                                 }
2297
2298                                 step = sizeof(struct inotify_event) + e->len;
2299                                 assert(step <= (size_t) l);
2300
2301                                 e = (struct inotify_event*) ((uint8_t*) e + step);
2302                                 l -= step;
2303                         }
2304
2305                         break;
2306                 }
2307
2308                 /* We close the tty fd here since if the old session
2309                  * ended our handle will be dead. It's important that
2310                  * we do this after sleeping, so that we don't enter
2311                  * an endless loop. */
2312                 close_nointr_nofail(fd);
2313         }
2314
2315         if (notify >= 0)
2316                 close_nointr_nofail(notify);
2317
2318         r = reset_terminal_fd(fd, true);
2319         if (r < 0)
2320                 log_warning("Failed to reset terminal: %s", strerror(-r));
2321
2322         return fd;
2323
2324 fail:
2325         if (fd >= 0)
2326                 close_nointr_nofail(fd);
2327
2328         if (notify >= 0)
2329                 close_nointr_nofail(notify);
2330
2331         return r;
2332 }
2333
2334 int release_terminal(void) {
2335         int r = 0, fd;
2336         struct sigaction sa_old, sa_new;
2337
2338         if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2339                 return -errno;
2340
2341         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2342          * by our own TIOCNOTTY */
2343
2344         zero(sa_new);
2345         sa_new.sa_handler = SIG_IGN;
2346         sa_new.sa_flags = SA_RESTART;
2347         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2348
2349         if (ioctl(fd, TIOCNOTTY) < 0)
2350                 r = -errno;
2351
2352         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2353
2354         close_nointr_nofail(fd);
2355         return r;
2356 }
2357
2358 int sigaction_many(const struct sigaction *sa, ...) {
2359         va_list ap;
2360         int r = 0, sig;
2361
2362         va_start(ap, sa);
2363         while ((sig = va_arg(ap, int)) > 0)
2364                 if (sigaction(sig, sa, NULL) < 0)
2365                         r = -errno;
2366         va_end(ap);
2367
2368         return r;
2369 }
2370
2371 int ignore_signals(int sig, ...) {
2372         struct sigaction sa;
2373         va_list ap;
2374         int r = 0;
2375
2376         zero(sa);
2377         sa.sa_handler = SIG_IGN;
2378         sa.sa_flags = SA_RESTART;
2379
2380         if (sigaction(sig, &sa, NULL) < 0)
2381                 r = -errno;
2382
2383         va_start(ap, sig);
2384         while ((sig = va_arg(ap, int)) > 0)
2385                 if (sigaction(sig, &sa, NULL) < 0)
2386                         r = -errno;
2387         va_end(ap);
2388
2389         return r;
2390 }
2391
2392 int default_signals(int sig, ...) {
2393         struct sigaction sa;
2394         va_list ap;
2395         int r = 0;
2396
2397         zero(sa);
2398         sa.sa_handler = SIG_DFL;
2399         sa.sa_flags = SA_RESTART;
2400
2401         if (sigaction(sig, &sa, NULL) < 0)
2402                 r = -errno;
2403
2404         va_start(ap, sig);
2405         while ((sig = va_arg(ap, int)) > 0)
2406                 if (sigaction(sig, &sa, NULL) < 0)
2407                         r = -errno;
2408         va_end(ap);
2409
2410         return r;
2411 }
2412
2413 int close_pipe(int p[]) {
2414         int a = 0, b = 0;
2415
2416         assert(p);
2417
2418         if (p[0] >= 0) {
2419                 a = close_nointr(p[0]);
2420                 p[0] = -1;
2421         }
2422
2423         if (p[1] >= 0) {
2424                 b = close_nointr(p[1]);
2425                 p[1] = -1;
2426         }
2427
2428         return a < 0 ? a : b;
2429 }
2430
2431 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2432         uint8_t *p;
2433         ssize_t n = 0;
2434
2435         assert(fd >= 0);
2436         assert(buf);
2437
2438         p = buf;
2439
2440         while (nbytes > 0) {
2441                 ssize_t k;
2442
2443                 if ((k = read(fd, p, nbytes)) <= 0) {
2444
2445                         if (k < 0 && errno == EINTR)
2446                                 continue;
2447
2448                         if (k < 0 && errno == EAGAIN && do_poll) {
2449                                 struct pollfd pollfd;
2450
2451                                 zero(pollfd);
2452                                 pollfd.fd = fd;
2453                                 pollfd.events = POLLIN;
2454
2455                                 if (poll(&pollfd, 1, -1) < 0) {
2456                                         if (errno == EINTR)
2457                                                 continue;
2458
2459                                         return n > 0 ? n : -errno;
2460                                 }
2461
2462                                 if (pollfd.revents != POLLIN)
2463                                         return n > 0 ? n : -EIO;
2464
2465                                 continue;
2466                         }
2467
2468                         return n > 0 ? n : (k < 0 ? -errno : 0);
2469                 }
2470
2471                 p += k;
2472                 nbytes -= k;
2473                 n += k;
2474         }
2475
2476         return n;
2477 }
2478
2479 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2480         const uint8_t *p;
2481         ssize_t n = 0;
2482
2483         assert(fd >= 0);
2484         assert(buf);
2485
2486         p = buf;
2487
2488         while (nbytes > 0) {
2489                 ssize_t k;
2490
2491                 k = write(fd, p, nbytes);
2492                 if (k <= 0) {
2493
2494                         if (k < 0 && errno == EINTR)
2495                                 continue;
2496
2497                         if (k < 0 && errno == EAGAIN && do_poll) {
2498                                 struct pollfd pollfd;
2499
2500                                 zero(pollfd);
2501                                 pollfd.fd = fd;
2502                                 pollfd.events = POLLOUT;
2503
2504                                 if (poll(&pollfd, 1, -1) < 0) {
2505                                         if (errno == EINTR)
2506                                                 continue;
2507
2508                                         return n > 0 ? n : -errno;
2509                                 }
2510
2511                                 if (pollfd.revents != POLLOUT)
2512                                         return n > 0 ? n : -EIO;
2513
2514                                 continue;
2515                         }
2516
2517                         return n > 0 ? n : (k < 0 ? -errno : 0);
2518                 }
2519
2520                 p += k;
2521                 nbytes -= k;
2522                 n += k;
2523         }
2524
2525         return n;
2526 }
2527
2528 int parse_bytes(const char *t, off_t *bytes) {
2529         static const struct {
2530                 const char *suffix;
2531                 off_t factor;
2532         } table[] = {
2533                 { "B", 1 },
2534                 { "K", 1024ULL },
2535                 { "M", 1024ULL*1024ULL },
2536                 { "G", 1024ULL*1024ULL*1024ULL },
2537                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2538                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2539                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2540                 { "", 1 },
2541         };
2542
2543         const char *p;
2544         off_t r = 0;
2545
2546         assert(t);
2547         assert(bytes);
2548
2549         p = t;
2550         do {
2551                 long long l;
2552                 char *e;
2553                 unsigned i;
2554
2555                 errno = 0;
2556                 l = strtoll(p, &e, 10);
2557
2558                 if (errno != 0)
2559                         return -errno;
2560
2561                 if (l < 0)
2562                         return -ERANGE;
2563
2564                 if (e == p)
2565                         return -EINVAL;
2566
2567                 e += strspn(e, WHITESPACE);
2568
2569                 for (i = 0; i < ELEMENTSOF(table); i++)
2570                         if (startswith(e, table[i].suffix)) {
2571                                 r += (off_t) l * table[i].factor;
2572                                 p = e + strlen(table[i].suffix);
2573                                 break;
2574                         }
2575
2576                 if (i >= ELEMENTSOF(table))
2577                         return -EINVAL;
2578
2579         } while (*p != 0);
2580
2581         *bytes = r;
2582
2583         return 0;
2584 }
2585
2586 int make_stdio(int fd) {
2587         int r, s, t;
2588
2589         assert(fd >= 0);
2590
2591         r = dup3(fd, STDIN_FILENO, 0);
2592         s = dup3(fd, STDOUT_FILENO, 0);
2593         t = dup3(fd, STDERR_FILENO, 0);
2594
2595         if (fd >= 3)
2596                 close_nointr_nofail(fd);
2597
2598         if (r < 0 || s < 0 || t < 0)
2599                 return -errno;
2600
2601         /* We rely here that the new fd has O_CLOEXEC not set */
2602
2603         return 0;
2604 }
2605
2606 int make_null_stdio(void) {
2607         int null_fd;
2608
2609         null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2610         if (null_fd < 0)
2611                 return -errno;
2612
2613         return make_stdio(null_fd);
2614 }
2615
2616 bool is_device_path(const char *path) {
2617
2618         /* Returns true on paths that refer to a device, either in
2619          * sysfs or in /dev */
2620
2621         return
2622                 path_startswith(path, "/dev/") ||
2623                 path_startswith(path, "/sys/");
2624 }
2625
2626 int dir_is_empty(const char *path) {
2627         _cleanup_closedir_ DIR *d;
2628         int r;
2629
2630         d = opendir(path);
2631         if (!d)
2632                 return -errno;
2633
2634         for (;;) {
2635                 struct dirent *de;
2636                 union dirent_storage buf;
2637
2638                 r = readdir_r(d, &buf.de, &de);
2639                 if (r > 0)
2640                         return -r;
2641
2642                 if (!de)
2643                         return 1;
2644
2645                 if (!ignore_file(de->d_name))
2646                         return 0;
2647         }
2648 }
2649
2650 unsigned long long random_ull(void) {
2651         _cleanup_close_ int fd;
2652         uint64_t ull;
2653         ssize_t r;
2654
2655         fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2656         if (fd < 0)
2657                 goto fallback;
2658
2659         r = loop_read(fd, &ull, sizeof(ull), true);
2660         if (r != sizeof(ull))
2661                 goto fallback;
2662
2663         return ull;
2664
2665 fallback:
2666         return random() * RAND_MAX + random();
2667 }
2668
2669 void rename_process(const char name[8]) {
2670         assert(name);
2671
2672         /* This is a like a poor man's setproctitle(). It changes the
2673          * comm field, argv[0], and also the glibc's internally used
2674          * name of the process. For the first one a limit of 16 chars
2675          * applies, to the second one usually one of 10 (i.e. length
2676          * of "/sbin/init"), to the third one one of 7 (i.e. length of
2677          * "systemd"). If you pass a longer string it will be
2678          * truncated */
2679
2680         prctl(PR_SET_NAME, name);
2681
2682         if (program_invocation_name)
2683                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2684
2685         if (saved_argc > 0) {
2686                 int i;
2687
2688                 if (saved_argv[0])
2689                         strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2690
2691                 for (i = 1; i < saved_argc; i++) {
2692                         if (!saved_argv[i])
2693                                 break;
2694
2695                         memset(saved_argv[i], 0, strlen(saved_argv[i]));
2696                 }
2697         }
2698 }
2699
2700 void sigset_add_many(sigset_t *ss, ...) {
2701         va_list ap;
2702         int sig;
2703
2704         assert(ss);
2705
2706         va_start(ap, ss);
2707         while ((sig = va_arg(ap, int)) > 0)
2708                 assert_se(sigaddset(ss, sig) == 0);
2709         va_end(ap);
2710 }
2711
2712 char* gethostname_malloc(void) {
2713         struct utsname u;
2714
2715         assert_se(uname(&u) >= 0);
2716
2717         if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2718                 return strdup(u.nodename);
2719
2720         return strdup(u.sysname);
2721 }
2722
2723 bool hostname_is_set(void) {
2724         struct utsname u;
2725
2726         assert_se(uname(&u) >= 0);
2727
2728         return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2729 }
2730
2731 static char *lookup_uid(uid_t uid) {
2732         long bufsize;
2733         char *name;
2734         _cleanup_free_ char *buf = NULL;
2735         struct passwd pwbuf, *pw = NULL;
2736
2737         /* Shortcut things to avoid NSS lookups */
2738         if (uid == 0)
2739                 return strdup("root");
2740
2741         bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2742         if (bufsize <= 0)
2743                 bufsize = 4096;
2744
2745         buf = malloc(bufsize);
2746         if (!buf)
2747                 return NULL;
2748
2749         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2750                 return strdup(pw->pw_name);
2751
2752         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2753                 return NULL;
2754
2755         return name;
2756 }
2757
2758 char* getlogname_malloc(void) {
2759         uid_t uid;
2760         struct stat st;
2761
2762         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2763                 uid = st.st_uid;
2764         else
2765                 uid = getuid();
2766
2767         return lookup_uid(uid);
2768 }
2769
2770 char *getusername_malloc(void) {
2771         const char *e;
2772
2773         e = getenv("USER");
2774         if (e)
2775                 return strdup(e);
2776
2777         return lookup_uid(getuid());
2778 }
2779
2780 int getttyname_malloc(int fd, char **r) {
2781         char path[PATH_MAX], *c;
2782         int k;
2783
2784         assert(r);
2785
2786         k = ttyname_r(fd, path, sizeof(path));
2787         if (k != 0)
2788                 return -k;
2789
2790         char_array_0(path);
2791
2792         c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2793         if (!c)
2794                 return -ENOMEM;
2795
2796         *r = c;
2797         return 0;
2798 }
2799
2800 int getttyname_harder(int fd, char **r) {
2801         int k;
2802         char *s;
2803
2804         k = getttyname_malloc(fd, &s);
2805         if (k < 0)
2806                 return k;
2807
2808         if (streq(s, "tty")) {
2809                 free(s);
2810                 return get_ctty(0, NULL, r);
2811         }
2812
2813         *r = s;
2814         return 0;
2815 }
2816
2817 int get_ctty_devnr(pid_t pid, dev_t *d) {
2818         int k;
2819         char line[LINE_MAX], *p, *fn;
2820         unsigned long ttynr;
2821         FILE *f;
2822
2823         if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2824                 return -ENOMEM;
2825
2826         f = fopen(fn, "re");
2827         free(fn);
2828         if (!f)
2829                 return -errno;
2830
2831         if (!fgets(line, sizeof(line), f)) {
2832                 k = feof(f) ? -EIO : -errno;
2833                 fclose(f);
2834                 return k;
2835         }
2836
2837         fclose(f);
2838
2839         p = strrchr(line, ')');
2840         if (!p)
2841                 return -EIO;
2842
2843         p++;
2844
2845         if (sscanf(p, " "
2846                    "%*c "  /* state */
2847                    "%*d "  /* ppid */
2848                    "%*d "  /* pgrp */
2849                    "%*d "  /* session */
2850                    "%lu ", /* ttynr */
2851                    &ttynr) != 1)
2852                 return -EIO;
2853
2854         *d = (dev_t) ttynr;
2855         return 0;
2856 }
2857
2858 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2859         int k;
2860         char fn[PATH_MAX], *s, *b, *p;
2861         dev_t devnr;
2862
2863         assert(r);
2864
2865         k = get_ctty_devnr(pid, &devnr);
2866         if (k < 0)
2867                 return k;
2868
2869         snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2870         char_array_0(fn);
2871
2872         k = readlink_malloc(fn, &s);
2873         if (k < 0) {
2874
2875                 if (k != -ENOENT)
2876                         return k;
2877
2878                 /* This is an ugly hack */
2879                 if (major(devnr) == 136) {
2880                         if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2881                                 return -ENOMEM;
2882
2883                         *r = b;
2884                         if (_devnr)
2885                                 *_devnr = devnr;
2886
2887                         return 0;
2888                 }
2889
2890                 /* Probably something like the ptys which have no
2891                  * symlink in /dev/char. Let's return something
2892                  * vaguely useful. */
2893
2894                 b = strdup(fn + 5);
2895                 if (!b)
2896                         return -ENOMEM;
2897
2898                 *r = b;
2899                 if (_devnr)
2900                         *_devnr = devnr;
2901
2902                 return 0;
2903         }
2904
2905         if (startswith(s, "/dev/"))
2906                 p = s + 5;
2907         else if (startswith(s, "../"))
2908                 p = s + 3;
2909         else
2910                 p = s;
2911
2912         b = strdup(p);
2913         free(s);
2914
2915         if (!b)
2916                 return -ENOMEM;
2917
2918         *r = b;
2919         if (_devnr)
2920                 *_devnr = devnr;
2921
2922         return 0;
2923 }
2924
2925 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2926         DIR *d;
2927         int ret = 0;
2928
2929         assert(fd >= 0);
2930
2931         /* This returns the first error we run into, but nevertheless
2932          * tries to go on. This closes the passed fd. */
2933
2934         d = fdopendir(fd);
2935         if (!d) {
2936                 close_nointr_nofail(fd);
2937
2938                 return errno == ENOENT ? 0 : -errno;
2939         }
2940
2941         for (;;) {
2942                 struct dirent *de;
2943                 union dirent_storage buf;
2944                 bool is_dir, keep_around;
2945                 struct stat st;
2946                 int r;
2947
2948                 r = readdir_r(d, &buf.de, &de);
2949                 if (r != 0 && ret == 0) {
2950                         ret = -r;
2951                         break;
2952                 }
2953
2954                 if (!de)
2955                         break;
2956
2957                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2958                         continue;
2959
2960                 if (de->d_type == DT_UNKNOWN ||
2961                     honour_sticky ||
2962                     (de->d_type == DT_DIR && root_dev)) {
2963                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2964                                 if (ret == 0 && errno != ENOENT)
2965                                         ret = -errno;
2966                                 continue;
2967                         }
2968
2969                         is_dir = S_ISDIR(st.st_mode);
2970                         keep_around =
2971                                 honour_sticky &&
2972                                 (st.st_uid == 0 || st.st_uid == getuid()) &&
2973                                 (st.st_mode & S_ISVTX);
2974                 } else {
2975                         is_dir = de->d_type == DT_DIR;
2976                         keep_around = false;
2977                 }
2978
2979                 if (is_dir) {
2980                         int subdir_fd;
2981
2982                         /* if root_dev is set, remove subdirectories only, if device is same as dir */
2983                         if (root_dev && st.st_dev != root_dev->st_dev)
2984                                 continue;
2985
2986                         subdir_fd = openat(fd, de->d_name,
2987                                            O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2988                         if (subdir_fd < 0) {
2989                                 if (ret == 0 && errno != ENOENT)
2990                                         ret = -errno;
2991                                 continue;
2992                         }
2993
2994                         r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2995                         if (r < 0 && ret == 0)
2996                                 ret = r;
2997
2998                         if (!keep_around)
2999                                 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3000                                         if (ret == 0 && errno != ENOENT)
3001                                                 ret = -errno;
3002                                 }
3003
3004                 } else if (!only_dirs && !keep_around) {
3005
3006                         if (unlinkat(fd, de->d_name, 0) < 0) {
3007                                 if (ret == 0 && errno != ENOENT)
3008                                         ret = -errno;
3009                         }
3010                 }
3011         }
3012
3013         closedir(d);
3014
3015         return ret;
3016 }
3017
3018 static int is_temporary_fs(struct statfs *s) {
3019         assert(s);
3020         return s->f_type == TMPFS_MAGIC ||
3021                 (long)s->f_type == (long)RAMFS_MAGIC;
3022 }
3023
3024 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3025         struct statfs s;
3026
3027         assert(fd >= 0);
3028
3029         if (fstatfs(fd, &s) < 0) {
3030                 close_nointr_nofail(fd);
3031                 return -errno;
3032         }
3033
3034         /* We refuse to clean disk file systems with this call. This
3035          * is extra paranoia just to be sure we never ever remove
3036          * non-state data */
3037         if (!is_temporary_fs(&s)) {
3038                 log_error("Attempted to remove disk file system, and we can't allow that.");
3039                 close_nointr_nofail(fd);
3040                 return -EPERM;
3041         }
3042
3043         return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3044 }
3045
3046 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3047         int fd, r;
3048         struct statfs s;
3049
3050         assert(path);
3051
3052         /* We refuse to clean the root file system with this
3053          * call. This is extra paranoia to never cause a really
3054          * seriously broken system. */
3055         if (path_equal(path, "/")) {
3056                 log_error("Attempted to remove entire root file system, and we can't allow that.");
3057                 return -EPERM;
3058         }
3059
3060         fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3061         if (fd < 0) {
3062
3063                 if (errno != ENOTDIR)
3064                         return -errno;
3065
3066                 if (!dangerous) {
3067                         if (statfs(path, &s) < 0)
3068                                 return -errno;
3069
3070                         if (!is_temporary_fs(&s)) {
3071                                 log_error("Attempted to remove disk file system, and we can't allow that.");
3072                                 return -EPERM;
3073                         }
3074                 }
3075
3076                 if (delete_root && !only_dirs)
3077                         if (unlink(path) < 0 && errno != ENOENT)
3078                                 return -errno;
3079
3080                 return 0;
3081         }
3082
3083         if (!dangerous) {
3084                 if (fstatfs(fd, &s) < 0) {
3085                         close_nointr_nofail(fd);
3086                         return -errno;
3087                 }
3088
3089                 if (!is_temporary_fs(&s)) {
3090                         log_error("Attempted to remove disk file system, and we can't allow that.");
3091                         close_nointr_nofail(fd);
3092                         return -EPERM;
3093                 }
3094         }
3095
3096         r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3097         if (delete_root) {
3098
3099                 if (honour_sticky && file_is_priv_sticky(path) > 0)
3100                         return r;
3101
3102                 if (rmdir(path) < 0 && errno != ENOENT) {
3103                         if (r == 0)
3104                                 r = -errno;
3105                 }
3106         }
3107
3108         return r;
3109 }
3110
3111 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3112         return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3113 }
3114
3115 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3116         return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3117 }
3118
3119 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3120         assert(path);
3121
3122         /* Under the assumption that we are running privileged we
3123          * first change the access mode and only then hand out
3124          * ownership to avoid a window where access is too open. */
3125
3126         if (mode != (mode_t) -1)
3127                 if (chmod(path, mode) < 0)
3128                         return -errno;
3129
3130         if (uid != (uid_t) -1 || gid != (gid_t) -1)
3131                 if (chown(path, uid, gid) < 0)
3132                         return -errno;
3133
3134         return 0;
3135 }
3136
3137 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3138         assert(fd >= 0);
3139
3140         /* Under the assumption that we are running privileged we
3141          * first change the access mode and only then hand out
3142          * ownership to avoid a window where access is too open. */
3143
3144         if (fchmod(fd, mode) < 0)
3145                 return -errno;
3146
3147         if (fchown(fd, uid, gid) < 0)
3148                 return -errno;
3149
3150         return 0;
3151 }
3152
3153 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3154         cpu_set_t *r;
3155         unsigned n = 1024;
3156
3157         /* Allocates the cpuset in the right size */
3158
3159         for (;;) {
3160                 if (!(r = CPU_ALLOC(n)))
3161                         return NULL;
3162
3163                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3164                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3165
3166                         if (ncpus)
3167                                 *ncpus = n;
3168
3169                         return r;
3170                 }
3171
3172                 CPU_FREE(r);
3173
3174                 if (errno != EINVAL)
3175                         return NULL;
3176
3177                 n *= 2;
3178         }
3179 }
3180
3181 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3182         static const char status_indent[] = "         "; /* "[" STATUS "] " */
3183         _cleanup_free_ char *s = NULL;
3184         _cleanup_close_ int fd = -1;
3185         struct iovec iovec[5];
3186         int n = 0;
3187
3188         assert(format);
3189
3190         /* This is independent of logging, as status messages are
3191          * optional and go exclusively to the console. */
3192
3193         if (vasprintf(&s, format, ap) < 0)
3194                 return log_oom();
3195
3196         fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3197         if (fd < 0)
3198                 return fd;
3199
3200         if (ellipse) {
3201                 char *e;
3202                 size_t emax, sl;
3203                 int c;
3204
3205                 c = fd_columns(fd);
3206                 if (c <= 0)
3207                         c = 80;
3208
3209                 sl = status ? sizeof(status_indent)-1 : 0;
3210
3211                 emax = c - sl - 1;
3212                 if (emax < 3)
3213                         emax = 3;
3214
3215                 e = ellipsize(s, emax, 75);
3216                 if (e) {
3217                         free(s);
3218                         s = e;
3219                 }
3220         }
3221
3222         zero(iovec);
3223
3224         if (status) {
3225                 if (!isempty(status)) {
3226                         IOVEC_SET_STRING(iovec[n++], "[");
3227                         IOVEC_SET_STRING(iovec[n++], status);
3228                         IOVEC_SET_STRING(iovec[n++], "] ");
3229                 } else
3230                         IOVEC_SET_STRING(iovec[n++], status_indent);
3231         }
3232
3233         IOVEC_SET_STRING(iovec[n++], s);
3234         IOVEC_SET_STRING(iovec[n++], "\n");
3235
3236         if (writev(fd, iovec, n) < 0)
3237                 return -errno;
3238
3239         return 0;
3240 }
3241
3242 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3243         va_list ap;
3244         int r;
3245
3246         assert(format);
3247
3248         va_start(ap, format);
3249         r = status_vprintf(status, ellipse, format, ap);
3250         va_end(ap);
3251
3252         return r;
3253 }
3254
3255 int status_welcome(void) {
3256         int r;
3257         _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3258
3259         r = parse_env_file("/etc/os-release", NEWLINE,
3260                            "PRETTY_NAME", &pretty_name,
3261                            "ANSI_COLOR", &ansi_color,
3262                            NULL);
3263         if (r < 0 && r != -ENOENT)
3264                 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3265
3266         return status_printf(NULL, false,
3267                              "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3268                              isempty(ansi_color) ? "1" : ansi_color,
3269                              isempty(pretty_name) ? "Linux" : pretty_name);
3270 }
3271
3272 char *replace_env(const char *format, char **env) {
3273         enum {
3274                 WORD,
3275                 CURLY,
3276                 VARIABLE
3277         } state = WORD;
3278
3279         const char *e, *word = format;
3280         char *r = NULL, *k;
3281
3282         assert(format);
3283
3284         for (e = format; *e; e ++) {
3285
3286                 switch (state) {
3287
3288                 case WORD:
3289                         if (*e == '$')
3290                                 state = CURLY;
3291                         break;
3292
3293                 case CURLY:
3294                         if (*e == '{') {
3295                                 if (!(k = strnappend(r, word, e-word-1)))
3296                                         goto fail;
3297
3298                                 free(r);
3299                                 r = k;
3300
3301                                 word = e-1;
3302                                 state = VARIABLE;
3303
3304                         } else if (*e == '$') {
3305                                 if (!(k = strnappend(r, word, e-word)))
3306                                         goto fail;
3307
3308                                 free(r);
3309                                 r = k;
3310
3311                                 word = e+1;
3312                                 state = WORD;
3313                         } else
3314                                 state = WORD;
3315                         break;
3316
3317                 case VARIABLE:
3318                         if (*e == '}') {
3319                                 const char *t;
3320
3321                                 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3322                                         t = "";
3323
3324                                 if (!(k = strappend(r, t)))
3325                                         goto fail;
3326
3327                                 free(r);
3328                                 r = k;
3329
3330                                 word = e+1;
3331                                 state = WORD;
3332                         }
3333                         break;
3334                 }
3335         }
3336
3337         if (!(k = strnappend(r, word, e-word)))
3338                 goto fail;
3339
3340         free(r);
3341         return k;
3342
3343 fail:
3344         free(r);
3345         return NULL;
3346 }
3347
3348 char **replace_env_argv(char **argv, char **env) {
3349         char **r, **i;
3350         unsigned k = 0, l = 0;
3351
3352         l = strv_length(argv);
3353
3354         if (!(r = new(char*, l+1)))
3355                 return NULL;
3356
3357         STRV_FOREACH(i, argv) {
3358
3359                 /* If $FOO appears as single word, replace it by the split up variable */
3360                 if ((*i)[0] == '$' && (*i)[1] != '{') {
3361                         char *e;
3362                         char **w, **m;
3363                         unsigned q;
3364
3365                         if ((e = strv_env_get(env, *i+1))) {
3366
3367                                 if (!(m = strv_split_quoted(e))) {
3368                                         r[k] = NULL;
3369                                         strv_free(r);
3370                                         return NULL;
3371                                 }
3372                         } else
3373                                 m = NULL;
3374
3375                         q = strv_length(m);
3376                         l = l + q - 1;
3377
3378                         if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3379                                 r[k] = NULL;
3380                                 strv_free(r);
3381                                 strv_free(m);
3382                                 return NULL;
3383                         }
3384
3385                         r = w;
3386                         if (m) {
3387                                 memcpy(r + k, m, q * sizeof(char*));
3388                                 free(m);
3389                         }
3390
3391                         k += q;
3392                         continue;
3393                 }
3394
3395                 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3396                 if (!(r[k++] = replace_env(*i, env))) {
3397                         strv_free(r);
3398                         return NULL;
3399                 }
3400         }
3401
3402         r[k] = NULL;
3403         return r;
3404 }
3405
3406 int fd_columns(int fd) {
3407         struct winsize ws;
3408         zero(ws);
3409
3410         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3411                 return -errno;
3412
3413         if (ws.ws_col <= 0)
3414                 return -EIO;
3415
3416         return ws.ws_col;
3417 }
3418
3419 unsigned columns(void) {
3420         const char *e;
3421         int c;
3422
3423         if (_likely_(cached_columns > 0))
3424                 return cached_columns;
3425
3426         c = 0;
3427         e = getenv("COLUMNS");
3428         if (e)
3429                 safe_atoi(e, &c);
3430
3431         if (c <= 0)
3432                 c = fd_columns(STDOUT_FILENO);
3433
3434         if (c <= 0)
3435                 c = 80;
3436
3437         cached_columns = c;
3438         return c;
3439 }
3440
3441 int fd_lines(int fd) {
3442         struct winsize ws;
3443         zero(ws);
3444
3445         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3446                 return -errno;
3447
3448         if (ws.ws_row <= 0)
3449                 return -EIO;
3450
3451         return ws.ws_row;
3452 }
3453
3454 unsigned lines(void) {
3455         const char *e;
3456         unsigned l;
3457
3458         if (_likely_(cached_lines > 0))
3459                 return cached_lines;
3460
3461         l = 0;
3462         e = getenv("LINES");
3463         if (e)
3464                 safe_atou(e, &l);
3465
3466         if (l <= 0)
3467                 l = fd_lines(STDOUT_FILENO);
3468
3469         if (l <= 0)
3470                 l = 24;
3471
3472         cached_lines = l;
3473         return cached_lines;
3474 }
3475
3476 /* intended to be used as a SIGWINCH sighandler */
3477 void columns_lines_cache_reset(int signum) {
3478         cached_columns = 0;
3479         cached_lines = 0;
3480 }
3481
3482 bool on_tty(void) {
3483         static int cached_on_tty = -1;
3484
3485         if (_unlikely_(cached_on_tty < 0))
3486                 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3487
3488         return cached_on_tty;
3489 }
3490
3491 int running_in_chroot(void) {
3492         struct stat a, b;
3493
3494         zero(a);
3495         zero(b);
3496
3497         /* Only works as root */
3498
3499         if (stat("/proc/1/root", &a) < 0)
3500                 return -errno;
3501
3502         if (stat("/", &b) < 0)
3503                 return -errno;
3504
3505         return
3506                 a.st_dev != b.st_dev ||
3507                 a.st_ino != b.st_ino;
3508 }
3509
3510 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3511         size_t x;
3512         char *r;
3513
3514         assert(s);
3515         assert(percent <= 100);
3516         assert(new_length >= 3);
3517
3518         if (old_length <= 3 || old_length <= new_length)
3519                 return strndup(s, old_length);
3520
3521         r = new0(char, new_length+1);
3522         if (!r)
3523                 return r;
3524
3525         x = (new_length * percent) / 100;
3526
3527         if (x > new_length - 3)
3528                 x = new_length - 3;
3529
3530         memcpy(r, s, x);
3531         r[x] = '.';
3532         r[x+1] = '.';
3533         r[x+2] = '.';
3534         memcpy(r + x + 3,
3535                s + old_length - (new_length - x - 3),
3536                new_length - x - 3);
3537
3538         return r;
3539 }
3540
3541 char *ellipsize(const char *s, size_t length, unsigned percent) {
3542         return ellipsize_mem(s, strlen(s), length, percent);
3543 }
3544
3545 int touch(const char *path) {
3546         int fd;
3547
3548         assert(path);
3549
3550         /* This just opens the file for writing, ensuring it
3551          * exists. It doesn't call utimensat() the way /usr/bin/touch
3552          * does it. */
3553
3554         fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3555         if (fd < 0)
3556                 return -errno;
3557
3558         close_nointr_nofail(fd);
3559         return 0;
3560 }
3561
3562 char *unquote(const char *s, const char* quotes) {
3563         size_t l;
3564         assert(s);
3565
3566         /* This is rather stupid, simply removes the heading and
3567          * trailing quotes if there is one. Doesn't care about
3568          * escaping or anything. We should make this smarter one
3569          * day...*/
3570
3571         l = strlen(s);
3572         if (l < 2)
3573                 return strdup(s);
3574
3575         if (strchr(quotes, s[0]) && s[l-1] == s[0])
3576                 return strndup(s+1, l-2);
3577
3578         return strdup(s);
3579 }
3580
3581 char *normalize_env_assignment(const char *s) {
3582         _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3583         char *eq, *r;
3584
3585         eq = strchr(s, '=');
3586         if (!eq) {
3587                 char *t;
3588
3589                 r = strdup(s);
3590                 if (!r)
3591                         return NULL;
3592
3593                 t = strstrip(r);
3594                 if (t == r)
3595                         return r;
3596
3597                 memmove(r, t, strlen(t) + 1);
3598                 return r;
3599         }
3600
3601         name = strndup(s, eq - s);
3602         if (!name)
3603                 return NULL;
3604
3605         p = strdup(eq + 1);
3606         if (!p)
3607                 return NULL;
3608
3609         value = unquote(strstrip(p), QUOTES);
3610         if (!value)
3611                 return NULL;
3612
3613         if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3614                 r = NULL;
3615
3616         return r;
3617 }
3618
3619 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3620         siginfo_t dummy;
3621
3622         assert(pid >= 1);
3623
3624         if (!status)
3625                 status = &dummy;
3626
3627         for (;;) {
3628                 zero(*status);
3629
3630                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3631
3632                         if (errno == EINTR)
3633                                 continue;
3634
3635                         return -errno;
3636                 }
3637
3638                 return 0;
3639         }
3640 }
3641
3642 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3643         int r;
3644         siginfo_t status;
3645
3646         assert(name);
3647         assert(pid > 1);
3648
3649         r = wait_for_terminate(pid, &status);
3650         if (r < 0) {
3651                 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3652                 return r;
3653         }
3654
3655         if (status.si_code == CLD_EXITED) {
3656                 if (status.si_status != 0) {
3657                         log_warning("%s failed with error code %i.", name, status.si_status);
3658                         return status.si_status;
3659                 }
3660
3661                 log_debug("%s succeeded.", name);
3662                 return 0;
3663
3664         } else if (status.si_code == CLD_KILLED ||
3665                    status.si_code == CLD_DUMPED) {
3666
3667                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3668                 return -EPROTO;
3669         }
3670
3671         log_warning("%s failed due to unknown reason.", name);
3672         return -EPROTO;
3673 }
3674
3675 _noreturn_ void freeze(void) {
3676
3677         /* Make sure nobody waits for us on a socket anymore */
3678         close_all_fds(NULL, 0);
3679
3680         sync();
3681
3682         for (;;)
3683                 pause();
3684 }
3685
3686 bool null_or_empty(struct stat *st) {
3687         assert(st);
3688
3689         if (S_ISREG(st->st_mode) && st->st_size <= 0)
3690                 return true;
3691
3692         if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3693                 return true;
3694
3695         return false;
3696 }
3697
3698 int null_or_empty_path(const char *fn) {
3699         struct stat st;
3700
3701         assert(fn);
3702
3703         if (stat(fn, &st) < 0)
3704                 return -errno;
3705
3706         return null_or_empty(&st);
3707 }
3708
3709 DIR *xopendirat(int fd, const char *name, int flags) {
3710         int nfd;
3711         DIR *d;
3712
3713         nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3714         if (nfd < 0)
3715                 return NULL;
3716
3717         d = fdopendir(nfd);
3718         if (!d) {
3719                 close_nointr_nofail(nfd);
3720                 return NULL;
3721         }
3722
3723         return d;
3724 }
3725
3726 int signal_from_string_try_harder(const char *s) {
3727         int signo;
3728         assert(s);
3729
3730         signo = signal_from_string(s);
3731         if (signo <= 0)
3732                 if (startswith(s, "SIG"))
3733                         return signal_from_string(s+3);
3734
3735         return signo;
3736 }
3737
3738 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3739         char *dn, *t, *u;
3740         int r;
3741
3742         /* FIXME: to follow udev's logic 100% we need to leave valid
3743          * UTF8 chars unescaped */
3744
3745         u = unquote(tagvalue, "\"\'");
3746         if (u == NULL)
3747                 return NULL;
3748
3749         t = xescape(u, "/ ");
3750         free(u);
3751
3752         if (t == NULL)
3753                 return NULL;
3754
3755         r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3756         free(t);
3757
3758         if (r < 0)
3759                 return NULL;
3760
3761         return dn;
3762 }
3763
3764 char *fstab_node_to_udev_node(const char *p) {
3765         assert(p);
3766
3767         if (startswith(p, "LABEL="))
3768                 return tag_to_udev_node(p+6, "label");
3769
3770         if (startswith(p, "UUID="))
3771                 return tag_to_udev_node(p+5, "uuid");
3772
3773         if (startswith(p, "PARTUUID="))
3774                 return tag_to_udev_node(p+9, "partuuid");
3775
3776         if (startswith(p, "PARTLABEL="))
3777                 return tag_to_udev_node(p+10, "partlabel");
3778
3779         return strdup(p);
3780 }
3781
3782 bool tty_is_vc(const char *tty) {
3783         assert(tty);
3784
3785         if (startswith(tty, "/dev/"))
3786                 tty += 5;
3787
3788         return vtnr_from_tty(tty) >= 0;
3789 }
3790
3791 bool tty_is_console(const char *tty) {
3792         assert(tty);
3793
3794         if (startswith(tty, "/dev/"))
3795                 tty += 5;
3796
3797         return streq(tty, "console");
3798 }
3799
3800 int vtnr_from_tty(const char *tty) {
3801         int i, r;
3802
3803         assert(tty);
3804
3805         if (startswith(tty, "/dev/"))
3806                 tty += 5;
3807
3808         if (!startswith(tty, "tty") )
3809                 return -EINVAL;
3810
3811         if (tty[3] < '0' || tty[3] > '9')
3812                 return -EINVAL;
3813
3814         r = safe_atoi(tty+3, &i);
3815         if (r < 0)
3816                 return r;
3817
3818         if (i < 0 || i > 63)
3819                 return -EINVAL;
3820
3821         return i;
3822 }
3823
3824 bool tty_is_vc_resolve(const char *tty) {
3825         char *active = NULL;
3826         bool b;
3827
3828         assert(tty);
3829
3830         if (startswith(tty, "/dev/"))
3831                 tty += 5;
3832
3833         /* Resolve where /dev/console is pointing to, if /sys is
3834          * actually ours (i.e. not read-only-mounted which is a sign
3835          * for container setups) */
3836         if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
3837                 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3838                         /* If multiple log outputs are configured the
3839                          * last one is what /dev/console points to */
3840                         tty = strrchr(active, ' ');
3841                         if (tty)
3842                                 tty++;
3843                         else
3844                                 tty = active;
3845                 }
3846
3847         b = tty_is_vc(tty);
3848         free(active);
3849
3850         return b;
3851 }
3852
3853 const char *default_term_for_tty(const char *tty) {
3854         assert(tty);
3855
3856         return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3857 }
3858
3859 bool dirent_is_file(const struct dirent *de) {
3860         assert(de);
3861
3862         if (ignore_file(de->d_name))
3863                 return false;
3864
3865         if (de->d_type != DT_REG &&
3866             de->d_type != DT_LNK &&
3867             de->d_type != DT_UNKNOWN)
3868                 return false;
3869
3870         return true;
3871 }
3872
3873 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3874         assert(de);
3875
3876         if (de->d_type != DT_REG &&
3877             de->d_type != DT_LNK &&
3878             de->d_type != DT_UNKNOWN)
3879                 return false;
3880
3881         if (ignore_file_allow_backup(de->d_name))
3882                 return false;
3883
3884         return endswith(de->d_name, suffix);
3885 }
3886
3887 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3888         DIR *_d = NULL;
3889         struct dirent *de;
3890         Hashmap *pids = NULL;
3891
3892         assert(directory);
3893
3894         /* Executes all binaries in a directory in parallel and waits
3895          * until all they all finished. */
3896
3897         if (!d) {
3898                 if (!(_d = opendir(directory))) {
3899
3900                         if (errno == ENOENT)
3901                                 return;
3902
3903                         log_error("Failed to enumerate directory %s: %m", directory);
3904                         return;
3905                 }
3906
3907                 d = _d;
3908         }
3909
3910         if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3911                 log_error("Failed to allocate set.");
3912                 goto finish;
3913         }
3914
3915         while ((de = readdir(d))) {
3916                 char *path;
3917                 pid_t pid;
3918                 int k;
3919
3920                 if (!dirent_is_file(de))
3921                         continue;
3922
3923                 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3924                         log_oom();
3925                         continue;
3926                 }
3927
3928                 if ((pid = fork()) < 0) {
3929                         log_error("Failed to fork: %m");
3930                         free(path);
3931                         continue;
3932                 }
3933
3934                 if (pid == 0) {
3935                         char *_argv[2];
3936                         /* Child */
3937
3938                         if (!argv) {
3939                                 _argv[0] = path;
3940                                 _argv[1] = NULL;
3941                                 argv = _argv;
3942                         } else
3943                                 argv[0] = path;
3944
3945                         execv(path, argv);
3946
3947                         log_error("Failed to execute %s: %m", path);
3948                         _exit(EXIT_FAILURE);
3949                 }
3950
3951                 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3952
3953                 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3954                         log_error("Failed to add PID to set: %s", strerror(-k));
3955                         free(path);
3956                 }
3957         }
3958
3959         while (!hashmap_isempty(pids)) {
3960                 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3961                 siginfo_t si;
3962                 char *path;
3963
3964                 zero(si);
3965                 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3966
3967                         if (errno == EINTR)
3968                                 continue;
3969
3970                         log_error("waitid() failed: %m");
3971                         goto finish;
3972                 }
3973
3974                 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3975                         if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3976                                 if (si.si_code == CLD_EXITED)
3977                                         log_error("%s exited with exit status %i.", path, si.si_status);
3978                                 else
3979                                         log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3980                         } else
3981                                 log_debug("%s exited successfully.", path);
3982
3983                         free(path);
3984                 }
3985         }
3986
3987 finish:
3988         if (_d)
3989                 closedir(_d);
3990
3991         if (pids)
3992                 hashmap_free_free(pids);
3993 }
3994
3995 int kill_and_sigcont(pid_t pid, int sig) {
3996         int r;
3997
3998         r = kill(pid, sig) < 0 ? -errno : 0;
3999
4000         if (r >= 0)
4001                 kill(pid, SIGCONT);
4002
4003         return r;
4004 }
4005
4006 bool nulstr_contains(const char*nulstr, const char *needle) {
4007         const char *i;
4008
4009         if (!nulstr)
4010                 return false;
4011
4012         NULSTR_FOREACH(i, nulstr)
4013                 if (streq(i, needle))
4014                         return true;
4015
4016         return false;
4017 }
4018
4019 bool plymouth_running(void) {
4020         return access("/run/plymouth/pid", F_OK) >= 0;
4021 }
4022
4023 char* strshorten(char *s, size_t l) {
4024         assert(s);
4025
4026         if (l < strlen(s))
4027                 s[l] = 0;
4028
4029         return s;
4030 }
4031
4032 static bool hostname_valid_char(char c) {
4033         return
4034                 (c >= 'a' && c <= 'z') ||
4035                 (c >= 'A' && c <= 'Z') ||
4036                 (c >= '0' && c <= '9') ||
4037                 c == '-' ||
4038                 c == '_' ||
4039                 c == '.';
4040 }
4041
4042 bool hostname_is_valid(const char *s) {
4043         const char *p;
4044
4045         if (isempty(s))
4046                 return false;
4047
4048         for (p = s; *p; p++)
4049                 if (!hostname_valid_char(*p))
4050                         return false;
4051
4052         if (p-s > HOST_NAME_MAX)
4053                 return false;
4054
4055         return true;
4056 }
4057
4058 char* hostname_cleanup(char *s) {
4059         char *p, *d;
4060
4061         for (p = s, d = s; *p; p++)
4062                 if ((*p >= 'a' && *p <= 'z') ||
4063                     (*p >= 'A' && *p <= 'Z') ||
4064                     (*p >= '0' && *p <= '9') ||
4065                     *p == '-' ||
4066                     *p == '_' ||
4067                     *p == '.')
4068                         *(d++) = *p;
4069
4070         *d = 0;
4071
4072         strshorten(s, HOST_NAME_MAX);
4073         return s;
4074 }
4075
4076 int pipe_eof(int fd) {
4077         struct pollfd pollfd;
4078         int r;
4079
4080         zero(pollfd);
4081         pollfd.fd = fd;
4082         pollfd.events = POLLIN|POLLHUP;
4083
4084         r = poll(&pollfd, 1, 0);
4085         if (r < 0)
4086                 return -errno;
4087
4088         if (r == 0)
4089                 return 0;
4090
4091         return pollfd.revents & POLLHUP;
4092 }
4093
4094 int fd_wait_for_event(int fd, int event, usec_t t) {
4095         struct pollfd pollfd;
4096         int r;
4097
4098         zero(pollfd);
4099         pollfd.fd = fd;
4100         pollfd.events = event;
4101
4102         r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4103         if (r < 0)
4104                 return -errno;
4105
4106         if (r == 0)
4107                 return 0;
4108
4109         return pollfd.revents;
4110 }
4111
4112 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4113         FILE *f;
4114         char *t;
4115         const char *fn;
4116         size_t k;
4117         int fd;
4118
4119         assert(path);
4120         assert(_f);
4121         assert(_temp_path);
4122
4123         t = new(char, strlen(path) + 1 + 6 + 1);
4124         if (!t)
4125                 return -ENOMEM;
4126
4127         fn = path_get_file_name(path);
4128         k = fn-path;
4129         memcpy(t, path, k);
4130         t[k] = '.';
4131         stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4132
4133         fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4134         if (fd < 0) {
4135                 free(t);
4136                 return -errno;
4137         }
4138
4139         f = fdopen(fd, "we");
4140         if (!f) {
4141                 unlink(t);
4142                 free(t);
4143                 return -errno;
4144         }
4145
4146         *_f = f;
4147         *_temp_path = t;
4148
4149         return 0;
4150 }
4151
4152 int terminal_vhangup_fd(int fd) {
4153         assert(fd >= 0);
4154
4155         if (ioctl(fd, TIOCVHANGUP) < 0)
4156                 return -errno;
4157
4158         return 0;
4159 }
4160
4161 int terminal_vhangup(const char *name) {
4162         int fd, r;
4163
4164         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4165         if (fd < 0)
4166                 return fd;
4167
4168         r = terminal_vhangup_fd(fd);
4169         close_nointr_nofail(fd);
4170
4171         return r;
4172 }
4173
4174 int vt_disallocate(const char *name) {
4175         int fd, r;
4176         unsigned u;
4177
4178         /* Deallocate the VT if possible. If not possible
4179          * (i.e. because it is the active one), at least clear it
4180          * entirely (including the scrollback buffer) */
4181
4182         if (!startswith(name, "/dev/"))
4183                 return -EINVAL;
4184
4185         if (!tty_is_vc(name)) {
4186                 /* So this is not a VT. I guess we cannot deallocate
4187                  * it then. But let's at least clear the screen */
4188
4189                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4190                 if (fd < 0)
4191                         return fd;
4192
4193                 loop_write(fd,
4194                            "\033[r"    /* clear scrolling region */
4195                            "\033[H"    /* move home */
4196                            "\033[2J",  /* clear screen */
4197                            10, false);
4198                 close_nointr_nofail(fd);
4199
4200                 return 0;
4201         }
4202
4203         if (!startswith(name, "/dev/tty"))
4204                 return -EINVAL;
4205
4206         r = safe_atou(name+8, &u);
4207         if (r < 0)
4208                 return r;
4209
4210         if (u <= 0)
4211                 return -EINVAL;
4212
4213         /* Try to deallocate */
4214         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4215         if (fd < 0)
4216                 return fd;
4217
4218         r = ioctl(fd, VT_DISALLOCATE, u);
4219         close_nointr_nofail(fd);
4220
4221         if (r >= 0)
4222                 return 0;
4223
4224         if (errno != EBUSY)
4225                 return -errno;
4226
4227         /* Couldn't deallocate, so let's clear it fully with
4228          * scrollback */
4229         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4230         if (fd < 0)
4231                 return fd;
4232
4233         loop_write(fd,
4234                    "\033[r"   /* clear scrolling region */
4235                    "\033[H"   /* move home */
4236                    "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4237                    10, false);
4238         close_nointr_nofail(fd);
4239
4240         return 0;
4241 }
4242
4243 int copy_file(const char *from, const char *to) {
4244         int r, fdf, fdt;
4245
4246         assert(from);
4247         assert(to);
4248
4249         fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4250         if (fdf < 0)
4251                 return -errno;
4252
4253         fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4254         if (fdt < 0) {
4255                 close_nointr_nofail(fdf);
4256                 return -errno;
4257         }
4258
4259         for (;;) {
4260                 char buf[PIPE_BUF];
4261                 ssize_t n, k;
4262
4263                 n = read(fdf, buf, sizeof(buf));
4264                 if (n < 0) {
4265                         r = -errno;
4266
4267                         close_nointr_nofail(fdf);
4268                         close_nointr(fdt);
4269                         unlink(to);
4270
4271                         return r;
4272                 }
4273
4274                 if (n == 0)
4275                         break;
4276
4277                 errno = 0;
4278                 k = loop_write(fdt, buf, n, false);
4279                 if (n != k) {
4280                         r = k < 0 ? k : (errno ? -errno : -EIO);
4281
4282                         close_nointr_nofail(fdf);
4283                         close_nointr(fdt);
4284
4285                         unlink(to);
4286                         return r;
4287                 }
4288         }
4289
4290         close_nointr_nofail(fdf);
4291         r = close_nointr(fdt);
4292
4293         if (r < 0) {
4294                 unlink(to);
4295                 return r;
4296         }
4297
4298         return 0;
4299 }
4300
4301 int symlink_atomic(const char *from, const char *to) {
4302         char *x;
4303         _cleanup_free_ char *t;
4304         const char *fn;
4305         size_t k;
4306         unsigned long long ull;
4307         unsigned i;
4308         int r;
4309
4310         assert(from);
4311         assert(to);
4312
4313         t = new(char, strlen(to) + 1 + 16 + 1);
4314         if (!t)
4315                 return -ENOMEM;
4316
4317         fn = path_get_file_name(to);
4318         k = fn-to;
4319         memcpy(t, to, k);
4320         t[k] = '.';
4321         x = stpcpy(t+k+1, fn);
4322
4323         ull = random_ull();
4324         for (i = 0; i < 16; i++) {
4325                 *(x++) = hexchar(ull & 0xF);
4326                 ull >>= 4;
4327         }
4328
4329         *x = 0;
4330
4331         if (symlink(from, t) < 0)
4332                 return -errno;
4333
4334         if (rename(t, to) < 0) {
4335                 r = -errno;
4336                 unlink(t);
4337                 return r;
4338         }
4339
4340         return 0;
4341 }
4342
4343 bool display_is_local(const char *display) {
4344         assert(display);
4345
4346         return
4347                 display[0] == ':' &&
4348                 display[1] >= '0' &&
4349                 display[1] <= '9';
4350 }
4351
4352 int socket_from_display(const char *display, char **path) {
4353         size_t k;
4354         char *f, *c;
4355
4356         assert(display);
4357         assert(path);
4358
4359         if (!display_is_local(display))
4360                 return -EINVAL;
4361
4362         k = strspn(display+1, "0123456789");
4363
4364         f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4365         if (!f)
4366                 return -ENOMEM;
4367
4368         c = stpcpy(f, "/tmp/.X11-unix/X");
4369         memcpy(c, display+1, k);
4370         c[k] = 0;
4371
4372         *path = f;
4373
4374         return 0;
4375 }
4376
4377 int get_user_creds(
4378                 const char **username,
4379                 uid_t *uid, gid_t *gid,
4380                 const char **home,
4381                 const char **shell) {
4382
4383         struct passwd *p;
4384         uid_t u;
4385
4386         assert(username);
4387         assert(*username);
4388
4389         /* We enforce some special rules for uid=0: in order to avoid
4390          * NSS lookups for root we hardcode its data. */
4391
4392         if (streq(*username, "root") || streq(*username, "0")) {
4393                 *username = "root";
4394
4395                 if (uid)
4396                         *uid = 0;
4397
4398                 if (gid)
4399                         *gid = 0;
4400
4401                 if (home)
4402                         *home = "/root";
4403
4404                 if (shell)
4405                         *shell = "/bin/sh";
4406
4407                 return 0;
4408         }
4409
4410         if (parse_uid(*username, &u) >= 0) {
4411                 errno = 0;
4412                 p = getpwuid(u);
4413
4414                 /* If there are multiple users with the same id, make
4415                  * sure to leave $USER to the configured value instead
4416                  * of the first occurrence in the database. However if
4417                  * the uid was configured by a numeric uid, then let's
4418                  * pick the real username from /etc/passwd. */
4419                 if (p)
4420                         *username = p->pw_name;
4421         } else {
4422                 errno = 0;
4423                 p = getpwnam(*username);
4424         }
4425
4426         if (!p)
4427                 return errno != 0 ? -errno : -ESRCH;
4428
4429         if (uid)
4430                 *uid = p->pw_uid;
4431
4432         if (gid)
4433                 *gid = p->pw_gid;
4434
4435         if (home)
4436                 *home = p->pw_dir;
4437
4438         if (shell)
4439                 *shell = p->pw_shell;
4440
4441         return 0;
4442 }
4443
4444 int get_group_creds(const char **groupname, gid_t *gid) {
4445         struct group *g;
4446         gid_t id;
4447
4448         assert(groupname);
4449
4450         /* We enforce some special rules for gid=0: in order to avoid
4451          * NSS lookups for root we hardcode its data. */
4452
4453         if (streq(*groupname, "root") || streq(*groupname, "0")) {
4454                 *groupname = "root";
4455
4456                 if (gid)
4457                         *gid = 0;
4458
4459                 return 0;
4460         }
4461
4462         if (parse_gid(*groupname, &id) >= 0) {
4463                 errno = 0;
4464                 g = getgrgid(id);
4465
4466                 if (g)
4467                         *groupname = g->gr_name;
4468         } else {
4469                 errno = 0;
4470                 g = getgrnam(*groupname);
4471         }
4472
4473         if (!g)
4474                 return errno != 0 ? -errno : -ESRCH;
4475
4476         if (gid)
4477                 *gid = g->gr_gid;
4478
4479         return 0;
4480 }
4481
4482 int in_group(const char *name) {
4483         gid_t gid, *gids;
4484         int ngroups_max, r, i;
4485
4486         r = get_group_creds(&name, &gid);
4487         if (r < 0)
4488                 return r;
4489
4490         if (getgid() == gid)
4491                 return 1;
4492
4493         if (getegid() == gid)
4494                 return 1;
4495
4496         ngroups_max = sysconf(_SC_NGROUPS_MAX);
4497         assert(ngroups_max > 0);
4498
4499         gids = alloca(sizeof(gid_t) * ngroups_max);
4500
4501         r = getgroups(ngroups_max, gids);
4502         if (r < 0)
4503                 return -errno;
4504
4505         for (i = 0; i < r; i++)
4506                 if (gids[i] == gid)
4507                         return 1;
4508
4509         return 0;
4510 }
4511
4512 int glob_exists(const char *path) {
4513         glob_t g;
4514         int r, k;
4515
4516         assert(path);
4517
4518         zero(g);
4519         errno = 0;
4520         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4521
4522         if (k == GLOB_NOMATCH)
4523                 r = 0;
4524         else if (k == GLOB_NOSPACE)
4525                 r = -ENOMEM;
4526         else if (k == 0)
4527                 r = !strv_isempty(g.gl_pathv);
4528         else
4529                 r = errno ? -errno : -EIO;
4530
4531         globfree(&g);
4532
4533         return r;
4534 }
4535
4536 int dirent_ensure_type(DIR *d, struct dirent *de) {
4537         struct stat st;
4538
4539         assert(d);
4540         assert(de);
4541
4542         if (de->d_type != DT_UNKNOWN)
4543                 return 0;
4544
4545         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4546                 return -errno;
4547
4548         de->d_type =
4549                 S_ISREG(st.st_mode)  ? DT_REG  :
4550                 S_ISDIR(st.st_mode)  ? DT_DIR  :
4551                 S_ISLNK(st.st_mode)  ? DT_LNK  :
4552                 S_ISFIFO(st.st_mode) ? DT_FIFO :
4553                 S_ISSOCK(st.st_mode) ? DT_SOCK :
4554                 S_ISCHR(st.st_mode)  ? DT_CHR  :
4555                 S_ISBLK(st.st_mode)  ? DT_BLK  :
4556                                        DT_UNKNOWN;
4557
4558         return 0;
4559 }
4560
4561 int in_search_path(const char *path, char **search) {
4562         char **i, *parent;
4563         int r;
4564
4565         r = path_get_parent(path, &parent);
4566         if (r < 0)
4567                 return r;
4568
4569         r = 0;
4570
4571         STRV_FOREACH(i, search) {
4572                 if (path_equal(parent, *i)) {
4573                         r = 1;
4574                         break;
4575                 }
4576         }
4577
4578         free(parent);
4579
4580         return r;
4581 }
4582
4583 int get_files_in_directory(const char *path, char ***list) {
4584         DIR *d;
4585         int r = 0;
4586         unsigned n = 0;
4587         char **l = NULL;
4588
4589         assert(path);
4590
4591         /* Returns all files in a directory in *list, and the number
4592          * of files as return value. If list is NULL returns only the
4593          * number */
4594
4595         d = opendir(path);
4596         if (!d)
4597                 return -errno;
4598
4599         for (;;) {
4600                 struct dirent *de;
4601                 union dirent_storage buf;
4602                 int k;
4603
4604                 k = readdir_r(d, &buf.de, &de);
4605                 if (k != 0) {
4606                         r = -k;
4607                         goto finish;
4608                 }
4609
4610                 if (!de)
4611                         break;
4612
4613                 dirent_ensure_type(d, de);
4614
4615                 if (!dirent_is_file(de))
4616                         continue;
4617
4618                 if (list) {
4619                         if ((unsigned) r >= n) {
4620                                 char **t;
4621
4622                                 n = MAX(16, 2*r);
4623                                 t = realloc(l, sizeof(char*) * n);
4624                                 if (!t) {
4625                                         r = -ENOMEM;
4626                                         goto finish;
4627                                 }
4628
4629                                 l = t;
4630                         }
4631
4632                         assert((unsigned) r < n);
4633
4634                         l[r] = strdup(de->d_name);
4635                         if (!l[r]) {
4636                                 r = -ENOMEM;
4637                                 goto finish;
4638                         }
4639
4640                         l[++r] = NULL;
4641                 } else
4642                         r++;
4643         }
4644
4645 finish:
4646         if (d)
4647                 closedir(d);
4648
4649         if (r >= 0) {
4650                 if (list)
4651                         *list = l;
4652         } else
4653                 strv_free(l);
4654
4655         return r;
4656 }
4657
4658 char *strjoin(const char *x, ...) {
4659         va_list ap;
4660         size_t l;
4661         char *r, *p;
4662
4663         va_start(ap, x);
4664
4665         if (x) {
4666                 l = strlen(x);
4667
4668                 for (;;) {
4669                         const char *t;
4670                         size_t n;
4671
4672                         t = va_arg(ap, const char *);
4673                         if (!t)
4674                                 break;
4675
4676                         n = strlen(t);
4677                         if (n > ((size_t) -1) - l) {
4678                                 va_end(ap);
4679                                 return NULL;
4680                         }
4681
4682                         l += n;
4683                 }
4684         } else
4685                 l = 0;
4686
4687         va_end(ap);
4688
4689         r = new(char, l+1);
4690         if (!r)
4691                 return NULL;
4692
4693         if (x) {
4694                 p = stpcpy(r, x);
4695
4696                 va_start(ap, x);
4697
4698                 for (;;) {
4699                         const char *t;
4700
4701                         t = va_arg(ap, const char *);
4702                         if (!t)
4703                                 break;
4704
4705                         p = stpcpy(p, t);
4706                 }
4707
4708                 va_end(ap);
4709         } else
4710                 r[0] = 0;
4711
4712         return r;
4713 }
4714
4715 bool is_main_thread(void) {
4716         static __thread int cached = 0;
4717
4718         if (_unlikely_(cached == 0))
4719                 cached = getpid() == gettid() ? 1 : -1;
4720
4721         return cached > 0;
4722 }
4723
4724 int block_get_whole_disk(dev_t d, dev_t *ret) {
4725         char *p, *s;
4726         int r;
4727         unsigned n, m;
4728
4729         assert(ret);
4730
4731         /* If it has a queue this is good enough for us */
4732         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4733                 return -ENOMEM;
4734
4735         r = access(p, F_OK);
4736         free(p);
4737
4738         if (r >= 0) {
4739                 *ret = d;
4740                 return 0;
4741         }
4742
4743         /* If it is a partition find the originating device */
4744         if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4745                 return -ENOMEM;
4746
4747         r = access(p, F_OK);
4748         free(p);
4749
4750         if (r < 0)
4751                 return -ENOENT;
4752
4753         /* Get parent dev_t */
4754         if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4755                 return -ENOMEM;
4756
4757         r = read_one_line_file(p, &s);
4758         free(p);
4759
4760         if (r < 0)
4761                 return r;
4762
4763         r = sscanf(s, "%u:%u", &m, &n);
4764         free(s);
4765
4766         if (r != 2)
4767                 return -EINVAL;
4768
4769         /* Only return this if it is really good enough for us. */
4770         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4771                 return -ENOMEM;
4772
4773         r = access(p, F_OK);
4774         free(p);
4775
4776         if (r >= 0) {
4777                 *ret = makedev(m, n);
4778                 return 0;
4779         }
4780
4781         return -ENOENT;
4782 }
4783
4784 int file_is_priv_sticky(const char *p) {
4785         struct stat st;
4786
4787         assert(p);
4788
4789         if (lstat(p, &st) < 0)
4790                 return -errno;
4791
4792         return
4793                 (st.st_uid == 0 || st.st_uid == getuid()) &&
4794                 (st.st_mode & S_ISVTX);
4795 }
4796
4797 static const char *const ioprio_class_table[] = {
4798         [IOPRIO_CLASS_NONE] = "none",
4799         [IOPRIO_CLASS_RT] = "realtime",
4800         [IOPRIO_CLASS_BE] = "best-effort",
4801         [IOPRIO_CLASS_IDLE] = "idle"
4802 };
4803
4804 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4805
4806 static const char *const sigchld_code_table[] = {
4807         [CLD_EXITED] = "exited",
4808         [CLD_KILLED] = "killed",
4809         [CLD_DUMPED] = "dumped",
4810         [CLD_TRAPPED] = "trapped",
4811         [CLD_STOPPED] = "stopped",
4812         [CLD_CONTINUED] = "continued",
4813 };
4814
4815 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4816
4817 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4818         [LOG_FAC(LOG_KERN)] = "kern",
4819         [LOG_FAC(LOG_USER)] = "user",
4820         [LOG_FAC(LOG_MAIL)] = "mail",
4821         [LOG_FAC(LOG_DAEMON)] = "daemon",
4822         [LOG_FAC(LOG_AUTH)] = "auth",
4823         [LOG_FAC(LOG_SYSLOG)] = "syslog",
4824         [LOG_FAC(LOG_LPR)] = "lpr",
4825         [LOG_FAC(LOG_NEWS)] = "news",
4826         [LOG_FAC(LOG_UUCP)] = "uucp",
4827         [LOG_FAC(LOG_CRON)] = "cron",
4828         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4829         [LOG_FAC(LOG_FTP)] = "ftp",
4830         [LOG_FAC(LOG_LOCAL0)] = "local0",
4831         [LOG_FAC(LOG_LOCAL1)] = "local1",
4832         [LOG_FAC(LOG_LOCAL2)] = "local2",
4833         [LOG_FAC(LOG_LOCAL3)] = "local3",
4834         [LOG_FAC(LOG_LOCAL4)] = "local4",
4835         [LOG_FAC(LOG_LOCAL5)] = "local5",
4836         [LOG_FAC(LOG_LOCAL6)] = "local6",
4837         [LOG_FAC(LOG_LOCAL7)] = "local7"
4838 };
4839
4840 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4841
4842 static const char *const log_level_table[] = {
4843         [LOG_EMERG] = "emerg",
4844         [LOG_ALERT] = "alert",
4845         [LOG_CRIT] = "crit",
4846         [LOG_ERR] = "err",
4847         [LOG_WARNING] = "warning",
4848         [LOG_NOTICE] = "notice",
4849         [LOG_INFO] = "info",
4850         [LOG_DEBUG] = "debug"
4851 };
4852
4853 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4854
4855 static const char* const sched_policy_table[] = {
4856         [SCHED_OTHER] = "other",
4857         [SCHED_BATCH] = "batch",
4858         [SCHED_IDLE] = "idle",
4859         [SCHED_FIFO] = "fifo",
4860         [SCHED_RR] = "rr"
4861 };
4862
4863 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4864
4865 static const char* const rlimit_table[] = {
4866         [RLIMIT_CPU] = "LimitCPU",
4867         [RLIMIT_FSIZE] = "LimitFSIZE",
4868         [RLIMIT_DATA] = "LimitDATA",
4869         [RLIMIT_STACK] = "LimitSTACK",
4870         [RLIMIT_CORE] = "LimitCORE",
4871         [RLIMIT_RSS] = "LimitRSS",
4872         [RLIMIT_NOFILE] = "LimitNOFILE",
4873         [RLIMIT_AS] = "LimitAS",
4874         [RLIMIT_NPROC] = "LimitNPROC",
4875         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4876         [RLIMIT_LOCKS] = "LimitLOCKS",
4877         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4878         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4879         [RLIMIT_NICE] = "LimitNICE",
4880         [RLIMIT_RTPRIO] = "LimitRTPRIO",
4881         [RLIMIT_RTTIME] = "LimitRTTIME"
4882 };
4883
4884 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4885
4886 static const char* const ip_tos_table[] = {
4887         [IPTOS_LOWDELAY] = "low-delay",
4888         [IPTOS_THROUGHPUT] = "throughput",
4889         [IPTOS_RELIABILITY] = "reliability",
4890         [IPTOS_LOWCOST] = "low-cost",
4891 };
4892
4893 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4894
4895 static const char *const __signal_table[] = {
4896         [SIGHUP] = "HUP",
4897         [SIGINT] = "INT",
4898         [SIGQUIT] = "QUIT",
4899         [SIGILL] = "ILL",
4900         [SIGTRAP] = "TRAP",
4901         [SIGABRT] = "ABRT",
4902         [SIGBUS] = "BUS",
4903         [SIGFPE] = "FPE",
4904         [SIGKILL] = "KILL",
4905         [SIGUSR1] = "USR1",
4906         [SIGSEGV] = "SEGV",
4907         [SIGUSR2] = "USR2",
4908         [SIGPIPE] = "PIPE",
4909         [SIGALRM] = "ALRM",
4910         [SIGTERM] = "TERM",
4911 #ifdef SIGSTKFLT
4912         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
4913 #endif
4914         [SIGCHLD] = "CHLD",
4915         [SIGCONT] = "CONT",
4916         [SIGSTOP] = "STOP",
4917         [SIGTSTP] = "TSTP",
4918         [SIGTTIN] = "TTIN",
4919         [SIGTTOU] = "TTOU",
4920         [SIGURG] = "URG",
4921         [SIGXCPU] = "XCPU",
4922         [SIGXFSZ] = "XFSZ",
4923         [SIGVTALRM] = "VTALRM",
4924         [SIGPROF] = "PROF",
4925         [SIGWINCH] = "WINCH",
4926         [SIGIO] = "IO",
4927         [SIGPWR] = "PWR",
4928         [SIGSYS] = "SYS"
4929 };
4930
4931 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4932
4933 const char *signal_to_string(int signo) {
4934         static __thread char buf[12];
4935         const char *name;
4936
4937         name = __signal_to_string(signo);
4938         if (name)
4939                 return name;
4940
4941         if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4942                 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4943         else
4944                 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4945         char_array_0(buf);
4946         return buf;
4947 }
4948
4949 int signal_from_string(const char *s) {
4950         int signo;
4951         int offset = 0;
4952         unsigned u;
4953
4954         signo = __signal_from_string(s);
4955         if (signo > 0)
4956                 return signo;
4957
4958         if (startswith(s, "RTMIN+")) {
4959                 s += 6;
4960                 offset = SIGRTMIN;
4961         }
4962         if (safe_atou(s, &u) >= 0) {
4963                 signo = (int) u + offset;
4964                 if (signo > 0 && signo < _NSIG)
4965                         return signo;
4966         }
4967         return -1;
4968 }
4969
4970 bool kexec_loaded(void) {
4971        bool loaded = false;
4972        char *s;
4973
4974        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4975                if (s[0] == '1')
4976                        loaded = true;
4977                free(s);
4978        }
4979        return loaded;
4980 }
4981
4982 int strdup_or_null(const char *a, char **b) {
4983         char *c;
4984
4985         assert(b);
4986
4987         if (!a) {
4988                 *b = NULL;
4989                 return 0;
4990         }
4991
4992         c = strdup(a);
4993         if (!c)
4994                 return -ENOMEM;
4995
4996         *b = c;
4997         return 0;
4998 }
4999
5000 int prot_from_flags(int flags) {
5001
5002         switch (flags & O_ACCMODE) {
5003
5004         case O_RDONLY:
5005                 return PROT_READ;
5006
5007         case O_WRONLY:
5008                 return PROT_WRITE;
5009
5010         case O_RDWR:
5011                 return PROT_READ|PROT_WRITE;
5012
5013         default:
5014                 return -EINVAL;
5015         }
5016 }
5017
5018 char *format_bytes(char *buf, size_t l, off_t t) {
5019         unsigned i;
5020
5021         static const struct {
5022                 const char *suffix;
5023                 off_t factor;
5024         } table[] = {
5025                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5026                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5027                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5028                 { "G", 1024ULL*1024ULL*1024ULL },
5029                 { "M", 1024ULL*1024ULL },
5030                 { "K", 1024ULL },
5031         };
5032
5033         for (i = 0; i < ELEMENTSOF(table); i++) {
5034
5035                 if (t >= table[i].factor) {
5036                         snprintf(buf, l,
5037                                  "%llu.%llu%s",
5038                                  (unsigned long long) (t / table[i].factor),
5039                                  (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5040                                  table[i].suffix);
5041
5042                         goto finish;
5043                 }
5044         }
5045
5046         snprintf(buf, l, "%lluB", (unsigned long long) t);
5047
5048 finish:
5049         buf[l-1] = 0;
5050         return buf;
5051
5052 }
5053
5054 void* memdup(const void *p, size_t l) {
5055         void *r;
5056
5057         assert(p);
5058
5059         r = malloc(l);
5060         if (!r)
5061                 return NULL;
5062
5063         memcpy(r, p, l);
5064         return r;
5065 }
5066
5067 int fd_inc_sndbuf(int fd, size_t n) {
5068         int r, value;
5069         socklen_t l = sizeof(value);
5070
5071         r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5072         if (r >= 0 &&
5073             l == sizeof(value) &&
5074             (size_t) value >= n*2)
5075                 return 0;
5076
5077         value = (int) n;
5078         r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5079         if (r < 0)
5080                 return -errno;
5081
5082         return 1;
5083 }
5084
5085 int fd_inc_rcvbuf(int fd, size_t n) {
5086         int r, value;
5087         socklen_t l = sizeof(value);
5088
5089         r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5090         if (r >= 0 &&
5091             l == sizeof(value) &&
5092             (size_t) value >= n*2)
5093                 return 0;
5094
5095         value = (int) n;
5096         r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5097         if (r < 0)
5098                 return -errno;
5099
5100         return 1;
5101 }
5102
5103 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5104         pid_t parent_pid, agent_pid;
5105         int fd;
5106         bool stdout_is_tty, stderr_is_tty;
5107         unsigned n, i;
5108         va_list ap;
5109         char **l;
5110
5111         assert(pid);
5112         assert(path);
5113
5114         parent_pid = getpid();
5115
5116         /* Spawns a temporary TTY agent, making sure it goes away when
5117          * we go away */
5118
5119         agent_pid = fork();
5120         if (agent_pid < 0)
5121                 return -errno;
5122
5123         if (agent_pid != 0) {
5124                 *pid = agent_pid;
5125                 return 0;
5126         }
5127
5128         /* In the child:
5129          *
5130          * Make sure the agent goes away when the parent dies */
5131         if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5132                 _exit(EXIT_FAILURE);
5133
5134         /* Check whether our parent died before we were able
5135          * to set the death signal */
5136         if (getppid() != parent_pid)
5137                 _exit(EXIT_SUCCESS);
5138
5139         /* Don't leak fds to the agent */
5140         close_all_fds(except, n_except);
5141
5142         stdout_is_tty = isatty(STDOUT_FILENO);
5143         stderr_is_tty = isatty(STDERR_FILENO);
5144
5145         if (!stdout_is_tty || !stderr_is_tty) {
5146                 /* Detach from stdout/stderr. and reopen
5147                  * /dev/tty for them. This is important to
5148                  * ensure that when systemctl is started via
5149                  * popen() or a similar call that expects to
5150                  * read EOF we actually do generate EOF and
5151                  * not delay this indefinitely by because we
5152                  * keep an unused copy of stdin around. */
5153                 fd = open("/dev/tty", O_WRONLY);
5154                 if (fd < 0) {
5155                         log_error("Failed to open /dev/tty: %m");
5156                         _exit(EXIT_FAILURE);
5157                 }
5158
5159                 if (!stdout_is_tty)
5160                         dup2(fd, STDOUT_FILENO);
5161
5162                 if (!stderr_is_tty)
5163                         dup2(fd, STDERR_FILENO);
5164
5165                 if (fd > 2)
5166                         close(fd);
5167         }
5168
5169         /* Count arguments */
5170         va_start(ap, path);
5171         for (n = 0; va_arg(ap, char*); n++)
5172                 ;
5173         va_end(ap);
5174
5175         /* Allocate strv */
5176         l = alloca(sizeof(char *) * (n + 1));
5177
5178         /* Fill in arguments */
5179         va_start(ap, path);
5180         for (i = 0; i <= n; i++)
5181                 l[i] = va_arg(ap, char*);
5182         va_end(ap);
5183
5184         execv(path, l);
5185         _exit(EXIT_FAILURE);
5186 }
5187
5188 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5189         struct rlimit highest, fixed;
5190
5191         assert(rlim);
5192
5193         if (setrlimit(resource, rlim) >= 0)
5194                 return 0;
5195
5196         if (errno != EPERM)
5197                 return -errno;
5198
5199         /* So we failed to set the desired setrlimit, then let's try
5200          * to get as close as we can */
5201         assert_se(getrlimit(resource, &highest) == 0);
5202
5203         fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5204         fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5205
5206         if (setrlimit(resource, &fixed) < 0)
5207                 return -errno;
5208
5209         return 0;
5210 }
5211
5212 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5213         char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5214         int r;
5215         FILE *f;
5216         bool done = false;
5217         size_t l;
5218
5219         assert(field);
5220         assert(_value);
5221
5222         if (pid == 0)
5223                 pid = getpid();
5224
5225         snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5226         char_array_0(path);
5227
5228         f = fopen(path, "re");
5229         if (!f)
5230                 return -errno;
5231
5232         l = strlen(field);
5233         r = 0;
5234
5235         do {
5236                 char line[LINE_MAX];
5237                 unsigned i;
5238
5239                 for (i = 0; i < sizeof(line)-1; i++) {
5240                         int c;
5241
5242                         c = getc(f);
5243                         if (_unlikely_(c == EOF)) {
5244                                 done = true;
5245                                 break;
5246                         } else if (c == 0)
5247                                 break;
5248
5249                         line[i] = c;
5250                 }
5251                 line[i] = 0;
5252
5253                 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5254                         value = strdup(line + l + 1);
5255                         if (!value) {
5256                                 r = -ENOMEM;
5257                                 break;
5258                         }
5259
5260                         r = 1;
5261                         break;
5262                 }
5263
5264         } while (!done);
5265
5266         fclose(f);
5267
5268         if (r >= 0)
5269                 *_value = value;
5270
5271         return r;
5272 }
5273
5274 int can_sleep(const char *type) {
5275         char *w, *state;
5276         size_t l, k;
5277         int r;
5278         _cleanup_free_ char *p = NULL;
5279
5280         assert(type);
5281
5282         r = read_one_line_file("/sys/power/state", &p);
5283         if (r < 0)
5284                 return r == -ENOENT ? 0 : r;
5285
5286         k = strlen(type);
5287         FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5288                 if (l == k && memcmp(w, type, l) == 0)
5289                         return true;
5290
5291         return false;
5292 }
5293
5294 int can_sleep_disk(const char *type) {
5295         char *w, *state;
5296         size_t l, k;
5297         int r;
5298         _cleanup_free_ char *p = NULL;
5299
5300         assert(type);
5301
5302         r = read_one_line_file("/sys/power/disk", &p);
5303         if (r < 0)
5304                 return r == -ENOENT ? 0 : r;
5305
5306         k = strlen(type);
5307         FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5308                 if (l == k && memcmp(w, type, l) == 0)
5309                         return true;
5310
5311                 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5312                         return true;
5313         }
5314
5315         return false;
5316 }
5317
5318 bool is_valid_documentation_url(const char *url) {
5319         assert(url);
5320
5321         if (startswith(url, "http://") && url[7])
5322                 return true;
5323
5324         if (startswith(url, "https://") && url[8])
5325                 return true;
5326
5327         if (startswith(url, "file:") && url[5])
5328                 return true;
5329
5330         if (startswith(url, "info:") && url[5])
5331                 return true;
5332
5333         if (startswith(url, "man:") && url[4])
5334                 return true;
5335
5336         return false;
5337 }
5338
5339 bool in_initrd(void) {
5340         static __thread int saved = -1;
5341         struct statfs s;
5342
5343         if (saved >= 0)
5344                 return saved;
5345
5346         /* We make two checks here:
5347          *
5348          * 1. the flag file /etc/initrd-release must exist
5349          * 2. the root file system must be a memory file system
5350          *
5351          * The second check is extra paranoia, since misdetecting an
5352          * initrd can have bad bad consequences due the initrd
5353          * emptying when transititioning to the main systemd.
5354          */
5355
5356         saved = access("/etc/initrd-release", F_OK) >= 0 &&
5357                 statfs("/", &s) >= 0 &&
5358                 is_temporary_fs(&s);
5359
5360         return saved;
5361 }
5362
5363 void warn_melody(void) {
5364         _cleanup_close_ int fd = -1;
5365
5366         fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5367         if (fd < 0)
5368                 return;
5369
5370         /* Yeah, this is synchronous. Kinda sucks. But well... */
5371
5372         ioctl(fd, KIOCSOUND, (int)(1193180/440));
5373         usleep(125*USEC_PER_MSEC);
5374
5375         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5376         usleep(125*USEC_PER_MSEC);
5377
5378         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5379         usleep(125*USEC_PER_MSEC);
5380
5381         ioctl(fd, KIOCSOUND, 0);
5382 }
5383
5384 int make_console_stdio(void) {
5385         int fd, r;
5386
5387         /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5388
5389         fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5390         if (fd < 0) {
5391                 log_error("Failed to acquire terminal: %s", strerror(-fd));
5392                 return fd;
5393         }
5394
5395         r = make_stdio(fd);
5396         if (r < 0) {
5397                 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5398                 return r;
5399         }
5400
5401         return 0;
5402 }
5403
5404 int get_home_dir(char **_h) {
5405         char *h;
5406         const char *e;
5407         uid_t u;
5408         struct passwd *p;
5409
5410         assert(_h);
5411
5412         /* Take the user specified one */
5413         e = getenv("HOME");
5414         if (e) {
5415                 h = strdup(e);
5416                 if (!h)
5417                         return -ENOMEM;
5418
5419                 *_h = h;
5420                 return 0;
5421         }
5422
5423         /* Hardcode home directory for root to avoid NSS */
5424         u = getuid();
5425         if (u == 0) {
5426                 h = strdup("/root");
5427                 if (!h)
5428                         return -ENOMEM;
5429
5430                 *_h = h;
5431                 return 0;
5432         }
5433
5434         /* Check the database... */
5435         errno = 0;
5436         p = getpwuid(u);
5437         if (!p)
5438                 return errno ? -errno : -ESRCH;
5439
5440         if (!path_is_absolute(p->pw_dir))
5441                 return -EINVAL;
5442
5443         h = strdup(p->pw_dir);
5444         if (!h)
5445                 return -ENOMEM;
5446
5447         *_h = h;
5448         return 0;
5449 }
5450
5451 int get_shell(char **_sh) {
5452         char *sh;
5453         const char *e;
5454         uid_t u;
5455         struct passwd *p;
5456
5457         assert(_sh);
5458
5459         /* Take the user specified one */
5460         e = getenv("SHELL");
5461         if (e) {
5462                 sh = strdup(e);
5463                 if (!sh)
5464                         return -ENOMEM;
5465
5466                 *_sh = sh;
5467                 return 0;
5468         }
5469
5470         /* Hardcode home directory for root to avoid NSS */
5471         u = getuid();
5472         if (u == 0) {
5473                 sh = strdup("/bin/sh");
5474                 if (!sh)
5475                         return -ENOMEM;
5476
5477                 *_sh = sh;
5478                 return 0;
5479         }
5480
5481         /* Check the database... */
5482         errno = 0;
5483         p = getpwuid(u);
5484         if (!p)
5485                 return errno ? -errno : -ESRCH;
5486
5487         if (!path_is_absolute(p->pw_shell))
5488                 return -EINVAL;
5489
5490         sh = strdup(p->pw_shell);
5491         if (!sh)
5492                 return -ENOMEM;
5493
5494         *_sh = sh;
5495         return 0;
5496 }
5497
5498 void freep(void *p) {
5499         free(*(void**) p);
5500 }
5501
5502 void fclosep(FILE **f) {
5503         if (*f)
5504                 fclose(*f);
5505 }
5506
5507 void closep(int *fd) {
5508         if (*fd >= 0)
5509                 close_nointr_nofail(*fd);
5510 }
5511
5512 void closedirp(DIR **d) {
5513         if (*d)
5514                 closedir(*d);
5515 }
5516
5517 void umaskp(mode_t *u) {
5518         umask(*u);
5519 }
5520
5521 bool filename_is_safe(const char *p) {
5522
5523         if (isempty(p))
5524                 return false;
5525
5526         if (strchr(p, '/'))
5527                 return false;
5528
5529         if (streq(p, "."))
5530                 return false;
5531
5532         if (streq(p, ".."))
5533                 return false;
5534
5535         if (strlen(p) > FILENAME_MAX)
5536                 return false;
5537
5538         return true;
5539 }
5540
5541 bool string_is_safe(const char *p) {
5542         const char *t;
5543
5544         assert(p);
5545
5546         for (t = p; *t; t++) {
5547                 if (*t > 0 && *t < ' ')
5548                         return false;
5549
5550                 if (strchr("\\\"\'", *t))
5551                         return false;
5552         }
5553
5554         return true;
5555 }
5556
5557 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5558 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5559                  int (*compar) (const void *, const void *, void *), void *arg) {
5560         size_t l, u, idx;
5561         const void *p;
5562         int comparison;
5563
5564         l = 0;
5565         u = nmemb;
5566         while (l < u) {
5567                 idx = (l + u) / 2;
5568                 p = (void *)(((const char *) base) + (idx * size));
5569                 comparison = compar(key, p, arg);
5570                 if (comparison < 0)
5571                         u = idx;
5572                 else if (comparison > 0)
5573                         l = idx + 1;
5574                 else
5575                         return (void *)p;
5576         }
5577         return NULL;
5578 }
5579
5580 bool is_locale_utf8(void) {
5581         const char *set;
5582         static int cached_answer = -1;
5583
5584         if (cached_answer >= 0)
5585                 goto out;
5586
5587         if (!setlocale(LC_ALL, "")) {
5588                 cached_answer = true;
5589                 goto out;
5590         }
5591
5592         set = nl_langinfo(CODESET);
5593         if (!set) {
5594                 cached_answer = true;
5595                 goto out;
5596         }
5597
5598         cached_answer = streq(set, "UTF-8");
5599 out:
5600         return (bool)cached_answer;
5601 }
5602
5603 const char *draw_special_char(DrawSpecialChar ch) {
5604         static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5605                 /* UTF-8 */ {
5606                         [DRAW_TREE_VERT]          = "\342\224\202 ",            /* │  */
5607                         [DRAW_TREE_BRANCH]        = "\342\224\234\342\224\200", /* ├─ */
5608                         [DRAW_TREE_RIGHT]         = "\342\224\224\342\224\200", /* └─ */
5609                         [DRAW_TRIANGULAR_BULLET]  = "\342\200\243 ",            /* ‣  */
5610                 },
5611                 /* ASCII fallback */ {
5612                         [DRAW_TREE_VERT]          = "| ",
5613                         [DRAW_TREE_BRANCH]        = "|-",
5614                         [DRAW_TREE_RIGHT]         = "`-",
5615                         [DRAW_TRIANGULAR_BULLET]  = "> ",
5616                 }
5617         };
5618
5619         return draw_table[!is_locale_utf8()][ch];
5620 }
5621
5622 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5623         const char *f;
5624         char *t, *r;
5625         size_t l, old_len, new_len;
5626
5627         assert(text);
5628         assert(old_string);
5629         assert(new_string);
5630
5631         old_len = strlen(old_string);
5632         new_len = strlen(new_string);
5633
5634         l = strlen(text);
5635         r = new(char, l+1);
5636         if (!r)
5637                 return NULL;
5638
5639         f = text;
5640         t = r;
5641         while (*f) {
5642                 char *a;
5643                 size_t d, nl;
5644
5645                 if (!startswith(f, old_string)) {
5646                         *(t++) = *(f++);
5647                         continue;
5648                 }
5649
5650                 d = t - r;
5651                 nl = l - old_len + new_len;
5652                 a = realloc(r, nl + 1);
5653                 if (!a)
5654                         goto oom;
5655
5656                 l = nl;
5657                 r = a;
5658                 t = r + d;
5659
5660                 t = stpcpy(t, new_string);
5661                 f += old_len;
5662         }
5663
5664         *t = 0;
5665         return r;
5666
5667 oom:
5668         free(r);
5669         return NULL;
5670 }
5671
5672 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5673         const char *i, *begin;
5674         enum {
5675                 STATE_OTHER,
5676                 STATE_ESCAPE,
5677                 STATE_BRACKET
5678         } state = STATE_OTHER;
5679         char *obuf = NULL;
5680         size_t osz = 0, isz;
5681         FILE *f;
5682
5683         assert(ibuf);
5684         assert(*ibuf);
5685
5686         /* Strips ANSI color and replaces TABs by 8 spaces */
5687
5688         isz = _isz ? *_isz : strlen(*ibuf);
5689
5690         f = open_memstream(&obuf, &osz);
5691         if (!f)
5692                 return NULL;
5693
5694         for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5695
5696                 switch (state) {
5697
5698                 case STATE_OTHER:
5699                         if (i >= *ibuf + isz) /* EOT */
5700                                 break;
5701                         else if (*i == '\x1B')
5702                                 state = STATE_ESCAPE;
5703                         else if (*i == '\t')
5704                                 fputs("        ", f);
5705                         else
5706                                 fputc(*i, f);
5707                         break;
5708
5709                 case STATE_ESCAPE:
5710                         if (i >= *ibuf + isz) { /* EOT */
5711                                 fputc('\x1B', f);
5712                                 break;
5713                         } else if (*i == '[') {
5714                                 state = STATE_BRACKET;
5715                                 begin = i + 1;
5716                         } else {
5717                                 fputc('\x1B', f);
5718                                 fputc(*i, f);
5719                                 state = STATE_OTHER;
5720                         }
5721
5722                         break;
5723
5724                 case STATE_BRACKET:
5725
5726                         if (i >= *ibuf + isz || /* EOT */
5727                             (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5728                                 fputc('\x1B', f);
5729                                 fputc('[', f);
5730                                 state = STATE_OTHER;
5731                                 i = begin-1;
5732                         } else if (*i == 'm')
5733                                 state = STATE_OTHER;
5734                         break;
5735                 }
5736         }
5737
5738         if (ferror(f)) {
5739                 fclose(f);
5740                 free(obuf);
5741                 return NULL;
5742         }
5743
5744         fclose(f);
5745
5746         free(*ibuf);
5747         *ibuf = obuf;
5748
5749         if (_isz)
5750                 *_isz = osz;
5751
5752         return obuf;
5753 }