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