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