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