1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
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.
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.
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/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
41 #include <sys/prctl.h>
42 #include <sys/utsname.h>
44 #include <netinet/ip.h>
51 #include <sys/mount.h>
52 #include <linux/magic.h>
56 #include <sys/personality.h>
57 #include <sys/xattr.h>
58 #include <sys/statvfs.h>
62 /* When we include libgen.h because we need dirname() we immediately
63 * undefine basename() since libgen.h defines it as a macro to the POSIX
64 * version which is really broken. We prefer GNU basename(). */
68 #ifdef HAVE_SYS_AUXV_H
80 #include "path-util.h"
81 #include "exit-status.h"
85 #include "device-nodes.h"
90 #include "sparse-endian.h"
91 #include "formats-util.h"
92 #include "process-util.h"
93 #include "random-util.h"
94 #include "terminal-util.h"
95 #include "hostname-util.h"
96 #include "signal-util.h"
98 /* Put this test here for a lack of better place */
99 assert_cc(EAGAIN
== EWOULDBLOCK
);
102 char **saved_argv
= NULL
;
104 size_t page_size(void) {
105 static thread_local
size_t pgsz
= 0;
108 if (_likely_(pgsz
> 0))
111 r
= sysconf(_SC_PAGESIZE
);
118 int strcmp_ptr(const char *a
, const char *b
) {
120 /* Like strcmp(), but tries to make sense of NULL pointers */
133 bool streq_ptr(const char *a
, const char *b
) {
134 return strcmp_ptr(a
, b
) == 0;
137 char* endswith(const char *s
, const char *postfix
) {
144 pl
= strlen(postfix
);
147 return (char*) s
+ sl
;
152 if (memcmp(s
+ sl
- pl
, postfix
, pl
) != 0)
155 return (char*) s
+ sl
- pl
;
158 char* endswith_no_case(const char *s
, const char *postfix
) {
165 pl
= strlen(postfix
);
168 return (char*) s
+ sl
;
173 if (strcasecmp(s
+ sl
- pl
, postfix
) != 0)
176 return (char*) s
+ sl
- pl
;
179 char* first_word(const char *s
, const char *word
) {
186 /* Checks if the string starts with the specified word, either
187 * followed by NUL or by whitespace. Returns a pointer to the
188 * NUL or the first character after the whitespace. */
199 if (memcmp(s
, word
, wl
) != 0)
206 if (!strchr(WHITESPACE
, *p
))
209 p
+= strspn(p
, WHITESPACE
);
213 size_t cescape_char(char c
, char *buf
) {
214 char * buf_old
= buf
;
260 /* For special chars we prefer octal over
261 * hexadecimal encoding, simply because glib's
262 * g_strescape() does the same */
263 if ((c
< ' ') || (c
>= 127)) {
265 *(buf
++) = octchar((unsigned char) c
>> 6);
266 *(buf
++) = octchar((unsigned char) c
>> 3);
267 *(buf
++) = octchar((unsigned char) c
);
273 return buf
- buf_old
;
276 int close_nointr(int fd
) {
283 * Just ignore EINTR; a retry loop is the wrong thing to do on
286 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
287 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
288 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
289 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
297 int safe_close(int fd
) {
300 * Like close_nointr() but cannot fail. Guarantees errno is
301 * unchanged. Is a NOP with negative fds passed, and returns
302 * -1, so that it can be used in this syntax:
304 * fd = safe_close(fd);
310 /* The kernel might return pretty much any error code
311 * via close(), but the fd will be closed anyway. The
312 * only condition we want to check for here is whether
313 * the fd was invalid at all... */
315 assert_se(close_nointr(fd
) != -EBADF
);
321 void close_many(const int fds
[], unsigned n_fd
) {
324 assert(fds
|| n_fd
<= 0);
326 for (i
= 0; i
< n_fd
; i
++)
330 int unlink_noerrno(const char *path
) {
341 int parse_boolean(const char *v
) {
344 if (streq(v
, "1") || strcaseeq(v
, "yes") || strcaseeq(v
, "y") || strcaseeq(v
, "true") || strcaseeq(v
, "t") || strcaseeq(v
, "on"))
346 else if (streq(v
, "0") || strcaseeq(v
, "no") || strcaseeq(v
, "n") || strcaseeq(v
, "false") || strcaseeq(v
, "f") || strcaseeq(v
, "off"))
352 int parse_pid(const char *s
, pid_t
* ret_pid
) {
353 unsigned long ul
= 0;
360 r
= safe_atolu(s
, &ul
);
366 if ((unsigned long) pid
!= ul
)
376 int parse_uid(const char *s
, uid_t
* ret_uid
) {
377 unsigned long ul
= 0;
383 r
= safe_atolu(s
, &ul
);
389 if ((unsigned long) uid
!= ul
)
392 /* Some libc APIs use UID_INVALID as special placeholder */
393 if (uid
== (uid_t
) 0xFFFFFFFF)
396 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
397 if (uid
== (uid_t
) 0xFFFF)
406 int safe_atou(const char *s
, unsigned *ret_u
) {
414 l
= strtoul(s
, &x
, 0);
416 if (!x
|| x
== s
|| *x
|| errno
)
417 return errno
> 0 ? -errno
: -EINVAL
;
419 if ((unsigned long) (unsigned) l
!= l
)
422 *ret_u
= (unsigned) l
;
426 int safe_atoi(const char *s
, int *ret_i
) {
434 l
= strtol(s
, &x
, 0);
436 if (!x
|| x
== s
|| *x
|| errno
)
437 return errno
> 0 ? -errno
: -EINVAL
;
439 if ((long) (int) l
!= l
)
446 int safe_atou8(const char *s
, uint8_t *ret
) {
454 l
= strtoul(s
, &x
, 0);
456 if (!x
|| x
== s
|| *x
|| errno
)
457 return errno
> 0 ? -errno
: -EINVAL
;
459 if ((unsigned long) (uint8_t) l
!= l
)
466 int safe_atou16(const char *s
, uint16_t *ret
) {
474 l
= strtoul(s
, &x
, 0);
476 if (!x
|| x
== s
|| *x
|| errno
)
477 return errno
> 0 ? -errno
: -EINVAL
;
479 if ((unsigned long) (uint16_t) l
!= l
)
486 int safe_atoi16(const char *s
, int16_t *ret
) {
494 l
= strtol(s
, &x
, 0);
496 if (!x
|| x
== s
|| *x
|| errno
)
497 return errno
> 0 ? -errno
: -EINVAL
;
499 if ((long) (int16_t) l
!= l
)
506 int safe_atollu(const char *s
, long long unsigned *ret_llu
) {
508 unsigned long long l
;
514 l
= strtoull(s
, &x
, 0);
516 if (!x
|| x
== s
|| *x
|| errno
)
517 return errno
? -errno
: -EINVAL
;
523 int safe_atolli(const char *s
, long long int *ret_lli
) {
531 l
= strtoll(s
, &x
, 0);
533 if (!x
|| x
== s
|| *x
|| errno
)
534 return errno
? -errno
: -EINVAL
;
540 int safe_atod(const char *s
, double *ret_d
) {
548 loc
= newlocale(LC_NUMERIC_MASK
, "C", (locale_t
) 0);
549 if (loc
== (locale_t
) 0)
553 d
= strtod_l(s
, &x
, loc
);
555 if (!x
|| x
== s
|| *x
|| errno
) {
557 return errno
? -errno
: -EINVAL
;
565 static size_t strcspn_escaped(const char *s
, const char *reject
) {
566 bool escaped
= false;
569 for (n
=0; s
[n
]; n
++) {
572 else if (s
[n
] == '\\')
574 else if (strchr(reject
, s
[n
]))
578 /* if s ends in \, return index of previous char */
582 /* Split a string into words. */
583 const char* split(const char **state
, size_t *l
, const char *separator
, bool quoted
) {
589 assert(**state
== '\0');
593 current
+= strspn(current
, separator
);
599 if (quoted
&& strchr("\'\"", *current
)) {
600 char quotechars
[2] = {*current
, '\0'};
602 *l
= strcspn_escaped(current
+ 1, quotechars
);
603 if (current
[*l
+ 1] == '\0' || current
[*l
+ 1] != quotechars
[0] ||
604 (current
[*l
+ 2] && !strchr(separator
, current
[*l
+ 2]))) {
605 /* right quote missing or garbage at the end */
609 *state
= current
++ + *l
+ 2;
611 *l
= strcspn_escaped(current
, separator
);
612 if (current
[*l
] && !strchr(separator
, current
[*l
])) {
613 /* unfinished escape */
617 *state
= current
+ *l
;
619 *l
= strcspn(current
, separator
);
620 *state
= current
+ *l
;
626 int fchmod_umask(int fd
, mode_t m
) {
631 r
= fchmod(fd
, m
& (~u
)) < 0 ? -errno
: 0;
637 char *truncate_nl(char *s
) {
640 s
[strcspn(s
, NEWLINE
)] = 0;
644 char *strnappend(const char *s
, const char *suffix
, size_t b
) {
652 return strndup(suffix
, b
);
661 if (b
> ((size_t) -1) - a
)
664 r
= new(char, a
+b
+1);
669 memcpy(r
+a
, suffix
, b
);
675 char *strappend(const char *s
, const char *suffix
) {
676 return strnappend(s
, suffix
, suffix
? strlen(suffix
) : 0);
679 int readlinkat_malloc(int fd
, const char *p
, char **ret
) {
694 n
= readlinkat(fd
, p
, c
, l
-1);
701 if ((size_t) n
< l
-1) {
712 int readlink_malloc(const char *p
, char **ret
) {
713 return readlinkat_malloc(AT_FDCWD
, p
, ret
);
716 int readlink_value(const char *p
, char **ret
) {
717 _cleanup_free_
char *link
= NULL
;
721 r
= readlink_malloc(p
, &link
);
725 value
= basename(link
);
729 value
= strdup(value
);
738 int readlink_and_make_absolute(const char *p
, char **r
) {
739 _cleanup_free_
char *target
= NULL
;
746 j
= readlink_malloc(p
, &target
);
750 k
= file_in_same_dir(p
, target
);
758 int readlink_and_canonicalize(const char *p
, char **r
) {
765 j
= readlink_and_make_absolute(p
, &t
);
769 s
= canonicalize_file_name(t
);
776 path_kill_slashes(*r
);
781 char *strstrip(char *s
) {
784 /* Drops trailing whitespace. Modifies the string in
785 * place. Returns pointer to first non-space character */
787 s
+= strspn(s
, WHITESPACE
);
789 for (e
= strchr(s
, 0); e
> s
; e
--)
790 if (!strchr(WHITESPACE
, e
[-1]))
798 char *delete_chars(char *s
, const char *bad
) {
801 /* Drops all whitespace, regardless where in the string */
803 for (f
= s
, t
= s
; *f
; f
++) {
815 char *file_in_same_dir(const char *path
, const char *filename
) {
822 /* This removes the last component of path and appends
823 * filename, unless the latter is absolute anyway or the
826 if (path_is_absolute(filename
))
827 return strdup(filename
);
829 e
= strrchr(path
, '/');
831 return strdup(filename
);
833 k
= strlen(filename
);
834 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
838 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
842 int rmdir_parents(const char *path
, const char *stop
) {
851 /* Skip trailing slashes */
852 while (l
> 0 && path
[l
-1] == '/')
858 /* Skip last component */
859 while (l
> 0 && path
[l
-1] != '/')
862 /* Skip trailing slashes */
863 while (l
> 0 && path
[l
-1] == '/')
869 if (!(t
= strndup(path
, l
)))
872 if (path_startswith(stop
, t
)) {
888 char hexchar(int x
) {
889 static const char table
[16] = "0123456789abcdef";
891 return table
[x
& 15];
894 int unhexchar(char c
) {
896 if (c
>= '0' && c
<= '9')
899 if (c
>= 'a' && c
<= 'f')
902 if (c
>= 'A' && c
<= 'F')
908 char *hexmem(const void *p
, size_t l
) {
912 z
= r
= malloc(l
* 2 + 1);
916 for (x
= p
; x
< (const uint8_t*) p
+ l
; x
++) {
917 *(z
++) = hexchar(*x
>> 4);
918 *(z
++) = hexchar(*x
& 15);
925 int unhexmem(const char *p
, size_t l
, void **mem
, size_t *len
) {
926 _cleanup_free_
uint8_t *r
= NULL
;
934 z
= r
= malloc((l
+ 1) / 2 + 1);
938 for (x
= p
; x
< p
+ l
; x
+= 2) {
944 else if (x
+1 < p
+ l
) {
951 *(z
++) = (uint8_t) a
<< 4 | (uint8_t) b
;
963 /* https://tools.ietf.org/html/rfc4648#section-6
964 * Notice that base32hex differs from base32 in the alphabet it uses.
965 * The distinction is that the base32hex representation preserves the
966 * order of the underlying data when compared as bytestrings, this is
967 * useful when representing NSEC3 hashes, as one can then verify the
968 * order of hashes directly from their representation. */
969 char base32hexchar(int x
) {
970 static const char table
[32] = "0123456789"
971 "ABCDEFGHIJKLMNOPQRSTUV";
973 return table
[x
& 31];
976 int unbase32hexchar(char c
) {
979 if (c
>= '0' && c
<= '9')
982 offset
= '9' - '0' + 1;
984 if (c
>= 'A' && c
<= 'V')
985 return c
- 'A' + offset
;
990 char *base32hexmem(const void *p
, size_t l
, bool padding
) {
996 /* five input bytes makes eight output bytes, padding is added so we must round up */
997 len
= 8 * (l
+ 4) / 5;
999 /* same, but round down as there is no padding */
1018 z
= r
= malloc(len
+ 1);
1022 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 5) * 5; x
+= 5) {
1023 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ
1024 x[3] == QQQQQQQQ; x[4] == WWWWWWWW */
1025 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1026 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1027 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1028 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1029 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
1030 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
1031 *(z
++) = base32hexchar((x
[3] & 3) << 3 | x
[4] >> 5); /* 000QQWWW */
1032 *(z
++) = base32hexchar((x
[4] & 31)); /* 000WWWWW */
1037 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1038 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1039 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1040 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1041 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
1042 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
1043 *(z
++) = base32hexchar((x
[3] & 3) << 3); /* 000QQ000 */
1050 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1051 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1052 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1053 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1054 *(z
++) = base32hexchar((x
[2] & 15) << 1); /* 000ZZZZ0 */
1064 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1065 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1066 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1067 *(z
++) = base32hexchar((x
[1] & 1) << 4); /* 000Y0000 */
1078 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1079 *(z
++) = base32hexchar((x
[0] & 7) << 2); /* 000XXX00 */
1096 int unbase32hexmem(const char *p
, size_t l
, bool padding
, void **mem
, size_t *_len
) {
1097 _cleanup_free_
uint8_t *r
= NULL
;
1098 int a
, b
, c
, d
, e
, f
, g
, h
;
1106 /* padding ensures any base32hex input has input divisible by 8 */
1107 if (padding
&& l
% 8 != 0)
1111 /* strip the padding */
1112 while (l
> 0 && p
[l
- 1] == '=' && pad
< 7) {
1118 /* a group of eight input bytes needs five output bytes, in case of
1119 padding we need to add some extra bytes */
1141 z
= r
= malloc(len
+ 1);
1145 for (x
= p
; x
< p
+ (l
/ 8) * 8; x
+= 8) {
1146 /* a == 000XXXXX; b == 000YYYYY; c == 000ZZZZZ; d == 000WWWWW
1147 e == 000SSSSS; f == 000QQQQQ; g == 000VVVVV; h == 000RRRRR */
1148 a
= unbase32hexchar(x
[0]);
1152 b
= unbase32hexchar(x
[1]);
1156 c
= unbase32hexchar(x
[2]);
1160 d
= unbase32hexchar(x
[3]);
1164 e
= unbase32hexchar(x
[4]);
1168 f
= unbase32hexchar(x
[5]);
1172 g
= unbase32hexchar(x
[6]);
1176 h
= unbase32hexchar(x
[7]);
1180 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1181 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1182 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1183 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
1184 *(z
++) = (uint8_t) g
<< 5 | (uint8_t) h
; /* VVVRRRRR */
1189 a
= unbase32hexchar(x
[0]);
1193 b
= unbase32hexchar(x
[1]);
1197 c
= unbase32hexchar(x
[2]);
1201 d
= unbase32hexchar(x
[3]);
1205 e
= unbase32hexchar(x
[4]);
1209 f
= unbase32hexchar(x
[5]);
1213 g
= unbase32hexchar(x
[6]);
1221 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1222 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1223 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1224 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
1228 a
= unbase32hexchar(x
[0]);
1232 b
= unbase32hexchar(x
[1]);
1236 c
= unbase32hexchar(x
[2]);
1240 d
= unbase32hexchar(x
[3]);
1244 e
= unbase32hexchar(x
[4]);
1252 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1253 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1254 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1258 a
= unbase32hexchar(x
[0]);
1262 b
= unbase32hexchar(x
[1]);
1266 c
= unbase32hexchar(x
[2]);
1270 d
= unbase32hexchar(x
[3]);
1278 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1279 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1283 a
= unbase32hexchar(x
[0]);
1287 b
= unbase32hexchar(x
[1]);
1295 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1313 /* https://tools.ietf.org/html/rfc4648#section-4 */
1314 char base64char(int x
) {
1315 static const char table
[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1316 "abcdefghijklmnopqrstuvwxyz"
1318 return table
[x
& 63];
1321 int unbase64char(char c
) {
1324 if (c
>= 'A' && c
<= 'Z')
1327 offset
= 'Z' - 'A' + 1;
1329 if (c
>= 'a' && c
<= 'z')
1330 return c
- 'a' + offset
;
1332 offset
+= 'z' - 'a' + 1;
1334 if (c
>= '0' && c
<= '9')
1335 return c
- '0' + offset
;
1337 offset
+= '9' - '0' + 1;
1350 char *base64mem(const void *p
, size_t l
) {
1354 /* three input bytes makes four output bytes, padding is added so we must round up */
1355 z
= r
= malloc(4 * (l
+ 2) / 3 + 1);
1359 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 3) * 3; x
+= 3) {
1360 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ */
1361 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1362 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1363 *(z
++) = base64char((x
[1] & 15) << 2 | x
[2] >> 6); /* 00YYYYZZ */
1364 *(z
++) = base64char(x
[2] & 63); /* 00ZZZZZZ */
1369 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1370 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1371 *(z
++) = base64char((x
[1] & 15) << 2); /* 00YYYY00 */
1376 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1377 *(z
++) = base64char((x
[0] & 3) << 4); /* 00XX0000 */
1388 int unbase64mem(const char *p
, size_t l
, void **mem
, size_t *_len
) {
1389 _cleanup_free_
uint8_t *r
= NULL
;
1397 /* padding ensures any base63 input has input divisible by 4 */
1401 /* strip the padding */
1402 if (l
> 0 && p
[l
- 1] == '=')
1404 if (l
> 0 && p
[l
- 1] == '=')
1407 /* a group of four input bytes needs three output bytes, in case of
1408 padding we need to add two or three extra bytes */
1409 len
= (l
/ 4) * 3 + (l
% 4 ? (l
% 4) - 1 : 0);
1411 z
= r
= malloc(len
+ 1);
1415 for (x
= p
; x
< p
+ (l
/ 4) * 4; x
+= 4) {
1416 /* a == 00XXXXXX; b == 00YYYYYY; c == 00ZZZZZZ; d == 00WWWWWW */
1417 a
= unbase64char(x
[0]);
1421 b
= unbase64char(x
[1]);
1425 c
= unbase64char(x
[2]);
1429 d
= unbase64char(x
[3]);
1433 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1434 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1435 *(z
++) = (uint8_t) c
<< 6 | (uint8_t) d
; /* ZZWWWWWW */
1440 a
= unbase64char(x
[0]);
1444 b
= unbase64char(x
[1]);
1448 c
= unbase64char(x
[2]);
1456 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1457 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1461 a
= unbase64char(x
[0]);
1465 b
= unbase64char(x
[1]);
1473 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) (b
>> 4); /* XXXXXXYY */
1492 char octchar(int x
) {
1493 return '0' + (x
& 7);
1496 int unoctchar(char c
) {
1498 if (c
>= '0' && c
<= '7')
1504 char decchar(int x
) {
1505 return '0' + (x
% 10);
1508 int undecchar(char c
) {
1510 if (c
>= '0' && c
<= '9')
1516 char *cescape(const char *s
) {
1522 /* Does C style string escaping. May be reversed with
1525 r
= new(char, strlen(s
)*4 + 1);
1529 for (f
= s
, t
= r
; *f
; f
++)
1530 t
+= cescape_char(*f
, t
);
1537 static int cunescape_one(const char *p
, size_t length
, char *ret
, uint32_t *ret_unicode
) {
1544 /* Unescapes C style. Returns the unescaped character in ret,
1545 * unless we encountered a \u sequence in which case the full
1546 * unicode character is returned in ret_unicode, instead. */
1548 if (length
!= (size_t) -1 && length
< 1)
1585 /* This is an extension of the XDG syntax files */
1590 /* hexadecimal encoding */
1593 if (length
!= (size_t) -1 && length
< 3)
1596 a
= unhexchar(p
[1]);
1600 b
= unhexchar(p
[2]);
1604 /* Don't allow NUL bytes */
1605 if (a
== 0 && b
== 0)
1608 *ret
= (char) ((a
<< 4U) | b
);
1614 /* C++11 style 16bit unicode */
1620 if (length
!= (size_t) -1 && length
< 5)
1623 for (i
= 0; i
< 4; i
++) {
1624 a
[i
] = unhexchar(p
[1 + i
]);
1629 c
= ((uint32_t) a
[0] << 12U) | ((uint32_t) a
[1] << 8U) | ((uint32_t) a
[2] << 4U) | (uint32_t) a
[3];
1631 /* Don't allow 0 chars */
1650 /* C++11 style 32bit unicode */
1656 if (length
!= (size_t) -1 && length
< 9)
1659 for (i
= 0; i
< 8; i
++) {
1660 a
[i
] = unhexchar(p
[1 + i
]);
1665 c
= ((uint32_t) a
[0] << 28U) | ((uint32_t) a
[1] << 24U) | ((uint32_t) a
[2] << 20U) | ((uint32_t) a
[3] << 16U) |
1666 ((uint32_t) a
[4] << 12U) | ((uint32_t) a
[5] << 8U) | ((uint32_t) a
[6] << 4U) | (uint32_t) a
[7];
1668 /* Don't allow 0 chars */
1672 /* Don't allow invalid code points */
1673 if (!unichar_is_valid(c
))
1698 /* octal encoding */
1702 if (length
!= (size_t) -1 && length
< 3)
1705 a
= unoctchar(p
[0]);
1709 b
= unoctchar(p
[1]);
1713 c
= unoctchar(p
[2]);
1717 /* don't allow NUL bytes */
1718 if (a
== 0 && b
== 0 && c
== 0)
1721 /* Don't allow bytes above 255 */
1722 m
= ((uint32_t) a
<< 6U) | ((uint32_t) b
<< 3U) | (uint32_t) c
;
1738 int cunescape_length_with_prefix(const char *s
, size_t length
, const char *prefix
, UnescapeFlags flags
, char **ret
) {
1746 /* Undoes C style string escaping, and optionally prefixes it. */
1748 pl
= prefix
? strlen(prefix
) : 0;
1750 r
= new(char, pl
+length
+1);
1755 memcpy(r
, prefix
, pl
);
1757 for (f
= s
, t
= r
+ pl
; f
< s
+ length
; f
++) {
1763 remaining
= s
+ length
- f
;
1764 assert(remaining
> 0);
1767 /* A literal literal, copy verbatim */
1772 if (remaining
== 1) {
1773 if (flags
& UNESCAPE_RELAX
) {
1774 /* A trailing backslash, copy verbatim */
1783 k
= cunescape_one(f
+ 1, remaining
- 1, &c
, &u
);
1785 if (flags
& UNESCAPE_RELAX
) {
1786 /* Invalid escape code, let's take it literal then */
1796 /* Non-Unicode? Let's encode this directly */
1799 /* Unicode? Then let's encode this in UTF-8 */
1800 t
+= utf8_encode_unichar(t
, u
);
1811 int cunescape_length(const char *s
, size_t length
, UnescapeFlags flags
, char **ret
) {
1812 return cunescape_length_with_prefix(s
, length
, NULL
, flags
, ret
);
1815 int cunescape(const char *s
, UnescapeFlags flags
, char **ret
) {
1816 return cunescape_length(s
, strlen(s
), flags
, ret
);
1819 char *xescape(const char *s
, const char *bad
) {
1823 /* Escapes all chars in bad, in addition to \ and all special
1824 * chars, in \xFF style escaping. May be reversed with
1827 r
= new(char, strlen(s
) * 4 + 1);
1831 for (f
= s
, t
= r
; *f
; f
++) {
1833 if ((*f
< ' ') || (*f
>= 127) ||
1834 (*f
== '\\') || strchr(bad
, *f
)) {
1837 *(t
++) = hexchar(*f
>> 4);
1838 *(t
++) = hexchar(*f
);
1848 char *ascii_strlower(char *t
) {
1853 for (p
= t
; *p
; p
++)
1854 if (*p
>= 'A' && *p
<= 'Z')
1855 *p
= *p
- 'A' + 'a';
1860 _pure_
static bool hidden_file_allow_backup(const char *filename
) {
1864 filename
[0] == '.' ||
1865 streq(filename
, "lost+found") ||
1866 streq(filename
, "aquota.user") ||
1867 streq(filename
, "aquota.group") ||
1868 endswith(filename
, ".rpmnew") ||
1869 endswith(filename
, ".rpmsave") ||
1870 endswith(filename
, ".rpmorig") ||
1871 endswith(filename
, ".dpkg-old") ||
1872 endswith(filename
, ".dpkg-new") ||
1873 endswith(filename
, ".dpkg-tmp") ||
1874 endswith(filename
, ".dpkg-dist") ||
1875 endswith(filename
, ".dpkg-bak") ||
1876 endswith(filename
, ".dpkg-backup") ||
1877 endswith(filename
, ".dpkg-remove") ||
1878 endswith(filename
, ".swp");
1881 bool hidden_file(const char *filename
) {
1884 if (endswith(filename
, "~"))
1887 return hidden_file_allow_backup(filename
);
1890 int fd_nonblock(int fd
, bool nonblock
) {
1895 flags
= fcntl(fd
, F_GETFL
, 0);
1900 nflags
= flags
| O_NONBLOCK
;
1902 nflags
= flags
& ~O_NONBLOCK
;
1904 if (nflags
== flags
)
1907 if (fcntl(fd
, F_SETFL
, nflags
) < 0)
1913 int fd_cloexec(int fd
, bool cloexec
) {
1918 flags
= fcntl(fd
, F_GETFD
, 0);
1923 nflags
= flags
| FD_CLOEXEC
;
1925 nflags
= flags
& ~FD_CLOEXEC
;
1927 if (nflags
== flags
)
1930 if (fcntl(fd
, F_SETFD
, nflags
) < 0)
1936 _pure_
static bool fd_in_set(int fd
, const int fdset
[], unsigned n_fdset
) {
1939 assert(n_fdset
== 0 || fdset
);
1941 for (i
= 0; i
< n_fdset
; i
++)
1948 int close_all_fds(const int except
[], unsigned n_except
) {
1949 _cleanup_closedir_
DIR *d
= NULL
;
1953 assert(n_except
== 0 || except
);
1955 d
= opendir("/proc/self/fd");
1960 /* When /proc isn't available (for example in chroots)
1961 * the fallback is brute forcing through the fd
1964 assert_se(getrlimit(RLIMIT_NOFILE
, &rl
) >= 0);
1965 for (fd
= 3; fd
< (int) rl
.rlim_max
; fd
++) {
1967 if (fd_in_set(fd
, except
, n_except
))
1970 if (close_nointr(fd
) < 0)
1971 if (errno
!= EBADF
&& r
== 0)
1978 while ((de
= readdir(d
))) {
1981 if (hidden_file(de
->d_name
))
1984 if (safe_atoi(de
->d_name
, &fd
) < 0)
1985 /* Let's better ignore this, just in case */
1994 if (fd_in_set(fd
, except
, n_except
))
1997 if (close_nointr(fd
) < 0) {
1998 /* Valgrind has its own FD and doesn't want to have it closed */
1999 if (errno
!= EBADF
&& r
== 0)
2007 bool chars_intersect(const char *a
, const char *b
) {
2010 /* Returns true if any of the chars in a are in b. */
2011 for (p
= a
; *p
; p
++)
2018 bool fstype_is_network(const char *fstype
) {
2019 static const char table
[] =
2034 x
= startswith(fstype
, "fuse.");
2038 return nulstr_contains(table
, fstype
);
2041 int flush_fd(int fd
) {
2042 struct pollfd pollfd
= {
2052 r
= poll(&pollfd
, 1, 0);
2062 l
= read(fd
, buf
, sizeof(buf
));
2068 if (errno
== EAGAIN
)
2077 void safe_close_pair(int p
[]) {
2081 /* Special case pairs which use the same fd in both
2083 p
[0] = p
[1] = safe_close(p
[0]);
2087 p
[0] = safe_close(p
[0]);
2088 p
[1] = safe_close(p
[1]);
2091 ssize_t
loop_read(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2098 while (nbytes
> 0) {
2101 k
= read(fd
, p
, nbytes
);
2106 if (errno
== EAGAIN
&& do_poll
) {
2108 /* We knowingly ignore any return value here,
2109 * and expect that any error/EOF is reported
2112 fd_wait_for_event(fd
, POLLIN
, USEC_INFINITY
);
2116 return n
> 0 ? n
: -errno
;
2130 int loop_read_exact(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2133 n
= loop_read(fd
, buf
, nbytes
, do_poll
);
2136 if ((size_t) n
!= nbytes
)
2141 int loop_write(int fd
, const void *buf
, size_t nbytes
, bool do_poll
) {
2142 const uint8_t *p
= buf
;
2152 k
= write(fd
, p
, nbytes
);
2157 if (errno
== EAGAIN
&& do_poll
) {
2158 /* We knowingly ignore any return value here,
2159 * and expect that any error/EOF is reported
2162 fd_wait_for_event(fd
, POLLOUT
, USEC_INFINITY
);
2169 if (nbytes
> 0 && k
== 0) /* Can't really happen */
2174 } while (nbytes
> 0);
2179 int parse_size(const char *t
, off_t base
, off_t
*size
) {
2181 /* Soo, sometimes we want to parse IEC binary suffixes, and
2182 * sometimes SI decimal suffixes. This function can parse
2183 * both. Which one is the right way depends on the
2184 * context. Wikipedia suggests that SI is customary for
2185 * hardware metrics and network speeds, while IEC is
2186 * customary for most data sizes used by software and volatile
2187 * (RAM) memory. Hence be careful which one you pick!
2189 * In either case we use just K, M, G as suffix, and not Ki,
2190 * Mi, Gi or so (as IEC would suggest). That's because that's
2191 * frickin' ugly. But this means you really need to make sure
2192 * to document which base you are parsing when you use this
2197 unsigned long long factor
;
2200 static const struct table iec
[] = {
2201 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2202 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2203 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2204 { "G", 1024ULL*1024ULL*1024ULL },
2205 { "M", 1024ULL*1024ULL },
2211 static const struct table si
[] = {
2212 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2213 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2214 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2215 { "G", 1000ULL*1000ULL*1000ULL },
2216 { "M", 1000ULL*1000ULL },
2222 const struct table
*table
;
2224 unsigned long long r
= 0;
2225 unsigned n_entries
, start_pos
= 0;
2228 assert(base
== 1000 || base
== 1024);
2233 n_entries
= ELEMENTSOF(si
);
2236 n_entries
= ELEMENTSOF(iec
);
2242 unsigned long long l2
;
2248 l
= strtoll(p
, &e
, 10);
2261 if (*e
>= '0' && *e
<= '9') {
2264 /* strotoull itself would accept space/+/- */
2265 l2
= strtoull(e
, &e2
, 10);
2267 if (errno
== ERANGE
)
2270 /* Ignore failure. E.g. 10.M is valid */
2277 e
+= strspn(e
, WHITESPACE
);
2279 for (i
= start_pos
; i
< n_entries
; i
++)
2280 if (startswith(e
, table
[i
].suffix
)) {
2281 unsigned long long tmp
;
2282 if ((unsigned long long) l
+ (frac
> 0) > ULLONG_MAX
/ table
[i
].factor
)
2284 tmp
= l
* table
[i
].factor
+ (unsigned long long) (frac
* table
[i
].factor
);
2285 if (tmp
> ULLONG_MAX
- r
)
2289 if ((unsigned long long) (off_t
) r
!= r
)
2292 p
= e
+ strlen(table
[i
].suffix
);
2308 bool is_device_path(const char *path
) {
2310 /* Returns true on paths that refer to a device, either in
2311 * sysfs or in /dev */
2314 path_startswith(path
, "/dev/") ||
2315 path_startswith(path
, "/sys/");
2318 int dir_is_empty(const char *path
) {
2319 _cleanup_closedir_
DIR *d
;
2330 if (!de
&& errno
!= 0)
2336 if (!hidden_file(de
->d_name
))
2341 char* dirname_malloc(const char *path
) {
2342 char *d
, *dir
, *dir2
;
2359 void rename_process(const char name
[8]) {
2362 /* This is a like a poor man's setproctitle(). It changes the
2363 * comm field, argv[0], and also the glibc's internally used
2364 * name of the process. For the first one a limit of 16 chars
2365 * applies, to the second one usually one of 10 (i.e. length
2366 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2367 * "systemd"). If you pass a longer string it will be
2370 prctl(PR_SET_NAME
, name
);
2372 if (program_invocation_name
)
2373 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
2375 if (saved_argc
> 0) {
2379 strncpy(saved_argv
[0], name
, strlen(saved_argv
[0]));
2381 for (i
= 1; i
< saved_argc
; i
++) {
2385 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
2390 char *lookup_uid(uid_t uid
) {
2393 _cleanup_free_
char *buf
= NULL
;
2394 struct passwd pwbuf
, *pw
= NULL
;
2396 /* Shortcut things to avoid NSS lookups */
2398 return strdup("root");
2400 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
2404 buf
= malloc(bufsize
);
2408 if (getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
) == 0 && pw
)
2409 return strdup(pw
->pw_name
);
2411 if (asprintf(&name
, UID_FMT
, uid
) < 0)
2417 char* getlogname_malloc(void) {
2421 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
2426 return lookup_uid(uid
);
2429 char *getusername_malloc(void) {
2436 return lookup_uid(getuid());
2439 bool is_temporary_fs(const struct statfs
*s
) {
2442 return F_TYPE_EQUAL(s
->f_type
, TMPFS_MAGIC
) ||
2443 F_TYPE_EQUAL(s
->f_type
, RAMFS_MAGIC
);
2446 int fd_is_temporary_fs(int fd
) {
2449 if (fstatfs(fd
, &s
) < 0)
2452 return is_temporary_fs(&s
);
2455 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
2458 /* Under the assumption that we are running privileged we
2459 * first change the access mode and only then hand out
2460 * ownership to avoid a window where access is too open. */
2462 if (mode
!= MODE_INVALID
)
2463 if (chmod(path
, mode
) < 0)
2466 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
2467 if (chown(path
, uid
, gid
) < 0)
2473 int fchmod_and_fchown(int fd
, mode_t mode
, uid_t uid
, gid_t gid
) {
2476 /* Under the assumption that we are running privileged we
2477 * first change the access mode and only then hand out
2478 * ownership to avoid a window where access is too open. */
2480 if (mode
!= MODE_INVALID
)
2481 if (fchmod(fd
, mode
) < 0)
2484 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
2485 if (fchown(fd
, uid
, gid
) < 0)
2491 cpu_set_t
* cpu_set_malloc(unsigned *ncpus
) {
2495 /* Allocates the cpuset in the right size */
2498 if (!(r
= CPU_ALLOC(n
)))
2501 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n
), r
) >= 0) {
2502 CPU_ZERO_S(CPU_ALLOC_SIZE(n
), r
);
2512 if (errno
!= EINVAL
)
2519 int files_same(const char *filea
, const char *fileb
) {
2522 if (stat(filea
, &a
) < 0)
2525 if (stat(fileb
, &b
) < 0)
2528 return a
.st_dev
== b
.st_dev
&&
2529 a
.st_ino
== b
.st_ino
;
2532 int running_in_chroot(void) {
2535 ret
= files_same("/proc/1/root", "/");
2542 static char *ascii_ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
2547 assert(percent
<= 100);
2548 assert(new_length
>= 3);
2550 if (old_length
<= 3 || old_length
<= new_length
)
2551 return strndup(s
, old_length
);
2553 r
= new0(char, new_length
+1);
2557 x
= (new_length
* percent
) / 100;
2559 if (x
> new_length
- 3)
2567 s
+ old_length
- (new_length
- x
- 3),
2568 new_length
- x
- 3);
2573 char *ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
2577 unsigned k
, len
, len2
;
2580 assert(percent
<= 100);
2581 assert(new_length
>= 3);
2583 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2584 if (ascii_is_valid(s
))
2585 return ascii_ellipsize_mem(s
, old_length
, new_length
, percent
);
2587 if (old_length
<= 3 || old_length
<= new_length
)
2588 return strndup(s
, old_length
);
2590 x
= (new_length
* percent
) / 100;
2592 if (x
> new_length
- 3)
2596 for (i
= s
; k
< x
&& i
< s
+ old_length
; i
= utf8_next_char(i
)) {
2599 c
= utf8_encoded_to_unichar(i
);
2602 k
+= unichar_iswide(c
) ? 2 : 1;
2605 if (k
> x
) /* last character was wide and went over quota */
2608 for (j
= s
+ old_length
; k
< new_length
&& j
> i
; ) {
2611 j
= utf8_prev_char(j
);
2612 c
= utf8_encoded_to_unichar(j
);
2615 k
+= unichar_iswide(c
) ? 2 : 1;
2619 /* we don't actually need to ellipsize */
2621 return memdup(s
, old_length
+ 1);
2623 /* make space for ellipsis */
2624 j
= utf8_next_char(j
);
2627 len2
= s
+ old_length
- j
;
2628 e
= new(char, len
+ 3 + len2
+ 1);
2633 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2634 old_length, new_length, x, len, len2, k);
2638 e
[len
] = 0xe2; /* tri-dot ellipsis: … */
2642 memcpy(e
+ len
+ 3, j
, len2
+ 1);
2647 char *ellipsize(const char *s
, size_t length
, unsigned percent
) {
2648 return ellipsize_mem(s
, strlen(s
), length
, percent
);
2651 int touch_file(const char *path
, bool parents
, usec_t stamp
, uid_t uid
, gid_t gid
, mode_t mode
) {
2652 _cleanup_close_
int fd
;
2658 mkdir_parents(path
, 0755);
2660 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, mode
> 0 ? mode
: 0644);
2665 r
= fchmod(fd
, mode
);
2670 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
) {
2671 r
= fchown(fd
, uid
, gid
);
2676 if (stamp
!= USEC_INFINITY
) {
2677 struct timespec ts
[2];
2679 timespec_store(&ts
[0], stamp
);
2681 r
= futimens(fd
, ts
);
2683 r
= futimens(fd
, NULL
);
2690 int touch(const char *path
) {
2691 return touch_file(path
, false, USEC_INFINITY
, UID_INVALID
, GID_INVALID
, 0);
2694 static char *unquote(const char *s
, const char* quotes
) {
2698 /* This is rather stupid, simply removes the heading and
2699 * trailing quotes if there is one. Doesn't care about
2700 * escaping or anything.
2702 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2708 if (strchr(quotes
, s
[0]) && s
[l
-1] == s
[0])
2709 return strndup(s
+1, l
-2);
2714 noreturn
void freeze(void) {
2716 /* Make sure nobody waits for us on a socket anymore */
2717 close_all_fds(NULL
, 0);
2725 bool null_or_empty(struct stat
*st
) {
2728 if (S_ISREG(st
->st_mode
) && st
->st_size
<= 0)
2731 if (S_ISCHR(st
->st_mode
) || S_ISBLK(st
->st_mode
))
2737 int null_or_empty_path(const char *fn
) {
2742 if (stat(fn
, &st
) < 0)
2745 return null_or_empty(&st
);
2748 int null_or_empty_fd(int fd
) {
2753 if (fstat(fd
, &st
) < 0)
2756 return null_or_empty(&st
);
2759 DIR *xopendirat(int fd
, const char *name
, int flags
) {
2763 assert(!(flags
& O_CREAT
));
2765 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
2778 static char *tag_to_udev_node(const char *tagvalue
, const char *by
) {
2779 _cleanup_free_
char *t
= NULL
, *u
= NULL
;
2782 u
= unquote(tagvalue
, QUOTES
);
2786 enc_len
= strlen(u
) * 4 + 1;
2787 t
= new(char, enc_len
);
2791 if (encode_devnode_name(u
, t
, enc_len
) < 0)
2794 return strjoin("/dev/disk/by-", by
, "/", t
, NULL
);
2797 char *fstab_node_to_udev_node(const char *p
) {
2800 if (startswith(p
, "LABEL="))
2801 return tag_to_udev_node(p
+6, "label");
2803 if (startswith(p
, "UUID="))
2804 return tag_to_udev_node(p
+5, "uuid");
2806 if (startswith(p
, "PARTUUID="))
2807 return tag_to_udev_node(p
+9, "partuuid");
2809 if (startswith(p
, "PARTLABEL="))
2810 return tag_to_udev_node(p
+10, "partlabel");
2815 bool dirent_is_file(const struct dirent
*de
) {
2818 if (hidden_file(de
->d_name
))
2821 if (de
->d_type
!= DT_REG
&&
2822 de
->d_type
!= DT_LNK
&&
2823 de
->d_type
!= DT_UNKNOWN
)
2829 bool dirent_is_file_with_suffix(const struct dirent
*de
, const char *suffix
) {
2832 if (de
->d_type
!= DT_REG
&&
2833 de
->d_type
!= DT_LNK
&&
2834 de
->d_type
!= DT_UNKNOWN
)
2837 if (hidden_file_allow_backup(de
->d_name
))
2840 return endswith(de
->d_name
, suffix
);
2843 static int do_execute(char **directories
, usec_t timeout
, char *argv
[]) {
2844 _cleanup_hashmap_free_free_ Hashmap
*pids
= NULL
;
2845 _cleanup_set_free_free_ Set
*seen
= NULL
;
2848 /* We fork this all off from a child process so that we can
2849 * somewhat cleanly make use of SIGALRM to set a time limit */
2851 (void) reset_all_signal_handlers();
2852 (void) reset_signal_mask();
2854 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
2856 pids
= hashmap_new(NULL
);
2860 seen
= set_new(&string_hash_ops
);
2864 STRV_FOREACH(directory
, directories
) {
2865 _cleanup_closedir_
DIR *d
;
2868 d
= opendir(*directory
);
2870 if (errno
== ENOENT
)
2873 return log_error_errno(errno
, "Failed to open directory %s: %m", *directory
);
2876 FOREACH_DIRENT(de
, d
, break) {
2877 _cleanup_free_
char *path
= NULL
;
2881 if (!dirent_is_file(de
))
2884 if (set_contains(seen
, de
->d_name
)) {
2885 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory
, de
->d_name
);
2889 r
= set_put_strdup(seen
, de
->d_name
);
2893 path
= strjoin(*directory
, "/", de
->d_name
, NULL
);
2897 if (null_or_empty_path(path
)) {
2898 log_debug("%s is empty (a mask).", path
);
2904 log_error_errno(errno
, "Failed to fork: %m");
2906 } else if (pid
== 0) {
2909 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
2919 return log_error_errno(errno
, "Failed to execute %s: %m", path
);
2922 log_debug("Spawned %s as " PID_FMT
".", path
, pid
);
2924 r
= hashmap_put(pids
, UINT_TO_PTR(pid
), path
);
2931 /* Abort execution of this process after the timout. We simply
2932 * rely on SIGALRM as default action terminating the process,
2933 * and turn on alarm(). */
2935 if (timeout
!= USEC_INFINITY
)
2936 alarm((timeout
+ USEC_PER_SEC
- 1) / USEC_PER_SEC
);
2938 while (!hashmap_isempty(pids
)) {
2939 _cleanup_free_
char *path
= NULL
;
2942 pid
= PTR_TO_UINT(hashmap_first_key(pids
));
2945 path
= hashmap_remove(pids
, UINT_TO_PTR(pid
));
2948 wait_for_terminate_and_warn(path
, pid
, true);
2954 void execute_directories(const char* const* directories
, usec_t timeout
, char *argv
[]) {
2958 char **dirs
= (char**) directories
;
2960 assert(!strv_isempty(dirs
));
2962 name
= basename(dirs
[0]);
2963 assert(!isempty(name
));
2965 /* Executes all binaries in the directories in parallel and waits
2966 * for them to finish. Optionally a timeout is applied. If a file
2967 * with the same name exists in more than one directory, the
2968 * earliest one wins. */
2970 executor_pid
= fork();
2971 if (executor_pid
< 0) {
2972 log_error_errno(errno
, "Failed to fork: %m");
2975 } else if (executor_pid
== 0) {
2976 r
= do_execute(dirs
, timeout
, argv
);
2977 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
2980 wait_for_terminate_and_warn(name
, executor_pid
, true);
2983 bool nulstr_contains(const char*nulstr
, const char *needle
) {
2989 NULSTR_FOREACH(i
, nulstr
)
2990 if (streq(i
, needle
))
2996 bool plymouth_running(void) {
2997 return access("/run/plymouth/pid", F_OK
) >= 0;
3000 char* strshorten(char *s
, size_t l
) {
3009 bool machine_name_is_valid(const char *s
) {
3011 if (!hostname_is_valid(s
, false))
3014 /* Machine names should be useful hostnames, but also be
3015 * useful in unit names, hence we enforce a stricter length
3024 int pipe_eof(int fd
) {
3025 struct pollfd pollfd
= {
3027 .events
= POLLIN
|POLLHUP
,
3032 r
= poll(&pollfd
, 1, 0);
3039 return pollfd
.revents
& POLLHUP
;
3042 int fd_wait_for_event(int fd
, int event
, usec_t t
) {
3044 struct pollfd pollfd
= {
3052 r
= ppoll(&pollfd
, 1, t
== USEC_INFINITY
? NULL
: timespec_store(&ts
, t
), NULL
);
3059 return pollfd
.revents
;
3062 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
3071 r
= tempfn_xxxxxx(path
, NULL
, &t
);
3075 fd
= mkostemp_safe(t
, O_WRONLY
|O_CLOEXEC
);
3081 f
= fdopen(fd
, "we");
3095 int symlink_atomic(const char *from
, const char *to
) {
3096 _cleanup_free_
char *t
= NULL
;
3102 r
= tempfn_random(to
, NULL
, &t
);
3106 if (symlink(from
, t
) < 0)
3109 if (rename(t
, to
) < 0) {
3117 int symlink_idempotent(const char *from
, const char *to
) {
3118 _cleanup_free_
char *p
= NULL
;
3124 if (symlink(from
, to
) < 0) {
3125 if (errno
!= EEXIST
)
3128 r
= readlink_malloc(to
, &p
);
3132 if (!streq(p
, from
))
3139 int mknod_atomic(const char *path
, mode_t mode
, dev_t dev
) {
3140 _cleanup_free_
char *t
= NULL
;
3145 r
= tempfn_random(path
, NULL
, &t
);
3149 if (mknod(t
, mode
, dev
) < 0)
3152 if (rename(t
, path
) < 0) {
3160 int mkfifo_atomic(const char *path
, mode_t mode
) {
3161 _cleanup_free_
char *t
= NULL
;
3166 r
= tempfn_random(path
, NULL
, &t
);
3170 if (mkfifo(t
, mode
) < 0)
3173 if (rename(t
, path
) < 0) {
3181 bool display_is_local(const char *display
) {
3185 display
[0] == ':' &&
3186 display
[1] >= '0' &&
3190 int socket_from_display(const char *display
, char **path
) {
3197 if (!display_is_local(display
))
3200 k
= strspn(display
+1, "0123456789");
3202 f
= new(char, strlen("/tmp/.X11-unix/X") + k
+ 1);
3206 c
= stpcpy(f
, "/tmp/.X11-unix/X");
3207 memcpy(c
, display
+1, k
);
3216 const char **username
,
3217 uid_t
*uid
, gid_t
*gid
,
3219 const char **shell
) {
3227 /* We enforce some special rules for uid=0: in order to avoid
3228 * NSS lookups for root we hardcode its data. */
3230 if (streq(*username
, "root") || streq(*username
, "0")) {
3248 if (parse_uid(*username
, &u
) >= 0) {
3252 /* If there are multiple users with the same id, make
3253 * sure to leave $USER to the configured value instead
3254 * of the first occurrence in the database. However if
3255 * the uid was configured by a numeric uid, then let's
3256 * pick the real username from /etc/passwd. */
3258 *username
= p
->pw_name
;
3261 p
= getpwnam(*username
);
3265 return errno
> 0 ? -errno
: -ESRCH
;
3277 *shell
= p
->pw_shell
;
3282 char* uid_to_name(uid_t uid
) {
3287 return strdup("root");
3291 return strdup(p
->pw_name
);
3293 if (asprintf(&r
, UID_FMT
, uid
) < 0)
3299 char* gid_to_name(gid_t gid
) {
3304 return strdup("root");
3308 return strdup(p
->gr_name
);
3310 if (asprintf(&r
, GID_FMT
, gid
) < 0)
3316 int get_group_creds(const char **groupname
, gid_t
*gid
) {
3322 /* We enforce some special rules for gid=0: in order to avoid
3323 * NSS lookups for root we hardcode its data. */
3325 if (streq(*groupname
, "root") || streq(*groupname
, "0")) {
3326 *groupname
= "root";
3334 if (parse_gid(*groupname
, &id
) >= 0) {
3339 *groupname
= g
->gr_name
;
3342 g
= getgrnam(*groupname
);
3346 return errno
> 0 ? -errno
: -ESRCH
;
3354 int in_gid(gid_t gid
) {
3356 int ngroups_max
, r
, i
;
3358 if (getgid() == gid
)
3361 if (getegid() == gid
)
3364 ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
3365 assert(ngroups_max
> 0);
3367 gids
= alloca(sizeof(gid_t
) * ngroups_max
);
3369 r
= getgroups(ngroups_max
, gids
);
3373 for (i
= 0; i
< r
; i
++)
3380 int in_group(const char *name
) {
3384 r
= get_group_creds(&name
, &gid
);
3391 int glob_exists(const char *path
) {
3392 _cleanup_globfree_ glob_t g
= {};
3398 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
3400 if (k
== GLOB_NOMATCH
)
3402 else if (k
== GLOB_NOSPACE
)
3405 return !strv_isempty(g
.gl_pathv
);
3407 return errno
? -errno
: -EIO
;
3410 int glob_extend(char ***strv
, const char *path
) {
3411 _cleanup_globfree_ glob_t g
= {};
3416 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
3418 if (k
== GLOB_NOMATCH
)
3420 else if (k
== GLOB_NOSPACE
)
3422 else if (k
!= 0 || strv_isempty(g
.gl_pathv
))
3423 return errno
? -errno
: -EIO
;
3425 STRV_FOREACH(p
, g
.gl_pathv
) {
3426 k
= strv_extend(strv
, *p
);
3434 int dirent_ensure_type(DIR *d
, struct dirent
*de
) {
3440 if (de
->d_type
!= DT_UNKNOWN
)
3443 if (fstatat(dirfd(d
), de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
3447 S_ISREG(st
.st_mode
) ? DT_REG
:
3448 S_ISDIR(st
.st_mode
) ? DT_DIR
:
3449 S_ISLNK(st
.st_mode
) ? DT_LNK
:
3450 S_ISFIFO(st
.st_mode
) ? DT_FIFO
:
3451 S_ISSOCK(st
.st_mode
) ? DT_SOCK
:
3452 S_ISCHR(st
.st_mode
) ? DT_CHR
:
3453 S_ISBLK(st
.st_mode
) ? DT_BLK
:
3459 int get_files_in_directory(const char *path
, char ***list
) {
3460 _cleanup_closedir_
DIR *d
= NULL
;
3461 size_t bufsize
= 0, n
= 0;
3462 _cleanup_strv_free_
char **l
= NULL
;
3466 /* Returns all files in a directory in *list, and the number
3467 * of files as return value. If list is NULL returns only the
3479 if (!de
&& errno
!= 0)
3484 dirent_ensure_type(d
, de
);
3486 if (!dirent_is_file(de
))
3490 /* one extra slot is needed for the terminating NULL */
3491 if (!GREEDY_REALLOC(l
, bufsize
, n
+ 2))
3494 l
[n
] = strdup(de
->d_name
);
3505 l
= NULL
; /* avoid freeing */
3511 char *strjoin(const char *x
, ...) {
3525 t
= va_arg(ap
, const char *);
3530 if (n
> ((size_t) -1) - l
) {
3554 t
= va_arg(ap
, const char *);
3568 bool is_main_thread(void) {
3569 static thread_local
int cached
= 0;
3571 if (_unlikely_(cached
== 0))
3572 cached
= getpid() == gettid() ? 1 : -1;
3577 int block_get_whole_disk(dev_t d
, dev_t
*ret
) {
3584 /* If it has a queue this is good enough for us */
3585 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", major(d
), minor(d
)) < 0)
3588 r
= access(p
, F_OK
);
3596 /* If it is a partition find the originating device */
3597 if (asprintf(&p
, "/sys/dev/block/%u:%u/partition", major(d
), minor(d
)) < 0)
3600 r
= access(p
, F_OK
);
3606 /* Get parent dev_t */
3607 if (asprintf(&p
, "/sys/dev/block/%u:%u/../dev", major(d
), minor(d
)) < 0)
3610 r
= read_one_line_file(p
, &s
);
3616 r
= sscanf(s
, "%u:%u", &m
, &n
);
3622 /* Only return this if it is really good enough for us. */
3623 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", m
, n
) < 0)
3626 r
= access(p
, F_OK
);
3630 *ret
= makedev(m
, n
);
3637 static const char *const ioprio_class_table
[] = {
3638 [IOPRIO_CLASS_NONE
] = "none",
3639 [IOPRIO_CLASS_RT
] = "realtime",
3640 [IOPRIO_CLASS_BE
] = "best-effort",
3641 [IOPRIO_CLASS_IDLE
] = "idle"
3644 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, INT_MAX
);
3646 static const char *const sigchld_code_table
[] = {
3647 [CLD_EXITED
] = "exited",
3648 [CLD_KILLED
] = "killed",
3649 [CLD_DUMPED
] = "dumped",
3650 [CLD_TRAPPED
] = "trapped",
3651 [CLD_STOPPED
] = "stopped",
3652 [CLD_CONTINUED
] = "continued",
3655 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
3657 static const char *const log_facility_unshifted_table
[LOG_NFACILITIES
] = {
3658 [LOG_FAC(LOG_KERN
)] = "kern",
3659 [LOG_FAC(LOG_USER
)] = "user",
3660 [LOG_FAC(LOG_MAIL
)] = "mail",
3661 [LOG_FAC(LOG_DAEMON
)] = "daemon",
3662 [LOG_FAC(LOG_AUTH
)] = "auth",
3663 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
3664 [LOG_FAC(LOG_LPR
)] = "lpr",
3665 [LOG_FAC(LOG_NEWS
)] = "news",
3666 [LOG_FAC(LOG_UUCP
)] = "uucp",
3667 [LOG_FAC(LOG_CRON
)] = "cron",
3668 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
3669 [LOG_FAC(LOG_FTP
)] = "ftp",
3670 [LOG_FAC(LOG_LOCAL0
)] = "local0",
3671 [LOG_FAC(LOG_LOCAL1
)] = "local1",
3672 [LOG_FAC(LOG_LOCAL2
)] = "local2",
3673 [LOG_FAC(LOG_LOCAL3
)] = "local3",
3674 [LOG_FAC(LOG_LOCAL4
)] = "local4",
3675 [LOG_FAC(LOG_LOCAL5
)] = "local5",
3676 [LOG_FAC(LOG_LOCAL6
)] = "local6",
3677 [LOG_FAC(LOG_LOCAL7
)] = "local7"
3680 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted
, int, LOG_FAC(~0));
3682 static const char *const log_level_table
[] = {
3683 [LOG_EMERG
] = "emerg",
3684 [LOG_ALERT
] = "alert",
3685 [LOG_CRIT
] = "crit",
3687 [LOG_WARNING
] = "warning",
3688 [LOG_NOTICE
] = "notice",
3689 [LOG_INFO
] = "info",
3690 [LOG_DEBUG
] = "debug"
3693 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level
, int, LOG_DEBUG
);
3695 static const char* const sched_policy_table
[] = {
3696 [SCHED_OTHER
] = "other",
3697 [SCHED_BATCH
] = "batch",
3698 [SCHED_IDLE
] = "idle",
3699 [SCHED_FIFO
] = "fifo",
3703 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);
3705 static const char* const rlimit_table
[_RLIMIT_MAX
] = {
3706 [RLIMIT_CPU
] = "LimitCPU",
3707 [RLIMIT_FSIZE
] = "LimitFSIZE",
3708 [RLIMIT_DATA
] = "LimitDATA",
3709 [RLIMIT_STACK
] = "LimitSTACK",
3710 [RLIMIT_CORE
] = "LimitCORE",
3711 [RLIMIT_RSS
] = "LimitRSS",
3712 [RLIMIT_NOFILE
] = "LimitNOFILE",
3713 [RLIMIT_AS
] = "LimitAS",
3714 [RLIMIT_NPROC
] = "LimitNPROC",
3715 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
3716 [RLIMIT_LOCKS
] = "LimitLOCKS",
3717 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
3718 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
3719 [RLIMIT_NICE
] = "LimitNICE",
3720 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
3721 [RLIMIT_RTTIME
] = "LimitRTTIME"
3724 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
3726 static const char* const ip_tos_table
[] = {
3727 [IPTOS_LOWDELAY
] = "low-delay",
3728 [IPTOS_THROUGHPUT
] = "throughput",
3729 [IPTOS_RELIABILITY
] = "reliability",
3730 [IPTOS_LOWCOST
] = "low-cost",
3733 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
3735 bool kexec_loaded(void) {
3736 bool loaded
= false;
3739 if (read_one_line_file("/sys/kernel/kexec_loaded", &s
) >= 0) {
3747 int prot_from_flags(int flags
) {
3749 switch (flags
& O_ACCMODE
) {
3758 return PROT_READ
|PROT_WRITE
;
3765 char *format_bytes(char *buf
, size_t l
, off_t t
) {
3768 static const struct {
3772 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3773 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3774 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3775 { "G", 1024ULL*1024ULL*1024ULL },
3776 { "M", 1024ULL*1024ULL },
3780 if (t
== (off_t
) -1)
3783 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
3785 if (t
>= table
[i
].factor
) {
3788 (unsigned long long) (t
/ table
[i
].factor
),
3789 (unsigned long long) (((t
*10ULL) / table
[i
].factor
) % 10ULL),
3796 snprintf(buf
, l
, "%lluB", (unsigned long long) t
);
3804 void* memdup(const void *p
, size_t l
) {
3817 int fd_inc_sndbuf(int fd
, size_t n
) {
3819 socklen_t l
= sizeof(value
);
3821 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
3822 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
3825 /* If we have the privileges we will ignore the kernel limit. */
3828 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
3829 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
3835 int fd_inc_rcvbuf(int fd
, size_t n
) {
3837 socklen_t l
= sizeof(value
);
3839 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
3840 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
3843 /* If we have the privileges we will ignore the kernel limit. */
3846 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
3847 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
3852 int fork_agent(pid_t
*pid
, const int except
[], unsigned n_except
, const char *path
, ...) {
3853 bool stdout_is_tty
, stderr_is_tty
;
3854 pid_t parent_pid
, agent_pid
;
3855 sigset_t ss
, saved_ss
;
3863 /* Spawns a temporary TTY agent, making sure it goes away when
3866 parent_pid
= getpid();
3868 /* First we temporarily block all signals, so that the new
3869 * child has them blocked initially. This way, we can be sure
3870 * that SIGTERMs are not lost we might send to the agent. */
3871 assert_se(sigfillset(&ss
) >= 0);
3872 assert_se(sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) >= 0);
3875 if (agent_pid
< 0) {
3876 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
3880 if (agent_pid
!= 0) {
3881 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
3888 * Make sure the agent goes away when the parent dies */
3889 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
3890 _exit(EXIT_FAILURE
);
3892 /* Make sure we actually can kill the agent, if we need to, in
3893 * case somebody invoked us from a shell script that trapped
3894 * SIGTERM or so... */
3895 (void) reset_all_signal_handlers();
3896 (void) reset_signal_mask();
3898 /* Check whether our parent died before we were able
3899 * to set the death signal and unblock the signals */
3900 if (getppid() != parent_pid
)
3901 _exit(EXIT_SUCCESS
);
3903 /* Don't leak fds to the agent */
3904 close_all_fds(except
, n_except
);
3906 stdout_is_tty
= isatty(STDOUT_FILENO
);
3907 stderr_is_tty
= isatty(STDERR_FILENO
);
3909 if (!stdout_is_tty
|| !stderr_is_tty
) {
3912 /* Detach from stdout/stderr. and reopen
3913 * /dev/tty for them. This is important to
3914 * ensure that when systemctl is started via
3915 * popen() or a similar call that expects to
3916 * read EOF we actually do generate EOF and
3917 * not delay this indefinitely by because we
3918 * keep an unused copy of stdin around. */
3919 fd
= open("/dev/tty", O_WRONLY
);
3921 log_error_errno(errno
, "Failed to open /dev/tty: %m");
3922 _exit(EXIT_FAILURE
);
3926 dup2(fd
, STDOUT_FILENO
);
3929 dup2(fd
, STDERR_FILENO
);
3935 /* Count arguments */
3937 for (n
= 0; va_arg(ap
, char*); n
++)
3942 l
= alloca(sizeof(char *) * (n
+ 1));
3944 /* Fill in arguments */
3946 for (i
= 0; i
<= n
; i
++)
3947 l
[i
] = va_arg(ap
, char*);
3951 _exit(EXIT_FAILURE
);
3954 int setrlimit_closest(int resource
, const struct rlimit
*rlim
) {
3955 struct rlimit highest
, fixed
;
3959 if (setrlimit(resource
, rlim
) >= 0)
3965 /* So we failed to set the desired setrlimit, then let's try
3966 * to get as close as we can */
3967 assert_se(getrlimit(resource
, &highest
) == 0);
3969 fixed
.rlim_cur
= MIN(rlim
->rlim_cur
, highest
.rlim_max
);
3970 fixed
.rlim_max
= MIN(rlim
->rlim_max
, highest
.rlim_max
);
3972 if (setrlimit(resource
, &fixed
) < 0)
3978 bool http_etag_is_valid(const char *etag
) {
3982 if (!endswith(etag
, "\""))
3985 if (!startswith(etag
, "\"") && !startswith(etag
, "W/\""))
3991 bool http_url_is_valid(const char *url
) {
3997 p
= startswith(url
, "http://");
3999 p
= startswith(url
, "https://");
4006 return ascii_is_valid(p
);
4009 bool documentation_url_is_valid(const char *url
) {
4015 if (http_url_is_valid(url
))
4018 p
= startswith(url
, "file:/");
4020 p
= startswith(url
, "info:");
4022 p
= startswith(url
, "man:");
4027 return ascii_is_valid(p
);
4030 bool in_initrd(void) {
4031 static int saved
= -1;
4037 /* We make two checks here:
4039 * 1. the flag file /etc/initrd-release must exist
4040 * 2. the root file system must be a memory file system
4042 * The second check is extra paranoia, since misdetecting an
4043 * initrd can have bad bad consequences due the initrd
4044 * emptying when transititioning to the main systemd.
4047 saved
= access("/etc/initrd-release", F_OK
) >= 0 &&
4048 statfs("/", &s
) >= 0 &&
4049 is_temporary_fs(&s
);
4054 int get_home_dir(char **_h
) {
4062 /* Take the user specified one */
4063 e
= secure_getenv("HOME");
4064 if (e
&& path_is_absolute(e
)) {
4073 /* Hardcode home directory for root to avoid NSS */
4076 h
= strdup("/root");
4084 /* Check the database... */
4088 return errno
> 0 ? -errno
: -ESRCH
;
4090 if (!path_is_absolute(p
->pw_dir
))
4093 h
= strdup(p
->pw_dir
);
4101 int get_shell(char **_s
) {
4109 /* Take the user specified one */
4110 e
= getenv("SHELL");
4120 /* Hardcode home directory for root to avoid NSS */
4123 s
= strdup("/bin/sh");
4131 /* Check the database... */
4135 return errno
> 0 ? -errno
: -ESRCH
;
4137 if (!path_is_absolute(p
->pw_shell
))
4140 s
= strdup(p
->pw_shell
);
4148 bool filename_is_valid(const char *p
) {
4162 if (strlen(p
) > FILENAME_MAX
)
4168 bool string_is_safe(const char *p
) {
4174 for (t
= p
; *t
; t
++) {
4175 if (*t
> 0 && *t
< ' ')
4178 if (strchr("\\\"\'\x7f", *t
))
4186 * Check if a string contains control characters. If 'ok' is non-NULL
4187 * it may be a string containing additional CCs to be considered OK.
4189 bool string_has_cc(const char *p
, const char *ok
) {
4194 for (t
= p
; *t
; t
++) {
4195 if (ok
&& strchr(ok
, *t
))
4198 if (*t
> 0 && *t
< ' ')
4208 bool path_is_safe(const char *p
) {
4213 if (streq(p
, "..") || startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
4216 if (strlen(p
)+1 > PATH_MAX
)
4219 /* The following two checks are not really dangerous, but hey, they still are confusing */
4220 if (streq(p
, ".") || startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
4223 if (strstr(p
, "//"))
4229 /* hey glibc, APIs with callbacks without a user pointer are so useless */
4230 void *xbsearch_r(const void *key
, const void *base
, size_t nmemb
, size_t size
,
4231 int (*compar
) (const void *, const void *, void *), void *arg
) {
4240 p
= (void *)(((const char *) base
) + (idx
* size
));
4241 comparison
= compar(key
, p
, arg
);
4244 else if (comparison
> 0)
4252 void init_gettext(void) {
4253 setlocale(LC_ALL
, "");
4254 textdomain(GETTEXT_PACKAGE
);
4257 bool is_locale_utf8(void) {
4259 static int cached_answer
= -1;
4261 if (cached_answer
>= 0)
4264 if (!setlocale(LC_ALL
, "")) {
4265 cached_answer
= true;
4269 set
= nl_langinfo(CODESET
);
4271 cached_answer
= true;
4275 if (streq(set
, "UTF-8")) {
4276 cached_answer
= true;
4280 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
4281 * unset and everything can do to UTF-8 nowadays. */
4282 set
= setlocale(LC_CTYPE
, NULL
);
4284 cached_answer
= true;
4288 /* Check result, but ignore the result if C was set
4292 !getenv("LC_ALL") &&
4293 !getenv("LC_CTYPE") &&
4297 return (bool) cached_answer
;
4300 const char *draw_special_char(DrawSpecialChar ch
) {
4301 static const char *draw_table
[2][_DRAW_SPECIAL_CHAR_MAX
] = {
4304 [DRAW_TREE_VERTICAL
] = "\342\224\202 ", /* │ */
4305 [DRAW_TREE_BRANCH
] = "\342\224\234\342\224\200", /* ├─ */
4306 [DRAW_TREE_RIGHT
] = "\342\224\224\342\224\200", /* └─ */
4307 [DRAW_TREE_SPACE
] = " ", /* */
4308 [DRAW_TRIANGULAR_BULLET
] = "\342\200\243", /* ‣ */
4309 [DRAW_BLACK_CIRCLE
] = "\342\227\217", /* ● */
4310 [DRAW_ARROW
] = "\342\206\222", /* → */
4311 [DRAW_DASH
] = "\342\200\223", /* – */
4314 /* ASCII fallback */ {
4315 [DRAW_TREE_VERTICAL
] = "| ",
4316 [DRAW_TREE_BRANCH
] = "|-",
4317 [DRAW_TREE_RIGHT
] = "`-",
4318 [DRAW_TREE_SPACE
] = " ",
4319 [DRAW_TRIANGULAR_BULLET
] = ">",
4320 [DRAW_BLACK_CIRCLE
] = "*",
4321 [DRAW_ARROW
] = "->",
4326 return draw_table
[!is_locale_utf8()][ch
];
4329 char *strreplace(const char *text
, const char *old_string
, const char *new_string
) {
4332 size_t l
, old_len
, new_len
;
4338 old_len
= strlen(old_string
);
4339 new_len
= strlen(new_string
);
4352 if (!startswith(f
, old_string
)) {
4358 nl
= l
- old_len
+ new_len
;
4359 a
= realloc(r
, nl
+ 1);
4367 t
= stpcpy(t
, new_string
);
4379 char *strip_tab_ansi(char **ibuf
, size_t *_isz
) {
4380 const char *i
, *begin
= NULL
;
4385 } state
= STATE_OTHER
;
4387 size_t osz
= 0, isz
;
4393 /* Strips ANSI color and replaces TABs by 8 spaces */
4395 isz
= _isz
? *_isz
: strlen(*ibuf
);
4397 f
= open_memstream(&obuf
, &osz
);
4401 for (i
= *ibuf
; i
< *ibuf
+ isz
+ 1; i
++) {
4406 if (i
>= *ibuf
+ isz
) /* EOT */
4408 else if (*i
== '\x1B')
4409 state
= STATE_ESCAPE
;
4410 else if (*i
== '\t')
4417 if (i
>= *ibuf
+ isz
) { /* EOT */
4420 } else if (*i
== '[') {
4421 state
= STATE_BRACKET
;
4426 state
= STATE_OTHER
;
4433 if (i
>= *ibuf
+ isz
|| /* EOT */
4434 (!(*i
>= '0' && *i
<= '9') && *i
!= ';' && *i
!= 'm')) {
4437 state
= STATE_OTHER
;
4439 } else if (*i
== 'm')
4440 state
= STATE_OTHER
;
4462 int on_ac_power(void) {
4463 bool found_offline
= false, found_online
= false;
4464 _cleanup_closedir_
DIR *d
= NULL
;
4466 d
= opendir("/sys/class/power_supply");
4468 return errno
== ENOENT
? true : -errno
;
4472 _cleanup_close_
int fd
= -1, device
= -1;
4478 if (!de
&& errno
!= 0)
4484 if (hidden_file(de
->d_name
))
4487 device
= openat(dirfd(d
), de
->d_name
, O_DIRECTORY
|O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4489 if (errno
== ENOENT
|| errno
== ENOTDIR
)
4495 fd
= openat(device
, "type", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4497 if (errno
== ENOENT
)
4503 n
= read(fd
, contents
, sizeof(contents
));
4507 if (n
!= 6 || memcmp(contents
, "Mains\n", 6))
4511 fd
= openat(device
, "online", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4513 if (errno
== ENOENT
)
4519 n
= read(fd
, contents
, sizeof(contents
));
4523 if (n
!= 2 || contents
[1] != '\n')
4526 if (contents
[0] == '1') {
4527 found_online
= true;
4529 } else if (contents
[0] == '0')
4530 found_offline
= true;
4535 return found_online
|| !found_offline
;
4538 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
4545 if (!path_strv_resolve_uniq(search
, root
))
4548 STRV_FOREACH(i
, search
) {
4549 _cleanup_free_
char *p
= NULL
;
4553 p
= strjoin(root
, *i
, "/", path
, NULL
);
4555 p
= strjoin(*i
, "/", path
, NULL
);
4565 if (errno
!= ENOENT
)
4572 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
4573 _cleanup_strv_free_
char **copy
= NULL
;
4579 if (path_is_absolute(path
)) {
4582 f
= fopen(path
, mode
);
4591 copy
= strv_copy((char**) search
);
4595 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
4598 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
4599 _cleanup_strv_free_
char **s
= NULL
;
4601 if (path_is_absolute(path
)) {
4604 f
= fopen(path
, mode
);
4613 s
= strv_split_nulstr(search
);
4617 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
4620 char *strextend(char **x
, ...) {
4627 l
= f
= *x
? strlen(*x
) : 0;
4634 t
= va_arg(ap
, const char *);
4639 if (n
> ((size_t) -1) - l
) {
4648 r
= realloc(*x
, l
+1);
4658 t
= va_arg(ap
, const char *);
4672 char *strrep(const char *s
, unsigned n
) {
4680 p
= r
= malloc(l
* n
+ 1);
4684 for (i
= 0; i
< n
; i
++)
4691 void* greedy_realloc(void **p
, size_t *allocated
, size_t need
, size_t size
) {
4698 if (*allocated
>= need
)
4701 newalloc
= MAX(need
* 2, 64u / size
);
4702 a
= newalloc
* size
;
4704 /* check for overflows */
4705 if (a
< size
* need
)
4713 *allocated
= newalloc
;
4717 void* greedy_realloc0(void **p
, size_t *allocated
, size_t need
, size_t size
) {
4726 q
= greedy_realloc(p
, allocated
, need
, size
);
4730 if (*allocated
> prev
)
4731 memzero(q
+ prev
* size
, (*allocated
- prev
) * size
);
4736 bool id128_is_valid(const char *s
) {
4742 /* Simple formatted 128bit hex string */
4744 for (i
= 0; i
< l
; i
++) {
4747 if (!(c
>= '0' && c
<= '9') &&
4748 !(c
>= 'a' && c
<= 'z') &&
4749 !(c
>= 'A' && c
<= 'Z'))
4753 } else if (l
== 36) {
4755 /* Formatted UUID */
4757 for (i
= 0; i
< l
; i
++) {
4760 if ((i
== 8 || i
== 13 || i
== 18 || i
== 23)) {
4764 if (!(c
>= '0' && c
<= '9') &&
4765 !(c
>= 'a' && c
<= 'z') &&
4766 !(c
>= 'A' && c
<= 'Z'))
4777 int split_pair(const char *s
, const char *sep
, char **l
, char **r
) {
4792 a
= strndup(s
, x
- s
);
4796 b
= strdup(x
+ strlen(sep
));
4808 int shall_restore_state(void) {
4809 _cleanup_free_
char *value
= NULL
;
4812 r
= get_proc_cmdline_key("systemd.restore_state=", &value
);
4818 return parse_boolean(value
) != 0;
4821 int proc_cmdline(char **ret
) {
4824 if (detect_container(NULL
) > 0)
4825 return get_process_cmdline(1, 0, false, ret
);
4827 return read_one_line_file("/proc/cmdline", ret
);
4830 int parse_proc_cmdline(int (*parse_item
)(const char *key
, const char *value
)) {
4831 _cleanup_free_
char *line
= NULL
;
4837 r
= proc_cmdline(&line
);
4843 _cleanup_free_
char *word
= NULL
;
4846 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
4852 /* Filter out arguments that are intended only for the
4854 if (!in_initrd() && startswith(word
, "rd."))
4857 value
= strchr(word
, '=');
4861 r
= parse_item(word
, value
);
4869 int get_proc_cmdline_key(const char *key
, char **value
) {
4870 _cleanup_free_
char *line
= NULL
, *ret
= NULL
;
4877 r
= proc_cmdline(&line
);
4883 _cleanup_free_
char *word
= NULL
;
4886 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
4892 /* Filter out arguments that are intended only for the
4894 if (!in_initrd() && startswith(word
, "rd."))
4898 e
= startswith(word
, key
);
4902 r
= free_and_strdup(&ret
, e
);
4908 if (streq(word
, key
))
4922 int container_get_leader(const char *machine
, pid_t
*pid
) {
4923 _cleanup_free_
char *s
= NULL
, *class = NULL
;
4931 p
= strjoina("/run/systemd/machines/", machine
);
4932 r
= parse_env_file(p
, NEWLINE
, "LEADER", &s
, "CLASS", &class, NULL
);
4940 if (!streq_ptr(class, "container"))
4943 r
= parse_pid(s
, &leader
);
4953 int namespace_open(pid_t pid
, int *pidns_fd
, int *mntns_fd
, int *netns_fd
, int *root_fd
) {
4954 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, netnsfd
= -1;
4962 mntns
= procfs_file_alloca(pid
, "ns/mnt");
4963 mntnsfd
= open(mntns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
4971 pidns
= procfs_file_alloca(pid
, "ns/pid");
4972 pidnsfd
= open(pidns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
4980 netns
= procfs_file_alloca(pid
, "ns/net");
4981 netnsfd
= open(netns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
4989 root
= procfs_file_alloca(pid
, "root");
4990 rfd
= open(root
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
|O_DIRECTORY
);
4996 *pidns_fd
= pidnsfd
;
4999 *mntns_fd
= mntnsfd
;
5002 *netns_fd
= netnsfd
;
5007 pidnsfd
= mntnsfd
= netnsfd
= -1;
5012 int namespace_enter(int pidns_fd
, int mntns_fd
, int netns_fd
, int root_fd
) {
5015 if (setns(pidns_fd
, CLONE_NEWPID
) < 0)
5019 if (setns(mntns_fd
, CLONE_NEWNS
) < 0)
5023 if (setns(netns_fd
, CLONE_NEWNET
) < 0)
5027 if (fchdir(root_fd
) < 0)
5030 if (chroot(".") < 0)
5034 return reset_uid_gid();
5037 int getpeercred(int fd
, struct ucred
*ucred
) {
5038 socklen_t n
= sizeof(struct ucred
);
5045 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
);
5049 if (n
!= sizeof(struct ucred
))
5052 /* Check if the data is actually useful and not suppressed due
5053 * to namespacing issues */
5056 if (u
.uid
== UID_INVALID
)
5058 if (u
.gid
== GID_INVALID
)
5065 int getpeersec(int fd
, char **ret
) {
5077 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
5081 if (errno
!= ERANGE
)
5088 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
5104 /* This is much like like mkostemp() but is subject to umask(). */
5105 int mkostemp_safe(char *pattern
, int flags
) {
5106 _cleanup_umask_ mode_t u
;
5113 fd
= mkostemp(pattern
, flags
);
5120 int open_tmpfile(const char *path
, int flags
) {
5127 /* Try O_TMPFILE first, if it is supported */
5128 fd
= open(path
, flags
|O_TMPFILE
|O_EXCL
, S_IRUSR
|S_IWUSR
);
5133 /* Fall back to unguessable name + unlinking */
5134 p
= strjoina(path
, "/systemd-tmp-XXXXXX");
5136 fd
= mkostemp_safe(p
, flags
);
5144 int fd_warn_permissions(const char *path
, int fd
) {
5147 if (fstat(fd
, &st
) < 0)
5150 if (st
.st_mode
& 0111)
5151 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path
);
5153 if (st
.st_mode
& 0002)
5154 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path
);
5156 if (getpid() == 1 && (st
.st_mode
& 0044) != 0044)
5157 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
);
5162 unsigned long personality_from_string(const char *p
) {
5164 /* Parse a personality specifier. We introduce our own
5165 * identifiers that indicate specific ABIs, rather than just
5166 * hints regarding the register size, since we want to keep
5167 * things open for multiple locally supported ABIs for the
5168 * same register size. We try to reuse the ABI identifiers
5169 * used by libseccomp. */
5171 #if defined(__x86_64__)
5173 if (streq(p
, "x86"))
5176 if (streq(p
, "x86-64"))
5179 #elif defined(__i386__)
5181 if (streq(p
, "x86"))
5185 return PERSONALITY_INVALID
;
5188 const char* personality_to_string(unsigned long p
) {
5190 #if defined(__x86_64__)
5192 if (p
== PER_LINUX32
)
5198 #elif defined(__i386__)
5207 uint64_t physical_memory(void) {
5210 /* We return this as uint64_t in case we are running as 32bit
5211 * process on a 64bit kernel with huge amounts of memory */
5213 mem
= sysconf(_SC_PHYS_PAGES
);
5216 return (uint64_t) mem
* (uint64_t) page_size();
5219 void hexdump(FILE *f
, const void *p
, size_t s
) {
5220 const uint8_t *b
= p
;
5223 assert(s
== 0 || b
);
5228 fprintf(f
, "%04x ", n
);
5230 for (i
= 0; i
< 16; i
++) {
5235 fprintf(f
, "%02x ", b
[i
]);
5243 for (i
= 0; i
< 16; i
++) {
5248 fputc(isprint(b
[i
]) ? (char) b
[i
] : '.', f
);
5262 int update_reboot_param_file(const char *param
) {
5267 r
= write_string_file(REBOOT_PARAM_FILE
, param
, WRITE_STRING_FILE_CREATE
);
5269 log_error("Failed to write reboot param to "
5270 REBOOT_PARAM_FILE
": %s", strerror(-r
));
5272 unlink(REBOOT_PARAM_FILE
);
5277 int umount_recursive(const char *prefix
, int flags
) {
5281 /* Try to umount everything recursively below a
5282 * directory. Also, take care of stacked mounts, and keep
5283 * unmounting them until they are gone. */
5286 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
5291 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
5292 if (!proc_self_mountinfo
)
5296 _cleanup_free_
char *path
= NULL
, *p
= NULL
;
5299 k
= fscanf(proc_self_mountinfo
,
5300 "%*s " /* (1) mount id */
5301 "%*s " /* (2) parent id */
5302 "%*s " /* (3) major:minor */
5303 "%*s " /* (4) root */
5304 "%ms " /* (5) mount point */
5305 "%*s" /* (6) mount options */
5306 "%*[^-]" /* (7) optional fields */
5307 "- " /* (8) separator */
5308 "%*s " /* (9) file system type */
5309 "%*s" /* (10) mount source */
5310 "%*s" /* (11) mount options 2 */
5311 "%*[^\n]", /* some rubbish at the end */
5320 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
5324 if (!path_startswith(p
, prefix
))
5327 if (umount2(p
, flags
) < 0) {
5343 static int get_mount_flags(const char *path
, unsigned long *flags
) {
5346 if (statvfs(path
, &buf
) < 0)
5348 *flags
= buf
.f_flag
;
5352 int bind_remount_recursive(const char *prefix
, bool ro
) {
5353 _cleanup_set_free_free_ Set
*done
= NULL
;
5354 _cleanup_free_
char *cleaned
= NULL
;
5357 /* Recursively remount a directory (and all its submounts)
5358 * read-only or read-write. If the directory is already
5359 * mounted, we reuse the mount and simply mark it
5360 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
5361 * operation). If it isn't we first make it one. Afterwards we
5362 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
5363 * submounts we can access, too. When mounts are stacked on
5364 * the same mount point we only care for each individual
5365 * "top-level" mount on each point, as we cannot
5366 * influence/access the underlying mounts anyway. We do not
5367 * have any effect on future submounts that might get
5368 * propagated, they migt be writable. This includes future
5369 * submounts that have been triggered via autofs. */
5371 cleaned
= strdup(prefix
);
5375 path_kill_slashes(cleaned
);
5377 done
= set_new(&string_hash_ops
);
5382 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
5383 _cleanup_set_free_free_ Set
*todo
= NULL
;
5384 bool top_autofs
= false;
5386 unsigned long orig_flags
;
5388 todo
= set_new(&string_hash_ops
);
5392 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
5393 if (!proc_self_mountinfo
)
5397 _cleanup_free_
char *path
= NULL
, *p
= NULL
, *type
= NULL
;
5400 k
= fscanf(proc_self_mountinfo
,
5401 "%*s " /* (1) mount id */
5402 "%*s " /* (2) parent id */
5403 "%*s " /* (3) major:minor */
5404 "%*s " /* (4) root */
5405 "%ms " /* (5) mount point */
5406 "%*s" /* (6) mount options (superblock) */
5407 "%*[^-]" /* (7) optional fields */
5408 "- " /* (8) separator */
5409 "%ms " /* (9) file system type */
5410 "%*s" /* (10) mount source */
5411 "%*s" /* (11) mount options (bind mount) */
5412 "%*[^\n]", /* some rubbish at the end */
5422 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
5426 /* Let's ignore autofs mounts. If they aren't
5427 * triggered yet, we want to avoid triggering
5428 * them, as we don't make any guarantees for
5429 * future submounts anyway. If they are
5430 * already triggered, then we will find
5431 * another entry for this. */
5432 if (streq(type
, "autofs")) {
5433 top_autofs
= top_autofs
|| path_equal(cleaned
, p
);
5437 if (path_startswith(p
, cleaned
) &&
5438 !set_contains(done
, p
)) {
5440 r
= set_consume(todo
, p
);
5450 /* If we have no submounts to process anymore and if
5451 * the root is either already done, or an autofs, we
5453 if (set_isempty(todo
) &&
5454 (top_autofs
|| set_contains(done
, cleaned
)))
5457 if (!set_contains(done
, cleaned
) &&
5458 !set_contains(todo
, cleaned
)) {
5459 /* The prefix directory itself is not yet a
5460 * mount, make it one. */
5461 if (mount(cleaned
, cleaned
, NULL
, MS_BIND
|MS_REC
, NULL
) < 0)
5465 (void) get_mount_flags(cleaned
, &orig_flags
);
5466 orig_flags
&= ~MS_RDONLY
;
5468 if (mount(NULL
, prefix
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0)
5471 x
= strdup(cleaned
);
5475 r
= set_consume(done
, x
);
5480 while ((x
= set_steal_first(todo
))) {
5482 r
= set_consume(done
, x
);
5483 if (r
== -EEXIST
|| r
== 0)
5488 /* Try to reuse the original flag set, but
5489 * don't care for errors, in case of
5490 * obstructed mounts */
5492 (void) get_mount_flags(x
, &orig_flags
);
5493 orig_flags
&= ~MS_RDONLY
;
5495 if (mount(NULL
, x
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0) {
5497 /* Deal with mount points that are
5498 * obstructed by a later mount */
5500 if (errno
!= ENOENT
)
5508 int fflush_and_check(FILE *f
) {
5515 return errno
? -errno
: -EIO
;
5520 int tempfn_xxxxxx(const char *p
, const char *extra
, char **ret
) {
5532 * /foo/bar/.#<extra>waldoXXXXXX
5536 if (!filename_is_valid(fn
))
5542 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 6 + 1);
5546 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
), "XXXXXX");
5548 *ret
= path_kill_slashes(t
);
5552 int tempfn_random(const char *p
, const char *extra
, char **ret
) {
5566 * /foo/bar/.#<extra>waldobaa2a261115984a9
5570 if (!filename_is_valid(fn
))
5576 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 16 + 1);
5580 x
= stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
);
5583 for (i
= 0; i
< 16; i
++) {
5584 *(x
++) = hexchar(u
& 0xF);
5590 *ret
= path_kill_slashes(t
);
5594 int tempfn_random_child(const char *p
, const char *extra
, char **ret
) {
5605 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
5611 t
= new(char, strlen(p
) + 3 + strlen(extra
) + 16 + 1);
5615 x
= stpcpy(stpcpy(stpcpy(t
, p
), "/.#"), extra
);
5618 for (i
= 0; i
< 16; i
++) {
5619 *(x
++) = hexchar(u
& 0xF);
5625 *ret
= path_kill_slashes(t
);
5629 int take_password_lock(const char *root
) {
5631 struct flock flock
= {
5633 .l_whence
= SEEK_SET
,
5641 /* This is roughly the same as lckpwdf(), but not as awful. We
5642 * don't want to use alarm() and signals, hence we implement
5643 * our own trivial version of this.
5645 * Note that shadow-utils also takes per-database locks in
5646 * addition to lckpwdf(). However, we don't given that they
5647 * are redundant as they they invoke lckpwdf() first and keep
5648 * it during everything they do. The per-database locks are
5649 * awfully racy, and thus we just won't do them. */
5652 path
= strjoina(root
, "/etc/.pwd.lock");
5654 path
= "/etc/.pwd.lock";
5656 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
5660 r
= fcntl(fd
, F_SETLKW
, &flock
);
5669 int is_symlink(const char *path
) {
5672 if (lstat(path
, &info
) < 0)
5675 return !!S_ISLNK(info
.st_mode
);
5678 int is_dir(const char* path
, bool follow
) {
5683 r
= stat(path
, &st
);
5685 r
= lstat(path
, &st
);
5689 return !!S_ISDIR(st
.st_mode
);
5692 int is_device_node(const char *path
) {
5695 if (lstat(path
, &info
) < 0)
5698 return !!(S_ISBLK(info
.st_mode
) || S_ISCHR(info
.st_mode
));
5701 int extract_first_word(const char **p
, char **ret
, const char *separators
, ExtractFlags flags
) {
5702 _cleanup_free_
char *s
= NULL
;
5703 size_t allocated
= 0, sz
= 0;
5711 SINGLE_QUOTE_ESCAPE
,
5713 DOUBLE_QUOTE_ESCAPE
,
5721 separators
= WHITESPACE
;
5723 /* Bail early if called after last value or with no input */
5725 goto finish_force_terminate
;
5727 /* Parses the first word of a string, and returns it in
5728 * *ret. Removes all quotes in the process. When parsing fails
5729 * (because of an uneven number of quotes or similar), leaves
5730 * the pointer *p at the first invalid character. */
5739 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
)
5740 if (!GREEDY_REALLOC(s
, allocated
, sz
+1))
5742 goto finish_force_terminate
;
5743 } else if (strchr(separators
, c
)) {
5744 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
) {
5745 if (!GREEDY_REALLOC(s
, allocated
, sz
+1))
5748 goto finish_force_next
;
5758 goto finish_force_terminate
;
5759 else if (c
== '\'' && (flags
& EXTRACT_QUOTES
)) {
5760 if (!GREEDY_REALLOC(s
, allocated
, sz
+1))
5763 state
= SINGLE_QUOTE
;
5764 } else if (c
== '\\')
5765 state
= VALUE_ESCAPE
;
5766 else if (c
== '\"' && (flags
& EXTRACT_QUOTES
)) {
5767 if (!GREEDY_REALLOC(s
, allocated
, sz
+1))
5770 state
= DOUBLE_QUOTE
;
5771 } else if (strchr(separators
, c
)) {
5772 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
) {
5774 goto finish_force_next
;
5778 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5788 if (flags
& EXTRACT_RELAX
)
5789 goto finish_force_terminate
;
5791 } else if (c
== '\'')
5794 state
= SINGLE_QUOTE_ESCAPE
;
5796 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5810 state
= DOUBLE_QUOTE_ESCAPE
;
5812 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5820 case SINGLE_QUOTE_ESCAPE
:
5821 case DOUBLE_QUOTE_ESCAPE
:
5823 if (!GREEDY_REALLOC(s
, allocated
, sz
+7))
5827 if ((flags
& EXTRACT_CUNESCAPE_RELAX
) &&
5828 (state
== VALUE_ESCAPE
|| flags
& EXTRACT_RELAX
)) {
5829 /* If we find an unquoted trailing backslash and we're in
5830 * EXTRACT_CUNESCAPE_RELAX mode, keep it verbatim in the
5833 * Unbalanced quotes will only be allowed in EXTRACT_RELAX
5834 * mode, EXTRACT_CUNESCAPE_RELAX mode does not allow them.
5837 goto finish_force_terminate
;
5839 if (flags
& EXTRACT_RELAX
)
5840 goto finish_force_terminate
;
5844 if (flags
& EXTRACT_CUNESCAPE
) {
5847 r
= cunescape_one(*p
, (size_t) -1, &c
, &u
);
5849 if (flags
& EXTRACT_CUNESCAPE_RELAX
) {
5860 s
[sz
++] = c
; /* normal explicit char */
5862 sz
+= utf8_encode_unichar(s
+ sz
, u
); /* unicode chars we'll encode as utf8 */
5867 state
= (state
== SINGLE_QUOTE_ESCAPE
) ? SINGLE_QUOTE
:
5868 (state
== DOUBLE_QUOTE_ESCAPE
) ? DOUBLE_QUOTE
:
5874 goto finish_force_terminate
;
5875 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
)
5876 goto finish_force_next
;
5877 if (!strchr(separators
, c
))
5885 finish_force_terminate
:
5902 int extract_first_word_and_warn(
5905 const char *separators
,
5908 const char *filename
,
5910 const char *rvalue
) {
5911 /* Try to unquote it, if it fails, warn about it and try again but this
5912 * time using EXTRACT_CUNESCAPE_RELAX to keep the backslashes verbatim
5913 * in invalid escape sequences. */
5918 r
= extract_first_word(p
, ret
, separators
, flags
);
5919 if (r
< 0 && !(flags
&EXTRACT_CUNESCAPE_RELAX
)) {
5920 /* Retry it with EXTRACT_CUNESCAPE_RELAX. */
5922 r
= extract_first_word(p
, ret
, separators
, flags
|EXTRACT_CUNESCAPE_RELAX
);
5924 log_syntax(unit
, LOG_ERR
, filename
, line
, EINVAL
,
5925 "Unbalanced quoting in command line, ignoring: \"%s\"", rvalue
);
5927 log_syntax(unit
, LOG_WARNING
, filename
, line
, EINVAL
,
5928 "Invalid escape sequences in command line: \"%s\"", rvalue
);
5933 int extract_many_words(const char **p
, const char *separators
, ExtractFlags flags
, ...) {
5938 /* Parses a number of words from a string, stripping any
5939 * quotes if necessary. */
5943 /* Count how many words are expected */
5944 va_start(ap
, flags
);
5946 if (!va_arg(ap
, char **))
5955 /* Read all words into a temporary array */
5956 l
= newa0(char*, n
);
5957 for (c
= 0; c
< n
; c
++) {
5959 r
= extract_first_word(p
, &l
[c
], separators
, flags
);
5963 for (j
= 0; j
< c
; j
++)
5973 /* If we managed to parse all words, return them in the passed
5975 va_start(ap
, flags
);
5976 for (i
= 0; i
< n
; i
++) {
5979 v
= va_arg(ap
, char **);
5989 int free_and_strdup(char **p
, const char *s
) {
5994 /* Replaces a string pointer with an strdup()ed new string,
5995 * possibly freeing the old one. */
5997 if (streq_ptr(*p
, s
))
6013 int ptsname_malloc(int fd
, char **ret
) {
6026 if (ptsname_r(fd
, c
, l
) == 0) {
6030 if (errno
!= ERANGE
) {
6040 int openpt_in_namespace(pid_t pid
, int flags
) {
6041 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, rootfd
= -1;
6042 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
6044 struct cmsghdr cmsghdr
;
6045 uint8_t buf
[CMSG_SPACE(sizeof(int))];
6047 struct msghdr mh
= {
6048 .msg_control
= &control
,
6049 .msg_controllen
= sizeof(control
),
6051 struct cmsghdr
*cmsg
;
6058 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &rootfd
);
6062 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
6072 pair
[0] = safe_close(pair
[0]);
6074 r
= namespace_enter(pidnsfd
, mntnsfd
, -1, rootfd
);
6076 _exit(EXIT_FAILURE
);
6078 master
= posix_openpt(flags
);
6080 _exit(EXIT_FAILURE
);
6082 cmsg
= CMSG_FIRSTHDR(&mh
);
6083 cmsg
->cmsg_level
= SOL_SOCKET
;
6084 cmsg
->cmsg_type
= SCM_RIGHTS
;
6085 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
6086 memcpy(CMSG_DATA(cmsg
), &master
, sizeof(int));
6088 mh
.msg_controllen
= cmsg
->cmsg_len
;
6090 if (sendmsg(pair
[1], &mh
, MSG_NOSIGNAL
) < 0)
6091 _exit(EXIT_FAILURE
);
6093 _exit(EXIT_SUCCESS
);
6096 pair
[1] = safe_close(pair
[1]);
6098 r
= wait_for_terminate(child
, &si
);
6101 if (si
.si_code
!= CLD_EXITED
|| si
.si_status
!= EXIT_SUCCESS
)
6104 if (recvmsg(pair
[0], &mh
, MSG_NOSIGNAL
|MSG_CMSG_CLOEXEC
) < 0)
6107 CMSG_FOREACH(cmsg
, &mh
)
6108 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
) {
6112 fds
= (int*) CMSG_DATA(cmsg
);
6113 n_fds
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
6116 close_many(fds
, n_fds
);
6126 ssize_t
fgetxattrat_fake(int dirfd
, const char *filename
, const char *attribute
, void *value
, size_t size
, int flags
) {
6127 _cleanup_close_
int fd
= -1;
6130 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
6132 fd
= openat(dirfd
, filename
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOATIME
|(flags
& AT_SYMLINK_NOFOLLOW
? O_NOFOLLOW
: 0));
6136 l
= fgetxattr(fd
, attribute
, value
, size
);
6143 static int parse_crtime(le64_t le
, usec_t
*usec
) {
6149 if (u
== 0 || u
== (uint64_t) -1)
6156 int fd_getcrtime(int fd
, usec_t
*usec
) {
6163 /* Until Linux gets a real concept of birthtime/creation time,
6164 * let's fake one with xattrs */
6166 n
= fgetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
));
6169 if (n
!= sizeof(le
))
6172 return parse_crtime(le
, usec
);
6175 int fd_getcrtime_at(int dirfd
, const char *name
, usec_t
*usec
, int flags
) {
6179 n
= fgetxattrat_fake(dirfd
, name
, "user.crtime_usec", &le
, sizeof(le
), flags
);
6182 if (n
!= sizeof(le
))
6185 return parse_crtime(le
, usec
);
6188 int path_getcrtime(const char *p
, usec_t
*usec
) {
6195 n
= getxattr(p
, "user.crtime_usec", &le
, sizeof(le
));
6198 if (n
!= sizeof(le
))
6201 return parse_crtime(le
, usec
);
6204 int fd_setcrtime(int fd
, usec_t usec
) {
6210 usec
= now(CLOCK_REALTIME
);
6212 le
= htole64((uint64_t) usec
);
6213 if (fsetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
), 0) < 0)
6219 int same_fd(int a
, int b
) {
6220 struct stat sta
, stb
;
6227 /* Compares two file descriptors. Note that semantics are
6228 * quite different depending on whether we have kcmp() or we
6229 * don't. If we have kcmp() this will only return true for
6230 * dup()ed file descriptors, but not otherwise. If we don't
6231 * have kcmp() this will also return true for two fds of the same
6232 * file, created by separate open() calls. Since we use this
6233 * call mostly for filtering out duplicates in the fd store
6234 * this difference hopefully doesn't matter too much. */
6239 /* Try to use kcmp() if we have it. */
6241 r
= kcmp(pid
, pid
, KCMP_FILE
, a
, b
);
6246 if (errno
!= ENOSYS
)
6249 /* We don't have kcmp(), use fstat() instead. */
6250 if (fstat(a
, &sta
) < 0)
6253 if (fstat(b
, &stb
) < 0)
6256 if ((sta
.st_mode
& S_IFMT
) != (stb
.st_mode
& S_IFMT
))
6259 /* We consider all device fds different, since two device fds
6260 * might refer to quite different device contexts even though
6261 * they share the same inode and backing dev_t. */
6263 if (S_ISCHR(sta
.st_mode
) || S_ISBLK(sta
.st_mode
))
6266 if (sta
.st_dev
!= stb
.st_dev
|| sta
.st_ino
!= stb
.st_ino
)
6269 /* The fds refer to the same inode on disk, let's also check
6270 * if they have the same fd flags. This is useful to
6271 * distinguish the read and write side of a pipe created with
6273 fa
= fcntl(a
, F_GETFL
);
6277 fb
= fcntl(b
, F_GETFL
);
6284 int chattr_fd(int fd
, unsigned value
, unsigned mask
) {
6285 unsigned old_attr
, new_attr
;
6290 if (fstat(fd
, &st
) < 0)
6293 /* Explicitly check whether this is a regular file or
6294 * directory. If it is anything else (such as a device node or
6295 * fifo), then the ioctl will not hit the file systems but
6296 * possibly drivers, where the ioctl might have different
6297 * effects. Notably, DRM is using the same ioctl() number. */
6299 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
6305 if (ioctl(fd
, FS_IOC_GETFLAGS
, &old_attr
) < 0)
6308 new_attr
= (old_attr
& ~mask
) | (value
& mask
);
6309 if (new_attr
== old_attr
)
6312 if (ioctl(fd
, FS_IOC_SETFLAGS
, &new_attr
) < 0)
6318 int chattr_path(const char *p
, unsigned value
, unsigned mask
) {
6319 _cleanup_close_
int fd
= -1;
6326 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
6330 return chattr_fd(fd
, value
, mask
);
6333 int read_attr_fd(int fd
, unsigned *ret
) {
6338 if (fstat(fd
, &st
) < 0)
6341 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
6344 if (ioctl(fd
, FS_IOC_GETFLAGS
, ret
) < 0)
6350 int read_attr_path(const char *p
, unsigned *ret
) {
6351 _cleanup_close_
int fd
= -1;
6356 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
6360 return read_attr_fd(fd
, ret
);
6363 static size_t nul_length(const uint8_t *p
, size_t sz
) {
6378 ssize_t
sparse_write(int fd
, const void *p
, size_t sz
, size_t run_length
) {
6379 const uint8_t *q
, *w
, *e
;
6387 n
= nul_length(q
, e
- q
);
6389 /* If there are more than the specified run length of
6390 * NUL bytes, or if this is the beginning or the end
6391 * of the buffer, then seek instead of write */
6392 if ((n
> run_length
) ||
6393 (n
> 0 && q
== p
) ||
6394 (n
> 0 && q
+ n
>= e
)) {
6396 l
= write(fd
, w
, q
- w
);
6403 if (lseek(fd
, n
, SEEK_CUR
) == (off_t
) -1)
6415 l
= write(fd
, w
, q
- w
);
6422 return q
- (const uint8_t*) p
;
6425 void sigkill_wait(pid_t
*pid
) {
6431 if (kill(*pid
, SIGKILL
) > 0)
6432 (void) wait_for_terminate(*pid
, NULL
);
6435 int syslog_parse_priority(const char **p
, int *priority
, bool with_facility
) {
6436 int a
= 0, b
= 0, c
= 0;
6446 if (!strchr(*p
, '>'))
6449 if ((*p
)[2] == '>') {
6450 c
= undecchar((*p
)[1]);
6452 } else if ((*p
)[3] == '>') {
6453 b
= undecchar((*p
)[1]);
6454 c
= undecchar((*p
)[2]);
6456 } else if ((*p
)[4] == '>') {
6457 a
= undecchar((*p
)[1]);
6458 b
= undecchar((*p
)[2]);
6459 c
= undecchar((*p
)[3]);
6464 if (a
< 0 || b
< 0 || c
< 0 ||
6465 (!with_facility
&& (a
|| b
|| c
> 7)))
6469 *priority
= a
*100 + b
*10 + c
;
6471 *priority
= (*priority
& LOG_FACMASK
) | c
;
6477 ssize_t
string_table_lookup(const char * const *table
, size_t len
, const char *key
) {
6483 for (i
= 0; i
< len
; ++i
)
6484 if (streq_ptr(table
[i
], key
))
6490 void cmsg_close_all(struct msghdr
*mh
) {
6491 struct cmsghdr
*cmsg
;
6495 CMSG_FOREACH(cmsg
, mh
)
6496 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
)
6497 close_many((int*) CMSG_DATA(cmsg
), (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int));
6500 int rename_noreplace(int olddirfd
, const char *oldpath
, int newdirfd
, const char *newpath
) {
6504 ret
= renameat2(olddirfd
, oldpath
, newdirfd
, newpath
, RENAME_NOREPLACE
);
6508 /* renameat2() exists since Linux 3.15, btrfs added support for it later.
6509 * If it is not implemented, fallback to another method. */
6510 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
6513 /* The link()/unlink() fallback does not work on directories. But
6514 * renameat() without RENAME_NOREPLACE gives the same semantics on
6515 * directories, except when newpath is an *empty* directory. This is
6517 ret
= fstatat(olddirfd
, oldpath
, &buf
, AT_SYMLINK_NOFOLLOW
);
6518 if (ret
>= 0 && S_ISDIR(buf
.st_mode
)) {
6519 ret
= renameat(olddirfd
, oldpath
, newdirfd
, newpath
);
6520 return ret
>= 0 ? 0 : -errno
;
6523 /* If it is not a directory, use the link()/unlink() fallback. */
6524 ret
= linkat(olddirfd
, oldpath
, newdirfd
, newpath
, 0);
6528 ret
= unlinkat(olddirfd
, oldpath
, 0);
6530 /* backup errno before the following unlinkat() alters it */
6532 (void) unlinkat(newdirfd
, newpath
, 0);
6540 static char *strcpy_backslash_escaped(char *t
, const char *s
, const char *bad
) {
6544 if (*s
== '\\' || strchr(bad
, *s
))
6553 char *shell_escape(const char *s
, const char *bad
) {
6556 r
= new(char, strlen(s
)*2+1);
6560 t
= strcpy_backslash_escaped(r
, s
, bad
);
6566 char *shell_maybe_quote(const char *s
) {
6572 /* Encloses a string in double quotes if necessary to make it
6573 * OK as shell string. */
6575 for (p
= s
; *p
; p
++)
6578 strchr(SHELL_NEED_QUOTES
, *p
))
6584 r
= new(char, 1+strlen(s
)*2+1+1);
6590 t
= mempcpy(t
, s
, p
- s
);
6592 t
= strcpy_backslash_escaped(t
, p
, SHELL_NEED_ESCAPE
);
6600 int parse_mode(const char *s
, mode_t
*ret
) {
6608 l
= strtol(s
, &x
, 8);
6612 if (!x
|| x
== s
|| *x
)
6614 if (l
< 0 || l
> 07777)
6621 int mount_move_root(const char *path
) {
6624 if (chdir(path
) < 0)
6627 if (mount(path
, "/", NULL
, MS_MOVE
, NULL
) < 0)
6630 if (chroot(".") < 0)
6639 int reset_uid_gid(void) {
6641 if (setgroups(0, NULL
) < 0)
6644 if (setresgid(0, 0, 0) < 0)
6647 if (setresuid(0, 0, 0) < 0)
6653 int getxattr_malloc(const char *path
, const char *name
, char **value
, bool allow_symlink
) {
6662 for (l
= 100; ; l
= (size_t) n
+ 1) {
6668 n
= lgetxattr(path
, name
, v
, l
);
6670 n
= getxattr(path
, name
, v
, l
);
6672 if (n
>= 0 && (size_t) n
< l
) {
6679 if (n
< 0 && errno
!= ERANGE
)
6683 n
= lgetxattr(path
, name
, NULL
, 0);
6685 n
= getxattr(path
, name
, NULL
, 0);
6691 int fgetxattr_malloc(int fd
, const char *name
, char **value
) {
6700 for (l
= 100; ; l
= (size_t) n
+ 1) {
6705 n
= fgetxattr(fd
, name
, v
, l
);
6707 if (n
>= 0 && (size_t) n
< l
) {
6714 if (n
< 0 && errno
!= ERANGE
)
6717 n
= fgetxattr(fd
, name
, NULL
, 0);