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