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