chiark / gitweb /
machine-id-setup: add a machine_id_commit call to commit on disk a transient machine-id
[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 <ctype.h>
45 #include <sys/prctl.h>
46 #include <sys/utsname.h>
47 #include <pwd.h>
48 #include <netinet/ip.h>
49 #include <linux/kd.h>
50 #include <dlfcn.h>
51 #include <sys/wait.h>
52 #include <sys/time.h>
53 #include <glob.h>
54 #include <grp.h>
55 #include <sys/mman.h>
56 #include <sys/vfs.h>
57 #include <sys/mount.h>
58 #include <linux/magic.h>
59 #include <limits.h>
60 #include <langinfo.h>
61 #include <locale.h>
62 #include <sys/personality.h>
63 #include <libgen.h>
64 #undef basename
65
66 #ifdef HAVE_SYS_AUXV_H
67 #include <sys/auxv.h>
68 #endif
69
70 #include "macro.h"
71 #include "util.h"
72 #include "ioprio.h"
73 #include "missing.h"
74 #include "log.h"
75 #include "strv.h"
76 #include "label.h"
77 #include "mkdir.h"
78 #include "path-util.h"
79 #include "exit-status.h"
80 #include "hashmap.h"
81 #include "env-util.h"
82 #include "fileio.h"
83 #include "device-nodes.h"
84 #include "utf8.h"
85 #include "gunicode.h"
86 #include "virt.h"
87 #include "def.h"
88
89 int saved_argc = 0;
90 char **saved_argv = NULL;
91
92 static volatile unsigned cached_columns = 0;
93 static volatile unsigned cached_lines = 0;
94
95 size_t page_size(void) {
96         static thread_local size_t pgsz = 0;
97         long r;
98
99         if (_likely_(pgsz > 0))
100                 return pgsz;
101
102         r = sysconf(_SC_PAGESIZE);
103         assert(r > 0);
104
105         pgsz = (size_t) r;
106         return pgsz;
107 }
108
109 bool streq_ptr(const char *a, const char *b) {
110
111         /* Like streq(), but tries to make sense of NULL pointers */
112
113         if (a && b)
114                 return streq(a, b);
115
116         if (!a && !b)
117                 return true;
118
119         return false;
120 }
121
122 char* endswith(const char *s, const char *postfix) {
123         size_t sl, pl;
124
125         assert(s);
126         assert(postfix);
127
128         sl = strlen(s);
129         pl = strlen(postfix);
130
131         if (pl == 0)
132                 return (char*) s + sl;
133
134         if (sl < pl)
135                 return NULL;
136
137         if (memcmp(s + sl - pl, postfix, pl) != 0)
138                 return NULL;
139
140         return (char*) s + sl - pl;
141 }
142
143 char* first_word(const char *s, const char *word) {
144         size_t sl, wl;
145         const char *p;
146
147         assert(s);
148         assert(word);
149
150         /* Checks if the string starts with the specified word, either
151          * followed by NUL or by whitespace. Returns a pointer to the
152          * NUL or the first character after the whitespace. */
153
154         sl = strlen(s);
155         wl = strlen(word);
156
157         if (sl < wl)
158                 return NULL;
159
160         if (wl == 0)
161                 return (char*) s;
162
163         if (memcmp(s, word, wl) != 0)
164                 return NULL;
165
166         p = s + wl;
167         if (*p == 0)
168                 return (char*) p;
169
170         if (!strchr(WHITESPACE, *p))
171                 return NULL;
172
173         p += strspn(p, WHITESPACE);
174         return (char*) p;
175 }
176
177 static size_t cescape_char(char c, char *buf) {
178         char * buf_old = buf;
179
180         switch (c) {
181
182                 case '\a':
183                         *(buf++) = '\\';
184                         *(buf++) = 'a';
185                         break;
186                 case '\b':
187                         *(buf++) = '\\';
188                         *(buf++) = 'b';
189                         break;
190                 case '\f':
191                         *(buf++) = '\\';
192                         *(buf++) = 'f';
193                         break;
194                 case '\n':
195                         *(buf++) = '\\';
196                         *(buf++) = 'n';
197                         break;
198                 case '\r':
199                         *(buf++) = '\\';
200                         *(buf++) = 'r';
201                         break;
202                 case '\t':
203                         *(buf++) = '\\';
204                         *(buf++) = 't';
205                         break;
206                 case '\v':
207                         *(buf++) = '\\';
208                         *(buf++) = 'v';
209                         break;
210                 case '\\':
211                         *(buf++) = '\\';
212                         *(buf++) = '\\';
213                         break;
214                 case '"':
215                         *(buf++) = '\\';
216                         *(buf++) = '"';
217                         break;
218                 case '\'':
219                         *(buf++) = '\\';
220                         *(buf++) = '\'';
221                         break;
222
223                 default:
224                         /* For special chars we prefer octal over
225                          * hexadecimal encoding, simply because glib's
226                          * g_strescape() does the same */
227                         if ((c < ' ') || (c >= 127)) {
228                                 *(buf++) = '\\';
229                                 *(buf++) = octchar((unsigned char) c >> 6);
230                                 *(buf++) = octchar((unsigned char) c >> 3);
231                                 *(buf++) = octchar((unsigned char) c);
232                         } else
233                                 *(buf++) = c;
234                         break;
235         }
236
237         return buf - buf_old;
238 }
239
240 int close_nointr(int fd) {
241         assert(fd >= 0);
242
243         if (close(fd) >= 0)
244                 return 0;
245
246         /*
247          * Just ignore EINTR; a retry loop is the wrong thing to do on
248          * Linux.
249          *
250          * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
251          * https://bugzilla.gnome.org/show_bug.cgi?id=682819
252          * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
253          * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
254          */
255         if (errno == EINTR)
256                 return 0;
257
258         return -errno;
259 }
260
261 int safe_close(int fd) {
262
263         /*
264          * Like close_nointr() but cannot fail. Guarantees errno is
265          * unchanged. Is a NOP with negative fds passed, and returns
266          * -1, so that it can be used in this syntax:
267          *
268          * fd = safe_close(fd);
269          */
270
271         if (fd >= 0) {
272                 PROTECT_ERRNO;
273
274                 /* The kernel might return pretty much any error code
275                  * via close(), but the fd will be closed anyway. The
276                  * only condition we want to check for here is whether
277                  * the fd was invalid at all... */
278
279                 assert_se(close_nointr(fd) != -EBADF);
280         }
281
282         return -1;
283 }
284
285 void close_many(const int fds[], unsigned n_fd) {
286         unsigned i;
287
288         assert(fds || n_fd <= 0);
289
290         for (i = 0; i < n_fd; i++)
291                 safe_close(fds[i]);
292 }
293
294 int unlink_noerrno(const char *path) {
295         PROTECT_ERRNO;
296         int r;
297
298         r = unlink(path);
299         if (r < 0)
300                 return -errno;
301
302         return 0;
303 }
304
305 int parse_boolean(const char *v) {
306         assert(v);
307
308         if (streq(v, "1") || strcaseeq(v, "yes") || strcaseeq(v, "y") || strcaseeq(v, "true") || strcaseeq(v, "t") || strcaseeq(v, "on"))
309                 return 1;
310         else if (streq(v, "0") || strcaseeq(v, "no") || strcaseeq(v, "n") || strcaseeq(v, "false") || strcaseeq(v, "f") || strcaseeq(v, "off"))
311                 return 0;
312
313         return -EINVAL;
314 }
315
316 int parse_pid(const char *s, pid_t* ret_pid) {
317         unsigned long ul = 0;
318         pid_t pid;
319         int r;
320
321         assert(s);
322         assert(ret_pid);
323
324         r = safe_atolu(s, &ul);
325         if (r < 0)
326                 return r;
327
328         pid = (pid_t) ul;
329
330         if ((unsigned long) pid != ul)
331                 return -ERANGE;
332
333         if (pid <= 0)
334                 return -ERANGE;
335
336         *ret_pid = pid;
337         return 0;
338 }
339
340 int parse_uid(const char *s, uid_t* ret_uid) {
341         unsigned long ul = 0;
342         uid_t uid;
343         int r;
344
345         assert(s);
346         assert(ret_uid);
347
348         r = safe_atolu(s, &ul);
349         if (r < 0)
350                 return r;
351
352         uid = (uid_t) ul;
353
354         if ((unsigned long) uid != ul)
355                 return -ERANGE;
356
357         /* Some libc APIs use UID_INVALID as special placeholder */
358         if (uid == (uid_t) 0xFFFFFFFF)
359                 return -ENXIO;
360
361         /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
362         if (uid == (uid_t) 0xFFFF)
363                 return -ENXIO;
364
365         *ret_uid = uid;
366         return 0;
367 }
368
369 int safe_atou(const char *s, unsigned *ret_u) {
370         char *x = NULL;
371         unsigned long l;
372
373         assert(s);
374         assert(ret_u);
375
376         errno = 0;
377         l = strtoul(s, &x, 0);
378
379         if (!x || x == s || *x || errno)
380                 return errno > 0 ? -errno : -EINVAL;
381
382         if ((unsigned long) (unsigned) l != l)
383                 return -ERANGE;
384
385         *ret_u = (unsigned) l;
386         return 0;
387 }
388
389 int safe_atoi(const char *s, int *ret_i) {
390         char *x = NULL;
391         long l;
392
393         assert(s);
394         assert(ret_i);
395
396         errno = 0;
397         l = strtol(s, &x, 0);
398
399         if (!x || x == s || *x || errno)
400                 return errno > 0 ? -errno : -EINVAL;
401
402         if ((long) (int) l != l)
403                 return -ERANGE;
404
405         *ret_i = (int) l;
406         return 0;
407 }
408
409 int safe_atou8(const char *s, uint8_t *ret) {
410         char *x = NULL;
411         unsigned long l;
412
413         assert(s);
414         assert(ret);
415
416         errno = 0;
417         l = strtoul(s, &x, 0);
418
419         if (!x || x == s || *x || errno)
420                 return errno > 0 ? -errno : -EINVAL;
421
422         if ((unsigned long) (uint8_t) l != l)
423                 return -ERANGE;
424
425         *ret = (uint8_t) l;
426         return 0;
427 }
428
429 int safe_atou16(const char *s, uint16_t *ret) {
430         char *x = NULL;
431         unsigned long l;
432
433         assert(s);
434         assert(ret);
435
436         errno = 0;
437         l = strtoul(s, &x, 0);
438
439         if (!x || x == s || *x || errno)
440                 return errno > 0 ? -errno : -EINVAL;
441
442         if ((unsigned long) (uint16_t) l != l)
443                 return -ERANGE;
444
445         *ret = (uint16_t) l;
446         return 0;
447 }
448
449 int safe_atoi16(const char *s, int16_t *ret) {
450         char *x = NULL;
451         long l;
452
453         assert(s);
454         assert(ret);
455
456         errno = 0;
457         l = strtol(s, &x, 0);
458
459         if (!x || x == s || *x || errno)
460                 return errno > 0 ? -errno : -EINVAL;
461
462         if ((long) (int16_t) l != l)
463                 return -ERANGE;
464
465         *ret = (int16_t) l;
466         return 0;
467 }
468
469 int safe_atollu(const char *s, long long unsigned *ret_llu) {
470         char *x = NULL;
471         unsigned long long l;
472
473         assert(s);
474         assert(ret_llu);
475
476         errno = 0;
477         l = strtoull(s, &x, 0);
478
479         if (!x || x == s || *x || errno)
480                 return errno ? -errno : -EINVAL;
481
482         *ret_llu = l;
483         return 0;
484 }
485
486 int safe_atolli(const char *s, long long int *ret_lli) {
487         char *x = NULL;
488         long long l;
489
490         assert(s);
491         assert(ret_lli);
492
493         errno = 0;
494         l = strtoll(s, &x, 0);
495
496         if (!x || x == s || *x || errno)
497                 return errno ? -errno : -EINVAL;
498
499         *ret_lli = l;
500         return 0;
501 }
502
503 int safe_atod(const char *s, double *ret_d) {
504         char *x = NULL;
505         double d = 0;
506
507         assert(s);
508         assert(ret_d);
509
510         RUN_WITH_LOCALE(LC_NUMERIC_MASK, "C") {
511                 errno = 0;
512                 d = strtod(s, &x);
513         }
514
515         if (!x || x == s || *x || errno)
516                 return errno ? -errno : -EINVAL;
517
518         *ret_d = (double) d;
519         return 0;
520 }
521
522 static size_t strcspn_escaped(const char *s, const char *reject) {
523         bool escaped = false;
524         size_t n;
525
526         for (n=0; s[n]; n++) {
527                 if (escaped)
528                         escaped = false;
529                 else if (s[n] == '\\')
530                         escaped = true;
531                 else if (strchr(reject, s[n]))
532                         break;
533         }
534         /* if s ends in \, return index of previous char */
535         return n - escaped;
536 }
537
538 /* Split a string into words. */
539 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
540         const char *current;
541
542         current = *state;
543
544         if (!*current) {
545                 assert(**state == '\0');
546                 return NULL;
547         }
548
549         current += strspn(current, separator);
550         if (!*current) {
551                 *state = current;
552                 return NULL;
553         }
554
555         if (quoted && strchr("\'\"", *current)) {
556                 char quotechars[2] = {*current, '\0'};
557
558                 *l = strcspn_escaped(current + 1, quotechars);
559                 if (current[*l + 1] == '\0' ||
560                     (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
561                         /* right quote missing or garbage at the end*/
562                         *state = current;
563                         return NULL;
564                 }
565                 assert(current[*l + 1] == quotechars[0]);
566                 *state = current++ + *l + 2;
567         } else if (quoted) {
568                 *l = strcspn_escaped(current, separator);
569                 *state = current + *l;
570         } else {
571                 *l = strcspn(current, separator);
572                 *state = current + *l;
573         }
574
575         return current;
576 }
577
578 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
579         int r;
580         _cleanup_free_ char *line = NULL;
581         long unsigned ppid;
582         const char *p;
583
584         assert(pid >= 0);
585         assert(_ppid);
586
587         if (pid == 0) {
588                 *_ppid = getppid();
589                 return 0;
590         }
591
592         p = procfs_file_alloca(pid, "stat");
593         r = read_one_line_file(p, &line);
594         if (r < 0)
595                 return r;
596
597         /* Let's skip the pid and comm fields. The latter is enclosed
598          * in () but does not escape any () in its value, so let's
599          * skip over it manually */
600
601         p = strrchr(line, ')');
602         if (!p)
603                 return -EIO;
604
605         p++;
606
607         if (sscanf(p, " "
608                    "%*c "  /* state */
609                    "%lu ", /* ppid */
610                    &ppid) != 1)
611                 return -EIO;
612
613         if ((long unsigned) (pid_t) ppid != ppid)
614                 return -ERANGE;
615
616         *_ppid = (pid_t) ppid;
617
618         return 0;
619 }
620
621 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
622         int r;
623         _cleanup_free_ char *line = NULL;
624         const char *p;
625
626         assert(pid >= 0);
627         assert(st);
628
629         p = procfs_file_alloca(pid, "stat");
630         r = read_one_line_file(p, &line);
631         if (r < 0)
632                 return r;
633
634         /* Let's skip the pid and comm fields. The latter is enclosed
635          * in () but does not escape any () in its value, so let's
636          * skip over it manually */
637
638         p = strrchr(line, ')');
639         if (!p)
640                 return -EIO;
641
642         p++;
643
644         if (sscanf(p, " "
645                    "%*c "  /* state */
646                    "%*d "  /* ppid */
647                    "%*d "  /* pgrp */
648                    "%*d "  /* session */
649                    "%*d "  /* tty_nr */
650                    "%*d "  /* tpgid */
651                    "%*u "  /* flags */
652                    "%*u "  /* minflt */
653                    "%*u "  /* cminflt */
654                    "%*u "  /* majflt */
655                    "%*u "  /* cmajflt */
656                    "%*u "  /* utime */
657                    "%*u "  /* stime */
658                    "%*d "  /* cutime */
659                    "%*d "  /* cstime */
660                    "%*d "  /* priority */
661                    "%*d "  /* nice */
662                    "%*d "  /* num_threads */
663                    "%*d "  /* itrealvalue */
664                    "%llu "  /* starttime */,
665                    st) != 1)
666                 return -EIO;
667
668         return 0;
669 }
670
671 int fchmod_umask(int fd, mode_t m) {
672         mode_t u;
673         int r;
674
675         u = umask(0777);
676         r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
677         umask(u);
678
679         return r;
680 }
681
682 char *truncate_nl(char *s) {
683         assert(s);
684
685         s[strcspn(s, NEWLINE)] = 0;
686         return s;
687 }
688
689 int get_process_state(pid_t pid) {
690         const char *p;
691         char state;
692         int r;
693         _cleanup_free_ char *line = NULL;
694
695         assert(pid >= 0);
696
697         p = procfs_file_alloca(pid, "stat");
698         r = read_one_line_file(p, &line);
699         if (r < 0)
700                 return r;
701
702         p = strrchr(line, ')');
703         if (!p)
704                 return -EIO;
705
706         p++;
707
708         if (sscanf(p, " %c", &state) != 1)
709                 return -EIO;
710
711         return (unsigned char) state;
712 }
713
714 int get_process_comm(pid_t pid, char **name) {
715         const char *p;
716         int r;
717
718         assert(name);
719         assert(pid >= 0);
720
721         p = procfs_file_alloca(pid, "comm");
722
723         r = read_one_line_file(p, name);
724         if (r == -ENOENT)
725                 return -ESRCH;
726
727         return r;
728 }
729
730 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
731         _cleanup_fclose_ FILE *f = NULL;
732         char *r = NULL, *k;
733         const char *p;
734         int c;
735
736         assert(line);
737         assert(pid >= 0);
738
739         p = procfs_file_alloca(pid, "cmdline");
740
741         f = fopen(p, "re");
742         if (!f)
743                 return -errno;
744
745         if (max_length == 0) {
746                 size_t len = 0, allocated = 0;
747
748                 while ((c = getc(f)) != EOF) {
749
750                         if (!GREEDY_REALLOC(r, allocated, len+2)) {
751                                 free(r);
752                                 return -ENOMEM;
753                         }
754
755                         r[len++] = isprint(c) ? c : ' ';
756                 }
757
758                 if (len > 0)
759                         r[len-1] = 0;
760
761         } else {
762                 bool space = false;
763                 size_t left;
764
765                 r = new(char, max_length);
766                 if (!r)
767                         return -ENOMEM;
768
769                 k = r;
770                 left = max_length;
771                 while ((c = getc(f)) != EOF) {
772
773                         if (isprint(c)) {
774                                 if (space) {
775                                         if (left <= 4)
776                                                 break;
777
778                                         *(k++) = ' ';
779                                         left--;
780                                         space = false;
781                                 }
782
783                                 if (left <= 4)
784                                         break;
785
786                                 *(k++) = (char) c;
787                                 left--;
788                         }  else
789                                 space = true;
790                 }
791
792                 if (left <= 4) {
793                         size_t n = MIN(left-1, 3U);
794                         memcpy(k, "...", n);
795                         k[n] = 0;
796                 } else
797                         *k = 0;
798         }
799
800         /* Kernel threads have no argv[] */
801         if (isempty(r)) {
802                 _cleanup_free_ char *t = NULL;
803                 int h;
804
805                 free(r);
806
807                 if (!comm_fallback)
808                         return -ENOENT;
809
810                 h = get_process_comm(pid, &t);
811                 if (h < 0)
812                         return h;
813
814                 r = strjoin("[", t, "]", NULL);
815                 if (!r)
816                         return -ENOMEM;
817         }
818
819         *line = r;
820         return 0;
821 }
822
823 int is_kernel_thread(pid_t pid) {
824         const char *p;
825         size_t count;
826         char c;
827         bool eof;
828         FILE *f;
829
830         if (pid == 0)
831                 return 0;
832
833         assert(pid > 0);
834
835         p = procfs_file_alloca(pid, "cmdline");
836         f = fopen(p, "re");
837         if (!f)
838                 return -errno;
839
840         count = fread(&c, 1, 1, f);
841         eof = feof(f);
842         fclose(f);
843
844         /* Kernel threads have an empty cmdline */
845
846         if (count <= 0)
847                 return eof ? 1 : -errno;
848
849         return 0;
850 }
851
852 int get_process_capeff(pid_t pid, char **capeff) {
853         const char *p;
854
855         assert(capeff);
856         assert(pid >= 0);
857
858         p = procfs_file_alloca(pid, "status");
859
860         return get_status_field(p, "\nCapEff:", capeff);
861 }
862
863 static int get_process_link_contents(const char *proc_file, char **name) {
864         int r;
865
866         assert(proc_file);
867         assert(name);
868
869         r = readlink_malloc(proc_file, name);
870         if (r < 0)
871                 return r == -ENOENT ? -ESRCH : r;
872
873         return 0;
874 }
875
876 int get_process_exe(pid_t pid, char **name) {
877         const char *p;
878         char *d;
879         int r;
880
881         assert(pid >= 0);
882
883         p = procfs_file_alloca(pid, "exe");
884         r = get_process_link_contents(p, name);
885         if (r < 0)
886                 return r;
887
888         d = endswith(*name, " (deleted)");
889         if (d)
890                 *d = '\0';
891
892         return 0;
893 }
894
895 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
896         _cleanup_fclose_ FILE *f = NULL;
897         char line[LINE_MAX];
898         const char *p;
899
900         assert(field);
901         assert(uid);
902
903         if (pid == 0)
904                 return getuid();
905
906         p = procfs_file_alloca(pid, "status");
907         f = fopen(p, "re");
908         if (!f)
909                 return -errno;
910
911         FOREACH_LINE(line, f, return -errno) {
912                 char *l;
913
914                 l = strstrip(line);
915
916                 if (startswith(l, field)) {
917                         l += strlen(field);
918                         l += strspn(l, WHITESPACE);
919
920                         l[strcspn(l, WHITESPACE)] = 0;
921
922                         return parse_uid(l, uid);
923                 }
924         }
925
926         return -EIO;
927 }
928
929 int get_process_uid(pid_t pid, uid_t *uid) {
930         return get_process_id(pid, "Uid:", uid);
931 }
932
933 int get_process_gid(pid_t pid, gid_t *gid) {
934         assert_cc(sizeof(uid_t) == sizeof(gid_t));
935         return get_process_id(pid, "Gid:", gid);
936 }
937
938 int get_process_cwd(pid_t pid, char **cwd) {
939         const char *p;
940
941         assert(pid >= 0);
942
943         p = procfs_file_alloca(pid, "cwd");
944
945         return get_process_link_contents(p, cwd);
946 }
947
948 int get_process_root(pid_t pid, char **root) {
949         const char *p;
950
951         assert(pid >= 0);
952
953         p = procfs_file_alloca(pid, "root");
954
955         return get_process_link_contents(p, root);
956 }
957
958 int get_process_environ(pid_t pid, char **environ) {
959         _cleanup_fclose_ FILE *f = NULL;
960         _cleanup_free_ char *outcome = NULL;
961         int c;
962         const char *p;
963         size_t allocated = 0, sz = 0;
964
965         assert(pid >= 0);
966         assert(environ);
967
968         p = procfs_file_alloca(pid, "environ");
969
970         f = fopen(p, "re");
971         if (!f)
972                 return -errno;
973
974         while ((c = fgetc(f)) != EOF) {
975                 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
976                         return -ENOMEM;
977
978                 if (c == '\0')
979                         outcome[sz++] = '\n';
980                 else
981                         sz += cescape_char(c, outcome + sz);
982         }
983
984         outcome[sz] = '\0';
985         *environ = outcome;
986         outcome = NULL;
987
988         return 0;
989 }
990
991 char *strnappend(const char *s, const char *suffix, size_t b) {
992         size_t a;
993         char *r;
994
995         if (!s && !suffix)
996                 return strdup("");
997
998         if (!s)
999                 return strndup(suffix, b);
1000
1001         if (!suffix)
1002                 return strdup(s);
1003
1004         assert(s);
1005         assert(suffix);
1006
1007         a = strlen(s);
1008         if (b > ((size_t) -1) - a)
1009                 return NULL;
1010
1011         r = new(char, a+b+1);
1012         if (!r)
1013                 return NULL;
1014
1015         memcpy(r, s, a);
1016         memcpy(r+a, suffix, b);
1017         r[a+b] = 0;
1018
1019         return r;
1020 }
1021
1022 char *strappend(const char *s, const char *suffix) {
1023         return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1024 }
1025
1026 int readlinkat_malloc(int fd, const char *p, char **ret) {
1027         size_t l = 100;
1028         int r;
1029
1030         assert(p);
1031         assert(ret);
1032
1033         for (;;) {
1034                 char *c;
1035                 ssize_t n;
1036
1037                 c = new(char, l);
1038                 if (!c)
1039                         return -ENOMEM;
1040
1041                 n = readlinkat(fd, p, c, l-1);
1042                 if (n < 0) {
1043                         r = -errno;
1044                         free(c);
1045                         return r;
1046                 }
1047
1048                 if ((size_t) n < l-1) {
1049                         c[n] = 0;
1050                         *ret = c;
1051                         return 0;
1052                 }
1053
1054                 free(c);
1055                 l *= 2;
1056         }
1057 }
1058
1059 int readlink_malloc(const char *p, char **ret) {
1060         return readlinkat_malloc(AT_FDCWD, p, ret);
1061 }
1062
1063 int readlink_value(const char *p, char **ret) {
1064         _cleanup_free_ char *link = NULL;
1065         char *value;
1066         int r;
1067
1068         r = readlink_malloc(p, &link);
1069         if (r < 0)
1070                 return r;
1071
1072         value = basename(link);
1073         if (!value)
1074                 return -ENOENT;
1075
1076         value = strdup(value);
1077         if (!value)
1078                 return -ENOMEM;
1079
1080         *ret = value;
1081
1082         return 0;
1083 }
1084
1085 int readlink_and_make_absolute(const char *p, char **r) {
1086         _cleanup_free_ char *target = NULL;
1087         char *k;
1088         int j;
1089
1090         assert(p);
1091         assert(r);
1092
1093         j = readlink_malloc(p, &target);
1094         if (j < 0)
1095                 return j;
1096
1097         k = file_in_same_dir(p, target);
1098         if (!k)
1099                 return -ENOMEM;
1100
1101         *r = k;
1102         return 0;
1103 }
1104
1105 int readlink_and_canonicalize(const char *p, char **r) {
1106         char *t, *s;
1107         int j;
1108
1109         assert(p);
1110         assert(r);
1111
1112         j = readlink_and_make_absolute(p, &t);
1113         if (j < 0)
1114                 return j;
1115
1116         s = canonicalize_file_name(t);
1117         if (s) {
1118                 free(t);
1119                 *r = s;
1120         } else
1121                 *r = t;
1122
1123         path_kill_slashes(*r);
1124
1125         return 0;
1126 }
1127
1128 int reset_all_signal_handlers(void) {
1129         int sig, r = 0;
1130
1131         for (sig = 1; sig < _NSIG; sig++) {
1132                 struct sigaction sa = {
1133                         .sa_handler = SIG_DFL,
1134                         .sa_flags = SA_RESTART,
1135                 };
1136
1137                 /* These two cannot be caught... */
1138                 if (sig == SIGKILL || sig == SIGSTOP)
1139                         continue;
1140
1141                 /* On Linux the first two RT signals are reserved by
1142                  * glibc, and sigaction() will return EINVAL for them. */
1143                 if ((sigaction(sig, &sa, NULL) < 0))
1144                         if (errno != EINVAL && r == 0)
1145                                 r = -errno;
1146         }
1147
1148         return r;
1149 }
1150
1151 int reset_signal_mask(void) {
1152         sigset_t ss;
1153
1154         if (sigemptyset(&ss) < 0)
1155                 return -errno;
1156
1157         if (sigprocmask(SIG_SETMASK, &ss, NULL) < 0)
1158                 return -errno;
1159
1160         return 0;
1161 }
1162
1163 char *strstrip(char *s) {
1164         char *e;
1165
1166         /* Drops trailing whitespace. Modifies the string in
1167          * place. Returns pointer to first non-space character */
1168
1169         s += strspn(s, WHITESPACE);
1170
1171         for (e = strchr(s, 0); e > s; e --)
1172                 if (!strchr(WHITESPACE, e[-1]))
1173                         break;
1174
1175         *e = 0;
1176
1177         return s;
1178 }
1179
1180 char *delete_chars(char *s, const char *bad) {
1181         char *f, *t;
1182
1183         /* Drops all whitespace, regardless where in the string */
1184
1185         for (f = s, t = s; *f; f++) {
1186                 if (strchr(bad, *f))
1187                         continue;
1188
1189                 *(t++) = *f;
1190         }
1191
1192         *t = 0;
1193
1194         return s;
1195 }
1196
1197 char *file_in_same_dir(const char *path, const char *filename) {
1198         char *e, *r;
1199         size_t k;
1200
1201         assert(path);
1202         assert(filename);
1203
1204         /* This removes the last component of path and appends
1205          * filename, unless the latter is absolute anyway or the
1206          * former isn't */
1207
1208         if (path_is_absolute(filename))
1209                 return strdup(filename);
1210
1211         if (!(e = strrchr(path, '/')))
1212                 return strdup(filename);
1213
1214         k = strlen(filename);
1215         if (!(r = new(char, e-path+1+k+1)))
1216                 return NULL;
1217
1218         memcpy(r, path, e-path+1);
1219         memcpy(r+(e-path)+1, filename, k+1);
1220
1221         return r;
1222 }
1223
1224 int rmdir_parents(const char *path, const char *stop) {
1225         size_t l;
1226         int r = 0;
1227
1228         assert(path);
1229         assert(stop);
1230
1231         l = strlen(path);
1232
1233         /* Skip trailing slashes */
1234         while (l > 0 && path[l-1] == '/')
1235                 l--;
1236
1237         while (l > 0) {
1238                 char *t;
1239
1240                 /* Skip last component */
1241                 while (l > 0 && path[l-1] != '/')
1242                         l--;
1243
1244                 /* Skip trailing slashes */
1245                 while (l > 0 && path[l-1] == '/')
1246                         l--;
1247
1248                 if (l <= 0)
1249                         break;
1250
1251                 if (!(t = strndup(path, l)))
1252                         return -ENOMEM;
1253
1254                 if (path_startswith(stop, t)) {
1255                         free(t);
1256                         return 0;
1257                 }
1258
1259                 r = rmdir(t);
1260                 free(t);
1261
1262                 if (r < 0)
1263                         if (errno != ENOENT)
1264                                 return -errno;
1265         }
1266
1267         return 0;
1268 }
1269
1270 char hexchar(int x) {
1271         static const char table[16] = "0123456789abcdef";
1272
1273         return table[x & 15];
1274 }
1275
1276 int unhexchar(char c) {
1277
1278         if (c >= '0' && c <= '9')
1279                 return c - '0';
1280
1281         if (c >= 'a' && c <= 'f')
1282                 return c - 'a' + 10;
1283
1284         if (c >= 'A' && c <= 'F')
1285                 return c - 'A' + 10;
1286
1287         return -EINVAL;
1288 }
1289
1290 char *hexmem(const void *p, size_t l) {
1291         char *r, *z;
1292         const uint8_t *x;
1293
1294         z = r = malloc(l * 2 + 1);
1295         if (!r)
1296                 return NULL;
1297
1298         for (x = p; x < (const uint8_t*) p + l; x++) {
1299                 *(z++) = hexchar(*x >> 4);
1300                 *(z++) = hexchar(*x & 15);
1301         }
1302
1303         *z = 0;
1304         return r;
1305 }
1306
1307 void *unhexmem(const char *p, size_t l) {
1308         uint8_t *r, *z;
1309         const char *x;
1310
1311         assert(p);
1312
1313         z = r = malloc((l + 1) / 2 + 1);
1314         if (!r)
1315                 return NULL;
1316
1317         for (x = p; x < p + l; x += 2) {
1318                 int a, b;
1319
1320                 a = unhexchar(x[0]);
1321                 if (x+1 < p + l)
1322                         b = unhexchar(x[1]);
1323                 else
1324                         b = 0;
1325
1326                 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1327         }
1328
1329         *z = 0;
1330         return r;
1331 }
1332
1333 char octchar(int x) {
1334         return '0' + (x & 7);
1335 }
1336
1337 int unoctchar(char c) {
1338
1339         if (c >= '0' && c <= '7')
1340                 return c - '0';
1341
1342         return -EINVAL;
1343 }
1344
1345 char decchar(int x) {
1346         return '0' + (x % 10);
1347 }
1348
1349 int undecchar(char c) {
1350
1351         if (c >= '0' && c <= '9')
1352                 return c - '0';
1353
1354         return -EINVAL;
1355 }
1356
1357 char *cescape(const char *s) {
1358         char *r, *t;
1359         const char *f;
1360
1361         assert(s);
1362
1363         /* Does C style string escaping. */
1364
1365         r = new(char, strlen(s)*4 + 1);
1366         if (!r)
1367                 return NULL;
1368
1369         for (f = s, t = r; *f; f++)
1370                 t += cescape_char(*f, t);
1371
1372         *t = 0;
1373
1374         return r;
1375 }
1376
1377 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1378         char *r, *t;
1379         const char *f;
1380         size_t pl;
1381
1382         assert(s);
1383
1384         /* Undoes C style string escaping, and optionally prefixes it. */
1385
1386         pl = prefix ? strlen(prefix) : 0;
1387
1388         r = new(char, pl+length+1);
1389         if (!r)
1390                 return NULL;
1391
1392         if (prefix)
1393                 memcpy(r, prefix, pl);
1394
1395         for (f = s, t = r + pl; f < s + length; f++) {
1396
1397                 if (*f != '\\') {
1398                         *(t++) = *f;
1399                         continue;
1400                 }
1401
1402                 f++;
1403
1404                 switch (*f) {
1405
1406                 case 'a':
1407                         *(t++) = '\a';
1408                         break;
1409                 case 'b':
1410                         *(t++) = '\b';
1411                         break;
1412                 case 'f':
1413                         *(t++) = '\f';
1414                         break;
1415                 case 'n':
1416                         *(t++) = '\n';
1417                         break;
1418                 case 'r':
1419                         *(t++) = '\r';
1420                         break;
1421                 case 't':
1422                         *(t++) = '\t';
1423                         break;
1424                 case 'v':
1425                         *(t++) = '\v';
1426                         break;
1427                 case '\\':
1428                         *(t++) = '\\';
1429                         break;
1430                 case '"':
1431                         *(t++) = '"';
1432                         break;
1433                 case '\'':
1434                         *(t++) = '\'';
1435                         break;
1436
1437                 case 's':
1438                         /* This is an extension of the XDG syntax files */
1439                         *(t++) = ' ';
1440                         break;
1441
1442                 case 'x': {
1443                         /* hexadecimal encoding */
1444                         int a, b;
1445
1446                         a = unhexchar(f[1]);
1447                         b = unhexchar(f[2]);
1448
1449                         if (a < 0 || b < 0 || (a == 0 && b == 0)) {
1450                                 /* Invalid escape code, let's take it literal then */
1451                                 *(t++) = '\\';
1452                                 *(t++) = 'x';
1453                         } else {
1454                                 *(t++) = (char) ((a << 4) | b);
1455                                 f += 2;
1456                         }
1457
1458                         break;
1459                 }
1460
1461                 case '0':
1462                 case '1':
1463                 case '2':
1464                 case '3':
1465                 case '4':
1466                 case '5':
1467                 case '6':
1468                 case '7': {
1469                         /* octal encoding */
1470                         int a, b, c;
1471
1472                         a = unoctchar(f[0]);
1473                         b = unoctchar(f[1]);
1474                         c = unoctchar(f[2]);
1475
1476                         if (a < 0 || b < 0 || c < 0 || (a == 0 && b == 0 && c == 0)) {
1477                                 /* Invalid escape code, let's take it literal then */
1478                                 *(t++) = '\\';
1479                                 *(t++) = f[0];
1480                         } else {
1481                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
1482                                 f += 2;
1483                         }
1484
1485                         break;
1486                 }
1487
1488                 case 0:
1489                         /* premature end of string.*/
1490                         *(t++) = '\\';
1491                         goto finish;
1492
1493                 default:
1494                         /* Invalid escape code, let's take it literal then */
1495                         *(t++) = '\\';
1496                         *(t++) = *f;
1497                         break;
1498                 }
1499         }
1500
1501 finish:
1502         *t = 0;
1503         return r;
1504 }
1505
1506 char *cunescape_length(const char *s, size_t length) {
1507         return cunescape_length_with_prefix(s, length, NULL);
1508 }
1509
1510 char *cunescape(const char *s) {
1511         assert(s);
1512
1513         return cunescape_length(s, strlen(s));
1514 }
1515
1516 char *xescape(const char *s, const char *bad) {
1517         char *r, *t;
1518         const char *f;
1519
1520         /* Escapes all chars in bad, in addition to \ and all special
1521          * chars, in \xFF style escaping. May be reversed with
1522          * cunescape. */
1523
1524         r = new(char, strlen(s) * 4 + 1);
1525         if (!r)
1526                 return NULL;
1527
1528         for (f = s, t = r; *f; f++) {
1529
1530                 if ((*f < ' ') || (*f >= 127) ||
1531                     (*f == '\\') || strchr(bad, *f)) {
1532                         *(t++) = '\\';
1533                         *(t++) = 'x';
1534                         *(t++) = hexchar(*f >> 4);
1535                         *(t++) = hexchar(*f);
1536                 } else
1537                         *(t++) = *f;
1538         }
1539
1540         *t = 0;
1541
1542         return r;
1543 }
1544
1545 char *ascii_strlower(char *t) {
1546         char *p;
1547
1548         assert(t);
1549
1550         for (p = t; *p; p++)
1551                 if (*p >= 'A' && *p <= 'Z')
1552                         *p = *p - 'A' + 'a';
1553
1554         return t;
1555 }
1556
1557 _pure_ static bool ignore_file_allow_backup(const char *filename) {
1558         assert(filename);
1559
1560         return
1561                 filename[0] == '.' ||
1562                 streq(filename, "lost+found") ||
1563                 streq(filename, "aquota.user") ||
1564                 streq(filename, "aquota.group") ||
1565                 endswith(filename, ".rpmnew") ||
1566                 endswith(filename, ".rpmsave") ||
1567                 endswith(filename, ".rpmorig") ||
1568                 endswith(filename, ".dpkg-old") ||
1569                 endswith(filename, ".dpkg-new") ||
1570                 endswith(filename, ".dpkg-tmp") ||
1571                 endswith(filename, ".swp");
1572 }
1573
1574 bool ignore_file(const char *filename) {
1575         assert(filename);
1576
1577         if (endswith(filename, "~"))
1578                 return true;
1579
1580         return ignore_file_allow_backup(filename);
1581 }
1582
1583 int fd_nonblock(int fd, bool nonblock) {
1584         int flags, nflags;
1585
1586         assert(fd >= 0);
1587
1588         flags = fcntl(fd, F_GETFL, 0);
1589         if (flags < 0)
1590                 return -errno;
1591
1592         if (nonblock)
1593                 nflags = flags | O_NONBLOCK;
1594         else
1595                 nflags = flags & ~O_NONBLOCK;
1596
1597         if (nflags == flags)
1598                 return 0;
1599
1600         if (fcntl(fd, F_SETFL, nflags) < 0)
1601                 return -errno;
1602
1603         return 0;
1604 }
1605
1606 int fd_cloexec(int fd, bool cloexec) {
1607         int flags, nflags;
1608
1609         assert(fd >= 0);
1610
1611         flags = fcntl(fd, F_GETFD, 0);
1612         if (flags < 0)
1613                 return -errno;
1614
1615         if (cloexec)
1616                 nflags = flags | FD_CLOEXEC;
1617         else
1618                 nflags = flags & ~FD_CLOEXEC;
1619
1620         if (nflags == flags)
1621                 return 0;
1622
1623         if (fcntl(fd, F_SETFD, nflags) < 0)
1624                 return -errno;
1625
1626         return 0;
1627 }
1628
1629 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1630         unsigned i;
1631
1632         assert(n_fdset == 0 || fdset);
1633
1634         for (i = 0; i < n_fdset; i++)
1635                 if (fdset[i] == fd)
1636                         return true;
1637
1638         return false;
1639 }
1640
1641 int close_all_fds(const int except[], unsigned n_except) {
1642         _cleanup_closedir_ DIR *d = NULL;
1643         struct dirent *de;
1644         int r = 0;
1645
1646         assert(n_except == 0 || except);
1647
1648         d = opendir("/proc/self/fd");
1649         if (!d) {
1650                 int fd;
1651                 struct rlimit rl;
1652
1653                 /* When /proc isn't available (for example in chroots)
1654                  * the fallback is brute forcing through the fd
1655                  * table */
1656
1657                 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1658                 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1659
1660                         if (fd_in_set(fd, except, n_except))
1661                                 continue;
1662
1663                         if (close_nointr(fd) < 0)
1664                                 if (errno != EBADF && r == 0)
1665                                         r = -errno;
1666                 }
1667
1668                 return r;
1669         }
1670
1671         while ((de = readdir(d))) {
1672                 int fd = -1;
1673
1674                 if (ignore_file(de->d_name))
1675                         continue;
1676
1677                 if (safe_atoi(de->d_name, &fd) < 0)
1678                         /* Let's better ignore this, just in case */
1679                         continue;
1680
1681                 if (fd < 3)
1682                         continue;
1683
1684                 if (fd == dirfd(d))
1685                         continue;
1686
1687                 if (fd_in_set(fd, except, n_except))
1688                         continue;
1689
1690                 if (close_nointr(fd) < 0) {
1691                         /* Valgrind has its own FD and doesn't want to have it closed */
1692                         if (errno != EBADF && r == 0)
1693                                 r = -errno;
1694                 }
1695         }
1696
1697         return r;
1698 }
1699
1700 bool chars_intersect(const char *a, const char *b) {
1701         const char *p;
1702
1703         /* Returns true if any of the chars in a are in b. */
1704         for (p = a; *p; p++)
1705                 if (strchr(b, *p))
1706                         return true;
1707
1708         return false;
1709 }
1710
1711 bool fstype_is_network(const char *fstype) {
1712         static const char table[] =
1713                 "cifs\0"
1714                 "smbfs\0"
1715                 "sshfs\0"
1716                 "ncpfs\0"
1717                 "ncp\0"
1718                 "nfs\0"
1719                 "nfs4\0"
1720                 "gfs\0"
1721                 "gfs2\0"
1722                 "glusterfs\0";
1723
1724         const char *x;
1725
1726         x = startswith(fstype, "fuse.");
1727         if (x)
1728                 fstype = x;
1729
1730         return nulstr_contains(table, fstype);
1731 }
1732
1733 int chvt(int vt) {
1734         _cleanup_close_ int fd;
1735
1736         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1737         if (fd < 0)
1738                 return -errno;
1739
1740         if (vt < 0) {
1741                 int tiocl[2] = {
1742                         TIOCL_GETKMSGREDIRECT,
1743                         0
1744                 };
1745
1746                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1747                         return -errno;
1748
1749                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1750         }
1751
1752         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1753                 return -errno;
1754
1755         return 0;
1756 }
1757
1758 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1759         struct termios old_termios, new_termios;
1760         char c, line[LINE_MAX];
1761
1762         assert(f);
1763         assert(ret);
1764
1765         if (tcgetattr(fileno(f), &old_termios) >= 0) {
1766                 new_termios = old_termios;
1767
1768                 new_termios.c_lflag &= ~ICANON;
1769                 new_termios.c_cc[VMIN] = 1;
1770                 new_termios.c_cc[VTIME] = 0;
1771
1772                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1773                         size_t k;
1774
1775                         if (t != USEC_INFINITY) {
1776                                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1777                                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1778                                         return -ETIMEDOUT;
1779                                 }
1780                         }
1781
1782                         k = fread(&c, 1, 1, f);
1783
1784                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1785
1786                         if (k <= 0)
1787                                 return -EIO;
1788
1789                         if (need_nl)
1790                                 *need_nl = c != '\n';
1791
1792                         *ret = c;
1793                         return 0;
1794                 }
1795         }
1796
1797         if (t != USEC_INFINITY) {
1798                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1799                         return -ETIMEDOUT;
1800         }
1801
1802         errno = 0;
1803         if (!fgets(line, sizeof(line), f))
1804                 return errno ? -errno : -EIO;
1805
1806         truncate_nl(line);
1807
1808         if (strlen(line) != 1)
1809                 return -EBADMSG;
1810
1811         if (need_nl)
1812                 *need_nl = false;
1813
1814         *ret = line[0];
1815         return 0;
1816 }
1817
1818 int ask_char(char *ret, const char *replies, const char *text, ...) {
1819         int r;
1820
1821         assert(ret);
1822         assert(replies);
1823         assert(text);
1824
1825         for (;;) {
1826                 va_list ap;
1827                 char c;
1828                 bool need_nl = true;
1829
1830                 if (on_tty())
1831                         fputs(ANSI_HIGHLIGHT_ON, stdout);
1832
1833                 va_start(ap, text);
1834                 vprintf(text, ap);
1835                 va_end(ap);
1836
1837                 if (on_tty())
1838                         fputs(ANSI_HIGHLIGHT_OFF, stdout);
1839
1840                 fflush(stdout);
1841
1842                 r = read_one_char(stdin, &c, USEC_INFINITY, &need_nl);
1843                 if (r < 0) {
1844
1845                         if (r == -EBADMSG) {
1846                                 puts("Bad input, please try again.");
1847                                 continue;
1848                         }
1849
1850                         putchar('\n');
1851                         return r;
1852                 }
1853
1854                 if (need_nl)
1855                         putchar('\n');
1856
1857                 if (strchr(replies, c)) {
1858                         *ret = c;
1859                         return 0;
1860                 }
1861
1862                 puts("Read unexpected character, please try again.");
1863         }
1864 }
1865
1866 int ask_string(char **ret, const char *text, ...) {
1867         assert(ret);
1868         assert(text);
1869
1870         for (;;) {
1871                 char line[LINE_MAX];
1872                 va_list ap;
1873
1874                 if (on_tty())
1875                         fputs(ANSI_HIGHLIGHT_ON, stdout);
1876
1877                 va_start(ap, text);
1878                 vprintf(text, ap);
1879                 va_end(ap);
1880
1881                 if (on_tty())
1882                         fputs(ANSI_HIGHLIGHT_OFF, stdout);
1883
1884                 fflush(stdout);
1885
1886                 errno = 0;
1887                 if (!fgets(line, sizeof(line), stdin))
1888                         return errno ? -errno : -EIO;
1889
1890                 if (!endswith(line, "\n"))
1891                         putchar('\n');
1892                 else {
1893                         char *s;
1894
1895                         if (isempty(line))
1896                                 continue;
1897
1898                         truncate_nl(line);
1899                         s = strdup(line);
1900                         if (!s)
1901                                 return -ENOMEM;
1902
1903                         *ret = s;
1904                         return 0;
1905                 }
1906         }
1907 }
1908
1909 int reset_terminal_fd(int fd, bool switch_to_text) {
1910         struct termios termios;
1911         int r = 0;
1912
1913         /* Set terminal to some sane defaults */
1914
1915         assert(fd >= 0);
1916
1917         /* We leave locked terminal attributes untouched, so that
1918          * Plymouth may set whatever it wants to set, and we don't
1919          * interfere with that. */
1920
1921         /* Disable exclusive mode, just in case */
1922         ioctl(fd, TIOCNXCL);
1923
1924         /* Switch to text mode */
1925         if (switch_to_text)
1926                 ioctl(fd, KDSETMODE, KD_TEXT);
1927
1928         /* Enable console unicode mode */
1929         ioctl(fd, KDSKBMODE, K_UNICODE);
1930
1931         if (tcgetattr(fd, &termios) < 0) {
1932                 r = -errno;
1933                 goto finish;
1934         }
1935
1936         /* We only reset the stuff that matters to the software. How
1937          * hardware is set up we don't touch assuming that somebody
1938          * else will do that for us */
1939
1940         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1941         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1942         termios.c_oflag |= ONLCR;
1943         termios.c_cflag |= CREAD;
1944         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1945
1946         termios.c_cc[VINTR]    =   03;  /* ^C */
1947         termios.c_cc[VQUIT]    =  034;  /* ^\ */
1948         termios.c_cc[VERASE]   = 0177;
1949         termios.c_cc[VKILL]    =  025;  /* ^X */
1950         termios.c_cc[VEOF]     =   04;  /* ^D */
1951         termios.c_cc[VSTART]   =  021;  /* ^Q */
1952         termios.c_cc[VSTOP]    =  023;  /* ^S */
1953         termios.c_cc[VSUSP]    =  032;  /* ^Z */
1954         termios.c_cc[VLNEXT]   =  026;  /* ^V */
1955         termios.c_cc[VWERASE]  =  027;  /* ^W */
1956         termios.c_cc[VREPRINT] =  022;  /* ^R */
1957         termios.c_cc[VEOL]     =    0;
1958         termios.c_cc[VEOL2]    =    0;
1959
1960         termios.c_cc[VTIME]  = 0;
1961         termios.c_cc[VMIN]   = 1;
1962
1963         if (tcsetattr(fd, TCSANOW, &termios) < 0)
1964                 r = -errno;
1965
1966 finish:
1967         /* Just in case, flush all crap out */
1968         tcflush(fd, TCIOFLUSH);
1969
1970         return r;
1971 }
1972
1973 int reset_terminal(const char *name) {
1974         _cleanup_close_ int fd = -1;
1975
1976         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1977         if (fd < 0)
1978                 return fd;
1979
1980         return reset_terminal_fd(fd, true);
1981 }
1982
1983 int open_terminal(const char *name, int mode) {
1984         int fd, r;
1985         unsigned c = 0;
1986
1987         /*
1988          * If a TTY is in the process of being closed opening it might
1989          * cause EIO. This is horribly awful, but unlikely to be
1990          * changed in the kernel. Hence we work around this problem by
1991          * retrying a couple of times.
1992          *
1993          * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1994          */
1995
1996         assert(!(mode & O_CREAT));
1997
1998         for (;;) {
1999                 fd = open(name, mode, 0);
2000                 if (fd >= 0)
2001                         break;
2002
2003                 if (errno != EIO)
2004                         return -errno;
2005
2006                 /* Max 1s in total */
2007                 if (c >= 20)
2008                         return -errno;
2009
2010                 usleep(50 * USEC_PER_MSEC);
2011                 c++;
2012         }
2013
2014         r = isatty(fd);
2015         if (r < 0) {
2016                 safe_close(fd);
2017                 return -errno;
2018         }
2019
2020         if (!r) {
2021                 safe_close(fd);
2022                 return -ENOTTY;
2023         }
2024
2025         return fd;
2026 }
2027
2028 int flush_fd(int fd) {
2029         struct pollfd pollfd = {
2030                 .fd = fd,
2031                 .events = POLLIN,
2032         };
2033
2034         for (;;) {
2035                 char buf[LINE_MAX];
2036                 ssize_t l;
2037                 int r;
2038
2039                 r = poll(&pollfd, 1, 0);
2040                 if (r < 0) {
2041                         if (errno == EINTR)
2042                                 continue;
2043
2044                         return -errno;
2045
2046                 } else if (r == 0)
2047                         return 0;
2048
2049                 l = read(fd, buf, sizeof(buf));
2050                 if (l < 0) {
2051
2052                         if (errno == EINTR)
2053                                 continue;
2054
2055                         if (errno == EAGAIN)
2056                                 return 0;
2057
2058                         return -errno;
2059                 } else if (l == 0)
2060                         return 0;
2061         }
2062 }
2063
2064 int acquire_terminal(
2065                 const char *name,
2066                 bool fail,
2067                 bool force,
2068                 bool ignore_tiocstty_eperm,
2069                 usec_t timeout) {
2070
2071         int fd = -1, notify = -1, r = 0, wd = -1;
2072         usec_t ts = 0;
2073
2074         assert(name);
2075
2076         /* We use inotify to be notified when the tty is closed. We
2077          * create the watch before checking if we can actually acquire
2078          * it, so that we don't lose any event.
2079          *
2080          * Note: strictly speaking this actually watches for the
2081          * device being closed, it does *not* really watch whether a
2082          * tty loses its controlling process. However, unless some
2083          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2084          * its tty otherwise this will not become a problem. As long
2085          * as the administrator makes sure not configure any service
2086          * on the same tty as an untrusted user this should not be a
2087          * problem. (Which he probably should not do anyway.) */
2088
2089         if (timeout != USEC_INFINITY)
2090                 ts = now(CLOCK_MONOTONIC);
2091
2092         if (!fail && !force) {
2093                 notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
2094                 if (notify < 0) {
2095                         r = -errno;
2096                         goto fail;
2097                 }
2098
2099                 wd = inotify_add_watch(notify, name, IN_CLOSE);
2100                 if (wd < 0) {
2101                         r = -errno;
2102                         goto fail;
2103                 }
2104         }
2105
2106         for (;;) {
2107                 struct sigaction sa_old, sa_new = {
2108                         .sa_handler = SIG_IGN,
2109                         .sa_flags = SA_RESTART,
2110                 };
2111
2112                 if (notify >= 0) {
2113                         r = flush_fd(notify);
2114                         if (r < 0)
2115                                 goto fail;
2116                 }
2117
2118                 /* We pass here O_NOCTTY only so that we can check the return
2119                  * value TIOCSCTTY and have a reliable way to figure out if we
2120                  * successfully became the controlling process of the tty */
2121                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2122                 if (fd < 0)
2123                         return fd;
2124
2125                 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2126                  * if we already own the tty. */
2127                 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2128
2129                 /* First, try to get the tty */
2130                 if (ioctl(fd, TIOCSCTTY, force) < 0)
2131                         r = -errno;
2132
2133                 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2134
2135                 /* Sometimes it makes sense to ignore TIOCSCTTY
2136                  * returning EPERM, i.e. when very likely we already
2137                  * are have this controlling terminal. */
2138                 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2139                         r = 0;
2140
2141                 if (r < 0 && (force || fail || r != -EPERM)) {
2142                         goto fail;
2143                 }
2144
2145                 if (r >= 0)
2146                         break;
2147
2148                 assert(!fail);
2149                 assert(!force);
2150                 assert(notify >= 0);
2151
2152                 for (;;) {
2153                         uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2154                         ssize_t l;
2155                         struct inotify_event *e;
2156
2157                         if (timeout != USEC_INFINITY) {
2158                                 usec_t n;
2159
2160                                 n = now(CLOCK_MONOTONIC);
2161                                 if (ts + timeout < n) {
2162                                         r = -ETIMEDOUT;
2163                                         goto fail;
2164                                 }
2165
2166                                 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2167                                 if (r < 0)
2168                                         goto fail;
2169
2170                                 if (r == 0) {
2171                                         r = -ETIMEDOUT;
2172                                         goto fail;
2173                                 }
2174                         }
2175
2176                         l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2177                         if (l < 0) {
2178
2179                                 if (errno == EINTR || errno == EAGAIN)
2180                                         continue;
2181
2182                                 r = -errno;
2183                                 goto fail;
2184                         }
2185
2186                         e = (struct inotify_event*) inotify_buffer;
2187
2188                         while (l > 0) {
2189                                 size_t step;
2190
2191                                 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2192                                         r = -EIO;
2193                                         goto fail;
2194                                 }
2195
2196                                 step = sizeof(struct inotify_event) + e->len;
2197                                 assert(step <= (size_t) l);
2198
2199                                 e = (struct inotify_event*) ((uint8_t*) e + step);
2200                                 l -= step;
2201                         }
2202
2203                         break;
2204                 }
2205
2206                 /* We close the tty fd here since if the old session
2207                  * ended our handle will be dead. It's important that
2208                  * we do this after sleeping, so that we don't enter
2209                  * an endless loop. */
2210                 fd = safe_close(fd);
2211         }
2212
2213         safe_close(notify);
2214
2215         r = reset_terminal_fd(fd, true);
2216         if (r < 0)
2217                 log_warning_errno(r, "Failed to reset terminal: %m");
2218
2219         return fd;
2220
2221 fail:
2222         safe_close(fd);
2223         safe_close(notify);
2224
2225         return r;
2226 }
2227
2228 int release_terminal(void) {
2229         static const struct sigaction sa_new = {
2230                 .sa_handler = SIG_IGN,
2231                 .sa_flags = SA_RESTART,
2232         };
2233
2234         _cleanup_close_ int fd = -1;
2235         struct sigaction sa_old;
2236         int r = 0;
2237
2238         fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2239         if (fd < 0)
2240                 return -errno;
2241
2242         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2243          * by our own TIOCNOTTY */
2244         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2245
2246         if (ioctl(fd, TIOCNOTTY) < 0)
2247                 r = -errno;
2248
2249         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2250
2251         return r;
2252 }
2253
2254 int sigaction_many(const struct sigaction *sa, ...) {
2255         va_list ap;
2256         int r = 0, sig;
2257
2258         va_start(ap, sa);
2259         while ((sig = va_arg(ap, int)) > 0)
2260                 if (sigaction(sig, sa, NULL) < 0)
2261                         r = -errno;
2262         va_end(ap);
2263
2264         return r;
2265 }
2266
2267 int ignore_signals(int sig, ...) {
2268         struct sigaction sa = {
2269                 .sa_handler = SIG_IGN,
2270                 .sa_flags = SA_RESTART,
2271         };
2272         va_list ap;
2273         int r = 0;
2274
2275         if (sigaction(sig, &sa, NULL) < 0)
2276                 r = -errno;
2277
2278         va_start(ap, sig);
2279         while ((sig = va_arg(ap, int)) > 0)
2280                 if (sigaction(sig, &sa, NULL) < 0)
2281                         r = -errno;
2282         va_end(ap);
2283
2284         return r;
2285 }
2286
2287 int default_signals(int sig, ...) {
2288         struct sigaction sa = {
2289                 .sa_handler = SIG_DFL,
2290                 .sa_flags = SA_RESTART,
2291         };
2292         va_list ap;
2293         int r = 0;
2294
2295         if (sigaction(sig, &sa, NULL) < 0)
2296                 r = -errno;
2297
2298         va_start(ap, sig);
2299         while ((sig = va_arg(ap, int)) > 0)
2300                 if (sigaction(sig, &sa, NULL) < 0)
2301                         r = -errno;
2302         va_end(ap);
2303
2304         return r;
2305 }
2306
2307 void safe_close_pair(int p[]) {
2308         assert(p);
2309
2310         if (p[0] == p[1]) {
2311                 /* Special case pairs which use the same fd in both
2312                  * directions... */
2313                 p[0] = p[1] = safe_close(p[0]);
2314                 return;
2315         }
2316
2317         p[0] = safe_close(p[0]);
2318         p[1] = safe_close(p[1]);
2319 }
2320
2321 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2322         uint8_t *p = buf;
2323         ssize_t n = 0;
2324
2325         assert(fd >= 0);
2326         assert(buf);
2327
2328         while (nbytes > 0) {
2329                 ssize_t k;
2330
2331                 k = read(fd, p, nbytes);
2332                 if (k < 0 && errno == EINTR)
2333                         continue;
2334
2335                 if (k < 0 && errno == EAGAIN && do_poll) {
2336
2337                         /* We knowingly ignore any return value here,
2338                          * and expect that any error/EOF is reported
2339                          * via read() */
2340
2341                         fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
2342                         continue;
2343                 }
2344
2345                 if (k <= 0)
2346                         return n > 0 ? n : (k < 0 ? -errno : 0);
2347
2348                 p += k;
2349                 nbytes -= k;
2350                 n += k;
2351         }
2352
2353         return n;
2354 }
2355
2356 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2357         const uint8_t *p = buf;
2358         ssize_t n = 0;
2359
2360         assert(fd >= 0);
2361         assert(buf);
2362
2363         while (nbytes > 0) {
2364                 ssize_t k;
2365
2366                 k = write(fd, p, nbytes);
2367                 if (k < 0 && errno == EINTR)
2368                         continue;
2369
2370                 if (k < 0 && errno == EAGAIN && do_poll) {
2371
2372                         /* We knowingly ignore any return value here,
2373                          * and expect that any error/EOF is reported
2374                          * via write() */
2375
2376                         fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
2377                         continue;
2378                 }
2379
2380                 if (k <= 0)
2381                         return n > 0 ? n : (k < 0 ? -errno : 0);
2382
2383                 p += k;
2384                 nbytes -= k;
2385                 n += k;
2386         }
2387
2388         return n;
2389 }
2390
2391 int parse_size(const char *t, off_t base, off_t *size) {
2392
2393         /* Soo, sometimes we want to parse IEC binary suffxies, and
2394          * sometimes SI decimal suffixes. This function can parse
2395          * both. Which one is the right way depends on the
2396          * context. Wikipedia suggests that SI is customary for
2397          * hardrware metrics and network speeds, while IEC is
2398          * customary for most data sizes used by software and volatile
2399          * (RAM) memory. Hence be careful which one you pick!
2400          *
2401          * In either case we use just K, M, G as suffix, and not Ki,
2402          * Mi, Gi or so (as IEC would suggest). That's because that's
2403          * frickin' ugly. But this means you really need to make sure
2404          * to document which base you are parsing when you use this
2405          * call. */
2406
2407         struct table {
2408                 const char *suffix;
2409                 unsigned long long factor;
2410         };
2411
2412         static const struct table iec[] = {
2413                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2414                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2415                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2416                 { "G", 1024ULL*1024ULL*1024ULL },
2417                 { "M", 1024ULL*1024ULL },
2418                 { "K", 1024ULL },
2419                 { "B", 1 },
2420                 { "", 1 },
2421         };
2422
2423         static const struct table si[] = {
2424                 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2425                 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2426                 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2427                 { "G", 1000ULL*1000ULL*1000ULL },
2428                 { "M", 1000ULL*1000ULL },
2429                 { "K", 1000ULL },
2430                 { "B", 1 },
2431                 { "", 1 },
2432         };
2433
2434         const struct table *table;
2435         const char *p;
2436         unsigned long long r = 0;
2437         unsigned n_entries, start_pos = 0;
2438
2439         assert(t);
2440         assert(base == 1000 || base == 1024);
2441         assert(size);
2442
2443         if (base == 1000) {
2444                 table = si;
2445                 n_entries = ELEMENTSOF(si);
2446         } else {
2447                 table = iec;
2448                 n_entries = ELEMENTSOF(iec);
2449         }
2450
2451         p = t;
2452         do {
2453                 long long l;
2454                 unsigned long long l2;
2455                 double frac = 0;
2456                 char *e;
2457                 unsigned i;
2458
2459                 errno = 0;
2460                 l = strtoll(p, &e, 10);
2461
2462                 if (errno > 0)
2463                         return -errno;
2464
2465                 if (l < 0)
2466                         return -ERANGE;
2467
2468                 if (e == p)
2469                         return -EINVAL;
2470
2471                 if (*e == '.') {
2472                         e++;
2473                         if (*e >= '0' && *e <= '9') {
2474                                 char *e2;
2475
2476                                 /* strotoull itself would accept space/+/- */
2477                                 l2 = strtoull(e, &e2, 10);
2478
2479                                 if (errno == ERANGE)
2480                                         return -errno;
2481
2482                                 /* Ignore failure. E.g. 10.M is valid */
2483                                 frac = l2;
2484                                 for (; e < e2; e++)
2485                                         frac /= 10;
2486                         }
2487                 }
2488
2489                 e += strspn(e, WHITESPACE);
2490
2491                 for (i = start_pos; i < n_entries; i++)
2492                         if (startswith(e, table[i].suffix)) {
2493                                 unsigned long long tmp;
2494                                 if ((unsigned long long) l + (frac > 0) > ULLONG_MAX / table[i].factor)
2495                                         return -ERANGE;
2496                                 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
2497                                 if (tmp > ULLONG_MAX - r)
2498                                         return -ERANGE;
2499
2500                                 r += tmp;
2501                                 if ((unsigned long long) (off_t) r != r)
2502                                         return -ERANGE;
2503
2504                                 p = e + strlen(table[i].suffix);
2505
2506                                 start_pos = i + 1;
2507                                 break;
2508                         }
2509
2510                 if (i >= n_entries)
2511                         return -EINVAL;
2512
2513         } while (*p);
2514
2515         *size = r;
2516
2517         return 0;
2518 }
2519
2520 int make_stdio(int fd) {
2521         int r, s, t;
2522
2523         assert(fd >= 0);
2524
2525         r = dup3(fd, STDIN_FILENO, 0);
2526         s = dup3(fd, STDOUT_FILENO, 0);
2527         t = dup3(fd, STDERR_FILENO, 0);
2528
2529         if (fd >= 3)
2530                 safe_close(fd);
2531
2532         if (r < 0 || s < 0 || t < 0)
2533                 return -errno;
2534
2535         /* We rely here that the new fd has O_CLOEXEC not set */
2536
2537         return 0;
2538 }
2539
2540 int make_null_stdio(void) {
2541         int null_fd;
2542
2543         null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2544         if (null_fd < 0)
2545                 return -errno;
2546
2547         return make_stdio(null_fd);
2548 }
2549
2550 bool is_device_path(const char *path) {
2551
2552         /* Returns true on paths that refer to a device, either in
2553          * sysfs or in /dev */
2554
2555         return
2556                 path_startswith(path, "/dev/") ||
2557                 path_startswith(path, "/sys/");
2558 }
2559
2560 int dir_is_empty(const char *path) {
2561         _cleanup_closedir_ DIR *d;
2562
2563         d = opendir(path);
2564         if (!d)
2565                 return -errno;
2566
2567         for (;;) {
2568                 struct dirent *de;
2569
2570                 errno = 0;
2571                 de = readdir(d);
2572                 if (!de && errno != 0)
2573                         return -errno;
2574
2575                 if (!de)
2576                         return 1;
2577
2578                 if (!ignore_file(de->d_name))
2579                         return 0;
2580         }
2581 }
2582
2583 char* dirname_malloc(const char *path) {
2584         char *d, *dir, *dir2;
2585
2586         d = strdup(path);
2587         if (!d)
2588                 return NULL;
2589         dir = dirname(d);
2590         assert(dir);
2591
2592         if (dir != d) {
2593                 dir2 = strdup(dir);
2594                 free(d);
2595                 return dir2;
2596         }
2597
2598         return dir;
2599 }
2600
2601 int dev_urandom(void *p, size_t n) {
2602         static int have_syscall = -1;
2603         int r, fd;
2604         ssize_t k;
2605
2606         /* Gathers some randomness from the kernel. This call will
2607          * never block, and will always return some data from the
2608          * kernel, regardless if the random pool is fully initialized
2609          * or not. It thus makes no guarantee for the quality of the
2610          * returned entropy, but is good enough for or usual usecases
2611          * of seeding the hash functions for hashtable */
2612
2613         /* Use the getrandom() syscall unless we know we don't have
2614          * it, or when the requested size is too large for it. */
2615         if (have_syscall != 0 || (size_t) (int) n != n) {
2616                 r = getrandom(p, n, GRND_NONBLOCK);
2617                 if (r == (int) n) {
2618                         have_syscall = true;
2619                         return 0;
2620                 }
2621
2622                 if (r < 0) {
2623                         if (errno == ENOSYS)
2624                                 /* we lack the syscall, continue with
2625                                  * reading from /dev/urandom */
2626                                 have_syscall = false;
2627                         else if (errno == EAGAIN)
2628                                 /* not enough entropy for now. Let's
2629                                  * remember to use the syscall the
2630                                  * next time, again, but also read
2631                                  * from /dev/urandom for now, which
2632                                  * doesn't care about the current
2633                                  * amount of entropy.  */
2634                                 have_syscall = true;
2635                         else
2636                                 return -errno;
2637                 } else
2638                         /* too short read? */
2639                         return -EIO;
2640         }
2641
2642         fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2643         if (fd < 0)
2644                 return errno == ENOENT ? -ENOSYS : -errno;
2645
2646         k = loop_read(fd, p, n, true);
2647         safe_close(fd);
2648
2649         if (k < 0)
2650                 return (int) k;
2651         if ((size_t) k != n)
2652                 return -EIO;
2653
2654         return 0;
2655 }
2656
2657 void initialize_srand(void) {
2658         static bool srand_called = false;
2659         unsigned x;
2660 #ifdef HAVE_SYS_AUXV_H
2661         void *auxv;
2662 #endif
2663
2664         if (srand_called)
2665                 return;
2666
2667         x = 0;
2668
2669 #ifdef HAVE_SYS_AUXV_H
2670         /* The kernel provides us with a bit of entropy in auxv, so
2671          * let's try to make use of that to seed the pseudo-random
2672          * generator. It's better than nothing... */
2673
2674         auxv = (void*) getauxval(AT_RANDOM);
2675         if (auxv)
2676                 x ^= *(unsigned*) auxv;
2677 #endif
2678
2679         x ^= (unsigned) now(CLOCK_REALTIME);
2680         x ^= (unsigned) gettid();
2681
2682         srand(x);
2683         srand_called = true;
2684 }
2685
2686 void random_bytes(void *p, size_t n) {
2687         uint8_t *q;
2688         int r;
2689
2690         r = dev_urandom(p, n);
2691         if (r >= 0)
2692                 return;
2693
2694         /* If some idiot made /dev/urandom unavailable to us, he'll
2695          * get a PRNG instead. */
2696
2697         initialize_srand();
2698
2699         for (q = p; q < (uint8_t*) p + n; q ++)
2700                 *q = rand();
2701 }
2702
2703 void rename_process(const char name[8]) {
2704         assert(name);
2705
2706         /* This is a like a poor man's setproctitle(). It changes the
2707          * comm field, argv[0], and also the glibc's internally used
2708          * name of the process. For the first one a limit of 16 chars
2709          * applies, to the second one usually one of 10 (i.e. length
2710          * of "/sbin/init"), to the third one one of 7 (i.e. length of
2711          * "systemd"). If you pass a longer string it will be
2712          * truncated */
2713
2714         prctl(PR_SET_NAME, name);
2715
2716         if (program_invocation_name)
2717                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2718
2719         if (saved_argc > 0) {
2720                 int i;
2721
2722                 if (saved_argv[0])
2723                         strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2724
2725                 for (i = 1; i < saved_argc; i++) {
2726                         if (!saved_argv[i])
2727                                 break;
2728
2729                         memzero(saved_argv[i], strlen(saved_argv[i]));
2730                 }
2731         }
2732 }
2733
2734 void sigset_add_many(sigset_t *ss, ...) {
2735         va_list ap;
2736         int sig;
2737
2738         assert(ss);
2739
2740         va_start(ap, ss);
2741         while ((sig = va_arg(ap, int)) > 0)
2742                 assert_se(sigaddset(ss, sig) == 0);
2743         va_end(ap);
2744 }
2745
2746 int sigprocmask_many(int how, ...) {
2747         va_list ap;
2748         sigset_t ss;
2749         int sig;
2750
2751         assert_se(sigemptyset(&ss) == 0);
2752
2753         va_start(ap, how);
2754         while ((sig = va_arg(ap, int)) > 0)
2755                 assert_se(sigaddset(&ss, sig) == 0);
2756         va_end(ap);
2757
2758         if (sigprocmask(how, &ss, NULL) < 0)
2759                 return -errno;
2760
2761         return 0;
2762 }
2763
2764 char* gethostname_malloc(void) {
2765         struct utsname u;
2766
2767         assert_se(uname(&u) >= 0);
2768
2769         if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2770                 return strdup(u.nodename);
2771
2772         return strdup(u.sysname);
2773 }
2774
2775 bool hostname_is_set(void) {
2776         struct utsname u;
2777
2778         assert_se(uname(&u) >= 0);
2779
2780         return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2781 }
2782
2783 char *lookup_uid(uid_t uid) {
2784         long bufsize;
2785         char *name;
2786         _cleanup_free_ char *buf = NULL;
2787         struct passwd pwbuf, *pw = NULL;
2788
2789         /* Shortcut things to avoid NSS lookups */
2790         if (uid == 0)
2791                 return strdup("root");
2792
2793         bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2794         if (bufsize <= 0)
2795                 bufsize = 4096;
2796
2797         buf = malloc(bufsize);
2798         if (!buf)
2799                 return NULL;
2800
2801         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2802                 return strdup(pw->pw_name);
2803
2804         if (asprintf(&name, UID_FMT, uid) < 0)
2805                 return NULL;
2806
2807         return name;
2808 }
2809
2810 char* getlogname_malloc(void) {
2811         uid_t uid;
2812         struct stat st;
2813
2814         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2815                 uid = st.st_uid;
2816         else
2817                 uid = getuid();
2818
2819         return lookup_uid(uid);
2820 }
2821
2822 char *getusername_malloc(void) {
2823         const char *e;
2824
2825         e = getenv("USER");
2826         if (e)
2827                 return strdup(e);
2828
2829         return lookup_uid(getuid());
2830 }
2831
2832 int getttyname_malloc(int fd, char **r) {
2833         char path[PATH_MAX], *c;
2834         int k;
2835
2836         assert(r);
2837
2838         k = ttyname_r(fd, path, sizeof(path));
2839         if (k > 0)
2840                 return -k;
2841
2842         char_array_0(path);
2843
2844         c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2845         if (!c)
2846                 return -ENOMEM;
2847
2848         *r = c;
2849         return 0;
2850 }
2851
2852 int getttyname_harder(int fd, char **r) {
2853         int k;
2854         char *s;
2855
2856         k = getttyname_malloc(fd, &s);
2857         if (k < 0)
2858                 return k;
2859
2860         if (streq(s, "tty")) {
2861                 free(s);
2862                 return get_ctty(0, NULL, r);
2863         }
2864
2865         *r = s;
2866         return 0;
2867 }
2868
2869 int get_ctty_devnr(pid_t pid, dev_t *d) {
2870         int r;
2871         _cleanup_free_ char *line = NULL;
2872         const char *p;
2873         unsigned long ttynr;
2874
2875         assert(pid >= 0);
2876
2877         p = procfs_file_alloca(pid, "stat");
2878         r = read_one_line_file(p, &line);
2879         if (r < 0)
2880                 return r;
2881
2882         p = strrchr(line, ')');
2883         if (!p)
2884                 return -EIO;
2885
2886         p++;
2887
2888         if (sscanf(p, " "
2889                    "%*c "  /* state */
2890                    "%*d "  /* ppid */
2891                    "%*d "  /* pgrp */
2892                    "%*d "  /* session */
2893                    "%lu ", /* ttynr */
2894                    &ttynr) != 1)
2895                 return -EIO;
2896
2897         if (major(ttynr) == 0 && minor(ttynr) == 0)
2898                 return -ENOENT;
2899
2900         if (d)
2901                 *d = (dev_t) ttynr;
2902
2903         return 0;
2904 }
2905
2906 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2907         char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *b = NULL;
2908         _cleanup_free_ char *s = NULL;
2909         const char *p;
2910         dev_t devnr;
2911         int k;
2912
2913         assert(r);
2914
2915         k = get_ctty_devnr(pid, &devnr);
2916         if (k < 0)
2917                 return k;
2918
2919         sprintf(fn, "/dev/char/%u:%u", major(devnr), minor(devnr));
2920
2921         k = readlink_malloc(fn, &s);
2922         if (k < 0) {
2923
2924                 if (k != -ENOENT)
2925                         return k;
2926
2927                 /* This is an ugly hack */
2928                 if (major(devnr) == 136) {
2929                         asprintf(&b, "pts/%u", minor(devnr));
2930                         goto finish;
2931                 }
2932
2933                 /* Probably something like the ptys which have no
2934                  * symlink in /dev/char. Let's return something
2935                  * vaguely useful. */
2936
2937                 b = strdup(fn + 5);
2938                 goto finish;
2939         }
2940
2941         if (startswith(s, "/dev/"))
2942                 p = s + 5;
2943         else if (startswith(s, "../"))
2944                 p = s + 3;
2945         else
2946                 p = s;
2947
2948         b = strdup(p);
2949
2950 finish:
2951         if (!b)
2952                 return -ENOMEM;
2953
2954         *r = b;
2955         if (_devnr)
2956                 *_devnr = devnr;
2957
2958         return 0;
2959 }
2960
2961 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2962         _cleanup_closedir_ DIR *d = NULL;
2963         int ret = 0;
2964
2965         assert(fd >= 0);
2966
2967         /* This returns the first error we run into, but nevertheless
2968          * tries to go on. This closes the passed fd. */
2969
2970         d = fdopendir(fd);
2971         if (!d) {
2972                 safe_close(fd);
2973
2974                 return errno == ENOENT ? 0 : -errno;
2975         }
2976
2977         for (;;) {
2978                 struct dirent *de;
2979                 bool is_dir, keep_around;
2980                 struct stat st;
2981                 int r;
2982
2983                 errno = 0;
2984                 de = readdir(d);
2985                 if (!de) {
2986                         if (errno != 0 && ret == 0)
2987                                 ret = -errno;
2988                         return ret;
2989                 }
2990
2991                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2992                         continue;
2993
2994                 if (de->d_type == DT_UNKNOWN ||
2995                     honour_sticky ||
2996                     (de->d_type == DT_DIR && root_dev)) {
2997                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2998                                 if (ret == 0 && errno != ENOENT)
2999                                         ret = -errno;
3000                                 continue;
3001                         }
3002
3003                         is_dir = S_ISDIR(st.st_mode);
3004                         keep_around =
3005                                 honour_sticky &&
3006                                 (st.st_uid == 0 || st.st_uid == getuid()) &&
3007                                 (st.st_mode & S_ISVTX);
3008                 } else {
3009                         is_dir = de->d_type == DT_DIR;
3010                         keep_around = false;
3011                 }
3012
3013                 if (is_dir) {
3014                         int subdir_fd;
3015
3016                         /* if root_dev is set, remove subdirectories only, if device is same as dir */
3017                         if (root_dev && st.st_dev != root_dev->st_dev)
3018                                 continue;
3019
3020                         subdir_fd = openat(fd, de->d_name,
3021                                            O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3022                         if (subdir_fd < 0) {
3023                                 if (ret == 0 && errno != ENOENT)
3024                                         ret = -errno;
3025                                 continue;
3026                         }
3027
3028                         r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3029                         if (r < 0 && ret == 0)
3030                                 ret = r;
3031
3032                         if (!keep_around)
3033                                 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3034                                         if (ret == 0 && errno != ENOENT)
3035                                                 ret = -errno;
3036                                 }
3037
3038                 } else if (!only_dirs && !keep_around) {
3039
3040                         if (unlinkat(fd, de->d_name, 0) < 0) {
3041                                 if (ret == 0 && errno != ENOENT)
3042                                         ret = -errno;
3043                         }
3044                 }
3045         }
3046 }
3047
3048 _pure_ static int is_temporary_fs(struct statfs *s) {
3049         assert(s);
3050
3051         return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
3052                F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
3053 }
3054
3055 int is_fd_on_temporary_fs(int fd) {
3056         struct statfs s;
3057
3058         if (fstatfs(fd, &s) < 0)
3059                 return -errno;
3060
3061         return is_temporary_fs(&s);
3062 }
3063
3064 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3065         struct statfs s;
3066
3067         assert(fd >= 0);
3068
3069         if (fstatfs(fd, &s) < 0) {
3070                 safe_close(fd);
3071                 return -errno;
3072         }
3073
3074         /* We refuse to clean disk file systems with this call. This
3075          * is extra paranoia just to be sure we never ever remove
3076          * non-state data */
3077         if (!is_temporary_fs(&s)) {
3078                 log_error("Attempted to remove disk file system, and we can't allow that.");
3079                 safe_close(fd);
3080                 return -EPERM;
3081         }
3082
3083         return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3084 }
3085
3086 static int file_is_priv_sticky(const char *p) {
3087         struct stat st;
3088
3089         assert(p);
3090
3091         if (lstat(p, &st) < 0)
3092                 return -errno;
3093
3094         return
3095                 (st.st_uid == 0 || st.st_uid == getuid()) &&
3096                 (st.st_mode & S_ISVTX);
3097 }
3098
3099 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3100         int fd, r;
3101         struct statfs s;
3102
3103         assert(path);
3104
3105         /* We refuse to clean the root file system with this
3106          * call. This is extra paranoia to never cause a really
3107          * seriously broken system. */
3108         if (path_equal(path, "/")) {
3109                 log_error("Attempted to remove entire root file system, and we can't allow that.");
3110                 return -EPERM;
3111         }
3112
3113         fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3114         if (fd < 0) {
3115
3116                 if (errno != ENOTDIR)
3117                         return -errno;
3118
3119                 if (!dangerous) {
3120                         if (statfs(path, &s) < 0)
3121                                 return -errno;
3122
3123                         if (!is_temporary_fs(&s)) {
3124                                 log_error("Attempted to remove disk file system, and we can't allow that.");
3125                                 return -EPERM;
3126                         }
3127                 }
3128
3129                 if (delete_root && !only_dirs)
3130                         if (unlink(path) < 0 && errno != ENOENT)
3131                                 return -errno;
3132
3133                 return 0;
3134         }
3135
3136         if (!dangerous) {
3137                 if (fstatfs(fd, &s) < 0) {
3138                         safe_close(fd);
3139                         return -errno;
3140                 }
3141
3142                 if (!is_temporary_fs(&s)) {
3143                         log_error("Attempted to remove disk file system, and we can't allow that.");
3144                         safe_close(fd);
3145                         return -EPERM;
3146                 }
3147         }
3148
3149         r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3150         if (delete_root) {
3151
3152                 if (honour_sticky && file_is_priv_sticky(path) > 0)
3153                         return r;
3154
3155                 if (rmdir(path) < 0 && errno != ENOENT) {
3156                         if (r == 0)
3157                                 r = -errno;
3158                 }
3159         }
3160
3161         return r;
3162 }
3163
3164 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3165         return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3166 }
3167
3168 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3169         return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3170 }
3171
3172 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3173         assert(path);
3174
3175         /* Under the assumption that we are running privileged we
3176          * first change the access mode and only then hand out
3177          * ownership to avoid a window where access is too open. */
3178
3179         if (mode != MODE_INVALID)
3180                 if (chmod(path, mode) < 0)
3181                         return -errno;
3182
3183         if (uid != UID_INVALID || gid != GID_INVALID)
3184                 if (chown(path, uid, gid) < 0)
3185                         return -errno;
3186
3187         return 0;
3188 }
3189
3190 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3191         assert(fd >= 0);
3192
3193         /* Under the assumption that we are running privileged we
3194          * first change the access mode and only then hand out
3195          * ownership to avoid a window where access is too open. */
3196
3197         if (mode != MODE_INVALID)
3198                 if (fchmod(fd, mode) < 0)
3199                         return -errno;
3200
3201         if (uid != UID_INVALID || gid != GID_INVALID)
3202                 if (fchown(fd, uid, gid) < 0)
3203                         return -errno;
3204
3205         return 0;
3206 }
3207
3208 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3209         cpu_set_t *r;
3210         unsigned n = 1024;
3211
3212         /* Allocates the cpuset in the right size */
3213
3214         for (;;) {
3215                 if (!(r = CPU_ALLOC(n)))
3216                         return NULL;
3217
3218                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3219                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3220
3221                         if (ncpus)
3222                                 *ncpus = n;
3223
3224                         return r;
3225                 }
3226
3227                 CPU_FREE(r);
3228
3229                 if (errno != EINVAL)
3230                         return NULL;
3231
3232                 n *= 2;
3233         }
3234 }
3235
3236 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
3237         static const char status_indent[] = "         "; /* "[" STATUS "] " */
3238         _cleanup_free_ char *s = NULL;
3239         _cleanup_close_ int fd = -1;
3240         struct iovec iovec[6] = {};
3241         int n = 0;
3242         static bool prev_ephemeral;
3243
3244         assert(format);
3245
3246         /* This is independent of logging, as status messages are
3247          * optional and go exclusively to the console. */
3248
3249         if (vasprintf(&s, format, ap) < 0)
3250                 return log_oom();
3251
3252         fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3253         if (fd < 0)
3254                 return fd;
3255
3256         if (ellipse) {
3257                 char *e;
3258                 size_t emax, sl;
3259                 int c;
3260
3261                 c = fd_columns(fd);
3262                 if (c <= 0)
3263                         c = 80;
3264
3265                 sl = status ? sizeof(status_indent)-1 : 0;
3266
3267                 emax = c - sl - 1;
3268                 if (emax < 3)
3269                         emax = 3;
3270
3271                 e = ellipsize(s, emax, 50);
3272                 if (e) {
3273                         free(s);
3274                         s = e;
3275                 }
3276         }
3277
3278         if (prev_ephemeral)
3279                 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
3280         prev_ephemeral = ephemeral;
3281
3282         if (status) {
3283                 if (!isempty(status)) {
3284                         IOVEC_SET_STRING(iovec[n++], "[");
3285                         IOVEC_SET_STRING(iovec[n++], status);
3286                         IOVEC_SET_STRING(iovec[n++], "] ");
3287                 } else
3288                         IOVEC_SET_STRING(iovec[n++], status_indent);
3289         }
3290
3291         IOVEC_SET_STRING(iovec[n++], s);
3292         if (!ephemeral)
3293                 IOVEC_SET_STRING(iovec[n++], "\n");
3294
3295         if (writev(fd, iovec, n) < 0)
3296                 return -errno;
3297
3298         return 0;
3299 }
3300
3301 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
3302         va_list ap;
3303         int r;
3304
3305         assert(format);
3306
3307         va_start(ap, format);
3308         r = status_vprintf(status, ellipse, ephemeral, format, ap);
3309         va_end(ap);
3310
3311         return r;
3312 }
3313
3314 char *replace_env(const char *format, char **env) {
3315         enum {
3316                 WORD,
3317                 CURLY,
3318                 VARIABLE
3319         } state = WORD;
3320
3321         const char *e, *word = format;
3322         char *r = NULL, *k;
3323
3324         assert(format);
3325
3326         for (e = format; *e; e ++) {
3327
3328                 switch (state) {
3329
3330                 case WORD:
3331                         if (*e == '$')
3332                                 state = CURLY;
3333                         break;
3334
3335                 case CURLY:
3336                         if (*e == '{') {
3337                                 k = strnappend(r, word, e-word-1);
3338                                 if (!k)
3339                                         goto fail;
3340
3341                                 free(r);
3342                                 r = k;
3343
3344                                 word = e-1;
3345                                 state = VARIABLE;
3346
3347                         } else if (*e == '$') {
3348                                 k = strnappend(r, word, e-word);
3349                                 if (!k)
3350                                         goto fail;
3351
3352                                 free(r);
3353                                 r = k;
3354
3355                                 word = e+1;
3356                                 state = WORD;
3357                         } else
3358                                 state = WORD;
3359                         break;
3360
3361                 case VARIABLE:
3362                         if (*e == '}') {
3363                                 const char *t;
3364
3365                                 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3366
3367                                 k = strappend(r, t);
3368                                 if (!k)
3369                                         goto fail;
3370
3371                                 free(r);
3372                                 r = k;
3373
3374                                 word = e+1;
3375                                 state = WORD;
3376                         }
3377                         break;
3378                 }
3379         }
3380
3381         k = strnappend(r, word, e-word);
3382         if (!k)
3383                 goto fail;
3384
3385         free(r);
3386         return k;
3387
3388 fail:
3389         free(r);
3390         return NULL;
3391 }
3392
3393 char **replace_env_argv(char **argv, char **env) {
3394         char **ret, **i;
3395         unsigned k = 0, l = 0;
3396
3397         l = strv_length(argv);
3398
3399         ret = new(char*, l+1);
3400         if (!ret)
3401                 return NULL;
3402
3403         STRV_FOREACH(i, argv) {
3404
3405                 /* If $FOO appears as single word, replace it by the split up variable */
3406                 if ((*i)[0] == '$' && (*i)[1] != '{') {
3407                         char *e;
3408                         char **w, **m;
3409                         unsigned q;
3410
3411                         e = strv_env_get(env, *i+1);
3412                         if (e) {
3413                                 int r;
3414
3415                                 r = strv_split_quoted(&m, e, true);
3416                                 if (r < 0) {
3417                                         ret[k] = NULL;
3418                                         strv_free(ret);
3419                                         return NULL;
3420                                 }
3421                         } else
3422                                 m = NULL;
3423
3424                         q = strv_length(m);
3425                         l = l + q - 1;
3426
3427                         w = realloc(ret, sizeof(char*) * (l+1));
3428                         if (!w) {
3429                                 ret[k] = NULL;
3430                                 strv_free(ret);
3431                                 strv_free(m);
3432                                 return NULL;
3433                         }
3434
3435                         ret = w;
3436                         if (m) {
3437                                 memcpy(ret + k, m, q * sizeof(char*));
3438                                 free(m);
3439                         }
3440
3441                         k += q;
3442                         continue;
3443                 }
3444
3445                 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3446                 ret[k] = replace_env(*i, env);
3447                 if (!ret[k]) {
3448                         strv_free(ret);
3449                         return NULL;
3450                 }
3451                 k++;
3452         }
3453
3454         ret[k] = NULL;
3455         return ret;
3456 }
3457
3458 int fd_columns(int fd) {
3459         struct winsize ws = {};
3460
3461         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3462                 return -errno;
3463
3464         if (ws.ws_col <= 0)
3465                 return -EIO;
3466
3467         return ws.ws_col;
3468 }
3469
3470 unsigned columns(void) {
3471         const char *e;
3472         int c;
3473
3474         if (_likely_(cached_columns > 0))
3475                 return cached_columns;
3476
3477         c = 0;
3478         e = getenv("COLUMNS");
3479         if (e)
3480                 (void) safe_atoi(e, &c);
3481
3482         if (c <= 0)
3483                 c = fd_columns(STDOUT_FILENO);
3484
3485         if (c <= 0)
3486                 c = 80;
3487
3488         cached_columns = c;
3489         return c;
3490 }
3491
3492 int fd_lines(int fd) {
3493         struct winsize ws = {};
3494
3495         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3496                 return -errno;
3497
3498         if (ws.ws_row <= 0)
3499                 return -EIO;
3500
3501         return ws.ws_row;
3502 }
3503
3504 unsigned lines(void) {
3505         const char *e;
3506         unsigned l;
3507
3508         if (_likely_(cached_lines > 0))
3509                 return cached_lines;
3510
3511         l = 0;
3512         e = getenv("LINES");
3513         if (e)
3514                 (void) safe_atou(e, &l);
3515
3516         if (l <= 0)
3517                 l = fd_lines(STDOUT_FILENO);
3518
3519         if (l <= 0)
3520                 l = 24;
3521
3522         cached_lines = l;
3523         return cached_lines;
3524 }
3525
3526 /* intended to be used as a SIGWINCH sighandler */
3527 void columns_lines_cache_reset(int signum) {
3528         cached_columns = 0;
3529         cached_lines = 0;
3530 }
3531
3532 bool on_tty(void) {
3533         static int cached_on_tty = -1;
3534
3535         if (_unlikely_(cached_on_tty < 0))
3536                 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3537
3538         return cached_on_tty;
3539 }
3540
3541 int files_same(const char *filea, const char *fileb) {
3542         struct stat a, b;
3543
3544         if (stat(filea, &a) < 0)
3545                 return -errno;
3546
3547         if (stat(fileb, &b) < 0)
3548                 return -errno;
3549
3550         return a.st_dev == b.st_dev &&
3551                a.st_ino == b.st_ino;
3552 }
3553
3554 int running_in_chroot(void) {
3555         int ret;
3556
3557         ret = files_same("/proc/1/root", "/");
3558         if (ret < 0)
3559                 return ret;
3560
3561         return ret == 0;
3562 }
3563
3564 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3565         size_t x;
3566         char *r;
3567
3568         assert(s);
3569         assert(percent <= 100);
3570         assert(new_length >= 3);
3571
3572         if (old_length <= 3 || old_length <= new_length)
3573                 return strndup(s, old_length);
3574
3575         r = new0(char, new_length+1);
3576         if (!r)
3577                 return NULL;
3578
3579         x = (new_length * percent) / 100;
3580
3581         if (x > new_length - 3)
3582                 x = new_length - 3;
3583
3584         memcpy(r, s, x);
3585         r[x] = '.';
3586         r[x+1] = '.';
3587         r[x+2] = '.';
3588         memcpy(r + x + 3,
3589                s + old_length - (new_length - x - 3),
3590                new_length - x - 3);
3591
3592         return r;
3593 }
3594
3595 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3596         size_t x;
3597         char *e;
3598         const char *i, *j;
3599         unsigned k, len, len2;
3600
3601         assert(s);
3602         assert(percent <= 100);
3603         assert(new_length >= 3);
3604
3605         /* if no multibyte characters use ascii_ellipsize_mem for speed */
3606         if (ascii_is_valid(s))
3607                 return ascii_ellipsize_mem(s, old_length, new_length, percent);
3608
3609         if (old_length <= 3 || old_length <= new_length)
3610                 return strndup(s, old_length);
3611
3612         x = (new_length * percent) / 100;
3613
3614         if (x > new_length - 3)
3615                 x = new_length - 3;
3616
3617         k = 0;
3618         for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
3619                 int c;
3620
3621                 c = utf8_encoded_to_unichar(i);
3622                 if (c < 0)
3623                         return NULL;
3624                 k += unichar_iswide(c) ? 2 : 1;
3625         }
3626
3627         if (k > x) /* last character was wide and went over quota */
3628                 x ++;
3629
3630         for (j = s + old_length; k < new_length && j > i; ) {
3631                 int c;
3632
3633                 j = utf8_prev_char(j);
3634                 c = utf8_encoded_to_unichar(j);
3635                 if (c < 0)
3636                         return NULL;
3637                 k += unichar_iswide(c) ? 2 : 1;
3638         }
3639         assert(i <= j);
3640
3641         /* we don't actually need to ellipsize */
3642         if (i == j)
3643                 return memdup(s, old_length + 1);
3644
3645         /* make space for ellipsis */
3646         j = utf8_next_char(j);
3647
3648         len = i - s;
3649         len2 = s + old_length - j;
3650         e = new(char, len + 3 + len2 + 1);
3651         if (!e)
3652                 return NULL;
3653
3654         /*
3655         printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
3656                old_length, new_length, x, len, len2, k);
3657         */
3658
3659         memcpy(e, s, len);
3660         e[len]   = 0xe2; /* tri-dot ellipsis: … */
3661         e[len + 1] = 0x80;
3662         e[len + 2] = 0xa6;
3663
3664         memcpy(e + len + 3, j, len2 + 1);
3665
3666         return e;
3667 }
3668
3669 char *ellipsize(const char *s, size_t length, unsigned percent) {
3670         return ellipsize_mem(s, strlen(s), length, percent);
3671 }
3672
3673 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
3674         _cleanup_close_ int fd;
3675         int r;
3676
3677         assert(path);
3678
3679         if (parents)
3680                 mkdir_parents(path, 0755);
3681
3682         fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
3683         if (fd < 0)
3684                 return -errno;
3685
3686         if (mode > 0) {
3687                 r = fchmod(fd, mode);
3688                 if (r < 0)
3689                         return -errno;
3690         }
3691
3692         if (uid != UID_INVALID || gid != GID_INVALID) {
3693                 r = fchown(fd, uid, gid);
3694                 if (r < 0)
3695                         return -errno;
3696         }
3697
3698         if (stamp != USEC_INFINITY) {
3699                 struct timespec ts[2];
3700
3701                 timespec_store(&ts[0], stamp);
3702                 ts[1] = ts[0];
3703                 r = futimens(fd, ts);
3704         } else
3705                 r = futimens(fd, NULL);
3706         if (r < 0)
3707                 return -errno;
3708
3709         return 0;
3710 }
3711
3712 int touch(const char *path) {
3713         return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
3714 }
3715
3716 char *unquote(const char *s, const char* quotes) {
3717         size_t l;
3718         assert(s);
3719
3720         /* This is rather stupid, simply removes the heading and
3721          * trailing quotes if there is one. Doesn't care about
3722          * escaping or anything. We should make this smarter one
3723          * day...*/
3724
3725         l = strlen(s);
3726         if (l < 2)
3727                 return strdup(s);
3728
3729         if (strchr(quotes, s[0]) && s[l-1] == s[0])
3730                 return strndup(s+1, l-2);
3731
3732         return strdup(s);
3733 }
3734
3735 char *normalize_env_assignment(const char *s) {
3736         _cleanup_free_ char *value = NULL;
3737         const char *eq;
3738         char *p, *name;
3739
3740         eq = strchr(s, '=');
3741         if (!eq) {
3742                 char *r, *t;
3743
3744                 r = strdup(s);
3745                 if (!r)
3746                         return NULL;
3747
3748                 t = strstrip(r);
3749                 if (t != r)
3750                         memmove(r, t, strlen(t) + 1);
3751
3752                 return r;
3753         }
3754
3755         name = strndupa(s, eq - s);
3756         p = strdupa(eq + 1);
3757
3758         value = unquote(strstrip(p), QUOTES);
3759         if (!value)
3760                 return NULL;
3761
3762         return strjoin(strstrip(name), "=", value, NULL);
3763 }
3764
3765 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3766         siginfo_t dummy;
3767
3768         assert(pid >= 1);
3769
3770         if (!status)
3771                 status = &dummy;
3772
3773         for (;;) {
3774                 zero(*status);
3775
3776                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3777
3778                         if (errno == EINTR)
3779                                 continue;
3780
3781                         return -errno;
3782                 }
3783
3784                 return 0;
3785         }
3786 }
3787
3788 /*
3789  * Return values:
3790  * < 0 : wait_for_terminate() failed to get the state of the
3791  *       process, the process was terminated by a signal, or
3792  *       failed for an unknown reason.
3793  * >=0 : The process terminated normally, and its exit code is
3794  *       returned.
3795  *
3796  * That is, success is indicated by a return value of zero, and an
3797  * error is indicated by a non-zero value.
3798  *
3799  * A warning is emitted if the process terminates abnormally,
3800  * and also if it returns non-zero unless check_exit_code is true.
3801  */
3802 int wait_for_terminate_and_warn(const char *name, pid_t pid, bool check_exit_code) {
3803         int r;
3804         siginfo_t status;
3805
3806         assert(name);
3807         assert(pid > 1);
3808
3809         r = wait_for_terminate(pid, &status);
3810         if (r < 0)
3811                 return log_warning_errno(r, "Failed to wait for %s: %m", name);
3812
3813         if (status.si_code == CLD_EXITED) {
3814                 if (status.si_status != 0)
3815                         log_full(check_exit_code ? LOG_WARNING : LOG_DEBUG,
3816                                  "%s failed with error code %i.", name, status.si_status);
3817                 else
3818                         log_debug("%s succeeded.", name);
3819
3820                 return status.si_status;
3821         } else if (status.si_code == CLD_KILLED ||
3822                    status.si_code == CLD_DUMPED) {
3823
3824                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3825                 return -EPROTO;
3826         }
3827
3828         log_warning("%s failed due to unknown reason.", name);
3829         return -EPROTO;
3830 }
3831
3832 noreturn void freeze(void) {
3833
3834         /* Make sure nobody waits for us on a socket anymore */
3835         close_all_fds(NULL, 0);
3836
3837         sync();
3838
3839         for (;;)
3840                 pause();
3841 }
3842
3843 bool null_or_empty(struct stat *st) {
3844         assert(st);
3845
3846         if (S_ISREG(st->st_mode) && st->st_size <= 0)
3847                 return true;
3848
3849         if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3850                 return true;
3851
3852         return false;
3853 }
3854
3855 int null_or_empty_path(const char *fn) {
3856         struct stat st;
3857
3858         assert(fn);
3859
3860         if (stat(fn, &st) < 0)
3861                 return -errno;
3862
3863         return null_or_empty(&st);
3864 }
3865
3866 int null_or_empty_fd(int fd) {
3867         struct stat st;
3868
3869         assert(fd >= 0);
3870
3871         if (fstat(fd, &st) < 0)
3872                 return -errno;
3873
3874         return null_or_empty(&st);
3875 }
3876
3877 DIR *xopendirat(int fd, const char *name, int flags) {
3878         int nfd;
3879         DIR *d;
3880
3881         assert(!(flags & O_CREAT));
3882
3883         nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
3884         if (nfd < 0)
3885                 return NULL;
3886
3887         d = fdopendir(nfd);
3888         if (!d) {
3889                 safe_close(nfd);
3890                 return NULL;
3891         }
3892
3893         return d;
3894 }
3895
3896 int signal_from_string_try_harder(const char *s) {
3897         int signo;
3898         assert(s);
3899
3900         signo = signal_from_string(s);
3901         if (signo <= 0)
3902                 if (startswith(s, "SIG"))
3903                         return signal_from_string(s+3);
3904
3905         return signo;
3906 }
3907
3908 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3909         _cleanup_free_ char *t = NULL, *u = NULL;
3910         size_t enc_len;
3911
3912         u = unquote(tagvalue, "\"\'");
3913         if (!u)
3914                 return NULL;
3915
3916         enc_len = strlen(u) * 4 + 1;
3917         t = new(char, enc_len);
3918         if (!t)
3919                 return NULL;
3920
3921         if (encode_devnode_name(u, t, enc_len) < 0)
3922                 return NULL;
3923
3924         return strjoin("/dev/disk/by-", by, "/", t, NULL);
3925 }
3926
3927 char *fstab_node_to_udev_node(const char *p) {
3928         assert(p);
3929
3930         if (startswith(p, "LABEL="))
3931                 return tag_to_udev_node(p+6, "label");
3932
3933         if (startswith(p, "UUID="))
3934                 return tag_to_udev_node(p+5, "uuid");
3935
3936         if (startswith(p, "PARTUUID="))
3937                 return tag_to_udev_node(p+9, "partuuid");
3938
3939         if (startswith(p, "PARTLABEL="))
3940                 return tag_to_udev_node(p+10, "partlabel");
3941
3942         return strdup(p);
3943 }
3944
3945 bool tty_is_vc(const char *tty) {
3946         assert(tty);
3947
3948         return vtnr_from_tty(tty) >= 0;
3949 }
3950
3951 bool tty_is_console(const char *tty) {
3952         assert(tty);
3953
3954         if (startswith(tty, "/dev/"))
3955                 tty += 5;
3956
3957         return streq(tty, "console");
3958 }
3959
3960 int vtnr_from_tty(const char *tty) {
3961         int i, r;
3962
3963         assert(tty);
3964
3965         if (startswith(tty, "/dev/"))
3966                 tty += 5;
3967
3968         if (!startswith(tty, "tty") )
3969                 return -EINVAL;
3970
3971         if (tty[3] < '0' || tty[3] > '9')
3972                 return -EINVAL;
3973
3974         r = safe_atoi(tty+3, &i);
3975         if (r < 0)
3976                 return r;
3977
3978         if (i < 0 || i > 63)
3979                 return -EINVAL;
3980
3981         return i;
3982 }
3983
3984 char *resolve_dev_console(char **active) {
3985         char *tty;
3986
3987         /* Resolve where /dev/console is pointing to, if /sys is actually ours
3988          * (i.e. not read-only-mounted which is a sign for container setups) */
3989
3990         if (path_is_read_only_fs("/sys") > 0)
3991                 return NULL;
3992
3993         if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3994                 return NULL;
3995
3996         /* If multiple log outputs are configured the last one is what
3997          * /dev/console points to */
3998         tty = strrchr(*active, ' ');
3999         if (tty)
4000                 tty++;
4001         else
4002                 tty = *active;
4003
4004         if (streq(tty, "tty0")) {
4005                 char *tmp;
4006
4007                 /* Get the active VC (e.g. tty1) */
4008                 if (read_one_line_file("/sys/class/tty/tty0/active", &tmp) >= 0) {
4009                         free(*active);
4010                         tty = *active = tmp;
4011                 }
4012         }
4013
4014         return tty;
4015 }
4016
4017 bool tty_is_vc_resolve(const char *tty) {
4018         _cleanup_free_ char *active = NULL;
4019
4020         assert(tty);
4021
4022         if (startswith(tty, "/dev/"))
4023                 tty += 5;
4024
4025         if (streq(tty, "console")) {
4026                 tty = resolve_dev_console(&active);
4027                 if (!tty)
4028                         return false;
4029         }
4030
4031         return tty_is_vc(tty);
4032 }
4033
4034 const char *default_term_for_tty(const char *tty) {
4035         assert(tty);
4036
4037         return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4038 }
4039
4040 bool dirent_is_file(const struct dirent *de) {
4041         assert(de);
4042
4043         if (ignore_file(de->d_name))
4044                 return false;
4045
4046         if (de->d_type != DT_REG &&
4047             de->d_type != DT_LNK &&
4048             de->d_type != DT_UNKNOWN)
4049                 return false;
4050
4051         return true;
4052 }
4053
4054 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4055         assert(de);
4056
4057         if (de->d_type != DT_REG &&
4058             de->d_type != DT_LNK &&
4059             de->d_type != DT_UNKNOWN)
4060                 return false;
4061
4062         if (ignore_file_allow_backup(de->d_name))
4063                 return false;
4064
4065         return endswith(de->d_name, suffix);
4066 }
4067
4068 void execute_directory(const char *directory, DIR *d, usec_t timeout, char *argv[]) {
4069         pid_t executor_pid;
4070         int r;
4071
4072         assert(directory);
4073
4074         /* Executes all binaries in a directory in parallel and waits
4075          * for them to finish. Optionally a timeout is applied. */
4076
4077         executor_pid = fork();
4078         if (executor_pid < 0) {
4079                 log_error_errno(errno, "Failed to fork: %m");
4080                 return;
4081
4082         } else if (executor_pid == 0) {
4083                 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
4084                 _cleanup_closedir_ DIR *_d = NULL;
4085                 struct dirent *de;
4086
4087                 /* We fork this all off from a child process so that
4088                  * we can somewhat cleanly make use of SIGALRM to set
4089                  * a time limit */
4090
4091                 reset_all_signal_handlers();
4092                 reset_signal_mask();
4093
4094                 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
4095
4096                 if (!d) {
4097                         d = _d = opendir(directory);
4098                         if (!d) {
4099                                 if (errno == ENOENT)
4100                                         _exit(EXIT_SUCCESS);
4101
4102                                 log_error_errno(errno, "Failed to enumerate directory %s: %m", directory);
4103                                 _exit(EXIT_FAILURE);
4104                         }
4105                 }
4106
4107                 pids = hashmap_new(NULL);
4108                 if (!pids) {
4109                         log_oom();
4110                         _exit(EXIT_FAILURE);
4111                 }
4112
4113                 FOREACH_DIRENT(de, d, break) {
4114                         _cleanup_free_ char *path = NULL;
4115                         pid_t pid;
4116
4117                         if (!dirent_is_file(de))
4118                                 continue;
4119
4120                         path = strjoin(directory, "/", de->d_name, NULL);
4121                         if (!path) {
4122                                 log_oom();
4123                                 _exit(EXIT_FAILURE);
4124                         }
4125
4126                         pid = fork();
4127                         if (pid < 0) {
4128                                 log_error_errno(errno, "Failed to fork: %m");
4129                                 continue;
4130                         } else if (pid == 0) {
4131                                 char *_argv[2];
4132
4133                                 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
4134
4135                                 if (!argv) {
4136                                         _argv[0] = path;
4137                                         _argv[1] = NULL;
4138                                         argv = _argv;
4139                                 } else
4140                                         argv[0] = path;
4141
4142                                 execv(path, argv);
4143                                 log_error_errno(errno, "Failed to execute %s: %m", path);
4144                                 _exit(EXIT_FAILURE);
4145                         }
4146
4147                         log_debug("Spawned %s as " PID_FMT ".", path, pid);
4148
4149                         r = hashmap_put(pids, UINT_TO_PTR(pid), path);
4150                         if (r < 0) {
4151                                 log_oom();
4152                                 _exit(EXIT_FAILURE);
4153                         }
4154
4155                         path = NULL;
4156                 }
4157
4158                 /* Abort execution of this process after the
4159                  * timout. We simply rely on SIGALRM as default action
4160                  * terminating the process, and turn on alarm(). */
4161
4162                 if (timeout != USEC_INFINITY)
4163                         alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
4164
4165                 while (!hashmap_isempty(pids)) {
4166                         _cleanup_free_ char *path = NULL;
4167                         pid_t pid;
4168
4169                         pid = PTR_TO_UINT(hashmap_first_key(pids));
4170                         assert(pid > 0);
4171
4172                         path = hashmap_remove(pids, UINT_TO_PTR(pid));
4173                         assert(path);
4174
4175                         wait_for_terminate_and_warn(path, pid, true);
4176                 }
4177
4178                 _exit(EXIT_SUCCESS);
4179         }
4180
4181         wait_for_terminate_and_warn(directory, executor_pid, true);
4182 }
4183
4184 int kill_and_sigcont(pid_t pid, int sig) {
4185         int r;
4186
4187         r = kill(pid, sig) < 0 ? -errno : 0;
4188
4189         if (r >= 0)
4190                 kill(pid, SIGCONT);
4191
4192         return r;
4193 }
4194
4195 bool nulstr_contains(const char*nulstr, const char *needle) {
4196         const char *i;
4197
4198         if (!nulstr)
4199                 return false;
4200
4201         NULSTR_FOREACH(i, nulstr)
4202                 if (streq(i, needle))
4203                         return true;
4204
4205         return false;
4206 }
4207
4208 bool plymouth_running(void) {
4209         return access("/run/plymouth/pid", F_OK) >= 0;
4210 }
4211
4212 char* strshorten(char *s, size_t l) {
4213         assert(s);
4214
4215         if (l < strlen(s))
4216                 s[l] = 0;
4217
4218         return s;
4219 }
4220
4221 static bool hostname_valid_char(char c) {
4222         return
4223                 (c >= 'a' && c <= 'z') ||
4224                 (c >= 'A' && c <= 'Z') ||
4225                 (c >= '0' && c <= '9') ||
4226                 c == '-' ||
4227                 c == '_' ||
4228                 c == '.';
4229 }
4230
4231 bool hostname_is_valid(const char *s) {
4232         const char *p;
4233         bool dot;
4234
4235         if (isempty(s))
4236                 return false;
4237
4238         for (p = s, dot = true; *p; p++) {
4239                 if (*p == '.') {
4240                         if (dot)
4241                                 return false;
4242
4243                         dot = true;
4244                 } else {
4245                         if (!hostname_valid_char(*p))
4246                                 return false;
4247
4248                         dot = false;
4249                 }
4250         }
4251
4252         if (dot)
4253                 return false;
4254
4255         if (p-s > HOST_NAME_MAX)
4256                 return false;
4257
4258         return true;
4259 }
4260
4261 char* hostname_cleanup(char *s, bool lowercase) {
4262         char *p, *d;
4263         bool dot;
4264
4265         for (p = s, d = s, dot = true; *p; p++) {
4266                 if (*p == '.') {
4267                         if (dot)
4268                                 continue;
4269
4270                         *(d++) = '.';
4271                         dot = true;
4272                 } else if (hostname_valid_char(*p)) {
4273                         *(d++) = lowercase ? tolower(*p) : *p;
4274                         dot = false;
4275                 }
4276
4277         }
4278
4279         if (dot && d > s)
4280                 d[-1] = 0;
4281         else
4282                 *d = 0;
4283
4284         strshorten(s, HOST_NAME_MAX);
4285
4286         return s;
4287 }
4288
4289 bool machine_name_is_valid(const char *s) {
4290
4291         if (!hostname_is_valid(s))
4292                 return false;
4293
4294         /* Machine names should be useful hostnames, but also be
4295          * useful in unit names, hence we enforce a stricter length
4296          * limitation. */
4297
4298         if (strlen(s) > 64)
4299                 return false;
4300
4301         return true;
4302 }
4303
4304 int pipe_eof(int fd) {
4305         struct pollfd pollfd = {
4306                 .fd = fd,
4307                 .events = POLLIN|POLLHUP,
4308         };
4309
4310         int r;
4311
4312         r = poll(&pollfd, 1, 0);
4313         if (r < 0)
4314                 return -errno;
4315
4316         if (r == 0)
4317                 return 0;
4318
4319         return pollfd.revents & POLLHUP;
4320 }
4321
4322 int fd_wait_for_event(int fd, int event, usec_t t) {
4323
4324         struct pollfd pollfd = {
4325                 .fd = fd,
4326                 .events = event,
4327         };
4328
4329         struct timespec ts;
4330         int r;
4331
4332         r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
4333         if (r < 0)
4334                 return -errno;
4335
4336         if (r == 0)
4337                 return 0;
4338
4339         return pollfd.revents;
4340 }
4341
4342 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4343         FILE *f;
4344         char *t;
4345         int fd;
4346
4347         assert(path);
4348         assert(_f);
4349         assert(_temp_path);
4350
4351         t = tempfn_xxxxxx(path);
4352         if (!t)
4353                 return -ENOMEM;
4354
4355         fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
4356         if (fd < 0) {
4357                 free(t);
4358                 return -errno;
4359         }
4360
4361         f = fdopen(fd, "we");
4362         if (!f) {
4363                 unlink(t);
4364                 free(t);
4365                 return -errno;
4366         }
4367
4368         *_f = f;
4369         *_temp_path = t;
4370
4371         return 0;
4372 }
4373
4374 int terminal_vhangup_fd(int fd) {
4375         assert(fd >= 0);
4376
4377         if (ioctl(fd, TIOCVHANGUP) < 0)
4378                 return -errno;
4379
4380         return 0;
4381 }
4382
4383 int terminal_vhangup(const char *name) {
4384         _cleanup_close_ int fd;
4385
4386         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4387         if (fd < 0)
4388                 return fd;
4389
4390         return terminal_vhangup_fd(fd);
4391 }
4392
4393 int vt_disallocate(const char *name) {
4394         int fd, r;
4395         unsigned u;
4396
4397         /* Deallocate the VT if possible. If not possible
4398          * (i.e. because it is the active one), at least clear it
4399          * entirely (including the scrollback buffer) */
4400
4401         if (!startswith(name, "/dev/"))
4402                 return -EINVAL;
4403
4404         if (!tty_is_vc(name)) {
4405                 /* So this is not a VT. I guess we cannot deallocate
4406                  * it then. But let's at least clear the screen */
4407
4408                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4409                 if (fd < 0)
4410                         return fd;
4411
4412                 loop_write(fd,
4413                            "\033[r"    /* clear scrolling region */
4414                            "\033[H"    /* move home */
4415                            "\033[2J",  /* clear screen */
4416                            10, false);
4417                 safe_close(fd);
4418
4419                 return 0;
4420         }
4421
4422         if (!startswith(name, "/dev/tty"))
4423                 return -EINVAL;
4424
4425         r = safe_atou(name+8, &u);
4426         if (r < 0)
4427                 return r;
4428
4429         if (u <= 0)
4430                 return -EINVAL;
4431
4432         /* Try to deallocate */
4433         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4434         if (fd < 0)
4435                 return fd;
4436
4437         r = ioctl(fd, VT_DISALLOCATE, u);
4438         safe_close(fd);
4439
4440         if (r >= 0)
4441                 return 0;
4442
4443         if (errno != EBUSY)
4444                 return -errno;
4445
4446         /* Couldn't deallocate, so let's clear it fully with
4447          * scrollback */
4448         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4449         if (fd < 0)
4450                 return fd;
4451
4452         loop_write(fd,
4453                    "\033[r"   /* clear scrolling region */
4454                    "\033[H"   /* move home */
4455                    "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4456                    10, false);
4457         safe_close(fd);
4458
4459         return 0;
4460 }
4461
4462 int symlink_atomic(const char *from, const char *to) {
4463         _cleanup_free_ char *t = NULL;
4464
4465         assert(from);
4466         assert(to);
4467
4468         t = tempfn_random(to);
4469         if (!t)
4470                 return -ENOMEM;
4471
4472         if (symlink(from, t) < 0)
4473                 return -errno;
4474
4475         if (rename(t, to) < 0) {
4476                 unlink_noerrno(t);
4477                 return -errno;
4478         }
4479
4480         return 0;
4481 }
4482
4483 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
4484         _cleanup_free_ char *t = NULL;
4485
4486         assert(path);
4487
4488         t = tempfn_random(path);
4489         if (!t)
4490                 return -ENOMEM;
4491
4492         if (mknod(t, mode, dev) < 0)
4493                 return -errno;
4494
4495         if (rename(t, path) < 0) {
4496                 unlink_noerrno(t);
4497                 return -errno;
4498         }
4499
4500         return 0;
4501 }
4502
4503 int mkfifo_atomic(const char *path, mode_t mode) {
4504         _cleanup_free_ char *t = NULL;
4505
4506         assert(path);
4507
4508         t = tempfn_random(path);
4509         if (!t)
4510                 return -ENOMEM;
4511
4512         if (mkfifo(t, mode) < 0)
4513                 return -errno;
4514
4515         if (rename(t, path) < 0) {
4516                 unlink_noerrno(t);
4517                 return -errno;
4518         }
4519
4520         return 0;
4521 }
4522
4523 bool display_is_local(const char *display) {
4524         assert(display);
4525
4526         return
4527                 display[0] == ':' &&
4528                 display[1] >= '0' &&
4529                 display[1] <= '9';
4530 }
4531
4532 int socket_from_display(const char *display, char **path) {
4533         size_t k;
4534         char *f, *c;
4535
4536         assert(display);
4537         assert(path);
4538
4539         if (!display_is_local(display))
4540                 return -EINVAL;
4541
4542         k = strspn(display+1, "0123456789");
4543
4544         f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
4545         if (!f)
4546                 return -ENOMEM;
4547
4548         c = stpcpy(f, "/tmp/.X11-unix/X");
4549         memcpy(c, display+1, k);
4550         c[k] = 0;
4551
4552         *path = f;
4553
4554         return 0;
4555 }
4556
4557 int get_user_creds(
4558                 const char **username,
4559                 uid_t *uid, gid_t *gid,
4560                 const char **home,
4561                 const char **shell) {
4562
4563         struct passwd *p;
4564         uid_t u;
4565
4566         assert(username);
4567         assert(*username);
4568
4569         /* We enforce some special rules for uid=0: in order to avoid
4570          * NSS lookups for root we hardcode its data. */
4571
4572         if (streq(*username, "root") || streq(*username, "0")) {
4573                 *username = "root";
4574
4575                 if (uid)
4576                         *uid = 0;
4577
4578                 if (gid)
4579                         *gid = 0;
4580
4581                 if (home)
4582                         *home = "/root";
4583
4584                 if (shell)
4585                         *shell = "/bin/sh";
4586
4587                 return 0;
4588         }
4589
4590         if (parse_uid(*username, &u) >= 0) {
4591                 errno = 0;
4592                 p = getpwuid(u);
4593
4594                 /* If there are multiple users with the same id, make
4595                  * sure to leave $USER to the configured value instead
4596                  * of the first occurrence in the database. However if
4597                  * the uid was configured by a numeric uid, then let's
4598                  * pick the real username from /etc/passwd. */
4599                 if (p)
4600                         *username = p->pw_name;
4601         } else {
4602                 errno = 0;
4603                 p = getpwnam(*username);
4604         }
4605
4606         if (!p)
4607                 return errno > 0 ? -errno : -ESRCH;
4608
4609         if (uid)
4610                 *uid = p->pw_uid;
4611
4612         if (gid)
4613                 *gid = p->pw_gid;
4614
4615         if (home)
4616                 *home = p->pw_dir;
4617
4618         if (shell)
4619                 *shell = p->pw_shell;
4620
4621         return 0;
4622 }
4623
4624 char* uid_to_name(uid_t uid) {
4625         struct passwd *p;
4626         char *r;
4627
4628         if (uid == 0)
4629                 return strdup("root");
4630
4631         p = getpwuid(uid);
4632         if (p)
4633                 return strdup(p->pw_name);
4634
4635         if (asprintf(&r, UID_FMT, uid) < 0)
4636                 return NULL;
4637
4638         return r;
4639 }
4640
4641 char* gid_to_name(gid_t gid) {
4642         struct group *p;
4643         char *r;
4644
4645         if (gid == 0)
4646                 return strdup("root");
4647
4648         p = getgrgid(gid);
4649         if (p)
4650                 return strdup(p->gr_name);
4651
4652         if (asprintf(&r, GID_FMT, gid) < 0)
4653                 return NULL;
4654
4655         return r;
4656 }
4657
4658 int get_group_creds(const char **groupname, gid_t *gid) {
4659         struct group *g;
4660         gid_t id;
4661
4662         assert(groupname);
4663
4664         /* We enforce some special rules for gid=0: in order to avoid
4665          * NSS lookups for root we hardcode its data. */
4666
4667         if (streq(*groupname, "root") || streq(*groupname, "0")) {
4668                 *groupname = "root";
4669
4670                 if (gid)
4671                         *gid = 0;
4672
4673                 return 0;
4674         }
4675
4676         if (parse_gid(*groupname, &id) >= 0) {
4677                 errno = 0;
4678                 g = getgrgid(id);
4679
4680                 if (g)
4681                         *groupname = g->gr_name;
4682         } else {
4683                 errno = 0;
4684                 g = getgrnam(*groupname);
4685         }
4686
4687         if (!g)
4688                 return errno > 0 ? -errno : -ESRCH;
4689
4690         if (gid)
4691                 *gid = g->gr_gid;
4692
4693         return 0;
4694 }
4695
4696 int in_gid(gid_t gid) {
4697         gid_t *gids;
4698         int ngroups_max, r, i;
4699
4700         if (getgid() == gid)
4701                 return 1;
4702
4703         if (getegid() == gid)
4704                 return 1;
4705
4706         ngroups_max = sysconf(_SC_NGROUPS_MAX);
4707         assert(ngroups_max > 0);
4708
4709         gids = alloca(sizeof(gid_t) * ngroups_max);
4710
4711         r = getgroups(ngroups_max, gids);
4712         if (r < 0)
4713                 return -errno;
4714
4715         for (i = 0; i < r; i++)
4716                 if (gids[i] == gid)
4717                         return 1;
4718
4719         return 0;
4720 }
4721
4722 int in_group(const char *name) {
4723         int r;
4724         gid_t gid;
4725
4726         r = get_group_creds(&name, &gid);
4727         if (r < 0)
4728                 return r;
4729
4730         return in_gid(gid);
4731 }
4732
4733 int glob_exists(const char *path) {
4734         _cleanup_globfree_ glob_t g = {};
4735         int k;
4736
4737         assert(path);
4738
4739         errno = 0;
4740         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4741
4742         if (k == GLOB_NOMATCH)
4743                 return 0;
4744         else if (k == GLOB_NOSPACE)
4745                 return -ENOMEM;
4746         else if (k == 0)
4747                 return !strv_isempty(g.gl_pathv);
4748         else
4749                 return errno ? -errno : -EIO;
4750 }
4751
4752 int glob_extend(char ***strv, const char *path) {
4753         _cleanup_globfree_ glob_t g = {};
4754         int k;
4755         char **p;
4756
4757         errno = 0;
4758         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4759
4760         if (k == GLOB_NOMATCH)
4761                 return -ENOENT;
4762         else if (k == GLOB_NOSPACE)
4763                 return -ENOMEM;
4764         else if (k != 0 || strv_isempty(g.gl_pathv))
4765                 return errno ? -errno : -EIO;
4766
4767         STRV_FOREACH(p, g.gl_pathv) {
4768                 k = strv_extend(strv, *p);
4769                 if (k < 0)
4770                         break;
4771         }
4772
4773         return k;
4774 }
4775
4776 int dirent_ensure_type(DIR *d, struct dirent *de) {
4777         struct stat st;
4778
4779         assert(d);
4780         assert(de);
4781
4782         if (de->d_type != DT_UNKNOWN)
4783                 return 0;
4784
4785         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4786                 return -errno;
4787
4788         de->d_type =
4789                 S_ISREG(st.st_mode)  ? DT_REG  :
4790                 S_ISDIR(st.st_mode)  ? DT_DIR  :
4791                 S_ISLNK(st.st_mode)  ? DT_LNK  :
4792                 S_ISFIFO(st.st_mode) ? DT_FIFO :
4793                 S_ISSOCK(st.st_mode) ? DT_SOCK :
4794                 S_ISCHR(st.st_mode)  ? DT_CHR  :
4795                 S_ISBLK(st.st_mode)  ? DT_BLK  :
4796                                        DT_UNKNOWN;
4797
4798         return 0;
4799 }
4800
4801 int get_files_in_directory(const char *path, char ***list) {
4802         _cleanup_closedir_ DIR *d = NULL;
4803         size_t bufsize = 0, n = 0;
4804         _cleanup_strv_free_ char **l = NULL;
4805
4806         assert(path);
4807
4808         /* Returns all files in a directory in *list, and the number
4809          * of files as return value. If list is NULL returns only the
4810          * number. */
4811
4812         d = opendir(path);
4813         if (!d)
4814                 return -errno;
4815
4816         for (;;) {
4817                 struct dirent *de;
4818
4819                 errno = 0;
4820                 de = readdir(d);
4821                 if (!de && errno != 0)
4822                         return -errno;
4823                 if (!de)
4824                         break;
4825
4826                 dirent_ensure_type(d, de);
4827
4828                 if (!dirent_is_file(de))
4829                         continue;
4830
4831                 if (list) {
4832                         /* one extra slot is needed for the terminating NULL */
4833                         if (!GREEDY_REALLOC(l, bufsize, n + 2))
4834                                 return -ENOMEM;
4835
4836                         l[n] = strdup(de->d_name);
4837                         if (!l[n])
4838                                 return -ENOMEM;
4839
4840                         l[++n] = NULL;
4841                 } else
4842                         n++;
4843         }
4844
4845         if (list) {
4846                 *list = l;
4847                 l = NULL; /* avoid freeing */
4848         }
4849
4850         return n;
4851 }
4852
4853 char *strjoin(const char *x, ...) {
4854         va_list ap;
4855         size_t l;
4856         char *r, *p;
4857
4858         va_start(ap, x);
4859
4860         if (x) {
4861                 l = strlen(x);
4862
4863                 for (;;) {
4864                         const char *t;
4865                         size_t n;
4866
4867                         t = va_arg(ap, const char *);
4868                         if (!t)
4869                                 break;
4870
4871                         n = strlen(t);
4872                         if (n > ((size_t) -1) - l) {
4873                                 va_end(ap);
4874                                 return NULL;
4875                         }
4876
4877                         l += n;
4878                 }
4879         } else
4880                 l = 0;
4881
4882         va_end(ap);
4883
4884         r = new(char, l+1);
4885         if (!r)
4886                 return NULL;
4887
4888         if (x) {
4889                 p = stpcpy(r, x);
4890
4891                 va_start(ap, x);
4892
4893                 for (;;) {
4894                         const char *t;
4895
4896                         t = va_arg(ap, const char *);
4897                         if (!t)
4898                                 break;
4899
4900                         p = stpcpy(p, t);
4901                 }
4902
4903                 va_end(ap);
4904         } else
4905                 r[0] = 0;
4906
4907         return r;
4908 }
4909
4910 bool is_main_thread(void) {
4911         static thread_local int cached = 0;
4912
4913         if (_unlikely_(cached == 0))
4914                 cached = getpid() == gettid() ? 1 : -1;
4915
4916         return cached > 0;
4917 }
4918
4919 int block_get_whole_disk(dev_t d, dev_t *ret) {
4920         char *p, *s;
4921         int r;
4922         unsigned n, m;
4923
4924         assert(ret);
4925
4926         /* If it has a queue this is good enough for us */
4927         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4928                 return -ENOMEM;
4929
4930         r = access(p, F_OK);
4931         free(p);
4932
4933         if (r >= 0) {
4934                 *ret = d;
4935                 return 0;
4936         }
4937
4938         /* If it is a partition find the originating device */
4939         if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4940                 return -ENOMEM;
4941
4942         r = access(p, F_OK);
4943         free(p);
4944
4945         if (r < 0)
4946                 return -ENOENT;
4947
4948         /* Get parent dev_t */
4949         if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4950                 return -ENOMEM;
4951
4952         r = read_one_line_file(p, &s);
4953         free(p);
4954
4955         if (r < 0)
4956                 return r;
4957
4958         r = sscanf(s, "%u:%u", &m, &n);
4959         free(s);
4960
4961         if (r != 2)
4962                 return -EINVAL;
4963
4964         /* Only return this if it is really good enough for us. */
4965         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4966                 return -ENOMEM;
4967
4968         r = access(p, F_OK);
4969         free(p);
4970
4971         if (r >= 0) {
4972                 *ret = makedev(m, n);
4973                 return 0;
4974         }
4975
4976         return -ENOENT;
4977 }
4978
4979 static const char *const ioprio_class_table[] = {
4980         [IOPRIO_CLASS_NONE] = "none",
4981         [IOPRIO_CLASS_RT] = "realtime",
4982         [IOPRIO_CLASS_BE] = "best-effort",
4983         [IOPRIO_CLASS_IDLE] = "idle"
4984 };
4985
4986 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4987
4988 static const char *const sigchld_code_table[] = {
4989         [CLD_EXITED] = "exited",
4990         [CLD_KILLED] = "killed",
4991         [CLD_DUMPED] = "dumped",
4992         [CLD_TRAPPED] = "trapped",
4993         [CLD_STOPPED] = "stopped",
4994         [CLD_CONTINUED] = "continued",
4995 };
4996
4997 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4998
4999 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5000         [LOG_FAC(LOG_KERN)] = "kern",
5001         [LOG_FAC(LOG_USER)] = "user",
5002         [LOG_FAC(LOG_MAIL)] = "mail",
5003         [LOG_FAC(LOG_DAEMON)] = "daemon",
5004         [LOG_FAC(LOG_AUTH)] = "auth",
5005         [LOG_FAC(LOG_SYSLOG)] = "syslog",
5006         [LOG_FAC(LOG_LPR)] = "lpr",
5007         [LOG_FAC(LOG_NEWS)] = "news",
5008         [LOG_FAC(LOG_UUCP)] = "uucp",
5009         [LOG_FAC(LOG_CRON)] = "cron",
5010         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5011         [LOG_FAC(LOG_FTP)] = "ftp",
5012         [LOG_FAC(LOG_LOCAL0)] = "local0",
5013         [LOG_FAC(LOG_LOCAL1)] = "local1",
5014         [LOG_FAC(LOG_LOCAL2)] = "local2",
5015         [LOG_FAC(LOG_LOCAL3)] = "local3",
5016         [LOG_FAC(LOG_LOCAL4)] = "local4",
5017         [LOG_FAC(LOG_LOCAL5)] = "local5",
5018         [LOG_FAC(LOG_LOCAL6)] = "local6",
5019         [LOG_FAC(LOG_LOCAL7)] = "local7"
5020 };
5021
5022 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
5023
5024 static const char *const log_level_table[] = {
5025         [LOG_EMERG] = "emerg",
5026         [LOG_ALERT] = "alert",
5027         [LOG_CRIT] = "crit",
5028         [LOG_ERR] = "err",
5029         [LOG_WARNING] = "warning",
5030         [LOG_NOTICE] = "notice",
5031         [LOG_INFO] = "info",
5032         [LOG_DEBUG] = "debug"
5033 };
5034
5035 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
5036
5037 static const char* const sched_policy_table[] = {
5038         [SCHED_OTHER] = "other",
5039         [SCHED_BATCH] = "batch",
5040         [SCHED_IDLE] = "idle",
5041         [SCHED_FIFO] = "fifo",
5042         [SCHED_RR] = "rr"
5043 };
5044
5045 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
5046
5047 static const char* const rlimit_table[_RLIMIT_MAX] = {
5048         [RLIMIT_CPU] = "LimitCPU",
5049         [RLIMIT_FSIZE] = "LimitFSIZE",
5050         [RLIMIT_DATA] = "LimitDATA",
5051         [RLIMIT_STACK] = "LimitSTACK",
5052         [RLIMIT_CORE] = "LimitCORE",
5053         [RLIMIT_RSS] = "LimitRSS",
5054         [RLIMIT_NOFILE] = "LimitNOFILE",
5055         [RLIMIT_AS] = "LimitAS",
5056         [RLIMIT_NPROC] = "LimitNPROC",
5057         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5058         [RLIMIT_LOCKS] = "LimitLOCKS",
5059         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5060         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5061         [RLIMIT_NICE] = "LimitNICE",
5062         [RLIMIT_RTPRIO] = "LimitRTPRIO",
5063         [RLIMIT_RTTIME] = "LimitRTTIME"
5064 };
5065
5066 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5067
5068 static const char* const ip_tos_table[] = {
5069         [IPTOS_LOWDELAY] = "low-delay",
5070         [IPTOS_THROUGHPUT] = "throughput",
5071         [IPTOS_RELIABILITY] = "reliability",
5072         [IPTOS_LOWCOST] = "low-cost",
5073 };
5074
5075 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
5076
5077 static const char *const __signal_table[] = {
5078         [SIGHUP] = "HUP",
5079         [SIGINT] = "INT",
5080         [SIGQUIT] = "QUIT",
5081         [SIGILL] = "ILL",
5082         [SIGTRAP] = "TRAP",
5083         [SIGABRT] = "ABRT",
5084         [SIGBUS] = "BUS",
5085         [SIGFPE] = "FPE",
5086         [SIGKILL] = "KILL",
5087         [SIGUSR1] = "USR1",
5088         [SIGSEGV] = "SEGV",
5089         [SIGUSR2] = "USR2",
5090         [SIGPIPE] = "PIPE",
5091         [SIGALRM] = "ALRM",
5092         [SIGTERM] = "TERM",
5093 #ifdef SIGSTKFLT
5094         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
5095 #endif
5096         [SIGCHLD] = "CHLD",
5097         [SIGCONT] = "CONT",
5098         [SIGSTOP] = "STOP",
5099         [SIGTSTP] = "TSTP",
5100         [SIGTTIN] = "TTIN",
5101         [SIGTTOU] = "TTOU",
5102         [SIGURG] = "URG",
5103         [SIGXCPU] = "XCPU",
5104         [SIGXFSZ] = "XFSZ",
5105         [SIGVTALRM] = "VTALRM",
5106         [SIGPROF] = "PROF",
5107         [SIGWINCH] = "WINCH",
5108         [SIGIO] = "IO",
5109         [SIGPWR] = "PWR",
5110         [SIGSYS] = "SYS"
5111 };
5112
5113 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5114
5115 const char *signal_to_string(int signo) {
5116         static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
5117         const char *name;
5118
5119         name = __signal_to_string(signo);
5120         if (name)
5121                 return name;
5122
5123         if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5124                 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
5125         else
5126                 snprintf(buf, sizeof(buf), "%d", signo);
5127
5128         return buf;
5129 }
5130
5131 int signal_from_string(const char *s) {
5132         int signo;
5133         int offset = 0;
5134         unsigned u;
5135
5136         signo = __signal_from_string(s);
5137         if (signo > 0)
5138                 return signo;
5139
5140         if (startswith(s, "RTMIN+")) {
5141                 s += 6;
5142                 offset = SIGRTMIN;
5143         }
5144         if (safe_atou(s, &u) >= 0) {
5145                 signo = (int) u + offset;
5146                 if (signo > 0 && signo < _NSIG)
5147                         return signo;
5148         }
5149         return -EINVAL;
5150 }
5151
5152 bool kexec_loaded(void) {
5153        bool loaded = false;
5154        char *s;
5155
5156        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5157                if (s[0] == '1')
5158                        loaded = true;
5159                free(s);
5160        }
5161        return loaded;
5162 }
5163
5164 int prot_from_flags(int flags) {
5165
5166         switch (flags & O_ACCMODE) {
5167
5168         case O_RDONLY:
5169                 return PROT_READ;
5170
5171         case O_WRONLY:
5172                 return PROT_WRITE;
5173
5174         case O_RDWR:
5175                 return PROT_READ|PROT_WRITE;
5176
5177         default:
5178                 return -EINVAL;
5179         }
5180 }
5181
5182 char *format_bytes(char *buf, size_t l, off_t t) {
5183         unsigned i;
5184
5185         static const struct {
5186                 const char *suffix;
5187                 off_t factor;
5188         } table[] = {
5189                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5190                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5191                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5192                 { "G", 1024ULL*1024ULL*1024ULL },
5193                 { "M", 1024ULL*1024ULL },
5194                 { "K", 1024ULL },
5195         };
5196
5197         for (i = 0; i < ELEMENTSOF(table); i++) {
5198
5199                 if (t >= table[i].factor) {
5200                         snprintf(buf, l,
5201                                  "%llu.%llu%s",
5202                                  (unsigned long long) (t / table[i].factor),
5203                                  (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5204                                  table[i].suffix);
5205
5206                         goto finish;
5207                 }
5208         }
5209
5210         snprintf(buf, l, "%lluB", (unsigned long long) t);
5211
5212 finish:
5213         buf[l-1] = 0;
5214         return buf;
5215
5216 }
5217
5218 void* memdup(const void *p, size_t l) {
5219         void *r;
5220
5221         assert(p);
5222
5223         r = malloc(l);
5224         if (!r)
5225                 return NULL;
5226
5227         memcpy(r, p, l);
5228         return r;
5229 }
5230
5231 int fd_inc_sndbuf(int fd, size_t n) {
5232         int r, value;
5233         socklen_t l = sizeof(value);
5234
5235         r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5236         if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
5237                 return 0;
5238
5239         /* If we have the privileges we will ignore the kernel limit. */
5240
5241         value = (int) n;
5242         if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
5243                 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
5244                         return -errno;
5245
5246         return 1;
5247 }
5248
5249 int fd_inc_rcvbuf(int fd, size_t n) {
5250         int r, value;
5251         socklen_t l = sizeof(value);
5252
5253         r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5254         if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
5255                 return 0;
5256
5257         /* If we have the privileges we will ignore the kernel limit. */
5258
5259         value = (int) n;
5260         if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
5261                 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
5262                         return -errno;
5263         return 1;
5264 }
5265
5266 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5267         bool stdout_is_tty, stderr_is_tty;
5268         pid_t parent_pid, agent_pid;
5269         sigset_t ss, saved_ss;
5270         unsigned n, i;
5271         va_list ap;
5272         char **l;
5273
5274         assert(pid);
5275         assert(path);
5276
5277         /* Spawns a temporary TTY agent, making sure it goes away when
5278          * we go away */
5279
5280         parent_pid = getpid();
5281
5282         /* First we temporarily block all signals, so that the new
5283          * child has them blocked initially. This way, we can be sure
5284          * that SIGTERMs are not lost we might send to the agent. */
5285         assert_se(sigfillset(&ss) >= 0);
5286         assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
5287
5288         agent_pid = fork();
5289         if (agent_pid < 0) {
5290                 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
5291                 return -errno;
5292         }
5293
5294         if (agent_pid != 0) {
5295                 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
5296                 *pid = agent_pid;
5297                 return 0;
5298         }
5299
5300         /* In the child:
5301          *
5302          * Make sure the agent goes away when the parent dies */
5303         if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5304                 _exit(EXIT_FAILURE);
5305
5306         /* Make sure we actually can kill the agent, if we need to, in
5307          * case somebody invoked us from a shell script that trapped
5308          * SIGTERM or so... */
5309         reset_all_signal_handlers();
5310         reset_signal_mask();
5311
5312         /* Check whether our parent died before we were able
5313          * to set the death signal and unblock the signals */
5314         if (getppid() != parent_pid)
5315                 _exit(EXIT_SUCCESS);
5316
5317         /* Don't leak fds to the agent */
5318         close_all_fds(except, n_except);
5319
5320         stdout_is_tty = isatty(STDOUT_FILENO);
5321         stderr_is_tty = isatty(STDERR_FILENO);
5322
5323         if (!stdout_is_tty || !stderr_is_tty) {
5324                 int fd;
5325
5326                 /* Detach from stdout/stderr. and reopen
5327                  * /dev/tty for them. This is important to
5328                  * ensure that when systemctl is started via
5329                  * popen() or a similar call that expects to
5330                  * read EOF we actually do generate EOF and
5331                  * not delay this indefinitely by because we
5332                  * keep an unused copy of stdin around. */
5333                 fd = open("/dev/tty", O_WRONLY);
5334                 if (fd < 0) {
5335                         log_error_errno(errno, "Failed to open /dev/tty: %m");
5336                         _exit(EXIT_FAILURE);
5337                 }
5338
5339                 if (!stdout_is_tty)
5340                         dup2(fd, STDOUT_FILENO);
5341
5342                 if (!stderr_is_tty)
5343                         dup2(fd, STDERR_FILENO);
5344
5345                 if (fd > 2)
5346                         close(fd);
5347         }
5348
5349         /* Count arguments */
5350         va_start(ap, path);
5351         for (n = 0; va_arg(ap, char*); n++)
5352                 ;
5353         va_end(ap);
5354
5355         /* Allocate strv */
5356         l = alloca(sizeof(char *) * (n + 1));
5357
5358         /* Fill in arguments */
5359         va_start(ap, path);
5360         for (i = 0; i <= n; i++)
5361                 l[i] = va_arg(ap, char*);
5362         va_end(ap);
5363
5364         execv(path, l);
5365         _exit(EXIT_FAILURE);
5366 }
5367
5368 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5369         struct rlimit highest, fixed;
5370
5371         assert(rlim);
5372
5373         if (setrlimit(resource, rlim) >= 0)
5374                 return 0;
5375
5376         if (errno != EPERM)
5377                 return -errno;
5378
5379         /* So we failed to set the desired setrlimit, then let's try
5380          * to get as close as we can */
5381         assert_se(getrlimit(resource, &highest) == 0);
5382
5383         fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5384         fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5385
5386         if (setrlimit(resource, &fixed) < 0)
5387                 return -errno;
5388
5389         return 0;
5390 }
5391
5392 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5393         _cleanup_fclose_ FILE *f = NULL;
5394         char *value = NULL;
5395         int r;
5396         bool done = false;
5397         size_t l;
5398         const char *path;
5399
5400         assert(pid >= 0);
5401         assert(field);
5402         assert(_value);
5403
5404         path = procfs_file_alloca(pid, "environ");
5405
5406         f = fopen(path, "re");
5407         if (!f)
5408                 return -errno;
5409
5410         l = strlen(field);
5411         r = 0;
5412
5413         do {
5414                 char line[LINE_MAX];
5415                 unsigned i;
5416
5417                 for (i = 0; i < sizeof(line)-1; i++) {
5418                         int c;
5419
5420                         c = getc(f);
5421                         if (_unlikely_(c == EOF)) {
5422                                 done = true;
5423                                 break;
5424                         } else if (c == 0)
5425                                 break;
5426
5427                         line[i] = c;
5428                 }
5429                 line[i] = 0;
5430
5431                 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5432                         value = strdup(line + l + 1);
5433                         if (!value)
5434                                 return -ENOMEM;
5435
5436                         r = 1;
5437                         break;
5438                 }
5439
5440         } while (!done);
5441
5442         *_value = value;
5443         return r;
5444 }
5445
5446 bool is_valid_documentation_url(const char *url) {
5447         assert(url);
5448
5449         if (startswith(url, "http://") && url[7])
5450                 return true;
5451
5452         if (startswith(url, "https://") && url[8])
5453                 return true;
5454
5455         if (startswith(url, "file:") && url[5])
5456                 return true;
5457
5458         if (startswith(url, "info:") && url[5])
5459                 return true;
5460
5461         if (startswith(url, "man:") && url[4])
5462                 return true;
5463
5464         return false;
5465 }
5466
5467 bool in_initrd(void) {
5468         static int saved = -1;
5469         struct statfs s;
5470
5471         if (saved >= 0)
5472                 return saved;
5473
5474         /* We make two checks here:
5475          *
5476          * 1. the flag file /etc/initrd-release must exist
5477          * 2. the root file system must be a memory file system
5478          *
5479          * The second check is extra paranoia, since misdetecting an
5480          * initrd can have bad bad consequences due the initrd
5481          * emptying when transititioning to the main systemd.
5482          */
5483
5484         saved = access("/etc/initrd-release", F_OK) >= 0 &&
5485                 statfs("/", &s) >= 0 &&
5486                 is_temporary_fs(&s);
5487
5488         return saved;
5489 }
5490
5491 void warn_melody(void) {
5492         _cleanup_close_ int fd = -1;
5493
5494         fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5495         if (fd < 0)
5496                 return;
5497
5498         /* Yeah, this is synchronous. Kinda sucks. But well... */
5499
5500         ioctl(fd, KIOCSOUND, (int)(1193180/440));
5501         usleep(125*USEC_PER_MSEC);
5502
5503         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5504         usleep(125*USEC_PER_MSEC);
5505
5506         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5507         usleep(125*USEC_PER_MSEC);
5508
5509         ioctl(fd, KIOCSOUND, 0);
5510 }
5511
5512 int make_console_stdio(void) {
5513         int fd, r;
5514
5515         /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5516
5517         fd = acquire_terminal("/dev/console", false, true, true, USEC_INFINITY);
5518         if (fd < 0)
5519                 return log_error_errno(fd, "Failed to acquire terminal: %m");
5520
5521         r = make_stdio(fd);
5522         if (r < 0)
5523                 return log_error_errno(r, "Failed to duplicate terminal fd: %m");
5524
5525         return 0;
5526 }
5527
5528 int get_home_dir(char **_h) {
5529         struct passwd *p;
5530         const char *e;
5531         char *h;
5532         uid_t u;
5533
5534         assert(_h);
5535
5536         /* Take the user specified one */
5537         e = secure_getenv("HOME");
5538         if (e && path_is_absolute(e)) {
5539                 h = strdup(e);
5540                 if (!h)
5541                         return -ENOMEM;
5542
5543                 *_h = h;
5544                 return 0;
5545         }
5546
5547         /* Hardcode home directory for root to avoid NSS */
5548         u = getuid();
5549         if (u == 0) {
5550                 h = strdup("/root");
5551                 if (!h)
5552                         return -ENOMEM;
5553
5554                 *_h = h;
5555                 return 0;
5556         }
5557
5558         /* Check the database... */
5559         errno = 0;
5560         p = getpwuid(u);
5561         if (!p)
5562                 return errno > 0 ? -errno : -ESRCH;
5563
5564         if (!path_is_absolute(p->pw_dir))
5565                 return -EINVAL;
5566
5567         h = strdup(p->pw_dir);
5568         if (!h)
5569                 return -ENOMEM;
5570
5571         *_h = h;
5572         return 0;
5573 }
5574
5575 int get_shell(char **_s) {
5576         struct passwd *p;
5577         const char *e;
5578         char *s;
5579         uid_t u;
5580
5581         assert(_s);
5582
5583         /* Take the user specified one */
5584         e = getenv("SHELL");
5585         if (e) {
5586                 s = strdup(e);
5587                 if (!s)
5588                         return -ENOMEM;
5589
5590                 *_s = s;
5591                 return 0;
5592         }
5593
5594         /* Hardcode home directory for root to avoid NSS */
5595         u = getuid();
5596         if (u == 0) {
5597                 s = strdup("/bin/sh");
5598                 if (!s)
5599                         return -ENOMEM;
5600
5601                 *_s = s;
5602                 return 0;
5603         }
5604
5605         /* Check the database... */
5606         errno = 0;
5607         p = getpwuid(u);
5608         if (!p)
5609                 return errno > 0 ? -errno : -ESRCH;
5610
5611         if (!path_is_absolute(p->pw_shell))
5612                 return -EINVAL;
5613
5614         s = strdup(p->pw_shell);
5615         if (!s)
5616                 return -ENOMEM;
5617
5618         *_s = s;
5619         return 0;
5620 }
5621
5622 bool filename_is_safe(const char *p) {
5623
5624         if (isempty(p))
5625                 return false;
5626
5627         if (strchr(p, '/'))
5628                 return false;
5629
5630         if (streq(p, "."))
5631                 return false;
5632
5633         if (streq(p, ".."))
5634                 return false;
5635
5636         if (strlen(p) > FILENAME_MAX)
5637                 return false;
5638
5639         return true;
5640 }
5641
5642 bool string_is_safe(const char *p) {
5643         const char *t;
5644
5645         if (!p)
5646                 return false;
5647
5648         for (t = p; *t; t++) {
5649                 if (*t > 0 && *t < ' ')
5650                         return false;
5651
5652                 if (strchr("\\\"\'\0x7f", *t))
5653                         return false;
5654         }
5655
5656         return true;
5657 }
5658
5659 /**
5660  * Check if a string contains control characters. If 'ok' is non-NULL
5661  * it may be a string containing additional CCs to be considered OK.
5662  */
5663 bool string_has_cc(const char *p, const char *ok) {
5664         const char *t;
5665
5666         assert(p);
5667
5668         for (t = p; *t; t++) {
5669                 if (ok && strchr(ok, *t))
5670                         continue;
5671
5672                 if (*t > 0 && *t < ' ')
5673                         return true;
5674
5675                 if (*t == 127)
5676                         return true;
5677         }
5678
5679         return false;
5680 }
5681
5682 bool path_is_safe(const char *p) {
5683
5684         if (isempty(p))
5685                 return false;
5686
5687         if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5688                 return false;
5689
5690         if (strlen(p) > PATH_MAX)
5691                 return false;
5692
5693         /* The following two checks are not really dangerous, but hey, they still are confusing */
5694         if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5695                 return false;
5696
5697         if (strstr(p, "//"))
5698                 return false;
5699
5700         return true;
5701 }
5702
5703 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5704 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5705                  int (*compar) (const void *, const void *, void *), void *arg) {
5706         size_t l, u, idx;
5707         const void *p;
5708         int comparison;
5709
5710         l = 0;
5711         u = nmemb;
5712         while (l < u) {
5713                 idx = (l + u) / 2;
5714                 p = (void *)(((const char *) base) + (idx * size));
5715                 comparison = compar(key, p, arg);
5716                 if (comparison < 0)
5717                         u = idx;
5718                 else if (comparison > 0)
5719                         l = idx + 1;
5720                 else
5721                         return (void *)p;
5722         }
5723         return NULL;
5724 }
5725
5726 bool is_locale_utf8(void) {
5727         const char *set;
5728         static int cached_answer = -1;
5729
5730         if (cached_answer >= 0)
5731                 goto out;
5732
5733         if (!setlocale(LC_ALL, "")) {
5734                 cached_answer = true;
5735                 goto out;
5736         }
5737
5738         set = nl_langinfo(CODESET);
5739         if (!set) {
5740                 cached_answer = true;
5741                 goto out;
5742         }
5743
5744         if (streq(set, "UTF-8")) {
5745                 cached_answer = true;
5746                 goto out;
5747         }
5748
5749         /* For LC_CTYPE=="C" return true, because CTYPE is effectly
5750          * unset and everything can do to UTF-8 nowadays. */
5751         set = setlocale(LC_CTYPE, NULL);
5752         if (!set) {
5753                 cached_answer = true;
5754                 goto out;
5755         }
5756
5757         /* Check result, but ignore the result if C was set
5758          * explicitly. */
5759         cached_answer =
5760                 streq(set, "C") &&
5761                 !getenv("LC_ALL") &&
5762                 !getenv("LC_CTYPE") &&
5763                 !getenv("LANG");
5764
5765 out:
5766         return (bool) cached_answer;
5767 }
5768
5769 const char *draw_special_char(DrawSpecialChar ch) {
5770         static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5771
5772                 /* UTF-8 */ {
5773                         [DRAW_TREE_VERTICAL]      = "\342\224\202 ",            /* │  */
5774                         [DRAW_TREE_BRANCH]        = "\342\224\234\342\224\200", /* ├─ */
5775                         [DRAW_TREE_RIGHT]         = "\342\224\224\342\224\200", /* └─ */
5776                         [DRAW_TREE_SPACE]         = "  ",                       /*    */
5777                         [DRAW_TRIANGULAR_BULLET]  = "\342\200\243",             /* ‣ */
5778                         [DRAW_BLACK_CIRCLE]       = "\342\227\217",             /* ● */
5779                         [DRAW_ARROW]              = "\342\206\222",             /* → */
5780                         [DRAW_DASH]               = "\342\200\223",             /* – */
5781                 },
5782
5783                 /* ASCII fallback */ {
5784                         [DRAW_TREE_VERTICAL]      = "| ",
5785                         [DRAW_TREE_BRANCH]        = "|-",
5786                         [DRAW_TREE_RIGHT]         = "`-",
5787                         [DRAW_TREE_SPACE]         = "  ",
5788                         [DRAW_TRIANGULAR_BULLET]  = ">",
5789                         [DRAW_BLACK_CIRCLE]       = "*",
5790                         [DRAW_ARROW]              = "->",
5791                         [DRAW_DASH]               = "-",
5792                 }
5793         };
5794
5795         return draw_table[!is_locale_utf8()][ch];
5796 }
5797
5798 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5799         const char *f;
5800         char *t, *r;
5801         size_t l, old_len, new_len;
5802
5803         assert(text);
5804         assert(old_string);
5805         assert(new_string);
5806
5807         old_len = strlen(old_string);
5808         new_len = strlen(new_string);
5809
5810         l = strlen(text);
5811         r = new(char, l+1);
5812         if (!r)
5813                 return NULL;
5814
5815         f = text;
5816         t = r;
5817         while (*f) {
5818                 char *a;
5819                 size_t d, nl;
5820
5821                 if (!startswith(f, old_string)) {
5822                         *(t++) = *(f++);
5823                         continue;
5824                 }
5825
5826                 d = t - r;
5827                 nl = l - old_len + new_len;
5828                 a = realloc(r, nl + 1);
5829                 if (!a)
5830                         goto oom;
5831
5832                 l = nl;
5833                 r = a;
5834                 t = r + d;
5835
5836                 t = stpcpy(t, new_string);
5837                 f += old_len;
5838         }
5839
5840         *t = 0;
5841         return r;
5842
5843 oom:
5844         free(r);
5845         return NULL;
5846 }
5847
5848 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5849         const char *i, *begin = NULL;
5850         enum {
5851                 STATE_OTHER,
5852                 STATE_ESCAPE,
5853                 STATE_BRACKET
5854         } state = STATE_OTHER;
5855         char *obuf = NULL;
5856         size_t osz = 0, isz;
5857         FILE *f;
5858
5859         assert(ibuf);
5860         assert(*ibuf);
5861
5862         /* Strips ANSI color and replaces TABs by 8 spaces */
5863
5864         isz = _isz ? *_isz : strlen(*ibuf);
5865
5866         f = open_memstream(&obuf, &osz);
5867         if (!f)
5868                 return NULL;
5869
5870         for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5871
5872                 switch (state) {
5873
5874                 case STATE_OTHER:
5875                         if (i >= *ibuf + isz) /* EOT */
5876                                 break;
5877                         else if (*i == '\x1B')
5878                                 state = STATE_ESCAPE;
5879                         else if (*i == '\t')
5880                                 fputs("        ", f);
5881                         else
5882                                 fputc(*i, f);
5883                         break;
5884
5885                 case STATE_ESCAPE:
5886                         if (i >= *ibuf + isz) { /* EOT */
5887                                 fputc('\x1B', f);
5888                                 break;
5889                         } else if (*i == '[') {
5890                                 state = STATE_BRACKET;
5891                                 begin = i + 1;
5892                         } else {
5893                                 fputc('\x1B', f);
5894                                 fputc(*i, f);
5895                                 state = STATE_OTHER;
5896                         }
5897
5898                         break;
5899
5900                 case STATE_BRACKET:
5901
5902                         if (i >= *ibuf + isz || /* EOT */
5903                             (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5904                                 fputc('\x1B', f);
5905                                 fputc('[', f);
5906                                 state = STATE_OTHER;
5907                                 i = begin-1;
5908                         } else if (*i == 'm')
5909                                 state = STATE_OTHER;
5910                         break;
5911                 }
5912         }
5913
5914         if (ferror(f)) {
5915                 fclose(f);
5916                 free(obuf);
5917                 return NULL;
5918         }
5919
5920         fclose(f);
5921
5922         free(*ibuf);
5923         *ibuf = obuf;
5924
5925         if (_isz)
5926                 *_isz = osz;
5927
5928         return obuf;
5929 }
5930
5931 int on_ac_power(void) {
5932         bool found_offline = false, found_online = false;
5933         _cleanup_closedir_ DIR *d = NULL;
5934
5935         d = opendir("/sys/class/power_supply");
5936         if (!d)
5937                 return -errno;
5938
5939         for (;;) {
5940                 struct dirent *de;
5941                 _cleanup_close_ int fd = -1, device = -1;
5942                 char contents[6];
5943                 ssize_t n;
5944
5945                 errno = 0;
5946                 de = readdir(d);
5947                 if (!de && errno != 0)
5948                         return -errno;
5949
5950                 if (!de)
5951                         break;
5952
5953                 if (ignore_file(de->d_name))
5954                         continue;
5955
5956                 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5957                 if (device < 0) {
5958                         if (errno == ENOENT || errno == ENOTDIR)
5959                                 continue;
5960
5961                         return -errno;
5962                 }
5963
5964                 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5965                 if (fd < 0) {
5966                         if (errno == ENOENT)
5967                                 continue;
5968
5969                         return -errno;
5970                 }
5971
5972                 n = read(fd, contents, sizeof(contents));
5973                 if (n < 0)
5974                         return -errno;
5975
5976                 if (n != 6 || memcmp(contents, "Mains\n", 6))
5977                         continue;
5978
5979                 safe_close(fd);
5980                 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5981                 if (fd < 0) {
5982                         if (errno == ENOENT)
5983                                 continue;
5984
5985                         return -errno;
5986                 }
5987
5988                 n = read(fd, contents, sizeof(contents));
5989                 if (n < 0)
5990                         return -errno;
5991
5992                 if (n != 2 || contents[1] != '\n')
5993                         return -EIO;
5994
5995                 if (contents[0] == '1') {
5996                         found_online = true;
5997                         break;
5998                 } else if (contents[0] == '0')
5999                         found_offline = true;
6000                 else
6001                         return -EIO;
6002         }
6003
6004         return found_online || !found_offline;
6005 }
6006
6007 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
6008         char **i;
6009
6010         assert(path);
6011         assert(mode);
6012         assert(_f);
6013
6014         if (!path_strv_resolve_uniq(search, root))
6015                 return -ENOMEM;
6016
6017         STRV_FOREACH(i, search) {
6018                 _cleanup_free_ char *p = NULL;
6019                 FILE *f;
6020
6021                 if (root)
6022                         p = strjoin(root, *i, "/", path, NULL);
6023                 else
6024                         p = strjoin(*i, "/", path, NULL);
6025                 if (!p)
6026                         return -ENOMEM;
6027
6028                 f = fopen(p, mode);
6029                 if (f) {
6030                         *_f = f;
6031                         return 0;
6032                 }
6033
6034                 if (errno != ENOENT)
6035                         return -errno;
6036         }
6037
6038         return -ENOENT;
6039 }
6040
6041 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
6042         _cleanup_strv_free_ char **copy = NULL;
6043
6044         assert(path);
6045         assert(mode);
6046         assert(_f);
6047
6048         if (path_is_absolute(path)) {
6049                 FILE *f;
6050
6051                 f = fopen(path, mode);
6052                 if (f) {
6053                         *_f = f;
6054                         return 0;
6055                 }
6056
6057                 return -errno;
6058         }
6059
6060         copy = strv_copy((char**) search);
6061         if (!copy)
6062                 return -ENOMEM;
6063
6064         return search_and_fopen_internal(path, mode, root, copy, _f);
6065 }
6066
6067 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
6068         _cleanup_strv_free_ char **s = NULL;
6069
6070         if (path_is_absolute(path)) {
6071                 FILE *f;
6072
6073                 f = fopen(path, mode);
6074                 if (f) {
6075                         *_f = f;
6076                         return 0;
6077                 }
6078
6079                 return -errno;
6080         }
6081
6082         s = strv_split_nulstr(search);
6083         if (!s)
6084                 return -ENOMEM;
6085
6086         return search_and_fopen_internal(path, mode, root, s, _f);
6087 }
6088
6089 char *strextend(char **x, ...) {
6090         va_list ap;
6091         size_t f, l;
6092         char *r, *p;
6093
6094         assert(x);
6095
6096         l = f = *x ? strlen(*x) : 0;
6097
6098         va_start(ap, x);
6099         for (;;) {
6100                 const char *t;
6101                 size_t n;
6102
6103                 t = va_arg(ap, const char *);
6104                 if (!t)
6105                         break;
6106
6107                 n = strlen(t);
6108                 if (n > ((size_t) -1) - l) {
6109                         va_end(ap);
6110                         return NULL;
6111                 }
6112
6113                 l += n;
6114         }
6115         va_end(ap);
6116
6117         r = realloc(*x, l+1);
6118         if (!r)
6119                 return NULL;
6120
6121         p = r + f;
6122
6123         va_start(ap, x);
6124         for (;;) {
6125                 const char *t;
6126
6127                 t = va_arg(ap, const char *);
6128                 if (!t)
6129                         break;
6130
6131                 p = stpcpy(p, t);
6132         }
6133         va_end(ap);
6134
6135         *p = 0;
6136         *x = r;
6137
6138         return r + l;
6139 }
6140
6141 char *strrep(const char *s, unsigned n) {
6142         size_t l;
6143         char *r, *p;
6144         unsigned i;
6145
6146         assert(s);
6147
6148         l = strlen(s);
6149         p = r = malloc(l * n + 1);
6150         if (!r)
6151                 return NULL;
6152
6153         for (i = 0; i < n; i++)
6154                 p = stpcpy(p, s);
6155
6156         *p = 0;
6157         return r;
6158 }
6159
6160 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
6161         size_t a, newalloc;
6162         void *q;
6163
6164         assert(p);
6165         assert(allocated);
6166
6167         if (*allocated >= need)
6168                 return *p;
6169
6170         newalloc = MAX(need * 2, 64u / size);
6171         a = newalloc * size;
6172
6173         /* check for overflows */
6174         if (a < size * need)
6175                 return NULL;
6176
6177         q = realloc(*p, a);
6178         if (!q)
6179                 return NULL;
6180
6181         *p = q;
6182         *allocated = newalloc;
6183         return q;
6184 }
6185
6186 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
6187         size_t prev;
6188         uint8_t *q;
6189
6190         assert(p);
6191         assert(allocated);
6192
6193         prev = *allocated;
6194
6195         q = greedy_realloc(p, allocated, need, size);
6196         if (!q)
6197                 return NULL;
6198
6199         if (*allocated > prev)
6200                 memzero(q + prev * size, (*allocated - prev) * size);
6201
6202         return q;
6203 }
6204
6205 bool id128_is_valid(const char *s) {
6206         size_t i, l;
6207
6208         l = strlen(s);
6209         if (l == 32) {
6210
6211                 /* Simple formatted 128bit hex string */
6212
6213                 for (i = 0; i < l; i++) {
6214                         char c = s[i];
6215
6216                         if (!(c >= '0' && c <= '9') &&
6217                             !(c >= 'a' && c <= 'z') &&
6218                             !(c >= 'A' && c <= 'Z'))
6219                                 return false;
6220                 }
6221
6222         } else if (l == 36) {
6223
6224                 /* Formatted UUID */
6225
6226                 for (i = 0; i < l; i++) {
6227                         char c = s[i];
6228
6229                         if ((i == 8 || i == 13 || i == 18 || i == 23)) {
6230                                 if (c != '-')
6231                                         return false;
6232                         } else {
6233                                 if (!(c >= '0' && c <= '9') &&
6234                                     !(c >= 'a' && c <= 'z') &&
6235                                     !(c >= 'A' && c <= 'Z'))
6236                                         return false;
6237                         }
6238                 }
6239
6240         } else
6241                 return false;
6242
6243         return true;
6244 }
6245
6246 int split_pair(const char *s, const char *sep, char **l, char **r) {
6247         char *x, *a, *b;
6248
6249         assert(s);
6250         assert(sep);
6251         assert(l);
6252         assert(r);
6253
6254         if (isempty(sep))
6255                 return -EINVAL;
6256
6257         x = strstr(s, sep);
6258         if (!x)
6259                 return -EINVAL;
6260
6261         a = strndup(s, x - s);
6262         if (!a)
6263                 return -ENOMEM;
6264
6265         b = strdup(x + strlen(sep));
6266         if (!b) {
6267                 free(a);
6268                 return -ENOMEM;
6269         }
6270
6271         *l = a;
6272         *r = b;
6273
6274         return 0;
6275 }
6276
6277 int shall_restore_state(void) {
6278         _cleanup_free_ char *value = NULL;
6279         int r;
6280
6281         r = get_proc_cmdline_key("systemd.restore_state=", &value);
6282         if (r < 0)
6283                 return r;
6284         if (r == 0)
6285                 return true;
6286
6287         return parse_boolean(value) != 0;
6288 }
6289
6290 int proc_cmdline(char **ret) {
6291         assert(ret);
6292
6293         if (detect_container(NULL) > 0)
6294                 return get_process_cmdline(1, 0, false, ret);
6295         else
6296                 return read_one_line_file("/proc/cmdline", ret);
6297 }
6298
6299 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
6300         _cleanup_free_ char *line = NULL;
6301         const char *p;
6302         int r;
6303
6304         assert(parse_item);
6305
6306         r = proc_cmdline(&line);
6307         if (r < 0)
6308                 return r;
6309
6310         p = line;
6311         for (;;) {
6312                 _cleanup_free_ char *word = NULL;
6313                 char *value = NULL;
6314
6315                 r = unquote_first_word(&p, &word, true);
6316                 if (r < 0)
6317                         return r;
6318                 if (r == 0)
6319                         break;
6320
6321                 /* Filter out arguments that are intended only for the
6322                  * initrd */
6323                 if (!in_initrd() && startswith(word, "rd."))
6324                         continue;
6325
6326                 value = strchr(word, '=');
6327                 if (value)
6328                         *(value++) = 0;
6329
6330                 r = parse_item(word, value);
6331                 if (r < 0)
6332                         return r;
6333         }
6334
6335         return 0;
6336 }
6337
6338 int get_proc_cmdline_key(const char *key, char **value) {
6339         _cleanup_free_ char *line = NULL, *ret = NULL;
6340         bool found = false;
6341         const char *p;
6342         int r;
6343
6344         assert(key);
6345
6346         r = proc_cmdline(&line);
6347         if (r < 0)
6348                 return r;
6349
6350         p = line;
6351         for (;;) {
6352                 _cleanup_free_ char *word = NULL;
6353                 const char *e;
6354
6355                 r = unquote_first_word(&p, &word, true);
6356                 if (r < 0)
6357                         return r;
6358                 if (r == 0)
6359                         break;
6360
6361                 /* Filter out arguments that are intended only for the
6362                  * initrd */
6363                 if (!in_initrd() && startswith(word, "rd."))
6364                         continue;
6365
6366                 if (value) {
6367                         e = startswith(word, key);
6368                         if (!e)
6369                                 continue;
6370
6371                         r = free_and_strdup(&ret, e);
6372                         if (r < 0)
6373                                 return r;
6374
6375                         found = true;
6376                 } else {
6377                         if (streq(word, key))
6378                                 found = true;
6379                 }
6380         }
6381
6382         if (value) {
6383                 *value = ret;
6384                 ret = NULL;
6385         }
6386
6387         return found;
6388
6389 }
6390
6391 int container_get_leader(const char *machine, pid_t *pid) {
6392         _cleanup_free_ char *s = NULL, *class = NULL;
6393         const char *p;
6394         pid_t leader;
6395         int r;
6396
6397         assert(machine);
6398         assert(pid);
6399
6400         p = strappenda("/run/systemd/machines/", machine);
6401         r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
6402         if (r == -ENOENT)
6403                 return -EHOSTDOWN;
6404         if (r < 0)
6405                 return r;
6406         if (!s)
6407                 return -EIO;
6408
6409         if (!streq_ptr(class, "container"))
6410                 return -EIO;
6411
6412         r = parse_pid(s, &leader);
6413         if (r < 0)
6414                 return r;
6415         if (leader <= 1)
6416                 return -EIO;
6417
6418         *pid = leader;
6419         return 0;
6420 }
6421
6422 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
6423         _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
6424         int rfd = -1;
6425
6426         assert(pid >= 0);
6427
6428         if (mntns_fd) {
6429                 const char *mntns;
6430
6431                 mntns = procfs_file_alloca(pid, "ns/mnt");
6432                 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6433                 if (mntnsfd < 0)
6434                         return -errno;
6435         }
6436
6437         if (pidns_fd) {
6438                 const char *pidns;
6439
6440                 pidns = procfs_file_alloca(pid, "ns/pid");
6441                 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6442                 if (pidnsfd < 0)
6443                         return -errno;
6444         }
6445
6446         if (netns_fd) {
6447                 const char *netns;
6448
6449                 netns = procfs_file_alloca(pid, "ns/net");
6450                 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6451                 if (netnsfd < 0)
6452                         return -errno;
6453         }
6454
6455         if (root_fd) {
6456                 const char *root;
6457
6458                 root = procfs_file_alloca(pid, "root");
6459                 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
6460                 if (rfd < 0)
6461                         return -errno;
6462         }
6463
6464         if (pidns_fd)
6465                 *pidns_fd = pidnsfd;
6466
6467         if (mntns_fd)
6468                 *mntns_fd = mntnsfd;
6469
6470         if (netns_fd)
6471                 *netns_fd = netnsfd;
6472
6473         if (root_fd)
6474                 *root_fd = rfd;
6475
6476         pidnsfd = mntnsfd = netnsfd = -1;
6477
6478         return 0;
6479 }
6480
6481 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
6482
6483         if (pidns_fd >= 0)
6484                 if (setns(pidns_fd, CLONE_NEWPID) < 0)
6485                         return -errno;
6486
6487         if (mntns_fd >= 0)
6488                 if (setns(mntns_fd, CLONE_NEWNS) < 0)
6489                         return -errno;
6490
6491         if (netns_fd >= 0)
6492                 if (setns(netns_fd, CLONE_NEWNET) < 0)
6493                         return -errno;
6494
6495         if (root_fd >= 0) {
6496                 if (fchdir(root_fd) < 0)
6497                         return -errno;
6498
6499                 if (chroot(".") < 0)
6500                         return -errno;
6501         }
6502
6503         if (setresgid(0, 0, 0) < 0)
6504                 return -errno;
6505
6506         if (setgroups(0, NULL) < 0)
6507                 return -errno;
6508
6509         if (setresuid(0, 0, 0) < 0)
6510                 return -errno;
6511
6512         return 0;
6513 }
6514
6515 bool pid_is_unwaited(pid_t pid) {
6516         /* Checks whether a PID is still valid at all, including a zombie */
6517
6518         if (pid <= 0)
6519                 return false;
6520
6521         if (kill(pid, 0) >= 0)
6522                 return true;
6523
6524         return errno != ESRCH;
6525 }
6526
6527 bool pid_is_alive(pid_t pid) {
6528         int r;
6529
6530         /* Checks whether a PID is still valid and not a zombie */
6531
6532         if (pid <= 0)
6533                 return false;
6534
6535         r = get_process_state(pid);
6536         if (r == -ENOENT || r == 'Z')
6537                 return false;
6538
6539         return true;
6540 }
6541
6542 int getpeercred(int fd, struct ucred *ucred) {
6543         socklen_t n = sizeof(struct ucred);
6544         struct ucred u;
6545         int r;
6546
6547         assert(fd >= 0);
6548         assert(ucred);
6549
6550         r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
6551         if (r < 0)
6552                 return -errno;
6553
6554         if (n != sizeof(struct ucred))
6555                 return -EIO;
6556
6557         /* Check if the data is actually useful and not suppressed due
6558          * to namespacing issues */
6559         if (u.pid <= 0)
6560                 return -ENODATA;
6561         if (u.uid == UID_INVALID)
6562                 return -ENODATA;
6563         if (u.gid == GID_INVALID)
6564                 return -ENODATA;
6565
6566         *ucred = u;
6567         return 0;
6568 }
6569
6570 int getpeersec(int fd, char **ret) {
6571         socklen_t n = 64;
6572         char *s;
6573         int r;
6574
6575         assert(fd >= 0);
6576         assert(ret);
6577
6578         s = new0(char, n);
6579         if (!s)
6580                 return -ENOMEM;
6581
6582         r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6583         if (r < 0) {
6584                 free(s);
6585
6586                 if (errno != ERANGE)
6587                         return -errno;
6588
6589                 s = new0(char, n);
6590                 if (!s)
6591                         return -ENOMEM;
6592
6593                 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6594                 if (r < 0) {
6595                         free(s);
6596                         return -errno;
6597                 }
6598         }
6599
6600         if (isempty(s)) {
6601                 free(s);
6602                 return -ENOTSUP;
6603         }
6604
6605         *ret = s;
6606         return 0;
6607 }
6608
6609 /* This is much like like mkostemp() but is subject to umask(). */
6610 int mkostemp_safe(char *pattern, int flags) {
6611         _cleanup_umask_ mode_t u;
6612         int fd;
6613
6614         assert(pattern);
6615
6616         u = umask(077);
6617
6618         fd = mkostemp(pattern, flags);
6619         if (fd < 0)
6620                 return -errno;
6621
6622         return fd;
6623 }
6624
6625 int open_tmpfile(const char *path, int flags) {
6626         char *p;
6627         int fd;
6628
6629         assert(path);
6630
6631 #ifdef O_TMPFILE
6632         /* Try O_TMPFILE first, if it is supported */
6633         fd = open(path, flags|O_TMPFILE, S_IRUSR|S_IWUSR);
6634         if (fd >= 0)
6635                 return fd;
6636 #endif
6637
6638         /* Fall back to unguessable name + unlinking */
6639         p = strappenda(path, "/systemd-tmp-XXXXXX");
6640
6641         fd = mkostemp_safe(p, flags);
6642         if (fd < 0)
6643                 return fd;
6644
6645         unlink(p);
6646         return fd;
6647 }
6648
6649 int fd_warn_permissions(const char *path, int fd) {
6650         struct stat st;
6651
6652         if (fstat(fd, &st) < 0)
6653                 return -errno;
6654
6655         if (st.st_mode & 0111)
6656                 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
6657
6658         if (st.st_mode & 0002)
6659                 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
6660
6661         if (getpid() == 1 && (st.st_mode & 0044) != 0044)
6662                 log_warning("Configuration file %s is marked world-inaccessible. This has no effect as configuration data is accessible via APIs without restrictions. Proceeding anyway.", path);
6663
6664         return 0;
6665 }
6666
6667 unsigned long personality_from_string(const char *p) {
6668
6669         /* Parse a personality specifier. We introduce our own
6670          * identifiers that indicate specific ABIs, rather than just
6671          * hints regarding the register size, since we want to keep
6672          * things open for multiple locally supported ABIs for the
6673          * same register size. We try to reuse the ABI identifiers
6674          * used by libseccomp. */
6675
6676 #if defined(__x86_64__)
6677
6678         if (streq(p, "x86"))
6679                 return PER_LINUX32;
6680
6681         if (streq(p, "x86-64"))
6682                 return PER_LINUX;
6683
6684 #elif defined(__i386__)
6685
6686         if (streq(p, "x86"))
6687                 return PER_LINUX;
6688 #endif
6689
6690         /* personality(7) documents that 0xffffffffUL is used for
6691          * querying the current personality, hence let's use that here
6692          * as error indicator. */
6693         return 0xffffffffUL;
6694 }
6695
6696 const char* personality_to_string(unsigned long p) {
6697
6698 #if defined(__x86_64__)
6699
6700         if (p == PER_LINUX32)
6701                 return "x86";
6702
6703         if (p == PER_LINUX)
6704                 return "x86-64";
6705
6706 #elif defined(__i386__)
6707
6708         if (p == PER_LINUX)
6709                 return "x86";
6710 #endif
6711
6712         return NULL;
6713 }
6714
6715 uint64_t physical_memory(void) {
6716         long mem;
6717
6718         /* We return this as uint64_t in case we are running as 32bit
6719          * process on a 64bit kernel with huge amounts of memory */
6720
6721         mem = sysconf(_SC_PHYS_PAGES);
6722         assert(mem > 0);
6723
6724         return (uint64_t) mem * (uint64_t) page_size();
6725 }
6726
6727 char* mount_test_option(const char *haystack, const char *needle) {
6728
6729         struct mntent me = {
6730                 .mnt_opts = (char*) haystack
6731         };
6732
6733         assert(needle);
6734
6735         /* Like glibc's hasmntopt(), but works on a string, not a
6736          * struct mntent */
6737
6738         if (!haystack)
6739                 return NULL;
6740
6741         return hasmntopt(&me, needle);
6742 }
6743
6744 void hexdump(FILE *f, const void *p, size_t s) {
6745         const uint8_t *b = p;
6746         unsigned n = 0;
6747
6748         assert(s == 0 || b);
6749
6750         while (s > 0) {
6751                 size_t i;
6752
6753                 fprintf(f, "%04x  ", n);
6754
6755                 for (i = 0; i < 16; i++) {
6756
6757                         if (i >= s)
6758                                 fputs("   ", f);
6759                         else
6760                                 fprintf(f, "%02x ", b[i]);
6761
6762                         if (i == 7)
6763                                 fputc(' ', f);
6764                 }
6765
6766                 fputc(' ', f);
6767
6768                 for (i = 0; i < 16; i++) {
6769
6770                         if (i >= s)
6771                                 fputc(' ', f);
6772                         else
6773                                 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
6774                 }
6775
6776                 fputc('\n', f);
6777
6778                 if (s < 16)
6779                         break;
6780
6781                 n += 16;
6782                 b += 16;
6783                 s -= 16;
6784         }
6785 }
6786
6787 int update_reboot_param_file(const char *param) {
6788         int r = 0;
6789
6790         if (param) {
6791
6792                 r = write_string_file(REBOOT_PARAM_FILE, param);
6793                 if (r < 0)
6794                         log_error("Failed to write reboot param to "
6795                                   REBOOT_PARAM_FILE": %s", strerror(-r));
6796         } else
6797                 unlink(REBOOT_PARAM_FILE);
6798
6799         return r;
6800 }
6801
6802 int umount_recursive(const char *prefix, int flags) {
6803         bool again;
6804         int n = 0, r;
6805
6806         /* Try to umount everything recursively below a
6807          * directory. Also, take care of stacked mounts, and keep
6808          * unmounting them until they are gone. */
6809
6810         do {
6811                 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6812
6813                 again = false;
6814                 r = 0;
6815
6816                 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6817                 if (!proc_self_mountinfo)
6818                         return -errno;
6819
6820                 for (;;) {
6821                         _cleanup_free_ char *path = NULL, *p = NULL;
6822                         int k;
6823
6824                         k = fscanf(proc_self_mountinfo,
6825                                    "%*s "       /* (1) mount id */
6826                                    "%*s "       /* (2) parent id */
6827                                    "%*s "       /* (3) major:minor */
6828                                    "%*s "       /* (4) root */
6829                                    "%ms "       /* (5) mount point */
6830                                    "%*s"        /* (6) mount options */
6831                                    "%*[^-]"     /* (7) optional fields */
6832                                    "- "         /* (8) separator */
6833                                    "%*s "       /* (9) file system type */
6834                                    "%*s"        /* (10) mount source */
6835                                    "%*s"        /* (11) mount options 2 */
6836                                    "%*[^\n]",   /* some rubbish at the end */
6837                                    &path);
6838                         if (k != 1) {
6839                                 if (k == EOF)
6840                                         break;
6841
6842                                 continue;
6843                         }
6844
6845                         p = cunescape(path);
6846                         if (!p)
6847                                 return -ENOMEM;
6848
6849                         if (!path_startswith(p, prefix))
6850                                 continue;
6851
6852                         if (umount2(p, flags) < 0) {
6853                                 r = -errno;
6854                                 continue;
6855                         }
6856
6857                         again = true;
6858                         n++;
6859
6860                         break;
6861                 }
6862
6863         } while (again);
6864
6865         return r ? r : n;
6866 }
6867
6868 int bind_remount_recursive(const char *prefix, bool ro) {
6869         _cleanup_set_free_free_ Set *done = NULL;
6870         _cleanup_free_ char *cleaned = NULL;
6871         int r;
6872
6873         /* Recursively remount a directory (and all its submounts)
6874          * read-only or read-write. If the directory is already
6875          * mounted, we reuse the mount and simply mark it
6876          * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
6877          * operation). If it isn't we first make it one. Afterwards we
6878          * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
6879          * submounts we can access, too. When mounts are stacked on
6880          * the same mount point we only care for each individual
6881          * "top-level" mount on each point, as we cannot
6882          * influence/access the underlying mounts anyway. We do not
6883          * have any effect on future submounts that might get
6884          * propagated, they migt be writable. This includes future
6885          * submounts that have been triggered via autofs. */
6886
6887         cleaned = strdup(prefix);
6888         if (!cleaned)
6889                 return -ENOMEM;
6890
6891         path_kill_slashes(cleaned);
6892
6893         done = set_new(&string_hash_ops);
6894         if (!done)
6895                 return -ENOMEM;
6896
6897         for (;;) {
6898                 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6899                 _cleanup_set_free_free_ Set *todo = NULL;
6900                 bool top_autofs = false;
6901                 char *x;
6902
6903                 todo = set_new(&string_hash_ops);
6904                 if (!todo)
6905                         return -ENOMEM;
6906
6907                 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6908                 if (!proc_self_mountinfo)
6909                         return -errno;
6910
6911                 for (;;) {
6912                         _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
6913                         int k;
6914
6915                         k = fscanf(proc_self_mountinfo,
6916                                    "%*s "       /* (1) mount id */
6917                                    "%*s "       /* (2) parent id */
6918                                    "%*s "       /* (3) major:minor */
6919                                    "%*s "       /* (4) root */
6920                                    "%ms "       /* (5) mount point */
6921                                    "%*s"        /* (6) mount options (superblock) */
6922                                    "%*[^-]"     /* (7) optional fields */
6923                                    "- "         /* (8) separator */
6924                                    "%ms "       /* (9) file system type */
6925                                    "%*s"        /* (10) mount source */
6926                                    "%*s"        /* (11) mount options (bind mount) */
6927                                    "%*[^\n]",   /* some rubbish at the end */
6928                                    &path,
6929                                    &type);
6930                         if (k != 2) {
6931                                 if (k == EOF)
6932                                         break;
6933
6934                                 continue;
6935                         }
6936
6937                         p = cunescape(path);
6938                         if (!p)
6939                                 return -ENOMEM;
6940
6941                         /* Let's ignore autofs mounts.  If they aren't
6942                          * triggered yet, we want to avoid triggering
6943                          * them, as we don't make any guarantees for
6944                          * future submounts anyway.  If they are
6945                          * already triggered, then we will find
6946                          * another entry for this. */
6947                         if (streq(type, "autofs")) {
6948                                 top_autofs = top_autofs || path_equal(cleaned, p);
6949                                 continue;
6950                         }
6951
6952                         if (path_startswith(p, cleaned) &&
6953                             !set_contains(done, p)) {
6954
6955                                 r = set_consume(todo, p);
6956                                 p = NULL;
6957
6958                                 if (r == -EEXIST)
6959                                         continue;
6960                                 if (r < 0)
6961                                         return r;
6962                         }
6963                 }
6964
6965                 /* If we have no submounts to process anymore and if
6966                  * the root is either already done, or an autofs, we
6967                  * are done */
6968                 if (set_isempty(todo) &&
6969                     (top_autofs || set_contains(done, cleaned)))
6970                         return 0;
6971
6972                 if (!set_contains(done, cleaned) &&
6973                     !set_contains(todo, cleaned)) {
6974                         /* The prefix directory itself is not yet a
6975                          * mount, make it one. */
6976                         if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
6977                                 return -errno;
6978
6979                         if (mount(NULL, prefix, NULL, MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
6980                                 return -errno;
6981
6982                         x = strdup(cleaned);
6983                         if (!x)
6984                                 return -ENOMEM;
6985
6986                         r = set_consume(done, x);
6987                         if (r < 0)
6988                                 return r;
6989                 }
6990
6991                 while ((x = set_steal_first(todo))) {
6992
6993                         r = set_consume(done, x);
6994                         if (r == -EEXIST)
6995                                 continue;
6996                         if (r < 0)
6997                                 return r;
6998
6999                         if (mount(NULL, x, NULL, MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
7000
7001                                 /* Deal with mount points that are
7002                                  * obstructed by a later mount */
7003
7004                                 if (errno != ENOENT)
7005                                         return -errno;
7006                         }
7007
7008                 }
7009         }
7010 }
7011
7012 int fflush_and_check(FILE *f) {
7013         assert(f);
7014
7015         errno = 0;
7016         fflush(f);
7017
7018         if (ferror(f))
7019                 return errno ? -errno : -EIO;
7020
7021         return 0;
7022 }
7023
7024 char *tempfn_xxxxxx(const char *p) {
7025         const char *fn;
7026         char *t;
7027         size_t k;
7028
7029         assert(p);
7030
7031         t = new(char, strlen(p) + 1 + 6 + 1);
7032         if (!t)
7033                 return NULL;
7034
7035         fn = basename(p);
7036         k = fn - p;
7037
7038         strcpy(stpcpy(stpcpy(mempcpy(t, p, k), "."), fn), "XXXXXX");
7039
7040         return t;
7041 }
7042
7043 char *tempfn_random(const char *p) {
7044         const char *fn;
7045         char *t, *x;
7046         uint64_t u;
7047         size_t k;
7048         unsigned i;
7049
7050         assert(p);
7051
7052         t = new(char, strlen(p) + 1 + 16 + 1);
7053         if (!t)
7054                 return NULL;
7055
7056         fn = basename(p);
7057         k = fn - p;
7058
7059         x = stpcpy(stpcpy(mempcpy(t, p, k), "."), fn);
7060
7061         u = random_u64();
7062         for (i = 0; i < 16; i++) {
7063                 *(x++) = hexchar(u & 0xF);
7064                 u >>= 4;
7065         }
7066
7067         *x = 0;
7068
7069         return t;
7070 }
7071
7072 /* make sure the hostname is not "localhost" */
7073 bool is_localhost(const char *hostname) {
7074         assert(hostname);
7075
7076         /* This tries to identify local host and domain names
7077          * described in RFC6761 plus the redhatism of .localdomain */
7078
7079         return streq(hostname, "localhost") ||
7080                streq(hostname, "localhost.") ||
7081                streq(hostname, "localdomain.") ||
7082                streq(hostname, "localdomain") ||
7083                endswith(hostname, ".localhost") ||
7084                endswith(hostname, ".localhost.") ||
7085                endswith(hostname, ".localdomain") ||
7086                endswith(hostname, ".localdomain.");
7087 }
7088
7089 int take_password_lock(const char *root) {
7090
7091         struct flock flock = {
7092                 .l_type = F_WRLCK,
7093                 .l_whence = SEEK_SET,
7094                 .l_start = 0,
7095                 .l_len = 0,
7096         };
7097
7098         const char *path;
7099         int fd, r;
7100
7101         /* This is roughly the same as lckpwdf(), but not as awful. We
7102          * don't want to use alarm() and signals, hence we implement
7103          * our own trivial version of this.
7104          *
7105          * Note that shadow-utils also takes per-database locks in
7106          * addition to lckpwdf(). However, we don't given that they
7107          * are redundant as they they invoke lckpwdf() first and keep
7108          * it during everything they do. The per-database locks are
7109          * awfully racy, and thus we just won't do them. */
7110
7111         if (root)
7112                 path = strappenda(root, "/etc/.pwd.lock");
7113         else
7114                 path = "/etc/.pwd.lock";
7115
7116         fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
7117         if (fd < 0)
7118                 return -errno;
7119
7120         r = fcntl(fd, F_SETLKW, &flock);
7121         if (r < 0) {
7122                 safe_close(fd);
7123                 return -errno;
7124         }
7125
7126         return fd;
7127 }
7128
7129 int is_symlink(const char *path) {
7130         struct stat info;
7131
7132         if (lstat(path, &info) < 0)
7133                 return -errno;
7134
7135         return !!S_ISLNK(info.st_mode);
7136 }
7137
7138 int is_dir(const char* path, bool follow) {
7139         struct stat st;
7140         int r;
7141
7142         if (follow)
7143                 r = stat(path, &st);
7144         else
7145                 r = lstat(path, &st);
7146         if (r < 0)
7147                 return -errno;
7148
7149         return !!S_ISDIR(st.st_mode);
7150 }
7151
7152 int unquote_first_word(const char **p, char **ret, bool relax) {
7153         _cleanup_free_ char *s = NULL;
7154         size_t allocated = 0, sz = 0;
7155
7156         enum {
7157                 START,
7158                 VALUE,
7159                 VALUE_ESCAPE,
7160                 SINGLE_QUOTE,
7161                 SINGLE_QUOTE_ESCAPE,
7162                 DOUBLE_QUOTE,
7163                 DOUBLE_QUOTE_ESCAPE,
7164                 SPACE,
7165         } state = START;
7166
7167         assert(p);
7168         assert(*p);
7169         assert(ret);
7170
7171         /* Parses the first word of a string, and returns it in
7172          * *ret. Removes all quotes in the process. When parsing fails
7173          * (because of an uneven number of quotes or similar), leaves
7174          * the pointer *p at the first invalid character. */
7175
7176         for (;;) {
7177                 char c = **p;
7178
7179                 switch (state) {
7180
7181                 case START:
7182                         if (c == 0)
7183                                 goto finish;
7184                         else if (strchr(WHITESPACE, c))
7185                                 break;
7186
7187                         state = VALUE;
7188                         /* fallthrough */
7189
7190                 case VALUE:
7191                         if (c == 0)
7192                                 goto finish;
7193                         else if (c == '\'')
7194                                 state = SINGLE_QUOTE;
7195                         else if (c == '\\')
7196                                 state = VALUE_ESCAPE;
7197                         else if (c == '\"')
7198                                 state = DOUBLE_QUOTE;
7199                         else if (strchr(WHITESPACE, c))
7200                                 state = SPACE;
7201                         else {
7202                                 if (!GREEDY_REALLOC(s, allocated, sz+2))
7203                                         return -ENOMEM;
7204
7205                                 s[sz++] = c;
7206                         }
7207
7208                         break;
7209
7210                 case VALUE_ESCAPE:
7211                         if (c == 0) {
7212                                 if (relax)
7213                                         goto finish;
7214                                 return -EINVAL;
7215                         }
7216
7217                         if (!GREEDY_REALLOC(s, allocated, sz+2))
7218                                 return -ENOMEM;
7219
7220                         s[sz++] = c;
7221                         state = VALUE;
7222
7223                         break;
7224
7225                 case SINGLE_QUOTE:
7226                         if (c == 0) {
7227                                 if (relax)
7228                                         goto finish;
7229                                 return -EINVAL;
7230                         } else if (c == '\'')
7231                                 state = VALUE;
7232                         else if (c == '\\')
7233                                 state = SINGLE_QUOTE_ESCAPE;
7234                         else {
7235                                 if (!GREEDY_REALLOC(s, allocated, sz+2))
7236                                         return -ENOMEM;
7237
7238                                 s[sz++] = c;
7239                         }
7240
7241                         break;
7242
7243                 case SINGLE_QUOTE_ESCAPE:
7244                         if (c == 0) {
7245                                 if (relax)
7246                                         goto finish;
7247                                 return -EINVAL;
7248                         }
7249
7250                         if (!GREEDY_REALLOC(s, allocated, sz+2))
7251                                 return -ENOMEM;
7252
7253                         s[sz++] = c;
7254                         state = SINGLE_QUOTE;
7255                         break;
7256
7257                 case DOUBLE_QUOTE:
7258                         if (c == 0)
7259                                 return -EINVAL;
7260                         else if (c == '\"')
7261                                 state = VALUE;
7262                         else if (c == '\\')
7263                                 state = DOUBLE_QUOTE_ESCAPE;
7264                         else {
7265                                 if (!GREEDY_REALLOC(s, allocated, sz+2))
7266                                         return -ENOMEM;
7267
7268                                 s[sz++] = c;
7269                         }
7270
7271                         break;
7272
7273                 case DOUBLE_QUOTE_ESCAPE:
7274                         if (c == 0) {
7275                                 if (relax)
7276                                         goto finish;
7277                                 return -EINVAL;
7278                         }
7279
7280                         if (!GREEDY_REALLOC(s, allocated, sz+2))
7281                                 return -ENOMEM;
7282
7283                         s[sz++] = c;
7284                         state = DOUBLE_QUOTE;
7285                         break;
7286
7287                 case SPACE:
7288                         if (c == 0)
7289                                 goto finish;
7290                         if (!strchr(WHITESPACE, c))
7291                                 goto finish;
7292
7293                         break;
7294                 }
7295
7296                 (*p) ++;
7297         }
7298
7299 finish:
7300         if (!s) {
7301                 *ret = NULL;
7302                 return 0;
7303         }
7304
7305         s[sz] = 0;
7306         *ret = s;
7307         s = NULL;
7308
7309         return 1;
7310 }
7311
7312 int unquote_many_words(const char **p, ...) {
7313         va_list ap;
7314         char **l;
7315         int n = 0, i, c, r;
7316
7317         /* Parses a number of words from a string, stripping any
7318          * quotes if necessary. */
7319
7320         assert(p);
7321
7322         /* Count how many words are expected */
7323         va_start(ap, p);
7324         for (;;) {
7325                 if (!va_arg(ap, char **))
7326                         break;
7327                 n++;
7328         }
7329         va_end(ap);
7330
7331         if (n <= 0)
7332                 return 0;
7333
7334         /* Read all words into a temporary array */
7335         l = newa0(char*, n);
7336         for (c = 0; c < n; c++) {
7337
7338                 r = unquote_first_word(p, &l[c], false);
7339                 if (r < 0) {
7340                         int j;
7341
7342                         for (j = 0; j < c; j++)
7343                                 free(l[j]);
7344
7345                         return r;
7346                 }
7347
7348                 if (r == 0)
7349                         break;
7350         }
7351
7352         /* If we managed to parse all words, return them in the passed
7353          * in parameters */
7354         va_start(ap, p);
7355         for (i = 0; i < n; i++) {
7356                 char **v;
7357
7358                 v = va_arg(ap, char **);
7359                 assert(v);
7360
7361                 *v = l[i];
7362         }
7363         va_end(ap);
7364
7365         return c;
7366 }
7367
7368 int free_and_strdup(char **p, const char *s) {
7369         char *t;
7370
7371         assert(p);
7372
7373         /* Replaces a string pointer with an strdup()ed new string,
7374          * possibly freeing the old one. */
7375
7376         if (s) {
7377                 t = strdup(s);
7378                 if (!t)
7379                         return -ENOMEM;
7380         } else
7381                 t = NULL;
7382
7383         free(*p);
7384         *p = t;
7385
7386         return 0;
7387 }
7388
7389 int sethostname_idempotent(const char *s) {
7390         int r;
7391         char buf[HOST_NAME_MAX + 1] = {};
7392
7393         assert(s);
7394
7395         r = gethostname(buf, sizeof(buf));
7396         if (r < 0)
7397                 return -errno;
7398
7399         if (streq(buf, s))
7400                 return 0;
7401
7402         r = sethostname(s, strlen(s));
7403         if (r < 0)
7404                 return -errno;
7405
7406         return 1;
7407 }