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