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