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
;
2390 FOREACH_DIRENT(de
, d
, return -errno
)
2396 char* dirname_malloc(const char *path
) {
2397 char *d
, *dir
, *dir2
;
2414 void rename_process(const char name
[8]) {
2417 /* This is a like a poor man's setproctitle(). It changes the
2418 * comm field, argv[0], and also the glibc's internally used
2419 * name of the process. For the first one a limit of 16 chars
2420 * applies, to the second one usually one of 10 (i.e. length
2421 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2422 * "systemd"). If you pass a longer string it will be
2425 prctl(PR_SET_NAME
, name
);
2427 if (program_invocation_name
)
2428 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
2430 if (saved_argc
> 0) {
2434 strncpy(saved_argv
[0], name
, strlen(saved_argv
[0]));
2436 for (i
= 1; i
< saved_argc
; i
++) {
2440 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
2445 char *lookup_uid(uid_t uid
) {
2448 _cleanup_free_
char *buf
= NULL
;
2449 struct passwd pwbuf
, *pw
= NULL
;
2451 /* Shortcut things to avoid NSS lookups */
2453 return strdup("root");
2455 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
2459 buf
= malloc(bufsize
);
2463 if (getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
) == 0 && pw
)
2464 return strdup(pw
->pw_name
);
2466 if (asprintf(&name
, UID_FMT
, uid
) < 0)
2472 char* getlogname_malloc(void) {
2476 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
2481 return lookup_uid(uid
);
2484 char *getusername_malloc(void) {
2491 return lookup_uid(getuid());
2494 bool is_fs_type(const struct statfs
*s
, statfs_f_type_t magic_value
) {
2496 assert_cc(sizeof(statfs_f_type_t
) >= sizeof(s
->f_type
));
2498 return F_TYPE_EQUAL(s
->f_type
, magic_value
);
2501 int fd_check_fstype(int fd
, statfs_f_type_t magic_value
) {
2504 if (fstatfs(fd
, &s
) < 0)
2507 return is_fs_type(&s
, magic_value
);
2510 int path_check_fstype(const char *path
, statfs_f_type_t magic_value
) {
2511 _cleanup_close_
int fd
= -1;
2513 fd
= open(path
, O_RDONLY
);
2517 return fd_check_fstype(fd
, magic_value
);
2520 bool is_temporary_fs(const struct statfs
*s
) {
2521 return is_fs_type(s
, TMPFS_MAGIC
) ||
2522 is_fs_type(s
, RAMFS_MAGIC
);
2525 int fd_is_temporary_fs(int fd
) {
2528 if (fstatfs(fd
, &s
) < 0)
2531 return is_temporary_fs(&s
);
2534 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
2537 /* Under the assumption that we are running privileged we
2538 * first change the access mode and only then hand out
2539 * ownership to avoid a window where access is too open. */
2541 if (mode
!= MODE_INVALID
)
2542 if (chmod(path
, mode
) < 0)
2545 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
2546 if (chown(path
, uid
, gid
) < 0)
2552 int fchmod_and_fchown(int fd
, mode_t mode
, uid_t uid
, gid_t gid
) {
2555 /* Under the assumption that we are running privileged we
2556 * first change the access mode and only then hand out
2557 * ownership to avoid a window where access is too open. */
2559 if (mode
!= MODE_INVALID
)
2560 if (fchmod(fd
, mode
) < 0)
2563 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
2564 if (fchown(fd
, uid
, gid
) < 0)
2570 int files_same(const char *filea
, const char *fileb
) {
2573 if (stat(filea
, &a
) < 0)
2576 if (stat(fileb
, &b
) < 0)
2579 return a
.st_dev
== b
.st_dev
&&
2580 a
.st_ino
== b
.st_ino
;
2583 int running_in_chroot(void) {
2586 ret
= files_same("/proc/1/root", "/");
2593 static char *ascii_ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
2598 assert(percent
<= 100);
2599 assert(new_length
>= 3);
2601 if (old_length
<= 3 || old_length
<= new_length
)
2602 return strndup(s
, old_length
);
2604 r
= new0(char, new_length
+1);
2608 x
= (new_length
* percent
) / 100;
2610 if (x
> new_length
- 3)
2618 s
+ old_length
- (new_length
- x
- 3),
2619 new_length
- x
- 3);
2624 char *ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
2628 unsigned k
, len
, len2
;
2631 assert(percent
<= 100);
2632 assert(new_length
>= 3);
2634 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2635 if (ascii_is_valid(s
))
2636 return ascii_ellipsize_mem(s
, old_length
, new_length
, percent
);
2638 if (old_length
<= 3 || old_length
<= new_length
)
2639 return strndup(s
, old_length
);
2641 x
= (new_length
* percent
) / 100;
2643 if (x
> new_length
- 3)
2647 for (i
= s
; k
< x
&& i
< s
+ old_length
; i
= utf8_next_char(i
)) {
2650 c
= utf8_encoded_to_unichar(i
);
2653 k
+= unichar_iswide(c
) ? 2 : 1;
2656 if (k
> x
) /* last character was wide and went over quota */
2659 for (j
= s
+ old_length
; k
< new_length
&& j
> i
; ) {
2662 j
= utf8_prev_char(j
);
2663 c
= utf8_encoded_to_unichar(j
);
2666 k
+= unichar_iswide(c
) ? 2 : 1;
2670 /* we don't actually need to ellipsize */
2672 return memdup(s
, old_length
+ 1);
2674 /* make space for ellipsis */
2675 j
= utf8_next_char(j
);
2678 len2
= s
+ old_length
- j
;
2679 e
= new(char, len
+ 3 + len2
+ 1);
2684 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2685 old_length, new_length, x, len, len2, k);
2689 e
[len
] = 0xe2; /* tri-dot ellipsis: … */
2693 memcpy(e
+ len
+ 3, j
, len2
+ 1);
2698 char *ellipsize(const char *s
, size_t length
, unsigned percent
) {
2699 return ellipsize_mem(s
, strlen(s
), length
, percent
);
2702 int touch_file(const char *path
, bool parents
, usec_t stamp
, uid_t uid
, gid_t gid
, mode_t mode
) {
2703 _cleanup_close_
int fd
;
2709 mkdir_parents(path
, 0755);
2711 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, mode
> 0 ? mode
: 0644);
2716 r
= fchmod(fd
, mode
);
2721 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
) {
2722 r
= fchown(fd
, uid
, gid
);
2727 if (stamp
!= USEC_INFINITY
) {
2728 struct timespec ts
[2];
2730 timespec_store(&ts
[0], stamp
);
2732 r
= futimens(fd
, ts
);
2734 r
= futimens(fd
, NULL
);
2741 int touch(const char *path
) {
2742 return touch_file(path
, false, USEC_INFINITY
, UID_INVALID
, GID_INVALID
, 0);
2745 static char *unquote(const char *s
, const char* quotes
) {
2749 /* This is rather stupid, simply removes the heading and
2750 * trailing quotes if there is one. Doesn't care about
2751 * escaping or anything.
2753 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2759 if (strchr(quotes
, s
[0]) && s
[l
-1] == s
[0])
2760 return strndup(s
+1, l
-2);
2765 noreturn
void freeze(void) {
2767 /* Make sure nobody waits for us on a socket anymore */
2768 close_all_fds(NULL
, 0);
2776 bool null_or_empty(struct stat
*st
) {
2779 if (S_ISREG(st
->st_mode
) && st
->st_size
<= 0)
2782 if (S_ISCHR(st
->st_mode
) || S_ISBLK(st
->st_mode
))
2788 int null_or_empty_path(const char *fn
) {
2793 if (stat(fn
, &st
) < 0)
2796 return null_or_empty(&st
);
2799 int null_or_empty_fd(int fd
) {
2804 if (fstat(fd
, &st
) < 0)
2807 return null_or_empty(&st
);
2810 DIR *xopendirat(int fd
, const char *name
, int flags
) {
2814 assert(!(flags
& O_CREAT
));
2816 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
2829 static char *tag_to_udev_node(const char *tagvalue
, const char *by
) {
2830 _cleanup_free_
char *t
= NULL
, *u
= NULL
;
2833 u
= unquote(tagvalue
, QUOTES
);
2837 enc_len
= strlen(u
) * 4 + 1;
2838 t
= new(char, enc_len
);
2842 if (encode_devnode_name(u
, t
, enc_len
) < 0)
2845 return strjoin("/dev/disk/by-", by
, "/", t
, NULL
);
2848 char *fstab_node_to_udev_node(const char *p
) {
2851 if (startswith(p
, "LABEL="))
2852 return tag_to_udev_node(p
+6, "label");
2854 if (startswith(p
, "UUID="))
2855 return tag_to_udev_node(p
+5, "uuid");
2857 if (startswith(p
, "PARTUUID="))
2858 return tag_to_udev_node(p
+9, "partuuid");
2860 if (startswith(p
, "PARTLABEL="))
2861 return tag_to_udev_node(p
+10, "partlabel");
2866 bool dirent_is_file(const struct dirent
*de
) {
2869 if (hidden_file(de
->d_name
))
2872 if (de
->d_type
!= DT_REG
&&
2873 de
->d_type
!= DT_LNK
&&
2874 de
->d_type
!= DT_UNKNOWN
)
2880 bool dirent_is_file_with_suffix(const struct dirent
*de
, const char *suffix
) {
2883 if (de
->d_type
!= DT_REG
&&
2884 de
->d_type
!= DT_LNK
&&
2885 de
->d_type
!= DT_UNKNOWN
)
2888 if (hidden_file_allow_backup(de
->d_name
))
2891 return endswith(de
->d_name
, suffix
);
2894 static int do_execute(char **directories
, usec_t timeout
, char *argv
[]) {
2895 _cleanup_hashmap_free_free_ Hashmap
*pids
= NULL
;
2896 _cleanup_set_free_free_ Set
*seen
= NULL
;
2899 /* We fork this all off from a child process so that we can
2900 * somewhat cleanly make use of SIGALRM to set a time limit */
2902 (void) reset_all_signal_handlers();
2903 (void) reset_signal_mask();
2905 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
2907 pids
= hashmap_new(NULL
);
2911 seen
= set_new(&string_hash_ops
);
2915 STRV_FOREACH(directory
, directories
) {
2916 _cleanup_closedir_
DIR *d
;
2919 d
= opendir(*directory
);
2921 if (errno
== ENOENT
)
2924 return log_error_errno(errno
, "Failed to open directory %s: %m", *directory
);
2927 FOREACH_DIRENT(de
, d
, break) {
2928 _cleanup_free_
char *path
= NULL
;
2932 if (!dirent_is_file(de
))
2935 if (set_contains(seen
, de
->d_name
)) {
2936 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory
, de
->d_name
);
2940 r
= set_put_strdup(seen
, de
->d_name
);
2944 path
= strjoin(*directory
, "/", de
->d_name
, NULL
);
2948 if (null_or_empty_path(path
)) {
2949 log_debug("%s is empty (a mask).", path
);
2955 log_error_errno(errno
, "Failed to fork: %m");
2957 } else if (pid
== 0) {
2960 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
2970 return log_error_errno(errno
, "Failed to execute %s: %m", path
);
2973 log_debug("Spawned %s as " PID_FMT
".", path
, pid
);
2975 r
= hashmap_put(pids
, UINT_TO_PTR(pid
), path
);
2982 /* Abort execution of this process after the timout. We simply
2983 * rely on SIGALRM as default action terminating the process,
2984 * and turn on alarm(). */
2986 if (timeout
!= USEC_INFINITY
)
2987 alarm((timeout
+ USEC_PER_SEC
- 1) / USEC_PER_SEC
);
2989 while (!hashmap_isempty(pids
)) {
2990 _cleanup_free_
char *path
= NULL
;
2993 pid
= PTR_TO_UINT(hashmap_first_key(pids
));
2996 path
= hashmap_remove(pids
, UINT_TO_PTR(pid
));
2999 wait_for_terminate_and_warn(path
, pid
, true);
3005 void execute_directories(const char* const* directories
, usec_t timeout
, char *argv
[]) {
3009 char **dirs
= (char**) directories
;
3011 assert(!strv_isempty(dirs
));
3013 name
= basename(dirs
[0]);
3014 assert(!isempty(name
));
3016 /* Executes all binaries in the directories in parallel and waits
3017 * for them to finish. Optionally a timeout is applied. If a file
3018 * with the same name exists in more than one directory, the
3019 * earliest one wins. */
3021 executor_pid
= fork();
3022 if (executor_pid
< 0) {
3023 log_error_errno(errno
, "Failed to fork: %m");
3026 } else if (executor_pid
== 0) {
3027 r
= do_execute(dirs
, timeout
, argv
);
3028 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
3031 wait_for_terminate_and_warn(name
, executor_pid
, true);
3034 bool nulstr_contains(const char*nulstr
, const char *needle
) {
3040 NULSTR_FOREACH(i
, nulstr
)
3041 if (streq(i
, needle
))
3047 bool plymouth_running(void) {
3048 return access("/run/plymouth/pid", F_OK
) >= 0;
3051 char* strshorten(char *s
, size_t l
) {
3060 int pipe_eof(int fd
) {
3061 struct pollfd pollfd
= {
3063 .events
= POLLIN
|POLLHUP
,
3068 r
= poll(&pollfd
, 1, 0);
3075 return pollfd
.revents
& POLLHUP
;
3078 int fd_wait_for_event(int fd
, int event
, usec_t t
) {
3080 struct pollfd pollfd
= {
3088 r
= ppoll(&pollfd
, 1, t
== USEC_INFINITY
? NULL
: timespec_store(&ts
, t
), NULL
);
3095 return pollfd
.revents
;
3098 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
3107 r
= tempfn_xxxxxx(path
, NULL
, &t
);
3111 fd
= mkostemp_safe(t
, O_WRONLY
|O_CLOEXEC
);
3117 f
= fdopen(fd
, "we");
3131 int symlink_atomic(const char *from
, const char *to
) {
3132 _cleanup_free_
char *t
= NULL
;
3138 r
= tempfn_random(to
, NULL
, &t
);
3142 if (symlink(from
, t
) < 0)
3145 if (rename(t
, to
) < 0) {
3153 int symlink_idempotent(const char *from
, const char *to
) {
3154 _cleanup_free_
char *p
= NULL
;
3160 if (symlink(from
, to
) < 0) {
3161 if (errno
!= EEXIST
)
3164 r
= readlink_malloc(to
, &p
);
3168 if (!streq(p
, from
))
3175 int mknod_atomic(const char *path
, mode_t mode
, dev_t dev
) {
3176 _cleanup_free_
char *t
= NULL
;
3181 r
= tempfn_random(path
, NULL
, &t
);
3185 if (mknod(t
, mode
, dev
) < 0)
3188 if (rename(t
, path
) < 0) {
3196 int mkfifo_atomic(const char *path
, mode_t mode
) {
3197 _cleanup_free_
char *t
= NULL
;
3202 r
= tempfn_random(path
, NULL
, &t
);
3206 if (mkfifo(t
, mode
) < 0)
3209 if (rename(t
, path
) < 0) {
3217 bool display_is_local(const char *display
) {
3221 display
[0] == ':' &&
3222 display
[1] >= '0' &&
3226 int socket_from_display(const char *display
, char **path
) {
3233 if (!display_is_local(display
))
3236 k
= strspn(display
+1, "0123456789");
3238 f
= new(char, strlen("/tmp/.X11-unix/X") + k
+ 1);
3242 c
= stpcpy(f
, "/tmp/.X11-unix/X");
3243 memcpy(c
, display
+1, k
);
3252 const char **username
,
3253 uid_t
*uid
, gid_t
*gid
,
3255 const char **shell
) {
3263 /* We enforce some special rules for uid=0: in order to avoid
3264 * NSS lookups for root we hardcode its data. */
3266 if (streq(*username
, "root") || streq(*username
, "0")) {
3284 if (parse_uid(*username
, &u
) >= 0) {
3288 /* If there are multiple users with the same id, make
3289 * sure to leave $USER to the configured value instead
3290 * of the first occurrence in the database. However if
3291 * the uid was configured by a numeric uid, then let's
3292 * pick the real username from /etc/passwd. */
3294 *username
= p
->pw_name
;
3297 p
= getpwnam(*username
);
3301 return errno
> 0 ? -errno
: -ESRCH
;
3313 *shell
= p
->pw_shell
;
3318 char* uid_to_name(uid_t uid
) {
3323 return strdup("root");
3327 return strdup(p
->pw_name
);
3329 if (asprintf(&r
, UID_FMT
, uid
) < 0)
3335 char* gid_to_name(gid_t gid
) {
3340 return strdup("root");
3344 return strdup(p
->gr_name
);
3346 if (asprintf(&r
, GID_FMT
, gid
) < 0)
3352 int get_group_creds(const char **groupname
, gid_t
*gid
) {
3358 /* We enforce some special rules for gid=0: in order to avoid
3359 * NSS lookups for root we hardcode its data. */
3361 if (streq(*groupname
, "root") || streq(*groupname
, "0")) {
3362 *groupname
= "root";
3370 if (parse_gid(*groupname
, &id
) >= 0) {
3375 *groupname
= g
->gr_name
;
3378 g
= getgrnam(*groupname
);
3382 return errno
> 0 ? -errno
: -ESRCH
;
3390 int in_gid(gid_t gid
) {
3392 int ngroups_max
, r
, i
;
3394 if (getgid() == gid
)
3397 if (getegid() == gid
)
3400 ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
3401 assert(ngroups_max
> 0);
3403 gids
= alloca(sizeof(gid_t
) * ngroups_max
);
3405 r
= getgroups(ngroups_max
, gids
);
3409 for (i
= 0; i
< r
; i
++)
3416 int in_group(const char *name
) {
3420 r
= get_group_creds(&name
, &gid
);
3427 int glob_exists(const char *path
) {
3428 _cleanup_globfree_ glob_t g
= {};
3434 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
3436 if (k
== GLOB_NOMATCH
)
3438 else if (k
== GLOB_NOSPACE
)
3441 return !strv_isempty(g
.gl_pathv
);
3443 return errno
? -errno
: -EIO
;
3446 int glob_extend(char ***strv
, const char *path
) {
3447 _cleanup_globfree_ glob_t g
= {};
3452 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
3454 if (k
== GLOB_NOMATCH
)
3456 else if (k
== GLOB_NOSPACE
)
3458 else if (k
!= 0 || strv_isempty(g
.gl_pathv
))
3459 return errno
? -errno
: -EIO
;
3461 STRV_FOREACH(p
, g
.gl_pathv
) {
3462 k
= strv_extend(strv
, *p
);
3470 int dirent_ensure_type(DIR *d
, struct dirent
*de
) {
3476 if (de
->d_type
!= DT_UNKNOWN
)
3479 if (fstatat(dirfd(d
), de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
3483 S_ISREG(st
.st_mode
) ? DT_REG
:
3484 S_ISDIR(st
.st_mode
) ? DT_DIR
:
3485 S_ISLNK(st
.st_mode
) ? DT_LNK
:
3486 S_ISFIFO(st
.st_mode
) ? DT_FIFO
:
3487 S_ISSOCK(st
.st_mode
) ? DT_SOCK
:
3488 S_ISCHR(st
.st_mode
) ? DT_CHR
:
3489 S_ISBLK(st
.st_mode
) ? DT_BLK
:
3495 int get_files_in_directory(const char *path
, char ***list
) {
3496 _cleanup_closedir_
DIR *d
= NULL
;
3497 size_t bufsize
= 0, n
= 0;
3498 _cleanup_strv_free_
char **l
= NULL
;
3502 /* Returns all files in a directory in *list, and the number
3503 * of files as return value. If list is NULL returns only the
3515 if (!de
&& errno
!= 0)
3520 dirent_ensure_type(d
, de
);
3522 if (!dirent_is_file(de
))
3526 /* one extra slot is needed for the terminating NULL */
3527 if (!GREEDY_REALLOC(l
, bufsize
, n
+ 2))
3530 l
[n
] = strdup(de
->d_name
);
3541 l
= NULL
; /* avoid freeing */
3547 char *strjoin(const char *x
, ...) {
3561 t
= va_arg(ap
, const char *);
3566 if (n
> ((size_t) -1) - l
) {
3590 t
= va_arg(ap
, const char *);
3604 bool is_main_thread(void) {
3605 static thread_local
int cached
= 0;
3607 if (_unlikely_(cached
== 0))
3608 cached
= getpid() == gettid() ? 1 : -1;
3613 int block_get_whole_disk(dev_t d
, dev_t
*ret
) {
3620 /* If it has a queue this is good enough for us */
3621 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", major(d
), minor(d
)) < 0)
3624 r
= access(p
, F_OK
);
3632 /* If it is a partition find the originating device */
3633 if (asprintf(&p
, "/sys/dev/block/%u:%u/partition", major(d
), minor(d
)) < 0)
3636 r
= access(p
, F_OK
);
3642 /* Get parent dev_t */
3643 if (asprintf(&p
, "/sys/dev/block/%u:%u/../dev", major(d
), minor(d
)) < 0)
3646 r
= read_one_line_file(p
, &s
);
3652 r
= sscanf(s
, "%u:%u", &m
, &n
);
3658 /* Only return this if it is really good enough for us. */
3659 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", m
, n
) < 0)
3662 r
= access(p
, F_OK
);
3666 *ret
= makedev(m
, n
);
3673 static const char *const ioprio_class_table
[] = {
3674 [IOPRIO_CLASS_NONE
] = "none",
3675 [IOPRIO_CLASS_RT
] = "realtime",
3676 [IOPRIO_CLASS_BE
] = "best-effort",
3677 [IOPRIO_CLASS_IDLE
] = "idle"
3680 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, INT_MAX
);
3682 static const char *const sigchld_code_table
[] = {
3683 [CLD_EXITED
] = "exited",
3684 [CLD_KILLED
] = "killed",
3685 [CLD_DUMPED
] = "dumped",
3686 [CLD_TRAPPED
] = "trapped",
3687 [CLD_STOPPED
] = "stopped",
3688 [CLD_CONTINUED
] = "continued",
3691 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
3693 static const char *const log_facility_unshifted_table
[LOG_NFACILITIES
] = {
3694 [LOG_FAC(LOG_KERN
)] = "kern",
3695 [LOG_FAC(LOG_USER
)] = "user",
3696 [LOG_FAC(LOG_MAIL
)] = "mail",
3697 [LOG_FAC(LOG_DAEMON
)] = "daemon",
3698 [LOG_FAC(LOG_AUTH
)] = "auth",
3699 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
3700 [LOG_FAC(LOG_LPR
)] = "lpr",
3701 [LOG_FAC(LOG_NEWS
)] = "news",
3702 [LOG_FAC(LOG_UUCP
)] = "uucp",
3703 [LOG_FAC(LOG_CRON
)] = "cron",
3704 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
3705 [LOG_FAC(LOG_FTP
)] = "ftp",
3706 [LOG_FAC(LOG_LOCAL0
)] = "local0",
3707 [LOG_FAC(LOG_LOCAL1
)] = "local1",
3708 [LOG_FAC(LOG_LOCAL2
)] = "local2",
3709 [LOG_FAC(LOG_LOCAL3
)] = "local3",
3710 [LOG_FAC(LOG_LOCAL4
)] = "local4",
3711 [LOG_FAC(LOG_LOCAL5
)] = "local5",
3712 [LOG_FAC(LOG_LOCAL6
)] = "local6",
3713 [LOG_FAC(LOG_LOCAL7
)] = "local7"
3716 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted
, int, LOG_FAC(~0));
3718 bool log_facility_unshifted_is_valid(int facility
) {
3719 return facility
>= 0 && facility
<= LOG_FAC(~0);
3722 static const char *const log_level_table
[] = {
3723 [LOG_EMERG
] = "emerg",
3724 [LOG_ALERT
] = "alert",
3725 [LOG_CRIT
] = "crit",
3727 [LOG_WARNING
] = "warning",
3728 [LOG_NOTICE
] = "notice",
3729 [LOG_INFO
] = "info",
3730 [LOG_DEBUG
] = "debug"
3733 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level
, int, LOG_DEBUG
);
3735 bool log_level_is_valid(int level
) {
3736 return level
>= 0 && level
<= LOG_DEBUG
;
3739 static const char* const sched_policy_table
[] = {
3740 [SCHED_OTHER
] = "other",
3741 [SCHED_BATCH
] = "batch",
3742 [SCHED_IDLE
] = "idle",
3743 [SCHED_FIFO
] = "fifo",
3747 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);
3749 static const char* const rlimit_table
[_RLIMIT_MAX
] = {
3750 [RLIMIT_CPU
] = "LimitCPU",
3751 [RLIMIT_FSIZE
] = "LimitFSIZE",
3752 [RLIMIT_DATA
] = "LimitDATA",
3753 [RLIMIT_STACK
] = "LimitSTACK",
3754 [RLIMIT_CORE
] = "LimitCORE",
3755 [RLIMIT_RSS
] = "LimitRSS",
3756 [RLIMIT_NOFILE
] = "LimitNOFILE",
3757 [RLIMIT_AS
] = "LimitAS",
3758 [RLIMIT_NPROC
] = "LimitNPROC",
3759 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
3760 [RLIMIT_LOCKS
] = "LimitLOCKS",
3761 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
3762 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
3763 [RLIMIT_NICE
] = "LimitNICE",
3764 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
3765 [RLIMIT_RTTIME
] = "LimitRTTIME"
3768 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
3770 static const char* const ip_tos_table
[] = {
3771 [IPTOS_LOWDELAY
] = "low-delay",
3772 [IPTOS_THROUGHPUT
] = "throughput",
3773 [IPTOS_RELIABILITY
] = "reliability",
3774 [IPTOS_LOWCOST
] = "low-cost",
3777 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
3779 bool kexec_loaded(void) {
3780 bool loaded
= false;
3783 if (read_one_line_file("/sys/kernel/kexec_loaded", &s
) >= 0) {
3791 int prot_from_flags(int flags
) {
3793 switch (flags
& O_ACCMODE
) {
3802 return PROT_READ
|PROT_WRITE
;
3809 char *format_bytes(char *buf
, size_t l
, uint64_t t
) {
3812 static const struct {
3816 { "E", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3817 { "P", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3818 { "T", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3819 { "G", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3820 { "M", UINT64_C(1024)*UINT64_C(1024) },
3821 { "K", UINT64_C(1024) },
3824 if (t
== (uint64_t) -1)
3827 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
3829 if (t
>= table
[i
].factor
) {
3831 "%" PRIu64
".%" PRIu64
"%s",
3832 t
/ table
[i
].factor
,
3833 ((t
*UINT64_C(10)) / table
[i
].factor
) % UINT64_C(10),
3840 snprintf(buf
, l
, "%" PRIu64
"B", t
);
3848 void* memdup(const void *p
, size_t l
) {
3861 int fd_inc_sndbuf(int fd
, size_t n
) {
3863 socklen_t l
= sizeof(value
);
3865 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
3866 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
3869 /* If we have the privileges we will ignore the kernel limit. */
3872 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
3873 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
3879 int fd_inc_rcvbuf(int fd
, size_t n
) {
3881 socklen_t l
= sizeof(value
);
3883 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
3884 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
3887 /* If we have the privileges we will ignore the kernel limit. */
3890 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
3891 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
3896 int fork_agent(pid_t
*pid
, const int except
[], unsigned n_except
, const char *path
, ...) {
3897 bool stdout_is_tty
, stderr_is_tty
;
3898 pid_t parent_pid
, agent_pid
;
3899 sigset_t ss
, saved_ss
;
3907 /* Spawns a temporary TTY agent, making sure it goes away when
3910 parent_pid
= getpid();
3912 /* First we temporarily block all signals, so that the new
3913 * child has them blocked initially. This way, we can be sure
3914 * that SIGTERMs are not lost we might send to the agent. */
3915 assert_se(sigfillset(&ss
) >= 0);
3916 assert_se(sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) >= 0);
3919 if (agent_pid
< 0) {
3920 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
3924 if (agent_pid
!= 0) {
3925 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
3932 * Make sure the agent goes away when the parent dies */
3933 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
3934 _exit(EXIT_FAILURE
);
3936 /* Make sure we actually can kill the agent, if we need to, in
3937 * case somebody invoked us from a shell script that trapped
3938 * SIGTERM or so... */
3939 (void) reset_all_signal_handlers();
3940 (void) reset_signal_mask();
3942 /* Check whether our parent died before we were able
3943 * to set the death signal and unblock the signals */
3944 if (getppid() != parent_pid
)
3945 _exit(EXIT_SUCCESS
);
3947 /* Don't leak fds to the agent */
3948 close_all_fds(except
, n_except
);
3950 stdout_is_tty
= isatty(STDOUT_FILENO
);
3951 stderr_is_tty
= isatty(STDERR_FILENO
);
3953 if (!stdout_is_tty
|| !stderr_is_tty
) {
3956 /* Detach from stdout/stderr. and reopen
3957 * /dev/tty for them. This is important to
3958 * ensure that when systemctl is started via
3959 * popen() or a similar call that expects to
3960 * read EOF we actually do generate EOF and
3961 * not delay this indefinitely by because we
3962 * keep an unused copy of stdin around. */
3963 fd
= open("/dev/tty", O_WRONLY
);
3965 log_error_errno(errno
, "Failed to open /dev/tty: %m");
3966 _exit(EXIT_FAILURE
);
3970 dup2(fd
, STDOUT_FILENO
);
3973 dup2(fd
, STDERR_FILENO
);
3979 /* Count arguments */
3981 for (n
= 0; va_arg(ap
, char*); n
++)
3986 l
= alloca(sizeof(char *) * (n
+ 1));
3988 /* Fill in arguments */
3990 for (i
= 0; i
<= n
; i
++)
3991 l
[i
] = va_arg(ap
, char*);
3995 _exit(EXIT_FAILURE
);
3998 int setrlimit_closest(int resource
, const struct rlimit
*rlim
) {
3999 struct rlimit highest
, fixed
;
4003 if (setrlimit(resource
, rlim
) >= 0)
4009 /* So we failed to set the desired setrlimit, then let's try
4010 * to get as close as we can */
4011 assert_se(getrlimit(resource
, &highest
) == 0);
4013 fixed
.rlim_cur
= MIN(rlim
->rlim_cur
, highest
.rlim_max
);
4014 fixed
.rlim_max
= MIN(rlim
->rlim_max
, highest
.rlim_max
);
4016 if (setrlimit(resource
, &fixed
) < 0)
4022 bool http_etag_is_valid(const char *etag
) {
4026 if (!endswith(etag
, "\""))
4029 if (!startswith(etag
, "\"") && !startswith(etag
, "W/\""))
4035 bool http_url_is_valid(const char *url
) {
4041 p
= startswith(url
, "http://");
4043 p
= startswith(url
, "https://");
4050 return ascii_is_valid(p
);
4053 bool documentation_url_is_valid(const char *url
) {
4059 if (http_url_is_valid(url
))
4062 p
= startswith(url
, "file:/");
4064 p
= startswith(url
, "info:");
4066 p
= startswith(url
, "man:");
4071 return ascii_is_valid(p
);
4074 bool in_initrd(void) {
4075 static int saved
= -1;
4081 /* We make two checks here:
4083 * 1. the flag file /etc/initrd-release must exist
4084 * 2. the root file system must be a memory file system
4086 * The second check is extra paranoia, since misdetecting an
4087 * initrd can have bad bad consequences due the initrd
4088 * emptying when transititioning to the main systemd.
4091 saved
= access("/etc/initrd-release", F_OK
) >= 0 &&
4092 statfs("/", &s
) >= 0 &&
4093 is_temporary_fs(&s
);
4098 int get_home_dir(char **_h
) {
4106 /* Take the user specified one */
4107 e
= secure_getenv("HOME");
4108 if (e
&& path_is_absolute(e
)) {
4117 /* Hardcode home directory for root to avoid NSS */
4120 h
= strdup("/root");
4128 /* Check the database... */
4132 return errno
> 0 ? -errno
: -ESRCH
;
4134 if (!path_is_absolute(p
->pw_dir
))
4137 h
= strdup(p
->pw_dir
);
4145 int get_shell(char **_s
) {
4153 /* Take the user specified one */
4154 e
= getenv("SHELL");
4164 /* Hardcode home directory for root to avoid NSS */
4167 s
= strdup("/bin/sh");
4175 /* Check the database... */
4179 return errno
> 0 ? -errno
: -ESRCH
;
4181 if (!path_is_absolute(p
->pw_shell
))
4184 s
= strdup(p
->pw_shell
);
4192 bool filename_is_valid(const char *p
) {
4206 if (strlen(p
) > FILENAME_MAX
)
4212 bool string_is_safe(const char *p
) {
4218 for (t
= p
; *t
; t
++) {
4219 if (*t
> 0 && *t
< ' ')
4222 if (strchr("\\\"\'\x7f", *t
))
4230 * Check if a string contains control characters. If 'ok' is non-NULL
4231 * it may be a string containing additional CCs to be considered OK.
4233 bool string_has_cc(const char *p
, const char *ok
) {
4238 for (t
= p
; *t
; t
++) {
4239 if (ok
&& strchr(ok
, *t
))
4242 if (*t
> 0 && *t
< ' ')
4252 bool path_is_safe(const char *p
) {
4257 if (streq(p
, "..") || startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
4260 if (strlen(p
)+1 > PATH_MAX
)
4263 /* The following two checks are not really dangerous, but hey, they still are confusing */
4264 if (streq(p
, ".") || startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
4267 if (strstr(p
, "//"))
4273 /* hey glibc, APIs with callbacks without a user pointer are so useless */
4274 void *xbsearch_r(const void *key
, const void *base
, size_t nmemb
, size_t size
,
4275 int (*compar
) (const void *, const void *, void *), void *arg
) {
4284 p
= (void *)(((const char *) base
) + (idx
* size
));
4285 comparison
= compar(key
, p
, arg
);
4288 else if (comparison
> 0)
4296 void init_gettext(void) {
4297 setlocale(LC_ALL
, "");
4298 textdomain(GETTEXT_PACKAGE
);
4301 bool is_locale_utf8(void) {
4303 static int cached_answer
= -1;
4305 if (cached_answer
>= 0)
4308 if (!setlocale(LC_ALL
, "")) {
4309 cached_answer
= true;
4313 set
= nl_langinfo(CODESET
);
4315 cached_answer
= true;
4319 if (streq(set
, "UTF-8")) {
4320 cached_answer
= true;
4324 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
4325 * unset and everything can do to UTF-8 nowadays. */
4326 set
= setlocale(LC_CTYPE
, NULL
);
4328 cached_answer
= true;
4332 /* Check result, but ignore the result if C was set
4335 STR_IN_SET(set
, "C", "POSIX") &&
4336 !getenv("LC_ALL") &&
4337 !getenv("LC_CTYPE") &&
4341 return (bool) cached_answer
;
4344 const char *draw_special_char(DrawSpecialChar ch
) {
4345 static const char *draw_table
[2][_DRAW_SPECIAL_CHAR_MAX
] = {
4348 [DRAW_TREE_VERTICAL
] = "\342\224\202 ", /* │ */
4349 [DRAW_TREE_BRANCH
] = "\342\224\234\342\224\200", /* ├─ */
4350 [DRAW_TREE_RIGHT
] = "\342\224\224\342\224\200", /* └─ */
4351 [DRAW_TREE_SPACE
] = " ", /* */
4352 [DRAW_TRIANGULAR_BULLET
] = "\342\200\243", /* ‣ */
4353 [DRAW_BLACK_CIRCLE
] = "\342\227\217", /* ● */
4354 [DRAW_ARROW
] = "\342\206\222", /* → */
4355 [DRAW_DASH
] = "\342\200\223", /* – */
4358 /* ASCII fallback */ {
4359 [DRAW_TREE_VERTICAL
] = "| ",
4360 [DRAW_TREE_BRANCH
] = "|-",
4361 [DRAW_TREE_RIGHT
] = "`-",
4362 [DRAW_TREE_SPACE
] = " ",
4363 [DRAW_TRIANGULAR_BULLET
] = ">",
4364 [DRAW_BLACK_CIRCLE
] = "*",
4365 [DRAW_ARROW
] = "->",
4370 return draw_table
[!is_locale_utf8()][ch
];
4373 char *strreplace(const char *text
, const char *old_string
, const char *new_string
) {
4376 size_t l
, old_len
, new_len
;
4382 old_len
= strlen(old_string
);
4383 new_len
= strlen(new_string
);
4396 if (!startswith(f
, old_string
)) {
4402 nl
= l
- old_len
+ new_len
;
4403 a
= realloc(r
, nl
+ 1);
4411 t
= stpcpy(t
, new_string
);
4423 char *strip_tab_ansi(char **ibuf
, size_t *_isz
) {
4424 const char *i
, *begin
= NULL
;
4429 } state
= STATE_OTHER
;
4431 size_t osz
= 0, isz
;
4437 /* Strips ANSI color and replaces TABs by 8 spaces */
4439 isz
= _isz
? *_isz
: strlen(*ibuf
);
4441 f
= open_memstream(&obuf
, &osz
);
4445 for (i
= *ibuf
; i
< *ibuf
+ isz
+ 1; i
++) {
4450 if (i
>= *ibuf
+ isz
) /* EOT */
4452 else if (*i
== '\x1B')
4453 state
= STATE_ESCAPE
;
4454 else if (*i
== '\t')
4461 if (i
>= *ibuf
+ isz
) { /* EOT */
4464 } else if (*i
== '[') {
4465 state
= STATE_BRACKET
;
4470 state
= STATE_OTHER
;
4477 if (i
>= *ibuf
+ isz
|| /* EOT */
4478 (!(*i
>= '0' && *i
<= '9') && *i
!= ';' && *i
!= 'm')) {
4481 state
= STATE_OTHER
;
4483 } else if (*i
== 'm')
4484 state
= STATE_OTHER
;
4506 int on_ac_power(void) {
4507 bool found_offline
= false, found_online
= false;
4508 _cleanup_closedir_
DIR *d
= NULL
;
4510 d
= opendir("/sys/class/power_supply");
4512 return errno
== ENOENT
? true : -errno
;
4516 _cleanup_close_
int fd
= -1, device
= -1;
4522 if (!de
&& errno
!= 0)
4528 if (hidden_file(de
->d_name
))
4531 device
= openat(dirfd(d
), de
->d_name
, O_DIRECTORY
|O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4533 if (errno
== ENOENT
|| errno
== ENOTDIR
)
4539 fd
= openat(device
, "type", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4541 if (errno
== ENOENT
)
4547 n
= read(fd
, contents
, sizeof(contents
));
4551 if (n
!= 6 || memcmp(contents
, "Mains\n", 6))
4555 fd
= openat(device
, "online", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4557 if (errno
== ENOENT
)
4563 n
= read(fd
, contents
, sizeof(contents
));
4567 if (n
!= 2 || contents
[1] != '\n')
4570 if (contents
[0] == '1') {
4571 found_online
= true;
4573 } else if (contents
[0] == '0')
4574 found_offline
= true;
4579 return found_online
|| !found_offline
;
4582 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
4589 if (!path_strv_resolve_uniq(search
, root
))
4592 STRV_FOREACH(i
, search
) {
4593 _cleanup_free_
char *p
= NULL
;
4597 p
= strjoin(root
, *i
, "/", path
, NULL
);
4599 p
= strjoin(*i
, "/", path
, NULL
);
4609 if (errno
!= ENOENT
)
4616 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
4617 _cleanup_strv_free_
char **copy
= NULL
;
4623 if (path_is_absolute(path
)) {
4626 f
= fopen(path
, mode
);
4635 copy
= strv_copy((char**) search
);
4639 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
4642 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
4643 _cleanup_strv_free_
char **s
= NULL
;
4645 if (path_is_absolute(path
)) {
4648 f
= fopen(path
, mode
);
4657 s
= strv_split_nulstr(search
);
4661 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
4664 char *strextend(char **x
, ...) {
4671 l
= f
= *x
? strlen(*x
) : 0;
4678 t
= va_arg(ap
, const char *);
4683 if (n
> ((size_t) -1) - l
) {
4692 r
= realloc(*x
, l
+1);
4702 t
= va_arg(ap
, const char *);
4716 char *strrep(const char *s
, unsigned n
) {
4724 p
= r
= malloc(l
* n
+ 1);
4728 for (i
= 0; i
< n
; i
++)
4735 void* greedy_realloc(void **p
, size_t *allocated
, size_t need
, size_t size
) {
4742 if (*allocated
>= need
)
4745 newalloc
= MAX(need
* 2, 64u / size
);
4746 a
= newalloc
* size
;
4748 /* check for overflows */
4749 if (a
< size
* need
)
4757 *allocated
= newalloc
;
4761 void* greedy_realloc0(void **p
, size_t *allocated
, size_t need
, size_t size
) {
4770 q
= greedy_realloc(p
, allocated
, need
, size
);
4774 if (*allocated
> prev
)
4775 memzero(q
+ prev
* size
, (*allocated
- prev
) * size
);
4780 bool id128_is_valid(const char *s
) {
4786 /* Simple formatted 128bit hex string */
4788 for (i
= 0; i
< l
; i
++) {
4791 if (!(c
>= '0' && c
<= '9') &&
4792 !(c
>= 'a' && c
<= 'z') &&
4793 !(c
>= 'A' && c
<= 'Z'))
4797 } else if (l
== 36) {
4799 /* Formatted UUID */
4801 for (i
= 0; i
< l
; i
++) {
4804 if ((i
== 8 || i
== 13 || i
== 18 || i
== 23)) {
4808 if (!(c
>= '0' && c
<= '9') &&
4809 !(c
>= 'a' && c
<= 'z') &&
4810 !(c
>= 'A' && c
<= 'Z'))
4821 int split_pair(const char *s
, const char *sep
, char **l
, char **r
) {
4836 a
= strndup(s
, x
- s
);
4840 b
= strdup(x
+ strlen(sep
));
4852 int shall_restore_state(void) {
4853 _cleanup_free_
char *value
= NULL
;
4856 r
= get_proc_cmdline_key("systemd.restore_state=", &value
);
4862 return parse_boolean(value
) != 0;
4865 int proc_cmdline(char **ret
) {
4868 if (detect_container() > 0)
4869 return get_process_cmdline(1, 0, false, ret
);
4871 return read_one_line_file("/proc/cmdline", ret
);
4874 int parse_proc_cmdline(int (*parse_item
)(const char *key
, const char *value
)) {
4875 _cleanup_free_
char *line
= NULL
;
4881 r
= proc_cmdline(&line
);
4887 _cleanup_free_
char *word
= NULL
;
4890 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
4896 /* Filter out arguments that are intended only for the
4898 if (!in_initrd() && startswith(word
, "rd."))
4901 value
= strchr(word
, '=');
4905 r
= parse_item(word
, value
);
4913 int get_proc_cmdline_key(const char *key
, char **value
) {
4914 _cleanup_free_
char *line
= NULL
, *ret
= NULL
;
4921 r
= proc_cmdline(&line
);
4927 _cleanup_free_
char *word
= NULL
;
4930 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
4936 /* Filter out arguments that are intended only for the
4938 if (!in_initrd() && startswith(word
, "rd."))
4942 e
= startswith(word
, key
);
4946 r
= free_and_strdup(&ret
, e
);
4952 if (streq(word
, key
))
4966 int container_get_leader(const char *machine
, pid_t
*pid
) {
4967 _cleanup_free_
char *s
= NULL
, *class = NULL
;
4975 if (!machine_name_is_valid(machine
))
4978 p
= strjoina("/run/systemd/machines/", machine
);
4979 r
= parse_env_file(p
, NEWLINE
, "LEADER", &s
, "CLASS", &class, NULL
);
4987 if (!streq_ptr(class, "container"))
4990 r
= parse_pid(s
, &leader
);
5000 int namespace_open(pid_t pid
, int *pidns_fd
, int *mntns_fd
, int *netns_fd
, int *userns_fd
, int *root_fd
) {
5001 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, netnsfd
= -1, usernsfd
= -1;
5009 mntns
= procfs_file_alloca(pid
, "ns/mnt");
5010 mntnsfd
= open(mntns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5018 pidns
= procfs_file_alloca(pid
, "ns/pid");
5019 pidnsfd
= open(pidns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5027 netns
= procfs_file_alloca(pid
, "ns/net");
5028 netnsfd
= open(netns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5036 userns
= procfs_file_alloca(pid
, "ns/user");
5037 usernsfd
= open(userns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5038 if (usernsfd
< 0 && errno
!= ENOENT
)
5045 root
= procfs_file_alloca(pid
, "root");
5046 rfd
= open(root
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
|O_DIRECTORY
);
5052 *pidns_fd
= pidnsfd
;
5055 *mntns_fd
= mntnsfd
;
5058 *netns_fd
= netnsfd
;
5061 *userns_fd
= usernsfd
;
5066 pidnsfd
= mntnsfd
= netnsfd
= usernsfd
= -1;
5071 int namespace_enter(int pidns_fd
, int mntns_fd
, int netns_fd
, int userns_fd
, int root_fd
) {
5072 if (userns_fd
>= 0) {
5073 /* Can't setns to your own userns, since then you could
5074 * escalate from non-root to root in your own namespace, so
5075 * check if namespaces equal before attempting to enter. */
5076 _cleanup_free_
char *userns_fd_path
= NULL
;
5078 if (asprintf(&userns_fd_path
, "/proc/self/fd/%d", userns_fd
) < 0)
5081 r
= files_same(userns_fd_path
, "/proc/self/ns/user");
5089 if (setns(pidns_fd
, CLONE_NEWPID
) < 0)
5093 if (setns(mntns_fd
, CLONE_NEWNS
) < 0)
5097 if (setns(netns_fd
, CLONE_NEWNET
) < 0)
5101 if (setns(userns_fd
, CLONE_NEWUSER
) < 0)
5105 if (fchdir(root_fd
) < 0)
5108 if (chroot(".") < 0)
5112 return reset_uid_gid();
5115 int getpeercred(int fd
, struct ucred
*ucred
) {
5116 socklen_t n
= sizeof(struct ucred
);
5123 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
);
5127 if (n
!= sizeof(struct ucred
))
5130 /* Check if the data is actually useful and not suppressed due
5131 * to namespacing issues */
5134 if (u
.uid
== UID_INVALID
)
5136 if (u
.gid
== GID_INVALID
)
5143 int getpeersec(int fd
, char **ret
) {
5155 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
5159 if (errno
!= ERANGE
)
5166 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
5182 /* This is much like like mkostemp() but is subject to umask(). */
5183 int mkostemp_safe(char *pattern
, int flags
) {
5184 _cleanup_umask_ mode_t u
;
5191 fd
= mkostemp(pattern
, flags
);
5198 int open_tmpfile(const char *path
, int flags
) {
5205 /* Try O_TMPFILE first, if it is supported */
5206 fd
= open(path
, flags
|O_TMPFILE
|O_EXCL
, S_IRUSR
|S_IWUSR
);
5211 /* Fall back to unguessable name + unlinking */
5212 p
= strjoina(path
, "/systemd-tmp-XXXXXX");
5214 fd
= mkostemp_safe(p
, flags
);
5222 int fd_warn_permissions(const char *path
, int fd
) {
5225 if (fstat(fd
, &st
) < 0)
5228 if (st
.st_mode
& 0111)
5229 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path
);
5231 if (st
.st_mode
& 0002)
5232 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path
);
5234 if (getpid() == 1 && (st
.st_mode
& 0044) != 0044)
5235 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
);
5240 unsigned long personality_from_string(const char *p
) {
5242 /* Parse a personality specifier. We introduce our own
5243 * identifiers that indicate specific ABIs, rather than just
5244 * hints regarding the register size, since we want to keep
5245 * things open for multiple locally supported ABIs for the
5246 * same register size. We try to reuse the ABI identifiers
5247 * used by libseccomp. */
5249 #if defined(__x86_64__)
5251 if (streq(p
, "x86"))
5254 if (streq(p
, "x86-64"))
5257 #elif defined(__i386__)
5259 if (streq(p
, "x86"))
5262 #elif defined(__s390x__)
5264 if (streq(p
, "s390"))
5267 if (streq(p
, "s390x"))
5270 #elif defined(__s390__)
5272 if (streq(p
, "s390"))
5276 return PERSONALITY_INVALID
;
5279 const char* personality_to_string(unsigned long p
) {
5281 #if defined(__x86_64__)
5283 if (p
== PER_LINUX32
)
5289 #elif defined(__i386__)
5294 #elif defined(__s390x__)
5299 if (p
== PER_LINUX32
)
5302 #elif defined(__s390__)
5312 uint64_t physical_memory(void) {
5315 /* We return this as uint64_t in case we are running as 32bit
5316 * process on a 64bit kernel with huge amounts of memory */
5318 mem
= sysconf(_SC_PHYS_PAGES
);
5321 return (uint64_t) mem
* (uint64_t) page_size();
5324 void hexdump(FILE *f
, const void *p
, size_t s
) {
5325 const uint8_t *b
= p
;
5328 assert(s
== 0 || b
);
5333 fprintf(f
, "%04x ", n
);
5335 for (i
= 0; i
< 16; i
++) {
5340 fprintf(f
, "%02x ", b
[i
]);
5348 for (i
= 0; i
< 16; i
++) {
5353 fputc(isprint(b
[i
]) ? (char) b
[i
] : '.', f
);
5367 int update_reboot_param_file(const char *param
) {
5371 r
= write_string_file(REBOOT_PARAM_FILE
, param
, WRITE_STRING_FILE_CREATE
);
5373 return log_error_errno(r
, "Failed to write reboot param to "REBOOT_PARAM_FILE
": %m");
5375 (void) unlink(REBOOT_PARAM_FILE
);
5380 int umount_recursive(const char *prefix
, int flags
) {
5384 /* Try to umount everything recursively below a
5385 * directory. Also, take care of stacked mounts, and keep
5386 * unmounting them until they are gone. */
5389 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
5394 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
5395 if (!proc_self_mountinfo
)
5399 _cleanup_free_
char *path
= NULL
, *p
= NULL
;
5402 k
= fscanf(proc_self_mountinfo
,
5403 "%*s " /* (1) mount id */
5404 "%*s " /* (2) parent id */
5405 "%*s " /* (3) major:minor */
5406 "%*s " /* (4) root */
5407 "%ms " /* (5) mount point */
5408 "%*s" /* (6) mount options */
5409 "%*[^-]" /* (7) optional fields */
5410 "- " /* (8) separator */
5411 "%*s " /* (9) file system type */
5412 "%*s" /* (10) mount source */
5413 "%*s" /* (11) mount options 2 */
5414 "%*[^\n]", /* some rubbish at the end */
5423 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
5427 if (!path_startswith(p
, prefix
))
5430 if (umount2(p
, flags
) < 0) {
5446 static int get_mount_flags(const char *path
, unsigned long *flags
) {
5449 if (statvfs(path
, &buf
) < 0)
5451 *flags
= buf
.f_flag
;
5455 int bind_remount_recursive(const char *prefix
, bool ro
) {
5456 _cleanup_set_free_free_ Set
*done
= NULL
;
5457 _cleanup_free_
char *cleaned
= NULL
;
5460 /* Recursively remount a directory (and all its submounts)
5461 * read-only or read-write. If the directory is already
5462 * mounted, we reuse the mount and simply mark it
5463 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
5464 * operation). If it isn't we first make it one. Afterwards we
5465 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
5466 * submounts we can access, too. When mounts are stacked on
5467 * the same mount point we only care for each individual
5468 * "top-level" mount on each point, as we cannot
5469 * influence/access the underlying mounts anyway. We do not
5470 * have any effect on future submounts that might get
5471 * propagated, they migt be writable. This includes future
5472 * submounts that have been triggered via autofs. */
5474 cleaned
= strdup(prefix
);
5478 path_kill_slashes(cleaned
);
5480 done
= set_new(&string_hash_ops
);
5485 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
5486 _cleanup_set_free_free_ Set
*todo
= NULL
;
5487 bool top_autofs
= false;
5489 unsigned long orig_flags
;
5491 todo
= set_new(&string_hash_ops
);
5495 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
5496 if (!proc_self_mountinfo
)
5500 _cleanup_free_
char *path
= NULL
, *p
= NULL
, *type
= NULL
;
5503 k
= fscanf(proc_self_mountinfo
,
5504 "%*s " /* (1) mount id */
5505 "%*s " /* (2) parent id */
5506 "%*s " /* (3) major:minor */
5507 "%*s " /* (4) root */
5508 "%ms " /* (5) mount point */
5509 "%*s" /* (6) mount options (superblock) */
5510 "%*[^-]" /* (7) optional fields */
5511 "- " /* (8) separator */
5512 "%ms " /* (9) file system type */
5513 "%*s" /* (10) mount source */
5514 "%*s" /* (11) mount options (bind mount) */
5515 "%*[^\n]", /* some rubbish at the end */
5525 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
5529 /* Let's ignore autofs mounts. If they aren't
5530 * triggered yet, we want to avoid triggering
5531 * them, as we don't make any guarantees for
5532 * future submounts anyway. If they are
5533 * already triggered, then we will find
5534 * another entry for this. */
5535 if (streq(type
, "autofs")) {
5536 top_autofs
= top_autofs
|| path_equal(cleaned
, p
);
5540 if (path_startswith(p
, cleaned
) &&
5541 !set_contains(done
, p
)) {
5543 r
= set_consume(todo
, p
);
5553 /* If we have no submounts to process anymore and if
5554 * the root is either already done, or an autofs, we
5556 if (set_isempty(todo
) &&
5557 (top_autofs
|| set_contains(done
, cleaned
)))
5560 if (!set_contains(done
, cleaned
) &&
5561 !set_contains(todo
, cleaned
)) {
5562 /* The prefix directory itself is not yet a
5563 * mount, make it one. */
5564 if (mount(cleaned
, cleaned
, NULL
, MS_BIND
|MS_REC
, NULL
) < 0)
5568 (void) get_mount_flags(cleaned
, &orig_flags
);
5569 orig_flags
&= ~MS_RDONLY
;
5571 if (mount(NULL
, prefix
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0)
5574 x
= strdup(cleaned
);
5578 r
= set_consume(done
, x
);
5583 while ((x
= set_steal_first(todo
))) {
5585 r
= set_consume(done
, x
);
5586 if (r
== -EEXIST
|| r
== 0)
5591 /* Try to reuse the original flag set, but
5592 * don't care for errors, in case of
5593 * obstructed mounts */
5595 (void) get_mount_flags(x
, &orig_flags
);
5596 orig_flags
&= ~MS_RDONLY
;
5598 if (mount(NULL
, x
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0) {
5600 /* Deal with mount points that are
5601 * obstructed by a later mount */
5603 if (errno
!= ENOENT
)
5611 int fflush_and_check(FILE *f
) {
5618 return errno
? -errno
: -EIO
;
5623 int tempfn_xxxxxx(const char *p
, const char *extra
, char **ret
) {
5635 * /foo/bar/.#<extra>waldoXXXXXX
5639 if (!filename_is_valid(fn
))
5645 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 6 + 1);
5649 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
), "XXXXXX");
5651 *ret
= path_kill_slashes(t
);
5655 int tempfn_random(const char *p
, const char *extra
, char **ret
) {
5669 * /foo/bar/.#<extra>waldobaa2a261115984a9
5673 if (!filename_is_valid(fn
))
5679 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 16 + 1);
5683 x
= stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
);
5686 for (i
= 0; i
< 16; i
++) {
5687 *(x
++) = hexchar(u
& 0xF);
5693 *ret
= path_kill_slashes(t
);
5697 int tempfn_random_child(const char *p
, const char *extra
, char **ret
) {
5708 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
5714 t
= new(char, strlen(p
) + 3 + strlen(extra
) + 16 + 1);
5718 x
= stpcpy(stpcpy(stpcpy(t
, p
), "/.#"), extra
);
5721 for (i
= 0; i
< 16; i
++) {
5722 *(x
++) = hexchar(u
& 0xF);
5728 *ret
= path_kill_slashes(t
);
5732 int take_password_lock(const char *root
) {
5734 struct flock flock
= {
5736 .l_whence
= SEEK_SET
,
5744 /* This is roughly the same as lckpwdf(), but not as awful. We
5745 * don't want to use alarm() and signals, hence we implement
5746 * our own trivial version of this.
5748 * Note that shadow-utils also takes per-database locks in
5749 * addition to lckpwdf(). However, we don't given that they
5750 * are redundant as they they invoke lckpwdf() first and keep
5751 * it during everything they do. The per-database locks are
5752 * awfully racy, and thus we just won't do them. */
5755 path
= strjoina(root
, "/etc/.pwd.lock");
5757 path
= "/etc/.pwd.lock";
5759 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
5763 r
= fcntl(fd
, F_SETLKW
, &flock
);
5772 int is_symlink(const char *path
) {
5775 if (lstat(path
, &info
) < 0)
5778 return !!S_ISLNK(info
.st_mode
);
5781 int is_dir(const char* path
, bool follow
) {
5786 r
= stat(path
, &st
);
5788 r
= lstat(path
, &st
);
5792 return !!S_ISDIR(st
.st_mode
);
5795 int is_device_node(const char *path
) {
5798 if (lstat(path
, &info
) < 0)
5801 return !!(S_ISBLK(info
.st_mode
) || S_ISCHR(info
.st_mode
));
5804 int extract_first_word(const char **p
, char **ret
, const char *separators
, ExtractFlags flags
) {
5805 _cleanup_free_
char *s
= NULL
;
5806 size_t allocated
= 0, sz
= 0;
5814 SINGLE_QUOTE_ESCAPE
,
5816 DOUBLE_QUOTE_ESCAPE
,
5824 separators
= WHITESPACE
;
5826 /* Bail early if called after last value or with no input */
5828 goto finish_force_terminate
;
5830 /* Parses the first word of a string, and returns it in
5831 * *ret. Removes all quotes in the process. When parsing fails
5832 * (because of an uneven number of quotes or similar), leaves
5833 * the pointer *p at the first invalid character. */
5841 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
)
5842 if (!GREEDY_REALLOC(s
, allocated
, sz
+1))
5846 goto finish_force_terminate
;
5847 else if (strchr(separators
, c
)) {
5848 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
) {
5850 goto finish_force_next
;
5855 /* We found a non-blank character, so we will always
5856 * want to return a string (even if it is empty),
5857 * allocate it here. */
5858 if (!GREEDY_REALLOC(s
, allocated
, sz
+1))
5866 goto finish_force_terminate
;
5867 else if (c
== '\'' && (flags
& EXTRACT_QUOTES
))
5868 state
= SINGLE_QUOTE
;
5870 state
= VALUE_ESCAPE
;
5871 else if (c
== '\"' && (flags
& EXTRACT_QUOTES
))
5872 state
= DOUBLE_QUOTE
;
5873 else if (strchr(separators
, c
)) {
5874 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
) {
5876 goto finish_force_next
;
5880 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5890 if (flags
& EXTRACT_RELAX
)
5891 goto finish_force_terminate
;
5893 } else if (c
== '\'')
5896 state
= SINGLE_QUOTE_ESCAPE
;
5898 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5908 if (flags
& EXTRACT_RELAX
)
5909 goto finish_force_terminate
;
5911 } else if (c
== '\"')
5914 state
= DOUBLE_QUOTE_ESCAPE
;
5916 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5924 case SINGLE_QUOTE_ESCAPE
:
5925 case DOUBLE_QUOTE_ESCAPE
:
5927 if (!GREEDY_REALLOC(s
, allocated
, sz
+7))
5931 if ((flags
& EXTRACT_CUNESCAPE_RELAX
) &&
5932 (state
== VALUE_ESCAPE
|| flags
& EXTRACT_RELAX
)) {
5933 /* If we find an unquoted trailing backslash and we're in
5934 * EXTRACT_CUNESCAPE_RELAX mode, keep it verbatim in the
5937 * Unbalanced quotes will only be allowed in EXTRACT_RELAX
5938 * mode, EXTRACT_CUNESCAPE_RELAX mode does not allow them.
5941 goto finish_force_terminate
;
5943 if (flags
& EXTRACT_RELAX
)
5944 goto finish_force_terminate
;
5948 if (flags
& EXTRACT_CUNESCAPE
) {
5951 r
= cunescape_one(*p
, (size_t) -1, &c
, &u
);
5953 if (flags
& EXTRACT_CUNESCAPE_RELAX
) {
5964 s
[sz
++] = c
; /* normal explicit char */
5966 sz
+= utf8_encode_unichar(s
+ sz
, u
); /* unicode chars we'll encode as utf8 */
5971 state
= (state
== SINGLE_QUOTE_ESCAPE
) ? SINGLE_QUOTE
:
5972 (state
== DOUBLE_QUOTE_ESCAPE
) ? DOUBLE_QUOTE
:
5978 goto finish_force_terminate
;
5979 if (!strchr(separators
, c
))
5987 finish_force_terminate
:
6004 int extract_first_word_and_warn(
6007 const char *separators
,
6010 const char *filename
,
6012 const char *rvalue
) {
6014 /* Try to unquote it, if it fails, warn about it and try again but this
6015 * time using EXTRACT_CUNESCAPE_RELAX to keep the backslashes verbatim
6016 * in invalid escape sequences. */
6021 r
= extract_first_word(p
, ret
, separators
, flags
);
6022 if (r
< 0 && !(flags
& EXTRACT_CUNESCAPE_RELAX
)) {
6024 /* Retry it with EXTRACT_CUNESCAPE_RELAX. */
6026 r
= extract_first_word(p
, ret
, separators
, flags
|EXTRACT_CUNESCAPE_RELAX
);
6028 log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Unbalanced quoting in command line, ignoring: \"%s\"", rvalue
);
6030 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0, "Invalid escape sequences in command line: \"%s\"", rvalue
);
6036 int extract_many_words(const char **p
, const char *separators
, ExtractFlags flags
, ...) {
6041 /* Parses a number of words from a string, stripping any
6042 * quotes if necessary. */
6046 /* Count how many words are expected */
6047 va_start(ap
, flags
);
6049 if (!va_arg(ap
, char **))
6058 /* Read all words into a temporary array */
6059 l
= newa0(char*, n
);
6060 for (c
= 0; c
< n
; c
++) {
6062 r
= extract_first_word(p
, &l
[c
], separators
, flags
);
6066 for (j
= 0; j
< c
; j
++)
6076 /* If we managed to parse all words, return them in the passed
6078 va_start(ap
, flags
);
6079 for (i
= 0; i
< n
; i
++) {
6082 v
= va_arg(ap
, char **);
6092 int free_and_strdup(char **p
, const char *s
) {
6097 /* Replaces a string pointer with an strdup()ed new string,
6098 * possibly freeing the old one. */
6100 if (streq_ptr(*p
, s
))
6116 ssize_t
fgetxattrat_fake(int dirfd
, const char *filename
, const char *attribute
, void *value
, size_t size
, int flags
) {
6117 char fn
[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(int) + 1];
6118 _cleanup_close_
int fd
= -1;
6121 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
6123 fd
= openat(dirfd
, filename
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_PATH
|(flags
& AT_SYMLINK_NOFOLLOW
? O_NOFOLLOW
: 0));
6127 xsprintf(fn
, "/proc/self/fd/%i", fd
);
6129 l
= getxattr(fn
, attribute
, value
, size
);
6136 static int parse_crtime(le64_t le
, usec_t
*usec
) {
6142 if (u
== 0 || u
== (uint64_t) -1)
6149 int fd_getcrtime(int fd
, usec_t
*usec
) {
6156 /* Until Linux gets a real concept of birthtime/creation time,
6157 * let's fake one with xattrs */
6159 n
= fgetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
));
6162 if (n
!= sizeof(le
))
6165 return parse_crtime(le
, usec
);
6168 int fd_getcrtime_at(int dirfd
, const char *name
, usec_t
*usec
, int flags
) {
6172 n
= fgetxattrat_fake(dirfd
, name
, "user.crtime_usec", &le
, sizeof(le
), flags
);
6175 if (n
!= sizeof(le
))
6178 return parse_crtime(le
, usec
);
6181 int path_getcrtime(const char *p
, usec_t
*usec
) {
6188 n
= getxattr(p
, "user.crtime_usec", &le
, sizeof(le
));
6191 if (n
!= sizeof(le
))
6194 return parse_crtime(le
, usec
);
6197 int fd_setcrtime(int fd
, usec_t usec
) {
6203 usec
= now(CLOCK_REALTIME
);
6205 le
= htole64((uint64_t) usec
);
6206 if (fsetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
), 0) < 0)
6212 int same_fd(int a
, int b
) {
6213 struct stat sta
, stb
;
6220 /* Compares two file descriptors. Note that semantics are
6221 * quite different depending on whether we have kcmp() or we
6222 * don't. If we have kcmp() this will only return true for
6223 * dup()ed file descriptors, but not otherwise. If we don't
6224 * have kcmp() this will also return true for two fds of the same
6225 * file, created by separate open() calls. Since we use this
6226 * call mostly for filtering out duplicates in the fd store
6227 * this difference hopefully doesn't matter too much. */
6232 /* Try to use kcmp() if we have it. */
6234 r
= kcmp(pid
, pid
, KCMP_FILE
, a
, b
);
6239 if (errno
!= ENOSYS
)
6242 /* We don't have kcmp(), use fstat() instead. */
6243 if (fstat(a
, &sta
) < 0)
6246 if (fstat(b
, &stb
) < 0)
6249 if ((sta
.st_mode
& S_IFMT
) != (stb
.st_mode
& S_IFMT
))
6252 /* We consider all device fds different, since two device fds
6253 * might refer to quite different device contexts even though
6254 * they share the same inode and backing dev_t. */
6256 if (S_ISCHR(sta
.st_mode
) || S_ISBLK(sta
.st_mode
))
6259 if (sta
.st_dev
!= stb
.st_dev
|| sta
.st_ino
!= stb
.st_ino
)
6262 /* The fds refer to the same inode on disk, let's also check
6263 * if they have the same fd flags. This is useful to
6264 * distinguish the read and write side of a pipe created with
6266 fa
= fcntl(a
, F_GETFL
);
6270 fb
= fcntl(b
, F_GETFL
);
6277 int chattr_fd(int fd
, unsigned value
, unsigned mask
) {
6278 unsigned old_attr
, new_attr
;
6283 if (fstat(fd
, &st
) < 0)
6286 /* Explicitly check whether this is a regular file or
6287 * directory. If it is anything else (such as a device node or
6288 * fifo), then the ioctl will not hit the file systems but
6289 * possibly drivers, where the ioctl might have different
6290 * effects. Notably, DRM is using the same ioctl() number. */
6292 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
6298 if (ioctl(fd
, FS_IOC_GETFLAGS
, &old_attr
) < 0)
6301 new_attr
= (old_attr
& ~mask
) | (value
& mask
);
6302 if (new_attr
== old_attr
)
6305 if (ioctl(fd
, FS_IOC_SETFLAGS
, &new_attr
) < 0)
6311 int chattr_path(const char *p
, unsigned value
, unsigned mask
) {
6312 _cleanup_close_
int fd
= -1;
6319 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
6323 return chattr_fd(fd
, value
, mask
);
6326 int read_attr_fd(int fd
, unsigned *ret
) {
6331 if (fstat(fd
, &st
) < 0)
6334 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
6337 if (ioctl(fd
, FS_IOC_GETFLAGS
, ret
) < 0)
6343 int read_attr_path(const char *p
, unsigned *ret
) {
6344 _cleanup_close_
int fd
= -1;
6349 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
6353 return read_attr_fd(fd
, ret
);
6356 static size_t nul_length(const uint8_t *p
, size_t sz
) {
6371 ssize_t
sparse_write(int fd
, const void *p
, size_t sz
, size_t run_length
) {
6372 const uint8_t *q
, *w
, *e
;
6380 n
= nul_length(q
, e
- q
);
6382 /* If there are more than the specified run length of
6383 * NUL bytes, or if this is the beginning or the end
6384 * of the buffer, then seek instead of write */
6385 if ((n
> run_length
) ||
6386 (n
> 0 && q
== p
) ||
6387 (n
> 0 && q
+ n
>= e
)) {
6389 l
= write(fd
, w
, q
- w
);
6396 if (lseek(fd
, n
, SEEK_CUR
) == (off_t
) -1)
6408 l
= write(fd
, w
, q
- w
);
6415 return q
- (const uint8_t*) p
;
6418 void sigkill_wait(pid_t
*pid
) {
6424 if (kill(*pid
, SIGKILL
) > 0)
6425 (void) wait_for_terminate(*pid
, NULL
);
6428 int syslog_parse_priority(const char **p
, int *priority
, bool with_facility
) {
6429 int a
= 0, b
= 0, c
= 0;
6439 if (!strchr(*p
, '>'))
6442 if ((*p
)[2] == '>') {
6443 c
= undecchar((*p
)[1]);
6445 } else if ((*p
)[3] == '>') {
6446 b
= undecchar((*p
)[1]);
6447 c
= undecchar((*p
)[2]);
6449 } else if ((*p
)[4] == '>') {
6450 a
= undecchar((*p
)[1]);
6451 b
= undecchar((*p
)[2]);
6452 c
= undecchar((*p
)[3]);
6457 if (a
< 0 || b
< 0 || c
< 0 ||
6458 (!with_facility
&& (a
|| b
|| c
> 7)))
6462 *priority
= a
*100 + b
*10 + c
;
6464 *priority
= (*priority
& LOG_FACMASK
) | c
;
6470 ssize_t
string_table_lookup(const char * const *table
, size_t len
, const char *key
) {
6476 for (i
= 0; i
< len
; ++i
)
6477 if (streq_ptr(table
[i
], key
))
6483 void cmsg_close_all(struct msghdr
*mh
) {
6484 struct cmsghdr
*cmsg
;
6488 CMSG_FOREACH(cmsg
, mh
)
6489 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
)
6490 close_many((int*) CMSG_DATA(cmsg
), (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int));
6493 int rename_noreplace(int olddirfd
, const char *oldpath
, int newdirfd
, const char *newpath
) {
6497 ret
= renameat2(olddirfd
, oldpath
, newdirfd
, newpath
, RENAME_NOREPLACE
);
6501 /* renameat2() exists since Linux 3.15, btrfs added support for it later.
6502 * If it is not implemented, fallback to another method. */
6503 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
6506 /* The link()/unlink() fallback does not work on directories. But
6507 * renameat() without RENAME_NOREPLACE gives the same semantics on
6508 * directories, except when newpath is an *empty* directory. This is
6510 ret
= fstatat(olddirfd
, oldpath
, &buf
, AT_SYMLINK_NOFOLLOW
);
6511 if (ret
>= 0 && S_ISDIR(buf
.st_mode
)) {
6512 ret
= renameat(olddirfd
, oldpath
, newdirfd
, newpath
);
6513 return ret
>= 0 ? 0 : -errno
;
6516 /* If it is not a directory, use the link()/unlink() fallback. */
6517 ret
= linkat(olddirfd
, oldpath
, newdirfd
, newpath
, 0);
6521 ret
= unlinkat(olddirfd
, oldpath
, 0);
6523 /* backup errno before the following unlinkat() alters it */
6525 (void) unlinkat(newdirfd
, newpath
, 0);
6533 static char *strcpy_backslash_escaped(char *t
, const char *s
, const char *bad
) {
6537 if (*s
== '\\' || strchr(bad
, *s
))
6546 char *shell_escape(const char *s
, const char *bad
) {
6549 r
= new(char, strlen(s
)*2+1);
6553 t
= strcpy_backslash_escaped(r
, s
, bad
);
6559 char *shell_maybe_quote(const char *s
) {
6565 /* Encloses a string in double quotes if necessary to make it
6566 * OK as shell string. */
6568 for (p
= s
; *p
; p
++)
6571 strchr(SHELL_NEED_QUOTES
, *p
))
6577 r
= new(char, 1+strlen(s
)*2+1+1);
6583 t
= mempcpy(t
, s
, p
- s
);
6585 t
= strcpy_backslash_escaped(t
, p
, SHELL_NEED_ESCAPE
);
6593 int parse_mode(const char *s
, mode_t
*ret
) {
6601 l
= strtol(s
, &x
, 8);
6605 if (!x
|| x
== s
|| *x
)
6607 if (l
< 0 || l
> 07777)
6614 int mount_move_root(const char *path
) {
6617 if (chdir(path
) < 0)
6620 if (mount(path
, "/", NULL
, MS_MOVE
, NULL
) < 0)
6623 if (chroot(".") < 0)
6632 int reset_uid_gid(void) {
6634 if (setgroups(0, NULL
) < 0)
6637 if (setresgid(0, 0, 0) < 0)
6640 if (setresuid(0, 0, 0) < 0)
6646 int getxattr_malloc(const char *path
, const char *name
, char **value
, bool allow_symlink
) {
6655 for (l
= 100; ; l
= (size_t) n
+ 1) {
6661 n
= lgetxattr(path
, name
, v
, l
);
6663 n
= getxattr(path
, name
, v
, l
);
6665 if (n
>= 0 && (size_t) n
< l
) {
6672 if (n
< 0 && errno
!= ERANGE
)
6676 n
= lgetxattr(path
, name
, NULL
, 0);
6678 n
= getxattr(path
, name
, NULL
, 0);
6684 int fgetxattr_malloc(int fd
, const char *name
, char **value
) {
6693 for (l
= 100; ; l
= (size_t) n
+ 1) {
6698 n
= fgetxattr(fd
, name
, v
, l
);
6700 if (n
>= 0 && (size_t) n
< l
) {
6707 if (n
< 0 && errno
!= ERANGE
)
6710 n
= fgetxattr(fd
, name
, NULL
, 0);
6716 int send_one_fd(int transport_fd
, int fd
, int flags
) {
6718 struct cmsghdr cmsghdr
;
6719 uint8_t buf
[CMSG_SPACE(sizeof(int))];
6721 struct msghdr mh
= {
6722 .msg_control
= &control
,
6723 .msg_controllen
= sizeof(control
),
6725 struct cmsghdr
*cmsg
;
6727 assert(transport_fd
>= 0);
6730 cmsg
= CMSG_FIRSTHDR(&mh
);
6731 cmsg
->cmsg_level
= SOL_SOCKET
;
6732 cmsg
->cmsg_type
= SCM_RIGHTS
;
6733 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
6734 memcpy(CMSG_DATA(cmsg
), &fd
, sizeof(int));
6736 mh
.msg_controllen
= CMSG_SPACE(sizeof(int));
6737 if (sendmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| flags
) < 0)
6743 int receive_one_fd(int transport_fd
, int flags
) {
6745 struct cmsghdr cmsghdr
;
6746 uint8_t buf
[CMSG_SPACE(sizeof(int))];
6748 struct msghdr mh
= {
6749 .msg_control
= &control
,
6750 .msg_controllen
= sizeof(control
),
6752 struct cmsghdr
*cmsg
, *found
= NULL
;
6754 assert(transport_fd
>= 0);
6757 * Receive a single FD via @transport_fd. We don't care for
6758 * the transport-type. We retrieve a single FD at most, so for
6759 * packet-based transports, the caller must ensure to send
6760 * only a single FD per packet. This is best used in
6761 * combination with send_one_fd().
6764 if (recvmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| MSG_CMSG_CLOEXEC
| flags
) < 0)
6767 CMSG_FOREACH(cmsg
, &mh
) {
6768 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
6769 cmsg
->cmsg_type
== SCM_RIGHTS
&&
6770 cmsg
->cmsg_len
== CMSG_LEN(sizeof(int))) {
6778 cmsg_close_all(&mh
);
6782 return *(int*) CMSG_DATA(found
);
6785 void nop_signal_handler(int sig
) {
6790 puts(PACKAGE_STRING
"\n"
6795 bool fdname_is_valid(const char *s
) {
6798 /* Validates a name for $LISTEN_FDNAMES. We basically allow
6799 * everything ASCII that's not a control character. Also, as
6800 * special exception the ":" character is not allowed, as we
6801 * use that as field separator in $LISTEN_FDNAMES.
6803 * Note that the empty string is explicitly allowed
6804 * here. However, we limit the length of the names to 255
6810 for (p
= s
; *p
; p
++) {
6822 bool oom_score_adjust_is_valid(int oa
) {
6823 return oa
>= OOM_SCORE_ADJ_MIN
&& oa
<= OOM_SCORE_ADJ_MAX
;
6826 void string_erase(char *x
) {
6831 /* A delicious drop of snake-oil! To be called on memory where
6832 * we stored passphrases or so, after we used them. */
6834 memory_erase(x
, strlen(x
));
6837 char *string_free_erase(char *s
) {