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