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