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