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