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 <linux/magic.h>
32 #include <linux/oom.h>
33 #include <linux/sched.h>
35 #include <netinet/ip.h>
45 #include <sys/ioctl.h>
47 #include <sys/mount.h>
48 #include <sys/personality.h>
49 #include <sys/prctl.h>
50 #include <sys/resource.h>
52 #include <sys/statvfs.h>
54 #include <sys/types.h>
55 #include <sys/utsname.h>
58 #include <sys/xattr.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
64 * POSIX version which is really broken. We prefer GNU basename(). */
68 #ifdef HAVE_SYS_AUXV_H
72 /* We include linux/fs.h as last of the system headers, as it
73 * otherwise conflicts with sys/mount.h. Yay, Linux is great! */
78 #include "device-nodes.h"
80 #include "exit-status.h"
82 #include "formats-util.h"
85 #include "hostname-util.h"
91 #include "path-util.h"
92 #include "process-util.h"
93 #include "random-util.h"
94 #include "signal-util.h"
95 #include "sparse-endian.h"
97 #include "terminal-util.h"
102 /* Put this test here for a lack of better place */
103 assert_cc(EAGAIN
== EWOULDBLOCK
);
106 char **saved_argv
= NULL
;
108 size_t page_size(void) {
109 static thread_local
size_t pgsz
= 0;
112 if (_likely_(pgsz
> 0))
115 r
= sysconf(_SC_PAGESIZE
);
122 int strcmp_ptr(const char *a
, const char *b
) {
124 /* Like strcmp(), but tries to make sense of NULL pointers */
137 bool streq_ptr(const char *a
, const char *b
) {
138 return strcmp_ptr(a
, b
) == 0;
141 char* endswith(const char *s
, const char *postfix
) {
148 pl
= strlen(postfix
);
151 return (char*) s
+ sl
;
156 if (memcmp(s
+ sl
- pl
, postfix
, pl
) != 0)
159 return (char*) s
+ sl
- pl
;
162 char* endswith_no_case(const char *s
, const char *postfix
) {
169 pl
= strlen(postfix
);
172 return (char*) s
+ sl
;
177 if (strcasecmp(s
+ sl
- pl
, postfix
) != 0)
180 return (char*) s
+ sl
- pl
;
183 char* first_word(const char *s
, const char *word
) {
190 /* Checks if the string starts with the specified word, either
191 * followed by NUL or by whitespace. Returns a pointer to the
192 * NUL or the first character after the whitespace. */
203 if (memcmp(s
, word
, wl
) != 0)
210 if (!strchr(WHITESPACE
, *p
))
213 p
+= strspn(p
, WHITESPACE
);
217 size_t cescape_char(char c
, char *buf
) {
218 char * buf_old
= buf
;
264 /* For special chars we prefer octal over
265 * hexadecimal encoding, simply because glib's
266 * g_strescape() does the same */
267 if ((c
< ' ') || (c
>= 127)) {
269 *(buf
++) = octchar((unsigned char) c
>> 6);
270 *(buf
++) = octchar((unsigned char) c
>> 3);
271 *(buf
++) = octchar((unsigned char) c
);
277 return buf
- buf_old
;
280 int close_nointr(int fd
) {
287 * Just ignore EINTR; a retry loop is the wrong thing to do on
290 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
291 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
292 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
293 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
301 int safe_close(int fd
) {
304 * Like close_nointr() but cannot fail. Guarantees errno is
305 * unchanged. Is a NOP with negative fds passed, and returns
306 * -1, so that it can be used in this syntax:
308 * fd = safe_close(fd);
314 /* The kernel might return pretty much any error code
315 * via close(), but the fd will be closed anyway. The
316 * only condition we want to check for here is whether
317 * the fd was invalid at all... */
319 assert_se(close_nointr(fd
) != -EBADF
);
325 void close_many(const int fds
[], unsigned n_fd
) {
328 assert(fds
|| n_fd
<= 0);
330 for (i
= 0; i
< n_fd
; i
++)
334 int fclose_nointr(FILE *f
) {
337 /* Same as close_nointr(), but for fclose() */
348 FILE* safe_fclose(FILE *f
) {
350 /* Same as safe_close(), but for fclose() */
355 assert_se(fclose_nointr(f
) != EBADF
);
361 DIR* safe_closedir(DIR *d
) {
366 assert_se(closedir(d
) >= 0 || errno
!= EBADF
);
372 int unlink_noerrno(const char *path
) {
383 int parse_boolean(const char *v
) {
386 if (streq(v
, "1") || strcaseeq(v
, "yes") || strcaseeq(v
, "y") || strcaseeq(v
, "true") || strcaseeq(v
, "t") || strcaseeq(v
, "on"))
388 else if (streq(v
, "0") || strcaseeq(v
, "no") || strcaseeq(v
, "n") || strcaseeq(v
, "false") || strcaseeq(v
, "f") || strcaseeq(v
, "off"))
394 int parse_pid(const char *s
, pid_t
* ret_pid
) {
395 unsigned long ul
= 0;
402 r
= safe_atolu(s
, &ul
);
408 if ((unsigned long) pid
!= ul
)
418 bool uid_is_valid(uid_t uid
) {
420 /* Some libc APIs use UID_INVALID as special placeholder */
421 if (uid
== (uid_t
) 0xFFFFFFFF)
424 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
425 if (uid
== (uid_t
) 0xFFFF)
431 int parse_uid(const char *s
, uid_t
* ret_uid
) {
432 unsigned long ul
= 0;
438 r
= safe_atolu(s
, &ul
);
444 if ((unsigned long) uid
!= ul
)
447 if (!uid_is_valid(uid
))
448 return -ENXIO
; /* we return ENXIO instead of EINVAL
449 * here, to make it easy to distuingish
450 * invalid numeric uids invalid
459 int safe_atou(const char *s
, unsigned *ret_u
) {
467 l
= strtoul(s
, &x
, 0);
469 if (!x
|| x
== s
|| *x
|| errno
)
470 return errno
> 0 ? -errno
: -EINVAL
;
472 if ((unsigned long) (unsigned) l
!= l
)
475 *ret_u
= (unsigned) l
;
479 int safe_atoi(const char *s
, int *ret_i
) {
487 l
= strtol(s
, &x
, 0);
489 if (!x
|| x
== s
|| *x
|| errno
)
490 return errno
> 0 ? -errno
: -EINVAL
;
492 if ((long) (int) l
!= l
)
499 int safe_atou8(const char *s
, uint8_t *ret
) {
507 l
= strtoul(s
, &x
, 0);
509 if (!x
|| x
== s
|| *x
|| errno
)
510 return errno
> 0 ? -errno
: -EINVAL
;
512 if ((unsigned long) (uint8_t) l
!= l
)
519 int safe_atou16(const char *s
, uint16_t *ret
) {
527 l
= strtoul(s
, &x
, 0);
529 if (!x
|| x
== s
|| *x
|| errno
)
530 return errno
> 0 ? -errno
: -EINVAL
;
532 if ((unsigned long) (uint16_t) l
!= l
)
539 int safe_atoi16(const char *s
, int16_t *ret
) {
547 l
= strtol(s
, &x
, 0);
549 if (!x
|| x
== s
|| *x
|| errno
)
550 return errno
> 0 ? -errno
: -EINVAL
;
552 if ((long) (int16_t) l
!= l
)
559 int safe_atollu(const char *s
, long long unsigned *ret_llu
) {
561 unsigned long long l
;
567 l
= strtoull(s
, &x
, 0);
569 if (!x
|| x
== s
|| *x
|| errno
)
570 return errno
? -errno
: -EINVAL
;
576 int safe_atolli(const char *s
, long long int *ret_lli
) {
584 l
= strtoll(s
, &x
, 0);
586 if (!x
|| x
== s
|| *x
|| errno
)
587 return errno
? -errno
: -EINVAL
;
593 int safe_atod(const char *s
, double *ret_d
) {
601 loc
= newlocale(LC_NUMERIC_MASK
, "C", (locale_t
) 0);
602 if (loc
== (locale_t
) 0)
606 d
= strtod_l(s
, &x
, loc
);
608 if (!x
|| x
== s
|| *x
|| errno
) {
610 return errno
? -errno
: -EINVAL
;
618 static size_t strcspn_escaped(const char *s
, const char *reject
) {
619 bool escaped
= false;
622 for (n
=0; s
[n
]; n
++) {
625 else if (s
[n
] == '\\')
627 else if (strchr(reject
, s
[n
]))
631 /* if s ends in \, return index of previous char */
635 /* Split a string into words. */
636 const char* split(const char **state
, size_t *l
, const char *separator
, bool quoted
) {
642 assert(**state
== '\0');
646 current
+= strspn(current
, separator
);
652 if (quoted
&& strchr("\'\"", *current
)) {
653 char quotechars
[2] = {*current
, '\0'};
655 *l
= strcspn_escaped(current
+ 1, quotechars
);
656 if (current
[*l
+ 1] == '\0' || current
[*l
+ 1] != quotechars
[0] ||
657 (current
[*l
+ 2] && !strchr(separator
, current
[*l
+ 2]))) {
658 /* right quote missing or garbage at the end */
662 *state
= current
++ + *l
+ 2;
664 *l
= strcspn_escaped(current
, separator
);
665 if (current
[*l
] && !strchr(separator
, current
[*l
])) {
666 /* unfinished escape */
670 *state
= current
+ *l
;
672 *l
= strcspn(current
, separator
);
673 *state
= current
+ *l
;
679 int fchmod_umask(int fd
, mode_t m
) {
684 r
= fchmod(fd
, m
& (~u
)) < 0 ? -errno
: 0;
690 char *truncate_nl(char *s
) {
693 s
[strcspn(s
, NEWLINE
)] = 0;
697 char *strnappend(const char *s
, const char *suffix
, size_t b
) {
705 return strndup(suffix
, b
);
714 if (b
> ((size_t) -1) - a
)
717 r
= new(char, a
+b
+1);
722 memcpy(r
+a
, suffix
, b
);
728 char *strappend(const char *s
, const char *suffix
) {
729 return strnappend(s
, suffix
, suffix
? strlen(suffix
) : 0);
732 int readlinkat_malloc(int fd
, const char *p
, char **ret
) {
747 n
= readlinkat(fd
, p
, c
, l
-1);
754 if ((size_t) n
< l
-1) {
765 int readlink_malloc(const char *p
, char **ret
) {
766 return readlinkat_malloc(AT_FDCWD
, p
, ret
);
769 int readlink_value(const char *p
, char **ret
) {
770 _cleanup_free_
char *link
= NULL
;
774 r
= readlink_malloc(p
, &link
);
778 value
= basename(link
);
782 value
= strdup(value
);
791 int readlink_and_make_absolute(const char *p
, char **r
) {
792 _cleanup_free_
char *target
= NULL
;
799 j
= readlink_malloc(p
, &target
);
803 k
= file_in_same_dir(p
, target
);
811 int readlink_and_canonicalize(const char *p
, char **r
) {
818 j
= readlink_and_make_absolute(p
, &t
);
822 s
= canonicalize_file_name(t
);
829 path_kill_slashes(*r
);
834 char *strstrip(char *s
) {
837 /* Drops trailing whitespace. Modifies the string in
838 * place. Returns pointer to first non-space character */
840 s
+= strspn(s
, WHITESPACE
);
842 for (e
= strchr(s
, 0); e
> s
; e
--)
843 if (!strchr(WHITESPACE
, e
[-1]))
851 char *delete_chars(char *s
, const char *bad
) {
854 /* Drops all whitespace, regardless where in the string */
856 for (f
= s
, t
= s
; *f
; f
++) {
868 char *file_in_same_dir(const char *path
, const char *filename
) {
875 /* This removes the last component of path and appends
876 * filename, unless the latter is absolute anyway or the
879 if (path_is_absolute(filename
))
880 return strdup(filename
);
882 e
= strrchr(path
, '/');
884 return strdup(filename
);
886 k
= strlen(filename
);
887 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
891 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
895 int rmdir_parents(const char *path
, const char *stop
) {
904 /* Skip trailing slashes */
905 while (l
> 0 && path
[l
-1] == '/')
911 /* Skip last component */
912 while (l
> 0 && path
[l
-1] != '/')
915 /* Skip trailing slashes */
916 while (l
> 0 && path
[l
-1] == '/')
922 if (!(t
= strndup(path
, l
)))
925 if (path_startswith(stop
, t
)) {
941 char hexchar(int x
) {
942 static const char table
[16] = "0123456789abcdef";
944 return table
[x
& 15];
947 int unhexchar(char c
) {
949 if (c
>= '0' && c
<= '9')
952 if (c
>= 'a' && c
<= 'f')
955 if (c
>= 'A' && c
<= 'F')
961 char *hexmem(const void *p
, size_t l
) {
965 z
= r
= malloc(l
* 2 + 1);
969 for (x
= p
; x
< (const uint8_t*) p
+ l
; x
++) {
970 *(z
++) = hexchar(*x
>> 4);
971 *(z
++) = hexchar(*x
& 15);
978 int unhexmem(const char *p
, size_t l
, void **mem
, size_t *len
) {
979 _cleanup_free_
uint8_t *r
= NULL
;
987 z
= r
= malloc((l
+ 1) / 2 + 1);
991 for (x
= p
; x
< p
+ l
; x
+= 2) {
997 else if (x
+1 < p
+ l
) {
1004 *(z
++) = (uint8_t) a
<< 4 | (uint8_t) b
;
1016 /* https://tools.ietf.org/html/rfc4648#section-6
1017 * Notice that base32hex differs from base32 in the alphabet it uses.
1018 * The distinction is that the base32hex representation preserves the
1019 * order of the underlying data when compared as bytestrings, this is
1020 * useful when representing NSEC3 hashes, as one can then verify the
1021 * order of hashes directly from their representation. */
1022 char base32hexchar(int x
) {
1023 static const char table
[32] = "0123456789"
1024 "ABCDEFGHIJKLMNOPQRSTUV";
1026 return table
[x
& 31];
1029 int unbase32hexchar(char c
) {
1032 if (c
>= '0' && c
<= '9')
1035 offset
= '9' - '0' + 1;
1037 if (c
>= 'A' && c
<= 'V')
1038 return c
- 'A' + offset
;
1043 char *base32hexmem(const void *p
, size_t l
, bool padding
) {
1049 /* five input bytes makes eight output bytes, padding is added so we must round up */
1050 len
= 8 * (l
+ 4) / 5;
1052 /* same, but round down as there is no padding */
1071 z
= r
= malloc(len
+ 1);
1075 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 5) * 5; x
+= 5) {
1076 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ
1077 x[3] == QQQQQQQQ; x[4] == WWWWWWWW */
1078 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1079 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1080 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1081 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1082 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
1083 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
1084 *(z
++) = base32hexchar((x
[3] & 3) << 3 | x
[4] >> 5); /* 000QQWWW */
1085 *(z
++) = base32hexchar((x
[4] & 31)); /* 000WWWWW */
1090 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1091 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1092 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1093 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1094 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
1095 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
1096 *(z
++) = base32hexchar((x
[3] & 3) << 3); /* 000QQ000 */
1103 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1104 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1105 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1106 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1107 *(z
++) = base32hexchar((x
[2] & 15) << 1); /* 000ZZZZ0 */
1117 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1118 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1119 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1120 *(z
++) = base32hexchar((x
[1] & 1) << 4); /* 000Y0000 */
1131 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1132 *(z
++) = base32hexchar((x
[0] & 7) << 2); /* 000XXX00 */
1149 int unbase32hexmem(const char *p
, size_t l
, bool padding
, void **mem
, size_t *_len
) {
1150 _cleanup_free_
uint8_t *r
= NULL
;
1151 int a
, b
, c
, d
, e
, f
, g
, h
;
1159 /* padding ensures any base32hex input has input divisible by 8 */
1160 if (padding
&& l
% 8 != 0)
1164 /* strip the padding */
1165 while (l
> 0 && p
[l
- 1] == '=' && pad
< 7) {
1171 /* a group of eight input bytes needs five output bytes, in case of
1172 padding we need to add some extra bytes */
1194 z
= r
= malloc(len
+ 1);
1198 for (x
= p
; x
< p
+ (l
/ 8) * 8; x
+= 8) {
1199 /* a == 000XXXXX; b == 000YYYYY; c == 000ZZZZZ; d == 000WWWWW
1200 e == 000SSSSS; f == 000QQQQQ; g == 000VVVVV; h == 000RRRRR */
1201 a
= unbase32hexchar(x
[0]);
1205 b
= unbase32hexchar(x
[1]);
1209 c
= unbase32hexchar(x
[2]);
1213 d
= unbase32hexchar(x
[3]);
1217 e
= unbase32hexchar(x
[4]);
1221 f
= unbase32hexchar(x
[5]);
1225 g
= unbase32hexchar(x
[6]);
1229 h
= unbase32hexchar(x
[7]);
1233 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1234 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1235 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1236 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
1237 *(z
++) = (uint8_t) g
<< 5 | (uint8_t) h
; /* VVVRRRRR */
1242 a
= unbase32hexchar(x
[0]);
1246 b
= unbase32hexchar(x
[1]);
1250 c
= unbase32hexchar(x
[2]);
1254 d
= unbase32hexchar(x
[3]);
1258 e
= unbase32hexchar(x
[4]);
1262 f
= unbase32hexchar(x
[5]);
1266 g
= unbase32hexchar(x
[6]);
1274 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1275 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1276 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1277 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
1281 a
= unbase32hexchar(x
[0]);
1285 b
= unbase32hexchar(x
[1]);
1289 c
= unbase32hexchar(x
[2]);
1293 d
= unbase32hexchar(x
[3]);
1297 e
= unbase32hexchar(x
[4]);
1305 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1306 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1307 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1311 a
= unbase32hexchar(x
[0]);
1315 b
= unbase32hexchar(x
[1]);
1319 c
= unbase32hexchar(x
[2]);
1323 d
= unbase32hexchar(x
[3]);
1331 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1332 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1336 a
= unbase32hexchar(x
[0]);
1340 b
= unbase32hexchar(x
[1]);
1348 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1366 /* https://tools.ietf.org/html/rfc4648#section-4 */
1367 char base64char(int x
) {
1368 static const char table
[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1369 "abcdefghijklmnopqrstuvwxyz"
1371 return table
[x
& 63];
1374 int unbase64char(char c
) {
1377 if (c
>= 'A' && c
<= 'Z')
1380 offset
= 'Z' - 'A' + 1;
1382 if (c
>= 'a' && c
<= 'z')
1383 return c
- 'a' + offset
;
1385 offset
+= 'z' - 'a' + 1;
1387 if (c
>= '0' && c
<= '9')
1388 return c
- '0' + offset
;
1390 offset
+= '9' - '0' + 1;
1403 char *base64mem(const void *p
, size_t l
) {
1407 /* three input bytes makes four output bytes, padding is added so we must round up */
1408 z
= r
= malloc(4 * (l
+ 2) / 3 + 1);
1412 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 3) * 3; x
+= 3) {
1413 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ */
1414 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1415 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1416 *(z
++) = base64char((x
[1] & 15) << 2 | x
[2] >> 6); /* 00YYYYZZ */
1417 *(z
++) = base64char(x
[2] & 63); /* 00ZZZZZZ */
1422 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1423 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1424 *(z
++) = base64char((x
[1] & 15) << 2); /* 00YYYY00 */
1429 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1430 *(z
++) = base64char((x
[0] & 3) << 4); /* 00XX0000 */
1441 int unbase64mem(const char *p
, size_t l
, void **mem
, size_t *_len
) {
1442 _cleanup_free_
uint8_t *r
= NULL
;
1450 /* padding ensures any base63 input has input divisible by 4 */
1454 /* strip the padding */
1455 if (l
> 0 && p
[l
- 1] == '=')
1457 if (l
> 0 && p
[l
- 1] == '=')
1460 /* a group of four input bytes needs three output bytes, in case of
1461 padding we need to add two or three extra bytes */
1462 len
= (l
/ 4) * 3 + (l
% 4 ? (l
% 4) - 1 : 0);
1464 z
= r
= malloc(len
+ 1);
1468 for (x
= p
; x
< p
+ (l
/ 4) * 4; x
+= 4) {
1469 /* a == 00XXXXXX; b == 00YYYYYY; c == 00ZZZZZZ; d == 00WWWWWW */
1470 a
= unbase64char(x
[0]);
1474 b
= unbase64char(x
[1]);
1478 c
= unbase64char(x
[2]);
1482 d
= unbase64char(x
[3]);
1486 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1487 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1488 *(z
++) = (uint8_t) c
<< 6 | (uint8_t) d
; /* ZZWWWWWW */
1493 a
= unbase64char(x
[0]);
1497 b
= unbase64char(x
[1]);
1501 c
= unbase64char(x
[2]);
1509 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1510 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1514 a
= unbase64char(x
[0]);
1518 b
= unbase64char(x
[1]);
1526 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) (b
>> 4); /* XXXXXXYY */
1545 char octchar(int x
) {
1546 return '0' + (x
& 7);
1549 int unoctchar(char c
) {
1551 if (c
>= '0' && c
<= '7')
1557 char decchar(int x
) {
1558 return '0' + (x
% 10);
1561 int undecchar(char c
) {
1563 if (c
>= '0' && c
<= '9')
1569 char *cescape(const char *s
) {
1575 /* Does C style string escaping. May be reversed with
1578 r
= new(char, strlen(s
)*4 + 1);
1582 for (f
= s
, t
= r
; *f
; f
++)
1583 t
+= cescape_char(*f
, t
);
1590 static int cunescape_one(const char *p
, size_t length
, char *ret
, uint32_t *ret_unicode
) {
1597 /* Unescapes C style. Returns the unescaped character in ret,
1598 * unless we encountered a \u sequence in which case the full
1599 * unicode character is returned in ret_unicode, instead. */
1601 if (length
!= (size_t) -1 && length
< 1)
1638 /* This is an extension of the XDG syntax files */
1643 /* hexadecimal encoding */
1646 if (length
!= (size_t) -1 && length
< 3)
1649 a
= unhexchar(p
[1]);
1653 b
= unhexchar(p
[2]);
1657 /* Don't allow NUL bytes */
1658 if (a
== 0 && b
== 0)
1661 *ret
= (char) ((a
<< 4U) | b
);
1667 /* C++11 style 16bit unicode */
1673 if (length
!= (size_t) -1 && length
< 5)
1676 for (i
= 0; i
< 4; i
++) {
1677 a
[i
] = unhexchar(p
[1 + i
]);
1682 c
= ((uint32_t) a
[0] << 12U) | ((uint32_t) a
[1] << 8U) | ((uint32_t) a
[2] << 4U) | (uint32_t) a
[3];
1684 /* Don't allow 0 chars */
1703 /* C++11 style 32bit unicode */
1709 if (length
!= (size_t) -1 && length
< 9)
1712 for (i
= 0; i
< 8; i
++) {
1713 a
[i
] = unhexchar(p
[1 + i
]);
1718 c
= ((uint32_t) a
[0] << 28U) | ((uint32_t) a
[1] << 24U) | ((uint32_t) a
[2] << 20U) | ((uint32_t) a
[3] << 16U) |
1719 ((uint32_t) a
[4] << 12U) | ((uint32_t) a
[5] << 8U) | ((uint32_t) a
[6] << 4U) | (uint32_t) a
[7];
1721 /* Don't allow 0 chars */
1725 /* Don't allow invalid code points */
1726 if (!unichar_is_valid(c
))
1751 /* octal encoding */
1755 if (length
!= (size_t) -1 && length
< 3)
1758 a
= unoctchar(p
[0]);
1762 b
= unoctchar(p
[1]);
1766 c
= unoctchar(p
[2]);
1770 /* don't allow NUL bytes */
1771 if (a
== 0 && b
== 0 && c
== 0)
1774 /* Don't allow bytes above 255 */
1775 m
= ((uint32_t) a
<< 6U) | ((uint32_t) b
<< 3U) | (uint32_t) c
;
1791 int cunescape_length_with_prefix(const char *s
, size_t length
, const char *prefix
, UnescapeFlags flags
, char **ret
) {
1799 /* Undoes C style string escaping, and optionally prefixes it. */
1801 pl
= prefix
? strlen(prefix
) : 0;
1803 r
= new(char, pl
+length
+1);
1808 memcpy(r
, prefix
, pl
);
1810 for (f
= s
, t
= r
+ pl
; f
< s
+ length
; f
++) {
1816 remaining
= s
+ length
- f
;
1817 assert(remaining
> 0);
1820 /* A literal literal, copy verbatim */
1825 if (remaining
== 1) {
1826 if (flags
& UNESCAPE_RELAX
) {
1827 /* A trailing backslash, copy verbatim */
1836 k
= cunescape_one(f
+ 1, remaining
- 1, &c
, &u
);
1838 if (flags
& UNESCAPE_RELAX
) {
1839 /* Invalid escape code, let's take it literal then */
1849 /* Non-Unicode? Let's encode this directly */
1852 /* Unicode? Then let's encode this in UTF-8 */
1853 t
+= utf8_encode_unichar(t
, u
);
1864 int cunescape_length(const char *s
, size_t length
, UnescapeFlags flags
, char **ret
) {
1865 return cunescape_length_with_prefix(s
, length
, NULL
, flags
, ret
);
1868 int cunescape(const char *s
, UnescapeFlags flags
, char **ret
) {
1869 return cunescape_length(s
, strlen(s
), flags
, ret
);
1872 char *xescape(const char *s
, const char *bad
) {
1876 /* Escapes all chars in bad, in addition to \ and all special
1877 * chars, in \xFF style escaping. May be reversed with
1880 r
= new(char, strlen(s
) * 4 + 1);
1884 for (f
= s
, t
= r
; *f
; f
++) {
1886 if ((*f
< ' ') || (*f
>= 127) ||
1887 (*f
== '\\') || strchr(bad
, *f
)) {
1890 *(t
++) = hexchar(*f
>> 4);
1891 *(t
++) = hexchar(*f
);
1901 char *ascii_strlower(char *t
) {
1906 for (p
= t
; *p
; p
++)
1907 if (*p
>= 'A' && *p
<= 'Z')
1908 *p
= *p
- 'A' + 'a';
1913 _pure_
static bool hidden_file_allow_backup(const char *filename
) {
1917 filename
[0] == '.' ||
1918 streq(filename
, "lost+found") ||
1919 streq(filename
, "aquota.user") ||
1920 streq(filename
, "aquota.group") ||
1921 endswith(filename
, ".rpmnew") ||
1922 endswith(filename
, ".rpmsave") ||
1923 endswith(filename
, ".rpmorig") ||
1924 endswith(filename
, ".dpkg-old") ||
1925 endswith(filename
, ".dpkg-new") ||
1926 endswith(filename
, ".dpkg-tmp") ||
1927 endswith(filename
, ".dpkg-dist") ||
1928 endswith(filename
, ".dpkg-bak") ||
1929 endswith(filename
, ".dpkg-backup") ||
1930 endswith(filename
, ".dpkg-remove") ||
1931 endswith(filename
, ".swp");
1934 bool hidden_file(const char *filename
) {
1937 if (endswith(filename
, "~"))
1940 return hidden_file_allow_backup(filename
);
1943 int fd_nonblock(int fd
, bool nonblock
) {
1948 flags
= fcntl(fd
, F_GETFL
, 0);
1953 nflags
= flags
| O_NONBLOCK
;
1955 nflags
= flags
& ~O_NONBLOCK
;
1957 if (nflags
== flags
)
1960 if (fcntl(fd
, F_SETFL
, nflags
) < 0)
1966 int fd_cloexec(int fd
, bool cloexec
) {
1971 flags
= fcntl(fd
, F_GETFD
, 0);
1976 nflags
= flags
| FD_CLOEXEC
;
1978 nflags
= flags
& ~FD_CLOEXEC
;
1980 if (nflags
== flags
)
1983 if (fcntl(fd
, F_SETFD
, nflags
) < 0)
1989 _pure_
static bool fd_in_set(int fd
, const int fdset
[], unsigned n_fdset
) {
1992 assert(n_fdset
== 0 || fdset
);
1994 for (i
= 0; i
< n_fdset
; i
++)
2001 int close_all_fds(const int except
[], unsigned n_except
) {
2002 _cleanup_closedir_
DIR *d
= NULL
;
2006 assert(n_except
== 0 || except
);
2008 d
= opendir("/proc/self/fd");
2013 /* When /proc isn't available (for example in chroots)
2014 * the fallback is brute forcing through the fd
2017 assert_se(getrlimit(RLIMIT_NOFILE
, &rl
) >= 0);
2018 for (fd
= 3; fd
< (int) rl
.rlim_max
; fd
++) {
2020 if (fd_in_set(fd
, except
, n_except
))
2023 if (close_nointr(fd
) < 0)
2024 if (errno
!= EBADF
&& r
== 0)
2031 while ((de
= readdir(d
))) {
2034 if (hidden_file(de
->d_name
))
2037 if (safe_atoi(de
->d_name
, &fd
) < 0)
2038 /* Let's better ignore this, just in case */
2047 if (fd_in_set(fd
, except
, n_except
))
2050 if (close_nointr(fd
) < 0) {
2051 /* Valgrind has its own FD and doesn't want to have it closed */
2052 if (errno
!= EBADF
&& r
== 0)
2060 bool chars_intersect(const char *a
, const char *b
) {
2063 /* Returns true if any of the chars in a are in b. */
2064 for (p
= a
; *p
; p
++)
2071 bool fstype_is_network(const char *fstype
) {
2072 static const char table
[] =
2087 x
= startswith(fstype
, "fuse.");
2091 return nulstr_contains(table
, fstype
);
2094 int flush_fd(int fd
) {
2095 struct pollfd pollfd
= {
2105 r
= poll(&pollfd
, 1, 0);
2115 l
= read(fd
, buf
, sizeof(buf
));
2121 if (errno
== EAGAIN
)
2130 void safe_close_pair(int p
[]) {
2134 /* Special case pairs which use the same fd in both
2136 p
[0] = p
[1] = safe_close(p
[0]);
2140 p
[0] = safe_close(p
[0]);
2141 p
[1] = safe_close(p
[1]);
2144 ssize_t
loop_read(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2151 /* If called with nbytes == 0, let's call read() at least
2152 * once, to validate the operation */
2154 if (nbytes
> (size_t) SSIZE_MAX
)
2160 k
= read(fd
, p
, nbytes
);
2165 if (errno
== EAGAIN
&& do_poll
) {
2167 /* We knowingly ignore any return value here,
2168 * and expect that any error/EOF is reported
2171 (void) fd_wait_for_event(fd
, POLLIN
, USEC_INFINITY
);
2175 return n
> 0 ? n
: -errno
;
2181 assert((size_t) k
<= nbytes
);
2186 } while (nbytes
> 0);
2191 int loop_read_exact(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2194 n
= loop_read(fd
, buf
, nbytes
, do_poll
);
2197 if ((size_t) n
!= nbytes
)
2203 int loop_write(int fd
, const void *buf
, size_t nbytes
, bool do_poll
) {
2204 const uint8_t *p
= buf
;
2209 if (nbytes
> (size_t) SSIZE_MAX
)
2215 k
= write(fd
, p
, nbytes
);
2220 if (errno
== EAGAIN
&& do_poll
) {
2221 /* We knowingly ignore any return value here,
2222 * and expect that any error/EOF is reported
2225 (void) fd_wait_for_event(fd
, POLLOUT
, USEC_INFINITY
);
2232 if (_unlikely_(nbytes
> 0 && k
== 0)) /* Can't really happen */
2235 assert((size_t) k
<= nbytes
);
2239 } while (nbytes
> 0);
2244 int parse_size(const char *t
, uint64_t base
, uint64_t *size
) {
2246 /* Soo, sometimes we want to parse IEC binary suffixes, and
2247 * sometimes SI decimal suffixes. This function can parse
2248 * both. Which one is the right way depends on the
2249 * context. Wikipedia suggests that SI is customary for
2250 * hardware metrics and network speeds, while IEC is
2251 * customary for most data sizes used by software and volatile
2252 * (RAM) memory. Hence be careful which one you pick!
2254 * In either case we use just K, M, G as suffix, and not Ki,
2255 * Mi, Gi or so (as IEC would suggest). That's because that's
2256 * frickin' ugly. But this means you really need to make sure
2257 * to document which base you are parsing when you use this
2262 unsigned long long factor
;
2265 static const struct table iec
[] = {
2266 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2267 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2268 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2269 { "G", 1024ULL*1024ULL*1024ULL },
2270 { "M", 1024ULL*1024ULL },
2276 static const struct table si
[] = {
2277 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2278 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2279 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2280 { "G", 1000ULL*1000ULL*1000ULL },
2281 { "M", 1000ULL*1000ULL },
2287 const struct table
*table
;
2289 unsigned long long r
= 0;
2290 unsigned n_entries
, start_pos
= 0;
2293 assert(base
== 1000 || base
== 1024);
2298 n_entries
= ELEMENTSOF(si
);
2301 n_entries
= ELEMENTSOF(iec
);
2306 unsigned long long l
, tmp
;
2311 p
+= strspn(p
, WHITESPACE
);
2316 l
= strtoull(p
, &e
, 10);
2325 /* strtoull() itself would accept space/+/- */
2326 if (*e
>= '0' && *e
<= '9') {
2327 unsigned long long l2
;
2330 l2
= strtoull(e
, &e2
, 10);
2334 /* Ignore failure. E.g. 10.M is valid */
2341 e
+= strspn(e
, WHITESPACE
);
2343 for (i
= start_pos
; i
< n_entries
; i
++)
2344 if (startswith(e
, table
[i
].suffix
))
2350 if (l
+ (frac
> 0) > ULLONG_MAX
/ table
[i
].factor
)
2353 tmp
= l
* table
[i
].factor
+ (unsigned long long) (frac
* table
[i
].factor
);
2354 if (tmp
> ULLONG_MAX
- r
)
2358 if ((unsigned long long) (uint64_t) r
!= r
)
2361 p
= e
+ strlen(table
[i
].suffix
);
2372 bool is_device_path(const char *path
) {
2374 /* Returns true on paths that refer to a device, either in
2375 * sysfs or in /dev */
2378 path_startswith(path
, "/dev/") ||
2379 path_startswith(path
, "/sys/");
2382 int dir_is_empty(const char *path
) {
2383 _cleanup_closedir_
DIR *d
;
2394 if (!de
&& errno
!= 0)
2400 if (!hidden_file(de
->d_name
))
2405 char* dirname_malloc(const char *path
) {
2406 char *d
, *dir
, *dir2
;
2423 void rename_process(const char name
[8]) {
2426 /* This is a like a poor man's setproctitle(). It changes the
2427 * comm field, argv[0], and also the glibc's internally used
2428 * name of the process. For the first one a limit of 16 chars
2429 * applies, to the second one usually one of 10 (i.e. length
2430 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2431 * "systemd"). If you pass a longer string it will be
2434 prctl(PR_SET_NAME
, name
);
2436 if (program_invocation_name
)
2437 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
2439 if (saved_argc
> 0) {
2443 strncpy(saved_argv
[0], name
, strlen(saved_argv
[0]));
2445 for (i
= 1; i
< saved_argc
; i
++) {
2449 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
2454 char *lookup_uid(uid_t uid
) {
2457 _cleanup_free_
char *buf
= NULL
;
2458 struct passwd pwbuf
, *pw
= NULL
;
2460 /* Shortcut things to avoid NSS lookups */
2462 return strdup("root");
2464 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
2468 buf
= malloc(bufsize
);
2472 if (getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
) == 0 && pw
)
2473 return strdup(pw
->pw_name
);
2475 if (asprintf(&name
, UID_FMT
, uid
) < 0)
2481 char* getlogname_malloc(void) {
2485 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
2490 return lookup_uid(uid
);
2493 char *getusername_malloc(void) {
2500 return lookup_uid(getuid());
2503 bool is_fs_type(const struct statfs
*s
, statfs_f_type_t magic_value
) {
2505 assert_cc(sizeof(statfs_f_type_t
) >= sizeof(s
->f_type
));
2507 return F_TYPE_EQUAL(s
->f_type
, magic_value
);
2510 int fd_check_fstype(int fd
, statfs_f_type_t magic_value
) {
2513 if (fstatfs(fd
, &s
) < 0)
2516 return is_fs_type(&s
, magic_value
);
2519 int path_check_fstype(const char *path
, statfs_f_type_t magic_value
) {
2520 _cleanup_close_
int fd
= -1;
2522 fd
= open(path
, O_RDONLY
);
2526 return fd_check_fstype(fd
, magic_value
);
2529 bool is_temporary_fs(const struct statfs
*s
) {
2530 return is_fs_type(s
, TMPFS_MAGIC
) ||
2531 is_fs_type(s
, RAMFS_MAGIC
);
2534 int fd_is_temporary_fs(int fd
) {
2537 if (fstatfs(fd
, &s
) < 0)
2540 return is_temporary_fs(&s
);
2543 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
2546 /* Under the assumption that we are running privileged we
2547 * first change the access mode and only then hand out
2548 * ownership to avoid a window where access is too open. */
2550 if (mode
!= MODE_INVALID
)
2551 if (chmod(path
, mode
) < 0)
2554 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
2555 if (chown(path
, uid
, gid
) < 0)
2561 int fchmod_and_fchown(int fd
, mode_t mode
, uid_t uid
, gid_t gid
) {
2564 /* Under the assumption that we are running privileged we
2565 * first change the access mode and only then hand out
2566 * ownership to avoid a window where access is too open. */
2568 if (mode
!= MODE_INVALID
)
2569 if (fchmod(fd
, mode
) < 0)
2572 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
2573 if (fchown(fd
, uid
, gid
) < 0)
2579 int files_same(const char *filea
, const char *fileb
) {
2582 if (stat(filea
, &a
) < 0)
2585 if (stat(fileb
, &b
) < 0)
2588 return a
.st_dev
== b
.st_dev
&&
2589 a
.st_ino
== b
.st_ino
;
2592 int running_in_chroot(void) {
2595 ret
= files_same("/proc/1/root", "/");
2602 static char *ascii_ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
2607 assert(percent
<= 100);
2608 assert(new_length
>= 3);
2610 if (old_length
<= 3 || old_length
<= new_length
)
2611 return strndup(s
, old_length
);
2613 r
= new0(char, new_length
+1);
2617 x
= (new_length
* percent
) / 100;
2619 if (x
> new_length
- 3)
2627 s
+ old_length
- (new_length
- x
- 3),
2628 new_length
- x
- 3);
2633 char *ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
2637 unsigned k
, len
, len2
;
2640 assert(percent
<= 100);
2641 assert(new_length
>= 3);
2643 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2644 if (ascii_is_valid(s
))
2645 return ascii_ellipsize_mem(s
, old_length
, new_length
, percent
);
2647 if (old_length
<= 3 || old_length
<= new_length
)
2648 return strndup(s
, old_length
);
2650 x
= (new_length
* percent
) / 100;
2652 if (x
> new_length
- 3)
2656 for (i
= s
; k
< x
&& i
< s
+ old_length
; i
= utf8_next_char(i
)) {
2659 c
= utf8_encoded_to_unichar(i
);
2662 k
+= unichar_iswide(c
) ? 2 : 1;
2665 if (k
> x
) /* last character was wide and went over quota */
2668 for (j
= s
+ old_length
; k
< new_length
&& j
> i
; ) {
2671 j
= utf8_prev_char(j
);
2672 c
= utf8_encoded_to_unichar(j
);
2675 k
+= unichar_iswide(c
) ? 2 : 1;
2679 /* we don't actually need to ellipsize */
2681 return memdup(s
, old_length
+ 1);
2683 /* make space for ellipsis */
2684 j
= utf8_next_char(j
);
2687 len2
= s
+ old_length
- j
;
2688 e
= new(char, len
+ 3 + len2
+ 1);
2693 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2694 old_length, new_length, x, len, len2, k);
2698 e
[len
] = 0xe2; /* tri-dot ellipsis: … */
2702 memcpy(e
+ len
+ 3, j
, len2
+ 1);
2707 char *ellipsize(const char *s
, size_t length
, unsigned percent
) {
2708 return ellipsize_mem(s
, strlen(s
), length
, percent
);
2711 int touch_file(const char *path
, bool parents
, usec_t stamp
, uid_t uid
, gid_t gid
, mode_t mode
) {
2712 _cleanup_close_
int fd
;
2718 mkdir_parents(path
, 0755);
2720 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, mode
> 0 ? mode
: 0644);
2725 r
= fchmod(fd
, mode
);
2730 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
) {
2731 r
= fchown(fd
, uid
, gid
);
2736 if (stamp
!= USEC_INFINITY
) {
2737 struct timespec ts
[2];
2739 timespec_store(&ts
[0], stamp
);
2741 r
= futimens(fd
, ts
);
2743 r
= futimens(fd
, NULL
);
2750 int touch(const char *path
) {
2751 return touch_file(path
, false, USEC_INFINITY
, UID_INVALID
, GID_INVALID
, 0);
2754 static char *unquote(const char *s
, const char* quotes
) {
2758 /* This is rather stupid, simply removes the heading and
2759 * trailing quotes if there is one. Doesn't care about
2760 * escaping or anything.
2762 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2768 if (strchr(quotes
, s
[0]) && s
[l
-1] == s
[0])
2769 return strndup(s
+1, l
-2);
2774 noreturn
void freeze(void) {
2776 /* Make sure nobody waits for us on a socket anymore */
2777 close_all_fds(NULL
, 0);
2785 bool null_or_empty(struct stat
*st
) {
2788 if (S_ISREG(st
->st_mode
) && st
->st_size
<= 0)
2791 if (S_ISCHR(st
->st_mode
) || S_ISBLK(st
->st_mode
))
2797 int null_or_empty_path(const char *fn
) {
2802 if (stat(fn
, &st
) < 0)
2805 return null_or_empty(&st
);
2808 int null_or_empty_fd(int fd
) {
2813 if (fstat(fd
, &st
) < 0)
2816 return null_or_empty(&st
);
2819 DIR *xopendirat(int fd
, const char *name
, int flags
) {
2823 assert(!(flags
& O_CREAT
));
2825 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
2838 static char *tag_to_udev_node(const char *tagvalue
, const char *by
) {
2839 _cleanup_free_
char *t
= NULL
, *u
= NULL
;
2842 u
= unquote(tagvalue
, QUOTES
);
2846 enc_len
= strlen(u
) * 4 + 1;
2847 t
= new(char, enc_len
);
2851 if (encode_devnode_name(u
, t
, enc_len
) < 0)
2854 return strjoin("/dev/disk/by-", by
, "/", t
, NULL
);
2857 char *fstab_node_to_udev_node(const char *p
) {
2860 if (startswith(p
, "LABEL="))
2861 return tag_to_udev_node(p
+6, "label");
2863 if (startswith(p
, "UUID="))
2864 return tag_to_udev_node(p
+5, "uuid");
2866 if (startswith(p
, "PARTUUID="))
2867 return tag_to_udev_node(p
+9, "partuuid");
2869 if (startswith(p
, "PARTLABEL="))
2870 return tag_to_udev_node(p
+10, "partlabel");
2875 bool dirent_is_file(const struct dirent
*de
) {
2878 if (hidden_file(de
->d_name
))
2881 if (de
->d_type
!= DT_REG
&&
2882 de
->d_type
!= DT_LNK
&&
2883 de
->d_type
!= DT_UNKNOWN
)
2889 bool dirent_is_file_with_suffix(const struct dirent
*de
, const char *suffix
) {
2892 if (de
->d_type
!= DT_REG
&&
2893 de
->d_type
!= DT_LNK
&&
2894 de
->d_type
!= DT_UNKNOWN
)
2897 if (hidden_file_allow_backup(de
->d_name
))
2900 return endswith(de
->d_name
, suffix
);
2903 static int do_execute(char **directories
, usec_t timeout
, char *argv
[]) {
2904 _cleanup_hashmap_free_free_ Hashmap
*pids
= NULL
;
2905 _cleanup_set_free_free_ Set
*seen
= NULL
;
2908 /* We fork this all off from a child process so that we can
2909 * somewhat cleanly make use of SIGALRM to set a time limit */
2911 (void) reset_all_signal_handlers();
2912 (void) reset_signal_mask();
2914 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
2916 pids
= hashmap_new(NULL
);
2920 seen
= set_new(&string_hash_ops
);
2924 STRV_FOREACH(directory
, directories
) {
2925 _cleanup_closedir_
DIR *d
;
2928 d
= opendir(*directory
);
2930 if (errno
== ENOENT
)
2933 return log_error_errno(errno
, "Failed to open directory %s: %m", *directory
);
2936 FOREACH_DIRENT(de
, d
, break) {
2937 _cleanup_free_
char *path
= NULL
;
2941 if (!dirent_is_file(de
))
2944 if (set_contains(seen
, de
->d_name
)) {
2945 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory
, de
->d_name
);
2949 r
= set_put_strdup(seen
, de
->d_name
);
2953 path
= strjoin(*directory
, "/", de
->d_name
, NULL
);
2957 if (null_or_empty_path(path
)) {
2958 log_debug("%s is empty (a mask).", path
);
2964 log_error_errno(errno
, "Failed to fork: %m");
2966 } else if (pid
== 0) {
2969 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
2979 return log_error_errno(errno
, "Failed to execute %s: %m", path
);
2982 log_debug("Spawned %s as " PID_FMT
".", path
, pid
);
2984 r
= hashmap_put(pids
, UINT_TO_PTR(pid
), path
);
2991 /* Abort execution of this process after the timout. We simply
2992 * rely on SIGALRM as default action terminating the process,
2993 * and turn on alarm(). */
2995 if (timeout
!= USEC_INFINITY
)
2996 alarm((timeout
+ USEC_PER_SEC
- 1) / USEC_PER_SEC
);
2998 while (!hashmap_isempty(pids
)) {
2999 _cleanup_free_
char *path
= NULL
;
3002 pid
= PTR_TO_UINT(hashmap_first_key(pids
));
3005 path
= hashmap_remove(pids
, UINT_TO_PTR(pid
));
3008 wait_for_terminate_and_warn(path
, pid
, true);
3014 void execute_directories(const char* const* directories
, usec_t timeout
, char *argv
[]) {
3018 char **dirs
= (char**) directories
;
3020 assert(!strv_isempty(dirs
));
3022 name
= basename(dirs
[0]);
3023 assert(!isempty(name
));
3025 /* Executes all binaries in the directories in parallel and waits
3026 * for them to finish. Optionally a timeout is applied. If a file
3027 * with the same name exists in more than one directory, the
3028 * earliest one wins. */
3030 executor_pid
= fork();
3031 if (executor_pid
< 0) {
3032 log_error_errno(errno
, "Failed to fork: %m");
3035 } else if (executor_pid
== 0) {
3036 r
= do_execute(dirs
, timeout
, argv
);
3037 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
3040 wait_for_terminate_and_warn(name
, executor_pid
, true);
3043 bool nulstr_contains(const char*nulstr
, const char *needle
) {
3049 NULSTR_FOREACH(i
, nulstr
)
3050 if (streq(i
, needle
))
3056 bool plymouth_running(void) {
3057 return access("/run/plymouth/pid", F_OK
) >= 0;
3060 char* strshorten(char *s
, size_t l
) {
3069 int pipe_eof(int fd
) {
3070 struct pollfd pollfd
= {
3072 .events
= POLLIN
|POLLHUP
,
3077 r
= poll(&pollfd
, 1, 0);
3084 return pollfd
.revents
& POLLHUP
;
3087 int fd_wait_for_event(int fd
, int event
, usec_t t
) {
3089 struct pollfd pollfd
= {
3097 r
= ppoll(&pollfd
, 1, t
== USEC_INFINITY
? NULL
: timespec_store(&ts
, t
), NULL
);
3104 return pollfd
.revents
;
3107 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
3116 r
= tempfn_xxxxxx(path
, NULL
, &t
);
3120 fd
= mkostemp_safe(t
, O_WRONLY
|O_CLOEXEC
);
3126 f
= fdopen(fd
, "we");
3140 int symlink_atomic(const char *from
, const char *to
) {
3141 _cleanup_free_
char *t
= NULL
;
3147 r
= tempfn_random(to
, NULL
, &t
);
3151 if (symlink(from
, t
) < 0)
3154 if (rename(t
, to
) < 0) {
3162 int symlink_idempotent(const char *from
, const char *to
) {
3163 _cleanup_free_
char *p
= NULL
;
3169 if (symlink(from
, to
) < 0) {
3170 if (errno
!= EEXIST
)
3173 r
= readlink_malloc(to
, &p
);
3177 if (!streq(p
, from
))
3184 int mknod_atomic(const char *path
, mode_t mode
, dev_t dev
) {
3185 _cleanup_free_
char *t
= NULL
;
3190 r
= tempfn_random(path
, NULL
, &t
);
3194 if (mknod(t
, mode
, dev
) < 0)
3197 if (rename(t
, path
) < 0) {
3205 int mkfifo_atomic(const char *path
, mode_t mode
) {
3206 _cleanup_free_
char *t
= NULL
;
3211 r
= tempfn_random(path
, NULL
, &t
);
3215 if (mkfifo(t
, mode
) < 0)
3218 if (rename(t
, path
) < 0) {
3226 bool display_is_local(const char *display
) {
3230 display
[0] == ':' &&
3231 display
[1] >= '0' &&
3235 int socket_from_display(const char *display
, char **path
) {
3242 if (!display_is_local(display
))
3245 k
= strspn(display
+1, "0123456789");
3247 f
= new(char, strlen("/tmp/.X11-unix/X") + k
+ 1);
3251 c
= stpcpy(f
, "/tmp/.X11-unix/X");
3252 memcpy(c
, display
+1, k
);
3261 const char **username
,
3262 uid_t
*uid
, gid_t
*gid
,
3264 const char **shell
) {
3272 /* We enforce some special rules for uid=0: in order to avoid
3273 * NSS lookups for root we hardcode its data. */
3275 if (streq(*username
, "root") || streq(*username
, "0")) {
3293 if (parse_uid(*username
, &u
) >= 0) {
3297 /* If there are multiple users with the same id, make
3298 * sure to leave $USER to the configured value instead
3299 * of the first occurrence in the database. However if
3300 * the uid was configured by a numeric uid, then let's
3301 * pick the real username from /etc/passwd. */
3303 *username
= p
->pw_name
;
3306 p
= getpwnam(*username
);
3310 return errno
> 0 ? -errno
: -ESRCH
;
3322 *shell
= p
->pw_shell
;
3327 char* uid_to_name(uid_t uid
) {
3332 return strdup("root");
3336 return strdup(p
->pw_name
);
3338 if (asprintf(&r
, UID_FMT
, uid
) < 0)
3344 char* gid_to_name(gid_t gid
) {
3349 return strdup("root");
3353 return strdup(p
->gr_name
);
3355 if (asprintf(&r
, GID_FMT
, gid
) < 0)
3361 int get_group_creds(const char **groupname
, gid_t
*gid
) {
3367 /* We enforce some special rules for gid=0: in order to avoid
3368 * NSS lookups for root we hardcode its data. */
3370 if (streq(*groupname
, "root") || streq(*groupname
, "0")) {
3371 *groupname
= "root";
3379 if (parse_gid(*groupname
, &id
) >= 0) {
3384 *groupname
= g
->gr_name
;
3387 g
= getgrnam(*groupname
);
3391 return errno
> 0 ? -errno
: -ESRCH
;
3399 int in_gid(gid_t gid
) {
3401 int ngroups_max
, r
, i
;
3403 if (getgid() == gid
)
3406 if (getegid() == gid
)
3409 ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
3410 assert(ngroups_max
> 0);
3412 gids
= alloca(sizeof(gid_t
) * ngroups_max
);
3414 r
= getgroups(ngroups_max
, gids
);
3418 for (i
= 0; i
< r
; i
++)
3425 int in_group(const char *name
) {
3429 r
= get_group_creds(&name
, &gid
);
3436 int glob_exists(const char *path
) {
3437 _cleanup_globfree_ glob_t g
= {};
3443 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
3445 if (k
== GLOB_NOMATCH
)
3447 else if (k
== GLOB_NOSPACE
)
3450 return !strv_isempty(g
.gl_pathv
);
3452 return errno
? -errno
: -EIO
;
3455 int glob_extend(char ***strv
, const char *path
) {
3456 _cleanup_globfree_ glob_t g
= {};
3461 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
3463 if (k
== GLOB_NOMATCH
)
3465 else if (k
== GLOB_NOSPACE
)
3467 else if (k
!= 0 || strv_isempty(g
.gl_pathv
))
3468 return errno
? -errno
: -EIO
;
3470 STRV_FOREACH(p
, g
.gl_pathv
) {
3471 k
= strv_extend(strv
, *p
);
3479 int dirent_ensure_type(DIR *d
, struct dirent
*de
) {
3485 if (de
->d_type
!= DT_UNKNOWN
)
3488 if (fstatat(dirfd(d
), de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
3492 S_ISREG(st
.st_mode
) ? DT_REG
:
3493 S_ISDIR(st
.st_mode
) ? DT_DIR
:
3494 S_ISLNK(st
.st_mode
) ? DT_LNK
:
3495 S_ISFIFO(st
.st_mode
) ? DT_FIFO
:
3496 S_ISSOCK(st
.st_mode
) ? DT_SOCK
:
3497 S_ISCHR(st
.st_mode
) ? DT_CHR
:
3498 S_ISBLK(st
.st_mode
) ? DT_BLK
:
3504 int get_files_in_directory(const char *path
, char ***list
) {
3505 _cleanup_closedir_
DIR *d
= NULL
;
3506 size_t bufsize
= 0, n
= 0;
3507 _cleanup_strv_free_
char **l
= NULL
;
3511 /* Returns all files in a directory in *list, and the number
3512 * of files as return value. If list is NULL returns only the
3524 if (!de
&& errno
!= 0)
3529 dirent_ensure_type(d
, de
);
3531 if (!dirent_is_file(de
))
3535 /* one extra slot is needed for the terminating NULL */
3536 if (!GREEDY_REALLOC(l
, bufsize
, n
+ 2))
3539 l
[n
] = strdup(de
->d_name
);
3550 l
= NULL
; /* avoid freeing */
3556 char *strjoin(const char *x
, ...) {
3570 t
= va_arg(ap
, const char *);
3575 if (n
> ((size_t) -1) - l
) {
3599 t
= va_arg(ap
, const char *);
3613 bool is_main_thread(void) {
3614 static thread_local
int cached
= 0;
3616 if (_unlikely_(cached
== 0))
3617 cached
= getpid() == gettid() ? 1 : -1;
3622 int block_get_whole_disk(dev_t d
, dev_t
*ret
) {
3629 /* If it has a queue this is good enough for us */
3630 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", major(d
), minor(d
)) < 0)
3633 r
= access(p
, F_OK
);
3641 /* If it is a partition find the originating device */
3642 if (asprintf(&p
, "/sys/dev/block/%u:%u/partition", major(d
), minor(d
)) < 0)
3645 r
= access(p
, F_OK
);
3651 /* Get parent dev_t */
3652 if (asprintf(&p
, "/sys/dev/block/%u:%u/../dev", major(d
), minor(d
)) < 0)
3655 r
= read_one_line_file(p
, &s
);
3661 r
= sscanf(s
, "%u:%u", &m
, &n
);
3667 /* Only return this if it is really good enough for us. */
3668 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", m
, n
) < 0)
3671 r
= access(p
, F_OK
);
3675 *ret
= makedev(m
, n
);
3682 static const char *const ioprio_class_table
[] = {
3683 [IOPRIO_CLASS_NONE
] = "none",
3684 [IOPRIO_CLASS_RT
] = "realtime",
3685 [IOPRIO_CLASS_BE
] = "best-effort",
3686 [IOPRIO_CLASS_IDLE
] = "idle"
3689 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, INT_MAX
);
3691 static const char *const sigchld_code_table
[] = {
3692 [CLD_EXITED
] = "exited",
3693 [CLD_KILLED
] = "killed",
3694 [CLD_DUMPED
] = "dumped",
3695 [CLD_TRAPPED
] = "trapped",
3696 [CLD_STOPPED
] = "stopped",
3697 [CLD_CONTINUED
] = "continued",
3700 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
3702 static const char *const log_facility_unshifted_table
[LOG_NFACILITIES
] = {
3703 [LOG_FAC(LOG_KERN
)] = "kern",
3704 [LOG_FAC(LOG_USER
)] = "user",
3705 [LOG_FAC(LOG_MAIL
)] = "mail",
3706 [LOG_FAC(LOG_DAEMON
)] = "daemon",
3707 [LOG_FAC(LOG_AUTH
)] = "auth",
3708 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
3709 [LOG_FAC(LOG_LPR
)] = "lpr",
3710 [LOG_FAC(LOG_NEWS
)] = "news",
3711 [LOG_FAC(LOG_UUCP
)] = "uucp",
3712 [LOG_FAC(LOG_CRON
)] = "cron",
3713 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
3714 [LOG_FAC(LOG_FTP
)] = "ftp",
3715 [LOG_FAC(LOG_LOCAL0
)] = "local0",
3716 [LOG_FAC(LOG_LOCAL1
)] = "local1",
3717 [LOG_FAC(LOG_LOCAL2
)] = "local2",
3718 [LOG_FAC(LOG_LOCAL3
)] = "local3",
3719 [LOG_FAC(LOG_LOCAL4
)] = "local4",
3720 [LOG_FAC(LOG_LOCAL5
)] = "local5",
3721 [LOG_FAC(LOG_LOCAL6
)] = "local6",
3722 [LOG_FAC(LOG_LOCAL7
)] = "local7"
3725 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted
, int, LOG_FAC(~0));
3727 bool log_facility_unshifted_is_valid(int facility
) {
3728 return facility
>= 0 && facility
<= LOG_FAC(~0);
3731 static const char *const log_level_table
[] = {
3732 [LOG_EMERG
] = "emerg",
3733 [LOG_ALERT
] = "alert",
3734 [LOG_CRIT
] = "crit",
3736 [LOG_WARNING
] = "warning",
3737 [LOG_NOTICE
] = "notice",
3738 [LOG_INFO
] = "info",
3739 [LOG_DEBUG
] = "debug"
3742 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level
, int, LOG_DEBUG
);
3744 bool log_level_is_valid(int level
) {
3745 return level
>= 0 && level
<= LOG_DEBUG
;
3748 static const char* const sched_policy_table
[] = {
3749 [SCHED_OTHER
] = "other",
3750 [SCHED_BATCH
] = "batch",
3751 [SCHED_IDLE
] = "idle",
3752 [SCHED_FIFO
] = "fifo",
3756 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);
3758 static const char* const rlimit_table
[_RLIMIT_MAX
] = {
3759 [RLIMIT_CPU
] = "LimitCPU",
3760 [RLIMIT_FSIZE
] = "LimitFSIZE",
3761 [RLIMIT_DATA
] = "LimitDATA",
3762 [RLIMIT_STACK
] = "LimitSTACK",
3763 [RLIMIT_CORE
] = "LimitCORE",
3764 [RLIMIT_RSS
] = "LimitRSS",
3765 [RLIMIT_NOFILE
] = "LimitNOFILE",
3766 [RLIMIT_AS
] = "LimitAS",
3767 [RLIMIT_NPROC
] = "LimitNPROC",
3768 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
3769 [RLIMIT_LOCKS
] = "LimitLOCKS",
3770 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
3771 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
3772 [RLIMIT_NICE
] = "LimitNICE",
3773 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
3774 [RLIMIT_RTTIME
] = "LimitRTTIME"
3777 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
3779 static const char* const ip_tos_table
[] = {
3780 [IPTOS_LOWDELAY
] = "low-delay",
3781 [IPTOS_THROUGHPUT
] = "throughput",
3782 [IPTOS_RELIABILITY
] = "reliability",
3783 [IPTOS_LOWCOST
] = "low-cost",
3786 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
3788 bool kexec_loaded(void) {
3789 bool loaded
= false;
3792 if (read_one_line_file("/sys/kernel/kexec_loaded", &s
) >= 0) {
3800 int prot_from_flags(int flags
) {
3802 switch (flags
& O_ACCMODE
) {
3811 return PROT_READ
|PROT_WRITE
;
3818 char *format_bytes(char *buf
, size_t l
, uint64_t t
) {
3821 static const struct {
3825 { "E", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3826 { "P", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3827 { "T", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3828 { "G", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3829 { "M", UINT64_C(1024)*UINT64_C(1024) },
3830 { "K", UINT64_C(1024) },
3833 if (t
== (uint64_t) -1)
3836 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
3838 if (t
>= table
[i
].factor
) {
3840 "%" PRIu64
".%" PRIu64
"%s",
3841 t
/ table
[i
].factor
,
3842 ((t
*UINT64_C(10)) / table
[i
].factor
) % UINT64_C(10),
3849 snprintf(buf
, l
, "%" PRIu64
"B", t
);
3857 void* memdup(const void *p
, size_t l
) {
3870 int fd_inc_sndbuf(int fd
, size_t n
) {
3872 socklen_t l
= sizeof(value
);
3874 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
3875 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
3878 /* If we have the privileges we will ignore the kernel limit. */
3881 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
3882 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
3888 int fd_inc_rcvbuf(int fd
, size_t n
) {
3890 socklen_t l
= sizeof(value
);
3892 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
3893 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
3896 /* If we have the privileges we will ignore the kernel limit. */
3899 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
3900 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
3905 int fork_agent(pid_t
*pid
, const int except
[], unsigned n_except
, const char *path
, ...) {
3906 bool stdout_is_tty
, stderr_is_tty
;
3907 pid_t parent_pid
, agent_pid
;
3908 sigset_t ss
, saved_ss
;
3916 /* Spawns a temporary TTY agent, making sure it goes away when
3919 parent_pid
= getpid();
3921 /* First we temporarily block all signals, so that the new
3922 * child has them blocked initially. This way, we can be sure
3923 * that SIGTERMs are not lost we might send to the agent. */
3924 assert_se(sigfillset(&ss
) >= 0);
3925 assert_se(sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) >= 0);
3928 if (agent_pid
< 0) {
3929 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
3933 if (agent_pid
!= 0) {
3934 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
3941 * Make sure the agent goes away when the parent dies */
3942 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
3943 _exit(EXIT_FAILURE
);
3945 /* Make sure we actually can kill the agent, if we need to, in
3946 * case somebody invoked us from a shell script that trapped
3947 * SIGTERM or so... */
3948 (void) reset_all_signal_handlers();
3949 (void) reset_signal_mask();
3951 /* Check whether our parent died before we were able
3952 * to set the death signal and unblock the signals */
3953 if (getppid() != parent_pid
)
3954 _exit(EXIT_SUCCESS
);
3956 /* Don't leak fds to the agent */
3957 close_all_fds(except
, n_except
);
3959 stdout_is_tty
= isatty(STDOUT_FILENO
);
3960 stderr_is_tty
= isatty(STDERR_FILENO
);
3962 if (!stdout_is_tty
|| !stderr_is_tty
) {
3965 /* Detach from stdout/stderr. and reopen
3966 * /dev/tty for them. This is important to
3967 * ensure that when systemctl is started via
3968 * popen() or a similar call that expects to
3969 * read EOF we actually do generate EOF and
3970 * not delay this indefinitely by because we
3971 * keep an unused copy of stdin around. */
3972 fd
= open("/dev/tty", O_WRONLY
);
3974 log_error_errno(errno
, "Failed to open /dev/tty: %m");
3975 _exit(EXIT_FAILURE
);
3979 dup2(fd
, STDOUT_FILENO
);
3982 dup2(fd
, STDERR_FILENO
);
3988 /* Count arguments */
3990 for (n
= 0; va_arg(ap
, char*); n
++)
3995 l
= alloca(sizeof(char *) * (n
+ 1));
3997 /* Fill in arguments */
3999 for (i
= 0; i
<= n
; i
++)
4000 l
[i
] = va_arg(ap
, char*);
4004 _exit(EXIT_FAILURE
);
4007 int setrlimit_closest(int resource
, const struct rlimit
*rlim
) {
4008 struct rlimit highest
, fixed
;
4012 if (setrlimit(resource
, rlim
) >= 0)
4018 /* So we failed to set the desired setrlimit, then let's try
4019 * to get as close as we can */
4020 assert_se(getrlimit(resource
, &highest
) == 0);
4022 fixed
.rlim_cur
= MIN(rlim
->rlim_cur
, highest
.rlim_max
);
4023 fixed
.rlim_max
= MIN(rlim
->rlim_max
, highest
.rlim_max
);
4025 if (setrlimit(resource
, &fixed
) < 0)
4031 bool http_etag_is_valid(const char *etag
) {
4035 if (!endswith(etag
, "\""))
4038 if (!startswith(etag
, "\"") && !startswith(etag
, "W/\""))
4044 bool http_url_is_valid(const char *url
) {
4050 p
= startswith(url
, "http://");
4052 p
= startswith(url
, "https://");
4059 return ascii_is_valid(p
);
4062 bool documentation_url_is_valid(const char *url
) {
4068 if (http_url_is_valid(url
))
4071 p
= startswith(url
, "file:/");
4073 p
= startswith(url
, "info:");
4075 p
= startswith(url
, "man:");
4080 return ascii_is_valid(p
);
4083 bool in_initrd(void) {
4084 static int saved
= -1;
4090 /* We make two checks here:
4092 * 1. the flag file /etc/initrd-release must exist
4093 * 2. the root file system must be a memory file system
4095 * The second check is extra paranoia, since misdetecting an
4096 * initrd can have bad bad consequences due the initrd
4097 * emptying when transititioning to the main systemd.
4100 saved
= access("/etc/initrd-release", F_OK
) >= 0 &&
4101 statfs("/", &s
) >= 0 &&
4102 is_temporary_fs(&s
);
4107 int get_home_dir(char **_h
) {
4115 /* Take the user specified one */
4116 e
= secure_getenv("HOME");
4117 if (e
&& path_is_absolute(e
)) {
4126 /* Hardcode home directory for root to avoid NSS */
4129 h
= strdup("/root");
4137 /* Check the database... */
4141 return errno
> 0 ? -errno
: -ESRCH
;
4143 if (!path_is_absolute(p
->pw_dir
))
4146 h
= strdup(p
->pw_dir
);
4154 int get_shell(char **_s
) {
4162 /* Take the user specified one */
4163 e
= getenv("SHELL");
4173 /* Hardcode home directory for root to avoid NSS */
4176 s
= strdup("/bin/sh");
4184 /* Check the database... */
4188 return errno
> 0 ? -errno
: -ESRCH
;
4190 if (!path_is_absolute(p
->pw_shell
))
4193 s
= strdup(p
->pw_shell
);
4201 bool filename_is_valid(const char *p
) {
4215 if (strlen(p
) > FILENAME_MAX
)
4221 bool string_is_safe(const char *p
) {
4227 for (t
= p
; *t
; t
++) {
4228 if (*t
> 0 && *t
< ' ')
4231 if (strchr("\\\"\'\x7f", *t
))
4239 * Check if a string contains control characters. If 'ok' is non-NULL
4240 * it may be a string containing additional CCs to be considered OK.
4242 bool string_has_cc(const char *p
, const char *ok
) {
4247 for (t
= p
; *t
; t
++) {
4248 if (ok
&& strchr(ok
, *t
))
4251 if (*t
> 0 && *t
< ' ')
4261 bool path_is_safe(const char *p
) {
4266 if (streq(p
, "..") || startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
4269 if (strlen(p
)+1 > PATH_MAX
)
4272 /* The following two checks are not really dangerous, but hey, they still are confusing */
4273 if (streq(p
, ".") || startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
4276 if (strstr(p
, "//"))
4282 /* hey glibc, APIs with callbacks without a user pointer are so useless */
4283 void *xbsearch_r(const void *key
, const void *base
, size_t nmemb
, size_t size
,
4284 int (*compar
) (const void *, const void *, void *), void *arg
) {
4293 p
= (void *)(((const char *) base
) + (idx
* size
));
4294 comparison
= compar(key
, p
, arg
);
4297 else if (comparison
> 0)
4305 void init_gettext(void) {
4306 setlocale(LC_ALL
, "");
4307 textdomain(GETTEXT_PACKAGE
);
4310 bool is_locale_utf8(void) {
4312 static int cached_answer
= -1;
4314 if (cached_answer
>= 0)
4317 if (!setlocale(LC_ALL
, "")) {
4318 cached_answer
= true;
4322 set
= nl_langinfo(CODESET
);
4324 cached_answer
= true;
4328 if (streq(set
, "UTF-8")) {
4329 cached_answer
= true;
4333 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
4334 * unset and everything can do to UTF-8 nowadays. */
4335 set
= setlocale(LC_CTYPE
, NULL
);
4337 cached_answer
= true;
4341 /* Check result, but ignore the result if C was set
4344 STR_IN_SET(set
, "C", "POSIX") &&
4345 !getenv("LC_ALL") &&
4346 !getenv("LC_CTYPE") &&
4350 return (bool) cached_answer
;
4353 const char *draw_special_char(DrawSpecialChar ch
) {
4354 static const char *draw_table
[2][_DRAW_SPECIAL_CHAR_MAX
] = {
4357 [DRAW_TREE_VERTICAL
] = "\342\224\202 ", /* │ */
4358 [DRAW_TREE_BRANCH
] = "\342\224\234\342\224\200", /* ├─ */
4359 [DRAW_TREE_RIGHT
] = "\342\224\224\342\224\200", /* └─ */
4360 [DRAW_TREE_SPACE
] = " ", /* */
4361 [DRAW_TRIANGULAR_BULLET
] = "\342\200\243", /* ‣ */
4362 [DRAW_BLACK_CIRCLE
] = "\342\227\217", /* ● */
4363 [DRAW_ARROW
] = "\342\206\222", /* → */
4364 [DRAW_DASH
] = "\342\200\223", /* – */
4367 /* ASCII fallback */ {
4368 [DRAW_TREE_VERTICAL
] = "| ",
4369 [DRAW_TREE_BRANCH
] = "|-",
4370 [DRAW_TREE_RIGHT
] = "`-",
4371 [DRAW_TREE_SPACE
] = " ",
4372 [DRAW_TRIANGULAR_BULLET
] = ">",
4373 [DRAW_BLACK_CIRCLE
] = "*",
4374 [DRAW_ARROW
] = "->",
4379 return draw_table
[!is_locale_utf8()][ch
];
4382 char *strreplace(const char *text
, const char *old_string
, const char *new_string
) {
4385 size_t l
, old_len
, new_len
;
4391 old_len
= strlen(old_string
);
4392 new_len
= strlen(new_string
);
4405 if (!startswith(f
, old_string
)) {
4411 nl
= l
- old_len
+ new_len
;
4412 a
= realloc(r
, nl
+ 1);
4420 t
= stpcpy(t
, new_string
);
4432 char *strip_tab_ansi(char **ibuf
, size_t *_isz
) {
4433 const char *i
, *begin
= NULL
;
4438 } state
= STATE_OTHER
;
4440 size_t osz
= 0, isz
;
4446 /* Strips ANSI color and replaces TABs by 8 spaces */
4448 isz
= _isz
? *_isz
: strlen(*ibuf
);
4450 f
= open_memstream(&obuf
, &osz
);
4454 for (i
= *ibuf
; i
< *ibuf
+ isz
+ 1; i
++) {
4459 if (i
>= *ibuf
+ isz
) /* EOT */
4461 else if (*i
== '\x1B')
4462 state
= STATE_ESCAPE
;
4463 else if (*i
== '\t')
4470 if (i
>= *ibuf
+ isz
) { /* EOT */
4473 } else if (*i
== '[') {
4474 state
= STATE_BRACKET
;
4479 state
= STATE_OTHER
;
4486 if (i
>= *ibuf
+ isz
|| /* EOT */
4487 (!(*i
>= '0' && *i
<= '9') && *i
!= ';' && *i
!= 'm')) {
4490 state
= STATE_OTHER
;
4492 } else if (*i
== 'm')
4493 state
= STATE_OTHER
;
4515 int on_ac_power(void) {
4516 bool found_offline
= false, found_online
= false;
4517 _cleanup_closedir_
DIR *d
= NULL
;
4519 d
= opendir("/sys/class/power_supply");
4521 return errno
== ENOENT
? true : -errno
;
4525 _cleanup_close_
int fd
= -1, device
= -1;
4531 if (!de
&& errno
!= 0)
4537 if (hidden_file(de
->d_name
))
4540 device
= openat(dirfd(d
), de
->d_name
, O_DIRECTORY
|O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4542 if (errno
== ENOENT
|| errno
== ENOTDIR
)
4548 fd
= openat(device
, "type", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4550 if (errno
== ENOENT
)
4556 n
= read(fd
, contents
, sizeof(contents
));
4560 if (n
!= 6 || memcmp(contents
, "Mains\n", 6))
4564 fd
= openat(device
, "online", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4566 if (errno
== ENOENT
)
4572 n
= read(fd
, contents
, sizeof(contents
));
4576 if (n
!= 2 || contents
[1] != '\n')
4579 if (contents
[0] == '1') {
4580 found_online
= true;
4582 } else if (contents
[0] == '0')
4583 found_offline
= true;
4588 return found_online
|| !found_offline
;
4591 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
4598 if (!path_strv_resolve_uniq(search
, root
))
4601 STRV_FOREACH(i
, search
) {
4602 _cleanup_free_
char *p
= NULL
;
4606 p
= strjoin(root
, *i
, "/", path
, NULL
);
4608 p
= strjoin(*i
, "/", path
, NULL
);
4618 if (errno
!= ENOENT
)
4625 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
4626 _cleanup_strv_free_
char **copy
= NULL
;
4632 if (path_is_absolute(path
)) {
4635 f
= fopen(path
, mode
);
4644 copy
= strv_copy((char**) search
);
4648 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
4651 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
4652 _cleanup_strv_free_
char **s
= NULL
;
4654 if (path_is_absolute(path
)) {
4657 f
= fopen(path
, mode
);
4666 s
= strv_split_nulstr(search
);
4670 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
4673 char *strextend(char **x
, ...) {
4680 l
= f
= *x
? strlen(*x
) : 0;
4687 t
= va_arg(ap
, const char *);
4692 if (n
> ((size_t) -1) - l
) {
4701 r
= realloc(*x
, l
+1);
4711 t
= va_arg(ap
, const char *);
4725 char *strrep(const char *s
, unsigned n
) {
4733 p
= r
= malloc(l
* n
+ 1);
4737 for (i
= 0; i
< n
; i
++)
4744 void* greedy_realloc(void **p
, size_t *allocated
, size_t need
, size_t size
) {
4751 if (*allocated
>= need
)
4754 newalloc
= MAX(need
* 2, 64u / size
);
4755 a
= newalloc
* size
;
4757 /* check for overflows */
4758 if (a
< size
* need
)
4766 *allocated
= newalloc
;
4770 void* greedy_realloc0(void **p
, size_t *allocated
, size_t need
, size_t size
) {
4779 q
= greedy_realloc(p
, allocated
, need
, size
);
4783 if (*allocated
> prev
)
4784 memzero(q
+ prev
* size
, (*allocated
- prev
) * size
);
4789 bool id128_is_valid(const char *s
) {
4795 /* Simple formatted 128bit hex string */
4797 for (i
= 0; i
< l
; i
++) {
4800 if (!(c
>= '0' && c
<= '9') &&
4801 !(c
>= 'a' && c
<= 'z') &&
4802 !(c
>= 'A' && c
<= 'Z'))
4806 } else if (l
== 36) {
4808 /* Formatted UUID */
4810 for (i
= 0; i
< l
; i
++) {
4813 if ((i
== 8 || i
== 13 || i
== 18 || i
== 23)) {
4817 if (!(c
>= '0' && c
<= '9') &&
4818 !(c
>= 'a' && c
<= 'z') &&
4819 !(c
>= 'A' && c
<= 'Z'))
4830 int split_pair(const char *s
, const char *sep
, char **l
, char **r
) {
4845 a
= strndup(s
, x
- s
);
4849 b
= strdup(x
+ strlen(sep
));
4861 int shall_restore_state(void) {
4862 _cleanup_free_
char *value
= NULL
;
4865 r
= get_proc_cmdline_key("systemd.restore_state=", &value
);
4871 return parse_boolean(value
) != 0;
4874 int proc_cmdline(char **ret
) {
4877 if (detect_container() > 0)
4878 return get_process_cmdline(1, 0, false, ret
);
4880 return read_one_line_file("/proc/cmdline", ret
);
4883 int parse_proc_cmdline(int (*parse_item
)(const char *key
, const char *value
)) {
4884 _cleanup_free_
char *line
= NULL
;
4890 r
= proc_cmdline(&line
);
4896 _cleanup_free_
char *word
= NULL
;
4899 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
4905 /* Filter out arguments that are intended only for the
4907 if (!in_initrd() && startswith(word
, "rd."))
4910 value
= strchr(word
, '=');
4914 r
= parse_item(word
, value
);
4922 int get_proc_cmdline_key(const char *key
, char **value
) {
4923 _cleanup_free_
char *line
= NULL
, *ret
= NULL
;
4930 r
= proc_cmdline(&line
);
4936 _cleanup_free_
char *word
= NULL
;
4939 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
4945 /* Filter out arguments that are intended only for the
4947 if (!in_initrd() && startswith(word
, "rd."))
4951 e
= startswith(word
, key
);
4955 r
= free_and_strdup(&ret
, e
);
4961 if (streq(word
, key
))
4975 int container_get_leader(const char *machine
, pid_t
*pid
) {
4976 _cleanup_free_
char *s
= NULL
, *class = NULL
;
4984 if (!machine_name_is_valid(machine
))
4987 p
= strjoina("/run/systemd/machines/", machine
);
4988 r
= parse_env_file(p
, NEWLINE
, "LEADER", &s
, "CLASS", &class, NULL
);
4996 if (!streq_ptr(class, "container"))
4999 r
= parse_pid(s
, &leader
);
5009 int namespace_open(pid_t pid
, int *pidns_fd
, int *mntns_fd
, int *netns_fd
, int *userns_fd
, int *root_fd
) {
5010 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, netnsfd
= -1, usernsfd
= -1;
5018 mntns
= procfs_file_alloca(pid
, "ns/mnt");
5019 mntnsfd
= open(mntns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5027 pidns
= procfs_file_alloca(pid
, "ns/pid");
5028 pidnsfd
= open(pidns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5036 netns
= procfs_file_alloca(pid
, "ns/net");
5037 netnsfd
= open(netns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5045 userns
= procfs_file_alloca(pid
, "ns/user");
5046 usernsfd
= open(userns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5047 if (usernsfd
< 0 && errno
!= ENOENT
)
5054 root
= procfs_file_alloca(pid
, "root");
5055 rfd
= open(root
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
|O_DIRECTORY
);
5061 *pidns_fd
= pidnsfd
;
5064 *mntns_fd
= mntnsfd
;
5067 *netns_fd
= netnsfd
;
5070 *userns_fd
= usernsfd
;
5075 pidnsfd
= mntnsfd
= netnsfd
= usernsfd
= -1;
5080 int namespace_enter(int pidns_fd
, int mntns_fd
, int netns_fd
, int userns_fd
, int root_fd
) {
5081 if (userns_fd
>= 0) {
5082 /* Can't setns to your own userns, since then you could
5083 * escalate from non-root to root in your own namespace, so
5084 * check if namespaces equal before attempting to enter. */
5085 _cleanup_free_
char *userns_fd_path
= NULL
;
5087 if (asprintf(&userns_fd_path
, "/proc/self/fd/%d", userns_fd
) < 0)
5090 r
= files_same(userns_fd_path
, "/proc/self/ns/user");
5098 if (setns(pidns_fd
, CLONE_NEWPID
) < 0)
5102 if (setns(mntns_fd
, CLONE_NEWNS
) < 0)
5106 if (setns(netns_fd
, CLONE_NEWNET
) < 0)
5110 if (setns(userns_fd
, CLONE_NEWUSER
) < 0)
5114 if (fchdir(root_fd
) < 0)
5117 if (chroot(".") < 0)
5121 return reset_uid_gid();
5124 int getpeercred(int fd
, struct ucred
*ucred
) {
5125 socklen_t n
= sizeof(struct ucred
);
5132 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
);
5136 if (n
!= sizeof(struct ucred
))
5139 /* Check if the data is actually useful and not suppressed due
5140 * to namespacing issues */
5143 if (u
.uid
== UID_INVALID
)
5145 if (u
.gid
== GID_INVALID
)
5152 int getpeersec(int fd
, char **ret
) {
5164 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
5168 if (errno
!= ERANGE
)
5175 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
5191 /* This is much like like mkostemp() but is subject to umask(). */
5192 int mkostemp_safe(char *pattern
, int flags
) {
5193 _cleanup_umask_ mode_t u
;
5200 fd
= mkostemp(pattern
, flags
);
5207 int open_tmpfile(const char *path
, int flags
) {
5214 /* Try O_TMPFILE first, if it is supported */
5215 fd
= open(path
, flags
|O_TMPFILE
|O_EXCL
, S_IRUSR
|S_IWUSR
);
5220 /* Fall back to unguessable name + unlinking */
5221 p
= strjoina(path
, "/systemd-tmp-XXXXXX");
5223 fd
= mkostemp_safe(p
, flags
);
5231 int fd_warn_permissions(const char *path
, int fd
) {
5234 if (fstat(fd
, &st
) < 0)
5237 if (st
.st_mode
& 0111)
5238 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path
);
5240 if (st
.st_mode
& 0002)
5241 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path
);
5243 if (getpid() == 1 && (st
.st_mode
& 0044) != 0044)
5244 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
);
5249 unsigned long personality_from_string(const char *p
) {
5251 /* Parse a personality specifier. We introduce our own
5252 * identifiers that indicate specific ABIs, rather than just
5253 * hints regarding the register size, since we want to keep
5254 * things open for multiple locally supported ABIs for the
5255 * same register size. We try to reuse the ABI identifiers
5256 * used by libseccomp. */
5258 #if defined(__x86_64__)
5260 if (streq(p
, "x86"))
5263 if (streq(p
, "x86-64"))
5266 #elif defined(__i386__)
5268 if (streq(p
, "x86"))
5271 #elif defined(__s390x__)
5273 if (streq(p
, "s390"))
5276 if (streq(p
, "s390x"))
5279 #elif defined(__s390__)
5281 if (streq(p
, "s390"))
5285 return PERSONALITY_INVALID
;
5288 const char* personality_to_string(unsigned long p
) {
5290 #if defined(__x86_64__)
5292 if (p
== PER_LINUX32
)
5298 #elif defined(__i386__)
5303 #elif defined(__s390x__)
5308 if (p
== PER_LINUX32
)
5311 #elif defined(__s390__)
5321 uint64_t physical_memory(void) {
5324 /* We return this as uint64_t in case we are running as 32bit
5325 * process on a 64bit kernel with huge amounts of memory */
5327 mem
= sysconf(_SC_PHYS_PAGES
);
5330 return (uint64_t) mem
* (uint64_t) page_size();
5333 void hexdump(FILE *f
, const void *p
, size_t s
) {
5334 const uint8_t *b
= p
;
5337 assert(s
== 0 || b
);
5342 fprintf(f
, "%04x ", n
);
5344 for (i
= 0; i
< 16; i
++) {
5349 fprintf(f
, "%02x ", b
[i
]);
5357 for (i
= 0; i
< 16; i
++) {
5362 fputc(isprint(b
[i
]) ? (char) b
[i
] : '.', f
);
5376 int update_reboot_param_file(const char *param
) {
5380 r
= write_string_file(REBOOT_PARAM_FILE
, param
, WRITE_STRING_FILE_CREATE
);
5382 return log_error_errno(r
, "Failed to write reboot param to "REBOOT_PARAM_FILE
": %m");
5384 (void) unlink(REBOOT_PARAM_FILE
);
5389 int umount_recursive(const char *prefix
, int flags
) {
5393 /* Try to umount everything recursively below a
5394 * directory. Also, take care of stacked mounts, and keep
5395 * unmounting them until they are gone. */
5398 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
5403 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
5404 if (!proc_self_mountinfo
)
5408 _cleanup_free_
char *path
= NULL
, *p
= NULL
;
5411 k
= fscanf(proc_self_mountinfo
,
5412 "%*s " /* (1) mount id */
5413 "%*s " /* (2) parent id */
5414 "%*s " /* (3) major:minor */
5415 "%*s " /* (4) root */
5416 "%ms " /* (5) mount point */
5417 "%*s" /* (6) mount options */
5418 "%*[^-]" /* (7) optional fields */
5419 "- " /* (8) separator */
5420 "%*s " /* (9) file system type */
5421 "%*s" /* (10) mount source */
5422 "%*s" /* (11) mount options 2 */
5423 "%*[^\n]", /* some rubbish at the end */
5432 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
5436 if (!path_startswith(p
, prefix
))
5439 if (umount2(p
, flags
) < 0) {
5455 static int get_mount_flags(const char *path
, unsigned long *flags
) {
5458 if (statvfs(path
, &buf
) < 0)
5460 *flags
= buf
.f_flag
;
5464 int bind_remount_recursive(const char *prefix
, bool ro
) {
5465 _cleanup_set_free_free_ Set
*done
= NULL
;
5466 _cleanup_free_
char *cleaned
= NULL
;
5469 /* Recursively remount a directory (and all its submounts)
5470 * read-only or read-write. If the directory is already
5471 * mounted, we reuse the mount and simply mark it
5472 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
5473 * operation). If it isn't we first make it one. Afterwards we
5474 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
5475 * submounts we can access, too. When mounts are stacked on
5476 * the same mount point we only care for each individual
5477 * "top-level" mount on each point, as we cannot
5478 * influence/access the underlying mounts anyway. We do not
5479 * have any effect on future submounts that might get
5480 * propagated, they migt be writable. This includes future
5481 * submounts that have been triggered via autofs. */
5483 cleaned
= strdup(prefix
);
5487 path_kill_slashes(cleaned
);
5489 done
= set_new(&string_hash_ops
);
5494 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
5495 _cleanup_set_free_free_ Set
*todo
= NULL
;
5496 bool top_autofs
= false;
5498 unsigned long orig_flags
;
5500 todo
= set_new(&string_hash_ops
);
5504 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
5505 if (!proc_self_mountinfo
)
5509 _cleanup_free_
char *path
= NULL
, *p
= NULL
, *type
= NULL
;
5512 k
= fscanf(proc_self_mountinfo
,
5513 "%*s " /* (1) mount id */
5514 "%*s " /* (2) parent id */
5515 "%*s " /* (3) major:minor */
5516 "%*s " /* (4) root */
5517 "%ms " /* (5) mount point */
5518 "%*s" /* (6) mount options (superblock) */
5519 "%*[^-]" /* (7) optional fields */
5520 "- " /* (8) separator */
5521 "%ms " /* (9) file system type */
5522 "%*s" /* (10) mount source */
5523 "%*s" /* (11) mount options (bind mount) */
5524 "%*[^\n]", /* some rubbish at the end */
5534 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
5538 /* Let's ignore autofs mounts. If they aren't
5539 * triggered yet, we want to avoid triggering
5540 * them, as we don't make any guarantees for
5541 * future submounts anyway. If they are
5542 * already triggered, then we will find
5543 * another entry for this. */
5544 if (streq(type
, "autofs")) {
5545 top_autofs
= top_autofs
|| path_equal(cleaned
, p
);
5549 if (path_startswith(p
, cleaned
) &&
5550 !set_contains(done
, p
)) {
5552 r
= set_consume(todo
, p
);
5562 /* If we have no submounts to process anymore and if
5563 * the root is either already done, or an autofs, we
5565 if (set_isempty(todo
) &&
5566 (top_autofs
|| set_contains(done
, cleaned
)))
5569 if (!set_contains(done
, cleaned
) &&
5570 !set_contains(todo
, cleaned
)) {
5571 /* The prefix directory itself is not yet a
5572 * mount, make it one. */
5573 if (mount(cleaned
, cleaned
, NULL
, MS_BIND
|MS_REC
, NULL
) < 0)
5577 (void) get_mount_flags(cleaned
, &orig_flags
);
5578 orig_flags
&= ~MS_RDONLY
;
5580 if (mount(NULL
, prefix
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0)
5583 x
= strdup(cleaned
);
5587 r
= set_consume(done
, x
);
5592 while ((x
= set_steal_first(todo
))) {
5594 r
= set_consume(done
, x
);
5595 if (r
== -EEXIST
|| r
== 0)
5600 /* Try to reuse the original flag set, but
5601 * don't care for errors, in case of
5602 * obstructed mounts */
5604 (void) get_mount_flags(x
, &orig_flags
);
5605 orig_flags
&= ~MS_RDONLY
;
5607 if (mount(NULL
, x
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0) {
5609 /* Deal with mount points that are
5610 * obstructed by a later mount */
5612 if (errno
!= ENOENT
)
5620 int fflush_and_check(FILE *f
) {
5627 return errno
? -errno
: -EIO
;
5632 int tempfn_xxxxxx(const char *p
, const char *extra
, char **ret
) {
5644 * /foo/bar/.#<extra>waldoXXXXXX
5648 if (!filename_is_valid(fn
))
5654 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 6 + 1);
5658 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
), "XXXXXX");
5660 *ret
= path_kill_slashes(t
);
5664 int tempfn_random(const char *p
, const char *extra
, char **ret
) {
5678 * /foo/bar/.#<extra>waldobaa2a261115984a9
5682 if (!filename_is_valid(fn
))
5688 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 16 + 1);
5692 x
= stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
);
5695 for (i
= 0; i
< 16; i
++) {
5696 *(x
++) = hexchar(u
& 0xF);
5702 *ret
= path_kill_slashes(t
);
5706 int tempfn_random_child(const char *p
, const char *extra
, char **ret
) {
5717 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
5723 t
= new(char, strlen(p
) + 3 + strlen(extra
) + 16 + 1);
5727 x
= stpcpy(stpcpy(stpcpy(t
, p
), "/.#"), extra
);
5730 for (i
= 0; i
< 16; i
++) {
5731 *(x
++) = hexchar(u
& 0xF);
5737 *ret
= path_kill_slashes(t
);
5741 int take_password_lock(const char *root
) {
5743 struct flock flock
= {
5745 .l_whence
= SEEK_SET
,
5753 /* This is roughly the same as lckpwdf(), but not as awful. We
5754 * don't want to use alarm() and signals, hence we implement
5755 * our own trivial version of this.
5757 * Note that shadow-utils also takes per-database locks in
5758 * addition to lckpwdf(). However, we don't given that they
5759 * are redundant as they they invoke lckpwdf() first and keep
5760 * it during everything they do. The per-database locks are
5761 * awfully racy, and thus we just won't do them. */
5764 path
= strjoina(root
, "/etc/.pwd.lock");
5766 path
= "/etc/.pwd.lock";
5768 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
5772 r
= fcntl(fd
, F_SETLKW
, &flock
);
5781 int is_symlink(const char *path
) {
5784 if (lstat(path
, &info
) < 0)
5787 return !!S_ISLNK(info
.st_mode
);
5790 int is_dir(const char* path
, bool follow
) {
5795 r
= stat(path
, &st
);
5797 r
= lstat(path
, &st
);
5801 return !!S_ISDIR(st
.st_mode
);
5804 int is_device_node(const char *path
) {
5807 if (lstat(path
, &info
) < 0)
5810 return !!(S_ISBLK(info
.st_mode
) || S_ISCHR(info
.st_mode
));
5813 int extract_first_word(const char **p
, char **ret
, const char *separators
, ExtractFlags flags
) {
5814 _cleanup_free_
char *s
= NULL
;
5815 size_t allocated
= 0, sz
= 0;
5823 SINGLE_QUOTE_ESCAPE
,
5825 DOUBLE_QUOTE_ESCAPE
,
5833 separators
= WHITESPACE
;
5835 /* Bail early if called after last value or with no input */
5837 goto finish_force_terminate
;
5839 /* Parses the first word of a string, and returns it in
5840 * *ret. Removes all quotes in the process. When parsing fails
5841 * (because of an uneven number of quotes or similar), leaves
5842 * the pointer *p at the first invalid character. */
5850 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
)
5851 if (!GREEDY_REALLOC(s
, allocated
, sz
+1))
5855 goto finish_force_terminate
;
5856 else if (strchr(separators
, c
)) {
5857 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
) {
5859 goto finish_force_next
;
5864 /* We found a non-blank character, so we will always
5865 * want to return a string (even if it is empty),
5866 * allocate it here. */
5867 if (!GREEDY_REALLOC(s
, allocated
, sz
+1))
5875 goto finish_force_terminate
;
5876 else if (c
== '\'' && (flags
& EXTRACT_QUOTES
))
5877 state
= SINGLE_QUOTE
;
5879 state
= VALUE_ESCAPE
;
5880 else if (c
== '\"' && (flags
& EXTRACT_QUOTES
))
5881 state
= DOUBLE_QUOTE
;
5882 else if (strchr(separators
, c
)) {
5883 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
) {
5885 goto finish_force_next
;
5889 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5899 if (flags
& EXTRACT_RELAX
)
5900 goto finish_force_terminate
;
5902 } else if (c
== '\'')
5905 state
= SINGLE_QUOTE_ESCAPE
;
5907 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5921 state
= DOUBLE_QUOTE_ESCAPE
;
5923 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5931 case SINGLE_QUOTE_ESCAPE
:
5932 case DOUBLE_QUOTE_ESCAPE
:
5934 if (!GREEDY_REALLOC(s
, allocated
, sz
+7))
5938 if ((flags
& EXTRACT_CUNESCAPE_RELAX
) &&
5939 (state
== VALUE_ESCAPE
|| flags
& EXTRACT_RELAX
)) {
5940 /* If we find an unquoted trailing backslash and we're in
5941 * EXTRACT_CUNESCAPE_RELAX mode, keep it verbatim in the
5944 * Unbalanced quotes will only be allowed in EXTRACT_RELAX
5945 * mode, EXTRACT_CUNESCAPE_RELAX mode does not allow them.
5948 goto finish_force_terminate
;
5950 if (flags
& EXTRACT_RELAX
)
5951 goto finish_force_terminate
;
5955 if (flags
& EXTRACT_CUNESCAPE
) {
5958 r
= cunescape_one(*p
, (size_t) -1, &c
, &u
);
5960 if (flags
& EXTRACT_CUNESCAPE_RELAX
) {
5971 s
[sz
++] = c
; /* normal explicit char */
5973 sz
+= utf8_encode_unichar(s
+ sz
, u
); /* unicode chars we'll encode as utf8 */
5978 state
= (state
== SINGLE_QUOTE_ESCAPE
) ? SINGLE_QUOTE
:
5979 (state
== DOUBLE_QUOTE_ESCAPE
) ? DOUBLE_QUOTE
:
5985 goto finish_force_terminate
;
5986 if (!strchr(separators
, c
))
5994 finish_force_terminate
:
6011 int extract_first_word_and_warn(
6014 const char *separators
,
6017 const char *filename
,
6019 const char *rvalue
) {
6021 /* Try to unquote it, if it fails, warn about it and try again but this
6022 * time using EXTRACT_CUNESCAPE_RELAX to keep the backslashes verbatim
6023 * in invalid escape sequences. */
6028 r
= extract_first_word(p
, ret
, separators
, flags
);
6029 if (r
< 0 && !(flags
& EXTRACT_CUNESCAPE_RELAX
)) {
6031 /* Retry it with EXTRACT_CUNESCAPE_RELAX. */
6033 r
= extract_first_word(p
, ret
, separators
, flags
|EXTRACT_CUNESCAPE_RELAX
);
6035 log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Unbalanced quoting in command line, ignoring: \"%s\"", rvalue
);
6037 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0, "Invalid escape sequences in command line: \"%s\"", rvalue
);
6043 int extract_many_words(const char **p
, const char *separators
, ExtractFlags flags
, ...) {
6048 /* Parses a number of words from a string, stripping any
6049 * quotes if necessary. */
6053 /* Count how many words are expected */
6054 va_start(ap
, flags
);
6056 if (!va_arg(ap
, char **))
6065 /* Read all words into a temporary array */
6066 l
= newa0(char*, n
);
6067 for (c
= 0; c
< n
; c
++) {
6069 r
= extract_first_word(p
, &l
[c
], separators
, flags
);
6073 for (j
= 0; j
< c
; j
++)
6083 /* If we managed to parse all words, return them in the passed
6085 va_start(ap
, flags
);
6086 for (i
= 0; i
< n
; i
++) {
6089 v
= va_arg(ap
, char **);
6099 int free_and_strdup(char **p
, const char *s
) {
6104 /* Replaces a string pointer with an strdup()ed new string,
6105 * possibly freeing the old one. */
6107 if (streq_ptr(*p
, s
))
6123 ssize_t
fgetxattrat_fake(int dirfd
, const char *filename
, const char *attribute
, void *value
, size_t size
, int flags
) {
6124 char fn
[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(int) + 1];
6125 _cleanup_close_
int fd
= -1;
6128 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
6130 fd
= openat(dirfd
, filename
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_PATH
|(flags
& AT_SYMLINK_NOFOLLOW
? O_NOFOLLOW
: 0));
6134 xsprintf(fn
, "/proc/self/fd/%i", fd
);
6136 l
= getxattr(fn
, attribute
, value
, size
);
6143 static int parse_crtime(le64_t le
, usec_t
*usec
) {
6149 if (u
== 0 || u
== (uint64_t) -1)
6156 int fd_getcrtime(int fd
, usec_t
*usec
) {
6163 /* Until Linux gets a real concept of birthtime/creation time,
6164 * let's fake one with xattrs */
6166 n
= fgetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
));
6169 if (n
!= sizeof(le
))
6172 return parse_crtime(le
, usec
);
6175 int fd_getcrtime_at(int dirfd
, const char *name
, usec_t
*usec
, int flags
) {
6179 n
= fgetxattrat_fake(dirfd
, name
, "user.crtime_usec", &le
, sizeof(le
), flags
);
6182 if (n
!= sizeof(le
))
6185 return parse_crtime(le
, usec
);
6188 int path_getcrtime(const char *p
, usec_t
*usec
) {
6195 n
= getxattr(p
, "user.crtime_usec", &le
, sizeof(le
));
6198 if (n
!= sizeof(le
))
6201 return parse_crtime(le
, usec
);
6204 int fd_setcrtime(int fd
, usec_t usec
) {
6210 usec
= now(CLOCK_REALTIME
);
6212 le
= htole64((uint64_t) usec
);
6213 if (fsetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
), 0) < 0)
6219 int same_fd(int a
, int b
) {
6220 struct stat sta
, stb
;
6227 /* Compares two file descriptors. Note that semantics are
6228 * quite different depending on whether we have kcmp() or we
6229 * don't. If we have kcmp() this will only return true for
6230 * dup()ed file descriptors, but not otherwise. If we don't
6231 * have kcmp() this will also return true for two fds of the same
6232 * file, created by separate open() calls. Since we use this
6233 * call mostly for filtering out duplicates in the fd store
6234 * this difference hopefully doesn't matter too much. */
6239 /* Try to use kcmp() if we have it. */
6241 r
= kcmp(pid
, pid
, KCMP_FILE
, a
, b
);
6246 if (errno
!= ENOSYS
)
6249 /* We don't have kcmp(), use fstat() instead. */
6250 if (fstat(a
, &sta
) < 0)
6253 if (fstat(b
, &stb
) < 0)
6256 if ((sta
.st_mode
& S_IFMT
) != (stb
.st_mode
& S_IFMT
))
6259 /* We consider all device fds different, since two device fds
6260 * might refer to quite different device contexts even though
6261 * they share the same inode and backing dev_t. */
6263 if (S_ISCHR(sta
.st_mode
) || S_ISBLK(sta
.st_mode
))
6266 if (sta
.st_dev
!= stb
.st_dev
|| sta
.st_ino
!= stb
.st_ino
)
6269 /* The fds refer to the same inode on disk, let's also check
6270 * if they have the same fd flags. This is useful to
6271 * distinguish the read and write side of a pipe created with
6273 fa
= fcntl(a
, F_GETFL
);
6277 fb
= fcntl(b
, F_GETFL
);
6284 int chattr_fd(int fd
, unsigned value
, unsigned mask
) {
6285 unsigned old_attr
, new_attr
;
6290 if (fstat(fd
, &st
) < 0)
6293 /* Explicitly check whether this is a regular file or
6294 * directory. If it is anything else (such as a device node or
6295 * fifo), then the ioctl will not hit the file systems but
6296 * possibly drivers, where the ioctl might have different
6297 * effects. Notably, DRM is using the same ioctl() number. */
6299 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
6305 if (ioctl(fd
, FS_IOC_GETFLAGS
, &old_attr
) < 0)
6308 new_attr
= (old_attr
& ~mask
) | (value
& mask
);
6309 if (new_attr
== old_attr
)
6312 if (ioctl(fd
, FS_IOC_SETFLAGS
, &new_attr
) < 0)
6318 int chattr_path(const char *p
, unsigned value
, unsigned mask
) {
6319 _cleanup_close_
int fd
= -1;
6326 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
6330 return chattr_fd(fd
, value
, mask
);
6333 int read_attr_fd(int fd
, unsigned *ret
) {
6338 if (fstat(fd
, &st
) < 0)
6341 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
6344 if (ioctl(fd
, FS_IOC_GETFLAGS
, ret
) < 0)
6350 int read_attr_path(const char *p
, unsigned *ret
) {
6351 _cleanup_close_
int fd
= -1;
6356 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
6360 return read_attr_fd(fd
, ret
);
6363 static size_t nul_length(const uint8_t *p
, size_t sz
) {
6378 ssize_t
sparse_write(int fd
, const void *p
, size_t sz
, size_t run_length
) {
6379 const uint8_t *q
, *w
, *e
;
6387 n
= nul_length(q
, e
- q
);
6389 /* If there are more than the specified run length of
6390 * NUL bytes, or if this is the beginning or the end
6391 * of the buffer, then seek instead of write */
6392 if ((n
> run_length
) ||
6393 (n
> 0 && q
== p
) ||
6394 (n
> 0 && q
+ n
>= e
)) {
6396 l
= write(fd
, w
, q
- w
);
6403 if (lseek(fd
, n
, SEEK_CUR
) == (off_t
) -1)
6415 l
= write(fd
, w
, q
- w
);
6422 return q
- (const uint8_t*) p
;
6425 void sigkill_wait(pid_t
*pid
) {
6431 if (kill(*pid
, SIGKILL
) > 0)
6432 (void) wait_for_terminate(*pid
, NULL
);
6435 int syslog_parse_priority(const char **p
, int *priority
, bool with_facility
) {
6436 int a
= 0, b
= 0, c
= 0;
6446 if (!strchr(*p
, '>'))
6449 if ((*p
)[2] == '>') {
6450 c
= undecchar((*p
)[1]);
6452 } else if ((*p
)[3] == '>') {
6453 b
= undecchar((*p
)[1]);
6454 c
= undecchar((*p
)[2]);
6456 } else if ((*p
)[4] == '>') {
6457 a
= undecchar((*p
)[1]);
6458 b
= undecchar((*p
)[2]);
6459 c
= undecchar((*p
)[3]);
6464 if (a
< 0 || b
< 0 || c
< 0 ||
6465 (!with_facility
&& (a
|| b
|| c
> 7)))
6469 *priority
= a
*100 + b
*10 + c
;
6471 *priority
= (*priority
& LOG_FACMASK
) | c
;
6477 ssize_t
string_table_lookup(const char * const *table
, size_t len
, const char *key
) {
6483 for (i
= 0; i
< len
; ++i
)
6484 if (streq_ptr(table
[i
], key
))
6490 void cmsg_close_all(struct msghdr
*mh
) {
6491 struct cmsghdr
*cmsg
;
6495 CMSG_FOREACH(cmsg
, mh
)
6496 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
)
6497 close_many((int*) CMSG_DATA(cmsg
), (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int));
6500 int rename_noreplace(int olddirfd
, const char *oldpath
, int newdirfd
, const char *newpath
) {
6504 ret
= renameat2(olddirfd
, oldpath
, newdirfd
, newpath
, RENAME_NOREPLACE
);
6508 /* renameat2() exists since Linux 3.15, btrfs added support for it later.
6509 * If it is not implemented, fallback to another method. */
6510 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
6513 /* The link()/unlink() fallback does not work on directories. But
6514 * renameat() without RENAME_NOREPLACE gives the same semantics on
6515 * directories, except when newpath is an *empty* directory. This is
6517 ret
= fstatat(olddirfd
, oldpath
, &buf
, AT_SYMLINK_NOFOLLOW
);
6518 if (ret
>= 0 && S_ISDIR(buf
.st_mode
)) {
6519 ret
= renameat(olddirfd
, oldpath
, newdirfd
, newpath
);
6520 return ret
>= 0 ? 0 : -errno
;
6523 /* If it is not a directory, use the link()/unlink() fallback. */
6524 ret
= linkat(olddirfd
, oldpath
, newdirfd
, newpath
, 0);
6528 ret
= unlinkat(olddirfd
, oldpath
, 0);
6530 /* backup errno before the following unlinkat() alters it */
6532 (void) unlinkat(newdirfd
, newpath
, 0);
6540 static char *strcpy_backslash_escaped(char *t
, const char *s
, const char *bad
) {
6544 if (*s
== '\\' || strchr(bad
, *s
))
6553 char *shell_escape(const char *s
, const char *bad
) {
6556 r
= new(char, strlen(s
)*2+1);
6560 t
= strcpy_backslash_escaped(r
, s
, bad
);
6566 char *shell_maybe_quote(const char *s
) {
6572 /* Encloses a string in double quotes if necessary to make it
6573 * OK as shell string. */
6575 for (p
= s
; *p
; p
++)
6578 strchr(SHELL_NEED_QUOTES
, *p
))
6584 r
= new(char, 1+strlen(s
)*2+1+1);
6590 t
= mempcpy(t
, s
, p
- s
);
6592 t
= strcpy_backslash_escaped(t
, p
, SHELL_NEED_ESCAPE
);
6600 int parse_mode(const char *s
, mode_t
*ret
) {
6608 l
= strtol(s
, &x
, 8);
6612 if (!x
|| x
== s
|| *x
)
6614 if (l
< 0 || l
> 07777)
6621 int mount_move_root(const char *path
) {
6624 if (chdir(path
) < 0)
6627 if (mount(path
, "/", NULL
, MS_MOVE
, NULL
) < 0)
6630 if (chroot(".") < 0)
6639 int reset_uid_gid(void) {
6641 if (setgroups(0, NULL
) < 0)
6644 if (setresgid(0, 0, 0) < 0)
6647 if (setresuid(0, 0, 0) < 0)
6653 int getxattr_malloc(const char *path
, const char *name
, char **value
, bool allow_symlink
) {
6662 for (l
= 100; ; l
= (size_t) n
+ 1) {
6668 n
= lgetxattr(path
, name
, v
, l
);
6670 n
= getxattr(path
, name
, v
, l
);
6672 if (n
>= 0 && (size_t) n
< l
) {
6679 if (n
< 0 && errno
!= ERANGE
)
6683 n
= lgetxattr(path
, name
, NULL
, 0);
6685 n
= getxattr(path
, name
, NULL
, 0);
6691 int fgetxattr_malloc(int fd
, const char *name
, char **value
) {
6700 for (l
= 100; ; l
= (size_t) n
+ 1) {
6705 n
= fgetxattr(fd
, name
, v
, l
);
6707 if (n
>= 0 && (size_t) n
< l
) {
6714 if (n
< 0 && errno
!= ERANGE
)
6717 n
= fgetxattr(fd
, name
, NULL
, 0);
6723 int send_one_fd(int transport_fd
, int fd
, int flags
) {
6725 struct cmsghdr cmsghdr
;
6726 uint8_t buf
[CMSG_SPACE(sizeof(int))];
6728 struct msghdr mh
= {
6729 .msg_control
= &control
,
6730 .msg_controllen
= sizeof(control
),
6732 struct cmsghdr
*cmsg
;
6734 assert(transport_fd
>= 0);
6737 cmsg
= CMSG_FIRSTHDR(&mh
);
6738 cmsg
->cmsg_level
= SOL_SOCKET
;
6739 cmsg
->cmsg_type
= SCM_RIGHTS
;
6740 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
6741 memcpy(CMSG_DATA(cmsg
), &fd
, sizeof(int));
6743 mh
.msg_controllen
= CMSG_SPACE(sizeof(int));
6744 if (sendmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| flags
) < 0)
6750 int receive_one_fd(int transport_fd
, int flags
) {
6752 struct cmsghdr cmsghdr
;
6753 uint8_t buf
[CMSG_SPACE(sizeof(int))];
6755 struct msghdr mh
= {
6756 .msg_control
= &control
,
6757 .msg_controllen
= sizeof(control
),
6759 struct cmsghdr
*cmsg
, *found
= NULL
;
6761 assert(transport_fd
>= 0);
6764 * Receive a single FD via @transport_fd. We don't care for
6765 * the transport-type. We retrieve a single FD at most, so for
6766 * packet-based transports, the caller must ensure to send
6767 * only a single FD per packet. This is best used in
6768 * combination with send_one_fd().
6771 if (recvmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| MSG_CMSG_CLOEXEC
| flags
) < 0)
6774 CMSG_FOREACH(cmsg
, &mh
) {
6775 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
6776 cmsg
->cmsg_type
== SCM_RIGHTS
&&
6777 cmsg
->cmsg_len
== CMSG_LEN(sizeof(int))) {
6785 cmsg_close_all(&mh
);
6789 return *(int*) CMSG_DATA(found
);
6792 void nop_signal_handler(int sig
) {
6797 puts(PACKAGE_STRING
"\n"
6802 bool fdname_is_valid(const char *s
) {
6805 /* Validates a name for $LISTEN_FDNAMES. We basically allow
6806 * everything ASCII that's not a control character. Also, as
6807 * special exception the ":" character is not allowed, as we
6808 * use that as field separator in $LISTEN_FDNAMES.
6810 * Note that the empty string is explicitly allowed
6811 * here. However, we limit the length of the names to 255
6817 for (p
= s
; *p
; p
++) {
6829 bool oom_score_adjust_is_valid(int oa
) {
6830 return oa
>= OOM_SCORE_ADJ_MIN
&& oa
<= OOM_SCORE_ADJ_MAX
;
6833 void string_erase(char *x
) {
6838 /* A delicious drop of snake-oil! To be called on memory where
6839 * we stored passphrases or so, after we used them. */
6841 memory_erase(x
, strlen(x
));
6844 char *string_free_erase(char *s
) {