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