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