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