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