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