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 bool uid_is_valid(uid_t uid
) {
378 /* Some libc APIs use UID_INVALID as special placeholder */
379 if (uid
== (uid_t
) 0xFFFFFFFF)
382 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
383 if (uid
== (uid_t
) 0xFFFF)
389 int parse_uid(const char *s
, uid_t
* ret_uid
) {
390 unsigned long ul
= 0;
396 r
= safe_atolu(s
, &ul
);
402 if ((unsigned long) uid
!= ul
)
405 if (!uid_is_valid(uid
))
406 return -ENXIO
; /* we return ENXIO instead of EINVAL
407 * here, to make it easy to distuingish
408 * invalid numeric uids invalid
417 int safe_atou(const char *s
, unsigned *ret_u
) {
425 l
= strtoul(s
, &x
, 0);
427 if (!x
|| x
== s
|| *x
|| errno
)
428 return errno
> 0 ? -errno
: -EINVAL
;
430 if ((unsigned long) (unsigned) l
!= l
)
433 *ret_u
= (unsigned) l
;
437 int safe_atoi(const char *s
, int *ret_i
) {
445 l
= strtol(s
, &x
, 0);
447 if (!x
|| x
== s
|| *x
|| errno
)
448 return errno
> 0 ? -errno
: -EINVAL
;
450 if ((long) (int) l
!= l
)
457 int safe_atou8(const char *s
, uint8_t *ret
) {
465 l
= strtoul(s
, &x
, 0);
467 if (!x
|| x
== s
|| *x
|| errno
)
468 return errno
> 0 ? -errno
: -EINVAL
;
470 if ((unsigned long) (uint8_t) l
!= l
)
477 int safe_atou16(const char *s
, uint16_t *ret
) {
485 l
= strtoul(s
, &x
, 0);
487 if (!x
|| x
== s
|| *x
|| errno
)
488 return errno
> 0 ? -errno
: -EINVAL
;
490 if ((unsigned long) (uint16_t) l
!= l
)
497 int safe_atoi16(const char *s
, int16_t *ret
) {
505 l
= strtol(s
, &x
, 0);
507 if (!x
|| x
== s
|| *x
|| errno
)
508 return errno
> 0 ? -errno
: -EINVAL
;
510 if ((long) (int16_t) l
!= l
)
517 int safe_atollu(const char *s
, long long unsigned *ret_llu
) {
519 unsigned long long l
;
525 l
= strtoull(s
, &x
, 0);
527 if (!x
|| x
== s
|| *x
|| errno
)
528 return errno
? -errno
: -EINVAL
;
534 int safe_atolli(const char *s
, long long int *ret_lli
) {
542 l
= strtoll(s
, &x
, 0);
544 if (!x
|| x
== s
|| *x
|| errno
)
545 return errno
? -errno
: -EINVAL
;
551 int safe_atod(const char *s
, double *ret_d
) {
559 loc
= newlocale(LC_NUMERIC_MASK
, "C", (locale_t
) 0);
560 if (loc
== (locale_t
) 0)
564 d
= strtod_l(s
, &x
, loc
);
566 if (!x
|| x
== s
|| *x
|| errno
) {
568 return errno
? -errno
: -EINVAL
;
576 static size_t strcspn_escaped(const char *s
, const char *reject
) {
577 bool escaped
= false;
580 for (n
=0; s
[n
]; n
++) {
583 else if (s
[n
] == '\\')
585 else if (strchr(reject
, s
[n
]))
589 /* if s ends in \, return index of previous char */
593 /* Split a string into words. */
594 const char* split(const char **state
, size_t *l
, const char *separator
, bool quoted
) {
600 assert(**state
== '\0');
604 current
+= strspn(current
, separator
);
610 if (quoted
&& strchr("\'\"", *current
)) {
611 char quotechars
[2] = {*current
, '\0'};
613 *l
= strcspn_escaped(current
+ 1, quotechars
);
614 if (current
[*l
+ 1] == '\0' || current
[*l
+ 1] != quotechars
[0] ||
615 (current
[*l
+ 2] && !strchr(separator
, current
[*l
+ 2]))) {
616 /* right quote missing or garbage at the end */
620 *state
= current
++ + *l
+ 2;
622 *l
= strcspn_escaped(current
, separator
);
623 if (current
[*l
] && !strchr(separator
, current
[*l
])) {
624 /* unfinished escape */
628 *state
= current
+ *l
;
630 *l
= strcspn(current
, separator
);
631 *state
= current
+ *l
;
637 int fchmod_umask(int fd
, mode_t m
) {
642 r
= fchmod(fd
, m
& (~u
)) < 0 ? -errno
: 0;
648 char *truncate_nl(char *s
) {
651 s
[strcspn(s
, NEWLINE
)] = 0;
655 char *strnappend(const char *s
, const char *suffix
, size_t b
) {
663 return strndup(suffix
, b
);
672 if (b
> ((size_t) -1) - a
)
675 r
= new(char, a
+b
+1);
680 memcpy(r
+a
, suffix
, b
);
686 char *strappend(const char *s
, const char *suffix
) {
687 return strnappend(s
, suffix
, suffix
? strlen(suffix
) : 0);
690 int readlinkat_malloc(int fd
, const char *p
, char **ret
) {
705 n
= readlinkat(fd
, p
, c
, l
-1);
712 if ((size_t) n
< l
-1) {
723 int readlink_malloc(const char *p
, char **ret
) {
724 return readlinkat_malloc(AT_FDCWD
, p
, ret
);
727 int readlink_value(const char *p
, char **ret
) {
728 _cleanup_free_
char *link
= NULL
;
732 r
= readlink_malloc(p
, &link
);
736 value
= basename(link
);
740 value
= strdup(value
);
749 int readlink_and_make_absolute(const char *p
, char **r
) {
750 _cleanup_free_
char *target
= NULL
;
757 j
= readlink_malloc(p
, &target
);
761 k
= file_in_same_dir(p
, target
);
769 int readlink_and_canonicalize(const char *p
, char **r
) {
776 j
= readlink_and_make_absolute(p
, &t
);
780 s
= canonicalize_file_name(t
);
787 path_kill_slashes(*r
);
792 char *strstrip(char *s
) {
795 /* Drops trailing whitespace. Modifies the string in
796 * place. Returns pointer to first non-space character */
798 s
+= strspn(s
, WHITESPACE
);
800 for (e
= strchr(s
, 0); e
> s
; e
--)
801 if (!strchr(WHITESPACE
, e
[-1]))
809 char *delete_chars(char *s
, const char *bad
) {
812 /* Drops all whitespace, regardless where in the string */
814 for (f
= s
, t
= s
; *f
; f
++) {
826 char *file_in_same_dir(const char *path
, const char *filename
) {
833 /* This removes the last component of path and appends
834 * filename, unless the latter is absolute anyway or the
837 if (path_is_absolute(filename
))
838 return strdup(filename
);
840 e
= strrchr(path
, '/');
842 return strdup(filename
);
844 k
= strlen(filename
);
845 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
849 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
853 int rmdir_parents(const char *path
, const char *stop
) {
862 /* Skip trailing slashes */
863 while (l
> 0 && path
[l
-1] == '/')
869 /* Skip last component */
870 while (l
> 0 && path
[l
-1] != '/')
873 /* Skip trailing slashes */
874 while (l
> 0 && path
[l
-1] == '/')
880 if (!(t
= strndup(path
, l
)))
883 if (path_startswith(stop
, t
)) {
899 char hexchar(int x
) {
900 static const char table
[16] = "0123456789abcdef";
902 return table
[x
& 15];
905 int unhexchar(char c
) {
907 if (c
>= '0' && c
<= '9')
910 if (c
>= 'a' && c
<= 'f')
913 if (c
>= 'A' && c
<= 'F')
919 char *hexmem(const void *p
, size_t l
) {
923 z
= r
= malloc(l
* 2 + 1);
927 for (x
= p
; x
< (const uint8_t*) p
+ l
; x
++) {
928 *(z
++) = hexchar(*x
>> 4);
929 *(z
++) = hexchar(*x
& 15);
936 int unhexmem(const char *p
, size_t l
, void **mem
, size_t *len
) {
937 _cleanup_free_
uint8_t *r
= NULL
;
945 z
= r
= malloc((l
+ 1) / 2 + 1);
949 for (x
= p
; x
< p
+ l
; x
+= 2) {
955 else if (x
+1 < p
+ l
) {
962 *(z
++) = (uint8_t) a
<< 4 | (uint8_t) b
;
974 /* https://tools.ietf.org/html/rfc4648#section-6
975 * Notice that base32hex differs from base32 in the alphabet it uses.
976 * The distinction is that the base32hex representation preserves the
977 * order of the underlying data when compared as bytestrings, this is
978 * useful when representing NSEC3 hashes, as one can then verify the
979 * order of hashes directly from their representation. */
980 char base32hexchar(int x
) {
981 static const char table
[32] = "0123456789"
982 "ABCDEFGHIJKLMNOPQRSTUV";
984 return table
[x
& 31];
987 int unbase32hexchar(char c
) {
990 if (c
>= '0' && c
<= '9')
993 offset
= '9' - '0' + 1;
995 if (c
>= 'A' && c
<= 'V')
996 return c
- 'A' + offset
;
1001 char *base32hexmem(const void *p
, size_t l
, bool padding
) {
1007 /* five input bytes makes eight output bytes, padding is added so we must round up */
1008 len
= 8 * (l
+ 4) / 5;
1010 /* same, but round down as there is no padding */
1029 z
= r
= malloc(len
+ 1);
1033 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 5) * 5; x
+= 5) {
1034 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ
1035 x[3] == QQQQQQQQ; x[4] == WWWWWWWW */
1036 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1037 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1038 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1039 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1040 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
1041 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
1042 *(z
++) = base32hexchar((x
[3] & 3) << 3 | x
[4] >> 5); /* 000QQWWW */
1043 *(z
++) = base32hexchar((x
[4] & 31)); /* 000WWWWW */
1048 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1049 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1050 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1051 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1052 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
1053 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
1054 *(z
++) = base32hexchar((x
[3] & 3) << 3); /* 000QQ000 */
1061 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1062 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1063 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1064 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1065 *(z
++) = base32hexchar((x
[2] & 15) << 1); /* 000ZZZZ0 */
1075 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1076 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1077 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1078 *(z
++) = base32hexchar((x
[1] & 1) << 4); /* 000Y0000 */
1089 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1090 *(z
++) = base32hexchar((x
[0] & 7) << 2); /* 000XXX00 */
1107 int unbase32hexmem(const char *p
, size_t l
, bool padding
, void **mem
, size_t *_len
) {
1108 _cleanup_free_
uint8_t *r
= NULL
;
1109 int a
, b
, c
, d
, e
, f
, g
, h
;
1117 /* padding ensures any base32hex input has input divisible by 8 */
1118 if (padding
&& l
% 8 != 0)
1122 /* strip the padding */
1123 while (l
> 0 && p
[l
- 1] == '=' && pad
< 7) {
1129 /* a group of eight input bytes needs five output bytes, in case of
1130 padding we need to add some extra bytes */
1152 z
= r
= malloc(len
+ 1);
1156 for (x
= p
; x
< p
+ (l
/ 8) * 8; x
+= 8) {
1157 /* a == 000XXXXX; b == 000YYYYY; c == 000ZZZZZ; d == 000WWWWW
1158 e == 000SSSSS; f == 000QQQQQ; g == 000VVVVV; h == 000RRRRR */
1159 a
= unbase32hexchar(x
[0]);
1163 b
= unbase32hexchar(x
[1]);
1167 c
= unbase32hexchar(x
[2]);
1171 d
= unbase32hexchar(x
[3]);
1175 e
= unbase32hexchar(x
[4]);
1179 f
= unbase32hexchar(x
[5]);
1183 g
= unbase32hexchar(x
[6]);
1187 h
= unbase32hexchar(x
[7]);
1191 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1192 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1193 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1194 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
1195 *(z
++) = (uint8_t) g
<< 5 | (uint8_t) h
; /* VVVRRRRR */
1200 a
= unbase32hexchar(x
[0]);
1204 b
= unbase32hexchar(x
[1]);
1208 c
= unbase32hexchar(x
[2]);
1212 d
= unbase32hexchar(x
[3]);
1216 e
= unbase32hexchar(x
[4]);
1220 f
= unbase32hexchar(x
[5]);
1224 g
= unbase32hexchar(x
[6]);
1232 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1233 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1234 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1235 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
1239 a
= unbase32hexchar(x
[0]);
1243 b
= unbase32hexchar(x
[1]);
1247 c
= unbase32hexchar(x
[2]);
1251 d
= unbase32hexchar(x
[3]);
1255 e
= unbase32hexchar(x
[4]);
1263 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1264 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1265 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1269 a
= unbase32hexchar(x
[0]);
1273 b
= unbase32hexchar(x
[1]);
1277 c
= unbase32hexchar(x
[2]);
1281 d
= unbase32hexchar(x
[3]);
1289 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1290 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1294 a
= unbase32hexchar(x
[0]);
1298 b
= unbase32hexchar(x
[1]);
1306 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1324 /* https://tools.ietf.org/html/rfc4648#section-4 */
1325 char base64char(int x
) {
1326 static const char table
[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1327 "abcdefghijklmnopqrstuvwxyz"
1329 return table
[x
& 63];
1332 int unbase64char(char c
) {
1335 if (c
>= 'A' && c
<= 'Z')
1338 offset
= 'Z' - 'A' + 1;
1340 if (c
>= 'a' && c
<= 'z')
1341 return c
- 'a' + offset
;
1343 offset
+= 'z' - 'a' + 1;
1345 if (c
>= '0' && c
<= '9')
1346 return c
- '0' + offset
;
1348 offset
+= '9' - '0' + 1;
1361 char *base64mem(const void *p
, size_t l
) {
1365 /* three input bytes makes four output bytes, padding is added so we must round up */
1366 z
= r
= malloc(4 * (l
+ 2) / 3 + 1);
1370 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 3) * 3; x
+= 3) {
1371 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ */
1372 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1373 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1374 *(z
++) = base64char((x
[1] & 15) << 2 | x
[2] >> 6); /* 00YYYYZZ */
1375 *(z
++) = base64char(x
[2] & 63); /* 00ZZZZZZ */
1380 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1381 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1382 *(z
++) = base64char((x
[1] & 15) << 2); /* 00YYYY00 */
1387 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1388 *(z
++) = base64char((x
[0] & 3) << 4); /* 00XX0000 */
1399 int unbase64mem(const char *p
, size_t l
, void **mem
, size_t *_len
) {
1400 _cleanup_free_
uint8_t *r
= NULL
;
1408 /* padding ensures any base63 input has input divisible by 4 */
1412 /* strip the padding */
1413 if (l
> 0 && p
[l
- 1] == '=')
1415 if (l
> 0 && p
[l
- 1] == '=')
1418 /* a group of four input bytes needs three output bytes, in case of
1419 padding we need to add two or three extra bytes */
1420 len
= (l
/ 4) * 3 + (l
% 4 ? (l
% 4) - 1 : 0);
1422 z
= r
= malloc(len
+ 1);
1426 for (x
= p
; x
< p
+ (l
/ 4) * 4; x
+= 4) {
1427 /* a == 00XXXXXX; b == 00YYYYYY; c == 00ZZZZZZ; d == 00WWWWWW */
1428 a
= unbase64char(x
[0]);
1432 b
= unbase64char(x
[1]);
1436 c
= unbase64char(x
[2]);
1440 d
= unbase64char(x
[3]);
1444 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1445 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1446 *(z
++) = (uint8_t) c
<< 6 | (uint8_t) d
; /* ZZWWWWWW */
1451 a
= unbase64char(x
[0]);
1455 b
= unbase64char(x
[1]);
1459 c
= unbase64char(x
[2]);
1467 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1468 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1472 a
= unbase64char(x
[0]);
1476 b
= unbase64char(x
[1]);
1484 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) (b
>> 4); /* XXXXXXYY */
1503 char octchar(int x
) {
1504 return '0' + (x
& 7);
1507 int unoctchar(char c
) {
1509 if (c
>= '0' && c
<= '7')
1515 char decchar(int x
) {
1516 return '0' + (x
% 10);
1519 int undecchar(char c
) {
1521 if (c
>= '0' && c
<= '9')
1527 char *cescape(const char *s
) {
1533 /* Does C style string escaping. May be reversed with
1536 r
= new(char, strlen(s
)*4 + 1);
1540 for (f
= s
, t
= r
; *f
; f
++)
1541 t
+= cescape_char(*f
, t
);
1548 static int cunescape_one(const char *p
, size_t length
, char *ret
, uint32_t *ret_unicode
) {
1555 /* Unescapes C style. Returns the unescaped character in ret,
1556 * unless we encountered a \u sequence in which case the full
1557 * unicode character is returned in ret_unicode, instead. */
1559 if (length
!= (size_t) -1 && length
< 1)
1596 /* This is an extension of the XDG syntax files */
1601 /* hexadecimal encoding */
1604 if (length
!= (size_t) -1 && length
< 3)
1607 a
= unhexchar(p
[1]);
1611 b
= unhexchar(p
[2]);
1615 /* Don't allow NUL bytes */
1616 if (a
== 0 && b
== 0)
1619 *ret
= (char) ((a
<< 4U) | b
);
1625 /* C++11 style 16bit unicode */
1631 if (length
!= (size_t) -1 && length
< 5)
1634 for (i
= 0; i
< 4; i
++) {
1635 a
[i
] = unhexchar(p
[1 + i
]);
1640 c
= ((uint32_t) a
[0] << 12U) | ((uint32_t) a
[1] << 8U) | ((uint32_t) a
[2] << 4U) | (uint32_t) a
[3];
1642 /* Don't allow 0 chars */
1661 /* C++11 style 32bit unicode */
1667 if (length
!= (size_t) -1 && length
< 9)
1670 for (i
= 0; i
< 8; i
++) {
1671 a
[i
] = unhexchar(p
[1 + i
]);
1676 c
= ((uint32_t) a
[0] << 28U) | ((uint32_t) a
[1] << 24U) | ((uint32_t) a
[2] << 20U) | ((uint32_t) a
[3] << 16U) |
1677 ((uint32_t) a
[4] << 12U) | ((uint32_t) a
[5] << 8U) | ((uint32_t) a
[6] << 4U) | (uint32_t) a
[7];
1679 /* Don't allow 0 chars */
1683 /* Don't allow invalid code points */
1684 if (!unichar_is_valid(c
))
1709 /* octal encoding */
1713 if (length
!= (size_t) -1 && length
< 3)
1716 a
= unoctchar(p
[0]);
1720 b
= unoctchar(p
[1]);
1724 c
= unoctchar(p
[2]);
1728 /* don't allow NUL bytes */
1729 if (a
== 0 && b
== 0 && c
== 0)
1732 /* Don't allow bytes above 255 */
1733 m
= ((uint32_t) a
<< 6U) | ((uint32_t) b
<< 3U) | (uint32_t) c
;
1749 int cunescape_length_with_prefix(const char *s
, size_t length
, const char *prefix
, UnescapeFlags flags
, char **ret
) {
1757 /* Undoes C style string escaping, and optionally prefixes it. */
1759 pl
= prefix
? strlen(prefix
) : 0;
1761 r
= new(char, pl
+length
+1);
1766 memcpy(r
, prefix
, pl
);
1768 for (f
= s
, t
= r
+ pl
; f
< s
+ length
; f
++) {
1774 remaining
= s
+ length
- f
;
1775 assert(remaining
> 0);
1778 /* A literal literal, copy verbatim */
1783 if (remaining
== 1) {
1784 if (flags
& UNESCAPE_RELAX
) {
1785 /* A trailing backslash, copy verbatim */
1794 k
= cunescape_one(f
+ 1, remaining
- 1, &c
, &u
);
1796 if (flags
& UNESCAPE_RELAX
) {
1797 /* Invalid escape code, let's take it literal then */
1807 /* Non-Unicode? Let's encode this directly */
1810 /* Unicode? Then let's encode this in UTF-8 */
1811 t
+= utf8_encode_unichar(t
, u
);
1822 int cunescape_length(const char *s
, size_t length
, UnescapeFlags flags
, char **ret
) {
1823 return cunescape_length_with_prefix(s
, length
, NULL
, flags
, ret
);
1826 int cunescape(const char *s
, UnescapeFlags flags
, char **ret
) {
1827 return cunescape_length(s
, strlen(s
), flags
, ret
);
1830 char *xescape(const char *s
, const char *bad
) {
1834 /* Escapes all chars in bad, in addition to \ and all special
1835 * chars, in \xFF style escaping. May be reversed with
1838 r
= new(char, strlen(s
) * 4 + 1);
1842 for (f
= s
, t
= r
; *f
; f
++) {
1844 if ((*f
< ' ') || (*f
>= 127) ||
1845 (*f
== '\\') || strchr(bad
, *f
)) {
1848 *(t
++) = hexchar(*f
>> 4);
1849 *(t
++) = hexchar(*f
);
1859 char *ascii_strlower(char *t
) {
1864 for (p
= t
; *p
; p
++)
1865 if (*p
>= 'A' && *p
<= 'Z')
1866 *p
= *p
- 'A' + 'a';
1871 _pure_
static bool hidden_file_allow_backup(const char *filename
) {
1875 filename
[0] == '.' ||
1876 streq(filename
, "lost+found") ||
1877 streq(filename
, "aquota.user") ||
1878 streq(filename
, "aquota.group") ||
1879 endswith(filename
, ".rpmnew") ||
1880 endswith(filename
, ".rpmsave") ||
1881 endswith(filename
, ".rpmorig") ||
1882 endswith(filename
, ".dpkg-old") ||
1883 endswith(filename
, ".dpkg-new") ||
1884 endswith(filename
, ".dpkg-tmp") ||
1885 endswith(filename
, ".dpkg-dist") ||
1886 endswith(filename
, ".dpkg-bak") ||
1887 endswith(filename
, ".dpkg-backup") ||
1888 endswith(filename
, ".dpkg-remove") ||
1889 endswith(filename
, ".swp");
1892 bool hidden_file(const char *filename
) {
1895 if (endswith(filename
, "~"))
1898 return hidden_file_allow_backup(filename
);
1901 int fd_nonblock(int fd
, bool nonblock
) {
1906 flags
= fcntl(fd
, F_GETFL
, 0);
1911 nflags
= flags
| O_NONBLOCK
;
1913 nflags
= flags
& ~O_NONBLOCK
;
1915 if (nflags
== flags
)
1918 if (fcntl(fd
, F_SETFL
, nflags
) < 0)
1924 int fd_cloexec(int fd
, bool cloexec
) {
1929 flags
= fcntl(fd
, F_GETFD
, 0);
1934 nflags
= flags
| FD_CLOEXEC
;
1936 nflags
= flags
& ~FD_CLOEXEC
;
1938 if (nflags
== flags
)
1941 if (fcntl(fd
, F_SETFD
, nflags
) < 0)
1947 _pure_
static bool fd_in_set(int fd
, const int fdset
[], unsigned n_fdset
) {
1950 assert(n_fdset
== 0 || fdset
);
1952 for (i
= 0; i
< n_fdset
; i
++)
1959 int close_all_fds(const int except
[], unsigned n_except
) {
1960 _cleanup_closedir_
DIR *d
= NULL
;
1964 assert(n_except
== 0 || except
);
1966 d
= opendir("/proc/self/fd");
1971 /* When /proc isn't available (for example in chroots)
1972 * the fallback is brute forcing through the fd
1975 assert_se(getrlimit(RLIMIT_NOFILE
, &rl
) >= 0);
1976 for (fd
= 3; fd
< (int) rl
.rlim_max
; fd
++) {
1978 if (fd_in_set(fd
, except
, n_except
))
1981 if (close_nointr(fd
) < 0)
1982 if (errno
!= EBADF
&& r
== 0)
1989 while ((de
= readdir(d
))) {
1992 if (hidden_file(de
->d_name
))
1995 if (safe_atoi(de
->d_name
, &fd
) < 0)
1996 /* Let's better ignore this, just in case */
2005 if (fd_in_set(fd
, except
, n_except
))
2008 if (close_nointr(fd
) < 0) {
2009 /* Valgrind has its own FD and doesn't want to have it closed */
2010 if (errno
!= EBADF
&& r
== 0)
2018 bool chars_intersect(const char *a
, const char *b
) {
2021 /* Returns true if any of the chars in a are in b. */
2022 for (p
= a
; *p
; p
++)
2029 bool fstype_is_network(const char *fstype
) {
2030 static const char table
[] =
2045 x
= startswith(fstype
, "fuse.");
2049 return nulstr_contains(table
, fstype
);
2052 int flush_fd(int fd
) {
2053 struct pollfd pollfd
= {
2063 r
= poll(&pollfd
, 1, 0);
2073 l
= read(fd
, buf
, sizeof(buf
));
2079 if (errno
== EAGAIN
)
2088 void safe_close_pair(int p
[]) {
2092 /* Special case pairs which use the same fd in both
2094 p
[0] = p
[1] = safe_close(p
[0]);
2098 p
[0] = safe_close(p
[0]);
2099 p
[1] = safe_close(p
[1]);
2102 ssize_t
loop_read(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2109 while (nbytes
> 0) {
2112 k
= read(fd
, p
, nbytes
);
2117 if (errno
== EAGAIN
&& do_poll
) {
2119 /* We knowingly ignore any return value here,
2120 * and expect that any error/EOF is reported
2123 fd_wait_for_event(fd
, POLLIN
, USEC_INFINITY
);
2127 return n
> 0 ? n
: -errno
;
2141 int loop_read_exact(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2144 n
= loop_read(fd
, buf
, nbytes
, do_poll
);
2147 if ((size_t) n
!= nbytes
)
2152 int loop_write(int fd
, const void *buf
, size_t nbytes
, bool do_poll
) {
2153 const uint8_t *p
= buf
;
2163 k
= write(fd
, p
, nbytes
);
2168 if (errno
== EAGAIN
&& do_poll
) {
2169 /* We knowingly ignore any return value here,
2170 * and expect that any error/EOF is reported
2173 fd_wait_for_event(fd
, POLLOUT
, USEC_INFINITY
);
2180 if (nbytes
> 0 && k
== 0) /* Can't really happen */
2185 } while (nbytes
> 0);
2190 int parse_size(const char *t
, off_t base
, off_t
*size
) {
2192 /* Soo, sometimes we want to parse IEC binary suffixes, and
2193 * sometimes SI decimal suffixes. This function can parse
2194 * both. Which one is the right way depends on the
2195 * context. Wikipedia suggests that SI is customary for
2196 * hardware metrics and network speeds, while IEC is
2197 * customary for most data sizes used by software and volatile
2198 * (RAM) memory. Hence be careful which one you pick!
2200 * In either case we use just K, M, G as suffix, and not Ki,
2201 * Mi, Gi or so (as IEC would suggest). That's because that's
2202 * frickin' ugly. But this means you really need to make sure
2203 * to document which base you are parsing when you use this
2208 unsigned long long factor
;
2211 static const struct table iec
[] = {
2212 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2213 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2214 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2215 { "G", 1024ULL*1024ULL*1024ULL },
2216 { "M", 1024ULL*1024ULL },
2222 static const struct table si
[] = {
2223 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2224 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2225 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2226 { "G", 1000ULL*1000ULL*1000ULL },
2227 { "M", 1000ULL*1000ULL },
2233 const struct table
*table
;
2235 unsigned long long r
= 0;
2236 unsigned n_entries
, start_pos
= 0;
2239 assert(base
== 1000 || base
== 1024);
2244 n_entries
= ELEMENTSOF(si
);
2247 n_entries
= ELEMENTSOF(iec
);
2253 unsigned long long l2
;
2259 l
= strtoll(p
, &e
, 10);
2272 if (*e
>= '0' && *e
<= '9') {
2275 /* strotoull itself would accept space/+/- */
2276 l2
= strtoull(e
, &e2
, 10);
2278 if (errno
== ERANGE
)
2281 /* Ignore failure. E.g. 10.M is valid */
2288 e
+= strspn(e
, WHITESPACE
);
2290 for (i
= start_pos
; i
< n_entries
; i
++)
2291 if (startswith(e
, table
[i
].suffix
)) {
2292 unsigned long long tmp
;
2293 if ((unsigned long long) l
+ (frac
> 0) > ULLONG_MAX
/ table
[i
].factor
)
2295 tmp
= l
* table
[i
].factor
+ (unsigned long long) (frac
* table
[i
].factor
);
2296 if (tmp
> ULLONG_MAX
- r
)
2300 if ((unsigned long long) (off_t
) r
!= r
)
2303 p
= e
+ strlen(table
[i
].suffix
);
2319 bool is_device_path(const char *path
) {
2321 /* Returns true on paths that refer to a device, either in
2322 * sysfs or in /dev */
2325 path_startswith(path
, "/dev/") ||
2326 path_startswith(path
, "/sys/");
2329 int dir_is_empty(const char *path
) {
2330 _cleanup_closedir_
DIR *d
;
2341 if (!de
&& errno
!= 0)
2347 if (!hidden_file(de
->d_name
))
2352 char* dirname_malloc(const char *path
) {
2353 char *d
, *dir
, *dir2
;
2370 void rename_process(const char name
[8]) {
2373 /* This is a like a poor man's setproctitle(). It changes the
2374 * comm field, argv[0], and also the glibc's internally used
2375 * name of the process. For the first one a limit of 16 chars
2376 * applies, to the second one usually one of 10 (i.e. length
2377 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2378 * "systemd"). If you pass a longer string it will be
2381 prctl(PR_SET_NAME
, name
);
2383 if (program_invocation_name
)
2384 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
2386 if (saved_argc
> 0) {
2390 strncpy(saved_argv
[0], name
, strlen(saved_argv
[0]));
2392 for (i
= 1; i
< saved_argc
; i
++) {
2396 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
2401 char *lookup_uid(uid_t uid
) {
2404 _cleanup_free_
char *buf
= NULL
;
2405 struct passwd pwbuf
, *pw
= NULL
;
2407 /* Shortcut things to avoid NSS lookups */
2409 return strdup("root");
2411 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
2415 buf
= malloc(bufsize
);
2419 if (getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
) == 0 && pw
)
2420 return strdup(pw
->pw_name
);
2422 if (asprintf(&name
, UID_FMT
, uid
) < 0)
2428 char* getlogname_malloc(void) {
2432 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
2437 return lookup_uid(uid
);
2440 char *getusername_malloc(void) {
2447 return lookup_uid(getuid());
2450 bool is_temporary_fs(const struct statfs
*s
) {
2453 return F_TYPE_EQUAL(s
->f_type
, TMPFS_MAGIC
) ||
2454 F_TYPE_EQUAL(s
->f_type
, RAMFS_MAGIC
);
2457 int fd_is_temporary_fs(int fd
) {
2460 if (fstatfs(fd
, &s
) < 0)
2463 return is_temporary_fs(&s
);
2466 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
2469 /* Under the assumption that we are running privileged we
2470 * first change the access mode and only then hand out
2471 * ownership to avoid a window where access is too open. */
2473 if (mode
!= MODE_INVALID
)
2474 if (chmod(path
, mode
) < 0)
2477 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
2478 if (chown(path
, uid
, gid
) < 0)
2484 int fchmod_and_fchown(int fd
, mode_t mode
, uid_t uid
, gid_t gid
) {
2487 /* Under the assumption that we are running privileged we
2488 * first change the access mode and only then hand out
2489 * ownership to avoid a window where access is too open. */
2491 if (mode
!= MODE_INVALID
)
2492 if (fchmod(fd
, mode
) < 0)
2495 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
2496 if (fchown(fd
, uid
, gid
) < 0)
2502 cpu_set_t
* cpu_set_malloc(unsigned *ncpus
) {
2506 /* Allocates the cpuset in the right size */
2509 if (!(r
= CPU_ALLOC(n
)))
2512 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n
), r
) >= 0) {
2513 CPU_ZERO_S(CPU_ALLOC_SIZE(n
), r
);
2523 if (errno
!= EINVAL
)
2530 int files_same(const char *filea
, const char *fileb
) {
2533 if (stat(filea
, &a
) < 0)
2536 if (stat(fileb
, &b
) < 0)
2539 return a
.st_dev
== b
.st_dev
&&
2540 a
.st_ino
== b
.st_ino
;
2543 int running_in_chroot(void) {
2546 ret
= files_same("/proc/1/root", "/");
2553 static char *ascii_ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
2558 assert(percent
<= 100);
2559 assert(new_length
>= 3);
2561 if (old_length
<= 3 || old_length
<= new_length
)
2562 return strndup(s
, old_length
);
2564 r
= new0(char, new_length
+1);
2568 x
= (new_length
* percent
) / 100;
2570 if (x
> new_length
- 3)
2578 s
+ old_length
- (new_length
- x
- 3),
2579 new_length
- x
- 3);
2584 char *ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
2588 unsigned k
, len
, len2
;
2591 assert(percent
<= 100);
2592 assert(new_length
>= 3);
2594 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2595 if (ascii_is_valid(s
))
2596 return ascii_ellipsize_mem(s
, old_length
, new_length
, percent
);
2598 if (old_length
<= 3 || old_length
<= new_length
)
2599 return strndup(s
, old_length
);
2601 x
= (new_length
* percent
) / 100;
2603 if (x
> new_length
- 3)
2607 for (i
= s
; k
< x
&& i
< s
+ old_length
; i
= utf8_next_char(i
)) {
2610 c
= utf8_encoded_to_unichar(i
);
2613 k
+= unichar_iswide(c
) ? 2 : 1;
2616 if (k
> x
) /* last character was wide and went over quota */
2619 for (j
= s
+ old_length
; k
< new_length
&& j
> i
; ) {
2622 j
= utf8_prev_char(j
);
2623 c
= utf8_encoded_to_unichar(j
);
2626 k
+= unichar_iswide(c
) ? 2 : 1;
2630 /* we don't actually need to ellipsize */
2632 return memdup(s
, old_length
+ 1);
2634 /* make space for ellipsis */
2635 j
= utf8_next_char(j
);
2638 len2
= s
+ old_length
- j
;
2639 e
= new(char, len
+ 3 + len2
+ 1);
2644 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2645 old_length, new_length, x, len, len2, k);
2649 e
[len
] = 0xe2; /* tri-dot ellipsis: … */
2653 memcpy(e
+ len
+ 3, j
, len2
+ 1);
2658 char *ellipsize(const char *s
, size_t length
, unsigned percent
) {
2659 return ellipsize_mem(s
, strlen(s
), length
, percent
);
2662 int touch_file(const char *path
, bool parents
, usec_t stamp
, uid_t uid
, gid_t gid
, mode_t mode
) {
2663 _cleanup_close_
int fd
;
2669 mkdir_parents(path
, 0755);
2671 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, mode
> 0 ? mode
: 0644);
2676 r
= fchmod(fd
, mode
);
2681 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
) {
2682 r
= fchown(fd
, uid
, gid
);
2687 if (stamp
!= USEC_INFINITY
) {
2688 struct timespec ts
[2];
2690 timespec_store(&ts
[0], stamp
);
2692 r
= futimens(fd
, ts
);
2694 r
= futimens(fd
, NULL
);
2701 int touch(const char *path
) {
2702 return touch_file(path
, false, USEC_INFINITY
, UID_INVALID
, GID_INVALID
, 0);
2705 static char *unquote(const char *s
, const char* quotes
) {
2709 /* This is rather stupid, simply removes the heading and
2710 * trailing quotes if there is one. Doesn't care about
2711 * escaping or anything.
2713 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2719 if (strchr(quotes
, s
[0]) && s
[l
-1] == s
[0])
2720 return strndup(s
+1, l
-2);
2725 noreturn
void freeze(void) {
2727 /* Make sure nobody waits for us on a socket anymore */
2728 close_all_fds(NULL
, 0);
2736 bool null_or_empty(struct stat
*st
) {
2739 if (S_ISREG(st
->st_mode
) && st
->st_size
<= 0)
2742 if (S_ISCHR(st
->st_mode
) || S_ISBLK(st
->st_mode
))
2748 int null_or_empty_path(const char *fn
) {
2753 if (stat(fn
, &st
) < 0)
2756 return null_or_empty(&st
);
2759 int null_or_empty_fd(int fd
) {
2764 if (fstat(fd
, &st
) < 0)
2767 return null_or_empty(&st
);
2770 DIR *xopendirat(int fd
, const char *name
, int flags
) {
2774 assert(!(flags
& O_CREAT
));
2776 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
2789 static char *tag_to_udev_node(const char *tagvalue
, const char *by
) {
2790 _cleanup_free_
char *t
= NULL
, *u
= NULL
;
2793 u
= unquote(tagvalue
, QUOTES
);
2797 enc_len
= strlen(u
) * 4 + 1;
2798 t
= new(char, enc_len
);
2802 if (encode_devnode_name(u
, t
, enc_len
) < 0)
2805 return strjoin("/dev/disk/by-", by
, "/", t
, NULL
);
2808 char *fstab_node_to_udev_node(const char *p
) {
2811 if (startswith(p
, "LABEL="))
2812 return tag_to_udev_node(p
+6, "label");
2814 if (startswith(p
, "UUID="))
2815 return tag_to_udev_node(p
+5, "uuid");
2817 if (startswith(p
, "PARTUUID="))
2818 return tag_to_udev_node(p
+9, "partuuid");
2820 if (startswith(p
, "PARTLABEL="))
2821 return tag_to_udev_node(p
+10, "partlabel");
2826 bool dirent_is_file(const struct dirent
*de
) {
2829 if (hidden_file(de
->d_name
))
2832 if (de
->d_type
!= DT_REG
&&
2833 de
->d_type
!= DT_LNK
&&
2834 de
->d_type
!= DT_UNKNOWN
)
2840 bool dirent_is_file_with_suffix(const struct dirent
*de
, const char *suffix
) {
2843 if (de
->d_type
!= DT_REG
&&
2844 de
->d_type
!= DT_LNK
&&
2845 de
->d_type
!= DT_UNKNOWN
)
2848 if (hidden_file_allow_backup(de
->d_name
))
2851 return endswith(de
->d_name
, suffix
);
2854 static int do_execute(char **directories
, usec_t timeout
, char *argv
[]) {
2855 _cleanup_hashmap_free_free_ Hashmap
*pids
= NULL
;
2856 _cleanup_set_free_free_ Set
*seen
= NULL
;
2859 /* We fork this all off from a child process so that we can
2860 * somewhat cleanly make use of SIGALRM to set a time limit */
2862 (void) reset_all_signal_handlers();
2863 (void) reset_signal_mask();
2865 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
2867 pids
= hashmap_new(NULL
);
2871 seen
= set_new(&string_hash_ops
);
2875 STRV_FOREACH(directory
, directories
) {
2876 _cleanup_closedir_
DIR *d
;
2879 d
= opendir(*directory
);
2881 if (errno
== ENOENT
)
2884 return log_error_errno(errno
, "Failed to open directory %s: %m", *directory
);
2887 FOREACH_DIRENT(de
, d
, break) {
2888 _cleanup_free_
char *path
= NULL
;
2892 if (!dirent_is_file(de
))
2895 if (set_contains(seen
, de
->d_name
)) {
2896 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory
, de
->d_name
);
2900 r
= set_put_strdup(seen
, de
->d_name
);
2904 path
= strjoin(*directory
, "/", de
->d_name
, NULL
);
2908 if (null_or_empty_path(path
)) {
2909 log_debug("%s is empty (a mask).", path
);
2915 log_error_errno(errno
, "Failed to fork: %m");
2917 } else if (pid
== 0) {
2920 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
2930 return log_error_errno(errno
, "Failed to execute %s: %m", path
);
2933 log_debug("Spawned %s as " PID_FMT
".", path
, pid
);
2935 r
= hashmap_put(pids
, UINT_TO_PTR(pid
), path
);
2942 /* Abort execution of this process after the timout. We simply
2943 * rely on SIGALRM as default action terminating the process,
2944 * and turn on alarm(). */
2946 if (timeout
!= USEC_INFINITY
)
2947 alarm((timeout
+ USEC_PER_SEC
- 1) / USEC_PER_SEC
);
2949 while (!hashmap_isempty(pids
)) {
2950 _cleanup_free_
char *path
= NULL
;
2953 pid
= PTR_TO_UINT(hashmap_first_key(pids
));
2956 path
= hashmap_remove(pids
, UINT_TO_PTR(pid
));
2959 wait_for_terminate_and_warn(path
, pid
, true);
2965 void execute_directories(const char* const* directories
, usec_t timeout
, char *argv
[]) {
2969 char **dirs
= (char**) directories
;
2971 assert(!strv_isempty(dirs
));
2973 name
= basename(dirs
[0]);
2974 assert(!isempty(name
));
2976 /* Executes all binaries in the directories in parallel and waits
2977 * for them to finish. Optionally a timeout is applied. If a file
2978 * with the same name exists in more than one directory, the
2979 * earliest one wins. */
2981 executor_pid
= fork();
2982 if (executor_pid
< 0) {
2983 log_error_errno(errno
, "Failed to fork: %m");
2986 } else if (executor_pid
== 0) {
2987 r
= do_execute(dirs
, timeout
, argv
);
2988 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
2991 wait_for_terminate_and_warn(name
, executor_pid
, true);
2994 bool nulstr_contains(const char*nulstr
, const char *needle
) {
3000 NULSTR_FOREACH(i
, nulstr
)
3001 if (streq(i
, needle
))
3007 bool plymouth_running(void) {
3008 return access("/run/plymouth/pid", F_OK
) >= 0;
3011 char* strshorten(char *s
, size_t l
) {
3020 int pipe_eof(int fd
) {
3021 struct pollfd pollfd
= {
3023 .events
= POLLIN
|POLLHUP
,
3028 r
= poll(&pollfd
, 1, 0);
3035 return pollfd
.revents
& POLLHUP
;
3038 int fd_wait_for_event(int fd
, int event
, usec_t t
) {
3040 struct pollfd pollfd
= {
3048 r
= ppoll(&pollfd
, 1, t
== USEC_INFINITY
? NULL
: timespec_store(&ts
, t
), NULL
);
3055 return pollfd
.revents
;
3058 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
3067 r
= tempfn_xxxxxx(path
, NULL
, &t
);
3071 fd
= mkostemp_safe(t
, O_WRONLY
|O_CLOEXEC
);
3077 f
= fdopen(fd
, "we");
3091 int symlink_atomic(const char *from
, const char *to
) {
3092 _cleanup_free_
char *t
= NULL
;
3098 r
= tempfn_random(to
, NULL
, &t
);
3102 if (symlink(from
, t
) < 0)
3105 if (rename(t
, to
) < 0) {
3113 int symlink_idempotent(const char *from
, const char *to
) {
3114 _cleanup_free_
char *p
= NULL
;
3120 if (symlink(from
, to
) < 0) {
3121 if (errno
!= EEXIST
)
3124 r
= readlink_malloc(to
, &p
);
3128 if (!streq(p
, from
))
3135 int mknod_atomic(const char *path
, mode_t mode
, dev_t dev
) {
3136 _cleanup_free_
char *t
= NULL
;
3141 r
= tempfn_random(path
, NULL
, &t
);
3145 if (mknod(t
, mode
, dev
) < 0)
3148 if (rename(t
, path
) < 0) {
3156 int mkfifo_atomic(const char *path
, mode_t mode
) {
3157 _cleanup_free_
char *t
= NULL
;
3162 r
= tempfn_random(path
, NULL
, &t
);
3166 if (mkfifo(t
, mode
) < 0)
3169 if (rename(t
, path
) < 0) {
3177 bool display_is_local(const char *display
) {
3181 display
[0] == ':' &&
3182 display
[1] >= '0' &&
3186 int socket_from_display(const char *display
, char **path
) {
3193 if (!display_is_local(display
))
3196 k
= strspn(display
+1, "0123456789");
3198 f
= new(char, strlen("/tmp/.X11-unix/X") + k
+ 1);
3202 c
= stpcpy(f
, "/tmp/.X11-unix/X");
3203 memcpy(c
, display
+1, k
);
3212 const char **username
,
3213 uid_t
*uid
, gid_t
*gid
,
3215 const char **shell
) {
3223 /* We enforce some special rules for uid=0: in order to avoid
3224 * NSS lookups for root we hardcode its data. */
3226 if (streq(*username
, "root") || streq(*username
, "0")) {
3244 if (parse_uid(*username
, &u
) >= 0) {
3248 /* If there are multiple users with the same id, make
3249 * sure to leave $USER to the configured value instead
3250 * of the first occurrence in the database. However if
3251 * the uid was configured by a numeric uid, then let's
3252 * pick the real username from /etc/passwd. */
3254 *username
= p
->pw_name
;
3257 p
= getpwnam(*username
);
3261 return errno
> 0 ? -errno
: -ESRCH
;
3273 *shell
= p
->pw_shell
;
3278 char* uid_to_name(uid_t uid
) {
3283 return strdup("root");
3287 return strdup(p
->pw_name
);
3289 if (asprintf(&r
, UID_FMT
, uid
) < 0)
3295 char* gid_to_name(gid_t gid
) {
3300 return strdup("root");
3304 return strdup(p
->gr_name
);
3306 if (asprintf(&r
, GID_FMT
, gid
) < 0)
3312 int get_group_creds(const char **groupname
, gid_t
*gid
) {
3318 /* We enforce some special rules for gid=0: in order to avoid
3319 * NSS lookups for root we hardcode its data. */
3321 if (streq(*groupname
, "root") || streq(*groupname
, "0")) {
3322 *groupname
= "root";
3330 if (parse_gid(*groupname
, &id
) >= 0) {
3335 *groupname
= g
->gr_name
;
3338 g
= getgrnam(*groupname
);
3342 return errno
> 0 ? -errno
: -ESRCH
;
3350 int in_gid(gid_t gid
) {
3352 int ngroups_max
, r
, i
;
3354 if (getgid() == gid
)
3357 if (getegid() == gid
)
3360 ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
3361 assert(ngroups_max
> 0);
3363 gids
= alloca(sizeof(gid_t
) * ngroups_max
);
3365 r
= getgroups(ngroups_max
, gids
);
3369 for (i
= 0; i
< r
; i
++)
3376 int in_group(const char *name
) {
3380 r
= get_group_creds(&name
, &gid
);
3387 int glob_exists(const char *path
) {
3388 _cleanup_globfree_ glob_t g
= {};
3394 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
3396 if (k
== GLOB_NOMATCH
)
3398 else if (k
== GLOB_NOSPACE
)
3401 return !strv_isempty(g
.gl_pathv
);
3403 return errno
? -errno
: -EIO
;
3406 int glob_extend(char ***strv
, const char *path
) {
3407 _cleanup_globfree_ glob_t g
= {};
3412 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
3414 if (k
== GLOB_NOMATCH
)
3416 else if (k
== GLOB_NOSPACE
)
3418 else if (k
!= 0 || strv_isempty(g
.gl_pathv
))
3419 return errno
? -errno
: -EIO
;
3421 STRV_FOREACH(p
, g
.gl_pathv
) {
3422 k
= strv_extend(strv
, *p
);
3430 int dirent_ensure_type(DIR *d
, struct dirent
*de
) {
3436 if (de
->d_type
!= DT_UNKNOWN
)
3439 if (fstatat(dirfd(d
), de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
3443 S_ISREG(st
.st_mode
) ? DT_REG
:
3444 S_ISDIR(st
.st_mode
) ? DT_DIR
:
3445 S_ISLNK(st
.st_mode
) ? DT_LNK
:
3446 S_ISFIFO(st
.st_mode
) ? DT_FIFO
:
3447 S_ISSOCK(st
.st_mode
) ? DT_SOCK
:
3448 S_ISCHR(st
.st_mode
) ? DT_CHR
:
3449 S_ISBLK(st
.st_mode
) ? DT_BLK
:
3455 int get_files_in_directory(const char *path
, char ***list
) {
3456 _cleanup_closedir_
DIR *d
= NULL
;
3457 size_t bufsize
= 0, n
= 0;
3458 _cleanup_strv_free_
char **l
= NULL
;
3462 /* Returns all files in a directory in *list, and the number
3463 * of files as return value. If list is NULL returns only the
3475 if (!de
&& errno
!= 0)
3480 dirent_ensure_type(d
, de
);
3482 if (!dirent_is_file(de
))
3486 /* one extra slot is needed for the terminating NULL */
3487 if (!GREEDY_REALLOC(l
, bufsize
, n
+ 2))
3490 l
[n
] = strdup(de
->d_name
);
3501 l
= NULL
; /* avoid freeing */
3507 char *strjoin(const char *x
, ...) {
3521 t
= va_arg(ap
, const char *);
3526 if (n
> ((size_t) -1) - l
) {
3550 t
= va_arg(ap
, const char *);
3564 bool is_main_thread(void) {
3565 static thread_local
int cached
= 0;
3567 if (_unlikely_(cached
== 0))
3568 cached
= getpid() == gettid() ? 1 : -1;
3573 int block_get_whole_disk(dev_t d
, dev_t
*ret
) {
3580 /* If it has a queue this is good enough for us */
3581 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", major(d
), minor(d
)) < 0)
3584 r
= access(p
, F_OK
);
3592 /* If it is a partition find the originating device */
3593 if (asprintf(&p
, "/sys/dev/block/%u:%u/partition", major(d
), minor(d
)) < 0)
3596 r
= access(p
, F_OK
);
3602 /* Get parent dev_t */
3603 if (asprintf(&p
, "/sys/dev/block/%u:%u/../dev", major(d
), minor(d
)) < 0)
3606 r
= read_one_line_file(p
, &s
);
3612 r
= sscanf(s
, "%u:%u", &m
, &n
);
3618 /* Only return this if it is really good enough for us. */
3619 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", m
, n
) < 0)
3622 r
= access(p
, F_OK
);
3626 *ret
= makedev(m
, n
);
3633 static const char *const ioprio_class_table
[] = {
3634 [IOPRIO_CLASS_NONE
] = "none",
3635 [IOPRIO_CLASS_RT
] = "realtime",
3636 [IOPRIO_CLASS_BE
] = "best-effort",
3637 [IOPRIO_CLASS_IDLE
] = "idle"
3640 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, INT_MAX
);
3642 static const char *const sigchld_code_table
[] = {
3643 [CLD_EXITED
] = "exited",
3644 [CLD_KILLED
] = "killed",
3645 [CLD_DUMPED
] = "dumped",
3646 [CLD_TRAPPED
] = "trapped",
3647 [CLD_STOPPED
] = "stopped",
3648 [CLD_CONTINUED
] = "continued",
3651 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
3653 static const char *const log_facility_unshifted_table
[LOG_NFACILITIES
] = {
3654 [LOG_FAC(LOG_KERN
)] = "kern",
3655 [LOG_FAC(LOG_USER
)] = "user",
3656 [LOG_FAC(LOG_MAIL
)] = "mail",
3657 [LOG_FAC(LOG_DAEMON
)] = "daemon",
3658 [LOG_FAC(LOG_AUTH
)] = "auth",
3659 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
3660 [LOG_FAC(LOG_LPR
)] = "lpr",
3661 [LOG_FAC(LOG_NEWS
)] = "news",
3662 [LOG_FAC(LOG_UUCP
)] = "uucp",
3663 [LOG_FAC(LOG_CRON
)] = "cron",
3664 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
3665 [LOG_FAC(LOG_FTP
)] = "ftp",
3666 [LOG_FAC(LOG_LOCAL0
)] = "local0",
3667 [LOG_FAC(LOG_LOCAL1
)] = "local1",
3668 [LOG_FAC(LOG_LOCAL2
)] = "local2",
3669 [LOG_FAC(LOG_LOCAL3
)] = "local3",
3670 [LOG_FAC(LOG_LOCAL4
)] = "local4",
3671 [LOG_FAC(LOG_LOCAL5
)] = "local5",
3672 [LOG_FAC(LOG_LOCAL6
)] = "local6",
3673 [LOG_FAC(LOG_LOCAL7
)] = "local7"
3676 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted
, int, LOG_FAC(~0));
3678 static const char *const log_level_table
[] = {
3679 [LOG_EMERG
] = "emerg",
3680 [LOG_ALERT
] = "alert",
3681 [LOG_CRIT
] = "crit",
3683 [LOG_WARNING
] = "warning",
3684 [LOG_NOTICE
] = "notice",
3685 [LOG_INFO
] = "info",
3686 [LOG_DEBUG
] = "debug"
3689 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level
, int, LOG_DEBUG
);
3691 static const char* const sched_policy_table
[] = {
3692 [SCHED_OTHER
] = "other",
3693 [SCHED_BATCH
] = "batch",
3694 [SCHED_IDLE
] = "idle",
3695 [SCHED_FIFO
] = "fifo",
3699 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);
3701 static const char* const rlimit_table
[_RLIMIT_MAX
] = {
3702 [RLIMIT_CPU
] = "LimitCPU",
3703 [RLIMIT_FSIZE
] = "LimitFSIZE",
3704 [RLIMIT_DATA
] = "LimitDATA",
3705 [RLIMIT_STACK
] = "LimitSTACK",
3706 [RLIMIT_CORE
] = "LimitCORE",
3707 [RLIMIT_RSS
] = "LimitRSS",
3708 [RLIMIT_NOFILE
] = "LimitNOFILE",
3709 [RLIMIT_AS
] = "LimitAS",
3710 [RLIMIT_NPROC
] = "LimitNPROC",
3711 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
3712 [RLIMIT_LOCKS
] = "LimitLOCKS",
3713 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
3714 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
3715 [RLIMIT_NICE
] = "LimitNICE",
3716 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
3717 [RLIMIT_RTTIME
] = "LimitRTTIME"
3720 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
3722 static const char* const ip_tos_table
[] = {
3723 [IPTOS_LOWDELAY
] = "low-delay",
3724 [IPTOS_THROUGHPUT
] = "throughput",
3725 [IPTOS_RELIABILITY
] = "reliability",
3726 [IPTOS_LOWCOST
] = "low-cost",
3729 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
3731 bool kexec_loaded(void) {
3732 bool loaded
= false;
3735 if (read_one_line_file("/sys/kernel/kexec_loaded", &s
) >= 0) {
3743 int prot_from_flags(int flags
) {
3745 switch (flags
& O_ACCMODE
) {
3754 return PROT_READ
|PROT_WRITE
;
3761 char *format_bytes(char *buf
, size_t l
, off_t t
) {
3764 static const struct {
3768 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3769 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3770 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3771 { "G", 1024ULL*1024ULL*1024ULL },
3772 { "M", 1024ULL*1024ULL },
3776 if (t
== (off_t
) -1)
3779 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
3781 if (t
>= table
[i
].factor
) {
3784 (unsigned long long) (t
/ table
[i
].factor
),
3785 (unsigned long long) (((t
*10ULL) / table
[i
].factor
) % 10ULL),
3792 snprintf(buf
, l
, "%lluB", (unsigned long long) t
);
3800 void* memdup(const void *p
, size_t l
) {
3813 int fd_inc_sndbuf(int fd
, size_t n
) {
3815 socklen_t l
= sizeof(value
);
3817 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
3818 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
3821 /* If we have the privileges we will ignore the kernel limit. */
3824 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
3825 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
3831 int fd_inc_rcvbuf(int fd
, size_t n
) {
3833 socklen_t l
= sizeof(value
);
3835 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
3836 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
3839 /* If we have the privileges we will ignore the kernel limit. */
3842 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
3843 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
3848 int fork_agent(pid_t
*pid
, const int except
[], unsigned n_except
, const char *path
, ...) {
3849 bool stdout_is_tty
, stderr_is_tty
;
3850 pid_t parent_pid
, agent_pid
;
3851 sigset_t ss
, saved_ss
;
3859 /* Spawns a temporary TTY agent, making sure it goes away when
3862 parent_pid
= getpid();
3864 /* First we temporarily block all signals, so that the new
3865 * child has them blocked initially. This way, we can be sure
3866 * that SIGTERMs are not lost we might send to the agent. */
3867 assert_se(sigfillset(&ss
) >= 0);
3868 assert_se(sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) >= 0);
3871 if (agent_pid
< 0) {
3872 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
3876 if (agent_pid
!= 0) {
3877 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
3884 * Make sure the agent goes away when the parent dies */
3885 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
3886 _exit(EXIT_FAILURE
);
3888 /* Make sure we actually can kill the agent, if we need to, in
3889 * case somebody invoked us from a shell script that trapped
3890 * SIGTERM or so... */
3891 (void) reset_all_signal_handlers();
3892 (void) reset_signal_mask();
3894 /* Check whether our parent died before we were able
3895 * to set the death signal and unblock the signals */
3896 if (getppid() != parent_pid
)
3897 _exit(EXIT_SUCCESS
);
3899 /* Don't leak fds to the agent */
3900 close_all_fds(except
, n_except
);
3902 stdout_is_tty
= isatty(STDOUT_FILENO
);
3903 stderr_is_tty
= isatty(STDERR_FILENO
);
3905 if (!stdout_is_tty
|| !stderr_is_tty
) {
3908 /* Detach from stdout/stderr. and reopen
3909 * /dev/tty for them. This is important to
3910 * ensure that when systemctl is started via
3911 * popen() or a similar call that expects to
3912 * read EOF we actually do generate EOF and
3913 * not delay this indefinitely by because we
3914 * keep an unused copy of stdin around. */
3915 fd
= open("/dev/tty", O_WRONLY
);
3917 log_error_errno(errno
, "Failed to open /dev/tty: %m");
3918 _exit(EXIT_FAILURE
);
3922 dup2(fd
, STDOUT_FILENO
);
3925 dup2(fd
, STDERR_FILENO
);
3931 /* Count arguments */
3933 for (n
= 0; va_arg(ap
, char*); n
++)
3938 l
= alloca(sizeof(char *) * (n
+ 1));
3940 /* Fill in arguments */
3942 for (i
= 0; i
<= n
; i
++)
3943 l
[i
] = va_arg(ap
, char*);
3947 _exit(EXIT_FAILURE
);
3950 int setrlimit_closest(int resource
, const struct rlimit
*rlim
) {
3951 struct rlimit highest
, fixed
;
3955 if (setrlimit(resource
, rlim
) >= 0)
3961 /* So we failed to set the desired setrlimit, then let's try
3962 * to get as close as we can */
3963 assert_se(getrlimit(resource
, &highest
) == 0);
3965 fixed
.rlim_cur
= MIN(rlim
->rlim_cur
, highest
.rlim_max
);
3966 fixed
.rlim_max
= MIN(rlim
->rlim_max
, highest
.rlim_max
);
3968 if (setrlimit(resource
, &fixed
) < 0)
3974 bool http_etag_is_valid(const char *etag
) {
3978 if (!endswith(etag
, "\""))
3981 if (!startswith(etag
, "\"") && !startswith(etag
, "W/\""))
3987 bool http_url_is_valid(const char *url
) {
3993 p
= startswith(url
, "http://");
3995 p
= startswith(url
, "https://");
4002 return ascii_is_valid(p
);
4005 bool documentation_url_is_valid(const char *url
) {
4011 if (http_url_is_valid(url
))
4014 p
= startswith(url
, "file:/");
4016 p
= startswith(url
, "info:");
4018 p
= startswith(url
, "man:");
4023 return ascii_is_valid(p
);
4026 bool in_initrd(void) {
4027 static int saved
= -1;
4033 /* We make two checks here:
4035 * 1. the flag file /etc/initrd-release must exist
4036 * 2. the root file system must be a memory file system
4038 * The second check is extra paranoia, since misdetecting an
4039 * initrd can have bad bad consequences due the initrd
4040 * emptying when transititioning to the main systemd.
4043 saved
= access("/etc/initrd-release", F_OK
) >= 0 &&
4044 statfs("/", &s
) >= 0 &&
4045 is_temporary_fs(&s
);
4050 int get_home_dir(char **_h
) {
4058 /* Take the user specified one */
4059 e
= secure_getenv("HOME");
4060 if (e
&& path_is_absolute(e
)) {
4069 /* Hardcode home directory for root to avoid NSS */
4072 h
= strdup("/root");
4080 /* Check the database... */
4084 return errno
> 0 ? -errno
: -ESRCH
;
4086 if (!path_is_absolute(p
->pw_dir
))
4089 h
= strdup(p
->pw_dir
);
4097 int get_shell(char **_s
) {
4105 /* Take the user specified one */
4106 e
= getenv("SHELL");
4116 /* Hardcode home directory for root to avoid NSS */
4119 s
= strdup("/bin/sh");
4127 /* Check the database... */
4131 return errno
> 0 ? -errno
: -ESRCH
;
4133 if (!path_is_absolute(p
->pw_shell
))
4136 s
= strdup(p
->pw_shell
);
4144 bool filename_is_valid(const char *p
) {
4158 if (strlen(p
) > FILENAME_MAX
)
4164 bool string_is_safe(const char *p
) {
4170 for (t
= p
; *t
; t
++) {
4171 if (*t
> 0 && *t
< ' ')
4174 if (strchr("\\\"\'\x7f", *t
))
4182 * Check if a string contains control characters. If 'ok' is non-NULL
4183 * it may be a string containing additional CCs to be considered OK.
4185 bool string_has_cc(const char *p
, const char *ok
) {
4190 for (t
= p
; *t
; t
++) {
4191 if (ok
&& strchr(ok
, *t
))
4194 if (*t
> 0 && *t
< ' ')
4204 bool path_is_safe(const char *p
) {
4209 if (streq(p
, "..") || startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
4212 if (strlen(p
)+1 > PATH_MAX
)
4215 /* The following two checks are not really dangerous, but hey, they still are confusing */
4216 if (streq(p
, ".") || startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
4219 if (strstr(p
, "//"))
4225 /* hey glibc, APIs with callbacks without a user pointer are so useless */
4226 void *xbsearch_r(const void *key
, const void *base
, size_t nmemb
, size_t size
,
4227 int (*compar
) (const void *, const void *, void *), void *arg
) {
4236 p
= (void *)(((const char *) base
) + (idx
* size
));
4237 comparison
= compar(key
, p
, arg
);
4240 else if (comparison
> 0)
4248 void init_gettext(void) {
4249 setlocale(LC_ALL
, "");
4250 textdomain(GETTEXT_PACKAGE
);
4253 bool is_locale_utf8(void) {
4255 static int cached_answer
= -1;
4257 if (cached_answer
>= 0)
4260 if (!setlocale(LC_ALL
, "")) {
4261 cached_answer
= true;
4265 set
= nl_langinfo(CODESET
);
4267 cached_answer
= true;
4271 if (streq(set
, "UTF-8")) {
4272 cached_answer
= true;
4276 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
4277 * unset and everything can do to UTF-8 nowadays. */
4278 set
= setlocale(LC_CTYPE
, NULL
);
4280 cached_answer
= true;
4284 /* Check result, but ignore the result if C was set
4287 STR_IN_SET(set
, "C", "POSIX") &&
4288 !getenv("LC_ALL") &&
4289 !getenv("LC_CTYPE") &&
4293 return (bool) cached_answer
;
4296 const char *draw_special_char(DrawSpecialChar ch
) {
4297 static const char *draw_table
[2][_DRAW_SPECIAL_CHAR_MAX
] = {
4300 [DRAW_TREE_VERTICAL
] = "\342\224\202 ", /* │ */
4301 [DRAW_TREE_BRANCH
] = "\342\224\234\342\224\200", /* ├─ */
4302 [DRAW_TREE_RIGHT
] = "\342\224\224\342\224\200", /* └─ */
4303 [DRAW_TREE_SPACE
] = " ", /* */
4304 [DRAW_TRIANGULAR_BULLET
] = "\342\200\243", /* ‣ */
4305 [DRAW_BLACK_CIRCLE
] = "\342\227\217", /* ● */
4306 [DRAW_ARROW
] = "\342\206\222", /* → */
4307 [DRAW_DASH
] = "\342\200\223", /* – */
4310 /* ASCII fallback */ {
4311 [DRAW_TREE_VERTICAL
] = "| ",
4312 [DRAW_TREE_BRANCH
] = "|-",
4313 [DRAW_TREE_RIGHT
] = "`-",
4314 [DRAW_TREE_SPACE
] = " ",
4315 [DRAW_TRIANGULAR_BULLET
] = ">",
4316 [DRAW_BLACK_CIRCLE
] = "*",
4317 [DRAW_ARROW
] = "->",
4322 return draw_table
[!is_locale_utf8()][ch
];
4325 char *strreplace(const char *text
, const char *old_string
, const char *new_string
) {
4328 size_t l
, old_len
, new_len
;
4334 old_len
= strlen(old_string
);
4335 new_len
= strlen(new_string
);
4348 if (!startswith(f
, old_string
)) {
4354 nl
= l
- old_len
+ new_len
;
4355 a
= realloc(r
, nl
+ 1);
4363 t
= stpcpy(t
, new_string
);
4375 char *strip_tab_ansi(char **ibuf
, size_t *_isz
) {
4376 const char *i
, *begin
= NULL
;
4381 } state
= STATE_OTHER
;
4383 size_t osz
= 0, isz
;
4389 /* Strips ANSI color and replaces TABs by 8 spaces */
4391 isz
= _isz
? *_isz
: strlen(*ibuf
);
4393 f
= open_memstream(&obuf
, &osz
);
4397 for (i
= *ibuf
; i
< *ibuf
+ isz
+ 1; i
++) {
4402 if (i
>= *ibuf
+ isz
) /* EOT */
4404 else if (*i
== '\x1B')
4405 state
= STATE_ESCAPE
;
4406 else if (*i
== '\t')
4413 if (i
>= *ibuf
+ isz
) { /* EOT */
4416 } else if (*i
== '[') {
4417 state
= STATE_BRACKET
;
4422 state
= STATE_OTHER
;
4429 if (i
>= *ibuf
+ isz
|| /* EOT */
4430 (!(*i
>= '0' && *i
<= '9') && *i
!= ';' && *i
!= 'm')) {
4433 state
= STATE_OTHER
;
4435 } else if (*i
== 'm')
4436 state
= STATE_OTHER
;
4458 int on_ac_power(void) {
4459 bool found_offline
= false, found_online
= false;
4460 _cleanup_closedir_
DIR *d
= NULL
;
4462 d
= opendir("/sys/class/power_supply");
4464 return errno
== ENOENT
? true : -errno
;
4468 _cleanup_close_
int fd
= -1, device
= -1;
4474 if (!de
&& errno
!= 0)
4480 if (hidden_file(de
->d_name
))
4483 device
= openat(dirfd(d
), de
->d_name
, O_DIRECTORY
|O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4485 if (errno
== ENOENT
|| errno
== ENOTDIR
)
4491 fd
= openat(device
, "type", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4493 if (errno
== ENOENT
)
4499 n
= read(fd
, contents
, sizeof(contents
));
4503 if (n
!= 6 || memcmp(contents
, "Mains\n", 6))
4507 fd
= openat(device
, "online", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4509 if (errno
== ENOENT
)
4515 n
= read(fd
, contents
, sizeof(contents
));
4519 if (n
!= 2 || contents
[1] != '\n')
4522 if (contents
[0] == '1') {
4523 found_online
= true;
4525 } else if (contents
[0] == '0')
4526 found_offline
= true;
4531 return found_online
|| !found_offline
;
4534 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
4541 if (!path_strv_resolve_uniq(search
, root
))
4544 STRV_FOREACH(i
, search
) {
4545 _cleanup_free_
char *p
= NULL
;
4549 p
= strjoin(root
, *i
, "/", path
, NULL
);
4551 p
= strjoin(*i
, "/", path
, NULL
);
4561 if (errno
!= ENOENT
)
4568 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
4569 _cleanup_strv_free_
char **copy
= NULL
;
4575 if (path_is_absolute(path
)) {
4578 f
= fopen(path
, mode
);
4587 copy
= strv_copy((char**) search
);
4591 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
4594 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
4595 _cleanup_strv_free_
char **s
= NULL
;
4597 if (path_is_absolute(path
)) {
4600 f
= fopen(path
, mode
);
4609 s
= strv_split_nulstr(search
);
4613 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
4616 char *strextend(char **x
, ...) {
4623 l
= f
= *x
? strlen(*x
) : 0;
4630 t
= va_arg(ap
, const char *);
4635 if (n
> ((size_t) -1) - l
) {
4644 r
= realloc(*x
, l
+1);
4654 t
= va_arg(ap
, const char *);
4668 char *strrep(const char *s
, unsigned n
) {
4676 p
= r
= malloc(l
* n
+ 1);
4680 for (i
= 0; i
< n
; i
++)
4687 void* greedy_realloc(void **p
, size_t *allocated
, size_t need
, size_t size
) {
4694 if (*allocated
>= need
)
4697 newalloc
= MAX(need
* 2, 64u / size
);
4698 a
= newalloc
* size
;
4700 /* check for overflows */
4701 if (a
< size
* need
)
4709 *allocated
= newalloc
;
4713 void* greedy_realloc0(void **p
, size_t *allocated
, size_t need
, size_t size
) {
4722 q
= greedy_realloc(p
, allocated
, need
, size
);
4726 if (*allocated
> prev
)
4727 memzero(q
+ prev
* size
, (*allocated
- prev
) * size
);
4732 bool id128_is_valid(const char *s
) {
4738 /* Simple formatted 128bit hex string */
4740 for (i
= 0; i
< l
; i
++) {
4743 if (!(c
>= '0' && c
<= '9') &&
4744 !(c
>= 'a' && c
<= 'z') &&
4745 !(c
>= 'A' && c
<= 'Z'))
4749 } else if (l
== 36) {
4751 /* Formatted UUID */
4753 for (i
= 0; i
< l
; i
++) {
4756 if ((i
== 8 || i
== 13 || i
== 18 || i
== 23)) {
4760 if (!(c
>= '0' && c
<= '9') &&
4761 !(c
>= 'a' && c
<= 'z') &&
4762 !(c
>= 'A' && c
<= 'Z'))
4773 int split_pair(const char *s
, const char *sep
, char **l
, char **r
) {
4788 a
= strndup(s
, x
- s
);
4792 b
= strdup(x
+ strlen(sep
));
4804 int shall_restore_state(void) {
4805 _cleanup_free_
char *value
= NULL
;
4808 r
= get_proc_cmdline_key("systemd.restore_state=", &value
);
4814 return parse_boolean(value
) != 0;
4817 int proc_cmdline(char **ret
) {
4820 if (detect_container(NULL
) > 0)
4821 return get_process_cmdline(1, 0, false, ret
);
4823 return read_one_line_file("/proc/cmdline", ret
);
4826 int parse_proc_cmdline(int (*parse_item
)(const char *key
, const char *value
)) {
4827 _cleanup_free_
char *line
= NULL
;
4833 r
= proc_cmdline(&line
);
4839 _cleanup_free_
char *word
= NULL
;
4842 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
4848 /* Filter out arguments that are intended only for the
4850 if (!in_initrd() && startswith(word
, "rd."))
4853 value
= strchr(word
, '=');
4857 r
= parse_item(word
, value
);
4865 int get_proc_cmdline_key(const char *key
, char **value
) {
4866 _cleanup_free_
char *line
= NULL
, *ret
= NULL
;
4873 r
= proc_cmdline(&line
);
4879 _cleanup_free_
char *word
= NULL
;
4882 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
4888 /* Filter out arguments that are intended only for the
4890 if (!in_initrd() && startswith(word
, "rd."))
4894 e
= startswith(word
, key
);
4898 r
= free_and_strdup(&ret
, e
);
4904 if (streq(word
, key
))
4918 int container_get_leader(const char *machine
, pid_t
*pid
) {
4919 _cleanup_free_
char *s
= NULL
, *class = NULL
;
4927 if (!machine_name_is_valid(machine
))
4930 p
= strjoina("/run/systemd/machines/", machine
);
4931 r
= parse_env_file(p
, NEWLINE
, "LEADER", &s
, "CLASS", &class, NULL
);
4939 if (!streq_ptr(class, "container"))
4942 r
= parse_pid(s
, &leader
);
4952 int namespace_open(pid_t pid
, int *pidns_fd
, int *mntns_fd
, int *netns_fd
, int *userns_fd
, int *root_fd
) {
4953 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, netnsfd
= -1, usernsfd
= -1;
4961 mntns
= procfs_file_alloca(pid
, "ns/mnt");
4962 mntnsfd
= open(mntns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
4970 pidns
= procfs_file_alloca(pid
, "ns/pid");
4971 pidnsfd
= open(pidns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
4979 netns
= procfs_file_alloca(pid
, "ns/net");
4980 netnsfd
= open(netns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
4988 userns
= procfs_file_alloca(pid
, "ns/user");
4989 usernsfd
= open(userns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
4990 if (usernsfd
< 0 && errno
!= ENOENT
)
4997 root
= procfs_file_alloca(pid
, "root");
4998 rfd
= open(root
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
|O_DIRECTORY
);
5004 *pidns_fd
= pidnsfd
;
5007 *mntns_fd
= mntnsfd
;
5010 *netns_fd
= netnsfd
;
5013 *userns_fd
= usernsfd
;
5018 pidnsfd
= mntnsfd
= netnsfd
= usernsfd
= -1;
5023 int namespace_enter(int pidns_fd
, int mntns_fd
, int netns_fd
, int userns_fd
, int root_fd
) {
5024 if (userns_fd
>= 0) {
5025 /* Can't setns to your own userns, since then you could
5026 * escalate from non-root to root in your own namespace, so
5027 * check if namespaces equal before attempting to enter. */
5028 _cleanup_free_
char *userns_fd_path
= NULL
;
5030 if (asprintf(&userns_fd_path
, "/proc/self/fd/%d", userns_fd
) < 0)
5033 r
= files_same(userns_fd_path
, "/proc/self/ns/user");
5041 if (setns(pidns_fd
, CLONE_NEWPID
) < 0)
5045 if (setns(mntns_fd
, CLONE_NEWNS
) < 0)
5049 if (setns(netns_fd
, CLONE_NEWNET
) < 0)
5053 if (setns(userns_fd
, CLONE_NEWUSER
) < 0)
5057 if (fchdir(root_fd
) < 0)
5060 if (chroot(".") < 0)
5064 return reset_uid_gid();
5067 int getpeercred(int fd
, struct ucred
*ucred
) {
5068 socklen_t n
= sizeof(struct ucred
);
5075 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
);
5079 if (n
!= sizeof(struct ucred
))
5082 /* Check if the data is actually useful and not suppressed due
5083 * to namespacing issues */
5086 if (u
.uid
== UID_INVALID
)
5088 if (u
.gid
== GID_INVALID
)
5095 int getpeersec(int fd
, char **ret
) {
5107 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
5111 if (errno
!= ERANGE
)
5118 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
5134 /* This is much like like mkostemp() but is subject to umask(). */
5135 int mkostemp_safe(char *pattern
, int flags
) {
5136 _cleanup_umask_ mode_t u
;
5143 fd
= mkostemp(pattern
, flags
);
5150 int open_tmpfile(const char *path
, int flags
) {
5157 /* Try O_TMPFILE first, if it is supported */
5158 fd
= open(path
, flags
|O_TMPFILE
|O_EXCL
, S_IRUSR
|S_IWUSR
);
5163 /* Fall back to unguessable name + unlinking */
5164 p
= strjoina(path
, "/systemd-tmp-XXXXXX");
5166 fd
= mkostemp_safe(p
, flags
);
5174 int fd_warn_permissions(const char *path
, int fd
) {
5177 if (fstat(fd
, &st
) < 0)
5180 if (st
.st_mode
& 0111)
5181 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path
);
5183 if (st
.st_mode
& 0002)
5184 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path
);
5186 if (getpid() == 1 && (st
.st_mode
& 0044) != 0044)
5187 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
);
5192 unsigned long personality_from_string(const char *p
) {
5194 /* Parse a personality specifier. We introduce our own
5195 * identifiers that indicate specific ABIs, rather than just
5196 * hints regarding the register size, since we want to keep
5197 * things open for multiple locally supported ABIs for the
5198 * same register size. We try to reuse the ABI identifiers
5199 * used by libseccomp. */
5201 #if defined(__x86_64__)
5203 if (streq(p
, "x86"))
5206 if (streq(p
, "x86-64"))
5209 #elif defined(__i386__)
5211 if (streq(p
, "x86"))
5215 return PERSONALITY_INVALID
;
5218 const char* personality_to_string(unsigned long p
) {
5220 #if defined(__x86_64__)
5222 if (p
== PER_LINUX32
)
5228 #elif defined(__i386__)
5237 uint64_t physical_memory(void) {
5240 /* We return this as uint64_t in case we are running as 32bit
5241 * process on a 64bit kernel with huge amounts of memory */
5243 mem
= sysconf(_SC_PHYS_PAGES
);
5246 return (uint64_t) mem
* (uint64_t) page_size();
5249 void hexdump(FILE *f
, const void *p
, size_t s
) {
5250 const uint8_t *b
= p
;
5253 assert(s
== 0 || b
);
5258 fprintf(f
, "%04x ", n
);
5260 for (i
= 0; i
< 16; i
++) {
5265 fprintf(f
, "%02x ", b
[i
]);
5273 for (i
= 0; i
< 16; i
++) {
5278 fputc(isprint(b
[i
]) ? (char) b
[i
] : '.', f
);
5292 int update_reboot_param_file(const char *param
) {
5297 r
= write_string_file(REBOOT_PARAM_FILE
, param
, WRITE_STRING_FILE_CREATE
);
5299 log_error("Failed to write reboot param to "
5300 REBOOT_PARAM_FILE
": %s", strerror(-r
));
5302 unlink(REBOOT_PARAM_FILE
);
5307 int umount_recursive(const char *prefix
, int flags
) {
5311 /* Try to umount everything recursively below a
5312 * directory. Also, take care of stacked mounts, and keep
5313 * unmounting them until they are gone. */
5316 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
5321 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
5322 if (!proc_self_mountinfo
)
5326 _cleanup_free_
char *path
= NULL
, *p
= NULL
;
5329 k
= fscanf(proc_self_mountinfo
,
5330 "%*s " /* (1) mount id */
5331 "%*s " /* (2) parent id */
5332 "%*s " /* (3) major:minor */
5333 "%*s " /* (4) root */
5334 "%ms " /* (5) mount point */
5335 "%*s" /* (6) mount options */
5336 "%*[^-]" /* (7) optional fields */
5337 "- " /* (8) separator */
5338 "%*s " /* (9) file system type */
5339 "%*s" /* (10) mount source */
5340 "%*s" /* (11) mount options 2 */
5341 "%*[^\n]", /* some rubbish at the end */
5350 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
5354 if (!path_startswith(p
, prefix
))
5357 if (umount2(p
, flags
) < 0) {
5373 static int get_mount_flags(const char *path
, unsigned long *flags
) {
5376 if (statvfs(path
, &buf
) < 0)
5378 *flags
= buf
.f_flag
;
5382 int bind_remount_recursive(const char *prefix
, bool ro
) {
5383 _cleanup_set_free_free_ Set
*done
= NULL
;
5384 _cleanup_free_
char *cleaned
= NULL
;
5387 /* Recursively remount a directory (and all its submounts)
5388 * read-only or read-write. If the directory is already
5389 * mounted, we reuse the mount and simply mark it
5390 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
5391 * operation). If it isn't we first make it one. Afterwards we
5392 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
5393 * submounts we can access, too. When mounts are stacked on
5394 * the same mount point we only care for each individual
5395 * "top-level" mount on each point, as we cannot
5396 * influence/access the underlying mounts anyway. We do not
5397 * have any effect on future submounts that might get
5398 * propagated, they migt be writable. This includes future
5399 * submounts that have been triggered via autofs. */
5401 cleaned
= strdup(prefix
);
5405 path_kill_slashes(cleaned
);
5407 done
= set_new(&string_hash_ops
);
5412 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
5413 _cleanup_set_free_free_ Set
*todo
= NULL
;
5414 bool top_autofs
= false;
5416 unsigned long orig_flags
;
5418 todo
= set_new(&string_hash_ops
);
5422 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
5423 if (!proc_self_mountinfo
)
5427 _cleanup_free_
char *path
= NULL
, *p
= NULL
, *type
= NULL
;
5430 k
= fscanf(proc_self_mountinfo
,
5431 "%*s " /* (1) mount id */
5432 "%*s " /* (2) parent id */
5433 "%*s " /* (3) major:minor */
5434 "%*s " /* (4) root */
5435 "%ms " /* (5) mount point */
5436 "%*s" /* (6) mount options (superblock) */
5437 "%*[^-]" /* (7) optional fields */
5438 "- " /* (8) separator */
5439 "%ms " /* (9) file system type */
5440 "%*s" /* (10) mount source */
5441 "%*s" /* (11) mount options (bind mount) */
5442 "%*[^\n]", /* some rubbish at the end */
5452 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
5456 /* Let's ignore autofs mounts. If they aren't
5457 * triggered yet, we want to avoid triggering
5458 * them, as we don't make any guarantees for
5459 * future submounts anyway. If they are
5460 * already triggered, then we will find
5461 * another entry for this. */
5462 if (streq(type
, "autofs")) {
5463 top_autofs
= top_autofs
|| path_equal(cleaned
, p
);
5467 if (path_startswith(p
, cleaned
) &&
5468 !set_contains(done
, p
)) {
5470 r
= set_consume(todo
, p
);
5480 /* If we have no submounts to process anymore and if
5481 * the root is either already done, or an autofs, we
5483 if (set_isempty(todo
) &&
5484 (top_autofs
|| set_contains(done
, cleaned
)))
5487 if (!set_contains(done
, cleaned
) &&
5488 !set_contains(todo
, cleaned
)) {
5489 /* The prefix directory itself is not yet a
5490 * mount, make it one. */
5491 if (mount(cleaned
, cleaned
, NULL
, MS_BIND
|MS_REC
, NULL
) < 0)
5495 (void) get_mount_flags(cleaned
, &orig_flags
);
5496 orig_flags
&= ~MS_RDONLY
;
5498 if (mount(NULL
, prefix
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0)
5501 x
= strdup(cleaned
);
5505 r
= set_consume(done
, x
);
5510 while ((x
= set_steal_first(todo
))) {
5512 r
= set_consume(done
, x
);
5513 if (r
== -EEXIST
|| r
== 0)
5518 /* Try to reuse the original flag set, but
5519 * don't care for errors, in case of
5520 * obstructed mounts */
5522 (void) get_mount_flags(x
, &orig_flags
);
5523 orig_flags
&= ~MS_RDONLY
;
5525 if (mount(NULL
, x
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0) {
5527 /* Deal with mount points that are
5528 * obstructed by a later mount */
5530 if (errno
!= ENOENT
)
5538 int fflush_and_check(FILE *f
) {
5545 return errno
? -errno
: -EIO
;
5550 int tempfn_xxxxxx(const char *p
, const char *extra
, char **ret
) {
5562 * /foo/bar/.#<extra>waldoXXXXXX
5566 if (!filename_is_valid(fn
))
5572 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 6 + 1);
5576 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
), "XXXXXX");
5578 *ret
= path_kill_slashes(t
);
5582 int tempfn_random(const char *p
, const char *extra
, char **ret
) {
5596 * /foo/bar/.#<extra>waldobaa2a261115984a9
5600 if (!filename_is_valid(fn
))
5606 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 16 + 1);
5610 x
= stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
);
5613 for (i
= 0; i
< 16; i
++) {
5614 *(x
++) = hexchar(u
& 0xF);
5620 *ret
= path_kill_slashes(t
);
5624 int tempfn_random_child(const char *p
, const char *extra
, char **ret
) {
5635 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
5641 t
= new(char, strlen(p
) + 3 + strlen(extra
) + 16 + 1);
5645 x
= stpcpy(stpcpy(stpcpy(t
, p
), "/.#"), extra
);
5648 for (i
= 0; i
< 16; i
++) {
5649 *(x
++) = hexchar(u
& 0xF);
5655 *ret
= path_kill_slashes(t
);
5659 int take_password_lock(const char *root
) {
5661 struct flock flock
= {
5663 .l_whence
= SEEK_SET
,
5671 /* This is roughly the same as lckpwdf(), but not as awful. We
5672 * don't want to use alarm() and signals, hence we implement
5673 * our own trivial version of this.
5675 * Note that shadow-utils also takes per-database locks in
5676 * addition to lckpwdf(). However, we don't given that they
5677 * are redundant as they they invoke lckpwdf() first and keep
5678 * it during everything they do. The per-database locks are
5679 * awfully racy, and thus we just won't do them. */
5682 path
= strjoina(root
, "/etc/.pwd.lock");
5684 path
= "/etc/.pwd.lock";
5686 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
5690 r
= fcntl(fd
, F_SETLKW
, &flock
);
5699 int is_symlink(const char *path
) {
5702 if (lstat(path
, &info
) < 0)
5705 return !!S_ISLNK(info
.st_mode
);
5708 int is_dir(const char* path
, bool follow
) {
5713 r
= stat(path
, &st
);
5715 r
= lstat(path
, &st
);
5719 return !!S_ISDIR(st
.st_mode
);
5722 int is_device_node(const char *path
) {
5725 if (lstat(path
, &info
) < 0)
5728 return !!(S_ISBLK(info
.st_mode
) || S_ISCHR(info
.st_mode
));
5731 int extract_first_word(const char **p
, char **ret
, const char *separators
, ExtractFlags flags
) {
5732 _cleanup_free_
char *s
= NULL
;
5733 size_t allocated
= 0, sz
= 0;
5741 SINGLE_QUOTE_ESCAPE
,
5743 DOUBLE_QUOTE_ESCAPE
,
5751 separators
= WHITESPACE
;
5753 /* Bail early if called after last value or with no input */
5755 goto finish_force_terminate
;
5757 /* Parses the first word of a string, and returns it in
5758 * *ret. Removes all quotes in the process. When parsing fails
5759 * (because of an uneven number of quotes or similar), leaves
5760 * the pointer *p at the first invalid character. */
5768 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
)
5769 if (!GREEDY_REALLOC(s
, allocated
, sz
+1))
5773 goto finish_force_terminate
;
5774 else if (strchr(separators
, c
)) {
5775 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
) {
5777 goto finish_force_next
;
5782 /* We found a non-blank character, so we will always
5783 * want to return a string (even if it is empty),
5784 * allocate it here. */
5785 if (!GREEDY_REALLOC(s
, allocated
, sz
+1))
5793 goto finish_force_terminate
;
5794 else if (c
== '\'' && (flags
& EXTRACT_QUOTES
))
5795 state
= SINGLE_QUOTE
;
5797 state
= VALUE_ESCAPE
;
5798 else if (c
== '\"' && (flags
& EXTRACT_QUOTES
))
5799 state
= DOUBLE_QUOTE
;
5800 else if (strchr(separators
, c
)) {
5801 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
) {
5803 goto finish_force_next
;
5807 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5817 if (flags
& EXTRACT_RELAX
)
5818 goto finish_force_terminate
;
5820 } else if (c
== '\'')
5823 state
= SINGLE_QUOTE_ESCAPE
;
5825 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5839 state
= DOUBLE_QUOTE_ESCAPE
;
5841 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5849 case SINGLE_QUOTE_ESCAPE
:
5850 case DOUBLE_QUOTE_ESCAPE
:
5852 if (!GREEDY_REALLOC(s
, allocated
, sz
+7))
5856 if ((flags
& EXTRACT_CUNESCAPE_RELAX
) &&
5857 (state
== VALUE_ESCAPE
|| flags
& EXTRACT_RELAX
)) {
5858 /* If we find an unquoted trailing backslash and we're in
5859 * EXTRACT_CUNESCAPE_RELAX mode, keep it verbatim in the
5862 * Unbalanced quotes will only be allowed in EXTRACT_RELAX
5863 * mode, EXTRACT_CUNESCAPE_RELAX mode does not allow them.
5866 goto finish_force_terminate
;
5868 if (flags
& EXTRACT_RELAX
)
5869 goto finish_force_terminate
;
5873 if (flags
& EXTRACT_CUNESCAPE
) {
5876 r
= cunescape_one(*p
, (size_t) -1, &c
, &u
);
5878 if (flags
& EXTRACT_CUNESCAPE_RELAX
) {
5889 s
[sz
++] = c
; /* normal explicit char */
5891 sz
+= utf8_encode_unichar(s
+ sz
, u
); /* unicode chars we'll encode as utf8 */
5896 state
= (state
== SINGLE_QUOTE_ESCAPE
) ? SINGLE_QUOTE
:
5897 (state
== DOUBLE_QUOTE_ESCAPE
) ? DOUBLE_QUOTE
:
5903 goto finish_force_terminate
;
5904 if (!strchr(separators
, c
))
5912 finish_force_terminate
:
5929 int extract_first_word_and_warn(
5932 const char *separators
,
5935 const char *filename
,
5937 const char *rvalue
) {
5938 /* Try to unquote it, if it fails, warn about it and try again but this
5939 * time using EXTRACT_CUNESCAPE_RELAX to keep the backslashes verbatim
5940 * in invalid escape sequences. */
5945 r
= extract_first_word(p
, ret
, separators
, flags
);
5946 if (r
< 0 && !(flags
&EXTRACT_CUNESCAPE_RELAX
)) {
5947 /* Retry it with EXTRACT_CUNESCAPE_RELAX. */
5949 r
= extract_first_word(p
, ret
, separators
, flags
|EXTRACT_CUNESCAPE_RELAX
);
5951 log_syntax(unit
, LOG_ERR
, filename
, line
, EINVAL
,
5952 "Unbalanced quoting in command line, ignoring: \"%s\"", rvalue
);
5954 log_syntax(unit
, LOG_WARNING
, filename
, line
, EINVAL
,
5955 "Invalid escape sequences in command line: \"%s\"", rvalue
);
5960 int extract_many_words(const char **p
, const char *separators
, ExtractFlags flags
, ...) {
5965 /* Parses a number of words from a string, stripping any
5966 * quotes if necessary. */
5970 /* Count how many words are expected */
5971 va_start(ap
, flags
);
5973 if (!va_arg(ap
, char **))
5982 /* Read all words into a temporary array */
5983 l
= newa0(char*, n
);
5984 for (c
= 0; c
< n
; c
++) {
5986 r
= extract_first_word(p
, &l
[c
], separators
, flags
);
5990 for (j
= 0; j
< c
; j
++)
6000 /* If we managed to parse all words, return them in the passed
6002 va_start(ap
, flags
);
6003 for (i
= 0; i
< n
; i
++) {
6006 v
= va_arg(ap
, char **);
6016 int free_and_strdup(char **p
, const char *s
) {
6021 /* Replaces a string pointer with an strdup()ed new string,
6022 * possibly freeing the old one. */
6024 if (streq_ptr(*p
, s
))
6040 int ptsname_malloc(int fd
, char **ret
) {
6053 if (ptsname_r(fd
, c
, l
) == 0) {
6057 if (errno
!= ERANGE
) {
6067 int openpt_in_namespace(pid_t pid
, int flags
) {
6068 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, usernsfd
= -1, rootfd
= -1;
6069 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
6071 struct cmsghdr cmsghdr
;
6072 uint8_t buf
[CMSG_SPACE(sizeof(int))];
6074 struct msghdr mh
= {
6075 .msg_control
= &control
,
6076 .msg_controllen
= sizeof(control
),
6078 struct cmsghdr
*cmsg
;
6085 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &usernsfd
, &rootfd
);
6089 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
6099 pair
[0] = safe_close(pair
[0]);
6101 r
= namespace_enter(pidnsfd
, mntnsfd
, -1, usernsfd
, rootfd
);
6103 _exit(EXIT_FAILURE
);
6105 master
= posix_openpt(flags
);
6107 _exit(EXIT_FAILURE
);
6109 if (unlockpt(master
) < 0)
6110 _exit(EXIT_FAILURE
);
6112 cmsg
= CMSG_FIRSTHDR(&mh
);
6113 cmsg
->cmsg_level
= SOL_SOCKET
;
6114 cmsg
->cmsg_type
= SCM_RIGHTS
;
6115 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
6116 memcpy(CMSG_DATA(cmsg
), &master
, sizeof(int));
6118 mh
.msg_controllen
= cmsg
->cmsg_len
;
6120 if (sendmsg(pair
[1], &mh
, MSG_NOSIGNAL
) < 0)
6121 _exit(EXIT_FAILURE
);
6123 _exit(EXIT_SUCCESS
);
6126 pair
[1] = safe_close(pair
[1]);
6128 r
= wait_for_terminate(child
, &si
);
6131 if (si
.si_code
!= CLD_EXITED
|| si
.si_status
!= EXIT_SUCCESS
)
6134 if (recvmsg(pair
[0], &mh
, MSG_NOSIGNAL
|MSG_CMSG_CLOEXEC
) < 0)
6137 CMSG_FOREACH(cmsg
, &mh
)
6138 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
) {
6142 fds
= (int*) CMSG_DATA(cmsg
);
6143 n_fds
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
6146 close_many(fds
, n_fds
);
6156 ssize_t
fgetxattrat_fake(int dirfd
, const char *filename
, const char *attribute
, void *value
, size_t size
, int flags
) {
6157 _cleanup_close_
int fd
= -1;
6160 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
6162 fd
= openat(dirfd
, filename
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOATIME
|(flags
& AT_SYMLINK_NOFOLLOW
? O_NOFOLLOW
: 0));
6166 l
= fgetxattr(fd
, attribute
, value
, size
);
6173 static int parse_crtime(le64_t le
, usec_t
*usec
) {
6179 if (u
== 0 || u
== (uint64_t) -1)
6186 int fd_getcrtime(int fd
, usec_t
*usec
) {
6193 /* Until Linux gets a real concept of birthtime/creation time,
6194 * let's fake one with xattrs */
6196 n
= fgetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
));
6199 if (n
!= sizeof(le
))
6202 return parse_crtime(le
, usec
);
6205 int fd_getcrtime_at(int dirfd
, const char *name
, usec_t
*usec
, int flags
) {
6209 n
= fgetxattrat_fake(dirfd
, name
, "user.crtime_usec", &le
, sizeof(le
), flags
);
6212 if (n
!= sizeof(le
))
6215 return parse_crtime(le
, usec
);
6218 int path_getcrtime(const char *p
, usec_t
*usec
) {
6225 n
= getxattr(p
, "user.crtime_usec", &le
, sizeof(le
));
6228 if (n
!= sizeof(le
))
6231 return parse_crtime(le
, usec
);
6234 int fd_setcrtime(int fd
, usec_t usec
) {
6240 usec
= now(CLOCK_REALTIME
);
6242 le
= htole64((uint64_t) usec
);
6243 if (fsetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
), 0) < 0)
6249 int same_fd(int a
, int b
) {
6250 struct stat sta
, stb
;
6257 /* Compares two file descriptors. Note that semantics are
6258 * quite different depending on whether we have kcmp() or we
6259 * don't. If we have kcmp() this will only return true for
6260 * dup()ed file descriptors, but not otherwise. If we don't
6261 * have kcmp() this will also return true for two fds of the same
6262 * file, created by separate open() calls. Since we use this
6263 * call mostly for filtering out duplicates in the fd store
6264 * this difference hopefully doesn't matter too much. */
6269 /* Try to use kcmp() if we have it. */
6271 r
= kcmp(pid
, pid
, KCMP_FILE
, a
, b
);
6276 if (errno
!= ENOSYS
)
6279 /* We don't have kcmp(), use fstat() instead. */
6280 if (fstat(a
, &sta
) < 0)
6283 if (fstat(b
, &stb
) < 0)
6286 if ((sta
.st_mode
& S_IFMT
) != (stb
.st_mode
& S_IFMT
))
6289 /* We consider all device fds different, since two device fds
6290 * might refer to quite different device contexts even though
6291 * they share the same inode and backing dev_t. */
6293 if (S_ISCHR(sta
.st_mode
) || S_ISBLK(sta
.st_mode
))
6296 if (sta
.st_dev
!= stb
.st_dev
|| sta
.st_ino
!= stb
.st_ino
)
6299 /* The fds refer to the same inode on disk, let's also check
6300 * if they have the same fd flags. This is useful to
6301 * distinguish the read and write side of a pipe created with
6303 fa
= fcntl(a
, F_GETFL
);
6307 fb
= fcntl(b
, F_GETFL
);
6314 int chattr_fd(int fd
, unsigned value
, unsigned mask
) {
6315 unsigned old_attr
, new_attr
;
6320 if (fstat(fd
, &st
) < 0)
6323 /* Explicitly check whether this is a regular file or
6324 * directory. If it is anything else (such as a device node or
6325 * fifo), then the ioctl will not hit the file systems but
6326 * possibly drivers, where the ioctl might have different
6327 * effects. Notably, DRM is using the same ioctl() number. */
6329 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
6335 if (ioctl(fd
, FS_IOC_GETFLAGS
, &old_attr
) < 0)
6338 new_attr
= (old_attr
& ~mask
) | (value
& mask
);
6339 if (new_attr
== old_attr
)
6342 if (ioctl(fd
, FS_IOC_SETFLAGS
, &new_attr
) < 0)
6348 int chattr_path(const char *p
, unsigned value
, unsigned mask
) {
6349 _cleanup_close_
int fd
= -1;
6356 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
6360 return chattr_fd(fd
, value
, mask
);
6363 int read_attr_fd(int fd
, unsigned *ret
) {
6368 if (fstat(fd
, &st
) < 0)
6371 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
6374 if (ioctl(fd
, FS_IOC_GETFLAGS
, ret
) < 0)
6380 int read_attr_path(const char *p
, unsigned *ret
) {
6381 _cleanup_close_
int fd
= -1;
6386 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
6390 return read_attr_fd(fd
, ret
);
6393 static size_t nul_length(const uint8_t *p
, size_t sz
) {
6408 ssize_t
sparse_write(int fd
, const void *p
, size_t sz
, size_t run_length
) {
6409 const uint8_t *q
, *w
, *e
;
6417 n
= nul_length(q
, e
- q
);
6419 /* If there are more than the specified run length of
6420 * NUL bytes, or if this is the beginning or the end
6421 * of the buffer, then seek instead of write */
6422 if ((n
> run_length
) ||
6423 (n
> 0 && q
== p
) ||
6424 (n
> 0 && q
+ n
>= e
)) {
6426 l
= write(fd
, w
, q
- w
);
6433 if (lseek(fd
, n
, SEEK_CUR
) == (off_t
) -1)
6445 l
= write(fd
, w
, q
- w
);
6452 return q
- (const uint8_t*) p
;
6455 void sigkill_wait(pid_t
*pid
) {
6461 if (kill(*pid
, SIGKILL
) > 0)
6462 (void) wait_for_terminate(*pid
, NULL
);
6465 int syslog_parse_priority(const char **p
, int *priority
, bool with_facility
) {
6466 int a
= 0, b
= 0, c
= 0;
6476 if (!strchr(*p
, '>'))
6479 if ((*p
)[2] == '>') {
6480 c
= undecchar((*p
)[1]);
6482 } else if ((*p
)[3] == '>') {
6483 b
= undecchar((*p
)[1]);
6484 c
= undecchar((*p
)[2]);
6486 } else if ((*p
)[4] == '>') {
6487 a
= undecchar((*p
)[1]);
6488 b
= undecchar((*p
)[2]);
6489 c
= undecchar((*p
)[3]);
6494 if (a
< 0 || b
< 0 || c
< 0 ||
6495 (!with_facility
&& (a
|| b
|| c
> 7)))
6499 *priority
= a
*100 + b
*10 + c
;
6501 *priority
= (*priority
& LOG_FACMASK
) | c
;
6507 ssize_t
string_table_lookup(const char * const *table
, size_t len
, const char *key
) {
6513 for (i
= 0; i
< len
; ++i
)
6514 if (streq_ptr(table
[i
], key
))
6520 void cmsg_close_all(struct msghdr
*mh
) {
6521 struct cmsghdr
*cmsg
;
6525 CMSG_FOREACH(cmsg
, mh
)
6526 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
)
6527 close_many((int*) CMSG_DATA(cmsg
), (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int));
6530 int rename_noreplace(int olddirfd
, const char *oldpath
, int newdirfd
, const char *newpath
) {
6534 ret
= renameat2(olddirfd
, oldpath
, newdirfd
, newpath
, RENAME_NOREPLACE
);
6538 /* renameat2() exists since Linux 3.15, btrfs added support for it later.
6539 * If it is not implemented, fallback to another method. */
6540 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
6543 /* The link()/unlink() fallback does not work on directories. But
6544 * renameat() without RENAME_NOREPLACE gives the same semantics on
6545 * directories, except when newpath is an *empty* directory. This is
6547 ret
= fstatat(olddirfd
, oldpath
, &buf
, AT_SYMLINK_NOFOLLOW
);
6548 if (ret
>= 0 && S_ISDIR(buf
.st_mode
)) {
6549 ret
= renameat(olddirfd
, oldpath
, newdirfd
, newpath
);
6550 return ret
>= 0 ? 0 : -errno
;
6553 /* If it is not a directory, use the link()/unlink() fallback. */
6554 ret
= linkat(olddirfd
, oldpath
, newdirfd
, newpath
, 0);
6558 ret
= unlinkat(olddirfd
, oldpath
, 0);
6560 /* backup errno before the following unlinkat() alters it */
6562 (void) unlinkat(newdirfd
, newpath
, 0);
6570 static char *strcpy_backslash_escaped(char *t
, const char *s
, const char *bad
) {
6574 if (*s
== '\\' || strchr(bad
, *s
))
6583 char *shell_escape(const char *s
, const char *bad
) {
6586 r
= new(char, strlen(s
)*2+1);
6590 t
= strcpy_backslash_escaped(r
, s
, bad
);
6596 char *shell_maybe_quote(const char *s
) {
6602 /* Encloses a string in double quotes if necessary to make it
6603 * OK as shell string. */
6605 for (p
= s
; *p
; p
++)
6608 strchr(SHELL_NEED_QUOTES
, *p
))
6614 r
= new(char, 1+strlen(s
)*2+1+1);
6620 t
= mempcpy(t
, s
, p
- s
);
6622 t
= strcpy_backslash_escaped(t
, p
, SHELL_NEED_ESCAPE
);
6630 int parse_mode(const char *s
, mode_t
*ret
) {
6638 l
= strtol(s
, &x
, 8);
6642 if (!x
|| x
== s
|| *x
)
6644 if (l
< 0 || l
> 07777)
6651 int mount_move_root(const char *path
) {
6654 if (chdir(path
) < 0)
6657 if (mount(path
, "/", NULL
, MS_MOVE
, NULL
) < 0)
6660 if (chroot(".") < 0)
6669 int reset_uid_gid(void) {
6671 if (setgroups(0, NULL
) < 0)
6674 if (setresgid(0, 0, 0) < 0)
6677 if (setresuid(0, 0, 0) < 0)
6683 int getxattr_malloc(const char *path
, const char *name
, char **value
, bool allow_symlink
) {
6692 for (l
= 100; ; l
= (size_t) n
+ 1) {
6698 n
= lgetxattr(path
, name
, v
, l
);
6700 n
= getxattr(path
, name
, v
, l
);
6702 if (n
>= 0 && (size_t) n
< l
) {
6709 if (n
< 0 && errno
!= ERANGE
)
6713 n
= lgetxattr(path
, name
, NULL
, 0);
6715 n
= getxattr(path
, name
, NULL
, 0);
6721 int fgetxattr_malloc(int fd
, const char *name
, char **value
) {
6730 for (l
= 100; ; l
= (size_t) n
+ 1) {
6735 n
= fgetxattr(fd
, name
, v
, l
);
6737 if (n
>= 0 && (size_t) n
< l
) {
6744 if (n
< 0 && errno
!= ERANGE
)
6747 n
= fgetxattr(fd
, name
, NULL
, 0);