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 flush_fd(int fd
) {
1240 struct pollfd pollfd
= {
1250 r
= poll(&pollfd
, 1, 0);
1260 l
= read(fd
, buf
, sizeof(buf
));
1266 if (errno
== EAGAIN
)
1275 ssize_t
loop_read(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
1282 /* If called with nbytes == 0, let's call read() at least
1283 * once, to validate the operation */
1285 if (nbytes
> (size_t) SSIZE_MAX
)
1291 k
= read(fd
, p
, nbytes
);
1296 if (errno
== EAGAIN
&& do_poll
) {
1298 /* We knowingly ignore any return value here,
1299 * and expect that any error/EOF is reported
1302 (void) fd_wait_for_event(fd
, POLLIN
, USEC_INFINITY
);
1306 return n
> 0 ? n
: -errno
;
1312 assert((size_t) k
<= nbytes
);
1317 } while (nbytes
> 0);
1322 int loop_read_exact(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
1325 n
= loop_read(fd
, buf
, nbytes
, do_poll
);
1328 if ((size_t) n
!= nbytes
)
1334 int loop_write(int fd
, const void *buf
, size_t nbytes
, bool do_poll
) {
1335 const uint8_t *p
= buf
;
1340 if (nbytes
> (size_t) SSIZE_MAX
)
1346 k
= write(fd
, p
, nbytes
);
1351 if (errno
== EAGAIN
&& do_poll
) {
1352 /* We knowingly ignore any return value here,
1353 * and expect that any error/EOF is reported
1356 (void) fd_wait_for_event(fd
, POLLOUT
, USEC_INFINITY
);
1363 if (_unlikely_(nbytes
> 0 && k
== 0)) /* Can't really happen */
1366 assert((size_t) k
<= nbytes
);
1370 } while (nbytes
> 0);
1375 int parse_size(const char *t
, uint64_t base
, uint64_t *size
) {
1377 /* Soo, sometimes we want to parse IEC binary suffixes, and
1378 * sometimes SI decimal suffixes. This function can parse
1379 * both. Which one is the right way depends on the
1380 * context. Wikipedia suggests that SI is customary for
1381 * hardware metrics and network speeds, while IEC is
1382 * customary for most data sizes used by software and volatile
1383 * (RAM) memory. Hence be careful which one you pick!
1385 * In either case we use just K, M, G as suffix, and not Ki,
1386 * Mi, Gi or so (as IEC would suggest). That's because that's
1387 * frickin' ugly. But this means you really need to make sure
1388 * to document which base you are parsing when you use this
1393 unsigned long long factor
;
1396 static const struct table iec
[] = {
1397 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1398 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1399 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
1400 { "G", 1024ULL*1024ULL*1024ULL },
1401 { "M", 1024ULL*1024ULL },
1407 static const struct table si
[] = {
1408 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1409 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1410 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
1411 { "G", 1000ULL*1000ULL*1000ULL },
1412 { "M", 1000ULL*1000ULL },
1418 const struct table
*table
;
1420 unsigned long long r
= 0;
1421 unsigned n_entries
, start_pos
= 0;
1424 assert(base
== 1000 || base
== 1024);
1429 n_entries
= ELEMENTSOF(si
);
1432 n_entries
= ELEMENTSOF(iec
);
1437 unsigned long long l
, tmp
;
1442 p
+= strspn(p
, WHITESPACE
);
1447 l
= strtoull(p
, &e
, 10);
1456 /* strtoull() itself would accept space/+/- */
1457 if (*e
>= '0' && *e
<= '9') {
1458 unsigned long long l2
;
1461 l2
= strtoull(e
, &e2
, 10);
1465 /* Ignore failure. E.g. 10.M is valid */
1472 e
+= strspn(e
, WHITESPACE
);
1474 for (i
= start_pos
; i
< n_entries
; i
++)
1475 if (startswith(e
, table
[i
].suffix
))
1481 if (l
+ (frac
> 0) > ULLONG_MAX
/ table
[i
].factor
)
1484 tmp
= l
* table
[i
].factor
+ (unsigned long long) (frac
* table
[i
].factor
);
1485 if (tmp
> ULLONG_MAX
- r
)
1489 if ((unsigned long long) (uint64_t) r
!= r
)
1492 p
= e
+ strlen(table
[i
].suffix
);
1503 bool is_device_path(const char *path
) {
1505 /* Returns true on paths that refer to a device, either in
1506 * sysfs or in /dev */
1509 path_startswith(path
, "/dev/") ||
1510 path_startswith(path
, "/sys/");
1513 int dir_is_empty(const char *path
) {
1514 _cleanup_closedir_
DIR *d
;
1521 FOREACH_DIRENT(de
, d
, return -errno
)
1527 char* dirname_malloc(const char *path
) {
1528 char *d
, *dir
, *dir2
;
1545 void rename_process(const char name
[8]) {
1548 /* This is a like a poor man's setproctitle(). It changes the
1549 * comm field, argv[0], and also the glibc's internally used
1550 * name of the process. For the first one a limit of 16 chars
1551 * applies, to the second one usually one of 10 (i.e. length
1552 * of "/sbin/init"), to the third one one of 7 (i.e. length of
1553 * "systemd"). If you pass a longer string it will be
1556 prctl(PR_SET_NAME
, name
);
1558 if (program_invocation_name
)
1559 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
1561 if (saved_argc
> 0) {
1565 strncpy(saved_argv
[0], name
, strlen(saved_argv
[0]));
1567 for (i
= 1; i
< saved_argc
; i
++) {
1571 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
1576 char *lookup_uid(uid_t uid
) {
1579 _cleanup_free_
char *buf
= NULL
;
1580 struct passwd pwbuf
, *pw
= NULL
;
1582 /* Shortcut things to avoid NSS lookups */
1584 return strdup("root");
1586 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1590 buf
= malloc(bufsize
);
1594 if (getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
) == 0 && pw
)
1595 return strdup(pw
->pw_name
);
1597 if (asprintf(&name
, UID_FMT
, uid
) < 0)
1603 char* getlogname_malloc(void) {
1607 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
1612 return lookup_uid(uid
);
1615 char *getusername_malloc(void) {
1622 return lookup_uid(getuid());
1625 bool is_fs_type(const struct statfs
*s
, statfs_f_type_t magic_value
) {
1627 assert_cc(sizeof(statfs_f_type_t
) >= sizeof(s
->f_type
));
1629 return F_TYPE_EQUAL(s
->f_type
, magic_value
);
1632 int fd_check_fstype(int fd
, statfs_f_type_t magic_value
) {
1635 if (fstatfs(fd
, &s
) < 0)
1638 return is_fs_type(&s
, magic_value
);
1641 int path_check_fstype(const char *path
, statfs_f_type_t magic_value
) {
1642 _cleanup_close_
int fd
= -1;
1644 fd
= open(path
, O_RDONLY
);
1648 return fd_check_fstype(fd
, magic_value
);
1651 bool is_temporary_fs(const struct statfs
*s
) {
1652 return is_fs_type(s
, TMPFS_MAGIC
) ||
1653 is_fs_type(s
, RAMFS_MAGIC
);
1656 int fd_is_temporary_fs(int fd
) {
1659 if (fstatfs(fd
, &s
) < 0)
1662 return is_temporary_fs(&s
);
1665 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
1668 /* Under the assumption that we are running privileged we
1669 * first change the access mode and only then hand out
1670 * ownership to avoid a window where access is too open. */
1672 if (mode
!= MODE_INVALID
)
1673 if (chmod(path
, mode
) < 0)
1676 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
1677 if (chown(path
, uid
, gid
) < 0)
1683 int fchmod_and_fchown(int fd
, mode_t mode
, uid_t uid
, gid_t gid
) {
1686 /* Under the assumption that we are running privileged we
1687 * first change the access mode and only then hand out
1688 * ownership to avoid a window where access is too open. */
1690 if (mode
!= MODE_INVALID
)
1691 if (fchmod(fd
, mode
) < 0)
1694 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
1695 if (fchown(fd
, uid
, gid
) < 0)
1701 int files_same(const char *filea
, const char *fileb
) {
1704 if (stat(filea
, &a
) < 0)
1707 if (stat(fileb
, &b
) < 0)
1710 return a
.st_dev
== b
.st_dev
&&
1711 a
.st_ino
== b
.st_ino
;
1714 int running_in_chroot(void) {
1717 ret
= files_same("/proc/1/root", "/");
1724 int touch_file(const char *path
, bool parents
, usec_t stamp
, uid_t uid
, gid_t gid
, mode_t mode
) {
1725 _cleanup_close_
int fd
;
1731 mkdir_parents(path
, 0755);
1733 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, mode
> 0 ? mode
: 0644);
1738 r
= fchmod(fd
, mode
);
1743 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
) {
1744 r
= fchown(fd
, uid
, gid
);
1749 if (stamp
!= USEC_INFINITY
) {
1750 struct timespec ts
[2];
1752 timespec_store(&ts
[0], stamp
);
1754 r
= futimens(fd
, ts
);
1756 r
= futimens(fd
, NULL
);
1763 int touch(const char *path
) {
1764 return touch_file(path
, false, USEC_INFINITY
, UID_INVALID
, GID_INVALID
, 0);
1767 static char *unquote(const char *s
, const char* quotes
) {
1771 /* This is rather stupid, simply removes the heading and
1772 * trailing quotes if there is one. Doesn't care about
1773 * escaping or anything.
1775 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
1781 if (strchr(quotes
, s
[0]) && s
[l
-1] == s
[0])
1782 return strndup(s
+1, l
-2);
1787 noreturn
void freeze(void) {
1789 /* Make sure nobody waits for us on a socket anymore */
1790 close_all_fds(NULL
, 0);
1798 bool null_or_empty(struct stat
*st
) {
1801 if (S_ISREG(st
->st_mode
) && st
->st_size
<= 0)
1804 if (S_ISCHR(st
->st_mode
) || S_ISBLK(st
->st_mode
))
1810 int null_or_empty_path(const char *fn
) {
1815 if (stat(fn
, &st
) < 0)
1818 return null_or_empty(&st
);
1821 int null_or_empty_fd(int fd
) {
1826 if (fstat(fd
, &st
) < 0)
1829 return null_or_empty(&st
);
1832 DIR *xopendirat(int fd
, const char *name
, int flags
) {
1836 assert(!(flags
& O_CREAT
));
1838 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
1851 static char *tag_to_udev_node(const char *tagvalue
, const char *by
) {
1852 _cleanup_free_
char *t
= NULL
, *u
= NULL
;
1855 u
= unquote(tagvalue
, QUOTES
);
1859 enc_len
= strlen(u
) * 4 + 1;
1860 t
= new(char, enc_len
);
1864 if (encode_devnode_name(u
, t
, enc_len
) < 0)
1867 return strjoin("/dev/disk/by-", by
, "/", t
, NULL
);
1870 char *fstab_node_to_udev_node(const char *p
) {
1873 if (startswith(p
, "LABEL="))
1874 return tag_to_udev_node(p
+6, "label");
1876 if (startswith(p
, "UUID="))
1877 return tag_to_udev_node(p
+5, "uuid");
1879 if (startswith(p
, "PARTUUID="))
1880 return tag_to_udev_node(p
+9, "partuuid");
1882 if (startswith(p
, "PARTLABEL="))
1883 return tag_to_udev_node(p
+10, "partlabel");
1888 bool dirent_is_file(const struct dirent
*de
) {
1891 if (hidden_file(de
->d_name
))
1894 if (de
->d_type
!= DT_REG
&&
1895 de
->d_type
!= DT_LNK
&&
1896 de
->d_type
!= DT_UNKNOWN
)
1902 bool dirent_is_file_with_suffix(const struct dirent
*de
, const char *suffix
) {
1905 if (de
->d_type
!= DT_REG
&&
1906 de
->d_type
!= DT_LNK
&&
1907 de
->d_type
!= DT_UNKNOWN
)
1910 if (hidden_file_allow_backup(de
->d_name
))
1913 return endswith(de
->d_name
, suffix
);
1916 static int do_execute(char **directories
, usec_t timeout
, char *argv
[]) {
1917 _cleanup_hashmap_free_free_ Hashmap
*pids
= NULL
;
1918 _cleanup_set_free_free_ Set
*seen
= NULL
;
1921 /* We fork this all off from a child process so that we can
1922 * somewhat cleanly make use of SIGALRM to set a time limit */
1924 (void) reset_all_signal_handlers();
1925 (void) reset_signal_mask();
1927 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
1929 pids
= hashmap_new(NULL
);
1933 seen
= set_new(&string_hash_ops
);
1937 STRV_FOREACH(directory
, directories
) {
1938 _cleanup_closedir_
DIR *d
;
1941 d
= opendir(*directory
);
1943 if (errno
== ENOENT
)
1946 return log_error_errno(errno
, "Failed to open directory %s: %m", *directory
);
1949 FOREACH_DIRENT(de
, d
, break) {
1950 _cleanup_free_
char *path
= NULL
;
1954 if (!dirent_is_file(de
))
1957 if (set_contains(seen
, de
->d_name
)) {
1958 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory
, de
->d_name
);
1962 r
= set_put_strdup(seen
, de
->d_name
);
1966 path
= strjoin(*directory
, "/", de
->d_name
, NULL
);
1970 if (null_or_empty_path(path
)) {
1971 log_debug("%s is empty (a mask).", path
);
1977 log_error_errno(errno
, "Failed to fork: %m");
1979 } else if (pid
== 0) {
1982 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
1992 return log_error_errno(errno
, "Failed to execute %s: %m", path
);
1995 log_debug("Spawned %s as " PID_FMT
".", path
, pid
);
1997 r
= hashmap_put(pids
, UINT_TO_PTR(pid
), path
);
2004 /* Abort execution of this process after the timout. We simply
2005 * rely on SIGALRM as default action terminating the process,
2006 * and turn on alarm(). */
2008 if (timeout
!= USEC_INFINITY
)
2009 alarm((timeout
+ USEC_PER_SEC
- 1) / USEC_PER_SEC
);
2011 while (!hashmap_isempty(pids
)) {
2012 _cleanup_free_
char *path
= NULL
;
2015 pid
= PTR_TO_UINT(hashmap_first_key(pids
));
2018 path
= hashmap_remove(pids
, UINT_TO_PTR(pid
));
2021 wait_for_terminate_and_warn(path
, pid
, true);
2027 void execute_directories(const char* const* directories
, usec_t timeout
, char *argv
[]) {
2031 char **dirs
= (char**) directories
;
2033 assert(!strv_isempty(dirs
));
2035 name
= basename(dirs
[0]);
2036 assert(!isempty(name
));
2038 /* Executes all binaries in the directories in parallel and waits
2039 * for them to finish. Optionally a timeout is applied. If a file
2040 * with the same name exists in more than one directory, the
2041 * earliest one wins. */
2043 executor_pid
= fork();
2044 if (executor_pid
< 0) {
2045 log_error_errno(errno
, "Failed to fork: %m");
2048 } else if (executor_pid
== 0) {
2049 r
= do_execute(dirs
, timeout
, argv
);
2050 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
2053 wait_for_terminate_and_warn(name
, executor_pid
, true);
2056 bool plymouth_running(void) {
2057 return access("/run/plymouth/pid", F_OK
) >= 0;
2060 int pipe_eof(int fd
) {
2061 struct pollfd pollfd
= {
2063 .events
= POLLIN
|POLLHUP
,
2068 r
= poll(&pollfd
, 1, 0);
2075 return pollfd
.revents
& POLLHUP
;
2078 int fd_wait_for_event(int fd
, int event
, usec_t t
) {
2080 struct pollfd pollfd
= {
2088 r
= ppoll(&pollfd
, 1, t
== USEC_INFINITY
? NULL
: timespec_store(&ts
, t
), NULL
);
2095 return pollfd
.revents
;
2098 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
2107 r
= tempfn_xxxxxx(path
, NULL
, &t
);
2111 fd
= mkostemp_safe(t
, O_WRONLY
|O_CLOEXEC
);
2117 f
= fdopen(fd
, "we");
2131 int symlink_atomic(const char *from
, const char *to
) {
2132 _cleanup_free_
char *t
= NULL
;
2138 r
= tempfn_random(to
, NULL
, &t
);
2142 if (symlink(from
, t
) < 0)
2145 if (rename(t
, to
) < 0) {
2153 int symlink_idempotent(const char *from
, const char *to
) {
2154 _cleanup_free_
char *p
= NULL
;
2160 if (symlink(from
, to
) < 0) {
2161 if (errno
!= EEXIST
)
2164 r
= readlink_malloc(to
, &p
);
2168 if (!streq(p
, from
))
2175 int mknod_atomic(const char *path
, mode_t mode
, dev_t dev
) {
2176 _cleanup_free_
char *t
= NULL
;
2181 r
= tempfn_random(path
, NULL
, &t
);
2185 if (mknod(t
, mode
, dev
) < 0)
2188 if (rename(t
, path
) < 0) {
2196 int mkfifo_atomic(const char *path
, mode_t mode
) {
2197 _cleanup_free_
char *t
= NULL
;
2202 r
= tempfn_random(path
, NULL
, &t
);
2206 if (mkfifo(t
, mode
) < 0)
2209 if (rename(t
, path
) < 0) {
2217 bool display_is_local(const char *display
) {
2221 display
[0] == ':' &&
2222 display
[1] >= '0' &&
2226 int socket_from_display(const char *display
, char **path
) {
2233 if (!display_is_local(display
))
2236 k
= strspn(display
+1, "0123456789");
2238 f
= new(char, strlen("/tmp/.X11-unix/X") + k
+ 1);
2242 c
= stpcpy(f
, "/tmp/.X11-unix/X");
2243 memcpy(c
, display
+1, k
);
2252 const char **username
,
2253 uid_t
*uid
, gid_t
*gid
,
2255 const char **shell
) {
2263 /* We enforce some special rules for uid=0: in order to avoid
2264 * NSS lookups for root we hardcode its data. */
2266 if (streq(*username
, "root") || streq(*username
, "0")) {
2284 if (parse_uid(*username
, &u
) >= 0) {
2288 /* If there are multiple users with the same id, make
2289 * sure to leave $USER to the configured value instead
2290 * of the first occurrence in the database. However if
2291 * the uid was configured by a numeric uid, then let's
2292 * pick the real username from /etc/passwd. */
2294 *username
= p
->pw_name
;
2297 p
= getpwnam(*username
);
2301 return errno
> 0 ? -errno
: -ESRCH
;
2313 *shell
= p
->pw_shell
;
2318 char* uid_to_name(uid_t uid
) {
2323 return strdup("root");
2327 return strdup(p
->pw_name
);
2329 if (asprintf(&r
, UID_FMT
, uid
) < 0)
2335 char* gid_to_name(gid_t gid
) {
2340 return strdup("root");
2344 return strdup(p
->gr_name
);
2346 if (asprintf(&r
, GID_FMT
, gid
) < 0)
2352 int get_group_creds(const char **groupname
, gid_t
*gid
) {
2358 /* We enforce some special rules for gid=0: in order to avoid
2359 * NSS lookups for root we hardcode its data. */
2361 if (streq(*groupname
, "root") || streq(*groupname
, "0")) {
2362 *groupname
= "root";
2370 if (parse_gid(*groupname
, &id
) >= 0) {
2375 *groupname
= g
->gr_name
;
2378 g
= getgrnam(*groupname
);
2382 return errno
> 0 ? -errno
: -ESRCH
;
2390 int in_gid(gid_t gid
) {
2392 int ngroups_max
, r
, i
;
2394 if (getgid() == gid
)
2397 if (getegid() == gid
)
2400 ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
2401 assert(ngroups_max
> 0);
2403 gids
= alloca(sizeof(gid_t
) * ngroups_max
);
2405 r
= getgroups(ngroups_max
, gids
);
2409 for (i
= 0; i
< r
; i
++)
2416 int in_group(const char *name
) {
2420 r
= get_group_creds(&name
, &gid
);
2427 int glob_exists(const char *path
) {
2428 _cleanup_globfree_ glob_t g
= {};
2434 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
2436 if (k
== GLOB_NOMATCH
)
2438 else if (k
== GLOB_NOSPACE
)
2441 return !strv_isempty(g
.gl_pathv
);
2443 return errno
? -errno
: -EIO
;
2446 int glob_extend(char ***strv
, const char *path
) {
2447 _cleanup_globfree_ glob_t g
= {};
2452 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
2454 if (k
== GLOB_NOMATCH
)
2456 else if (k
== GLOB_NOSPACE
)
2458 else if (k
!= 0 || strv_isempty(g
.gl_pathv
))
2459 return errno
? -errno
: -EIO
;
2461 STRV_FOREACH(p
, g
.gl_pathv
) {
2462 k
= strv_extend(strv
, *p
);
2470 int dirent_ensure_type(DIR *d
, struct dirent
*de
) {
2476 if (de
->d_type
!= DT_UNKNOWN
)
2479 if (fstatat(dirfd(d
), de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
2483 S_ISREG(st
.st_mode
) ? DT_REG
:
2484 S_ISDIR(st
.st_mode
) ? DT_DIR
:
2485 S_ISLNK(st
.st_mode
) ? DT_LNK
:
2486 S_ISFIFO(st
.st_mode
) ? DT_FIFO
:
2487 S_ISSOCK(st
.st_mode
) ? DT_SOCK
:
2488 S_ISCHR(st
.st_mode
) ? DT_CHR
:
2489 S_ISBLK(st
.st_mode
) ? DT_BLK
:
2495 int get_files_in_directory(const char *path
, char ***list
) {
2496 _cleanup_closedir_
DIR *d
= NULL
;
2497 size_t bufsize
= 0, n
= 0;
2498 _cleanup_strv_free_
char **l
= NULL
;
2502 /* Returns all files in a directory in *list, and the number
2503 * of files as return value. If list is NULL returns only the
2515 if (!de
&& errno
!= 0)
2520 dirent_ensure_type(d
, de
);
2522 if (!dirent_is_file(de
))
2526 /* one extra slot is needed for the terminating NULL */
2527 if (!GREEDY_REALLOC(l
, bufsize
, n
+ 2))
2530 l
[n
] = strdup(de
->d_name
);
2541 l
= NULL
; /* avoid freeing */
2547 bool is_main_thread(void) {
2548 static thread_local
int cached
= 0;
2550 if (_unlikely_(cached
== 0))
2551 cached
= getpid() == gettid() ? 1 : -1;
2556 int block_get_whole_disk(dev_t d
, dev_t
*ret
) {
2563 /* If it has a queue this is good enough for us */
2564 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", major(d
), minor(d
)) < 0)
2567 r
= access(p
, F_OK
);
2575 /* If it is a partition find the originating device */
2576 if (asprintf(&p
, "/sys/dev/block/%u:%u/partition", major(d
), minor(d
)) < 0)
2579 r
= access(p
, F_OK
);
2585 /* Get parent dev_t */
2586 if (asprintf(&p
, "/sys/dev/block/%u:%u/../dev", major(d
), minor(d
)) < 0)
2589 r
= read_one_line_file(p
, &s
);
2595 r
= sscanf(s
, "%u:%u", &m
, &n
);
2601 /* Only return this if it is really good enough for us. */
2602 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", m
, n
) < 0)
2605 r
= access(p
, F_OK
);
2609 *ret
= makedev(m
, n
);
2616 static const char *const ioprio_class_table
[] = {
2617 [IOPRIO_CLASS_NONE
] = "none",
2618 [IOPRIO_CLASS_RT
] = "realtime",
2619 [IOPRIO_CLASS_BE
] = "best-effort",
2620 [IOPRIO_CLASS_IDLE
] = "idle"
2623 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, INT_MAX
);
2625 static const char *const sigchld_code_table
[] = {
2626 [CLD_EXITED
] = "exited",
2627 [CLD_KILLED
] = "killed",
2628 [CLD_DUMPED
] = "dumped",
2629 [CLD_TRAPPED
] = "trapped",
2630 [CLD_STOPPED
] = "stopped",
2631 [CLD_CONTINUED
] = "continued",
2634 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
2636 static const char *const log_facility_unshifted_table
[LOG_NFACILITIES
] = {
2637 [LOG_FAC(LOG_KERN
)] = "kern",
2638 [LOG_FAC(LOG_USER
)] = "user",
2639 [LOG_FAC(LOG_MAIL
)] = "mail",
2640 [LOG_FAC(LOG_DAEMON
)] = "daemon",
2641 [LOG_FAC(LOG_AUTH
)] = "auth",
2642 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
2643 [LOG_FAC(LOG_LPR
)] = "lpr",
2644 [LOG_FAC(LOG_NEWS
)] = "news",
2645 [LOG_FAC(LOG_UUCP
)] = "uucp",
2646 [LOG_FAC(LOG_CRON
)] = "cron",
2647 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
2648 [LOG_FAC(LOG_FTP
)] = "ftp",
2649 [LOG_FAC(LOG_LOCAL0
)] = "local0",
2650 [LOG_FAC(LOG_LOCAL1
)] = "local1",
2651 [LOG_FAC(LOG_LOCAL2
)] = "local2",
2652 [LOG_FAC(LOG_LOCAL3
)] = "local3",
2653 [LOG_FAC(LOG_LOCAL4
)] = "local4",
2654 [LOG_FAC(LOG_LOCAL5
)] = "local5",
2655 [LOG_FAC(LOG_LOCAL6
)] = "local6",
2656 [LOG_FAC(LOG_LOCAL7
)] = "local7"
2659 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted
, int, LOG_FAC(~0));
2661 bool log_facility_unshifted_is_valid(int facility
) {
2662 return facility
>= 0 && facility
<= LOG_FAC(~0);
2665 static const char *const log_level_table
[] = {
2666 [LOG_EMERG
] = "emerg",
2667 [LOG_ALERT
] = "alert",
2668 [LOG_CRIT
] = "crit",
2670 [LOG_WARNING
] = "warning",
2671 [LOG_NOTICE
] = "notice",
2672 [LOG_INFO
] = "info",
2673 [LOG_DEBUG
] = "debug"
2676 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level
, int, LOG_DEBUG
);
2678 bool log_level_is_valid(int level
) {
2679 return level
>= 0 && level
<= LOG_DEBUG
;
2682 static const char* const sched_policy_table
[] = {
2683 [SCHED_OTHER
] = "other",
2684 [SCHED_BATCH
] = "batch",
2685 [SCHED_IDLE
] = "idle",
2686 [SCHED_FIFO
] = "fifo",
2690 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);
2692 static const char* const rlimit_table
[_RLIMIT_MAX
] = {
2693 [RLIMIT_CPU
] = "LimitCPU",
2694 [RLIMIT_FSIZE
] = "LimitFSIZE",
2695 [RLIMIT_DATA
] = "LimitDATA",
2696 [RLIMIT_STACK
] = "LimitSTACK",
2697 [RLIMIT_CORE
] = "LimitCORE",
2698 [RLIMIT_RSS
] = "LimitRSS",
2699 [RLIMIT_NOFILE
] = "LimitNOFILE",
2700 [RLIMIT_AS
] = "LimitAS",
2701 [RLIMIT_NPROC
] = "LimitNPROC",
2702 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
2703 [RLIMIT_LOCKS
] = "LimitLOCKS",
2704 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
2705 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
2706 [RLIMIT_NICE
] = "LimitNICE",
2707 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
2708 [RLIMIT_RTTIME
] = "LimitRTTIME"
2711 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
2713 static const char* const ip_tos_table
[] = {
2714 [IPTOS_LOWDELAY
] = "low-delay",
2715 [IPTOS_THROUGHPUT
] = "throughput",
2716 [IPTOS_RELIABILITY
] = "reliability",
2717 [IPTOS_LOWCOST
] = "low-cost",
2720 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
2722 bool kexec_loaded(void) {
2723 bool loaded
= false;
2726 if (read_one_line_file("/sys/kernel/kexec_loaded", &s
) >= 0) {
2734 int prot_from_flags(int flags
) {
2736 switch (flags
& O_ACCMODE
) {
2745 return PROT_READ
|PROT_WRITE
;
2752 char *format_bytes(char *buf
, size_t l
, uint64_t t
) {
2755 static const struct {
2759 { "E", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2760 { "P", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2761 { "T", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2762 { "G", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2763 { "M", UINT64_C(1024)*UINT64_C(1024) },
2764 { "K", UINT64_C(1024) },
2767 if (t
== (uint64_t) -1)
2770 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
2772 if (t
>= table
[i
].factor
) {
2774 "%" PRIu64
".%" PRIu64
"%s",
2775 t
/ table
[i
].factor
,
2776 ((t
*UINT64_C(10)) / table
[i
].factor
) % UINT64_C(10),
2783 snprintf(buf
, l
, "%" PRIu64
"B", t
);
2791 void* memdup(const void *p
, size_t l
) {
2804 int fd_inc_sndbuf(int fd
, size_t n
) {
2806 socklen_t l
= sizeof(value
);
2808 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
2809 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
2812 /* If we have the privileges we will ignore the kernel limit. */
2815 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
2816 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
2822 int fd_inc_rcvbuf(int fd
, size_t n
) {
2824 socklen_t l
= sizeof(value
);
2826 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
2827 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
2830 /* If we have the privileges we will ignore the kernel limit. */
2833 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
2834 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
2839 int fork_agent(pid_t
*pid
, const int except
[], unsigned n_except
, const char *path
, ...) {
2840 bool stdout_is_tty
, stderr_is_tty
;
2841 pid_t parent_pid
, agent_pid
;
2842 sigset_t ss
, saved_ss
;
2850 /* Spawns a temporary TTY agent, making sure it goes away when
2853 parent_pid
= getpid();
2855 /* First we temporarily block all signals, so that the new
2856 * child has them blocked initially. This way, we can be sure
2857 * that SIGTERMs are not lost we might send to the agent. */
2858 assert_se(sigfillset(&ss
) >= 0);
2859 assert_se(sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) >= 0);
2862 if (agent_pid
< 0) {
2863 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
2867 if (agent_pid
!= 0) {
2868 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
2875 * Make sure the agent goes away when the parent dies */
2876 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
2877 _exit(EXIT_FAILURE
);
2879 /* Make sure we actually can kill the agent, if we need to, in
2880 * case somebody invoked us from a shell script that trapped
2881 * SIGTERM or so... */
2882 (void) reset_all_signal_handlers();
2883 (void) reset_signal_mask();
2885 /* Check whether our parent died before we were able
2886 * to set the death signal and unblock the signals */
2887 if (getppid() != parent_pid
)
2888 _exit(EXIT_SUCCESS
);
2890 /* Don't leak fds to the agent */
2891 close_all_fds(except
, n_except
);
2893 stdout_is_tty
= isatty(STDOUT_FILENO
);
2894 stderr_is_tty
= isatty(STDERR_FILENO
);
2896 if (!stdout_is_tty
|| !stderr_is_tty
) {
2899 /* Detach from stdout/stderr. and reopen
2900 * /dev/tty for them. This is important to
2901 * ensure that when systemctl is started via
2902 * popen() or a similar call that expects to
2903 * read EOF we actually do generate EOF and
2904 * not delay this indefinitely by because we
2905 * keep an unused copy of stdin around. */
2906 fd
= open("/dev/tty", O_WRONLY
);
2908 log_error_errno(errno
, "Failed to open /dev/tty: %m");
2909 _exit(EXIT_FAILURE
);
2913 dup2(fd
, STDOUT_FILENO
);
2916 dup2(fd
, STDERR_FILENO
);
2922 /* Count arguments */
2924 for (n
= 0; va_arg(ap
, char*); n
++)
2929 l
= alloca(sizeof(char *) * (n
+ 1));
2931 /* Fill in arguments */
2933 for (i
= 0; i
<= n
; i
++)
2934 l
[i
] = va_arg(ap
, char*);
2938 _exit(EXIT_FAILURE
);
2941 int setrlimit_closest(int resource
, const struct rlimit
*rlim
) {
2942 struct rlimit highest
, fixed
;
2946 if (setrlimit(resource
, rlim
) >= 0)
2952 /* So we failed to set the desired setrlimit, then let's try
2953 * to get as close as we can */
2954 assert_se(getrlimit(resource
, &highest
) == 0);
2956 fixed
.rlim_cur
= MIN(rlim
->rlim_cur
, highest
.rlim_max
);
2957 fixed
.rlim_max
= MIN(rlim
->rlim_max
, highest
.rlim_max
);
2959 if (setrlimit(resource
, &fixed
) < 0)
2965 bool http_etag_is_valid(const char *etag
) {
2969 if (!endswith(etag
, "\""))
2972 if (!startswith(etag
, "\"") && !startswith(etag
, "W/\""))
2978 bool http_url_is_valid(const char *url
) {
2984 p
= startswith(url
, "http://");
2986 p
= startswith(url
, "https://");
2993 return ascii_is_valid(p
);
2996 bool documentation_url_is_valid(const char *url
) {
3002 if (http_url_is_valid(url
))
3005 p
= startswith(url
, "file:/");
3007 p
= startswith(url
, "info:");
3009 p
= startswith(url
, "man:");
3014 return ascii_is_valid(p
);
3017 bool in_initrd(void) {
3018 static int saved
= -1;
3024 /* We make two checks here:
3026 * 1. the flag file /etc/initrd-release must exist
3027 * 2. the root file system must be a memory file system
3029 * The second check is extra paranoia, since misdetecting an
3030 * initrd can have bad bad consequences due the initrd
3031 * emptying when transititioning to the main systemd.
3034 saved
= access("/etc/initrd-release", F_OK
) >= 0 &&
3035 statfs("/", &s
) >= 0 &&
3036 is_temporary_fs(&s
);
3041 int get_home_dir(char **_h
) {
3049 /* Take the user specified one */
3050 e
= secure_getenv("HOME");
3051 if (e
&& path_is_absolute(e
)) {
3060 /* Hardcode home directory for root to avoid NSS */
3063 h
= strdup("/root");
3071 /* Check the database... */
3075 return errno
> 0 ? -errno
: -ESRCH
;
3077 if (!path_is_absolute(p
->pw_dir
))
3080 h
= strdup(p
->pw_dir
);
3088 int get_shell(char **_s
) {
3096 /* Take the user specified one */
3097 e
= getenv("SHELL");
3107 /* Hardcode home directory for root to avoid NSS */
3110 s
= strdup("/bin/sh");
3118 /* Check the database... */
3122 return errno
> 0 ? -errno
: -ESRCH
;
3124 if (!path_is_absolute(p
->pw_shell
))
3127 s
= strdup(p
->pw_shell
);
3135 bool filename_is_valid(const char *p
) {
3149 if (strlen(p
) > FILENAME_MAX
)
3155 bool string_is_safe(const char *p
) {
3161 for (t
= p
; *t
; t
++) {
3162 if (*t
> 0 && *t
< ' ')
3165 if (strchr("\\\"\'\x7f", *t
))
3172 bool path_is_safe(const char *p
) {
3177 if (streq(p
, "..") || startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
3180 if (strlen(p
)+1 > PATH_MAX
)
3183 /* The following two checks are not really dangerous, but hey, they still are confusing */
3184 if (streq(p
, ".") || startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
3187 if (strstr(p
, "//"))
3193 /* hey glibc, APIs with callbacks without a user pointer are so useless */
3194 void *xbsearch_r(const void *key
, const void *base
, size_t nmemb
, size_t size
,
3195 int (*compar
) (const void *, const void *, void *), void *arg
) {
3204 p
= (void *)(((const char *) base
) + (idx
* size
));
3205 comparison
= compar(key
, p
, arg
);
3208 else if (comparison
> 0)
3216 void init_gettext(void) {
3217 setlocale(LC_ALL
, "");
3218 textdomain(GETTEXT_PACKAGE
);
3221 bool is_locale_utf8(void) {
3223 static int cached_answer
= -1;
3225 if (cached_answer
>= 0)
3228 if (!setlocale(LC_ALL
, "")) {
3229 cached_answer
= true;
3233 set
= nl_langinfo(CODESET
);
3235 cached_answer
= true;
3239 if (streq(set
, "UTF-8")) {
3240 cached_answer
= true;
3244 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
3245 * unset and everything can do to UTF-8 nowadays. */
3246 set
= setlocale(LC_CTYPE
, NULL
);
3248 cached_answer
= true;
3252 /* Check result, but ignore the result if C was set
3255 STR_IN_SET(set
, "C", "POSIX") &&
3256 !getenv("LC_ALL") &&
3257 !getenv("LC_CTYPE") &&
3261 return (bool) cached_answer
;
3264 const char *draw_special_char(DrawSpecialChar ch
) {
3265 static const char *draw_table
[2][_DRAW_SPECIAL_CHAR_MAX
] = {
3268 [DRAW_TREE_VERTICAL
] = "\342\224\202 ", /* │ */
3269 [DRAW_TREE_BRANCH
] = "\342\224\234\342\224\200", /* ├─ */
3270 [DRAW_TREE_RIGHT
] = "\342\224\224\342\224\200", /* └─ */
3271 [DRAW_TREE_SPACE
] = " ", /* */
3272 [DRAW_TRIANGULAR_BULLET
] = "\342\200\243", /* ‣ */
3273 [DRAW_BLACK_CIRCLE
] = "\342\227\217", /* ● */
3274 [DRAW_ARROW
] = "\342\206\222", /* → */
3275 [DRAW_DASH
] = "\342\200\223", /* – */
3278 /* ASCII fallback */ {
3279 [DRAW_TREE_VERTICAL
] = "| ",
3280 [DRAW_TREE_BRANCH
] = "|-",
3281 [DRAW_TREE_RIGHT
] = "`-",
3282 [DRAW_TREE_SPACE
] = " ",
3283 [DRAW_TRIANGULAR_BULLET
] = ">",
3284 [DRAW_BLACK_CIRCLE
] = "*",
3285 [DRAW_ARROW
] = "->",
3290 return draw_table
[!is_locale_utf8()][ch
];
3293 int on_ac_power(void) {
3294 bool found_offline
= false, found_online
= false;
3295 _cleanup_closedir_
DIR *d
= NULL
;
3297 d
= opendir("/sys/class/power_supply");
3299 return errno
== ENOENT
? true : -errno
;
3303 _cleanup_close_
int fd
= -1, device
= -1;
3309 if (!de
&& errno
!= 0)
3315 if (hidden_file(de
->d_name
))
3318 device
= openat(dirfd(d
), de
->d_name
, O_DIRECTORY
|O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
3320 if (errno
== ENOENT
|| errno
== ENOTDIR
)
3326 fd
= openat(device
, "type", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
3328 if (errno
== ENOENT
)
3334 n
= read(fd
, contents
, sizeof(contents
));
3338 if (n
!= 6 || memcmp(contents
, "Mains\n", 6))
3342 fd
= openat(device
, "online", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
3344 if (errno
== ENOENT
)
3350 n
= read(fd
, contents
, sizeof(contents
));
3354 if (n
!= 2 || contents
[1] != '\n')
3357 if (contents
[0] == '1') {
3358 found_online
= true;
3360 } else if (contents
[0] == '0')
3361 found_offline
= true;
3366 return found_online
|| !found_offline
;
3369 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
3376 if (!path_strv_resolve_uniq(search
, root
))
3379 STRV_FOREACH(i
, search
) {
3380 _cleanup_free_
char *p
= NULL
;
3384 p
= strjoin(root
, *i
, "/", path
, NULL
);
3386 p
= strjoin(*i
, "/", path
, NULL
);
3396 if (errno
!= ENOENT
)
3403 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
3404 _cleanup_strv_free_
char **copy
= NULL
;
3410 if (path_is_absolute(path
)) {
3413 f
= fopen(path
, mode
);
3422 copy
= strv_copy((char**) search
);
3426 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
3429 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
3430 _cleanup_strv_free_
char **s
= NULL
;
3432 if (path_is_absolute(path
)) {
3435 f
= fopen(path
, mode
);
3444 s
= strv_split_nulstr(search
);
3448 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
3451 void* greedy_realloc(void **p
, size_t *allocated
, size_t need
, size_t size
) {
3458 if (*allocated
>= need
)
3461 newalloc
= MAX(need
* 2, 64u / size
);
3462 a
= newalloc
* size
;
3464 /* check for overflows */
3465 if (a
< size
* need
)
3473 *allocated
= newalloc
;
3477 void* greedy_realloc0(void **p
, size_t *allocated
, size_t need
, size_t size
) {
3486 q
= greedy_realloc(p
, allocated
, need
, size
);
3490 if (*allocated
> prev
)
3491 memzero(q
+ prev
* size
, (*allocated
- prev
) * size
);
3496 bool id128_is_valid(const char *s
) {
3502 /* Simple formatted 128bit hex string */
3504 for (i
= 0; i
< l
; i
++) {
3507 if (!(c
>= '0' && c
<= '9') &&
3508 !(c
>= 'a' && c
<= 'z') &&
3509 !(c
>= 'A' && c
<= 'Z'))
3513 } else if (l
== 36) {
3515 /* Formatted UUID */
3517 for (i
= 0; i
< l
; i
++) {
3520 if ((i
== 8 || i
== 13 || i
== 18 || i
== 23)) {
3524 if (!(c
>= '0' && c
<= '9') &&
3525 !(c
>= 'a' && c
<= 'z') &&
3526 !(c
>= 'A' && c
<= 'Z'))
3537 int shall_restore_state(void) {
3538 _cleanup_free_
char *value
= NULL
;
3541 r
= get_proc_cmdline_key("systemd.restore_state=", &value
);
3547 return parse_boolean(value
) != 0;
3550 int proc_cmdline(char **ret
) {
3553 if (detect_container() > 0)
3554 return get_process_cmdline(1, 0, false, ret
);
3556 return read_one_line_file("/proc/cmdline", ret
);
3559 int parse_proc_cmdline(int (*parse_item
)(const char *key
, const char *value
)) {
3560 _cleanup_free_
char *line
= NULL
;
3566 r
= proc_cmdline(&line
);
3572 _cleanup_free_
char *word
= NULL
;
3575 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
3581 /* Filter out arguments that are intended only for the
3583 if (!in_initrd() && startswith(word
, "rd."))
3586 value
= strchr(word
, '=');
3590 r
= parse_item(word
, value
);
3598 int get_proc_cmdline_key(const char *key
, char **value
) {
3599 _cleanup_free_
char *line
= NULL
, *ret
= NULL
;
3606 r
= proc_cmdline(&line
);
3612 _cleanup_free_
char *word
= NULL
;
3615 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
3621 /* Filter out arguments that are intended only for the
3623 if (!in_initrd() && startswith(word
, "rd."))
3627 e
= startswith(word
, key
);
3631 r
= free_and_strdup(&ret
, e
);
3637 if (streq(word
, key
))
3651 int container_get_leader(const char *machine
, pid_t
*pid
) {
3652 _cleanup_free_
char *s
= NULL
, *class = NULL
;
3660 if (!machine_name_is_valid(machine
))
3663 p
= strjoina("/run/systemd/machines/", machine
);
3664 r
= parse_env_file(p
, NEWLINE
, "LEADER", &s
, "CLASS", &class, NULL
);
3672 if (!streq_ptr(class, "container"))
3675 r
= parse_pid(s
, &leader
);
3685 int namespace_open(pid_t pid
, int *pidns_fd
, int *mntns_fd
, int *netns_fd
, int *userns_fd
, int *root_fd
) {
3686 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, netnsfd
= -1, usernsfd
= -1;
3694 mntns
= procfs_file_alloca(pid
, "ns/mnt");
3695 mntnsfd
= open(mntns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
3703 pidns
= procfs_file_alloca(pid
, "ns/pid");
3704 pidnsfd
= open(pidns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
3712 netns
= procfs_file_alloca(pid
, "ns/net");
3713 netnsfd
= open(netns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
3721 userns
= procfs_file_alloca(pid
, "ns/user");
3722 usernsfd
= open(userns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
3723 if (usernsfd
< 0 && errno
!= ENOENT
)
3730 root
= procfs_file_alloca(pid
, "root");
3731 rfd
= open(root
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
|O_DIRECTORY
);
3737 *pidns_fd
= pidnsfd
;
3740 *mntns_fd
= mntnsfd
;
3743 *netns_fd
= netnsfd
;
3746 *userns_fd
= usernsfd
;
3751 pidnsfd
= mntnsfd
= netnsfd
= usernsfd
= -1;
3756 int namespace_enter(int pidns_fd
, int mntns_fd
, int netns_fd
, int userns_fd
, int root_fd
) {
3757 if (userns_fd
>= 0) {
3758 /* Can't setns to your own userns, since then you could
3759 * escalate from non-root to root in your own namespace, so
3760 * check if namespaces equal before attempting to enter. */
3761 _cleanup_free_
char *userns_fd_path
= NULL
;
3763 if (asprintf(&userns_fd_path
, "/proc/self/fd/%d", userns_fd
) < 0)
3766 r
= files_same(userns_fd_path
, "/proc/self/ns/user");
3774 if (setns(pidns_fd
, CLONE_NEWPID
) < 0)
3778 if (setns(mntns_fd
, CLONE_NEWNS
) < 0)
3782 if (setns(netns_fd
, CLONE_NEWNET
) < 0)
3786 if (setns(userns_fd
, CLONE_NEWUSER
) < 0)
3790 if (fchdir(root_fd
) < 0)
3793 if (chroot(".") < 0)
3797 return reset_uid_gid();
3800 int getpeercred(int fd
, struct ucred
*ucred
) {
3801 socklen_t n
= sizeof(struct ucred
);
3808 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
);
3812 if (n
!= sizeof(struct ucred
))
3815 /* Check if the data is actually useful and not suppressed due
3816 * to namespacing issues */
3819 if (u
.uid
== UID_INVALID
)
3821 if (u
.gid
== GID_INVALID
)
3828 int getpeersec(int fd
, char **ret
) {
3840 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
3844 if (errno
!= ERANGE
)
3851 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
3867 /* This is much like like mkostemp() but is subject to umask(). */
3868 int mkostemp_safe(char *pattern
, int flags
) {
3869 _cleanup_umask_ mode_t u
;
3876 fd
= mkostemp(pattern
, flags
);
3883 int open_tmpfile(const char *path
, int flags
) {
3890 /* Try O_TMPFILE first, if it is supported */
3891 fd
= open(path
, flags
|O_TMPFILE
|O_EXCL
, S_IRUSR
|S_IWUSR
);
3896 /* Fall back to unguessable name + unlinking */
3897 p
= strjoina(path
, "/systemd-tmp-XXXXXX");
3899 fd
= mkostemp_safe(p
, flags
);
3907 int fd_warn_permissions(const char *path
, int fd
) {
3910 if (fstat(fd
, &st
) < 0)
3913 if (st
.st_mode
& 0111)
3914 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path
);
3916 if (st
.st_mode
& 0002)
3917 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path
);
3919 if (getpid() == 1 && (st
.st_mode
& 0044) != 0044)
3920 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
);
3925 unsigned long personality_from_string(const char *p
) {
3927 /* Parse a personality specifier. We introduce our own
3928 * identifiers that indicate specific ABIs, rather than just
3929 * hints regarding the register size, since we want to keep
3930 * things open for multiple locally supported ABIs for the
3931 * same register size. We try to reuse the ABI identifiers
3932 * used by libseccomp. */
3934 #if defined(__x86_64__)
3936 if (streq(p
, "x86"))
3939 if (streq(p
, "x86-64"))
3942 #elif defined(__i386__)
3944 if (streq(p
, "x86"))
3947 #elif defined(__s390x__)
3949 if (streq(p
, "s390"))
3952 if (streq(p
, "s390x"))
3955 #elif defined(__s390__)
3957 if (streq(p
, "s390"))
3961 return PERSONALITY_INVALID
;
3964 const char* personality_to_string(unsigned long p
) {
3966 #if defined(__x86_64__)
3968 if (p
== PER_LINUX32
)
3974 #elif defined(__i386__)
3979 #elif defined(__s390x__)
3984 if (p
== PER_LINUX32
)
3987 #elif defined(__s390__)
3997 uint64_t physical_memory(void) {
4000 /* We return this as uint64_t in case we are running as 32bit
4001 * process on a 64bit kernel with huge amounts of memory */
4003 mem
= sysconf(_SC_PHYS_PAGES
);
4006 return (uint64_t) mem
* (uint64_t) page_size();
4009 void hexdump(FILE *f
, const void *p
, size_t s
) {
4010 const uint8_t *b
= p
;
4013 assert(s
== 0 || b
);
4018 fprintf(f
, "%04x ", n
);
4020 for (i
= 0; i
< 16; i
++) {
4025 fprintf(f
, "%02x ", b
[i
]);
4033 for (i
= 0; i
< 16; i
++) {
4038 fputc(isprint(b
[i
]) ? (char) b
[i
] : '.', f
);
4052 int update_reboot_param_file(const char *param
) {
4056 r
= write_string_file(REBOOT_PARAM_FILE
, param
, WRITE_STRING_FILE_CREATE
);
4058 return log_error_errno(r
, "Failed to write reboot param to "REBOOT_PARAM_FILE
": %m");
4060 (void) unlink(REBOOT_PARAM_FILE
);
4065 int umount_recursive(const char *prefix
, int flags
) {
4069 /* Try to umount everything recursively below a
4070 * directory. Also, take care of stacked mounts, and keep
4071 * unmounting them until they are gone. */
4074 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
4079 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
4080 if (!proc_self_mountinfo
)
4084 _cleanup_free_
char *path
= NULL
, *p
= NULL
;
4087 k
= fscanf(proc_self_mountinfo
,
4088 "%*s " /* (1) mount id */
4089 "%*s " /* (2) parent id */
4090 "%*s " /* (3) major:minor */
4091 "%*s " /* (4) root */
4092 "%ms " /* (5) mount point */
4093 "%*s" /* (6) mount options */
4094 "%*[^-]" /* (7) optional fields */
4095 "- " /* (8) separator */
4096 "%*s " /* (9) file system type */
4097 "%*s" /* (10) mount source */
4098 "%*s" /* (11) mount options 2 */
4099 "%*[^\n]", /* some rubbish at the end */
4108 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
4112 if (!path_startswith(p
, prefix
))
4115 if (umount2(p
, flags
) < 0) {
4131 static int get_mount_flags(const char *path
, unsigned long *flags
) {
4134 if (statvfs(path
, &buf
) < 0)
4136 *flags
= buf
.f_flag
;
4140 int bind_remount_recursive(const char *prefix
, bool ro
) {
4141 _cleanup_set_free_free_ Set
*done
= NULL
;
4142 _cleanup_free_
char *cleaned
= NULL
;
4145 /* Recursively remount a directory (and all its submounts)
4146 * read-only or read-write. If the directory is already
4147 * mounted, we reuse the mount and simply mark it
4148 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
4149 * operation). If it isn't we first make it one. Afterwards we
4150 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
4151 * submounts we can access, too. When mounts are stacked on
4152 * the same mount point we only care for each individual
4153 * "top-level" mount on each point, as we cannot
4154 * influence/access the underlying mounts anyway. We do not
4155 * have any effect on future submounts that might get
4156 * propagated, they migt be writable. This includes future
4157 * submounts that have been triggered via autofs. */
4159 cleaned
= strdup(prefix
);
4163 path_kill_slashes(cleaned
);
4165 done
= set_new(&string_hash_ops
);
4170 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
4171 _cleanup_set_free_free_ Set
*todo
= NULL
;
4172 bool top_autofs
= false;
4174 unsigned long orig_flags
;
4176 todo
= set_new(&string_hash_ops
);
4180 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
4181 if (!proc_self_mountinfo
)
4185 _cleanup_free_
char *path
= NULL
, *p
= NULL
, *type
= NULL
;
4188 k
= fscanf(proc_self_mountinfo
,
4189 "%*s " /* (1) mount id */
4190 "%*s " /* (2) parent id */
4191 "%*s " /* (3) major:minor */
4192 "%*s " /* (4) root */
4193 "%ms " /* (5) mount point */
4194 "%*s" /* (6) mount options (superblock) */
4195 "%*[^-]" /* (7) optional fields */
4196 "- " /* (8) separator */
4197 "%ms " /* (9) file system type */
4198 "%*s" /* (10) mount source */
4199 "%*s" /* (11) mount options (bind mount) */
4200 "%*[^\n]", /* some rubbish at the end */
4210 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
4214 /* Let's ignore autofs mounts. If they aren't
4215 * triggered yet, we want to avoid triggering
4216 * them, as we don't make any guarantees for
4217 * future submounts anyway. If they are
4218 * already triggered, then we will find
4219 * another entry for this. */
4220 if (streq(type
, "autofs")) {
4221 top_autofs
= top_autofs
|| path_equal(cleaned
, p
);
4225 if (path_startswith(p
, cleaned
) &&
4226 !set_contains(done
, p
)) {
4228 r
= set_consume(todo
, p
);
4238 /* If we have no submounts to process anymore and if
4239 * the root is either already done, or an autofs, we
4241 if (set_isempty(todo
) &&
4242 (top_autofs
|| set_contains(done
, cleaned
)))
4245 if (!set_contains(done
, cleaned
) &&
4246 !set_contains(todo
, cleaned
)) {
4247 /* The prefix directory itself is not yet a
4248 * mount, make it one. */
4249 if (mount(cleaned
, cleaned
, NULL
, MS_BIND
|MS_REC
, NULL
) < 0)
4253 (void) get_mount_flags(cleaned
, &orig_flags
);
4254 orig_flags
&= ~MS_RDONLY
;
4256 if (mount(NULL
, prefix
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0)
4259 x
= strdup(cleaned
);
4263 r
= set_consume(done
, x
);
4268 while ((x
= set_steal_first(todo
))) {
4270 r
= set_consume(done
, x
);
4271 if (r
== -EEXIST
|| r
== 0)
4276 /* Try to reuse the original flag set, but
4277 * don't care for errors, in case of
4278 * obstructed mounts */
4280 (void) get_mount_flags(x
, &orig_flags
);
4281 orig_flags
&= ~MS_RDONLY
;
4283 if (mount(NULL
, x
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0) {
4285 /* Deal with mount points that are
4286 * obstructed by a later mount */
4288 if (errno
!= ENOENT
)
4296 int fflush_and_check(FILE *f
) {
4303 return errno
? -errno
: -EIO
;
4308 int tempfn_xxxxxx(const char *p
, const char *extra
, char **ret
) {
4320 * /foo/bar/.#<extra>waldoXXXXXX
4324 if (!filename_is_valid(fn
))
4330 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 6 + 1);
4334 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
), "XXXXXX");
4336 *ret
= path_kill_slashes(t
);
4340 int tempfn_random(const char *p
, const char *extra
, char **ret
) {
4354 * /foo/bar/.#<extra>waldobaa2a261115984a9
4358 if (!filename_is_valid(fn
))
4364 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 16 + 1);
4368 x
= stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
);
4371 for (i
= 0; i
< 16; i
++) {
4372 *(x
++) = hexchar(u
& 0xF);
4378 *ret
= path_kill_slashes(t
);
4382 int tempfn_random_child(const char *p
, const char *extra
, char **ret
) {
4393 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
4399 t
= new(char, strlen(p
) + 3 + strlen(extra
) + 16 + 1);
4403 x
= stpcpy(stpcpy(stpcpy(t
, p
), "/.#"), extra
);
4406 for (i
= 0; i
< 16; i
++) {
4407 *(x
++) = hexchar(u
& 0xF);
4413 *ret
= path_kill_slashes(t
);
4417 int take_password_lock(const char *root
) {
4419 struct flock flock
= {
4421 .l_whence
= SEEK_SET
,
4429 /* This is roughly the same as lckpwdf(), but not as awful. We
4430 * don't want to use alarm() and signals, hence we implement
4431 * our own trivial version of this.
4433 * Note that shadow-utils also takes per-database locks in
4434 * addition to lckpwdf(). However, we don't given that they
4435 * are redundant as they they invoke lckpwdf() first and keep
4436 * it during everything they do. The per-database locks are
4437 * awfully racy, and thus we just won't do them. */
4440 path
= strjoina(root
, "/etc/.pwd.lock");
4442 path
= "/etc/.pwd.lock";
4444 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
4448 r
= fcntl(fd
, F_SETLKW
, &flock
);
4457 int is_symlink(const char *path
) {
4460 if (lstat(path
, &info
) < 0)
4463 return !!S_ISLNK(info
.st_mode
);
4466 int is_dir(const char* path
, bool follow
) {
4471 r
= stat(path
, &st
);
4473 r
= lstat(path
, &st
);
4477 return !!S_ISDIR(st
.st_mode
);
4480 int is_device_node(const char *path
) {
4483 if (lstat(path
, &info
) < 0)
4486 return !!(S_ISBLK(info
.st_mode
) || S_ISCHR(info
.st_mode
));
4489 ssize_t
fgetxattrat_fake(int dirfd
, const char *filename
, const char *attribute
, void *value
, size_t size
, int flags
) {
4490 char fn
[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(int) + 1];
4491 _cleanup_close_
int fd
= -1;
4494 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
4496 fd
= openat(dirfd
, filename
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_PATH
|(flags
& AT_SYMLINK_NOFOLLOW
? O_NOFOLLOW
: 0));
4500 xsprintf(fn
, "/proc/self/fd/%i", fd
);
4502 l
= getxattr(fn
, attribute
, value
, size
);
4509 static int parse_crtime(le64_t le
, usec_t
*usec
) {
4515 if (u
== 0 || u
== (uint64_t) -1)
4522 int fd_getcrtime(int fd
, usec_t
*usec
) {
4529 /* Until Linux gets a real concept of birthtime/creation time,
4530 * let's fake one with xattrs */
4532 n
= fgetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
));
4535 if (n
!= sizeof(le
))
4538 return parse_crtime(le
, usec
);
4541 int fd_getcrtime_at(int dirfd
, const char *name
, usec_t
*usec
, int flags
) {
4545 n
= fgetxattrat_fake(dirfd
, name
, "user.crtime_usec", &le
, sizeof(le
), flags
);
4548 if (n
!= sizeof(le
))
4551 return parse_crtime(le
, usec
);
4554 int path_getcrtime(const char *p
, usec_t
*usec
) {
4561 n
= getxattr(p
, "user.crtime_usec", &le
, sizeof(le
));
4564 if (n
!= sizeof(le
))
4567 return parse_crtime(le
, usec
);
4570 int fd_setcrtime(int fd
, usec_t usec
) {
4576 usec
= now(CLOCK_REALTIME
);
4578 le
= htole64((uint64_t) usec
);
4579 if (fsetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
), 0) < 0)
4585 int chattr_fd(int fd
, unsigned value
, unsigned mask
) {
4586 unsigned old_attr
, new_attr
;
4591 if (fstat(fd
, &st
) < 0)
4594 /* Explicitly check whether this is a regular file or
4595 * directory. If it is anything else (such as a device node or
4596 * fifo), then the ioctl will not hit the file systems but
4597 * possibly drivers, where the ioctl might have different
4598 * effects. Notably, DRM is using the same ioctl() number. */
4600 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
4606 if (ioctl(fd
, FS_IOC_GETFLAGS
, &old_attr
) < 0)
4609 new_attr
= (old_attr
& ~mask
) | (value
& mask
);
4610 if (new_attr
== old_attr
)
4613 if (ioctl(fd
, FS_IOC_SETFLAGS
, &new_attr
) < 0)
4619 int chattr_path(const char *p
, unsigned value
, unsigned mask
) {
4620 _cleanup_close_
int fd
= -1;
4627 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
4631 return chattr_fd(fd
, value
, mask
);
4634 int read_attr_fd(int fd
, unsigned *ret
) {
4639 if (fstat(fd
, &st
) < 0)
4642 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
4645 if (ioctl(fd
, FS_IOC_GETFLAGS
, ret
) < 0)
4651 int read_attr_path(const char *p
, unsigned *ret
) {
4652 _cleanup_close_
int fd
= -1;
4657 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
4661 return read_attr_fd(fd
, ret
);
4664 static size_t nul_length(const uint8_t *p
, size_t sz
) {
4679 ssize_t
sparse_write(int fd
, const void *p
, size_t sz
, size_t run_length
) {
4680 const uint8_t *q
, *w
, *e
;
4688 n
= nul_length(q
, e
- q
);
4690 /* If there are more than the specified run length of
4691 * NUL bytes, or if this is the beginning or the end
4692 * of the buffer, then seek instead of write */
4693 if ((n
> run_length
) ||
4694 (n
> 0 && q
== p
) ||
4695 (n
> 0 && q
+ n
>= e
)) {
4697 l
= write(fd
, w
, q
- w
);
4704 if (lseek(fd
, n
, SEEK_CUR
) == (off_t
) -1)
4716 l
= write(fd
, w
, q
- w
);
4723 return q
- (const uint8_t*) p
;
4726 void sigkill_wait(pid_t
*pid
) {
4732 if (kill(*pid
, SIGKILL
) > 0)
4733 (void) wait_for_terminate(*pid
, NULL
);
4736 int syslog_parse_priority(const char **p
, int *priority
, bool with_facility
) {
4737 int a
= 0, b
= 0, c
= 0;
4747 if (!strchr(*p
, '>'))
4750 if ((*p
)[2] == '>') {
4751 c
= undecchar((*p
)[1]);
4753 } else if ((*p
)[3] == '>') {
4754 b
= undecchar((*p
)[1]);
4755 c
= undecchar((*p
)[2]);
4757 } else if ((*p
)[4] == '>') {
4758 a
= undecchar((*p
)[1]);
4759 b
= undecchar((*p
)[2]);
4760 c
= undecchar((*p
)[3]);
4765 if (a
< 0 || b
< 0 || c
< 0 ||
4766 (!with_facility
&& (a
|| b
|| c
> 7)))
4770 *priority
= a
*100 + b
*10 + c
;
4772 *priority
= (*priority
& LOG_FACMASK
) | c
;
4778 ssize_t
string_table_lookup(const char * const *table
, size_t len
, const char *key
) {
4784 for (i
= 0; i
< len
; ++i
)
4785 if (streq_ptr(table
[i
], key
))
4791 int rename_noreplace(int olddirfd
, const char *oldpath
, int newdirfd
, const char *newpath
) {
4795 ret
= renameat2(olddirfd
, oldpath
, newdirfd
, newpath
, RENAME_NOREPLACE
);
4799 /* renameat2() exists since Linux 3.15, btrfs added support for it later.
4800 * If it is not implemented, fallback to another method. */
4801 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
4804 /* The link()/unlink() fallback does not work on directories. But
4805 * renameat() without RENAME_NOREPLACE gives the same semantics on
4806 * directories, except when newpath is an *empty* directory. This is
4808 ret
= fstatat(olddirfd
, oldpath
, &buf
, AT_SYMLINK_NOFOLLOW
);
4809 if (ret
>= 0 && S_ISDIR(buf
.st_mode
)) {
4810 ret
= renameat(olddirfd
, oldpath
, newdirfd
, newpath
);
4811 return ret
>= 0 ? 0 : -errno
;
4814 /* If it is not a directory, use the link()/unlink() fallback. */
4815 ret
= linkat(olddirfd
, oldpath
, newdirfd
, newpath
, 0);
4819 ret
= unlinkat(olddirfd
, oldpath
, 0);
4821 /* backup errno before the following unlinkat() alters it */
4823 (void) unlinkat(newdirfd
, newpath
, 0);
4831 int parse_mode(const char *s
, mode_t
*ret
) {
4839 l
= strtol(s
, &x
, 8);
4843 if (!x
|| x
== s
|| *x
)
4845 if (l
< 0 || l
> 07777)
4852 int mount_move_root(const char *path
) {
4855 if (chdir(path
) < 0)
4858 if (mount(path
, "/", NULL
, MS_MOVE
, NULL
) < 0)
4861 if (chroot(".") < 0)
4870 int reset_uid_gid(void) {
4872 if (setgroups(0, NULL
) < 0)
4875 if (setresgid(0, 0, 0) < 0)
4878 if (setresuid(0, 0, 0) < 0)
4884 int getxattr_malloc(const char *path
, const char *name
, char **value
, bool allow_symlink
) {
4893 for (l
= 100; ; l
= (size_t) n
+ 1) {
4899 n
= lgetxattr(path
, name
, v
, l
);
4901 n
= getxattr(path
, name
, v
, l
);
4903 if (n
>= 0 && (size_t) n
< l
) {
4910 if (n
< 0 && errno
!= ERANGE
)
4914 n
= lgetxattr(path
, name
, NULL
, 0);
4916 n
= getxattr(path
, name
, NULL
, 0);
4922 int fgetxattr_malloc(int fd
, const char *name
, char **value
) {
4931 for (l
= 100; ; l
= (size_t) n
+ 1) {
4936 n
= fgetxattr(fd
, name
, v
, l
);
4938 if (n
>= 0 && (size_t) n
< l
) {
4945 if (n
< 0 && errno
!= ERANGE
)
4948 n
= fgetxattr(fd
, name
, NULL
, 0);
4954 int send_one_fd(int transport_fd
, int fd
, int flags
) {
4956 struct cmsghdr cmsghdr
;
4957 uint8_t buf
[CMSG_SPACE(sizeof(int))];
4959 struct msghdr mh
= {
4960 .msg_control
= &control
,
4961 .msg_controllen
= sizeof(control
),
4963 struct cmsghdr
*cmsg
;
4965 assert(transport_fd
>= 0);
4968 cmsg
= CMSG_FIRSTHDR(&mh
);
4969 cmsg
->cmsg_level
= SOL_SOCKET
;
4970 cmsg
->cmsg_type
= SCM_RIGHTS
;
4971 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
4972 memcpy(CMSG_DATA(cmsg
), &fd
, sizeof(int));
4974 mh
.msg_controllen
= CMSG_SPACE(sizeof(int));
4975 if (sendmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| flags
) < 0)
4981 int receive_one_fd(int transport_fd
, int flags
) {
4983 struct cmsghdr cmsghdr
;
4984 uint8_t buf
[CMSG_SPACE(sizeof(int))];
4986 struct msghdr mh
= {
4987 .msg_control
= &control
,
4988 .msg_controllen
= sizeof(control
),
4990 struct cmsghdr
*cmsg
, *found
= NULL
;
4992 assert(transport_fd
>= 0);
4995 * Receive a single FD via @transport_fd. We don't care for
4996 * the transport-type. We retrieve a single FD at most, so for
4997 * packet-based transports, the caller must ensure to send
4998 * only a single FD per packet. This is best used in
4999 * combination with send_one_fd().
5002 if (recvmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| MSG_CMSG_CLOEXEC
| flags
) < 0)
5005 CMSG_FOREACH(cmsg
, &mh
) {
5006 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
5007 cmsg
->cmsg_type
== SCM_RIGHTS
&&
5008 cmsg
->cmsg_len
== CMSG_LEN(sizeof(int))) {
5016 cmsg_close_all(&mh
);
5020 return *(int*) CMSG_DATA(found
);
5023 void nop_signal_handler(int sig
) {
5028 puts(PACKAGE_STRING
"\n"
5033 bool fdname_is_valid(const char *s
) {
5036 /* Validates a name for $LISTEN_FDNAMES. We basically allow
5037 * everything ASCII that's not a control character. Also, as
5038 * special exception the ":" character is not allowed, as we
5039 * use that as field separator in $LISTEN_FDNAMES.
5041 * Note that the empty string is explicitly allowed
5042 * here. However, we limit the length of the names to 255
5048 for (p
= s
; *p
; p
++) {
5060 bool oom_score_adjust_is_valid(int oa
) {
5061 return oa
>= OOM_SCORE_ADJ_MIN
&& oa
<= OOM_SCORE_ADJ_MAX
;