chiark / gitweb /
util: remove redundant debug message
[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                         }
4126
4127                         pid = fork();
4128                         if (pid < 0) {
4129                                 log_error_errno(errno, "Failed to fork: %m");
4130                                 continue;
4131                         } else if (pid == 0) {
4132                                 char *_argv[2];
4133
4134                                 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
4135
4136                                 if (!argv) {
4137                                         _argv[0] = path;
4138                                         _argv[1] = NULL;
4139                                         argv = _argv;
4140                                 } else
4141                                         argv[0] = path;
4142
4143                                 execv(path, argv);
4144                                 return log_error_errno(errno, "Failed to execute %s: %m", path);
4145                         }
4146
4147                         log_debug("Spawned %s as " PID_FMT ".", path, pid);
4148
4149                         r = hashmap_put(pids, UINT_TO_PTR(pid), path);
4150                         if (r < 0)
4151                                 return log_oom();
4152                         path = NULL;
4153                 }
4154         }
4155
4156         /* Abort execution of this process after the timout. We simply
4157          * rely on SIGALRM as default action terminating the process,
4158          * and turn on alarm(). */
4159
4160         if (timeout != USEC_INFINITY)
4161                 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
4162
4163         while (!hashmap_isempty(pids)) {
4164                 _cleanup_free_ char *path = NULL;
4165                 pid_t pid;
4166
4167                 pid = PTR_TO_UINT(hashmap_first_key(pids));
4168                 assert(pid > 0);
4169
4170                 path = hashmap_remove(pids, UINT_TO_PTR(pid));
4171                 assert(path);
4172
4173                 wait_for_terminate_and_warn(path, pid, true);
4174         }
4175
4176         return 0;
4177 }
4178
4179 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]) {
4180         pid_t executor_pid;
4181         int r;
4182         char *name;
4183         char **dirs = (char**) directories;
4184
4185         assert(!strv_isempty(dirs));
4186
4187         name = basename(dirs[0]);
4188         assert(!isempty(name));
4189
4190         /* Executes all binaries in the directories in parallel and waits
4191          * for them to finish. Optionally a timeout is applied. If a file
4192          * with the same name exists in more than one directory, the
4193          * earliest one wins. */
4194
4195         executor_pid = fork();
4196         if (executor_pid < 0) {
4197                 log_error_errno(errno, "Failed to fork: %m");
4198                 return;
4199
4200         } else if (executor_pid == 0) {
4201                 r = do_execute(dirs, timeout, argv);
4202                 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
4203         }
4204
4205         wait_for_terminate_and_warn(name, executor_pid, true);
4206 }
4207
4208 int kill_and_sigcont(pid_t pid, int sig) {
4209         int r;
4210
4211         r = kill(pid, sig) < 0 ? -errno : 0;
4212
4213         if (r >= 0)
4214                 kill(pid, SIGCONT);
4215
4216         return r;
4217 }
4218
4219 bool nulstr_contains(const char*nulstr, const char *needle) {
4220         const char *i;
4221
4222         if (!nulstr)
4223                 return false;
4224
4225         NULSTR_FOREACH(i, nulstr)
4226                 if (streq(i, needle))
4227                         return true;
4228
4229         return false;
4230 }
4231
4232 bool plymouth_running(void) {
4233         return access("/run/plymouth/pid", F_OK) >= 0;
4234 }
4235
4236 char* strshorten(char *s, size_t l) {
4237         assert(s);
4238
4239         if (l < strlen(s))
4240                 s[l] = 0;
4241
4242         return s;
4243 }
4244
4245 static bool hostname_valid_char(char c) {
4246         return
4247                 (c >= 'a' && c <= 'z') ||
4248                 (c >= 'A' && c <= 'Z') ||
4249                 (c >= '0' && c <= '9') ||
4250                 c == '-' ||
4251                 c == '_' ||
4252                 c == '.';
4253 }
4254
4255 bool hostname_is_valid(const char *s) {
4256         const char *p;
4257         bool dot;
4258
4259         if (isempty(s))
4260                 return false;
4261
4262         /* Doesn't accept empty hostnames, hostnames with trailing or
4263          * leading dots, and hostnames with multiple dots in a
4264          * sequence. Also ensures that the length stays below
4265          * HOST_NAME_MAX. */
4266
4267         for (p = s, dot = true; *p; p++) {
4268                 if (*p == '.') {
4269                         if (dot)
4270                                 return false;
4271
4272                         dot = true;
4273                 } else {
4274                         if (!hostname_valid_char(*p))
4275                                 return false;
4276
4277                         dot = false;
4278                 }
4279         }
4280
4281         if (dot)
4282                 return false;
4283
4284         if (p-s > HOST_NAME_MAX)
4285                 return false;
4286
4287         return true;
4288 }
4289
4290 char* hostname_cleanup(char *s, bool lowercase) {
4291         char *p, *d;
4292         bool dot;
4293
4294         for (p = s, d = s, dot = true; *p; p++) {
4295                 if (*p == '.') {
4296                         if (dot)
4297                                 continue;
4298
4299                         *(d++) = '.';
4300                         dot = true;
4301                 } else if (hostname_valid_char(*p)) {
4302                         *(d++) = lowercase ? tolower(*p) : *p;
4303                         dot = false;
4304                 }
4305
4306         }
4307
4308         if (dot && d > s)
4309                 d[-1] = 0;
4310         else
4311                 *d = 0;
4312
4313         strshorten(s, HOST_NAME_MAX);
4314
4315         return s;
4316 }
4317
4318 bool machine_name_is_valid(const char *s) {
4319
4320         if (!hostname_is_valid(s))
4321                 return false;
4322
4323         /* Machine names should be useful hostnames, but also be
4324          * useful in unit names, hence we enforce a stricter length
4325          * limitation. */
4326
4327         if (strlen(s) > 64)
4328                 return false;
4329
4330         return true;
4331 }
4332
4333 int pipe_eof(int fd) {
4334         struct pollfd pollfd = {
4335                 .fd = fd,
4336                 .events = POLLIN|POLLHUP,
4337         };
4338
4339         int r;
4340
4341         r = poll(&pollfd, 1, 0);
4342         if (r < 0)
4343                 return -errno;
4344
4345         if (r == 0)
4346                 return 0;
4347
4348         return pollfd.revents & POLLHUP;
4349 }
4350
4351 int fd_wait_for_event(int fd, int event, usec_t t) {
4352
4353         struct pollfd pollfd = {
4354                 .fd = fd,
4355                 .events = event,
4356         };
4357
4358         struct timespec ts;
4359         int r;
4360
4361         r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
4362         if (r < 0)
4363                 return -errno;
4364
4365         if (r == 0)
4366                 return 0;
4367
4368         return pollfd.revents;
4369 }
4370
4371 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4372         FILE *f;
4373         char *t;
4374         int r, fd;
4375
4376         assert(path);
4377         assert(_f);
4378         assert(_temp_path);
4379
4380         r = tempfn_xxxxxx(path, &t);
4381         if (r < 0)
4382                 return r;
4383
4384         fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
4385         if (fd < 0) {
4386                 free(t);
4387                 return -errno;
4388         }
4389
4390         f = fdopen(fd, "we");
4391         if (!f) {
4392                 unlink(t);
4393                 free(t);
4394                 return -errno;
4395         }
4396
4397         *_f = f;
4398         *_temp_path = t;
4399
4400         return 0;
4401 }
4402
4403 int terminal_vhangup_fd(int fd) {
4404         assert(fd >= 0);
4405
4406         if (ioctl(fd, TIOCVHANGUP) < 0)
4407                 return -errno;
4408
4409         return 0;
4410 }
4411
4412 int terminal_vhangup(const char *name) {
4413         _cleanup_close_ int fd;
4414
4415         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4416         if (fd < 0)
4417                 return fd;
4418
4419         return terminal_vhangup_fd(fd);
4420 }
4421
4422 int vt_disallocate(const char *name) {
4423         int fd, r;
4424         unsigned u;
4425
4426         /* Deallocate the VT if possible. If not possible
4427          * (i.e. because it is the active one), at least clear it
4428          * entirely (including the scrollback buffer) */
4429
4430         if (!startswith(name, "/dev/"))
4431                 return -EINVAL;
4432
4433         if (!tty_is_vc(name)) {
4434                 /* So this is not a VT. I guess we cannot deallocate
4435                  * it then. But let's at least clear the screen */
4436
4437                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4438                 if (fd < 0)
4439                         return fd;
4440
4441                 loop_write(fd,
4442                            "\033[r"    /* clear scrolling region */
4443                            "\033[H"    /* move home */
4444                            "\033[2J",  /* clear screen */
4445                            10, false);
4446                 safe_close(fd);
4447
4448                 return 0;
4449         }
4450
4451         if (!startswith(name, "/dev/tty"))
4452                 return -EINVAL;
4453
4454         r = safe_atou(name+8, &u);
4455         if (r < 0)
4456                 return r;
4457
4458         if (u <= 0)
4459                 return -EINVAL;
4460
4461         /* Try to deallocate */
4462         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4463         if (fd < 0)
4464                 return fd;
4465
4466         r = ioctl(fd, VT_DISALLOCATE, u);
4467         safe_close(fd);
4468
4469         if (r >= 0)
4470                 return 0;
4471
4472         if (errno != EBUSY)
4473                 return -errno;
4474
4475         /* Couldn't deallocate, so let's clear it fully with
4476          * scrollback */
4477         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4478         if (fd < 0)
4479                 return fd;
4480
4481         loop_write(fd,
4482                    "\033[r"   /* clear scrolling region */
4483                    "\033[H"   /* move home */
4484                    "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4485                    10, false);
4486         safe_close(fd);
4487
4488         return 0;
4489 }
4490
4491 int symlink_atomic(const char *from, const char *to) {
4492         _cleanup_free_ char *t = NULL;
4493         int r;
4494
4495         assert(from);
4496         assert(to);
4497
4498         r = tempfn_random(to, &t);
4499         if (r < 0)
4500                 return r;
4501
4502         if (symlink(from, t) < 0)
4503                 return -errno;
4504
4505         if (rename(t, to) < 0) {
4506                 unlink_noerrno(t);
4507                 return -errno;
4508         }
4509
4510         return 0;
4511 }
4512
4513 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
4514         _cleanup_free_ char *t = NULL;
4515         int r;
4516
4517         assert(path);
4518
4519         r = tempfn_random(path, &t);
4520         if (r < 0)
4521                 return r;
4522
4523         if (mknod(t, mode, dev) < 0)
4524                 return -errno;
4525
4526         if (rename(t, path) < 0) {
4527                 unlink_noerrno(t);
4528                 return -errno;
4529         }
4530
4531         return 0;
4532 }
4533
4534 int mkfifo_atomic(const char *path, mode_t mode) {
4535         _cleanup_free_ char *t = NULL;
4536         int r;
4537
4538         assert(path);
4539
4540         r = tempfn_random(path, &t);
4541         if (r < 0)
4542                 return r;
4543
4544         if (mkfifo(t, mode) < 0)
4545                 return -errno;
4546
4547         if (rename(t, path) < 0) {
4548                 unlink_noerrno(t);
4549                 return -errno;
4550         }
4551
4552         return 0;
4553 }
4554
4555 bool display_is_local(const char *display) {
4556         assert(display);
4557
4558         return
4559                 display[0] == ':' &&
4560                 display[1] >= '0' &&
4561                 display[1] <= '9';
4562 }
4563
4564 int socket_from_display(const char *display, char **path) {
4565         size_t k;
4566         char *f, *c;
4567
4568         assert(display);
4569         assert(path);
4570
4571         if (!display_is_local(display))
4572                 return -EINVAL;
4573
4574         k = strspn(display+1, "0123456789");
4575
4576         f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
4577         if (!f)
4578                 return -ENOMEM;
4579
4580         c = stpcpy(f, "/tmp/.X11-unix/X");
4581         memcpy(c, display+1, k);
4582         c[k] = 0;
4583
4584         *path = f;
4585
4586         return 0;
4587 }
4588
4589 int get_user_creds(
4590                 const char **username,
4591                 uid_t *uid, gid_t *gid,
4592                 const char **home,
4593                 const char **shell) {
4594
4595         struct passwd *p;
4596         uid_t u;
4597
4598         assert(username);
4599         assert(*username);
4600
4601         /* We enforce some special rules for uid=0: in order to avoid
4602          * NSS lookups for root we hardcode its data. */
4603
4604         if (streq(*username, "root") || streq(*username, "0")) {
4605                 *username = "root";
4606
4607                 if (uid)
4608                         *uid = 0;
4609
4610                 if (gid)
4611                         *gid = 0;
4612
4613                 if (home)
4614                         *home = "/root";
4615
4616                 if (shell)
4617                         *shell = "/bin/sh";
4618
4619                 return 0;
4620         }
4621
4622         if (parse_uid(*username, &u) >= 0) {
4623                 errno = 0;
4624                 p = getpwuid(u);
4625
4626                 /* If there are multiple users with the same id, make
4627                  * sure to leave $USER to the configured value instead
4628                  * of the first occurrence in the database. However if
4629                  * the uid was configured by a numeric uid, then let's
4630                  * pick the real username from /etc/passwd. */
4631                 if (p)
4632                         *username = p->pw_name;
4633         } else {
4634                 errno = 0;
4635                 p = getpwnam(*username);
4636         }
4637
4638         if (!p)
4639                 return errno > 0 ? -errno : -ESRCH;
4640
4641         if (uid)
4642                 *uid = p->pw_uid;
4643
4644         if (gid)
4645                 *gid = p->pw_gid;
4646
4647         if (home)
4648                 *home = p->pw_dir;
4649
4650         if (shell)
4651                 *shell = p->pw_shell;
4652
4653         return 0;
4654 }
4655
4656 char* uid_to_name(uid_t uid) {
4657         struct passwd *p;
4658         char *r;
4659
4660         if (uid == 0)
4661                 return strdup("root");
4662
4663         p = getpwuid(uid);
4664         if (p)
4665                 return strdup(p->pw_name);
4666
4667         if (asprintf(&r, UID_FMT, uid) < 0)
4668                 return NULL;
4669
4670         return r;
4671 }
4672
4673 char* gid_to_name(gid_t gid) {
4674         struct group *p;
4675         char *r;
4676
4677         if (gid == 0)
4678                 return strdup("root");
4679
4680         p = getgrgid(gid);
4681         if (p)
4682                 return strdup(p->gr_name);
4683
4684         if (asprintf(&r, GID_FMT, gid) < 0)
4685                 return NULL;
4686
4687         return r;
4688 }
4689
4690 int get_group_creds(const char **groupname, gid_t *gid) {
4691         struct group *g;
4692         gid_t id;
4693
4694         assert(groupname);
4695
4696         /* We enforce some special rules for gid=0: in order to avoid
4697          * NSS lookups for root we hardcode its data. */
4698
4699         if (streq(*groupname, "root") || streq(*groupname, "0")) {
4700                 *groupname = "root";
4701
4702                 if (gid)
4703                         *gid = 0;
4704
4705                 return 0;
4706         }
4707
4708         if (parse_gid(*groupname, &id) >= 0) {
4709                 errno = 0;
4710                 g = getgrgid(id);
4711
4712                 if (g)
4713                         *groupname = g->gr_name;
4714         } else {
4715                 errno = 0;
4716                 g = getgrnam(*groupname);
4717         }
4718
4719         if (!g)
4720                 return errno > 0 ? -errno : -ESRCH;
4721
4722         if (gid)
4723                 *gid = g->gr_gid;
4724
4725         return 0;
4726 }
4727
4728 int in_gid(gid_t gid) {
4729         gid_t *gids;
4730         int ngroups_max, r, i;
4731
4732         if (getgid() == gid)
4733                 return 1;
4734
4735         if (getegid() == gid)
4736                 return 1;
4737
4738         ngroups_max = sysconf(_SC_NGROUPS_MAX);
4739         assert(ngroups_max > 0);
4740
4741         gids = alloca(sizeof(gid_t) * ngroups_max);
4742
4743         r = getgroups(ngroups_max, gids);
4744         if (r < 0)
4745                 return -errno;
4746
4747         for (i = 0; i < r; i++)
4748                 if (gids[i] == gid)
4749                         return 1;
4750
4751         return 0;
4752 }
4753
4754 int in_group(const char *name) {
4755         int r;
4756         gid_t gid;
4757
4758         r = get_group_creds(&name, &gid);
4759         if (r < 0)
4760                 return r;
4761
4762         return in_gid(gid);
4763 }
4764
4765 int glob_exists(const char *path) {
4766         _cleanup_globfree_ glob_t g = {};
4767         int k;
4768
4769         assert(path);
4770
4771         errno = 0;
4772         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4773
4774         if (k == GLOB_NOMATCH)
4775                 return 0;
4776         else if (k == GLOB_NOSPACE)
4777                 return -ENOMEM;
4778         else if (k == 0)
4779                 return !strv_isempty(g.gl_pathv);
4780         else
4781                 return errno ? -errno : -EIO;
4782 }
4783
4784 int glob_extend(char ***strv, const char *path) {
4785         _cleanup_globfree_ glob_t g = {};
4786         int k;
4787         char **p;
4788
4789         errno = 0;
4790         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4791
4792         if (k == GLOB_NOMATCH)
4793                 return -ENOENT;
4794         else if (k == GLOB_NOSPACE)
4795                 return -ENOMEM;
4796         else if (k != 0 || strv_isempty(g.gl_pathv))
4797                 return errno ? -errno : -EIO;
4798
4799         STRV_FOREACH(p, g.gl_pathv) {
4800                 k = strv_extend(strv, *p);
4801                 if (k < 0)
4802                         break;
4803         }
4804
4805         return k;
4806 }
4807
4808 int dirent_ensure_type(DIR *d, struct dirent *de) {
4809         struct stat st;
4810
4811         assert(d);
4812         assert(de);
4813
4814         if (de->d_type != DT_UNKNOWN)
4815                 return 0;
4816
4817         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4818                 return -errno;
4819
4820         de->d_type =
4821                 S_ISREG(st.st_mode)  ? DT_REG  :
4822                 S_ISDIR(st.st_mode)  ? DT_DIR  :
4823                 S_ISLNK(st.st_mode)  ? DT_LNK  :
4824                 S_ISFIFO(st.st_mode) ? DT_FIFO :
4825                 S_ISSOCK(st.st_mode) ? DT_SOCK :
4826                 S_ISCHR(st.st_mode)  ? DT_CHR  :
4827                 S_ISBLK(st.st_mode)  ? DT_BLK  :
4828                                        DT_UNKNOWN;
4829
4830         return 0;
4831 }
4832
4833 int get_files_in_directory(const char *path, char ***list) {
4834         _cleanup_closedir_ DIR *d = NULL;
4835         size_t bufsize = 0, n = 0;
4836         _cleanup_strv_free_ char **l = NULL;
4837
4838         assert(path);
4839
4840         /* Returns all files in a directory in *list, and the number
4841          * of files as return value. If list is NULL returns only the
4842          * number. */
4843
4844         d = opendir(path);
4845         if (!d)
4846                 return -errno;
4847
4848         for (;;) {
4849                 struct dirent *de;
4850
4851                 errno = 0;
4852                 de = readdir(d);
4853                 if (!de && errno != 0)
4854                         return -errno;
4855                 if (!de)
4856                         break;
4857
4858                 dirent_ensure_type(d, de);
4859
4860                 if (!dirent_is_file(de))
4861                         continue;
4862
4863                 if (list) {
4864                         /* one extra slot is needed for the terminating NULL */
4865                         if (!GREEDY_REALLOC(l, bufsize, n + 2))
4866                                 return -ENOMEM;
4867
4868                         l[n] = strdup(de->d_name);
4869                         if (!l[n])
4870                                 return -ENOMEM;
4871
4872                         l[++n] = NULL;
4873                 } else
4874                         n++;
4875         }
4876
4877         if (list) {
4878                 *list = l;
4879                 l = NULL; /* avoid freeing */
4880         }
4881
4882         return n;
4883 }
4884
4885 char *strjoin(const char *x, ...) {
4886         va_list ap;
4887         size_t l;
4888         char *r, *p;
4889
4890         va_start(ap, x);
4891
4892         if (x) {
4893                 l = strlen(x);
4894
4895                 for (;;) {
4896                         const char *t;
4897                         size_t n;
4898
4899                         t = va_arg(ap, const char *);
4900                         if (!t)
4901                                 break;
4902
4903                         n = strlen(t);
4904                         if (n > ((size_t) -1) - l) {
4905                                 va_end(ap);
4906                                 return NULL;
4907                         }
4908
4909                         l += n;
4910                 }
4911         } else
4912                 l = 0;
4913
4914         va_end(ap);
4915
4916         r = new(char, l+1);
4917         if (!r)
4918                 return NULL;
4919
4920         if (x) {
4921                 p = stpcpy(r, x);
4922
4923                 va_start(ap, x);
4924
4925                 for (;;) {
4926                         const char *t;
4927
4928                         t = va_arg(ap, const char *);
4929                         if (!t)
4930                                 break;
4931
4932                         p = stpcpy(p, t);
4933                 }
4934
4935                 va_end(ap);
4936         } else
4937                 r[0] = 0;
4938
4939         return r;
4940 }
4941
4942 bool is_main_thread(void) {
4943         static thread_local int cached = 0;
4944
4945         if (_unlikely_(cached == 0))
4946                 cached = getpid() == gettid() ? 1 : -1;
4947
4948         return cached > 0;
4949 }
4950
4951 int block_get_whole_disk(dev_t d, dev_t *ret) {
4952         char *p, *s;
4953         int r;
4954         unsigned n, m;
4955
4956         assert(ret);
4957
4958         /* If it has a queue this is good enough for us */
4959         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4960                 return -ENOMEM;
4961
4962         r = access(p, F_OK);
4963         free(p);
4964
4965         if (r >= 0) {
4966                 *ret = d;
4967                 return 0;
4968         }
4969
4970         /* If it is a partition find the originating device */
4971         if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4972                 return -ENOMEM;
4973
4974         r = access(p, F_OK);
4975         free(p);
4976
4977         if (r < 0)
4978                 return -ENOENT;
4979
4980         /* Get parent dev_t */
4981         if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4982                 return -ENOMEM;
4983
4984         r = read_one_line_file(p, &s);
4985         free(p);
4986
4987         if (r < 0)
4988                 return r;
4989
4990         r = sscanf(s, "%u:%u", &m, &n);
4991         free(s);
4992
4993         if (r != 2)
4994                 return -EINVAL;
4995
4996         /* Only return this if it is really good enough for us. */
4997         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4998                 return -ENOMEM;
4999
5000         r = access(p, F_OK);
5001         free(p);
5002
5003         if (r >= 0) {
5004                 *ret = makedev(m, n);
5005                 return 0;
5006         }
5007
5008         return -ENOENT;
5009 }
5010
5011 static const char *const ioprio_class_table[] = {
5012         [IOPRIO_CLASS_NONE] = "none",
5013         [IOPRIO_CLASS_RT] = "realtime",
5014         [IOPRIO_CLASS_BE] = "best-effort",
5015         [IOPRIO_CLASS_IDLE] = "idle"
5016 };
5017
5018 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
5019
5020 static const char *const sigchld_code_table[] = {
5021         [CLD_EXITED] = "exited",
5022         [CLD_KILLED] = "killed",
5023         [CLD_DUMPED] = "dumped",
5024         [CLD_TRAPPED] = "trapped",
5025         [CLD_STOPPED] = "stopped",
5026         [CLD_CONTINUED] = "continued",
5027 };
5028
5029 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5030
5031 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5032         [LOG_FAC(LOG_KERN)] = "kern",
5033         [LOG_FAC(LOG_USER)] = "user",
5034         [LOG_FAC(LOG_MAIL)] = "mail",
5035         [LOG_FAC(LOG_DAEMON)] = "daemon",
5036         [LOG_FAC(LOG_AUTH)] = "auth",
5037         [LOG_FAC(LOG_SYSLOG)] = "syslog",
5038         [LOG_FAC(LOG_LPR)] = "lpr",
5039         [LOG_FAC(LOG_NEWS)] = "news",
5040         [LOG_FAC(LOG_UUCP)] = "uucp",
5041         [LOG_FAC(LOG_CRON)] = "cron",
5042         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5043         [LOG_FAC(LOG_FTP)] = "ftp",
5044         [LOG_FAC(LOG_LOCAL0)] = "local0",
5045         [LOG_FAC(LOG_LOCAL1)] = "local1",
5046         [LOG_FAC(LOG_LOCAL2)] = "local2",
5047         [LOG_FAC(LOG_LOCAL3)] = "local3",
5048         [LOG_FAC(LOG_LOCAL4)] = "local4",
5049         [LOG_FAC(LOG_LOCAL5)] = "local5",
5050         [LOG_FAC(LOG_LOCAL6)] = "local6",
5051         [LOG_FAC(LOG_LOCAL7)] = "local7"
5052 };
5053
5054 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
5055
5056 static const char *const log_level_table[] = {
5057         [LOG_EMERG] = "emerg",
5058         [LOG_ALERT] = "alert",
5059         [LOG_CRIT] = "crit",
5060         [LOG_ERR] = "err",
5061         [LOG_WARNING] = "warning",
5062         [LOG_NOTICE] = "notice",
5063         [LOG_INFO] = "info",
5064         [LOG_DEBUG] = "debug"
5065 };
5066
5067 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
5068
5069 static const char* const sched_policy_table[] = {
5070         [SCHED_OTHER] = "other",
5071         [SCHED_BATCH] = "batch",
5072         [SCHED_IDLE] = "idle",
5073         [SCHED_FIFO] = "fifo",
5074         [SCHED_RR] = "rr"
5075 };
5076
5077 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
5078
5079 static const char* const rlimit_table[_RLIMIT_MAX] = {
5080         [RLIMIT_CPU] = "LimitCPU",
5081         [RLIMIT_FSIZE] = "LimitFSIZE",
5082         [RLIMIT_DATA] = "LimitDATA",
5083         [RLIMIT_STACK] = "LimitSTACK",
5084         [RLIMIT_CORE] = "LimitCORE",
5085         [RLIMIT_RSS] = "LimitRSS",
5086         [RLIMIT_NOFILE] = "LimitNOFILE",
5087         [RLIMIT_AS] = "LimitAS",
5088         [RLIMIT_NPROC] = "LimitNPROC",
5089         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5090         [RLIMIT_LOCKS] = "LimitLOCKS",
5091         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5092         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5093         [RLIMIT_NICE] = "LimitNICE",
5094         [RLIMIT_RTPRIO] = "LimitRTPRIO",
5095         [RLIMIT_RTTIME] = "LimitRTTIME"
5096 };
5097
5098 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5099
5100 static const char* const ip_tos_table[] = {
5101         [IPTOS_LOWDELAY] = "low-delay",
5102         [IPTOS_THROUGHPUT] = "throughput",
5103         [IPTOS_RELIABILITY] = "reliability",
5104         [IPTOS_LOWCOST] = "low-cost",
5105 };
5106
5107 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
5108
5109 static const char *const __signal_table[] = {
5110         [SIGHUP] = "HUP",
5111         [SIGINT] = "INT",
5112         [SIGQUIT] = "QUIT",
5113         [SIGILL] = "ILL",
5114         [SIGTRAP] = "TRAP",
5115         [SIGABRT] = "ABRT",
5116         [SIGBUS] = "BUS",
5117         [SIGFPE] = "FPE",
5118         [SIGKILL] = "KILL",
5119         [SIGUSR1] = "USR1",
5120         [SIGSEGV] = "SEGV",
5121         [SIGUSR2] = "USR2",
5122         [SIGPIPE] = "PIPE",
5123         [SIGALRM] = "ALRM",
5124         [SIGTERM] = "TERM",
5125 #ifdef SIGSTKFLT
5126         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
5127 #endif
5128         [SIGCHLD] = "CHLD",
5129         [SIGCONT] = "CONT",
5130         [SIGSTOP] = "STOP",
5131         [SIGTSTP] = "TSTP",
5132         [SIGTTIN] = "TTIN",
5133         [SIGTTOU] = "TTOU",
5134         [SIGURG] = "URG",
5135         [SIGXCPU] = "XCPU",
5136         [SIGXFSZ] = "XFSZ",
5137         [SIGVTALRM] = "VTALRM",
5138         [SIGPROF] = "PROF",
5139         [SIGWINCH] = "WINCH",
5140         [SIGIO] = "IO",
5141         [SIGPWR] = "PWR",
5142         [SIGSYS] = "SYS"
5143 };
5144
5145 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5146
5147 const char *signal_to_string(int signo) {
5148         static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
5149         const char *name;
5150
5151         name = __signal_to_string(signo);
5152         if (name)
5153                 return name;
5154
5155         if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5156                 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
5157         else
5158                 snprintf(buf, sizeof(buf), "%d", signo);
5159
5160         return buf;
5161 }
5162
5163 int signal_from_string(const char *s) {
5164         int signo;
5165         int offset = 0;
5166         unsigned u;
5167
5168         signo = __signal_from_string(s);
5169         if (signo > 0)
5170                 return signo;
5171
5172         if (startswith(s, "RTMIN+")) {
5173                 s += 6;
5174                 offset = SIGRTMIN;
5175         }
5176         if (safe_atou(s, &u) >= 0) {
5177                 signo = (int) u + offset;
5178                 if (signo > 0 && signo < _NSIG)
5179                         return signo;
5180         }
5181         return -EINVAL;
5182 }
5183
5184 bool kexec_loaded(void) {
5185        bool loaded = false;
5186        char *s;
5187
5188        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5189                if (s[0] == '1')
5190                        loaded = true;
5191                free(s);
5192        }
5193        return loaded;
5194 }
5195
5196 int prot_from_flags(int flags) {
5197
5198         switch (flags & O_ACCMODE) {
5199
5200         case O_RDONLY:
5201                 return PROT_READ;
5202
5203         case O_WRONLY:
5204                 return PROT_WRITE;
5205
5206         case O_RDWR:
5207                 return PROT_READ|PROT_WRITE;
5208
5209         default:
5210                 return -EINVAL;
5211         }
5212 }
5213
5214 char *format_bytes(char *buf, size_t l, off_t t) {
5215         unsigned i;
5216
5217         static const struct {
5218                 const char *suffix;
5219                 off_t factor;
5220         } table[] = {
5221                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5222                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5223                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5224                 { "G", 1024ULL*1024ULL*1024ULL },
5225                 { "M", 1024ULL*1024ULL },
5226                 { "K", 1024ULL },
5227         };
5228
5229         if (t == (off_t) -1)
5230                 return NULL;
5231
5232         for (i = 0; i < ELEMENTSOF(table); i++) {
5233
5234                 if (t >= table[i].factor) {
5235                         snprintf(buf, l,
5236                                  "%llu.%llu%s",
5237                                  (unsigned long long) (t / table[i].factor),
5238                                  (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5239                                  table[i].suffix);
5240
5241                         goto finish;
5242                 }
5243         }
5244
5245         snprintf(buf, l, "%lluB", (unsigned long long) t);
5246
5247 finish:
5248         buf[l-1] = 0;
5249         return buf;
5250
5251 }
5252
5253 void* memdup(const void *p, size_t l) {
5254         void *r;
5255
5256         assert(p);
5257
5258         r = malloc(l);
5259         if (!r)
5260                 return NULL;
5261
5262         memcpy(r, p, l);
5263         return r;
5264 }
5265
5266 int fd_inc_sndbuf(int fd, size_t n) {
5267         int r, value;
5268         socklen_t l = sizeof(value);
5269
5270         r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5271         if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
5272                 return 0;
5273
5274         /* If we have the privileges we will ignore the kernel limit. */
5275
5276         value = (int) n;
5277         if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
5278                 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
5279                         return -errno;
5280
5281         return 1;
5282 }
5283
5284 int fd_inc_rcvbuf(int fd, size_t n) {
5285         int r, value;
5286         socklen_t l = sizeof(value);
5287
5288         r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5289         if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
5290                 return 0;
5291
5292         /* If we have the privileges we will ignore the kernel limit. */
5293
5294         value = (int) n;
5295         if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
5296                 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
5297                         return -errno;
5298         return 1;
5299 }
5300
5301 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5302         bool stdout_is_tty, stderr_is_tty;
5303         pid_t parent_pid, agent_pid;
5304         sigset_t ss, saved_ss;
5305         unsigned n, i;
5306         va_list ap;
5307         char **l;
5308
5309         assert(pid);
5310         assert(path);
5311
5312         /* Spawns a temporary TTY agent, making sure it goes away when
5313          * we go away */
5314
5315         parent_pid = getpid();
5316
5317         /* First we temporarily block all signals, so that the new
5318          * child has them blocked initially. This way, we can be sure
5319          * that SIGTERMs are not lost we might send to the agent. */
5320         assert_se(sigfillset(&ss) >= 0);
5321         assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
5322
5323         agent_pid = fork();
5324         if (agent_pid < 0) {
5325                 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
5326                 return -errno;
5327         }
5328
5329         if (agent_pid != 0) {
5330                 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
5331                 *pid = agent_pid;
5332                 return 0;
5333         }
5334
5335         /* In the child:
5336          *
5337          * Make sure the agent goes away when the parent dies */
5338         if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5339                 _exit(EXIT_FAILURE);
5340
5341         /* Make sure we actually can kill the agent, if we need to, in
5342          * case somebody invoked us from a shell script that trapped
5343          * SIGTERM or so... */
5344         reset_all_signal_handlers();
5345         reset_signal_mask();
5346
5347         /* Check whether our parent died before we were able
5348          * to set the death signal and unblock the signals */
5349         if (getppid() != parent_pid)
5350                 _exit(EXIT_SUCCESS);
5351
5352         /* Don't leak fds to the agent */
5353         close_all_fds(except, n_except);
5354
5355         stdout_is_tty = isatty(STDOUT_FILENO);
5356         stderr_is_tty = isatty(STDERR_FILENO);
5357
5358         if (!stdout_is_tty || !stderr_is_tty) {
5359                 int fd;
5360
5361                 /* Detach from stdout/stderr. and reopen
5362                  * /dev/tty for them. This is important to
5363                  * ensure that when systemctl is started via
5364                  * popen() or a similar call that expects to
5365                  * read EOF we actually do generate EOF and
5366                  * not delay this indefinitely by because we
5367                  * keep an unused copy of stdin around. */
5368                 fd = open("/dev/tty", O_WRONLY);
5369                 if (fd < 0) {
5370                         log_error_errno(errno, "Failed to open /dev/tty: %m");
5371                         _exit(EXIT_FAILURE);
5372                 }
5373
5374                 if (!stdout_is_tty)
5375                         dup2(fd, STDOUT_FILENO);
5376
5377                 if (!stderr_is_tty)
5378                         dup2(fd, STDERR_FILENO);
5379
5380                 if (fd > 2)
5381                         close(fd);
5382         }
5383
5384         /* Count arguments */
5385         va_start(ap, path);
5386         for (n = 0; va_arg(ap, char*); n++)
5387                 ;
5388         va_end(ap);
5389
5390         /* Allocate strv */
5391         l = alloca(sizeof(char *) * (n + 1));
5392
5393         /* Fill in arguments */
5394         va_start(ap, path);
5395         for (i = 0; i <= n; i++)
5396                 l[i] = va_arg(ap, char*);
5397         va_end(ap);
5398
5399         execv(path, l);
5400         _exit(EXIT_FAILURE);
5401 }
5402
5403 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5404         struct rlimit highest, fixed;
5405
5406         assert(rlim);
5407
5408         if (setrlimit(resource, rlim) >= 0)
5409                 return 0;
5410
5411         if (errno != EPERM)
5412                 return -errno;
5413
5414         /* So we failed to set the desired setrlimit, then let's try
5415          * to get as close as we can */
5416         assert_se(getrlimit(resource, &highest) == 0);
5417
5418         fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5419         fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5420
5421         if (setrlimit(resource, &fixed) < 0)
5422                 return -errno;
5423
5424         return 0;
5425 }
5426
5427 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5428         _cleanup_fclose_ FILE *f = NULL;
5429         char *value = NULL;
5430         int r;
5431         bool done = false;
5432         size_t l;
5433         const char *path;
5434
5435         assert(pid >= 0);
5436         assert(field);
5437         assert(_value);
5438
5439         path = procfs_file_alloca(pid, "environ");
5440
5441         f = fopen(path, "re");
5442         if (!f)
5443                 return -errno;
5444
5445         l = strlen(field);
5446         r = 0;
5447
5448         do {
5449                 char line[LINE_MAX];
5450                 unsigned i;
5451
5452                 for (i = 0; i < sizeof(line)-1; i++) {
5453                         int c;
5454
5455                         c = getc(f);
5456                         if (_unlikely_(c == EOF)) {
5457                                 done = true;
5458                                 break;
5459                         } else if (c == 0)
5460                                 break;
5461
5462                         line[i] = c;
5463                 }
5464                 line[i] = 0;
5465
5466                 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5467                         value = strdup(line + l + 1);
5468                         if (!value)
5469                                 return -ENOMEM;
5470
5471                         r = 1;
5472                         break;
5473                 }
5474
5475         } while (!done);
5476
5477         *_value = value;
5478         return r;
5479 }
5480
5481 bool http_etag_is_valid(const char *etag) {
5482         if (isempty(etag))
5483                 return false;
5484
5485         if (!endswith(etag, "\""))
5486                 return false;
5487
5488         if (!startswith(etag, "\"") && !startswith(etag, "W/\""))
5489                 return false;
5490
5491         return true;
5492 }
5493
5494 bool http_url_is_valid(const char *url) {
5495         const char *p;
5496
5497         if (isempty(url))
5498                 return false;
5499
5500         p = startswith(url, "http://");
5501         if (!p)
5502                 p = startswith(url, "https://");
5503         if (!p)
5504                 return false;
5505
5506         if (isempty(p))
5507                 return false;
5508
5509         return ascii_is_valid(p);
5510 }
5511
5512 bool documentation_url_is_valid(const char *url) {
5513         const char *p;
5514
5515         if (isempty(url))
5516                 return false;
5517
5518         if (http_url_is_valid(url))
5519                 return true;
5520
5521         p = startswith(url, "file:/");
5522         if (!p)
5523                 p = startswith(url, "info:");
5524         if (!p)
5525                 p = startswith(url, "man:");
5526
5527         if (isempty(p))
5528                 return false;
5529
5530         return ascii_is_valid(p);
5531 }
5532
5533 bool in_initrd(void) {
5534         static int saved = -1;
5535         struct statfs s;
5536
5537         if (saved >= 0)
5538                 return saved;
5539
5540         /* We make two checks here:
5541          *
5542          * 1. the flag file /etc/initrd-release must exist
5543          * 2. the root file system must be a memory file system
5544          *
5545          * The second check is extra paranoia, since misdetecting an
5546          * initrd can have bad bad consequences due the initrd
5547          * emptying when transititioning to the main systemd.
5548          */
5549
5550         saved = access("/etc/initrd-release", F_OK) >= 0 &&
5551                 statfs("/", &s) >= 0 &&
5552                 is_temporary_fs(&s);
5553
5554         return saved;
5555 }
5556
5557 void warn_melody(void) {
5558         _cleanup_close_ int fd = -1;
5559
5560         fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5561         if (fd < 0)
5562                 return;
5563
5564         /* Yeah, this is synchronous. Kinda sucks. But well... */
5565
5566         ioctl(fd, KIOCSOUND, (int)(1193180/440));
5567         usleep(125*USEC_PER_MSEC);
5568
5569         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5570         usleep(125*USEC_PER_MSEC);
5571
5572         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5573         usleep(125*USEC_PER_MSEC);
5574
5575         ioctl(fd, KIOCSOUND, 0);
5576 }
5577
5578 int make_console_stdio(void) {
5579         int fd, r;
5580
5581         /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5582
5583         fd = acquire_terminal("/dev/console", false, true, true, USEC_INFINITY);
5584         if (fd < 0)
5585                 return log_error_errno(fd, "Failed to acquire terminal: %m");
5586
5587         r = make_stdio(fd);
5588         if (r < 0)
5589                 return log_error_errno(r, "Failed to duplicate terminal fd: %m");
5590
5591         return 0;
5592 }
5593
5594 int get_home_dir(char **_h) {
5595         struct passwd *p;
5596         const char *e;
5597         char *h;
5598         uid_t u;
5599
5600         assert(_h);
5601
5602         /* Take the user specified one */
5603         e = secure_getenv("HOME");
5604         if (e && path_is_absolute(e)) {
5605                 h = strdup(e);
5606                 if (!h)
5607                         return -ENOMEM;
5608
5609                 *_h = h;
5610                 return 0;
5611         }
5612
5613         /* Hardcode home directory for root to avoid NSS */
5614         u = getuid();
5615         if (u == 0) {
5616                 h = strdup("/root");
5617                 if (!h)
5618                         return -ENOMEM;
5619
5620                 *_h = h;
5621                 return 0;
5622         }
5623
5624         /* Check the database... */
5625         errno = 0;
5626         p = getpwuid(u);
5627         if (!p)
5628                 return errno > 0 ? -errno : -ESRCH;
5629
5630         if (!path_is_absolute(p->pw_dir))
5631                 return -EINVAL;
5632
5633         h = strdup(p->pw_dir);
5634         if (!h)
5635                 return -ENOMEM;
5636
5637         *_h = h;
5638         return 0;
5639 }
5640
5641 int get_shell(char **_s) {
5642         struct passwd *p;
5643         const char *e;
5644         char *s;
5645         uid_t u;
5646
5647         assert(_s);
5648
5649         /* Take the user specified one */
5650         e = getenv("SHELL");
5651         if (e) {
5652                 s = strdup(e);
5653                 if (!s)
5654                         return -ENOMEM;
5655
5656                 *_s = s;
5657                 return 0;
5658         }
5659
5660         /* Hardcode home directory for root to avoid NSS */
5661         u = getuid();
5662         if (u == 0) {
5663                 s = strdup("/bin/sh");
5664                 if (!s)
5665                         return -ENOMEM;
5666
5667                 *_s = s;
5668                 return 0;
5669         }
5670
5671         /* Check the database... */
5672         errno = 0;
5673         p = getpwuid(u);
5674         if (!p)
5675                 return errno > 0 ? -errno : -ESRCH;
5676
5677         if (!path_is_absolute(p->pw_shell))
5678                 return -EINVAL;
5679
5680         s = strdup(p->pw_shell);
5681         if (!s)
5682                 return -ENOMEM;
5683
5684         *_s = s;
5685         return 0;
5686 }
5687
5688 bool filename_is_valid(const char *p) {
5689
5690         if (isempty(p))
5691                 return false;
5692
5693         if (strchr(p, '/'))
5694                 return false;
5695
5696         if (streq(p, "."))
5697                 return false;
5698
5699         if (streq(p, ".."))
5700                 return false;
5701
5702         if (strlen(p) > FILENAME_MAX)
5703                 return false;
5704
5705         return true;
5706 }
5707
5708 bool string_is_safe(const char *p) {
5709         const char *t;
5710
5711         if (!p)
5712                 return false;
5713
5714         for (t = p; *t; t++) {
5715                 if (*t > 0 && *t < ' ')
5716                         return false;
5717
5718                 if (strchr("\\\"\'\0x7f", *t))
5719                         return false;
5720         }
5721
5722         return true;
5723 }
5724
5725 /**
5726  * Check if a string contains control characters. If 'ok' is non-NULL
5727  * it may be a string containing additional CCs to be considered OK.
5728  */
5729 bool string_has_cc(const char *p, const char *ok) {
5730         const char *t;
5731
5732         assert(p);
5733
5734         for (t = p; *t; t++) {
5735                 if (ok && strchr(ok, *t))
5736                         continue;
5737
5738                 if (*t > 0 && *t < ' ')
5739                         return true;
5740
5741                 if (*t == 127)
5742                         return true;
5743         }
5744
5745         return false;
5746 }
5747
5748 bool path_is_safe(const char *p) {
5749
5750         if (isempty(p))
5751                 return false;
5752
5753         if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5754                 return false;
5755
5756         if (strlen(p) > PATH_MAX)
5757                 return false;
5758
5759         /* The following two checks are not really dangerous, but hey, they still are confusing */
5760         if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5761                 return false;
5762
5763         if (strstr(p, "//"))
5764                 return false;
5765
5766         return true;
5767 }
5768
5769 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5770 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5771                  int (*compar) (const void *, const void *, void *), void *arg) {
5772         size_t l, u, idx;
5773         const void *p;
5774         int comparison;
5775
5776         l = 0;
5777         u = nmemb;
5778         while (l < u) {
5779                 idx = (l + u) / 2;
5780                 p = (void *)(((const char *) base) + (idx * size));
5781                 comparison = compar(key, p, arg);
5782                 if (comparison < 0)
5783                         u = idx;
5784                 else if (comparison > 0)
5785                         l = idx + 1;
5786                 else
5787                         return (void *)p;
5788         }
5789         return NULL;
5790 }
5791
5792 void init_gettext(void) {
5793         setlocale(LC_ALL, "");
5794         textdomain(GETTEXT_PACKAGE);
5795 }
5796
5797 bool is_locale_utf8(void) {
5798         const char *set;
5799         static int cached_answer = -1;
5800
5801         if (cached_answer >= 0)
5802                 goto out;
5803
5804         if (!setlocale(LC_ALL, "")) {
5805                 cached_answer = true;
5806                 goto out;
5807         }
5808
5809         set = nl_langinfo(CODESET);
5810         if (!set) {
5811                 cached_answer = true;
5812                 goto out;
5813         }
5814
5815         if (streq(set, "UTF-8")) {
5816                 cached_answer = true;
5817                 goto out;
5818         }
5819
5820         /* For LC_CTYPE=="C" return true, because CTYPE is effectly
5821          * unset and everything can do to UTF-8 nowadays. */
5822         set = setlocale(LC_CTYPE, NULL);
5823         if (!set) {
5824                 cached_answer = true;
5825                 goto out;
5826         }
5827
5828         /* Check result, but ignore the result if C was set
5829          * explicitly. */
5830         cached_answer =
5831                 streq(set, "C") &&
5832                 !getenv("LC_ALL") &&
5833                 !getenv("LC_CTYPE") &&
5834                 !getenv("LANG");
5835
5836 out:
5837         return (bool) cached_answer;
5838 }
5839
5840 const char *draw_special_char(DrawSpecialChar ch) {
5841         static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5842
5843                 /* UTF-8 */ {
5844                         [DRAW_TREE_VERTICAL]      = "\342\224\202 ",            /* │  */
5845                         [DRAW_TREE_BRANCH]        = "\342\224\234\342\224\200", /* ├─ */
5846                         [DRAW_TREE_RIGHT]         = "\342\224\224\342\224\200", /* └─ */
5847                         [DRAW_TREE_SPACE]         = "  ",                       /*    */
5848                         [DRAW_TRIANGULAR_BULLET]  = "\342\200\243",             /* ‣ */
5849                         [DRAW_BLACK_CIRCLE]       = "\342\227\217",             /* ● */
5850                         [DRAW_ARROW]              = "\342\206\222",             /* → */
5851                         [DRAW_DASH]               = "\342\200\223",             /* – */
5852                 },
5853
5854                 /* ASCII fallback */ {
5855                         [DRAW_TREE_VERTICAL]      = "| ",
5856                         [DRAW_TREE_BRANCH]        = "|-",
5857                         [DRAW_TREE_RIGHT]         = "`-",
5858                         [DRAW_TREE_SPACE]         = "  ",
5859                         [DRAW_TRIANGULAR_BULLET]  = ">",
5860                         [DRAW_BLACK_CIRCLE]       = "*",
5861                         [DRAW_ARROW]              = "->",
5862                         [DRAW_DASH]               = "-",
5863                 }
5864         };
5865
5866         return draw_table[!is_locale_utf8()][ch];
5867 }
5868
5869 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5870         const char *f;
5871         char *t, *r;
5872         size_t l, old_len, new_len;
5873
5874         assert(text);
5875         assert(old_string);
5876         assert(new_string);
5877
5878         old_len = strlen(old_string);
5879         new_len = strlen(new_string);
5880
5881         l = strlen(text);
5882         r = new(char, l+1);
5883         if (!r)
5884                 return NULL;
5885
5886         f = text;
5887         t = r;
5888         while (*f) {
5889                 char *a;
5890                 size_t d, nl;
5891
5892                 if (!startswith(f, old_string)) {
5893                         *(t++) = *(f++);
5894                         continue;
5895                 }
5896
5897                 d = t - r;
5898                 nl = l - old_len + new_len;
5899                 a = realloc(r, nl + 1);
5900                 if (!a)
5901                         goto oom;
5902
5903                 l = nl;
5904                 r = a;
5905                 t = r + d;
5906
5907                 t = stpcpy(t, new_string);
5908                 f += old_len;
5909         }
5910
5911         *t = 0;
5912         return r;
5913
5914 oom:
5915         free(r);
5916         return NULL;
5917 }
5918
5919 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5920         const char *i, *begin = NULL;
5921         enum {
5922                 STATE_OTHER,
5923                 STATE_ESCAPE,
5924                 STATE_BRACKET
5925         } state = STATE_OTHER;
5926         char *obuf = NULL;
5927         size_t osz = 0, isz;
5928         FILE *f;
5929
5930         assert(ibuf);
5931         assert(*ibuf);
5932
5933         /* Strips ANSI color and replaces TABs by 8 spaces */
5934
5935         isz = _isz ? *_isz : strlen(*ibuf);
5936
5937         f = open_memstream(&obuf, &osz);
5938         if (!f)
5939                 return NULL;
5940
5941         for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5942
5943                 switch (state) {
5944
5945                 case STATE_OTHER:
5946                         if (i >= *ibuf + isz) /* EOT */
5947                                 break;
5948                         else if (*i == '\x1B')
5949                                 state = STATE_ESCAPE;
5950                         else if (*i == '\t')
5951                                 fputs("        ", f);
5952                         else
5953                                 fputc(*i, f);
5954                         break;
5955
5956                 case STATE_ESCAPE:
5957                         if (i >= *ibuf + isz) { /* EOT */
5958                                 fputc('\x1B', f);
5959                                 break;
5960                         } else if (*i == '[') {
5961                                 state = STATE_BRACKET;
5962                                 begin = i + 1;
5963                         } else {
5964                                 fputc('\x1B', f);
5965                                 fputc(*i, f);
5966                                 state = STATE_OTHER;
5967                         }
5968
5969                         break;
5970
5971                 case STATE_BRACKET:
5972
5973                         if (i >= *ibuf + isz || /* EOT */
5974                             (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5975                                 fputc('\x1B', f);
5976                                 fputc('[', f);
5977                                 state = STATE_OTHER;
5978                                 i = begin-1;
5979                         } else if (*i == 'm')
5980                                 state = STATE_OTHER;
5981                         break;
5982                 }
5983         }
5984
5985         if (ferror(f)) {
5986                 fclose(f);
5987                 free(obuf);
5988                 return NULL;
5989         }
5990
5991         fclose(f);
5992
5993         free(*ibuf);
5994         *ibuf = obuf;
5995
5996         if (_isz)
5997                 *_isz = osz;
5998
5999         return obuf;
6000 }
6001
6002 int on_ac_power(void) {
6003         bool found_offline = false, found_online = false;
6004         _cleanup_closedir_ DIR *d = NULL;
6005
6006         d = opendir("/sys/class/power_supply");
6007         if (!d)
6008                 return errno == ENOENT ? true : -errno;
6009
6010         for (;;) {
6011                 struct dirent *de;
6012                 _cleanup_close_ int fd = -1, device = -1;
6013                 char contents[6];
6014                 ssize_t n;
6015
6016                 errno = 0;
6017                 de = readdir(d);
6018                 if (!de && errno != 0)
6019                         return -errno;
6020
6021                 if (!de)
6022                         break;
6023
6024                 if (hidden_file(de->d_name))
6025                         continue;
6026
6027                 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
6028                 if (device < 0) {
6029                         if (errno == ENOENT || errno == ENOTDIR)
6030                                 continue;
6031
6032                         return -errno;
6033                 }
6034
6035                 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
6036                 if (fd < 0) {
6037                         if (errno == ENOENT)
6038                                 continue;
6039
6040                         return -errno;
6041                 }
6042
6043                 n = read(fd, contents, sizeof(contents));
6044                 if (n < 0)
6045                         return -errno;
6046
6047                 if (n != 6 || memcmp(contents, "Mains\n", 6))
6048                         continue;
6049
6050                 safe_close(fd);
6051                 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
6052                 if (fd < 0) {
6053                         if (errno == ENOENT)
6054                                 continue;
6055
6056                         return -errno;
6057                 }
6058
6059                 n = read(fd, contents, sizeof(contents));
6060                 if (n < 0)
6061                         return -errno;
6062
6063                 if (n != 2 || contents[1] != '\n')
6064                         return -EIO;
6065
6066                 if (contents[0] == '1') {
6067                         found_online = true;
6068                         break;
6069                 } else if (contents[0] == '0')
6070                         found_offline = true;
6071                 else
6072                         return -EIO;
6073         }
6074
6075         return found_online || !found_offline;
6076 }
6077
6078 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
6079         char **i;
6080
6081         assert(path);
6082         assert(mode);
6083         assert(_f);
6084
6085         if (!path_strv_resolve_uniq(search, root))
6086                 return -ENOMEM;
6087
6088         STRV_FOREACH(i, search) {
6089                 _cleanup_free_ char *p = NULL;
6090                 FILE *f;
6091
6092                 if (root)
6093                         p = strjoin(root, *i, "/", path, NULL);
6094                 else
6095                         p = strjoin(*i, "/", path, NULL);
6096                 if (!p)
6097                         return -ENOMEM;
6098
6099                 f = fopen(p, mode);
6100                 if (f) {
6101                         *_f = f;
6102                         return 0;
6103                 }
6104
6105                 if (errno != ENOENT)
6106                         return -errno;
6107         }
6108
6109         return -ENOENT;
6110 }
6111
6112 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
6113         _cleanup_strv_free_ char **copy = NULL;
6114
6115         assert(path);
6116         assert(mode);
6117         assert(_f);
6118
6119         if (path_is_absolute(path)) {
6120                 FILE *f;
6121
6122                 f = fopen(path, mode);
6123                 if (f) {
6124                         *_f = f;
6125                         return 0;
6126                 }
6127
6128                 return -errno;
6129         }
6130
6131         copy = strv_copy((char**) search);
6132         if (!copy)
6133                 return -ENOMEM;
6134
6135         return search_and_fopen_internal(path, mode, root, copy, _f);
6136 }
6137
6138 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
6139         _cleanup_strv_free_ char **s = NULL;
6140
6141         if (path_is_absolute(path)) {
6142                 FILE *f;
6143
6144                 f = fopen(path, mode);
6145                 if (f) {
6146                         *_f = f;
6147                         return 0;
6148                 }
6149
6150                 return -errno;
6151         }
6152
6153         s = strv_split_nulstr(search);
6154         if (!s)
6155                 return -ENOMEM;
6156
6157         return search_and_fopen_internal(path, mode, root, s, _f);
6158 }
6159
6160 char *strextend(char **x, ...) {
6161         va_list ap;
6162         size_t f, l;
6163         char *r, *p;
6164
6165         assert(x);
6166
6167         l = f = *x ? strlen(*x) : 0;
6168
6169         va_start(ap, x);
6170         for (;;) {
6171                 const char *t;
6172                 size_t n;
6173
6174                 t = va_arg(ap, const char *);
6175                 if (!t)
6176                         break;
6177
6178                 n = strlen(t);
6179                 if (n > ((size_t) -1) - l) {
6180                         va_end(ap);
6181                         return NULL;
6182                 }
6183
6184                 l += n;
6185         }
6186         va_end(ap);
6187
6188         r = realloc(*x, l+1);
6189         if (!r)
6190                 return NULL;
6191
6192         p = r + f;
6193
6194         va_start(ap, x);
6195         for (;;) {
6196                 const char *t;
6197
6198                 t = va_arg(ap, const char *);
6199                 if (!t)
6200                         break;
6201
6202                 p = stpcpy(p, t);
6203         }
6204         va_end(ap);
6205
6206         *p = 0;
6207         *x = r;
6208
6209         return r + l;
6210 }
6211
6212 char *strrep(const char *s, unsigned n) {
6213         size_t l;
6214         char *r, *p;
6215         unsigned i;
6216
6217         assert(s);
6218
6219         l = strlen(s);
6220         p = r = malloc(l * n + 1);
6221         if (!r)
6222                 return NULL;
6223
6224         for (i = 0; i < n; i++)
6225                 p = stpcpy(p, s);
6226
6227         *p = 0;
6228         return r;
6229 }
6230
6231 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
6232         size_t a, newalloc;
6233         void *q;
6234
6235         assert(p);
6236         assert(allocated);
6237
6238         if (*allocated >= need)
6239                 return *p;
6240
6241         newalloc = MAX(need * 2, 64u / size);
6242         a = newalloc * size;
6243
6244         /* check for overflows */
6245         if (a < size * need)
6246                 return NULL;
6247
6248         q = realloc(*p, a);
6249         if (!q)
6250                 return NULL;
6251
6252         *p = q;
6253         *allocated = newalloc;
6254         return q;
6255 }
6256
6257 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
6258         size_t prev;
6259         uint8_t *q;
6260
6261         assert(p);
6262         assert(allocated);
6263
6264         prev = *allocated;
6265
6266         q = greedy_realloc(p, allocated, need, size);
6267         if (!q)
6268                 return NULL;
6269
6270         if (*allocated > prev)
6271                 memzero(q + prev * size, (*allocated - prev) * size);
6272
6273         return q;
6274 }
6275
6276 bool id128_is_valid(const char *s) {
6277         size_t i, l;
6278
6279         l = strlen(s);
6280         if (l == 32) {
6281
6282                 /* Simple formatted 128bit hex string */
6283
6284                 for (i = 0; i < l; i++) {
6285                         char c = s[i];
6286
6287                         if (!(c >= '0' && c <= '9') &&
6288                             !(c >= 'a' && c <= 'z') &&
6289                             !(c >= 'A' && c <= 'Z'))
6290                                 return false;
6291                 }
6292
6293         } else if (l == 36) {
6294
6295                 /* Formatted UUID */
6296
6297                 for (i = 0; i < l; i++) {
6298                         char c = s[i];
6299
6300                         if ((i == 8 || i == 13 || i == 18 || i == 23)) {
6301                                 if (c != '-')
6302                                         return false;
6303                         } else {
6304                                 if (!(c >= '0' && c <= '9') &&
6305                                     !(c >= 'a' && c <= 'z') &&
6306                                     !(c >= 'A' && c <= 'Z'))
6307                                         return false;
6308                         }
6309                 }
6310
6311         } else
6312                 return false;
6313
6314         return true;
6315 }
6316
6317 int split_pair(const char *s, const char *sep, char **l, char **r) {
6318         char *x, *a, *b;
6319
6320         assert(s);
6321         assert(sep);
6322         assert(l);
6323         assert(r);
6324
6325         if (isempty(sep))
6326                 return -EINVAL;
6327
6328         x = strstr(s, sep);
6329         if (!x)
6330                 return -EINVAL;
6331
6332         a = strndup(s, x - s);
6333         if (!a)
6334                 return -ENOMEM;
6335
6336         b = strdup(x + strlen(sep));
6337         if (!b) {
6338                 free(a);
6339                 return -ENOMEM;
6340         }
6341
6342         *l = a;
6343         *r = b;
6344
6345         return 0;
6346 }
6347
6348 int shall_restore_state(void) {
6349         _cleanup_free_ char *value = NULL;
6350         int r;
6351
6352         r = get_proc_cmdline_key("systemd.restore_state=", &value);
6353         if (r < 0)
6354                 return r;
6355         if (r == 0)
6356                 return true;
6357
6358         return parse_boolean(value) != 0;
6359 }
6360
6361 int proc_cmdline(char **ret) {
6362         assert(ret);
6363
6364         if (detect_container(NULL) > 0)
6365                 return get_process_cmdline(1, 0, false, ret);
6366         else
6367                 return read_one_line_file("/proc/cmdline", ret);
6368 }
6369
6370 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
6371         _cleanup_free_ char *line = NULL;
6372         const char *p;
6373         int r;
6374
6375         assert(parse_item);
6376
6377         r = proc_cmdline(&line);
6378         if (r < 0)
6379                 return r;
6380
6381         p = line;
6382         for (;;) {
6383                 _cleanup_free_ char *word = NULL;
6384                 char *value = NULL;
6385
6386                 r = unquote_first_word(&p, &word, true);
6387                 if (r < 0)
6388                         return r;
6389                 if (r == 0)
6390                         break;
6391
6392                 /* Filter out arguments that are intended only for the
6393                  * initrd */
6394                 if (!in_initrd() && startswith(word, "rd."))
6395                         continue;
6396
6397                 value = strchr(word, '=');
6398                 if (value)
6399                         *(value++) = 0;
6400
6401                 r = parse_item(word, value);
6402                 if (r < 0)
6403                         return r;
6404         }
6405
6406         return 0;
6407 }
6408
6409 int get_proc_cmdline_key(const char *key, char **value) {
6410         _cleanup_free_ char *line = NULL, *ret = NULL;
6411         bool found = false;
6412         const char *p;
6413         int r;
6414
6415         assert(key);
6416
6417         r = proc_cmdline(&line);
6418         if (r < 0)
6419                 return r;
6420
6421         p = line;
6422         for (;;) {
6423                 _cleanup_free_ char *word = NULL;
6424                 const char *e;
6425
6426                 r = unquote_first_word(&p, &word, true);
6427                 if (r < 0)
6428                         return r;
6429                 if (r == 0)
6430                         break;
6431
6432                 /* Filter out arguments that are intended only for the
6433                  * initrd */
6434                 if (!in_initrd() && startswith(word, "rd."))
6435                         continue;
6436
6437                 if (value) {
6438                         e = startswith(word, key);
6439                         if (!e)
6440                                 continue;
6441
6442                         r = free_and_strdup(&ret, e);
6443                         if (r < 0)
6444                                 return r;
6445
6446                         found = true;
6447                 } else {
6448                         if (streq(word, key))
6449                                 found = true;
6450                 }
6451         }
6452
6453         if (value) {
6454                 *value = ret;
6455                 ret = NULL;
6456         }
6457
6458         return found;
6459
6460 }
6461
6462 int container_get_leader(const char *machine, pid_t *pid) {
6463         _cleanup_free_ char *s = NULL, *class = NULL;
6464         const char *p;
6465         pid_t leader;
6466         int r;
6467
6468         assert(machine);
6469         assert(pid);
6470
6471         p = strjoina("/run/systemd/machines/", machine);
6472         r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
6473         if (r == -ENOENT)
6474                 return -EHOSTDOWN;
6475         if (r < 0)
6476                 return r;
6477         if (!s)
6478                 return -EIO;
6479
6480         if (!streq_ptr(class, "container"))
6481                 return -EIO;
6482
6483         r = parse_pid(s, &leader);
6484         if (r < 0)
6485                 return r;
6486         if (leader <= 1)
6487                 return -EIO;
6488
6489         *pid = leader;
6490         return 0;
6491 }
6492
6493 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
6494         _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
6495         int rfd = -1;
6496
6497         assert(pid >= 0);
6498
6499         if (mntns_fd) {
6500                 const char *mntns;
6501
6502                 mntns = procfs_file_alloca(pid, "ns/mnt");
6503                 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6504                 if (mntnsfd < 0)
6505                         return -errno;
6506         }
6507
6508         if (pidns_fd) {
6509                 const char *pidns;
6510
6511                 pidns = procfs_file_alloca(pid, "ns/pid");
6512                 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6513                 if (pidnsfd < 0)
6514                         return -errno;
6515         }
6516
6517         if (netns_fd) {
6518                 const char *netns;
6519
6520                 netns = procfs_file_alloca(pid, "ns/net");
6521                 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6522                 if (netnsfd < 0)
6523                         return -errno;
6524         }
6525
6526         if (root_fd) {
6527                 const char *root;
6528
6529                 root = procfs_file_alloca(pid, "root");
6530                 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
6531                 if (rfd < 0)
6532                         return -errno;
6533         }
6534
6535         if (pidns_fd)
6536                 *pidns_fd = pidnsfd;
6537
6538         if (mntns_fd)
6539                 *mntns_fd = mntnsfd;
6540
6541         if (netns_fd)
6542                 *netns_fd = netnsfd;
6543
6544         if (root_fd)
6545                 *root_fd = rfd;
6546
6547         pidnsfd = mntnsfd = netnsfd = -1;
6548
6549         return 0;
6550 }
6551
6552 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
6553
6554         if (pidns_fd >= 0)
6555                 if (setns(pidns_fd, CLONE_NEWPID) < 0)
6556                         return -errno;
6557
6558         if (mntns_fd >= 0)
6559                 if (setns(mntns_fd, CLONE_NEWNS) < 0)
6560                         return -errno;
6561
6562         if (netns_fd >= 0)
6563                 if (setns(netns_fd, CLONE_NEWNET) < 0)
6564                         return -errno;
6565
6566         if (root_fd >= 0) {
6567                 if (fchdir(root_fd) < 0)
6568                         return -errno;
6569
6570                 if (chroot(".") < 0)
6571                         return -errno;
6572         }
6573
6574         if (setresgid(0, 0, 0) < 0)
6575                 return -errno;
6576
6577         if (setgroups(0, NULL) < 0)
6578                 return -errno;
6579
6580         if (setresuid(0, 0, 0) < 0)
6581                 return -errno;
6582
6583         return 0;
6584 }
6585
6586 bool pid_is_unwaited(pid_t pid) {
6587         /* Checks whether a PID is still valid at all, including a zombie */
6588
6589         if (pid <= 0)
6590                 return false;
6591
6592         if (kill(pid, 0) >= 0)
6593                 return true;
6594
6595         return errno != ESRCH;
6596 }
6597
6598 bool pid_is_alive(pid_t pid) {
6599         int r;
6600
6601         /* Checks whether a PID is still valid and not a zombie */
6602
6603         if (pid <= 0)
6604                 return false;
6605
6606         r = get_process_state(pid);
6607         if (r == -ENOENT || r == 'Z')
6608                 return false;
6609
6610         return true;
6611 }
6612
6613 int getpeercred(int fd, struct ucred *ucred) {
6614         socklen_t n = sizeof(struct ucred);
6615         struct ucred u;
6616         int r;
6617
6618         assert(fd >= 0);
6619         assert(ucred);
6620
6621         r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
6622         if (r < 0)
6623                 return -errno;
6624
6625         if (n != sizeof(struct ucred))
6626                 return -EIO;
6627
6628         /* Check if the data is actually useful and not suppressed due
6629          * to namespacing issues */
6630         if (u.pid <= 0)
6631                 return -ENODATA;
6632         if (u.uid == UID_INVALID)
6633                 return -ENODATA;
6634         if (u.gid == GID_INVALID)
6635                 return -ENODATA;
6636
6637         *ucred = u;
6638         return 0;
6639 }
6640
6641 int getpeersec(int fd, char **ret) {
6642         socklen_t n = 64;
6643         char *s;
6644         int r;
6645
6646         assert(fd >= 0);
6647         assert(ret);
6648
6649         s = new0(char, n);
6650         if (!s)
6651                 return -ENOMEM;
6652
6653         r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6654         if (r < 0) {
6655                 free(s);
6656
6657                 if (errno != ERANGE)
6658                         return -errno;
6659
6660                 s = new0(char, n);
6661                 if (!s)
6662                         return -ENOMEM;
6663
6664                 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6665                 if (r < 0) {
6666                         free(s);
6667                         return -errno;
6668                 }
6669         }
6670
6671         if (isempty(s)) {
6672                 free(s);
6673                 return -EOPNOTSUPP;
6674         }
6675
6676         *ret = s;
6677         return 0;
6678 }
6679
6680 /* This is much like like mkostemp() but is subject to umask(). */
6681 int mkostemp_safe(char *pattern, int flags) {
6682         _cleanup_umask_ mode_t u;
6683         int fd;
6684
6685         assert(pattern);
6686
6687         u = umask(077);
6688
6689         fd = mkostemp(pattern, flags);
6690         if (fd < 0)
6691                 return -errno;
6692
6693         return fd;
6694 }
6695
6696 int open_tmpfile(const char *path, int flags) {
6697         char *p;
6698         int fd;
6699
6700         assert(path);
6701
6702 #ifdef O_TMPFILE
6703         /* Try O_TMPFILE first, if it is supported */
6704         fd = open(path, flags|O_TMPFILE, S_IRUSR|S_IWUSR);
6705         if (fd >= 0)
6706                 return fd;
6707 #endif
6708
6709         /* Fall back to unguessable name + unlinking */
6710         p = strjoina(path, "/systemd-tmp-XXXXXX");
6711
6712         fd = mkostemp_safe(p, flags);
6713         if (fd < 0)
6714                 return fd;
6715
6716         unlink(p);
6717         return fd;
6718 }
6719
6720 int fd_warn_permissions(const char *path, int fd) {
6721         struct stat st;
6722
6723         if (fstat(fd, &st) < 0)
6724                 return -errno;
6725
6726         if (st.st_mode & 0111)
6727                 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
6728
6729         if (st.st_mode & 0002)
6730                 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
6731
6732         if (getpid() == 1 && (st.st_mode & 0044) != 0044)
6733                 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);
6734
6735         return 0;
6736 }
6737
6738 unsigned long personality_from_string(const char *p) {
6739
6740         /* Parse a personality specifier. We introduce our own
6741          * identifiers that indicate specific ABIs, rather than just
6742          * hints regarding the register size, since we want to keep
6743          * things open for multiple locally supported ABIs for the
6744          * same register size. We try to reuse the ABI identifiers
6745          * used by libseccomp. */
6746
6747 #if defined(__x86_64__)
6748
6749         if (streq(p, "x86"))
6750                 return PER_LINUX32;
6751
6752         if (streq(p, "x86-64"))
6753                 return PER_LINUX;
6754
6755 #elif defined(__i386__)
6756
6757         if (streq(p, "x86"))
6758                 return PER_LINUX;
6759 #endif
6760
6761         /* personality(7) documents that 0xffffffffUL is used for
6762          * querying the current personality, hence let's use that here
6763          * as error indicator. */
6764         return 0xffffffffUL;
6765 }
6766
6767 const char* personality_to_string(unsigned long p) {
6768
6769 #if defined(__x86_64__)
6770
6771         if (p == PER_LINUX32)
6772                 return "x86";
6773
6774         if (p == PER_LINUX)
6775                 return "x86-64";
6776
6777 #elif defined(__i386__)
6778
6779         if (p == PER_LINUX)
6780                 return "x86";
6781 #endif
6782
6783         return NULL;
6784 }
6785
6786 uint64_t physical_memory(void) {
6787         long mem;
6788
6789         /* We return this as uint64_t in case we are running as 32bit
6790          * process on a 64bit kernel with huge amounts of memory */
6791
6792         mem = sysconf(_SC_PHYS_PAGES);
6793         assert(mem > 0);
6794
6795         return (uint64_t) mem * (uint64_t) page_size();
6796 }
6797
6798 void hexdump(FILE *f, const void *p, size_t s) {
6799         const uint8_t *b = p;
6800         unsigned n = 0;
6801
6802         assert(s == 0 || b);
6803
6804         while (s > 0) {
6805                 size_t i;
6806
6807                 fprintf(f, "%04x  ", n);
6808
6809                 for (i = 0; i < 16; i++) {
6810
6811                         if (i >= s)
6812                                 fputs("   ", f);
6813                         else
6814                                 fprintf(f, "%02x ", b[i]);
6815
6816                         if (i == 7)
6817                                 fputc(' ', f);
6818                 }
6819
6820                 fputc(' ', f);
6821
6822                 for (i = 0; i < 16; i++) {
6823
6824                         if (i >= s)
6825                                 fputc(' ', f);
6826                         else
6827                                 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
6828                 }
6829
6830                 fputc('\n', f);
6831
6832                 if (s < 16)
6833                         break;
6834
6835                 n += 16;
6836                 b += 16;
6837                 s -= 16;
6838         }
6839 }
6840
6841 int update_reboot_param_file(const char *param) {
6842         int r = 0;
6843
6844         if (param) {
6845
6846                 r = write_string_file(REBOOT_PARAM_FILE, param);
6847                 if (r < 0)
6848                         log_error("Failed to write reboot param to "
6849                                   REBOOT_PARAM_FILE": %s", strerror(-r));
6850         } else
6851                 unlink(REBOOT_PARAM_FILE);
6852
6853         return r;
6854 }
6855
6856 int umount_recursive(const char *prefix, int flags) {
6857         bool again;
6858         int n = 0, r;
6859
6860         /* Try to umount everything recursively below a
6861          * directory. Also, take care of stacked mounts, and keep
6862          * unmounting them until they are gone. */
6863
6864         do {
6865                 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6866
6867                 again = false;
6868                 r = 0;
6869
6870                 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6871                 if (!proc_self_mountinfo)
6872                         return -errno;
6873
6874                 for (;;) {
6875                         _cleanup_free_ char *path = NULL, *p = NULL;
6876                         int k;
6877
6878                         k = fscanf(proc_self_mountinfo,
6879                                    "%*s "       /* (1) mount id */
6880                                    "%*s "       /* (2) parent id */
6881                                    "%*s "       /* (3) major:minor */
6882                                    "%*s "       /* (4) root */
6883                                    "%ms "       /* (5) mount point */
6884                                    "%*s"        /* (6) mount options */
6885                                    "%*[^-]"     /* (7) optional fields */
6886                                    "- "         /* (8) separator */
6887                                    "%*s "       /* (9) file system type */
6888                                    "%*s"        /* (10) mount source */
6889                                    "%*s"        /* (11) mount options 2 */
6890                                    "%*[^\n]",   /* some rubbish at the end */
6891                                    &path);
6892                         if (k != 1) {
6893                                 if (k == EOF)
6894                                         break;
6895
6896                                 continue;
6897                         }
6898
6899                         p = cunescape(path);
6900                         if (!p)
6901                                 return -ENOMEM;
6902
6903                         if (!path_startswith(p, prefix))
6904                                 continue;
6905
6906                         if (umount2(p, flags) < 0) {
6907                                 r = -errno;
6908                                 continue;
6909                         }
6910
6911                         again = true;
6912                         n++;
6913
6914                         break;
6915                 }
6916
6917         } while (again);
6918
6919         return r ? r : n;
6920 }
6921
6922 static int get_mount_flags(const char *path, unsigned long *flags) {
6923         struct statvfs buf;
6924
6925         if (statvfs(path, &buf) < 0)
6926                 return -errno;
6927         *flags = buf.f_flag;
6928         return 0;
6929 }
6930
6931 int bind_remount_recursive(const char *prefix, bool ro) {
6932         _cleanup_set_free_free_ Set *done = NULL;
6933         _cleanup_free_ char *cleaned = NULL;
6934         int r;
6935
6936         /* Recursively remount a directory (and all its submounts)
6937          * read-only or read-write. If the directory is already
6938          * mounted, we reuse the mount and simply mark it
6939          * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
6940          * operation). If it isn't we first make it one. Afterwards we
6941          * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
6942          * submounts we can access, too. When mounts are stacked on
6943          * the same mount point we only care for each individual
6944          * "top-level" mount on each point, as we cannot
6945          * influence/access the underlying mounts anyway. We do not
6946          * have any effect on future submounts that might get
6947          * propagated, they migt be writable. This includes future
6948          * submounts that have been triggered via autofs. */
6949
6950         cleaned = strdup(prefix);
6951         if (!cleaned)
6952                 return -ENOMEM;
6953
6954         path_kill_slashes(cleaned);
6955
6956         done = set_new(&string_hash_ops);
6957         if (!done)
6958                 return -ENOMEM;
6959
6960         for (;;) {
6961                 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6962                 _cleanup_set_free_free_ Set *todo = NULL;
6963                 bool top_autofs = false;
6964                 char *x;
6965                 unsigned long orig_flags;
6966
6967                 todo = set_new(&string_hash_ops);
6968                 if (!todo)
6969                         return -ENOMEM;
6970
6971                 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6972                 if (!proc_self_mountinfo)
6973                         return -errno;
6974
6975                 for (;;) {
6976                         _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
6977                         int k;
6978
6979                         k = fscanf(proc_self_mountinfo,
6980                                    "%*s "       /* (1) mount id */
6981                                    "%*s "       /* (2) parent id */
6982                                    "%*s "       /* (3) major:minor */
6983                                    "%*s "       /* (4) root */
6984                                    "%ms "       /* (5) mount point */
6985                                    "%*s"        /* (6) mount options (superblock) */
6986                                    "%*[^-]"     /* (7) optional fields */
6987                                    "- "         /* (8) separator */
6988                                    "%ms "       /* (9) file system type */
6989                                    "%*s"        /* (10) mount source */
6990                                    "%*s"        /* (11) mount options (bind mount) */
6991                                    "%*[^\n]",   /* some rubbish at the end */
6992                                    &path,
6993                                    &type);
6994                         if (k != 2) {
6995                                 if (k == EOF)
6996                                         break;
6997
6998                                 continue;
6999                         }
7000
7001                         p = cunescape(path);
7002                         if (!p)
7003                                 return -ENOMEM;
7004
7005                         /* Let's ignore autofs mounts.  If they aren't
7006                          * triggered yet, we want to avoid triggering
7007                          * them, as we don't make any guarantees for
7008                          * future submounts anyway.  If they are
7009                          * already triggered, then we will find
7010                          * another entry for this. */
7011                         if (streq(type, "autofs")) {
7012                                 top_autofs = top_autofs || path_equal(cleaned, p);
7013                                 continue;
7014                         }
7015
7016                         if (path_startswith(p, cleaned) &&
7017                             !set_contains(done, p)) {
7018
7019                                 r = set_consume(todo, p);
7020                                 p = NULL;
7021
7022                                 if (r == -EEXIST)
7023                                         continue;
7024                                 if (r < 0)
7025                                         return r;
7026                         }
7027                 }
7028
7029                 /* If we have no submounts to process anymore and if
7030                  * the root is either already done, or an autofs, we
7031                  * are done */
7032                 if (set_isempty(todo) &&
7033                     (top_autofs || set_contains(done, cleaned)))
7034                         return 0;
7035
7036                 if (!set_contains(done, cleaned) &&
7037                     !set_contains(todo, cleaned)) {
7038                         /* The prefix directory itself is not yet a
7039                          * mount, make it one. */
7040                         if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
7041                                 return -errno;
7042
7043                         orig_flags = 0;
7044                         (void) get_mount_flags(cleaned, &orig_flags);
7045                         orig_flags &= ~MS_RDONLY;
7046
7047                         if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
7048                                 return -errno;
7049
7050                         x = strdup(cleaned);
7051                         if (!x)
7052                                 return -ENOMEM;
7053
7054                         r = set_consume(done, x);
7055                         if (r < 0)
7056                                 return r;
7057                 }
7058
7059                 while ((x = set_steal_first(todo))) {
7060
7061                         r = set_consume(done, x);
7062                         if (r == -EEXIST)
7063                                 continue;
7064                         if (r < 0)
7065                                 return r;
7066
7067                         /* Try to reuse the original flag set, but
7068                          * don't care for errors, in case of
7069                          * obstructed mounts */
7070                         orig_flags = 0;
7071                         (void) get_mount_flags(x, &orig_flags);
7072                         orig_flags &= ~MS_RDONLY;
7073
7074                         if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
7075
7076                                 /* Deal with mount points that are
7077                                  * obstructed by a later mount */
7078
7079                                 if (errno != ENOENT)
7080                                         return -errno;
7081                         }
7082
7083                 }
7084         }
7085 }
7086
7087 int fflush_and_check(FILE *f) {
7088         assert(f);
7089
7090         errno = 0;
7091         fflush(f);
7092
7093         if (ferror(f))
7094                 return errno ? -errno : -EIO;
7095
7096         return 0;
7097 }
7098
7099 int tempfn_xxxxxx(const char *p, char **ret) {
7100         const char *fn;
7101         char *t;
7102
7103         assert(p);
7104         assert(ret);
7105
7106         /*
7107          * Turns this:
7108          *         /foo/bar/waldo
7109          *
7110          * Into this:
7111          *         /foo/bar/.#waldoXXXXXX
7112          */
7113
7114         fn = basename(p);
7115         if (!filename_is_valid(fn))
7116                 return -EINVAL;
7117
7118         t = new(char, strlen(p) + 2 + 6 + 1);
7119         if (!t)
7120                 return -ENOMEM;
7121
7122         strcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), "XXXXXX");
7123
7124         *ret = path_kill_slashes(t);
7125         return 0;
7126 }
7127
7128 int tempfn_random(const char *p, char **ret) {
7129         const char *fn;
7130         char *t, *x;
7131         uint64_t u;
7132         unsigned i;
7133
7134         assert(p);
7135         assert(ret);
7136
7137         /*
7138          * Turns this:
7139          *         /foo/bar/waldo
7140          *
7141          * Into this:
7142          *         /foo/bar/.#waldobaa2a261115984a9
7143          */
7144
7145         fn = basename(p);
7146         if (!filename_is_valid(fn))
7147                 return -EINVAL;
7148
7149         t = new(char, strlen(p) + 2 + 16 + 1);
7150         if (!t)
7151                 return -ENOMEM;
7152
7153         x = stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn);
7154
7155         u = random_u64();
7156         for (i = 0; i < 16; i++) {
7157                 *(x++) = hexchar(u & 0xF);
7158                 u >>= 4;
7159         }
7160
7161         *x = 0;
7162
7163         *ret = path_kill_slashes(t);
7164         return 0;
7165 }
7166
7167 int tempfn_random_child(const char *p, char **ret) {
7168         char *t, *x;
7169         uint64_t u;
7170         unsigned i;
7171
7172         assert(p);
7173         assert(ret);
7174
7175         /* Turns this:
7176          *         /foo/bar/waldo
7177          * Into this:
7178          *         /foo/bar/waldo/.#3c2b6219aa75d7d0
7179          */
7180
7181         t = new(char, strlen(p) + 3 + 16 + 1);
7182         if (!t)
7183                 return -ENOMEM;
7184
7185         x = stpcpy(stpcpy(t, p), "/.#");
7186
7187         u = random_u64();
7188         for (i = 0; i < 16; i++) {
7189                 *(x++) = hexchar(u & 0xF);
7190                 u >>= 4;
7191         }
7192
7193         *x = 0;
7194
7195         *ret = path_kill_slashes(t);
7196         return 0;
7197 }
7198
7199 /* make sure the hostname is not "localhost" */
7200 bool is_localhost(const char *hostname) {
7201         assert(hostname);
7202
7203         /* This tries to identify local host and domain names
7204          * described in RFC6761 plus the redhatism of .localdomain */
7205
7206         return streq(hostname, "localhost") ||
7207                streq(hostname, "localhost.") ||
7208                streq(hostname, "localdomain.") ||
7209                streq(hostname, "localdomain") ||
7210                endswith(hostname, ".localhost") ||
7211                endswith(hostname, ".localhost.") ||
7212                endswith(hostname, ".localdomain") ||
7213                endswith(hostname, ".localdomain.");
7214 }
7215
7216 int take_password_lock(const char *root) {
7217
7218         struct flock flock = {
7219                 .l_type = F_WRLCK,
7220                 .l_whence = SEEK_SET,
7221                 .l_start = 0,
7222                 .l_len = 0,
7223         };
7224
7225         const char *path;
7226         int fd, r;
7227
7228         /* This is roughly the same as lckpwdf(), but not as awful. We
7229          * don't want to use alarm() and signals, hence we implement
7230          * our own trivial version of this.
7231          *
7232          * Note that shadow-utils also takes per-database locks in
7233          * addition to lckpwdf(). However, we don't given that they
7234          * are redundant as they they invoke lckpwdf() first and keep
7235          * it during everything they do. The per-database locks are
7236          * awfully racy, and thus we just won't do them. */
7237
7238         if (root)
7239                 path = strjoina(root, "/etc/.pwd.lock");
7240         else
7241                 path = "/etc/.pwd.lock";
7242
7243         fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
7244         if (fd < 0)
7245                 return -errno;
7246
7247         r = fcntl(fd, F_SETLKW, &flock);
7248         if (r < 0) {
7249                 safe_close(fd);
7250                 return -errno;
7251         }
7252
7253         return fd;
7254 }
7255
7256 int is_symlink(const char *path) {
7257         struct stat info;
7258
7259         if (lstat(path, &info) < 0)
7260                 return -errno;
7261
7262         return !!S_ISLNK(info.st_mode);
7263 }
7264
7265 int is_dir(const char* path, bool follow) {
7266         struct stat st;
7267         int r;
7268
7269         if (follow)
7270                 r = stat(path, &st);
7271         else
7272                 r = lstat(path, &st);
7273         if (r < 0)
7274                 return -errno;
7275
7276         return !!S_ISDIR(st.st_mode);
7277 }
7278
7279 int unquote_first_word(const char **p, char **ret, bool relax) {
7280         _cleanup_free_ char *s = NULL;
7281         size_t allocated = 0, sz = 0;
7282
7283         enum {
7284                 START,
7285                 VALUE,
7286                 VALUE_ESCAPE,
7287                 SINGLE_QUOTE,
7288                 SINGLE_QUOTE_ESCAPE,
7289                 DOUBLE_QUOTE,
7290                 DOUBLE_QUOTE_ESCAPE,
7291                 SPACE,
7292         } state = START;
7293
7294         assert(p);
7295         assert(*p);
7296         assert(ret);
7297
7298         /* Parses the first word of a string, and returns it in
7299          * *ret. Removes all quotes in the process. When parsing fails
7300          * (because of an uneven number of quotes or similar), leaves
7301          * the pointer *p at the first invalid character. */
7302
7303         for (;;) {
7304                 char c = **p;
7305
7306                 switch (state) {
7307
7308                 case START:
7309                         if (c == 0)
7310                                 goto finish;
7311                         else if (strchr(WHITESPACE, c))
7312                                 break;
7313
7314                         state = VALUE;
7315                         /* fallthrough */
7316
7317                 case VALUE:
7318                         if (c == 0)
7319                                 goto finish;
7320                         else if (c == '\'')
7321                                 state = SINGLE_QUOTE;
7322                         else if (c == '\\')
7323                                 state = VALUE_ESCAPE;
7324                         else if (c == '\"')
7325                                 state = DOUBLE_QUOTE;
7326                         else if (strchr(WHITESPACE, c))
7327                                 state = SPACE;
7328                         else {
7329                                 if (!GREEDY_REALLOC(s, allocated, sz+2))
7330                                         return -ENOMEM;
7331
7332                                 s[sz++] = c;
7333                         }
7334
7335                         break;
7336
7337                 case VALUE_ESCAPE:
7338                         if (c == 0) {
7339                                 if (relax)
7340                                         goto finish;
7341                                 return -EINVAL;
7342                         }
7343
7344                         if (!GREEDY_REALLOC(s, allocated, sz+2))
7345                                 return -ENOMEM;
7346
7347                         s[sz++] = c;
7348                         state = VALUE;
7349
7350                         break;
7351
7352                 case SINGLE_QUOTE:
7353                         if (c == 0) {
7354                                 if (relax)
7355                                         goto finish;
7356                                 return -EINVAL;
7357                         } else if (c == '\'')
7358                                 state = VALUE;
7359                         else if (c == '\\')
7360                                 state = SINGLE_QUOTE_ESCAPE;
7361                         else {
7362                                 if (!GREEDY_REALLOC(s, allocated, sz+2))
7363                                         return -ENOMEM;
7364
7365                                 s[sz++] = c;
7366                         }
7367
7368                         break;
7369
7370                 case SINGLE_QUOTE_ESCAPE:
7371                         if (c == 0) {
7372                                 if (relax)
7373                                         goto finish;
7374                                 return -EINVAL;
7375                         }
7376
7377                         if (!GREEDY_REALLOC(s, allocated, sz+2))
7378                                 return -ENOMEM;
7379
7380                         s[sz++] = c;
7381                         state = SINGLE_QUOTE;
7382                         break;
7383
7384                 case DOUBLE_QUOTE:
7385                         if (c == 0)
7386                                 return -EINVAL;
7387                         else if (c == '\"')
7388                                 state = VALUE;
7389                         else if (c == '\\')
7390                                 state = DOUBLE_QUOTE_ESCAPE;
7391                         else {
7392                                 if (!GREEDY_REALLOC(s, allocated, sz+2))
7393                                         return -ENOMEM;
7394
7395                                 s[sz++] = c;
7396                         }
7397
7398                         break;
7399
7400                 case DOUBLE_QUOTE_ESCAPE:
7401                         if (c == 0) {
7402                                 if (relax)
7403                                         goto finish;
7404                                 return -EINVAL;
7405                         }
7406
7407                         if (!GREEDY_REALLOC(s, allocated, sz+2))
7408                                 return -ENOMEM;
7409
7410                         s[sz++] = c;
7411                         state = DOUBLE_QUOTE;
7412                         break;
7413
7414                 case SPACE:
7415                         if (c == 0)
7416                                 goto finish;
7417                         if (!strchr(WHITESPACE, c))
7418                                 goto finish;
7419
7420                         break;
7421                 }
7422
7423                 (*p) ++;
7424         }
7425
7426 finish:
7427         if (!s) {
7428                 *ret = NULL;
7429                 return 0;
7430         }
7431
7432         s[sz] = 0;
7433         *ret = s;
7434         s = NULL;
7435
7436         return 1;
7437 }
7438
7439 int unquote_many_words(const char **p, ...) {
7440         va_list ap;
7441         char **l;
7442         int n = 0, i, c, r;
7443
7444         /* Parses a number of words from a string, stripping any
7445          * quotes if necessary. */
7446
7447         assert(p);
7448
7449         /* Count how many words are expected */
7450         va_start(ap, p);
7451         for (;;) {
7452                 if (!va_arg(ap, char **))
7453                         break;
7454                 n++;
7455         }
7456         va_end(ap);
7457
7458         if (n <= 0)
7459                 return 0;
7460
7461         /* Read all words into a temporary array */
7462         l = newa0(char*, n);
7463         for (c = 0; c < n; c++) {
7464
7465                 r = unquote_first_word(p, &l[c], false);
7466                 if (r < 0) {
7467                         int j;
7468
7469                         for (j = 0; j < c; j++)
7470                                 free(l[j]);
7471
7472                         return r;
7473                 }
7474
7475                 if (r == 0)
7476                         break;
7477         }
7478
7479         /* If we managed to parse all words, return them in the passed
7480          * in parameters */
7481         va_start(ap, p);
7482         for (i = 0; i < n; i++) {
7483                 char **v;
7484
7485                 v = va_arg(ap, char **);
7486                 assert(v);
7487
7488                 *v = l[i];
7489         }
7490         va_end(ap);
7491
7492         return c;
7493 }
7494
7495 int free_and_strdup(char **p, const char *s) {
7496         char *t;
7497
7498         assert(p);
7499
7500         /* Replaces a string pointer with an strdup()ed new string,
7501          * possibly freeing the old one. */
7502
7503         if (s) {
7504                 t = strdup(s);
7505                 if (!t)
7506                         return -ENOMEM;
7507         } else
7508                 t = NULL;
7509
7510         free(*p);
7511         *p = t;
7512
7513         return 0;
7514 }
7515
7516 int sethostname_idempotent(const char *s) {
7517         int r;
7518         char buf[HOST_NAME_MAX + 1] = {};
7519
7520         assert(s);
7521
7522         r = gethostname(buf, sizeof(buf));
7523         if (r < 0)
7524                 return -errno;
7525
7526         if (streq(buf, s))
7527                 return 0;
7528
7529         r = sethostname(s, strlen(s));
7530         if (r < 0)
7531                 return -errno;
7532
7533         return 1;
7534 }
7535
7536 int ptsname_malloc(int fd, char **ret) {
7537         size_t l = 100;
7538
7539         assert(fd >= 0);
7540         assert(ret);
7541
7542         for (;;) {
7543                 char *c;
7544
7545                 c = new(char, l);
7546                 if (!c)
7547                         return -ENOMEM;
7548
7549                 if (ptsname_r(fd, c, l) == 0) {
7550                         *ret = c;
7551                         return 0;
7552                 }
7553                 if (errno != ERANGE) {
7554                         free(c);
7555                         return -errno;
7556                 }
7557
7558                 free(c);
7559                 l *= 2;
7560         }
7561 }
7562
7563 int openpt_in_namespace(pid_t pid, int flags) {
7564         _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
7565         _cleanup_close_pair_ int pair[2] = { -1, -1 };
7566         union {
7567                 struct cmsghdr cmsghdr;
7568                 uint8_t buf[CMSG_SPACE(sizeof(int))];
7569         } control = {};
7570         struct msghdr mh = {
7571                 .msg_control = &control,
7572                 .msg_controllen = sizeof(control),
7573         };
7574         struct cmsghdr *cmsg;
7575         siginfo_t si;
7576         pid_t child;
7577         int r;
7578
7579         assert(pid > 0);
7580
7581         r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
7582         if (r < 0)
7583                 return r;
7584
7585         if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
7586                 return -errno;
7587
7588         child = fork();
7589         if (child < 0)
7590                 return -errno;
7591
7592         if (child == 0) {
7593                 int master;
7594
7595                 pair[0] = safe_close(pair[0]);
7596
7597                 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
7598                 if (r < 0)
7599                         _exit(EXIT_FAILURE);
7600
7601                 master = posix_openpt(flags);
7602                 if (master < 0)
7603                         _exit(EXIT_FAILURE);
7604
7605                 cmsg = CMSG_FIRSTHDR(&mh);
7606                 cmsg->cmsg_level = SOL_SOCKET;
7607                 cmsg->cmsg_type = SCM_RIGHTS;
7608                 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
7609                 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
7610
7611                 mh.msg_controllen = cmsg->cmsg_len;
7612
7613                 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
7614                         _exit(EXIT_FAILURE);
7615
7616                 _exit(EXIT_SUCCESS);
7617         }
7618
7619         pair[1] = safe_close(pair[1]);
7620
7621         r = wait_for_terminate(child, &si);
7622         if (r < 0)
7623                 return r;
7624         if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
7625                 return -EIO;
7626
7627         if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
7628                 return -errno;
7629
7630         for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
7631                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
7632                         int *fds;
7633                         unsigned n_fds;
7634
7635                         fds = (int*) CMSG_DATA(cmsg);
7636                         n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
7637
7638                         if (n_fds != 1) {
7639                                 close_many(fds, n_fds);
7640                                 return -EIO;
7641                         }
7642
7643                         return fds[0];
7644                 }
7645
7646         return -EIO;
7647 }
7648
7649 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
7650         _cleanup_close_ int fd = -1;
7651         ssize_t l;
7652
7653         /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
7654
7655         fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
7656         if (fd < 0)
7657                 return -errno;
7658
7659         l = fgetxattr(fd, attribute, value, size);
7660         if (l < 0)
7661                 return -errno;
7662
7663         return l;
7664 }
7665
7666 static int parse_crtime(le64_t le, usec_t *usec) {
7667         uint64_t u;
7668
7669         assert(usec);
7670
7671         u = le64toh(le);
7672         if (u == 0 || u == (uint64_t) -1)
7673                 return -EIO;
7674
7675         *usec = (usec_t) u;
7676         return 0;
7677 }
7678
7679 int fd_getcrtime(int fd, usec_t *usec) {
7680         le64_t le;
7681         ssize_t n;
7682
7683         assert(fd >= 0);
7684         assert(usec);
7685
7686         /* Until Linux gets a real concept of birthtime/creation time,
7687          * let's fake one with xattrs */
7688
7689         n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
7690         if (n < 0)
7691                 return -errno;
7692         if (n != sizeof(le))
7693                 return -EIO;
7694
7695         return parse_crtime(le, usec);
7696 }
7697
7698 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
7699         le64_t le;
7700         ssize_t n;
7701
7702         n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
7703         if (n < 0)
7704                 return -errno;
7705         if (n != sizeof(le))
7706                 return -EIO;
7707
7708         return parse_crtime(le, usec);
7709 }
7710
7711 int path_getcrtime(const char *p, usec_t *usec) {
7712         le64_t le;
7713         ssize_t n;
7714
7715         assert(p);
7716         assert(usec);
7717
7718         n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
7719         if (n < 0)
7720                 return -errno;
7721         if (n != sizeof(le))
7722                 return -EIO;
7723
7724         return parse_crtime(le, usec);
7725 }
7726
7727 int fd_setcrtime(int fd, usec_t usec) {
7728         le64_t le;
7729
7730         assert(fd >= 0);
7731
7732         if (usec <= 0)
7733                 usec = now(CLOCK_REALTIME);
7734
7735         le = htole64((uint64_t) usec);
7736         if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
7737                 return -errno;
7738
7739         return 0;
7740 }
7741
7742 int same_fd(int a, int b) {
7743         struct stat sta, stb;
7744         pid_t pid;
7745         int r, fa, fb;
7746
7747         assert(a >= 0);
7748         assert(b >= 0);
7749
7750         /* Compares two file descriptors. Note that semantics are
7751          * quite different depending on whether we have kcmp() or we
7752          * don't. If we have kcmp() this will only return true for
7753          * dup()ed file descriptors, but not otherwise. If we don't
7754          * have kcmp() this will also return true for two fds of the same
7755          * file, created by separate open() calls. Since we use this
7756          * call mostly for filtering out duplicates in the fd store
7757          * this difference hopefully doesn't matter too much. */
7758
7759         if (a == b)
7760                 return true;
7761
7762         /* Try to use kcmp() if we have it. */
7763         pid = getpid();
7764         r = kcmp(pid, pid, KCMP_FILE, a, b);
7765         if (r == 0)
7766                 return true;
7767         if (r > 0)
7768                 return false;
7769         if (errno != ENOSYS)
7770                 return -errno;
7771
7772         /* We don't have kcmp(), use fstat() instead. */
7773         if (fstat(a, &sta) < 0)
7774                 return -errno;
7775
7776         if (fstat(b, &stb) < 0)
7777                 return -errno;
7778
7779         if ((sta.st_mode & S_IFMT) != (stb.st_mode & S_IFMT))
7780                 return false;
7781
7782         /* We consider all device fds different, since two device fds
7783          * might refer to quite different device contexts even though
7784          * they share the same inode and backing dev_t. */
7785
7786         if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
7787                 return false;
7788
7789         if (sta.st_dev != stb.st_dev || sta.st_ino != stb.st_ino)
7790                 return false;
7791
7792         /* The fds refer to the same inode on disk, let's also check
7793          * if they have the same fd flags. This is useful to
7794          * distuingish the read and write side of a pipe created with
7795          * pipe(). */
7796         fa = fcntl(a, F_GETFL);
7797         if (fa < 0)
7798                 return -errno;
7799
7800         fb = fcntl(b, F_GETFL);
7801         if (fb < 0)
7802                 return -errno;
7803
7804         return fa == fb;
7805 }
7806
7807 int chattr_fd(int fd, bool b, unsigned mask) {
7808         unsigned old_attr, new_attr;
7809
7810         assert(fd >= 0);
7811
7812         if (mask == 0)
7813                 return 0;
7814
7815         if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
7816                 return -errno;
7817
7818         if (b)
7819                 new_attr = old_attr | mask;
7820         else
7821                 new_attr = old_attr & ~mask;
7822
7823         if (new_attr == old_attr)
7824                 return 0;
7825
7826         if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
7827                 return -errno;
7828
7829         return 0;
7830 }
7831
7832 int chattr_path(const char *p, bool b, unsigned mask) {
7833         _cleanup_close_ int fd = -1;
7834
7835         assert(p);
7836
7837         if (mask == 0)
7838                 return 0;
7839
7840         fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
7841         if (fd < 0)
7842                 return -errno;
7843
7844         return chattr_fd(fd, b, mask);
7845 }
7846
7847 int read_attr_fd(int fd, unsigned *ret) {
7848         assert(fd >= 0);
7849
7850         if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
7851                 return -errno;
7852
7853         return 0;
7854 }
7855
7856 int read_attr_path(const char *p, unsigned *ret) {
7857         _cleanup_close_ int fd = -1;
7858
7859         assert(p);
7860         assert(ret);
7861
7862         fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
7863         if (fd < 0)
7864                 return -errno;
7865
7866         return read_attr_fd(fd, ret);
7867 }
7868
7869 int make_lock_file(const char *p, int operation, LockFile *ret) {
7870         _cleanup_close_ int fd = -1;
7871         _cleanup_free_ char *t = NULL;
7872         int r;
7873
7874         /*
7875          * We use UNPOSIX locks if they are available. They have nice
7876          * semantics, and are mostly compatible with NFS. However,
7877          * they are only available on new kernels. When we detect we
7878          * are running on an older kernel, then we fall back to good
7879          * old BSD locks. They also have nice semantics, but are
7880          * slightly problematic on NFS, where they are upgraded to
7881          * POSIX locks, even though locally they are orthogonal to
7882          * POSIX locks.
7883          */
7884
7885         t = strdup(p);
7886         if (!t)
7887                 return -ENOMEM;
7888
7889         for (;;) {
7890                 struct flock fl = {
7891                         .l_type = (operation & ~LOCK_NB) == LOCK_EX ? F_WRLCK : F_RDLCK,
7892                         .l_whence = SEEK_SET,
7893                 };
7894                 struct stat st;
7895
7896                 fd = open(p, O_CREAT|O_RDWR|O_NOFOLLOW|O_CLOEXEC|O_NOCTTY, 0600);
7897                 if (fd < 0)
7898                         return -errno;
7899
7900                 r = fcntl(fd, (operation & LOCK_NB) ? F_OFD_SETLK : F_OFD_SETLKW, &fl);
7901                 if (r < 0) {
7902
7903                         /* If the kernel is too old, use good old BSD locks */
7904                         if (errno == EINVAL)
7905                                 r = flock(fd, operation);
7906
7907                         if (r < 0)
7908                                 return errno == EAGAIN ? -EBUSY : -errno;
7909                 }
7910
7911                 /* If we acquired the lock, let's check if the file
7912                  * still exists in the file system. If not, then the
7913                  * previous exclusive owner removed it and then closed
7914                  * it. In such a case our acquired lock is worthless,
7915                  * hence try again. */
7916
7917                 r = fstat(fd, &st);
7918                 if (r < 0)
7919                         return -errno;
7920                 if (st.st_nlink > 0)
7921                         break;
7922
7923                 fd = safe_close(fd);
7924         }
7925
7926         ret->path = t;
7927         ret->fd = fd;
7928         ret->operation = operation;
7929
7930         fd = -1;
7931         t = NULL;
7932
7933         return r;
7934 }
7935
7936 int make_lock_file_for(const char *p, int operation, LockFile *ret) {
7937         const char *fn;
7938         char *t;
7939
7940         assert(p);
7941         assert(ret);
7942
7943         fn = basename(p);
7944         if (!filename_is_valid(fn))
7945                 return -EINVAL;
7946
7947         t = newa(char, strlen(p) + 2 + 4 + 1);
7948         stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), ".lck");
7949
7950         return make_lock_file(t, operation, ret);
7951 }
7952
7953 void release_lock_file(LockFile *f) {
7954         int r;
7955
7956         if (!f)
7957                 return;
7958
7959         if (f->path) {
7960
7961                 /* If we are the exclusive owner we can safely delete
7962                  * the lock file itself. If we are not the exclusive
7963                  * owner, we can try becoming it. */
7964
7965                 if (f->fd >= 0 &&
7966                     (f->operation & ~LOCK_NB) == LOCK_SH) {
7967                         static const struct flock fl = {
7968                                 .l_type = F_WRLCK,
7969                                 .l_whence = SEEK_SET,
7970                         };
7971
7972                         r = fcntl(f->fd, F_OFD_SETLK, &fl);
7973                         if (r < 0 && errno == EINVAL)
7974                                 r = flock(f->fd, LOCK_EX|LOCK_NB);
7975
7976                         if (r >= 0)
7977                                 f->operation = LOCK_EX|LOCK_NB;
7978                 }
7979
7980                 if ((f->operation & ~LOCK_NB) == LOCK_EX)
7981                         unlink_noerrno(f->path);
7982
7983                 free(f->path);
7984                 f->path = NULL;
7985         }
7986
7987         f->fd = safe_close(f->fd);
7988         f->operation = 0;
7989 }
7990
7991 static size_t nul_length(const uint8_t *p, size_t sz) {
7992         size_t n = 0;
7993
7994         while (sz > 0) {
7995                 if (*p != 0)
7996                         break;
7997
7998                 n++;
7999                 p++;
8000                 sz--;
8001         }
8002
8003         return n;
8004 }
8005
8006 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
8007         const uint8_t *q, *w, *e;
8008         ssize_t l;
8009
8010         q = w = p;
8011         e = q + sz;
8012         while (q < e) {
8013                 size_t n;
8014
8015                 n = nul_length(q, e - q);
8016
8017                 /* If there are more than the specified run length of
8018                  * NUL bytes, or if this is the beginning or the end
8019                  * of the buffer, then seek instead of write */
8020                 if ((n > run_length) ||
8021                     (n > 0 && q == p) ||
8022                     (n > 0 && q + n >= e)) {
8023                         if (q > w) {
8024                                 l = write(fd, w, q - w);
8025                                 if (l < 0)
8026                                         return -errno;
8027                                 if (l != q -w)
8028                                         return -EIO;
8029                         }
8030
8031                         if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
8032                                 return -errno;
8033
8034                         q += n;
8035                         w = q;
8036                 } else if (n > 0)
8037                         q += n;
8038                 else
8039                         q ++;
8040         }
8041
8042         if (q > w) {
8043                 l = write(fd, w, q - w);
8044                 if (l < 0)
8045                         return -errno;
8046                 if (l != q - w)
8047                         return -EIO;
8048         }
8049
8050         return q - (const uint8_t*) p;
8051 }
8052
8053 void sigkill_wait(pid_t *pid) {
8054         if (!pid)
8055                 return;
8056         if (*pid <= 1)
8057                 return;
8058
8059         if (kill(*pid, SIGKILL) > 0)
8060                 (void) wait_for_terminate(*pid, NULL);
8061 }
8062
8063 int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
8064         int a = 0, b = 0, c = 0;
8065         int k;
8066
8067         assert(p);
8068         assert(*p);
8069         assert(priority);
8070
8071         if ((*p)[0] != '<')
8072                 return 0;
8073
8074         if (!strchr(*p, '>'))
8075                 return 0;
8076
8077         if ((*p)[2] == '>') {
8078                 c = undecchar((*p)[1]);
8079                 k = 3;
8080         } else if ((*p)[3] == '>') {
8081                 b = undecchar((*p)[1]);
8082                 c = undecchar((*p)[2]);
8083                 k = 4;
8084         } else if ((*p)[4] == '>') {
8085                 a = undecchar((*p)[1]);
8086                 b = undecchar((*p)[2]);
8087                 c = undecchar((*p)[3]);
8088                 k = 5;
8089         } else
8090                 return 0;
8091
8092         if (a < 0 || b < 0 || c < 0 ||
8093             (!with_facility && (a || b || c > 7)))
8094                 return 0;
8095
8096         if (with_facility)
8097                 *priority = a*100 + b*10 + c;
8098         else
8099                 *priority = (*priority & LOG_FACMASK) | c;
8100
8101         *p += k;
8102         return 1;
8103 }
8104
8105 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
8106         size_t i;
8107
8108         if (!key)
8109                 return -1;
8110
8111         for (i = 0; i < len; ++i)
8112                 if (streq_ptr(table[i], key))
8113                         return (ssize_t)i;
8114
8115         return -1;
8116 }
8117
8118 void cmsg_close_all(struct msghdr *mh) {
8119         struct cmsghdr *cmsg;
8120
8121         assert(mh);
8122
8123         for (cmsg = CMSG_FIRSTHDR(mh); cmsg; cmsg = CMSG_NXTHDR(mh, cmsg))
8124                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
8125                         close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
8126 }
8127
8128 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
8129         struct stat buf;
8130         int ret;
8131
8132         ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
8133         if (ret >= 0)
8134                 return 0;
8135
8136         /* Even though renameat2() exists since Linux 3.15, btrfs added
8137          * support for it later. If it is not implemented, fallback to another
8138          * method. */
8139         if (errno != EINVAL)
8140                 return -errno;
8141
8142         /* The link()/unlink() fallback does not work on directories. But
8143          * renameat() without RENAME_NOREPLACE gives the same semantics on
8144          * directories, except when newpath is an *empty* directory. This is
8145          * good enough. */
8146         ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
8147         if (ret >= 0 && S_ISDIR(buf.st_mode)) {
8148                 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
8149                 return ret >= 0 ? 0 : -errno;
8150         }
8151
8152         /* If it is not a directory, use the link()/unlink() fallback. */
8153         ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
8154         if (ret < 0)
8155                 return -errno;
8156
8157         ret = unlinkat(olddirfd, oldpath, 0);
8158         if (ret < 0) {
8159                 /* backup errno before the following unlinkat() alters it */
8160                 ret = errno;
8161                 (void) unlinkat(newdirfd, newpath, 0);
8162                 errno = ret;
8163                 return -errno;
8164         }
8165
8166         return 0;
8167 }