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