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"
81 #include "exit-status.h"
84 #include "formats-util.h"
87 #include "hostname-util.h"
93 #include "path-util.h"
94 #include "process-util.h"
95 #include "random-util.h"
96 #include "signal-util.h"
97 #include "sparse-endian.h"
98 #include "string-util.h"
100 #include "terminal-util.h"
105 /* Put this test here for a lack of better place */
106 assert_cc(EAGAIN
== EWOULDBLOCK
);
109 char **saved_argv
= NULL
;
111 size_t page_size(void) {
112 static thread_local
size_t pgsz
= 0;
115 if (_likely_(pgsz
> 0))
118 r
= sysconf(_SC_PAGESIZE
);
125 int unlink_noerrno(const char *path
) {
136 int parse_boolean(const char *v
) {
139 if (streq(v
, "1") || strcaseeq(v
, "yes") || strcaseeq(v
, "y") || strcaseeq(v
, "true") || strcaseeq(v
, "t") || strcaseeq(v
, "on"))
141 else if (streq(v
, "0") || strcaseeq(v
, "no") || strcaseeq(v
, "n") || strcaseeq(v
, "false") || strcaseeq(v
, "f") || strcaseeq(v
, "off"))
147 int parse_pid(const char *s
, pid_t
* ret_pid
) {
148 unsigned long ul
= 0;
155 r
= safe_atolu(s
, &ul
);
161 if ((unsigned long) pid
!= ul
)
171 bool uid_is_valid(uid_t uid
) {
173 /* Some libc APIs use UID_INVALID as special placeholder */
174 if (uid
== (uid_t
) 0xFFFFFFFF)
177 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
178 if (uid
== (uid_t
) 0xFFFF)
184 int parse_uid(const char *s
, uid_t
* ret_uid
) {
185 unsigned long ul
= 0;
191 r
= safe_atolu(s
, &ul
);
197 if ((unsigned long) uid
!= ul
)
200 if (!uid_is_valid(uid
))
201 return -ENXIO
; /* we return ENXIO instead of EINVAL
202 * here, to make it easy to distuingish
203 * invalid numeric uids invalid
212 int safe_atou(const char *s
, unsigned *ret_u
) {
220 l
= strtoul(s
, &x
, 0);
222 if (!x
|| x
== s
|| *x
|| errno
)
223 return errno
> 0 ? -errno
: -EINVAL
;
225 if ((unsigned long) (unsigned) l
!= l
)
228 *ret_u
= (unsigned) l
;
232 int safe_atoi(const char *s
, int *ret_i
) {
240 l
= strtol(s
, &x
, 0);
242 if (!x
|| x
== s
|| *x
|| errno
)
243 return errno
> 0 ? -errno
: -EINVAL
;
245 if ((long) (int) l
!= l
)
252 int safe_atou8(const char *s
, uint8_t *ret
) {
260 l
= strtoul(s
, &x
, 0);
262 if (!x
|| x
== s
|| *x
|| errno
)
263 return errno
> 0 ? -errno
: -EINVAL
;
265 if ((unsigned long) (uint8_t) l
!= l
)
272 int safe_atou16(const char *s
, uint16_t *ret
) {
280 l
= strtoul(s
, &x
, 0);
282 if (!x
|| x
== s
|| *x
|| errno
)
283 return errno
> 0 ? -errno
: -EINVAL
;
285 if ((unsigned long) (uint16_t) l
!= l
)
292 int safe_atoi16(const char *s
, int16_t *ret
) {
300 l
= strtol(s
, &x
, 0);
302 if (!x
|| x
== s
|| *x
|| errno
)
303 return errno
> 0 ? -errno
: -EINVAL
;
305 if ((long) (int16_t) l
!= l
)
312 int safe_atollu(const char *s
, long long unsigned *ret_llu
) {
314 unsigned long long l
;
320 l
= strtoull(s
, &x
, 0);
322 if (!x
|| x
== s
|| *x
|| errno
)
323 return errno
? -errno
: -EINVAL
;
329 int safe_atolli(const char *s
, long long int *ret_lli
) {
337 l
= strtoll(s
, &x
, 0);
339 if (!x
|| x
== s
|| *x
|| errno
)
340 return errno
? -errno
: -EINVAL
;
346 int safe_atod(const char *s
, double *ret_d
) {
354 loc
= newlocale(LC_NUMERIC_MASK
, "C", (locale_t
) 0);
355 if (loc
== (locale_t
) 0)
359 d
= strtod_l(s
, &x
, loc
);
361 if (!x
|| x
== s
|| *x
|| errno
) {
363 return errno
? -errno
: -EINVAL
;
372 int fchmod_umask(int fd
, mode_t m
) {
377 r
= fchmod(fd
, m
& (~u
)) < 0 ? -errno
: 0;
383 int readlinkat_malloc(int fd
, const char *p
, char **ret
) {
398 n
= readlinkat(fd
, p
, c
, l
-1);
405 if ((size_t) n
< l
-1) {
416 int readlink_malloc(const char *p
, char **ret
) {
417 return readlinkat_malloc(AT_FDCWD
, p
, ret
);
420 int readlink_value(const char *p
, char **ret
) {
421 _cleanup_free_
char *link
= NULL
;
425 r
= readlink_malloc(p
, &link
);
429 value
= basename(link
);
433 value
= strdup(value
);
442 int readlink_and_make_absolute(const char *p
, char **r
) {
443 _cleanup_free_
char *target
= NULL
;
450 j
= readlink_malloc(p
, &target
);
454 k
= file_in_same_dir(p
, target
);
462 int readlink_and_canonicalize(const char *p
, char **r
) {
469 j
= readlink_and_make_absolute(p
, &t
);
473 s
= canonicalize_file_name(t
);
480 path_kill_slashes(*r
);
485 char *file_in_same_dir(const char *path
, const char *filename
) {
492 /* This removes the last component of path and appends
493 * filename, unless the latter is absolute anyway or the
496 if (path_is_absolute(filename
))
497 return strdup(filename
);
499 e
= strrchr(path
, '/');
501 return strdup(filename
);
503 k
= strlen(filename
);
504 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
508 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
512 int rmdir_parents(const char *path
, const char *stop
) {
521 /* Skip trailing slashes */
522 while (l
> 0 && path
[l
-1] == '/')
528 /* Skip last component */
529 while (l
> 0 && path
[l
-1] != '/')
532 /* Skip trailing slashes */
533 while (l
> 0 && path
[l
-1] == '/')
539 if (!(t
= strndup(path
, l
)))
542 if (path_startswith(stop
, t
)) {
558 char hexchar(int x
) {
559 static const char table
[16] = "0123456789abcdef";
561 return table
[x
& 15];
564 int unhexchar(char c
) {
566 if (c
>= '0' && c
<= '9')
569 if (c
>= 'a' && c
<= 'f')
572 if (c
>= 'A' && c
<= 'F')
578 char *hexmem(const void *p
, size_t l
) {
582 z
= r
= malloc(l
* 2 + 1);
586 for (x
= p
; x
< (const uint8_t*) p
+ l
; x
++) {
587 *(z
++) = hexchar(*x
>> 4);
588 *(z
++) = hexchar(*x
& 15);
595 int unhexmem(const char *p
, size_t l
, void **mem
, size_t *len
) {
596 _cleanup_free_
uint8_t *r
= NULL
;
604 z
= r
= malloc((l
+ 1) / 2 + 1);
608 for (x
= p
; x
< p
+ l
; x
+= 2) {
614 else if (x
+1 < p
+ l
) {
621 *(z
++) = (uint8_t) a
<< 4 | (uint8_t) b
;
633 /* https://tools.ietf.org/html/rfc4648#section-6
634 * Notice that base32hex differs from base32 in the alphabet it uses.
635 * The distinction is that the base32hex representation preserves the
636 * order of the underlying data when compared as bytestrings, this is
637 * useful when representing NSEC3 hashes, as one can then verify the
638 * order of hashes directly from their representation. */
639 char base32hexchar(int x
) {
640 static const char table
[32] = "0123456789"
641 "ABCDEFGHIJKLMNOPQRSTUV";
643 return table
[x
& 31];
646 int unbase32hexchar(char c
) {
649 if (c
>= '0' && c
<= '9')
652 offset
= '9' - '0' + 1;
654 if (c
>= 'A' && c
<= 'V')
655 return c
- 'A' + offset
;
660 char *base32hexmem(const void *p
, size_t l
, bool padding
) {
666 /* five input bytes makes eight output bytes, padding is added so we must round up */
667 len
= 8 * (l
+ 4) / 5;
669 /* same, but round down as there is no padding */
688 z
= r
= malloc(len
+ 1);
692 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 5) * 5; x
+= 5) {
693 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ
694 x[3] == QQQQQQQQ; x[4] == WWWWWWWW */
695 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
696 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
697 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
698 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
699 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
700 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
701 *(z
++) = base32hexchar((x
[3] & 3) << 3 | x
[4] >> 5); /* 000QQWWW */
702 *(z
++) = base32hexchar((x
[4] & 31)); /* 000WWWWW */
707 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
708 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
709 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
710 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
711 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
712 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
713 *(z
++) = base32hexchar((x
[3] & 3) << 3); /* 000QQ000 */
720 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
721 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
722 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
723 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
724 *(z
++) = base32hexchar((x
[2] & 15) << 1); /* 000ZZZZ0 */
734 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
735 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
736 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
737 *(z
++) = base32hexchar((x
[1] & 1) << 4); /* 000Y0000 */
748 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
749 *(z
++) = base32hexchar((x
[0] & 7) << 2); /* 000XXX00 */
766 int unbase32hexmem(const char *p
, size_t l
, bool padding
, void **mem
, size_t *_len
) {
767 _cleanup_free_
uint8_t *r
= NULL
;
768 int a
, b
, c
, d
, e
, f
, g
, h
;
776 /* padding ensures any base32hex input has input divisible by 8 */
777 if (padding
&& l
% 8 != 0)
781 /* strip the padding */
782 while (l
> 0 && p
[l
- 1] == '=' && pad
< 7) {
788 /* a group of eight input bytes needs five output bytes, in case of
789 padding we need to add some extra bytes */
811 z
= r
= malloc(len
+ 1);
815 for (x
= p
; x
< p
+ (l
/ 8) * 8; x
+= 8) {
816 /* a == 000XXXXX; b == 000YYYYY; c == 000ZZZZZ; d == 000WWWWW
817 e == 000SSSSS; f == 000QQQQQ; g == 000VVVVV; h == 000RRRRR */
818 a
= unbase32hexchar(x
[0]);
822 b
= unbase32hexchar(x
[1]);
826 c
= unbase32hexchar(x
[2]);
830 d
= unbase32hexchar(x
[3]);
834 e
= unbase32hexchar(x
[4]);
838 f
= unbase32hexchar(x
[5]);
842 g
= unbase32hexchar(x
[6]);
846 h
= unbase32hexchar(x
[7]);
850 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
851 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
852 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
853 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
854 *(z
++) = (uint8_t) g
<< 5 | (uint8_t) h
; /* VVVRRRRR */
859 a
= unbase32hexchar(x
[0]);
863 b
= unbase32hexchar(x
[1]);
867 c
= unbase32hexchar(x
[2]);
871 d
= unbase32hexchar(x
[3]);
875 e
= unbase32hexchar(x
[4]);
879 f
= unbase32hexchar(x
[5]);
883 g
= unbase32hexchar(x
[6]);
891 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
892 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
893 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
894 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
898 a
= unbase32hexchar(x
[0]);
902 b
= unbase32hexchar(x
[1]);
906 c
= unbase32hexchar(x
[2]);
910 d
= unbase32hexchar(x
[3]);
914 e
= unbase32hexchar(x
[4]);
922 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
923 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
924 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
928 a
= unbase32hexchar(x
[0]);
932 b
= unbase32hexchar(x
[1]);
936 c
= unbase32hexchar(x
[2]);
940 d
= unbase32hexchar(x
[3]);
948 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
949 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
953 a
= unbase32hexchar(x
[0]);
957 b
= unbase32hexchar(x
[1]);
965 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
983 /* https://tools.ietf.org/html/rfc4648#section-4 */
984 char base64char(int x
) {
985 static const char table
[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
986 "abcdefghijklmnopqrstuvwxyz"
988 return table
[x
& 63];
991 int unbase64char(char c
) {
994 if (c
>= 'A' && c
<= 'Z')
997 offset
= 'Z' - 'A' + 1;
999 if (c
>= 'a' && c
<= 'z')
1000 return c
- 'a' + offset
;
1002 offset
+= 'z' - 'a' + 1;
1004 if (c
>= '0' && c
<= '9')
1005 return c
- '0' + offset
;
1007 offset
+= '9' - '0' + 1;
1020 char *base64mem(const void *p
, size_t l
) {
1024 /* three input bytes makes four output bytes, padding is added so we must round up */
1025 z
= r
= malloc(4 * (l
+ 2) / 3 + 1);
1029 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 3) * 3; x
+= 3) {
1030 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ */
1031 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1032 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1033 *(z
++) = base64char((x
[1] & 15) << 2 | x
[2] >> 6); /* 00YYYYZZ */
1034 *(z
++) = base64char(x
[2] & 63); /* 00ZZZZZZ */
1039 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1040 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1041 *(z
++) = base64char((x
[1] & 15) << 2); /* 00YYYY00 */
1046 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1047 *(z
++) = base64char((x
[0] & 3) << 4); /* 00XX0000 */
1058 int unbase64mem(const char *p
, size_t l
, void **mem
, size_t *_len
) {
1059 _cleanup_free_
uint8_t *r
= NULL
;
1067 /* padding ensures any base63 input has input divisible by 4 */
1071 /* strip the padding */
1072 if (l
> 0 && p
[l
- 1] == '=')
1074 if (l
> 0 && p
[l
- 1] == '=')
1077 /* a group of four input bytes needs three output bytes, in case of
1078 padding we need to add two or three extra bytes */
1079 len
= (l
/ 4) * 3 + (l
% 4 ? (l
% 4) - 1 : 0);
1081 z
= r
= malloc(len
+ 1);
1085 for (x
= p
; x
< p
+ (l
/ 4) * 4; x
+= 4) {
1086 /* a == 00XXXXXX; b == 00YYYYYY; c == 00ZZZZZZ; d == 00WWWWWW */
1087 a
= unbase64char(x
[0]);
1091 b
= unbase64char(x
[1]);
1095 c
= unbase64char(x
[2]);
1099 d
= unbase64char(x
[3]);
1103 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1104 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1105 *(z
++) = (uint8_t) c
<< 6 | (uint8_t) d
; /* ZZWWWWWW */
1110 a
= unbase64char(x
[0]);
1114 b
= unbase64char(x
[1]);
1118 c
= unbase64char(x
[2]);
1126 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1127 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1131 a
= unbase64char(x
[0]);
1135 b
= unbase64char(x
[1]);
1143 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) (b
>> 4); /* XXXXXXYY */
1162 char octchar(int x
) {
1163 return '0' + (x
& 7);
1166 int unoctchar(char c
) {
1168 if (c
>= '0' && c
<= '7')
1174 char decchar(int x
) {
1175 return '0' + (x
% 10);
1178 int undecchar(char c
) {
1180 if (c
>= '0' && c
<= '9')
1186 _pure_
static bool hidden_file_allow_backup(const char *filename
) {
1190 filename
[0] == '.' ||
1191 streq(filename
, "lost+found") ||
1192 streq(filename
, "aquota.user") ||
1193 streq(filename
, "aquota.group") ||
1194 endswith(filename
, ".rpmnew") ||
1195 endswith(filename
, ".rpmsave") ||
1196 endswith(filename
, ".rpmorig") ||
1197 endswith(filename
, ".dpkg-old") ||
1198 endswith(filename
, ".dpkg-new") ||
1199 endswith(filename
, ".dpkg-tmp") ||
1200 endswith(filename
, ".dpkg-dist") ||
1201 endswith(filename
, ".dpkg-bak") ||
1202 endswith(filename
, ".dpkg-backup") ||
1203 endswith(filename
, ".dpkg-remove") ||
1204 endswith(filename
, ".swp");
1207 bool hidden_file(const char *filename
) {
1210 if (endswith(filename
, "~"))
1213 return hidden_file_allow_backup(filename
);
1216 bool fstype_is_network(const char *fstype
) {
1217 static const char table
[] =
1232 x
= startswith(fstype
, "fuse.");
1236 return nulstr_contains(table
, fstype
);
1239 int parse_size(const char *t
, uint64_t base
, uint64_t *size
) {
1241 /* Soo, sometimes we want to parse IEC binary suffixes, and
1242 * sometimes SI decimal suffixes. This function can parse
1243 * both. Which one is the right way depends on the
1244 * context. Wikipedia suggests that SI is customary for
1245 * hardware metrics and network speeds, while IEC is
1246 * customary for most data sizes used by software and volatile
1247 * (RAM) memory. Hence be careful which one you pick!
1249 * In either case we use just K, M, G as suffix, and not Ki,
1250 * Mi, Gi or so (as IEC would suggest). That's because that's
1251 * frickin' ugly. But this means you really need to make sure
1252 * to document which base you are parsing when you use this
1257 unsigned long long factor
;
1260 static const struct table iec
[] = {
1261 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1262 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1263 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
1264 { "G", 1024ULL*1024ULL*1024ULL },
1265 { "M", 1024ULL*1024ULL },
1271 static const struct table si
[] = {
1272 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1273 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1274 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
1275 { "G", 1000ULL*1000ULL*1000ULL },
1276 { "M", 1000ULL*1000ULL },
1282 const struct table
*table
;
1284 unsigned long long r
= 0;
1285 unsigned n_entries
, start_pos
= 0;
1288 assert(base
== 1000 || base
== 1024);
1293 n_entries
= ELEMENTSOF(si
);
1296 n_entries
= ELEMENTSOF(iec
);
1301 unsigned long long l
, tmp
;
1306 p
+= strspn(p
, WHITESPACE
);
1311 l
= strtoull(p
, &e
, 10);
1320 /* strtoull() itself would accept space/+/- */
1321 if (*e
>= '0' && *e
<= '9') {
1322 unsigned long long l2
;
1325 l2
= strtoull(e
, &e2
, 10);
1329 /* Ignore failure. E.g. 10.M is valid */
1336 e
+= strspn(e
, WHITESPACE
);
1338 for (i
= start_pos
; i
< n_entries
; i
++)
1339 if (startswith(e
, table
[i
].suffix
))
1345 if (l
+ (frac
> 0) > ULLONG_MAX
/ table
[i
].factor
)
1348 tmp
= l
* table
[i
].factor
+ (unsigned long long) (frac
* table
[i
].factor
);
1349 if (tmp
> ULLONG_MAX
- r
)
1353 if ((unsigned long long) (uint64_t) r
!= r
)
1356 p
= e
+ strlen(table
[i
].suffix
);
1367 bool is_device_path(const char *path
) {
1369 /* Returns true on paths that refer to a device, either in
1370 * sysfs or in /dev */
1373 path_startswith(path
, "/dev/") ||
1374 path_startswith(path
, "/sys/");
1377 int dir_is_empty(const char *path
) {
1378 _cleanup_closedir_
DIR *d
;
1385 FOREACH_DIRENT(de
, d
, return -errno
)
1391 char* dirname_malloc(const char *path
) {
1392 char *d
, *dir
, *dir2
;
1409 void rename_process(const char name
[8]) {
1412 /* This is a like a poor man's setproctitle(). It changes the
1413 * comm field, argv[0], and also the glibc's internally used
1414 * name of the process. For the first one a limit of 16 chars
1415 * applies, to the second one usually one of 10 (i.e. length
1416 * of "/sbin/init"), to the third one one of 7 (i.e. length of
1417 * "systemd"). If you pass a longer string it will be
1420 prctl(PR_SET_NAME
, name
);
1422 if (program_invocation_name
)
1423 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
1425 if (saved_argc
> 0) {
1429 strncpy(saved_argv
[0], name
, strlen(saved_argv
[0]));
1431 for (i
= 1; i
< saved_argc
; i
++) {
1435 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
1440 char *lookup_uid(uid_t uid
) {
1443 _cleanup_free_
char *buf
= NULL
;
1444 struct passwd pwbuf
, *pw
= NULL
;
1446 /* Shortcut things to avoid NSS lookups */
1448 return strdup("root");
1450 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1454 buf
= malloc(bufsize
);
1458 if (getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
) == 0 && pw
)
1459 return strdup(pw
->pw_name
);
1461 if (asprintf(&name
, UID_FMT
, uid
) < 0)
1467 char* getlogname_malloc(void) {
1471 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
1476 return lookup_uid(uid
);
1479 char *getusername_malloc(void) {
1486 return lookup_uid(getuid());
1489 bool is_fs_type(const struct statfs
*s
, statfs_f_type_t magic_value
) {
1491 assert_cc(sizeof(statfs_f_type_t
) >= sizeof(s
->f_type
));
1493 return F_TYPE_EQUAL(s
->f_type
, magic_value
);
1496 int fd_check_fstype(int fd
, statfs_f_type_t magic_value
) {
1499 if (fstatfs(fd
, &s
) < 0)
1502 return is_fs_type(&s
, magic_value
);
1505 int path_check_fstype(const char *path
, statfs_f_type_t magic_value
) {
1506 _cleanup_close_
int fd
= -1;
1508 fd
= open(path
, O_RDONLY
);
1512 return fd_check_fstype(fd
, magic_value
);
1515 bool is_temporary_fs(const struct statfs
*s
) {
1516 return is_fs_type(s
, TMPFS_MAGIC
) ||
1517 is_fs_type(s
, RAMFS_MAGIC
);
1520 int fd_is_temporary_fs(int fd
) {
1523 if (fstatfs(fd
, &s
) < 0)
1526 return is_temporary_fs(&s
);
1529 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
1532 /* Under the assumption that we are running privileged we
1533 * first change the access mode and only then hand out
1534 * ownership to avoid a window where access is too open. */
1536 if (mode
!= MODE_INVALID
)
1537 if (chmod(path
, mode
) < 0)
1540 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
1541 if (chown(path
, uid
, gid
) < 0)
1547 int fchmod_and_fchown(int fd
, mode_t mode
, uid_t uid
, gid_t gid
) {
1550 /* Under the assumption that we are running privileged we
1551 * first change the access mode and only then hand out
1552 * ownership to avoid a window where access is too open. */
1554 if (mode
!= MODE_INVALID
)
1555 if (fchmod(fd
, mode
) < 0)
1558 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
1559 if (fchown(fd
, uid
, gid
) < 0)
1565 int files_same(const char *filea
, const char *fileb
) {
1568 if (stat(filea
, &a
) < 0)
1571 if (stat(fileb
, &b
) < 0)
1574 return a
.st_dev
== b
.st_dev
&&
1575 a
.st_ino
== b
.st_ino
;
1578 int running_in_chroot(void) {
1581 ret
= files_same("/proc/1/root", "/");
1588 int touch_file(const char *path
, bool parents
, usec_t stamp
, uid_t uid
, gid_t gid
, mode_t mode
) {
1589 _cleanup_close_
int fd
;
1595 mkdir_parents(path
, 0755);
1597 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, mode
> 0 ? mode
: 0644);
1602 r
= fchmod(fd
, mode
);
1607 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
) {
1608 r
= fchown(fd
, uid
, gid
);
1613 if (stamp
!= USEC_INFINITY
) {
1614 struct timespec ts
[2];
1616 timespec_store(&ts
[0], stamp
);
1618 r
= futimens(fd
, ts
);
1620 r
= futimens(fd
, NULL
);
1627 int touch(const char *path
) {
1628 return touch_file(path
, false, USEC_INFINITY
, UID_INVALID
, GID_INVALID
, 0);
1631 static char *unquote(const char *s
, const char* quotes
) {
1635 /* This is rather stupid, simply removes the heading and
1636 * trailing quotes if there is one. Doesn't care about
1637 * escaping or anything.
1639 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
1645 if (strchr(quotes
, s
[0]) && s
[l
-1] == s
[0])
1646 return strndup(s
+1, l
-2);
1651 noreturn
void freeze(void) {
1653 /* Make sure nobody waits for us on a socket anymore */
1654 close_all_fds(NULL
, 0);
1662 bool null_or_empty(struct stat
*st
) {
1665 if (S_ISREG(st
->st_mode
) && st
->st_size
<= 0)
1668 if (S_ISCHR(st
->st_mode
) || S_ISBLK(st
->st_mode
))
1674 int null_or_empty_path(const char *fn
) {
1679 if (stat(fn
, &st
) < 0)
1682 return null_or_empty(&st
);
1685 int null_or_empty_fd(int fd
) {
1690 if (fstat(fd
, &st
) < 0)
1693 return null_or_empty(&st
);
1696 DIR *xopendirat(int fd
, const char *name
, int flags
) {
1700 assert(!(flags
& O_CREAT
));
1702 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
1715 static char *tag_to_udev_node(const char *tagvalue
, const char *by
) {
1716 _cleanup_free_
char *t
= NULL
, *u
= NULL
;
1719 u
= unquote(tagvalue
, QUOTES
);
1723 enc_len
= strlen(u
) * 4 + 1;
1724 t
= new(char, enc_len
);
1728 if (encode_devnode_name(u
, t
, enc_len
) < 0)
1731 return strjoin("/dev/disk/by-", by
, "/", t
, NULL
);
1734 char *fstab_node_to_udev_node(const char *p
) {
1737 if (startswith(p
, "LABEL="))
1738 return tag_to_udev_node(p
+6, "label");
1740 if (startswith(p
, "UUID="))
1741 return tag_to_udev_node(p
+5, "uuid");
1743 if (startswith(p
, "PARTUUID="))
1744 return tag_to_udev_node(p
+9, "partuuid");
1746 if (startswith(p
, "PARTLABEL="))
1747 return tag_to_udev_node(p
+10, "partlabel");
1752 bool dirent_is_file(const struct dirent
*de
) {
1755 if (hidden_file(de
->d_name
))
1758 if (de
->d_type
!= DT_REG
&&
1759 de
->d_type
!= DT_LNK
&&
1760 de
->d_type
!= DT_UNKNOWN
)
1766 bool dirent_is_file_with_suffix(const struct dirent
*de
, const char *suffix
) {
1769 if (de
->d_type
!= DT_REG
&&
1770 de
->d_type
!= DT_LNK
&&
1771 de
->d_type
!= DT_UNKNOWN
)
1774 if (hidden_file_allow_backup(de
->d_name
))
1777 return endswith(de
->d_name
, suffix
);
1780 static int do_execute(char **directories
, usec_t timeout
, char *argv
[]) {
1781 _cleanup_hashmap_free_free_ Hashmap
*pids
= NULL
;
1782 _cleanup_set_free_free_ Set
*seen
= NULL
;
1785 /* We fork this all off from a child process so that we can
1786 * somewhat cleanly make use of SIGALRM to set a time limit */
1788 (void) reset_all_signal_handlers();
1789 (void) reset_signal_mask();
1791 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
1793 pids
= hashmap_new(NULL
);
1797 seen
= set_new(&string_hash_ops
);
1801 STRV_FOREACH(directory
, directories
) {
1802 _cleanup_closedir_
DIR *d
;
1805 d
= opendir(*directory
);
1807 if (errno
== ENOENT
)
1810 return log_error_errno(errno
, "Failed to open directory %s: %m", *directory
);
1813 FOREACH_DIRENT(de
, d
, break) {
1814 _cleanup_free_
char *path
= NULL
;
1818 if (!dirent_is_file(de
))
1821 if (set_contains(seen
, de
->d_name
)) {
1822 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory
, de
->d_name
);
1826 r
= set_put_strdup(seen
, de
->d_name
);
1830 path
= strjoin(*directory
, "/", de
->d_name
, NULL
);
1834 if (null_or_empty_path(path
)) {
1835 log_debug("%s is empty (a mask).", path
);
1841 log_error_errno(errno
, "Failed to fork: %m");
1843 } else if (pid
== 0) {
1846 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
1856 return log_error_errno(errno
, "Failed to execute %s: %m", path
);
1859 log_debug("Spawned %s as " PID_FMT
".", path
, pid
);
1861 r
= hashmap_put(pids
, UINT_TO_PTR(pid
), path
);
1868 /* Abort execution of this process after the timout. We simply
1869 * rely on SIGALRM as default action terminating the process,
1870 * and turn on alarm(). */
1872 if (timeout
!= USEC_INFINITY
)
1873 alarm((timeout
+ USEC_PER_SEC
- 1) / USEC_PER_SEC
);
1875 while (!hashmap_isempty(pids
)) {
1876 _cleanup_free_
char *path
= NULL
;
1879 pid
= PTR_TO_UINT(hashmap_first_key(pids
));
1882 path
= hashmap_remove(pids
, UINT_TO_PTR(pid
));
1885 wait_for_terminate_and_warn(path
, pid
, true);
1891 void execute_directories(const char* const* directories
, usec_t timeout
, char *argv
[]) {
1895 char **dirs
= (char**) directories
;
1897 assert(!strv_isempty(dirs
));
1899 name
= basename(dirs
[0]);
1900 assert(!isempty(name
));
1902 /* Executes all binaries in the directories in parallel and waits
1903 * for them to finish. Optionally a timeout is applied. If a file
1904 * with the same name exists in more than one directory, the
1905 * earliest one wins. */
1907 executor_pid
= fork();
1908 if (executor_pid
< 0) {
1909 log_error_errno(errno
, "Failed to fork: %m");
1912 } else if (executor_pid
== 0) {
1913 r
= do_execute(dirs
, timeout
, argv
);
1914 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
1917 wait_for_terminate_and_warn(name
, executor_pid
, true);
1920 bool plymouth_running(void) {
1921 return access("/run/plymouth/pid", F_OK
) >= 0;
1924 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
1933 r
= tempfn_xxxxxx(path
, NULL
, &t
);
1937 fd
= mkostemp_safe(t
, O_WRONLY
|O_CLOEXEC
);
1943 f
= fdopen(fd
, "we");
1957 int symlink_atomic(const char *from
, const char *to
) {
1958 _cleanup_free_
char *t
= NULL
;
1964 r
= tempfn_random(to
, NULL
, &t
);
1968 if (symlink(from
, t
) < 0)
1971 if (rename(t
, to
) < 0) {
1979 int symlink_idempotent(const char *from
, const char *to
) {
1980 _cleanup_free_
char *p
= NULL
;
1986 if (symlink(from
, to
) < 0) {
1987 if (errno
!= EEXIST
)
1990 r
= readlink_malloc(to
, &p
);
1994 if (!streq(p
, from
))
2001 int mknod_atomic(const char *path
, mode_t mode
, dev_t dev
) {
2002 _cleanup_free_
char *t
= NULL
;
2007 r
= tempfn_random(path
, NULL
, &t
);
2011 if (mknod(t
, mode
, dev
) < 0)
2014 if (rename(t
, path
) < 0) {
2022 int mkfifo_atomic(const char *path
, mode_t mode
) {
2023 _cleanup_free_
char *t
= NULL
;
2028 r
= tempfn_random(path
, NULL
, &t
);
2032 if (mkfifo(t
, mode
) < 0)
2035 if (rename(t
, path
) < 0) {
2043 bool display_is_local(const char *display
) {
2047 display
[0] == ':' &&
2048 display
[1] >= '0' &&
2052 int socket_from_display(const char *display
, char **path
) {
2059 if (!display_is_local(display
))
2062 k
= strspn(display
+1, "0123456789");
2064 f
= new(char, strlen("/tmp/.X11-unix/X") + k
+ 1);
2068 c
= stpcpy(f
, "/tmp/.X11-unix/X");
2069 memcpy(c
, display
+1, k
);
2078 const char **username
,
2079 uid_t
*uid
, gid_t
*gid
,
2081 const char **shell
) {
2089 /* We enforce some special rules for uid=0: in order to avoid
2090 * NSS lookups for root we hardcode its data. */
2092 if (streq(*username
, "root") || streq(*username
, "0")) {
2110 if (parse_uid(*username
, &u
) >= 0) {
2114 /* If there are multiple users with the same id, make
2115 * sure to leave $USER to the configured value instead
2116 * of the first occurrence in the database. However if
2117 * the uid was configured by a numeric uid, then let's
2118 * pick the real username from /etc/passwd. */
2120 *username
= p
->pw_name
;
2123 p
= getpwnam(*username
);
2127 return errno
> 0 ? -errno
: -ESRCH
;
2139 *shell
= p
->pw_shell
;
2144 char* uid_to_name(uid_t uid
) {
2149 return strdup("root");
2153 return strdup(p
->pw_name
);
2155 if (asprintf(&r
, UID_FMT
, uid
) < 0)
2161 char* gid_to_name(gid_t gid
) {
2166 return strdup("root");
2170 return strdup(p
->gr_name
);
2172 if (asprintf(&r
, GID_FMT
, gid
) < 0)
2178 int get_group_creds(const char **groupname
, gid_t
*gid
) {
2184 /* We enforce some special rules for gid=0: in order to avoid
2185 * NSS lookups for root we hardcode its data. */
2187 if (streq(*groupname
, "root") || streq(*groupname
, "0")) {
2188 *groupname
= "root";
2196 if (parse_gid(*groupname
, &id
) >= 0) {
2201 *groupname
= g
->gr_name
;
2204 g
= getgrnam(*groupname
);
2208 return errno
> 0 ? -errno
: -ESRCH
;
2216 int in_gid(gid_t gid
) {
2218 int ngroups_max
, r
, i
;
2220 if (getgid() == gid
)
2223 if (getegid() == gid
)
2226 ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
2227 assert(ngroups_max
> 0);
2229 gids
= alloca(sizeof(gid_t
) * ngroups_max
);
2231 r
= getgroups(ngroups_max
, gids
);
2235 for (i
= 0; i
< r
; i
++)
2242 int in_group(const char *name
) {
2246 r
= get_group_creds(&name
, &gid
);
2253 int glob_exists(const char *path
) {
2254 _cleanup_globfree_ glob_t g
= {};
2260 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
2262 if (k
== GLOB_NOMATCH
)
2264 else if (k
== GLOB_NOSPACE
)
2267 return !strv_isempty(g
.gl_pathv
);
2269 return errno
? -errno
: -EIO
;
2272 int glob_extend(char ***strv
, const char *path
) {
2273 _cleanup_globfree_ glob_t g
= {};
2278 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
2280 if (k
== GLOB_NOMATCH
)
2282 else if (k
== GLOB_NOSPACE
)
2284 else if (k
!= 0 || strv_isempty(g
.gl_pathv
))
2285 return errno
? -errno
: -EIO
;
2287 STRV_FOREACH(p
, g
.gl_pathv
) {
2288 k
= strv_extend(strv
, *p
);
2296 int dirent_ensure_type(DIR *d
, struct dirent
*de
) {
2302 if (de
->d_type
!= DT_UNKNOWN
)
2305 if (fstatat(dirfd(d
), de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
2309 S_ISREG(st
.st_mode
) ? DT_REG
:
2310 S_ISDIR(st
.st_mode
) ? DT_DIR
:
2311 S_ISLNK(st
.st_mode
) ? DT_LNK
:
2312 S_ISFIFO(st
.st_mode
) ? DT_FIFO
:
2313 S_ISSOCK(st
.st_mode
) ? DT_SOCK
:
2314 S_ISCHR(st
.st_mode
) ? DT_CHR
:
2315 S_ISBLK(st
.st_mode
) ? DT_BLK
:
2321 int get_files_in_directory(const char *path
, char ***list
) {
2322 _cleanup_closedir_
DIR *d
= NULL
;
2323 size_t bufsize
= 0, n
= 0;
2324 _cleanup_strv_free_
char **l
= NULL
;
2328 /* Returns all files in a directory in *list, and the number
2329 * of files as return value. If list is NULL returns only the
2341 if (!de
&& errno
!= 0)
2346 dirent_ensure_type(d
, de
);
2348 if (!dirent_is_file(de
))
2352 /* one extra slot is needed for the terminating NULL */
2353 if (!GREEDY_REALLOC(l
, bufsize
, n
+ 2))
2356 l
[n
] = strdup(de
->d_name
);
2367 l
= NULL
; /* avoid freeing */
2373 bool is_main_thread(void) {
2374 static thread_local
int cached
= 0;
2376 if (_unlikely_(cached
== 0))
2377 cached
= getpid() == gettid() ? 1 : -1;
2382 int block_get_whole_disk(dev_t d
, dev_t
*ret
) {
2389 /* If it has a queue this is good enough for us */
2390 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", major(d
), minor(d
)) < 0)
2393 r
= access(p
, F_OK
);
2401 /* If it is a partition find the originating device */
2402 if (asprintf(&p
, "/sys/dev/block/%u:%u/partition", major(d
), minor(d
)) < 0)
2405 r
= access(p
, F_OK
);
2411 /* Get parent dev_t */
2412 if (asprintf(&p
, "/sys/dev/block/%u:%u/../dev", major(d
), minor(d
)) < 0)
2415 r
= read_one_line_file(p
, &s
);
2421 r
= sscanf(s
, "%u:%u", &m
, &n
);
2427 /* Only return this if it is really good enough for us. */
2428 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", m
, n
) < 0)
2431 r
= access(p
, F_OK
);
2435 *ret
= makedev(m
, n
);
2442 static const char *const ioprio_class_table
[] = {
2443 [IOPRIO_CLASS_NONE
] = "none",
2444 [IOPRIO_CLASS_RT
] = "realtime",
2445 [IOPRIO_CLASS_BE
] = "best-effort",
2446 [IOPRIO_CLASS_IDLE
] = "idle"
2449 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, INT_MAX
);
2451 static const char *const sigchld_code_table
[] = {
2452 [CLD_EXITED
] = "exited",
2453 [CLD_KILLED
] = "killed",
2454 [CLD_DUMPED
] = "dumped",
2455 [CLD_TRAPPED
] = "trapped",
2456 [CLD_STOPPED
] = "stopped",
2457 [CLD_CONTINUED
] = "continued",
2460 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
2462 static const char *const log_facility_unshifted_table
[LOG_NFACILITIES
] = {
2463 [LOG_FAC(LOG_KERN
)] = "kern",
2464 [LOG_FAC(LOG_USER
)] = "user",
2465 [LOG_FAC(LOG_MAIL
)] = "mail",
2466 [LOG_FAC(LOG_DAEMON
)] = "daemon",
2467 [LOG_FAC(LOG_AUTH
)] = "auth",
2468 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
2469 [LOG_FAC(LOG_LPR
)] = "lpr",
2470 [LOG_FAC(LOG_NEWS
)] = "news",
2471 [LOG_FAC(LOG_UUCP
)] = "uucp",
2472 [LOG_FAC(LOG_CRON
)] = "cron",
2473 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
2474 [LOG_FAC(LOG_FTP
)] = "ftp",
2475 [LOG_FAC(LOG_LOCAL0
)] = "local0",
2476 [LOG_FAC(LOG_LOCAL1
)] = "local1",
2477 [LOG_FAC(LOG_LOCAL2
)] = "local2",
2478 [LOG_FAC(LOG_LOCAL3
)] = "local3",
2479 [LOG_FAC(LOG_LOCAL4
)] = "local4",
2480 [LOG_FAC(LOG_LOCAL5
)] = "local5",
2481 [LOG_FAC(LOG_LOCAL6
)] = "local6",
2482 [LOG_FAC(LOG_LOCAL7
)] = "local7"
2485 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted
, int, LOG_FAC(~0));
2487 bool log_facility_unshifted_is_valid(int facility
) {
2488 return facility
>= 0 && facility
<= LOG_FAC(~0);
2491 static const char *const log_level_table
[] = {
2492 [LOG_EMERG
] = "emerg",
2493 [LOG_ALERT
] = "alert",
2494 [LOG_CRIT
] = "crit",
2496 [LOG_WARNING
] = "warning",
2497 [LOG_NOTICE
] = "notice",
2498 [LOG_INFO
] = "info",
2499 [LOG_DEBUG
] = "debug"
2502 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level
, int, LOG_DEBUG
);
2504 bool log_level_is_valid(int level
) {
2505 return level
>= 0 && level
<= LOG_DEBUG
;
2508 static const char* const sched_policy_table
[] = {
2509 [SCHED_OTHER
] = "other",
2510 [SCHED_BATCH
] = "batch",
2511 [SCHED_IDLE
] = "idle",
2512 [SCHED_FIFO
] = "fifo",
2516 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);
2518 static const char* const rlimit_table
[_RLIMIT_MAX
] = {
2519 [RLIMIT_CPU
] = "LimitCPU",
2520 [RLIMIT_FSIZE
] = "LimitFSIZE",
2521 [RLIMIT_DATA
] = "LimitDATA",
2522 [RLIMIT_STACK
] = "LimitSTACK",
2523 [RLIMIT_CORE
] = "LimitCORE",
2524 [RLIMIT_RSS
] = "LimitRSS",
2525 [RLIMIT_NOFILE
] = "LimitNOFILE",
2526 [RLIMIT_AS
] = "LimitAS",
2527 [RLIMIT_NPROC
] = "LimitNPROC",
2528 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
2529 [RLIMIT_LOCKS
] = "LimitLOCKS",
2530 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
2531 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
2532 [RLIMIT_NICE
] = "LimitNICE",
2533 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
2534 [RLIMIT_RTTIME
] = "LimitRTTIME"
2537 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
2539 static const char* const ip_tos_table
[] = {
2540 [IPTOS_LOWDELAY
] = "low-delay",
2541 [IPTOS_THROUGHPUT
] = "throughput",
2542 [IPTOS_RELIABILITY
] = "reliability",
2543 [IPTOS_LOWCOST
] = "low-cost",
2546 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
2548 bool kexec_loaded(void) {
2549 bool loaded
= false;
2552 if (read_one_line_file("/sys/kernel/kexec_loaded", &s
) >= 0) {
2560 int prot_from_flags(int flags
) {
2562 switch (flags
& O_ACCMODE
) {
2571 return PROT_READ
|PROT_WRITE
;
2578 char *format_bytes(char *buf
, size_t l
, uint64_t t
) {
2581 static const struct {
2585 { "E", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2586 { "P", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2587 { "T", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2588 { "G", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2589 { "M", UINT64_C(1024)*UINT64_C(1024) },
2590 { "K", UINT64_C(1024) },
2593 if (t
== (uint64_t) -1)
2596 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
2598 if (t
>= table
[i
].factor
) {
2600 "%" PRIu64
".%" PRIu64
"%s",
2601 t
/ table
[i
].factor
,
2602 ((t
*UINT64_C(10)) / table
[i
].factor
) % UINT64_C(10),
2609 snprintf(buf
, l
, "%" PRIu64
"B", t
);
2617 void* memdup(const void *p
, size_t l
) {
2630 int fd_inc_sndbuf(int fd
, size_t n
) {
2632 socklen_t l
= sizeof(value
);
2634 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
2635 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
2638 /* If we have the privileges we will ignore the kernel limit. */
2641 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
2642 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
2648 int fd_inc_rcvbuf(int fd
, size_t n
) {
2650 socklen_t l
= sizeof(value
);
2652 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
2653 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
2656 /* If we have the privileges we will ignore the kernel limit. */
2659 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
2660 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
2665 int fork_agent(pid_t
*pid
, const int except
[], unsigned n_except
, const char *path
, ...) {
2666 bool stdout_is_tty
, stderr_is_tty
;
2667 pid_t parent_pid
, agent_pid
;
2668 sigset_t ss
, saved_ss
;
2676 /* Spawns a temporary TTY agent, making sure it goes away when
2679 parent_pid
= getpid();
2681 /* First we temporarily block all signals, so that the new
2682 * child has them blocked initially. This way, we can be sure
2683 * that SIGTERMs are not lost we might send to the agent. */
2684 assert_se(sigfillset(&ss
) >= 0);
2685 assert_se(sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) >= 0);
2688 if (agent_pid
< 0) {
2689 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
2693 if (agent_pid
!= 0) {
2694 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
2701 * Make sure the agent goes away when the parent dies */
2702 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
2703 _exit(EXIT_FAILURE
);
2705 /* Make sure we actually can kill the agent, if we need to, in
2706 * case somebody invoked us from a shell script that trapped
2707 * SIGTERM or so... */
2708 (void) reset_all_signal_handlers();
2709 (void) reset_signal_mask();
2711 /* Check whether our parent died before we were able
2712 * to set the death signal and unblock the signals */
2713 if (getppid() != parent_pid
)
2714 _exit(EXIT_SUCCESS
);
2716 /* Don't leak fds to the agent */
2717 close_all_fds(except
, n_except
);
2719 stdout_is_tty
= isatty(STDOUT_FILENO
);
2720 stderr_is_tty
= isatty(STDERR_FILENO
);
2722 if (!stdout_is_tty
|| !stderr_is_tty
) {
2725 /* Detach from stdout/stderr. and reopen
2726 * /dev/tty for them. This is important to
2727 * ensure that when systemctl is started via
2728 * popen() or a similar call that expects to
2729 * read EOF we actually do generate EOF and
2730 * not delay this indefinitely by because we
2731 * keep an unused copy of stdin around. */
2732 fd
= open("/dev/tty", O_WRONLY
);
2734 log_error_errno(errno
, "Failed to open /dev/tty: %m");
2735 _exit(EXIT_FAILURE
);
2739 dup2(fd
, STDOUT_FILENO
);
2742 dup2(fd
, STDERR_FILENO
);
2748 /* Count arguments */
2750 for (n
= 0; va_arg(ap
, char*); n
++)
2755 l
= alloca(sizeof(char *) * (n
+ 1));
2757 /* Fill in arguments */
2759 for (i
= 0; i
<= n
; i
++)
2760 l
[i
] = va_arg(ap
, char*);
2764 _exit(EXIT_FAILURE
);
2767 int setrlimit_closest(int resource
, const struct rlimit
*rlim
) {
2768 struct rlimit highest
, fixed
;
2772 if (setrlimit(resource
, rlim
) >= 0)
2778 /* So we failed to set the desired setrlimit, then let's try
2779 * to get as close as we can */
2780 assert_se(getrlimit(resource
, &highest
) == 0);
2782 fixed
.rlim_cur
= MIN(rlim
->rlim_cur
, highest
.rlim_max
);
2783 fixed
.rlim_max
= MIN(rlim
->rlim_max
, highest
.rlim_max
);
2785 if (setrlimit(resource
, &fixed
) < 0)
2791 bool http_etag_is_valid(const char *etag
) {
2795 if (!endswith(etag
, "\""))
2798 if (!startswith(etag
, "\"") && !startswith(etag
, "W/\""))
2804 bool http_url_is_valid(const char *url
) {
2810 p
= startswith(url
, "http://");
2812 p
= startswith(url
, "https://");
2819 return ascii_is_valid(p
);
2822 bool documentation_url_is_valid(const char *url
) {
2828 if (http_url_is_valid(url
))
2831 p
= startswith(url
, "file:/");
2833 p
= startswith(url
, "info:");
2835 p
= startswith(url
, "man:");
2840 return ascii_is_valid(p
);
2843 bool in_initrd(void) {
2844 static int saved
= -1;
2850 /* We make two checks here:
2852 * 1. the flag file /etc/initrd-release must exist
2853 * 2. the root file system must be a memory file system
2855 * The second check is extra paranoia, since misdetecting an
2856 * initrd can have bad bad consequences due the initrd
2857 * emptying when transititioning to the main systemd.
2860 saved
= access("/etc/initrd-release", F_OK
) >= 0 &&
2861 statfs("/", &s
) >= 0 &&
2862 is_temporary_fs(&s
);
2867 int get_home_dir(char **_h
) {
2875 /* Take the user specified one */
2876 e
= secure_getenv("HOME");
2877 if (e
&& path_is_absolute(e
)) {
2886 /* Hardcode home directory for root to avoid NSS */
2889 h
= strdup("/root");
2897 /* Check the database... */
2901 return errno
> 0 ? -errno
: -ESRCH
;
2903 if (!path_is_absolute(p
->pw_dir
))
2906 h
= strdup(p
->pw_dir
);
2914 int get_shell(char **_s
) {
2922 /* Take the user specified one */
2923 e
= getenv("SHELL");
2933 /* Hardcode home directory for root to avoid NSS */
2936 s
= strdup("/bin/sh");
2944 /* Check the database... */
2948 return errno
> 0 ? -errno
: -ESRCH
;
2950 if (!path_is_absolute(p
->pw_shell
))
2953 s
= strdup(p
->pw_shell
);
2961 bool filename_is_valid(const char *p
) {
2975 if (strlen(p
) > FILENAME_MAX
)
2981 bool string_is_safe(const char *p
) {
2987 for (t
= p
; *t
; t
++) {
2988 if (*t
> 0 && *t
< ' ')
2991 if (strchr("\\\"\'\x7f", *t
))
2998 bool path_is_safe(const char *p
) {
3003 if (streq(p
, "..") || startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
3006 if (strlen(p
)+1 > PATH_MAX
)
3009 /* The following two checks are not really dangerous, but hey, they still are confusing */
3010 if (streq(p
, ".") || startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
3013 if (strstr(p
, "//"))
3019 /* hey glibc, APIs with callbacks without a user pointer are so useless */
3020 void *xbsearch_r(const void *key
, const void *base
, size_t nmemb
, size_t size
,
3021 int (*compar
) (const void *, const void *, void *), void *arg
) {
3030 p
= (void *)(((const char *) base
) + (idx
* size
));
3031 comparison
= compar(key
, p
, arg
);
3034 else if (comparison
> 0)
3042 void init_gettext(void) {
3043 setlocale(LC_ALL
, "");
3044 textdomain(GETTEXT_PACKAGE
);
3047 bool is_locale_utf8(void) {
3049 static int cached_answer
= -1;
3051 if (cached_answer
>= 0)
3054 if (!setlocale(LC_ALL
, "")) {
3055 cached_answer
= true;
3059 set
= nl_langinfo(CODESET
);
3061 cached_answer
= true;
3065 if (streq(set
, "UTF-8")) {
3066 cached_answer
= true;
3070 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
3071 * unset and everything can do to UTF-8 nowadays. */
3072 set
= setlocale(LC_CTYPE
, NULL
);
3074 cached_answer
= true;
3078 /* Check result, but ignore the result if C was set
3081 STR_IN_SET(set
, "C", "POSIX") &&
3082 !getenv("LC_ALL") &&
3083 !getenv("LC_CTYPE") &&
3087 return (bool) cached_answer
;
3090 const char *draw_special_char(DrawSpecialChar ch
) {
3091 static const char *draw_table
[2][_DRAW_SPECIAL_CHAR_MAX
] = {
3094 [DRAW_TREE_VERTICAL
] = "\342\224\202 ", /* │ */
3095 [DRAW_TREE_BRANCH
] = "\342\224\234\342\224\200", /* ├─ */
3096 [DRAW_TREE_RIGHT
] = "\342\224\224\342\224\200", /* └─ */
3097 [DRAW_TREE_SPACE
] = " ", /* */
3098 [DRAW_TRIANGULAR_BULLET
] = "\342\200\243", /* ‣ */
3099 [DRAW_BLACK_CIRCLE
] = "\342\227\217", /* ● */
3100 [DRAW_ARROW
] = "\342\206\222", /* → */
3101 [DRAW_DASH
] = "\342\200\223", /* – */
3104 /* ASCII fallback */ {
3105 [DRAW_TREE_VERTICAL
] = "| ",
3106 [DRAW_TREE_BRANCH
] = "|-",
3107 [DRAW_TREE_RIGHT
] = "`-",
3108 [DRAW_TREE_SPACE
] = " ",
3109 [DRAW_TRIANGULAR_BULLET
] = ">",
3110 [DRAW_BLACK_CIRCLE
] = "*",
3111 [DRAW_ARROW
] = "->",
3116 return draw_table
[!is_locale_utf8()][ch
];
3119 int on_ac_power(void) {
3120 bool found_offline
= false, found_online
= false;
3121 _cleanup_closedir_
DIR *d
= NULL
;
3123 d
= opendir("/sys/class/power_supply");
3125 return errno
== ENOENT
? true : -errno
;
3129 _cleanup_close_
int fd
= -1, device
= -1;
3135 if (!de
&& errno
!= 0)
3141 if (hidden_file(de
->d_name
))
3144 device
= openat(dirfd(d
), de
->d_name
, O_DIRECTORY
|O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
3146 if (errno
== ENOENT
|| errno
== ENOTDIR
)
3152 fd
= openat(device
, "type", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
3154 if (errno
== ENOENT
)
3160 n
= read(fd
, contents
, sizeof(contents
));
3164 if (n
!= 6 || memcmp(contents
, "Mains\n", 6))
3168 fd
= openat(device
, "online", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
3170 if (errno
== ENOENT
)
3176 n
= read(fd
, contents
, sizeof(contents
));
3180 if (n
!= 2 || contents
[1] != '\n')
3183 if (contents
[0] == '1') {
3184 found_online
= true;
3186 } else if (contents
[0] == '0')
3187 found_offline
= true;
3192 return found_online
|| !found_offline
;
3195 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
3202 if (!path_strv_resolve_uniq(search
, root
))
3205 STRV_FOREACH(i
, search
) {
3206 _cleanup_free_
char *p
= NULL
;
3210 p
= strjoin(root
, *i
, "/", path
, NULL
);
3212 p
= strjoin(*i
, "/", path
, NULL
);
3222 if (errno
!= ENOENT
)
3229 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
3230 _cleanup_strv_free_
char **copy
= NULL
;
3236 if (path_is_absolute(path
)) {
3239 f
= fopen(path
, mode
);
3248 copy
= strv_copy((char**) search
);
3252 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
3255 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
3256 _cleanup_strv_free_
char **s
= NULL
;
3258 if (path_is_absolute(path
)) {
3261 f
= fopen(path
, mode
);
3270 s
= strv_split_nulstr(search
);
3274 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
3277 void* greedy_realloc(void **p
, size_t *allocated
, size_t need
, size_t size
) {
3284 if (*allocated
>= need
)
3287 newalloc
= MAX(need
* 2, 64u / size
);
3288 a
= newalloc
* size
;
3290 /* check for overflows */
3291 if (a
< size
* need
)
3299 *allocated
= newalloc
;
3303 void* greedy_realloc0(void **p
, size_t *allocated
, size_t need
, size_t size
) {
3312 q
= greedy_realloc(p
, allocated
, need
, size
);
3316 if (*allocated
> prev
)
3317 memzero(q
+ prev
* size
, (*allocated
- prev
) * size
);
3322 bool id128_is_valid(const char *s
) {
3328 /* Simple formatted 128bit hex string */
3330 for (i
= 0; i
< l
; i
++) {
3333 if (!(c
>= '0' && c
<= '9') &&
3334 !(c
>= 'a' && c
<= 'z') &&
3335 !(c
>= 'A' && c
<= 'Z'))
3339 } else if (l
== 36) {
3341 /* Formatted UUID */
3343 for (i
= 0; i
< l
; i
++) {
3346 if ((i
== 8 || i
== 13 || i
== 18 || i
== 23)) {
3350 if (!(c
>= '0' && c
<= '9') &&
3351 !(c
>= 'a' && c
<= 'z') &&
3352 !(c
>= 'A' && c
<= 'Z'))
3363 int shall_restore_state(void) {
3364 _cleanup_free_
char *value
= NULL
;
3367 r
= get_proc_cmdline_key("systemd.restore_state=", &value
);
3373 return parse_boolean(value
) != 0;
3376 int proc_cmdline(char **ret
) {
3379 if (detect_container() > 0)
3380 return get_process_cmdline(1, 0, false, ret
);
3382 return read_one_line_file("/proc/cmdline", ret
);
3385 int parse_proc_cmdline(int (*parse_item
)(const char *key
, const char *value
)) {
3386 _cleanup_free_
char *line
= NULL
;
3392 r
= proc_cmdline(&line
);
3398 _cleanup_free_
char *word
= NULL
;
3401 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
3407 /* Filter out arguments that are intended only for the
3409 if (!in_initrd() && startswith(word
, "rd."))
3412 value
= strchr(word
, '=');
3416 r
= parse_item(word
, value
);
3424 int get_proc_cmdline_key(const char *key
, char **value
) {
3425 _cleanup_free_
char *line
= NULL
, *ret
= NULL
;
3432 r
= proc_cmdline(&line
);
3438 _cleanup_free_
char *word
= NULL
;
3441 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
3447 /* Filter out arguments that are intended only for the
3449 if (!in_initrd() && startswith(word
, "rd."))
3453 e
= startswith(word
, key
);
3457 r
= free_and_strdup(&ret
, e
);
3463 if (streq(word
, key
))
3477 int container_get_leader(const char *machine
, pid_t
*pid
) {
3478 _cleanup_free_
char *s
= NULL
, *class = NULL
;
3486 if (!machine_name_is_valid(machine
))
3489 p
= strjoina("/run/systemd/machines/", machine
);
3490 r
= parse_env_file(p
, NEWLINE
, "LEADER", &s
, "CLASS", &class, NULL
);
3498 if (!streq_ptr(class, "container"))
3501 r
= parse_pid(s
, &leader
);
3511 int namespace_open(pid_t pid
, int *pidns_fd
, int *mntns_fd
, int *netns_fd
, int *userns_fd
, int *root_fd
) {
3512 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, netnsfd
= -1, usernsfd
= -1;
3520 mntns
= procfs_file_alloca(pid
, "ns/mnt");
3521 mntnsfd
= open(mntns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
3529 pidns
= procfs_file_alloca(pid
, "ns/pid");
3530 pidnsfd
= open(pidns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
3538 netns
= procfs_file_alloca(pid
, "ns/net");
3539 netnsfd
= open(netns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
3547 userns
= procfs_file_alloca(pid
, "ns/user");
3548 usernsfd
= open(userns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
3549 if (usernsfd
< 0 && errno
!= ENOENT
)
3556 root
= procfs_file_alloca(pid
, "root");
3557 rfd
= open(root
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
|O_DIRECTORY
);
3563 *pidns_fd
= pidnsfd
;
3566 *mntns_fd
= mntnsfd
;
3569 *netns_fd
= netnsfd
;
3572 *userns_fd
= usernsfd
;
3577 pidnsfd
= mntnsfd
= netnsfd
= usernsfd
= -1;
3582 int namespace_enter(int pidns_fd
, int mntns_fd
, int netns_fd
, int userns_fd
, int root_fd
) {
3583 if (userns_fd
>= 0) {
3584 /* Can't setns to your own userns, since then you could
3585 * escalate from non-root to root in your own namespace, so
3586 * check if namespaces equal before attempting to enter. */
3587 _cleanup_free_
char *userns_fd_path
= NULL
;
3589 if (asprintf(&userns_fd_path
, "/proc/self/fd/%d", userns_fd
) < 0)
3592 r
= files_same(userns_fd_path
, "/proc/self/ns/user");
3600 if (setns(pidns_fd
, CLONE_NEWPID
) < 0)
3604 if (setns(mntns_fd
, CLONE_NEWNS
) < 0)
3608 if (setns(netns_fd
, CLONE_NEWNET
) < 0)
3612 if (setns(userns_fd
, CLONE_NEWUSER
) < 0)
3616 if (fchdir(root_fd
) < 0)
3619 if (chroot(".") < 0)
3623 return reset_uid_gid();
3626 int getpeercred(int fd
, struct ucred
*ucred
) {
3627 socklen_t n
= sizeof(struct ucred
);
3634 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
);
3638 if (n
!= sizeof(struct ucred
))
3641 /* Check if the data is actually useful and not suppressed due
3642 * to namespacing issues */
3645 if (u
.uid
== UID_INVALID
)
3647 if (u
.gid
== GID_INVALID
)
3654 int getpeersec(int fd
, char **ret
) {
3666 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
3670 if (errno
!= ERANGE
)
3677 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
3693 /* This is much like like mkostemp() but is subject to umask(). */
3694 int mkostemp_safe(char *pattern
, int flags
) {
3695 _cleanup_umask_ mode_t u
;
3702 fd
= mkostemp(pattern
, flags
);
3709 int open_tmpfile(const char *path
, int flags
) {
3716 /* Try O_TMPFILE first, if it is supported */
3717 fd
= open(path
, flags
|O_TMPFILE
|O_EXCL
, S_IRUSR
|S_IWUSR
);
3722 /* Fall back to unguessable name + unlinking */
3723 p
= strjoina(path
, "/systemd-tmp-XXXXXX");
3725 fd
= mkostemp_safe(p
, flags
);
3733 int fd_warn_permissions(const char *path
, int fd
) {
3736 if (fstat(fd
, &st
) < 0)
3739 if (st
.st_mode
& 0111)
3740 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path
);
3742 if (st
.st_mode
& 0002)
3743 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path
);
3745 if (getpid() == 1 && (st
.st_mode
& 0044) != 0044)
3746 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
);
3751 unsigned long personality_from_string(const char *p
) {
3753 /* Parse a personality specifier. We introduce our own
3754 * identifiers that indicate specific ABIs, rather than just
3755 * hints regarding the register size, since we want to keep
3756 * things open for multiple locally supported ABIs for the
3757 * same register size. We try to reuse the ABI identifiers
3758 * used by libseccomp. */
3760 #if defined(__x86_64__)
3762 if (streq(p
, "x86"))
3765 if (streq(p
, "x86-64"))
3768 #elif defined(__i386__)
3770 if (streq(p
, "x86"))
3773 #elif defined(__s390x__)
3775 if (streq(p
, "s390"))
3778 if (streq(p
, "s390x"))
3781 #elif defined(__s390__)
3783 if (streq(p
, "s390"))
3787 return PERSONALITY_INVALID
;
3790 const char* personality_to_string(unsigned long p
) {
3792 #if defined(__x86_64__)
3794 if (p
== PER_LINUX32
)
3800 #elif defined(__i386__)
3805 #elif defined(__s390x__)
3810 if (p
== PER_LINUX32
)
3813 #elif defined(__s390__)
3823 uint64_t physical_memory(void) {
3826 /* We return this as uint64_t in case we are running as 32bit
3827 * process on a 64bit kernel with huge amounts of memory */
3829 mem
= sysconf(_SC_PHYS_PAGES
);
3832 return (uint64_t) mem
* (uint64_t) page_size();
3835 void hexdump(FILE *f
, const void *p
, size_t s
) {
3836 const uint8_t *b
= p
;
3839 assert(s
== 0 || b
);
3844 fprintf(f
, "%04x ", n
);
3846 for (i
= 0; i
< 16; i
++) {
3851 fprintf(f
, "%02x ", b
[i
]);
3859 for (i
= 0; i
< 16; i
++) {
3864 fputc(isprint(b
[i
]) ? (char) b
[i
] : '.', f
);
3878 int update_reboot_param_file(const char *param
) {
3882 r
= write_string_file(REBOOT_PARAM_FILE
, param
, WRITE_STRING_FILE_CREATE
);
3884 return log_error_errno(r
, "Failed to write reboot param to "REBOOT_PARAM_FILE
": %m");
3886 (void) unlink(REBOOT_PARAM_FILE
);
3891 int umount_recursive(const char *prefix
, int flags
) {
3895 /* Try to umount everything recursively below a
3896 * directory. Also, take care of stacked mounts, and keep
3897 * unmounting them until they are gone. */
3900 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
3905 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
3906 if (!proc_self_mountinfo
)
3910 _cleanup_free_
char *path
= NULL
, *p
= NULL
;
3913 k
= fscanf(proc_self_mountinfo
,
3914 "%*s " /* (1) mount id */
3915 "%*s " /* (2) parent id */
3916 "%*s " /* (3) major:minor */
3917 "%*s " /* (4) root */
3918 "%ms " /* (5) mount point */
3919 "%*s" /* (6) mount options */
3920 "%*[^-]" /* (7) optional fields */
3921 "- " /* (8) separator */
3922 "%*s " /* (9) file system type */
3923 "%*s" /* (10) mount source */
3924 "%*s" /* (11) mount options 2 */
3925 "%*[^\n]", /* some rubbish at the end */
3934 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
3938 if (!path_startswith(p
, prefix
))
3941 if (umount2(p
, flags
) < 0) {
3957 static int get_mount_flags(const char *path
, unsigned long *flags
) {
3960 if (statvfs(path
, &buf
) < 0)
3962 *flags
= buf
.f_flag
;
3966 int bind_remount_recursive(const char *prefix
, bool ro
) {
3967 _cleanup_set_free_free_ Set
*done
= NULL
;
3968 _cleanup_free_
char *cleaned
= NULL
;
3971 /* Recursively remount a directory (and all its submounts)
3972 * read-only or read-write. If the directory is already
3973 * mounted, we reuse the mount and simply mark it
3974 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
3975 * operation). If it isn't we first make it one. Afterwards we
3976 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
3977 * submounts we can access, too. When mounts are stacked on
3978 * the same mount point we only care for each individual
3979 * "top-level" mount on each point, as we cannot
3980 * influence/access the underlying mounts anyway. We do not
3981 * have any effect on future submounts that might get
3982 * propagated, they migt be writable. This includes future
3983 * submounts that have been triggered via autofs. */
3985 cleaned
= strdup(prefix
);
3989 path_kill_slashes(cleaned
);
3991 done
= set_new(&string_hash_ops
);
3996 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
3997 _cleanup_set_free_free_ Set
*todo
= NULL
;
3998 bool top_autofs
= false;
4000 unsigned long orig_flags
;
4002 todo
= set_new(&string_hash_ops
);
4006 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
4007 if (!proc_self_mountinfo
)
4011 _cleanup_free_
char *path
= NULL
, *p
= NULL
, *type
= NULL
;
4014 k
= fscanf(proc_self_mountinfo
,
4015 "%*s " /* (1) mount id */
4016 "%*s " /* (2) parent id */
4017 "%*s " /* (3) major:minor */
4018 "%*s " /* (4) root */
4019 "%ms " /* (5) mount point */
4020 "%*s" /* (6) mount options (superblock) */
4021 "%*[^-]" /* (7) optional fields */
4022 "- " /* (8) separator */
4023 "%ms " /* (9) file system type */
4024 "%*s" /* (10) mount source */
4025 "%*s" /* (11) mount options (bind mount) */
4026 "%*[^\n]", /* some rubbish at the end */
4036 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
4040 /* Let's ignore autofs mounts. If they aren't
4041 * triggered yet, we want to avoid triggering
4042 * them, as we don't make any guarantees for
4043 * future submounts anyway. If they are
4044 * already triggered, then we will find
4045 * another entry for this. */
4046 if (streq(type
, "autofs")) {
4047 top_autofs
= top_autofs
|| path_equal(cleaned
, p
);
4051 if (path_startswith(p
, cleaned
) &&
4052 !set_contains(done
, p
)) {
4054 r
= set_consume(todo
, p
);
4064 /* If we have no submounts to process anymore and if
4065 * the root is either already done, or an autofs, we
4067 if (set_isempty(todo
) &&
4068 (top_autofs
|| set_contains(done
, cleaned
)))
4071 if (!set_contains(done
, cleaned
) &&
4072 !set_contains(todo
, cleaned
)) {
4073 /* The prefix directory itself is not yet a
4074 * mount, make it one. */
4075 if (mount(cleaned
, cleaned
, NULL
, MS_BIND
|MS_REC
, NULL
) < 0)
4079 (void) get_mount_flags(cleaned
, &orig_flags
);
4080 orig_flags
&= ~MS_RDONLY
;
4082 if (mount(NULL
, prefix
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0)
4085 x
= strdup(cleaned
);
4089 r
= set_consume(done
, x
);
4094 while ((x
= set_steal_first(todo
))) {
4096 r
= set_consume(done
, x
);
4097 if (r
== -EEXIST
|| r
== 0)
4102 /* Try to reuse the original flag set, but
4103 * don't care for errors, in case of
4104 * obstructed mounts */
4106 (void) get_mount_flags(x
, &orig_flags
);
4107 orig_flags
&= ~MS_RDONLY
;
4109 if (mount(NULL
, x
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0) {
4111 /* Deal with mount points that are
4112 * obstructed by a later mount */
4114 if (errno
!= ENOENT
)
4122 int fflush_and_check(FILE *f
) {
4129 return errno
? -errno
: -EIO
;
4134 int tempfn_xxxxxx(const char *p
, const char *extra
, char **ret
) {
4146 * /foo/bar/.#<extra>waldoXXXXXX
4150 if (!filename_is_valid(fn
))
4156 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 6 + 1);
4160 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
), "XXXXXX");
4162 *ret
= path_kill_slashes(t
);
4166 int tempfn_random(const char *p
, const char *extra
, char **ret
) {
4180 * /foo/bar/.#<extra>waldobaa2a261115984a9
4184 if (!filename_is_valid(fn
))
4190 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 16 + 1);
4194 x
= stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
);
4197 for (i
= 0; i
< 16; i
++) {
4198 *(x
++) = hexchar(u
& 0xF);
4204 *ret
= path_kill_slashes(t
);
4208 int tempfn_random_child(const char *p
, const char *extra
, char **ret
) {
4219 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
4225 t
= new(char, strlen(p
) + 3 + strlen(extra
) + 16 + 1);
4229 x
= stpcpy(stpcpy(stpcpy(t
, p
), "/.#"), extra
);
4232 for (i
= 0; i
< 16; i
++) {
4233 *(x
++) = hexchar(u
& 0xF);
4239 *ret
= path_kill_slashes(t
);
4243 int take_password_lock(const char *root
) {
4245 struct flock flock
= {
4247 .l_whence
= SEEK_SET
,
4255 /* This is roughly the same as lckpwdf(), but not as awful. We
4256 * don't want to use alarm() and signals, hence we implement
4257 * our own trivial version of this.
4259 * Note that shadow-utils also takes per-database locks in
4260 * addition to lckpwdf(). However, we don't given that they
4261 * are redundant as they they invoke lckpwdf() first and keep
4262 * it during everything they do. The per-database locks are
4263 * awfully racy, and thus we just won't do them. */
4266 path
= strjoina(root
, "/etc/.pwd.lock");
4268 path
= "/etc/.pwd.lock";
4270 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
4274 r
= fcntl(fd
, F_SETLKW
, &flock
);
4283 int is_symlink(const char *path
) {
4286 if (lstat(path
, &info
) < 0)
4289 return !!S_ISLNK(info
.st_mode
);
4292 int is_dir(const char* path
, bool follow
) {
4297 r
= stat(path
, &st
);
4299 r
= lstat(path
, &st
);
4303 return !!S_ISDIR(st
.st_mode
);
4306 int is_device_node(const char *path
) {
4309 if (lstat(path
, &info
) < 0)
4312 return !!(S_ISBLK(info
.st_mode
) || S_ISCHR(info
.st_mode
));
4315 ssize_t
fgetxattrat_fake(int dirfd
, const char *filename
, const char *attribute
, void *value
, size_t size
, int flags
) {
4316 char fn
[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(int) + 1];
4317 _cleanup_close_
int fd
= -1;
4320 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
4322 fd
= openat(dirfd
, filename
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_PATH
|(flags
& AT_SYMLINK_NOFOLLOW
? O_NOFOLLOW
: 0));
4326 xsprintf(fn
, "/proc/self/fd/%i", fd
);
4328 l
= getxattr(fn
, attribute
, value
, size
);
4335 static int parse_crtime(le64_t le
, usec_t
*usec
) {
4341 if (u
== 0 || u
== (uint64_t) -1)
4348 int fd_getcrtime(int fd
, usec_t
*usec
) {
4355 /* Until Linux gets a real concept of birthtime/creation time,
4356 * let's fake one with xattrs */
4358 n
= fgetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
));
4361 if (n
!= sizeof(le
))
4364 return parse_crtime(le
, usec
);
4367 int fd_getcrtime_at(int dirfd
, const char *name
, usec_t
*usec
, int flags
) {
4371 n
= fgetxattrat_fake(dirfd
, name
, "user.crtime_usec", &le
, sizeof(le
), flags
);
4374 if (n
!= sizeof(le
))
4377 return parse_crtime(le
, usec
);
4380 int path_getcrtime(const char *p
, usec_t
*usec
) {
4387 n
= getxattr(p
, "user.crtime_usec", &le
, sizeof(le
));
4390 if (n
!= sizeof(le
))
4393 return parse_crtime(le
, usec
);
4396 int fd_setcrtime(int fd
, usec_t usec
) {
4402 usec
= now(CLOCK_REALTIME
);
4404 le
= htole64((uint64_t) usec
);
4405 if (fsetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
), 0) < 0)
4411 int chattr_fd(int fd
, unsigned value
, unsigned mask
) {
4412 unsigned old_attr
, new_attr
;
4417 if (fstat(fd
, &st
) < 0)
4420 /* Explicitly check whether this is a regular file or
4421 * directory. If it is anything else (such as a device node or
4422 * fifo), then the ioctl will not hit the file systems but
4423 * possibly drivers, where the ioctl might have different
4424 * effects. Notably, DRM is using the same ioctl() number. */
4426 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
4432 if (ioctl(fd
, FS_IOC_GETFLAGS
, &old_attr
) < 0)
4435 new_attr
= (old_attr
& ~mask
) | (value
& mask
);
4436 if (new_attr
== old_attr
)
4439 if (ioctl(fd
, FS_IOC_SETFLAGS
, &new_attr
) < 0)
4445 int chattr_path(const char *p
, unsigned value
, unsigned mask
) {
4446 _cleanup_close_
int fd
= -1;
4453 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
4457 return chattr_fd(fd
, value
, mask
);
4460 int read_attr_fd(int fd
, unsigned *ret
) {
4465 if (fstat(fd
, &st
) < 0)
4468 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
4471 if (ioctl(fd
, FS_IOC_GETFLAGS
, ret
) < 0)
4477 int read_attr_path(const char *p
, unsigned *ret
) {
4478 _cleanup_close_
int fd
= -1;
4483 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
4487 return read_attr_fd(fd
, ret
);
4490 void sigkill_wait(pid_t
*pid
) {
4496 if (kill(*pid
, SIGKILL
) > 0)
4497 (void) wait_for_terminate(*pid
, NULL
);
4500 int syslog_parse_priority(const char **p
, int *priority
, bool with_facility
) {
4501 int a
= 0, b
= 0, c
= 0;
4511 if (!strchr(*p
, '>'))
4514 if ((*p
)[2] == '>') {
4515 c
= undecchar((*p
)[1]);
4517 } else if ((*p
)[3] == '>') {
4518 b
= undecchar((*p
)[1]);
4519 c
= undecchar((*p
)[2]);
4521 } else if ((*p
)[4] == '>') {
4522 a
= undecchar((*p
)[1]);
4523 b
= undecchar((*p
)[2]);
4524 c
= undecchar((*p
)[3]);
4529 if (a
< 0 || b
< 0 || c
< 0 ||
4530 (!with_facility
&& (a
|| b
|| c
> 7)))
4534 *priority
= a
*100 + b
*10 + c
;
4536 *priority
= (*priority
& LOG_FACMASK
) | c
;
4542 ssize_t
string_table_lookup(const char * const *table
, size_t len
, const char *key
) {
4548 for (i
= 0; i
< len
; ++i
)
4549 if (streq_ptr(table
[i
], key
))
4555 int rename_noreplace(int olddirfd
, const char *oldpath
, int newdirfd
, const char *newpath
) {
4559 ret
= renameat2(olddirfd
, oldpath
, newdirfd
, newpath
, RENAME_NOREPLACE
);
4563 /* renameat2() exists since Linux 3.15, btrfs added support for it later.
4564 * If it is not implemented, fallback to another method. */
4565 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
4568 /* The link()/unlink() fallback does not work on directories. But
4569 * renameat() without RENAME_NOREPLACE gives the same semantics on
4570 * directories, except when newpath is an *empty* directory. This is
4572 ret
= fstatat(olddirfd
, oldpath
, &buf
, AT_SYMLINK_NOFOLLOW
);
4573 if (ret
>= 0 && S_ISDIR(buf
.st_mode
)) {
4574 ret
= renameat(olddirfd
, oldpath
, newdirfd
, newpath
);
4575 return ret
>= 0 ? 0 : -errno
;
4578 /* If it is not a directory, use the link()/unlink() fallback. */
4579 ret
= linkat(olddirfd
, oldpath
, newdirfd
, newpath
, 0);
4583 ret
= unlinkat(olddirfd
, oldpath
, 0);
4585 /* backup errno before the following unlinkat() alters it */
4587 (void) unlinkat(newdirfd
, newpath
, 0);
4595 int parse_mode(const char *s
, mode_t
*ret
) {
4603 l
= strtol(s
, &x
, 8);
4607 if (!x
|| x
== s
|| *x
)
4609 if (l
< 0 || l
> 07777)
4616 int mount_move_root(const char *path
) {
4619 if (chdir(path
) < 0)
4622 if (mount(path
, "/", NULL
, MS_MOVE
, NULL
) < 0)
4625 if (chroot(".") < 0)
4634 int reset_uid_gid(void) {
4636 if (setgroups(0, NULL
) < 0)
4639 if (setresgid(0, 0, 0) < 0)
4642 if (setresuid(0, 0, 0) < 0)
4648 int getxattr_malloc(const char *path
, const char *name
, char **value
, bool allow_symlink
) {
4657 for (l
= 100; ; l
= (size_t) n
+ 1) {
4663 n
= lgetxattr(path
, name
, v
, l
);
4665 n
= getxattr(path
, name
, v
, l
);
4667 if (n
>= 0 && (size_t) n
< l
) {
4674 if (n
< 0 && errno
!= ERANGE
)
4678 n
= lgetxattr(path
, name
, NULL
, 0);
4680 n
= getxattr(path
, name
, NULL
, 0);
4686 int fgetxattr_malloc(int fd
, const char *name
, char **value
) {
4695 for (l
= 100; ; l
= (size_t) n
+ 1) {
4700 n
= fgetxattr(fd
, name
, v
, l
);
4702 if (n
>= 0 && (size_t) n
< l
) {
4709 if (n
< 0 && errno
!= ERANGE
)
4712 n
= fgetxattr(fd
, name
, NULL
, 0);
4718 int send_one_fd(int transport_fd
, int fd
, int flags
) {
4720 struct cmsghdr cmsghdr
;
4721 uint8_t buf
[CMSG_SPACE(sizeof(int))];
4723 struct msghdr mh
= {
4724 .msg_control
= &control
,
4725 .msg_controllen
= sizeof(control
),
4727 struct cmsghdr
*cmsg
;
4729 assert(transport_fd
>= 0);
4732 cmsg
= CMSG_FIRSTHDR(&mh
);
4733 cmsg
->cmsg_level
= SOL_SOCKET
;
4734 cmsg
->cmsg_type
= SCM_RIGHTS
;
4735 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
4736 memcpy(CMSG_DATA(cmsg
), &fd
, sizeof(int));
4738 mh
.msg_controllen
= CMSG_SPACE(sizeof(int));
4739 if (sendmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| flags
) < 0)
4745 int receive_one_fd(int transport_fd
, int flags
) {
4747 struct cmsghdr cmsghdr
;
4748 uint8_t buf
[CMSG_SPACE(sizeof(int))];
4750 struct msghdr mh
= {
4751 .msg_control
= &control
,
4752 .msg_controllen
= sizeof(control
),
4754 struct cmsghdr
*cmsg
, *found
= NULL
;
4756 assert(transport_fd
>= 0);
4759 * Receive a single FD via @transport_fd. We don't care for
4760 * the transport-type. We retrieve a single FD at most, so for
4761 * packet-based transports, the caller must ensure to send
4762 * only a single FD per packet. This is best used in
4763 * combination with send_one_fd().
4766 if (recvmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| MSG_CMSG_CLOEXEC
| flags
) < 0)
4769 CMSG_FOREACH(cmsg
, &mh
) {
4770 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
4771 cmsg
->cmsg_type
== SCM_RIGHTS
&&
4772 cmsg
->cmsg_len
== CMSG_LEN(sizeof(int))) {
4780 cmsg_close_all(&mh
);
4784 return *(int*) CMSG_DATA(found
);
4787 void nop_signal_handler(int sig
) {
4792 puts(PACKAGE_STRING
"\n"
4797 bool fdname_is_valid(const char *s
) {
4800 /* Validates a name for $LISTEN_FDNAMES. We basically allow
4801 * everything ASCII that's not a control character. Also, as
4802 * special exception the ":" character is not allowed, as we
4803 * use that as field separator in $LISTEN_FDNAMES.
4805 * Note that the empty string is explicitly allowed
4806 * here. However, we limit the length of the names to 255
4812 for (p
= s
; *p
; p
++) {
4824 bool oom_score_adjust_is_valid(int oa
) {
4825 return oa
>= OOM_SCORE_ADJ_MIN
&& oa
<= OOM_SCORE_ADJ_MAX
;