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