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