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"
83 #include "formats-util.h"
86 #include "hostname-util.h"
92 #include "path-util.h"
93 #include "process-util.h"
94 #include "random-util.h"
95 #include "signal-util.h"
96 #include "sparse-endian.h"
97 #include "string-util.h"
99 #include "terminal-util.h"
104 /* Put this test here for a lack of better place */
105 assert_cc(EAGAIN
== EWOULDBLOCK
);
108 char **saved_argv
= NULL
;
110 size_t page_size(void) {
111 static thread_local
size_t pgsz
= 0;
114 if (_likely_(pgsz
> 0))
117 r
= sysconf(_SC_PAGESIZE
);
124 int close_nointr(int fd
) {
131 * Just ignore EINTR; a retry loop is the wrong thing to do on
134 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
135 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
136 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
137 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
145 int safe_close(int fd
) {
148 * Like close_nointr() but cannot fail. Guarantees errno is
149 * unchanged. Is a NOP with negative fds passed, and returns
150 * -1, so that it can be used in this syntax:
152 * fd = safe_close(fd);
158 /* The kernel might return pretty much any error code
159 * via close(), but the fd will be closed anyway. The
160 * only condition we want to check for here is whether
161 * the fd was invalid at all... */
163 assert_se(close_nointr(fd
) != -EBADF
);
169 void close_many(const int fds
[], unsigned n_fd
) {
172 assert(fds
|| n_fd
<= 0);
174 for (i
= 0; i
< n_fd
; i
++)
178 int fclose_nointr(FILE *f
) {
181 /* Same as close_nointr(), but for fclose() */
192 FILE* safe_fclose(FILE *f
) {
194 /* Same as safe_close(), but for fclose() */
199 assert_se(fclose_nointr(f
) != EBADF
);
205 DIR* safe_closedir(DIR *d
) {
210 assert_se(closedir(d
) >= 0 || errno
!= EBADF
);
216 int unlink_noerrno(const char *path
) {
227 int parse_boolean(const char *v
) {
230 if (streq(v
, "1") || strcaseeq(v
, "yes") || strcaseeq(v
, "y") || strcaseeq(v
, "true") || strcaseeq(v
, "t") || strcaseeq(v
, "on"))
232 else if (streq(v
, "0") || strcaseeq(v
, "no") || strcaseeq(v
, "n") || strcaseeq(v
, "false") || strcaseeq(v
, "f") || strcaseeq(v
, "off"))
238 int parse_pid(const char *s
, pid_t
* ret_pid
) {
239 unsigned long ul
= 0;
246 r
= safe_atolu(s
, &ul
);
252 if ((unsigned long) pid
!= ul
)
262 bool uid_is_valid(uid_t uid
) {
264 /* Some libc APIs use UID_INVALID as special placeholder */
265 if (uid
== (uid_t
) 0xFFFFFFFF)
268 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
269 if (uid
== (uid_t
) 0xFFFF)
275 int parse_uid(const char *s
, uid_t
* ret_uid
) {
276 unsigned long ul
= 0;
282 r
= safe_atolu(s
, &ul
);
288 if ((unsigned long) uid
!= ul
)
291 if (!uid_is_valid(uid
))
292 return -ENXIO
; /* we return ENXIO instead of EINVAL
293 * here, to make it easy to distuingish
294 * invalid numeric uids invalid
303 int safe_atou(const char *s
, unsigned *ret_u
) {
311 l
= strtoul(s
, &x
, 0);
313 if (!x
|| x
== s
|| *x
|| errno
)
314 return errno
> 0 ? -errno
: -EINVAL
;
316 if ((unsigned long) (unsigned) l
!= l
)
319 *ret_u
= (unsigned) l
;
323 int safe_atoi(const char *s
, int *ret_i
) {
331 l
= strtol(s
, &x
, 0);
333 if (!x
|| x
== s
|| *x
|| errno
)
334 return errno
> 0 ? -errno
: -EINVAL
;
336 if ((long) (int) l
!= l
)
343 int safe_atou8(const char *s
, uint8_t *ret
) {
351 l
= strtoul(s
, &x
, 0);
353 if (!x
|| x
== s
|| *x
|| errno
)
354 return errno
> 0 ? -errno
: -EINVAL
;
356 if ((unsigned long) (uint8_t) l
!= l
)
363 int safe_atou16(const char *s
, uint16_t *ret
) {
371 l
= strtoul(s
, &x
, 0);
373 if (!x
|| x
== s
|| *x
|| errno
)
374 return errno
> 0 ? -errno
: -EINVAL
;
376 if ((unsigned long) (uint16_t) l
!= l
)
383 int safe_atoi16(const char *s
, int16_t *ret
) {
391 l
= strtol(s
, &x
, 0);
393 if (!x
|| x
== s
|| *x
|| errno
)
394 return errno
> 0 ? -errno
: -EINVAL
;
396 if ((long) (int16_t) l
!= l
)
403 int safe_atollu(const char *s
, long long unsigned *ret_llu
) {
405 unsigned long long l
;
411 l
= strtoull(s
, &x
, 0);
413 if (!x
|| x
== s
|| *x
|| errno
)
414 return errno
? -errno
: -EINVAL
;
420 int safe_atolli(const char *s
, long long int *ret_lli
) {
428 l
= strtoll(s
, &x
, 0);
430 if (!x
|| x
== s
|| *x
|| errno
)
431 return errno
? -errno
: -EINVAL
;
437 int safe_atod(const char *s
, double *ret_d
) {
445 loc
= newlocale(LC_NUMERIC_MASK
, "C", (locale_t
) 0);
446 if (loc
== (locale_t
) 0)
450 d
= strtod_l(s
, &x
, loc
);
452 if (!x
|| x
== s
|| *x
|| errno
) {
454 return errno
? -errno
: -EINVAL
;
463 int fchmod_umask(int fd
, mode_t m
) {
468 r
= fchmod(fd
, m
& (~u
)) < 0 ? -errno
: 0;
474 int readlinkat_malloc(int fd
, const char *p
, char **ret
) {
489 n
= readlinkat(fd
, p
, c
, l
-1);
496 if ((size_t) n
< l
-1) {
507 int readlink_malloc(const char *p
, char **ret
) {
508 return readlinkat_malloc(AT_FDCWD
, p
, ret
);
511 int readlink_value(const char *p
, char **ret
) {
512 _cleanup_free_
char *link
= NULL
;
516 r
= readlink_malloc(p
, &link
);
520 value
= basename(link
);
524 value
= strdup(value
);
533 int readlink_and_make_absolute(const char *p
, char **r
) {
534 _cleanup_free_
char *target
= NULL
;
541 j
= readlink_malloc(p
, &target
);
545 k
= file_in_same_dir(p
, target
);
553 int readlink_and_canonicalize(const char *p
, char **r
) {
560 j
= readlink_and_make_absolute(p
, &t
);
564 s
= canonicalize_file_name(t
);
571 path_kill_slashes(*r
);
576 char *file_in_same_dir(const char *path
, const char *filename
) {
583 /* This removes the last component of path and appends
584 * filename, unless the latter is absolute anyway or the
587 if (path_is_absolute(filename
))
588 return strdup(filename
);
590 e
= strrchr(path
, '/');
592 return strdup(filename
);
594 k
= strlen(filename
);
595 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
599 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
603 int rmdir_parents(const char *path
, const char *stop
) {
612 /* Skip trailing slashes */
613 while (l
> 0 && path
[l
-1] == '/')
619 /* Skip last component */
620 while (l
> 0 && path
[l
-1] != '/')
623 /* Skip trailing slashes */
624 while (l
> 0 && path
[l
-1] == '/')
630 if (!(t
= strndup(path
, l
)))
633 if (path_startswith(stop
, t
)) {
649 char hexchar(int x
) {
650 static const char table
[16] = "0123456789abcdef";
652 return table
[x
& 15];
655 int unhexchar(char c
) {
657 if (c
>= '0' && c
<= '9')
660 if (c
>= 'a' && c
<= 'f')
663 if (c
>= 'A' && c
<= 'F')
669 char *hexmem(const void *p
, size_t l
) {
673 z
= r
= malloc(l
* 2 + 1);
677 for (x
= p
; x
< (const uint8_t*) p
+ l
; x
++) {
678 *(z
++) = hexchar(*x
>> 4);
679 *(z
++) = hexchar(*x
& 15);
686 int unhexmem(const char *p
, size_t l
, void **mem
, size_t *len
) {
687 _cleanup_free_
uint8_t *r
= NULL
;
695 z
= r
= malloc((l
+ 1) / 2 + 1);
699 for (x
= p
; x
< p
+ l
; x
+= 2) {
705 else if (x
+1 < p
+ l
) {
712 *(z
++) = (uint8_t) a
<< 4 | (uint8_t) b
;
724 /* https://tools.ietf.org/html/rfc4648#section-6
725 * Notice that base32hex differs from base32 in the alphabet it uses.
726 * The distinction is that the base32hex representation preserves the
727 * order of the underlying data when compared as bytestrings, this is
728 * useful when representing NSEC3 hashes, as one can then verify the
729 * order of hashes directly from their representation. */
730 char base32hexchar(int x
) {
731 static const char table
[32] = "0123456789"
732 "ABCDEFGHIJKLMNOPQRSTUV";
734 return table
[x
& 31];
737 int unbase32hexchar(char c
) {
740 if (c
>= '0' && c
<= '9')
743 offset
= '9' - '0' + 1;
745 if (c
>= 'A' && c
<= 'V')
746 return c
- 'A' + offset
;
751 char *base32hexmem(const void *p
, size_t l
, bool padding
) {
757 /* five input bytes makes eight output bytes, padding is added so we must round up */
758 len
= 8 * (l
+ 4) / 5;
760 /* same, but round down as there is no padding */
779 z
= r
= malloc(len
+ 1);
783 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 5) * 5; x
+= 5) {
784 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ
785 x[3] == QQQQQQQQ; x[4] == WWWWWWWW */
786 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
787 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
788 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
789 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
790 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
791 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
792 *(z
++) = base32hexchar((x
[3] & 3) << 3 | x
[4] >> 5); /* 000QQWWW */
793 *(z
++) = base32hexchar((x
[4] & 31)); /* 000WWWWW */
798 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
799 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
800 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
801 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
802 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
803 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
804 *(z
++) = base32hexchar((x
[3] & 3) << 3); /* 000QQ000 */
811 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
812 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
813 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
814 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
815 *(z
++) = base32hexchar((x
[2] & 15) << 1); /* 000ZZZZ0 */
825 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
826 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
827 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
828 *(z
++) = base32hexchar((x
[1] & 1) << 4); /* 000Y0000 */
839 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
840 *(z
++) = base32hexchar((x
[0] & 7) << 2); /* 000XXX00 */
857 int unbase32hexmem(const char *p
, size_t l
, bool padding
, void **mem
, size_t *_len
) {
858 _cleanup_free_
uint8_t *r
= NULL
;
859 int a
, b
, c
, d
, e
, f
, g
, h
;
867 /* padding ensures any base32hex input has input divisible by 8 */
868 if (padding
&& l
% 8 != 0)
872 /* strip the padding */
873 while (l
> 0 && p
[l
- 1] == '=' && pad
< 7) {
879 /* a group of eight input bytes needs five output bytes, in case of
880 padding we need to add some extra bytes */
902 z
= r
= malloc(len
+ 1);
906 for (x
= p
; x
< p
+ (l
/ 8) * 8; x
+= 8) {
907 /* a == 000XXXXX; b == 000YYYYY; c == 000ZZZZZ; d == 000WWWWW
908 e == 000SSSSS; f == 000QQQQQ; g == 000VVVVV; h == 000RRRRR */
909 a
= unbase32hexchar(x
[0]);
913 b
= unbase32hexchar(x
[1]);
917 c
= unbase32hexchar(x
[2]);
921 d
= unbase32hexchar(x
[3]);
925 e
= unbase32hexchar(x
[4]);
929 f
= unbase32hexchar(x
[5]);
933 g
= unbase32hexchar(x
[6]);
937 h
= unbase32hexchar(x
[7]);
941 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
942 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
943 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
944 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
945 *(z
++) = (uint8_t) g
<< 5 | (uint8_t) h
; /* VVVRRRRR */
950 a
= unbase32hexchar(x
[0]);
954 b
= unbase32hexchar(x
[1]);
958 c
= unbase32hexchar(x
[2]);
962 d
= unbase32hexchar(x
[3]);
966 e
= unbase32hexchar(x
[4]);
970 f
= unbase32hexchar(x
[5]);
974 g
= unbase32hexchar(x
[6]);
982 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
983 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
984 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
985 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
989 a
= unbase32hexchar(x
[0]);
993 b
= unbase32hexchar(x
[1]);
997 c
= unbase32hexchar(x
[2]);
1001 d
= unbase32hexchar(x
[3]);
1005 e
= unbase32hexchar(x
[4]);
1013 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1014 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1015 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1019 a
= unbase32hexchar(x
[0]);
1023 b
= unbase32hexchar(x
[1]);
1027 c
= unbase32hexchar(x
[2]);
1031 d
= unbase32hexchar(x
[3]);
1039 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1040 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1044 a
= unbase32hexchar(x
[0]);
1048 b
= unbase32hexchar(x
[1]);
1056 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1074 /* https://tools.ietf.org/html/rfc4648#section-4 */
1075 char base64char(int x
) {
1076 static const char table
[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1077 "abcdefghijklmnopqrstuvwxyz"
1079 return table
[x
& 63];
1082 int unbase64char(char c
) {
1085 if (c
>= 'A' && c
<= 'Z')
1088 offset
= 'Z' - 'A' + 1;
1090 if (c
>= 'a' && c
<= 'z')
1091 return c
- 'a' + offset
;
1093 offset
+= 'z' - 'a' + 1;
1095 if (c
>= '0' && c
<= '9')
1096 return c
- '0' + offset
;
1098 offset
+= '9' - '0' + 1;
1111 char *base64mem(const void *p
, size_t l
) {
1115 /* three input bytes makes four output bytes, padding is added so we must round up */
1116 z
= r
= malloc(4 * (l
+ 2) / 3 + 1);
1120 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 3) * 3; x
+= 3) {
1121 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ */
1122 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1123 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1124 *(z
++) = base64char((x
[1] & 15) << 2 | x
[2] >> 6); /* 00YYYYZZ */
1125 *(z
++) = base64char(x
[2] & 63); /* 00ZZZZZZ */
1130 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1131 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1132 *(z
++) = base64char((x
[1] & 15) << 2); /* 00YYYY00 */
1137 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1138 *(z
++) = base64char((x
[0] & 3) << 4); /* 00XX0000 */
1149 int unbase64mem(const char *p
, size_t l
, void **mem
, size_t *_len
) {
1150 _cleanup_free_
uint8_t *r
= NULL
;
1158 /* padding ensures any base63 input has input divisible by 4 */
1162 /* strip the padding */
1163 if (l
> 0 && p
[l
- 1] == '=')
1165 if (l
> 0 && p
[l
- 1] == '=')
1168 /* a group of four input bytes needs three output bytes, in case of
1169 padding we need to add two or three extra bytes */
1170 len
= (l
/ 4) * 3 + (l
% 4 ? (l
% 4) - 1 : 0);
1172 z
= r
= malloc(len
+ 1);
1176 for (x
= p
; x
< p
+ (l
/ 4) * 4; x
+= 4) {
1177 /* a == 00XXXXXX; b == 00YYYYYY; c == 00ZZZZZZ; d == 00WWWWWW */
1178 a
= unbase64char(x
[0]);
1182 b
= unbase64char(x
[1]);
1186 c
= unbase64char(x
[2]);
1190 d
= unbase64char(x
[3]);
1194 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1195 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1196 *(z
++) = (uint8_t) c
<< 6 | (uint8_t) d
; /* ZZWWWWWW */
1201 a
= unbase64char(x
[0]);
1205 b
= unbase64char(x
[1]);
1209 c
= unbase64char(x
[2]);
1217 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1218 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1222 a
= unbase64char(x
[0]);
1226 b
= unbase64char(x
[1]);
1234 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) (b
>> 4); /* XXXXXXYY */
1253 char octchar(int x
) {
1254 return '0' + (x
& 7);
1257 int unoctchar(char c
) {
1259 if (c
>= '0' && c
<= '7')
1265 char decchar(int x
) {
1266 return '0' + (x
% 10);
1269 int undecchar(char c
) {
1271 if (c
>= '0' && c
<= '9')
1277 _pure_
static bool hidden_file_allow_backup(const char *filename
) {
1281 filename
[0] == '.' ||
1282 streq(filename
, "lost+found") ||
1283 streq(filename
, "aquota.user") ||
1284 streq(filename
, "aquota.group") ||
1285 endswith(filename
, ".rpmnew") ||
1286 endswith(filename
, ".rpmsave") ||
1287 endswith(filename
, ".rpmorig") ||
1288 endswith(filename
, ".dpkg-old") ||
1289 endswith(filename
, ".dpkg-new") ||
1290 endswith(filename
, ".dpkg-tmp") ||
1291 endswith(filename
, ".dpkg-dist") ||
1292 endswith(filename
, ".dpkg-bak") ||
1293 endswith(filename
, ".dpkg-backup") ||
1294 endswith(filename
, ".dpkg-remove") ||
1295 endswith(filename
, ".swp");
1298 bool hidden_file(const char *filename
) {
1301 if (endswith(filename
, "~"))
1304 return hidden_file_allow_backup(filename
);
1307 int fd_nonblock(int fd
, bool nonblock
) {
1312 flags
= fcntl(fd
, F_GETFL
, 0);
1317 nflags
= flags
| O_NONBLOCK
;
1319 nflags
= flags
& ~O_NONBLOCK
;
1321 if (nflags
== flags
)
1324 if (fcntl(fd
, F_SETFL
, nflags
) < 0)
1330 int fd_cloexec(int fd
, bool cloexec
) {
1335 flags
= fcntl(fd
, F_GETFD
, 0);
1340 nflags
= flags
| FD_CLOEXEC
;
1342 nflags
= flags
& ~FD_CLOEXEC
;
1344 if (nflags
== flags
)
1347 if (fcntl(fd
, F_SETFD
, nflags
) < 0)
1353 _pure_
static bool fd_in_set(int fd
, const int fdset
[], unsigned n_fdset
) {
1356 assert(n_fdset
== 0 || fdset
);
1358 for (i
= 0; i
< n_fdset
; i
++)
1365 int close_all_fds(const int except
[], unsigned n_except
) {
1366 _cleanup_closedir_
DIR *d
= NULL
;
1370 assert(n_except
== 0 || except
);
1372 d
= opendir("/proc/self/fd");
1377 /* When /proc isn't available (for example in chroots)
1378 * the fallback is brute forcing through the fd
1381 assert_se(getrlimit(RLIMIT_NOFILE
, &rl
) >= 0);
1382 for (fd
= 3; fd
< (int) rl
.rlim_max
; fd
++) {
1384 if (fd_in_set(fd
, except
, n_except
))
1387 if (close_nointr(fd
) < 0)
1388 if (errno
!= EBADF
&& r
== 0)
1395 while ((de
= readdir(d
))) {
1398 if (hidden_file(de
->d_name
))
1401 if (safe_atoi(de
->d_name
, &fd
) < 0)
1402 /* Let's better ignore this, just in case */
1411 if (fd_in_set(fd
, except
, n_except
))
1414 if (close_nointr(fd
) < 0) {
1415 /* Valgrind has its own FD and doesn't want to have it closed */
1416 if (errno
!= EBADF
&& r
== 0)
1424 bool fstype_is_network(const char *fstype
) {
1425 static const char table
[] =
1440 x
= startswith(fstype
, "fuse.");
1444 return nulstr_contains(table
, fstype
);
1447 int flush_fd(int fd
) {
1448 struct pollfd pollfd
= {
1458 r
= poll(&pollfd
, 1, 0);
1468 l
= read(fd
, buf
, sizeof(buf
));
1474 if (errno
== EAGAIN
)
1483 void safe_close_pair(int p
[]) {
1487 /* Special case pairs which use the same fd in both
1489 p
[0] = p
[1] = safe_close(p
[0]);
1493 p
[0] = safe_close(p
[0]);
1494 p
[1] = safe_close(p
[1]);
1497 ssize_t
loop_read(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
1504 /* If called with nbytes == 0, let's call read() at least
1505 * once, to validate the operation */
1507 if (nbytes
> (size_t) SSIZE_MAX
)
1513 k
= read(fd
, p
, nbytes
);
1518 if (errno
== EAGAIN
&& do_poll
) {
1520 /* We knowingly ignore any return value here,
1521 * and expect that any error/EOF is reported
1524 (void) fd_wait_for_event(fd
, POLLIN
, USEC_INFINITY
);
1528 return n
> 0 ? n
: -errno
;
1534 assert((size_t) k
<= nbytes
);
1539 } while (nbytes
> 0);
1544 int loop_read_exact(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
1547 n
= loop_read(fd
, buf
, nbytes
, do_poll
);
1550 if ((size_t) n
!= nbytes
)
1556 int loop_write(int fd
, const void *buf
, size_t nbytes
, bool do_poll
) {
1557 const uint8_t *p
= buf
;
1562 if (nbytes
> (size_t) SSIZE_MAX
)
1568 k
= write(fd
, p
, nbytes
);
1573 if (errno
== EAGAIN
&& do_poll
) {
1574 /* We knowingly ignore any return value here,
1575 * and expect that any error/EOF is reported
1578 (void) fd_wait_for_event(fd
, POLLOUT
, USEC_INFINITY
);
1585 if (_unlikely_(nbytes
> 0 && k
== 0)) /* Can't really happen */
1588 assert((size_t) k
<= nbytes
);
1592 } while (nbytes
> 0);
1597 int parse_size(const char *t
, uint64_t base
, uint64_t *size
) {
1599 /* Soo, sometimes we want to parse IEC binary suffixes, and
1600 * sometimes SI decimal suffixes. This function can parse
1601 * both. Which one is the right way depends on the
1602 * context. Wikipedia suggests that SI is customary for
1603 * hardware metrics and network speeds, while IEC is
1604 * customary for most data sizes used by software and volatile
1605 * (RAM) memory. Hence be careful which one you pick!
1607 * In either case we use just K, M, G as suffix, and not Ki,
1608 * Mi, Gi or so (as IEC would suggest). That's because that's
1609 * frickin' ugly. But this means you really need to make sure
1610 * to document which base you are parsing when you use this
1615 unsigned long long factor
;
1618 static const struct table iec
[] = {
1619 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1620 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1621 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
1622 { "G", 1024ULL*1024ULL*1024ULL },
1623 { "M", 1024ULL*1024ULL },
1629 static const struct table si
[] = {
1630 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1631 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1632 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
1633 { "G", 1000ULL*1000ULL*1000ULL },
1634 { "M", 1000ULL*1000ULL },
1640 const struct table
*table
;
1642 unsigned long long r
= 0;
1643 unsigned n_entries
, start_pos
= 0;
1646 assert(base
== 1000 || base
== 1024);
1651 n_entries
= ELEMENTSOF(si
);
1654 n_entries
= ELEMENTSOF(iec
);
1659 unsigned long long l
, tmp
;
1664 p
+= strspn(p
, WHITESPACE
);
1669 l
= strtoull(p
, &e
, 10);
1678 /* strtoull() itself would accept space/+/- */
1679 if (*e
>= '0' && *e
<= '9') {
1680 unsigned long long l2
;
1683 l2
= strtoull(e
, &e2
, 10);
1687 /* Ignore failure. E.g. 10.M is valid */
1694 e
+= strspn(e
, WHITESPACE
);
1696 for (i
= start_pos
; i
< n_entries
; i
++)
1697 if (startswith(e
, table
[i
].suffix
))
1703 if (l
+ (frac
> 0) > ULLONG_MAX
/ table
[i
].factor
)
1706 tmp
= l
* table
[i
].factor
+ (unsigned long long) (frac
* table
[i
].factor
);
1707 if (tmp
> ULLONG_MAX
- r
)
1711 if ((unsigned long long) (uint64_t) r
!= r
)
1714 p
= e
+ strlen(table
[i
].suffix
);
1725 bool is_device_path(const char *path
) {
1727 /* Returns true on paths that refer to a device, either in
1728 * sysfs or in /dev */
1731 path_startswith(path
, "/dev/") ||
1732 path_startswith(path
, "/sys/");
1735 int dir_is_empty(const char *path
) {
1736 _cleanup_closedir_
DIR *d
;
1743 FOREACH_DIRENT(de
, d
, return -errno
)
1749 char* dirname_malloc(const char *path
) {
1750 char *d
, *dir
, *dir2
;
1767 void rename_process(const char name
[8]) {
1770 /* This is a like a poor man's setproctitle(). It changes the
1771 * comm field, argv[0], and also the glibc's internally used
1772 * name of the process. For the first one a limit of 16 chars
1773 * applies, to the second one usually one of 10 (i.e. length
1774 * of "/sbin/init"), to the third one one of 7 (i.e. length of
1775 * "systemd"). If you pass a longer string it will be
1778 prctl(PR_SET_NAME
, name
);
1780 if (program_invocation_name
)
1781 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
1783 if (saved_argc
> 0) {
1787 strncpy(saved_argv
[0], name
, strlen(saved_argv
[0]));
1789 for (i
= 1; i
< saved_argc
; i
++) {
1793 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
1798 char *lookup_uid(uid_t uid
) {
1801 _cleanup_free_
char *buf
= NULL
;
1802 struct passwd pwbuf
, *pw
= NULL
;
1804 /* Shortcut things to avoid NSS lookups */
1806 return strdup("root");
1808 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1812 buf
= malloc(bufsize
);
1816 if (getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
) == 0 && pw
)
1817 return strdup(pw
->pw_name
);
1819 if (asprintf(&name
, UID_FMT
, uid
) < 0)
1825 char* getlogname_malloc(void) {
1829 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
1834 return lookup_uid(uid
);
1837 char *getusername_malloc(void) {
1844 return lookup_uid(getuid());
1847 bool is_fs_type(const struct statfs
*s
, statfs_f_type_t magic_value
) {
1849 assert_cc(sizeof(statfs_f_type_t
) >= sizeof(s
->f_type
));
1851 return F_TYPE_EQUAL(s
->f_type
, magic_value
);
1854 int fd_check_fstype(int fd
, statfs_f_type_t magic_value
) {
1857 if (fstatfs(fd
, &s
) < 0)
1860 return is_fs_type(&s
, magic_value
);
1863 int path_check_fstype(const char *path
, statfs_f_type_t magic_value
) {
1864 _cleanup_close_
int fd
= -1;
1866 fd
= open(path
, O_RDONLY
);
1870 return fd_check_fstype(fd
, magic_value
);
1873 bool is_temporary_fs(const struct statfs
*s
) {
1874 return is_fs_type(s
, TMPFS_MAGIC
) ||
1875 is_fs_type(s
, RAMFS_MAGIC
);
1878 int fd_is_temporary_fs(int fd
) {
1881 if (fstatfs(fd
, &s
) < 0)
1884 return is_temporary_fs(&s
);
1887 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
1890 /* Under the assumption that we are running privileged we
1891 * first change the access mode and only then hand out
1892 * ownership to avoid a window where access is too open. */
1894 if (mode
!= MODE_INVALID
)
1895 if (chmod(path
, mode
) < 0)
1898 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
1899 if (chown(path
, uid
, gid
) < 0)
1905 int fchmod_and_fchown(int fd
, mode_t mode
, uid_t uid
, gid_t gid
) {
1908 /* Under the assumption that we are running privileged we
1909 * first change the access mode and only then hand out
1910 * ownership to avoid a window where access is too open. */
1912 if (mode
!= MODE_INVALID
)
1913 if (fchmod(fd
, mode
) < 0)
1916 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
1917 if (fchown(fd
, uid
, gid
) < 0)
1923 int files_same(const char *filea
, const char *fileb
) {
1926 if (stat(filea
, &a
) < 0)
1929 if (stat(fileb
, &b
) < 0)
1932 return a
.st_dev
== b
.st_dev
&&
1933 a
.st_ino
== b
.st_ino
;
1936 int running_in_chroot(void) {
1939 ret
= files_same("/proc/1/root", "/");
1946 int touch_file(const char *path
, bool parents
, usec_t stamp
, uid_t uid
, gid_t gid
, mode_t mode
) {
1947 _cleanup_close_
int fd
;
1953 mkdir_parents(path
, 0755);
1955 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, mode
> 0 ? mode
: 0644);
1960 r
= fchmod(fd
, mode
);
1965 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
) {
1966 r
= fchown(fd
, uid
, gid
);
1971 if (stamp
!= USEC_INFINITY
) {
1972 struct timespec ts
[2];
1974 timespec_store(&ts
[0], stamp
);
1976 r
= futimens(fd
, ts
);
1978 r
= futimens(fd
, NULL
);
1985 int touch(const char *path
) {
1986 return touch_file(path
, false, USEC_INFINITY
, UID_INVALID
, GID_INVALID
, 0);
1989 static char *unquote(const char *s
, const char* quotes
) {
1993 /* This is rather stupid, simply removes the heading and
1994 * trailing quotes if there is one. Doesn't care about
1995 * escaping or anything.
1997 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2003 if (strchr(quotes
, s
[0]) && s
[l
-1] == s
[0])
2004 return strndup(s
+1, l
-2);
2009 noreturn
void freeze(void) {
2011 /* Make sure nobody waits for us on a socket anymore */
2012 close_all_fds(NULL
, 0);
2020 bool null_or_empty(struct stat
*st
) {
2023 if (S_ISREG(st
->st_mode
) && st
->st_size
<= 0)
2026 if (S_ISCHR(st
->st_mode
) || S_ISBLK(st
->st_mode
))
2032 int null_or_empty_path(const char *fn
) {
2037 if (stat(fn
, &st
) < 0)
2040 return null_or_empty(&st
);
2043 int null_or_empty_fd(int fd
) {
2048 if (fstat(fd
, &st
) < 0)
2051 return null_or_empty(&st
);
2054 DIR *xopendirat(int fd
, const char *name
, int flags
) {
2058 assert(!(flags
& O_CREAT
));
2060 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
2073 static char *tag_to_udev_node(const char *tagvalue
, const char *by
) {
2074 _cleanup_free_
char *t
= NULL
, *u
= NULL
;
2077 u
= unquote(tagvalue
, QUOTES
);
2081 enc_len
= strlen(u
) * 4 + 1;
2082 t
= new(char, enc_len
);
2086 if (encode_devnode_name(u
, t
, enc_len
) < 0)
2089 return strjoin("/dev/disk/by-", by
, "/", t
, NULL
);
2092 char *fstab_node_to_udev_node(const char *p
) {
2095 if (startswith(p
, "LABEL="))
2096 return tag_to_udev_node(p
+6, "label");
2098 if (startswith(p
, "UUID="))
2099 return tag_to_udev_node(p
+5, "uuid");
2101 if (startswith(p
, "PARTUUID="))
2102 return tag_to_udev_node(p
+9, "partuuid");
2104 if (startswith(p
, "PARTLABEL="))
2105 return tag_to_udev_node(p
+10, "partlabel");
2110 bool dirent_is_file(const struct dirent
*de
) {
2113 if (hidden_file(de
->d_name
))
2116 if (de
->d_type
!= DT_REG
&&
2117 de
->d_type
!= DT_LNK
&&
2118 de
->d_type
!= DT_UNKNOWN
)
2124 bool dirent_is_file_with_suffix(const struct dirent
*de
, const char *suffix
) {
2127 if (de
->d_type
!= DT_REG
&&
2128 de
->d_type
!= DT_LNK
&&
2129 de
->d_type
!= DT_UNKNOWN
)
2132 if (hidden_file_allow_backup(de
->d_name
))
2135 return endswith(de
->d_name
, suffix
);
2138 static int do_execute(char **directories
, usec_t timeout
, char *argv
[]) {
2139 _cleanup_hashmap_free_free_ Hashmap
*pids
= NULL
;
2140 _cleanup_set_free_free_ Set
*seen
= NULL
;
2143 /* We fork this all off from a child process so that we can
2144 * somewhat cleanly make use of SIGALRM to set a time limit */
2146 (void) reset_all_signal_handlers();
2147 (void) reset_signal_mask();
2149 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
2151 pids
= hashmap_new(NULL
);
2155 seen
= set_new(&string_hash_ops
);
2159 STRV_FOREACH(directory
, directories
) {
2160 _cleanup_closedir_
DIR *d
;
2163 d
= opendir(*directory
);
2165 if (errno
== ENOENT
)
2168 return log_error_errno(errno
, "Failed to open directory %s: %m", *directory
);
2171 FOREACH_DIRENT(de
, d
, break) {
2172 _cleanup_free_
char *path
= NULL
;
2176 if (!dirent_is_file(de
))
2179 if (set_contains(seen
, de
->d_name
)) {
2180 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory
, de
->d_name
);
2184 r
= set_put_strdup(seen
, de
->d_name
);
2188 path
= strjoin(*directory
, "/", de
->d_name
, NULL
);
2192 if (null_or_empty_path(path
)) {
2193 log_debug("%s is empty (a mask).", path
);
2199 log_error_errno(errno
, "Failed to fork: %m");
2201 } else if (pid
== 0) {
2204 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
2214 return log_error_errno(errno
, "Failed to execute %s: %m", path
);
2217 log_debug("Spawned %s as " PID_FMT
".", path
, pid
);
2219 r
= hashmap_put(pids
, UINT_TO_PTR(pid
), path
);
2226 /* Abort execution of this process after the timout. We simply
2227 * rely on SIGALRM as default action terminating the process,
2228 * and turn on alarm(). */
2230 if (timeout
!= USEC_INFINITY
)
2231 alarm((timeout
+ USEC_PER_SEC
- 1) / USEC_PER_SEC
);
2233 while (!hashmap_isempty(pids
)) {
2234 _cleanup_free_
char *path
= NULL
;
2237 pid
= PTR_TO_UINT(hashmap_first_key(pids
));
2240 path
= hashmap_remove(pids
, UINT_TO_PTR(pid
));
2243 wait_for_terminate_and_warn(path
, pid
, true);
2249 void execute_directories(const char* const* directories
, usec_t timeout
, char *argv
[]) {
2253 char **dirs
= (char**) directories
;
2255 assert(!strv_isempty(dirs
));
2257 name
= basename(dirs
[0]);
2258 assert(!isempty(name
));
2260 /* Executes all binaries in the directories in parallel and waits
2261 * for them to finish. Optionally a timeout is applied. If a file
2262 * with the same name exists in more than one directory, the
2263 * earliest one wins. */
2265 executor_pid
= fork();
2266 if (executor_pid
< 0) {
2267 log_error_errno(errno
, "Failed to fork: %m");
2270 } else if (executor_pid
== 0) {
2271 r
= do_execute(dirs
, timeout
, argv
);
2272 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
2275 wait_for_terminate_and_warn(name
, executor_pid
, true);
2278 bool plymouth_running(void) {
2279 return access("/run/plymouth/pid", F_OK
) >= 0;
2282 int pipe_eof(int fd
) {
2283 struct pollfd pollfd
= {
2285 .events
= POLLIN
|POLLHUP
,
2290 r
= poll(&pollfd
, 1, 0);
2297 return pollfd
.revents
& POLLHUP
;
2300 int fd_wait_for_event(int fd
, int event
, usec_t t
) {
2302 struct pollfd pollfd
= {
2310 r
= ppoll(&pollfd
, 1, t
== USEC_INFINITY
? NULL
: timespec_store(&ts
, t
), NULL
);
2317 return pollfd
.revents
;
2320 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
2329 r
= tempfn_xxxxxx(path
, NULL
, &t
);
2333 fd
= mkostemp_safe(t
, O_WRONLY
|O_CLOEXEC
);
2339 f
= fdopen(fd
, "we");
2353 int symlink_atomic(const char *from
, const char *to
) {
2354 _cleanup_free_
char *t
= NULL
;
2360 r
= tempfn_random(to
, NULL
, &t
);
2364 if (symlink(from
, t
) < 0)
2367 if (rename(t
, to
) < 0) {
2375 int symlink_idempotent(const char *from
, const char *to
) {
2376 _cleanup_free_
char *p
= NULL
;
2382 if (symlink(from
, to
) < 0) {
2383 if (errno
!= EEXIST
)
2386 r
= readlink_malloc(to
, &p
);
2390 if (!streq(p
, from
))
2397 int mknod_atomic(const char *path
, mode_t mode
, dev_t dev
) {
2398 _cleanup_free_
char *t
= NULL
;
2403 r
= tempfn_random(path
, NULL
, &t
);
2407 if (mknod(t
, mode
, dev
) < 0)
2410 if (rename(t
, path
) < 0) {
2418 int mkfifo_atomic(const char *path
, mode_t mode
) {
2419 _cleanup_free_
char *t
= NULL
;
2424 r
= tempfn_random(path
, NULL
, &t
);
2428 if (mkfifo(t
, mode
) < 0)
2431 if (rename(t
, path
) < 0) {
2439 bool display_is_local(const char *display
) {
2443 display
[0] == ':' &&
2444 display
[1] >= '0' &&
2448 int socket_from_display(const char *display
, char **path
) {
2455 if (!display_is_local(display
))
2458 k
= strspn(display
+1, "0123456789");
2460 f
= new(char, strlen("/tmp/.X11-unix/X") + k
+ 1);
2464 c
= stpcpy(f
, "/tmp/.X11-unix/X");
2465 memcpy(c
, display
+1, k
);
2474 const char **username
,
2475 uid_t
*uid
, gid_t
*gid
,
2477 const char **shell
) {
2485 /* We enforce some special rules for uid=0: in order to avoid
2486 * NSS lookups for root we hardcode its data. */
2488 if (streq(*username
, "root") || streq(*username
, "0")) {
2506 if (parse_uid(*username
, &u
) >= 0) {
2510 /* If there are multiple users with the same id, make
2511 * sure to leave $USER to the configured value instead
2512 * of the first occurrence in the database. However if
2513 * the uid was configured by a numeric uid, then let's
2514 * pick the real username from /etc/passwd. */
2516 *username
= p
->pw_name
;
2519 p
= getpwnam(*username
);
2523 return errno
> 0 ? -errno
: -ESRCH
;
2535 *shell
= p
->pw_shell
;
2540 char* uid_to_name(uid_t uid
) {
2545 return strdup("root");
2549 return strdup(p
->pw_name
);
2551 if (asprintf(&r
, UID_FMT
, uid
) < 0)
2557 char* gid_to_name(gid_t gid
) {
2562 return strdup("root");
2566 return strdup(p
->gr_name
);
2568 if (asprintf(&r
, GID_FMT
, gid
) < 0)
2574 int get_group_creds(const char **groupname
, gid_t
*gid
) {
2580 /* We enforce some special rules for gid=0: in order to avoid
2581 * NSS lookups for root we hardcode its data. */
2583 if (streq(*groupname
, "root") || streq(*groupname
, "0")) {
2584 *groupname
= "root";
2592 if (parse_gid(*groupname
, &id
) >= 0) {
2597 *groupname
= g
->gr_name
;
2600 g
= getgrnam(*groupname
);
2604 return errno
> 0 ? -errno
: -ESRCH
;
2612 int in_gid(gid_t gid
) {
2614 int ngroups_max
, r
, i
;
2616 if (getgid() == gid
)
2619 if (getegid() == gid
)
2622 ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
2623 assert(ngroups_max
> 0);
2625 gids
= alloca(sizeof(gid_t
) * ngroups_max
);
2627 r
= getgroups(ngroups_max
, gids
);
2631 for (i
= 0; i
< r
; i
++)
2638 int in_group(const char *name
) {
2642 r
= get_group_creds(&name
, &gid
);
2649 int glob_exists(const char *path
) {
2650 _cleanup_globfree_ glob_t g
= {};
2656 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
2658 if (k
== GLOB_NOMATCH
)
2660 else if (k
== GLOB_NOSPACE
)
2663 return !strv_isempty(g
.gl_pathv
);
2665 return errno
? -errno
: -EIO
;
2668 int glob_extend(char ***strv
, const char *path
) {
2669 _cleanup_globfree_ glob_t g
= {};
2674 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
2676 if (k
== GLOB_NOMATCH
)
2678 else if (k
== GLOB_NOSPACE
)
2680 else if (k
!= 0 || strv_isempty(g
.gl_pathv
))
2681 return errno
? -errno
: -EIO
;
2683 STRV_FOREACH(p
, g
.gl_pathv
) {
2684 k
= strv_extend(strv
, *p
);
2692 int dirent_ensure_type(DIR *d
, struct dirent
*de
) {
2698 if (de
->d_type
!= DT_UNKNOWN
)
2701 if (fstatat(dirfd(d
), de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
2705 S_ISREG(st
.st_mode
) ? DT_REG
:
2706 S_ISDIR(st
.st_mode
) ? DT_DIR
:
2707 S_ISLNK(st
.st_mode
) ? DT_LNK
:
2708 S_ISFIFO(st
.st_mode
) ? DT_FIFO
:
2709 S_ISSOCK(st
.st_mode
) ? DT_SOCK
:
2710 S_ISCHR(st
.st_mode
) ? DT_CHR
:
2711 S_ISBLK(st
.st_mode
) ? DT_BLK
:
2717 int get_files_in_directory(const char *path
, char ***list
) {
2718 _cleanup_closedir_
DIR *d
= NULL
;
2719 size_t bufsize
= 0, n
= 0;
2720 _cleanup_strv_free_
char **l
= NULL
;
2724 /* Returns all files in a directory in *list, and the number
2725 * of files as return value. If list is NULL returns only the
2737 if (!de
&& errno
!= 0)
2742 dirent_ensure_type(d
, de
);
2744 if (!dirent_is_file(de
))
2748 /* one extra slot is needed for the terminating NULL */
2749 if (!GREEDY_REALLOC(l
, bufsize
, n
+ 2))
2752 l
[n
] = strdup(de
->d_name
);
2763 l
= NULL
; /* avoid freeing */
2769 bool is_main_thread(void) {
2770 static thread_local
int cached
= 0;
2772 if (_unlikely_(cached
== 0))
2773 cached
= getpid() == gettid() ? 1 : -1;
2778 int block_get_whole_disk(dev_t d
, dev_t
*ret
) {
2785 /* If it has a queue this is good enough for us */
2786 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", major(d
), minor(d
)) < 0)
2789 r
= access(p
, F_OK
);
2797 /* If it is a partition find the originating device */
2798 if (asprintf(&p
, "/sys/dev/block/%u:%u/partition", major(d
), minor(d
)) < 0)
2801 r
= access(p
, F_OK
);
2807 /* Get parent dev_t */
2808 if (asprintf(&p
, "/sys/dev/block/%u:%u/../dev", major(d
), minor(d
)) < 0)
2811 r
= read_one_line_file(p
, &s
);
2817 r
= sscanf(s
, "%u:%u", &m
, &n
);
2823 /* Only return this if it is really good enough for us. */
2824 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", m
, n
) < 0)
2827 r
= access(p
, F_OK
);
2831 *ret
= makedev(m
, n
);
2838 static const char *const ioprio_class_table
[] = {
2839 [IOPRIO_CLASS_NONE
] = "none",
2840 [IOPRIO_CLASS_RT
] = "realtime",
2841 [IOPRIO_CLASS_BE
] = "best-effort",
2842 [IOPRIO_CLASS_IDLE
] = "idle"
2845 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, INT_MAX
);
2847 static const char *const sigchld_code_table
[] = {
2848 [CLD_EXITED
] = "exited",
2849 [CLD_KILLED
] = "killed",
2850 [CLD_DUMPED
] = "dumped",
2851 [CLD_TRAPPED
] = "trapped",
2852 [CLD_STOPPED
] = "stopped",
2853 [CLD_CONTINUED
] = "continued",
2856 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
2858 static const char *const log_facility_unshifted_table
[LOG_NFACILITIES
] = {
2859 [LOG_FAC(LOG_KERN
)] = "kern",
2860 [LOG_FAC(LOG_USER
)] = "user",
2861 [LOG_FAC(LOG_MAIL
)] = "mail",
2862 [LOG_FAC(LOG_DAEMON
)] = "daemon",
2863 [LOG_FAC(LOG_AUTH
)] = "auth",
2864 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
2865 [LOG_FAC(LOG_LPR
)] = "lpr",
2866 [LOG_FAC(LOG_NEWS
)] = "news",
2867 [LOG_FAC(LOG_UUCP
)] = "uucp",
2868 [LOG_FAC(LOG_CRON
)] = "cron",
2869 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
2870 [LOG_FAC(LOG_FTP
)] = "ftp",
2871 [LOG_FAC(LOG_LOCAL0
)] = "local0",
2872 [LOG_FAC(LOG_LOCAL1
)] = "local1",
2873 [LOG_FAC(LOG_LOCAL2
)] = "local2",
2874 [LOG_FAC(LOG_LOCAL3
)] = "local3",
2875 [LOG_FAC(LOG_LOCAL4
)] = "local4",
2876 [LOG_FAC(LOG_LOCAL5
)] = "local5",
2877 [LOG_FAC(LOG_LOCAL6
)] = "local6",
2878 [LOG_FAC(LOG_LOCAL7
)] = "local7"
2881 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted
, int, LOG_FAC(~0));
2883 bool log_facility_unshifted_is_valid(int facility
) {
2884 return facility
>= 0 && facility
<= LOG_FAC(~0);
2887 static const char *const log_level_table
[] = {
2888 [LOG_EMERG
] = "emerg",
2889 [LOG_ALERT
] = "alert",
2890 [LOG_CRIT
] = "crit",
2892 [LOG_WARNING
] = "warning",
2893 [LOG_NOTICE
] = "notice",
2894 [LOG_INFO
] = "info",
2895 [LOG_DEBUG
] = "debug"
2898 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level
, int, LOG_DEBUG
);
2900 bool log_level_is_valid(int level
) {
2901 return level
>= 0 && level
<= LOG_DEBUG
;
2904 static const char* const sched_policy_table
[] = {
2905 [SCHED_OTHER
] = "other",
2906 [SCHED_BATCH
] = "batch",
2907 [SCHED_IDLE
] = "idle",
2908 [SCHED_FIFO
] = "fifo",
2912 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);
2914 static const char* const rlimit_table
[_RLIMIT_MAX
] = {
2915 [RLIMIT_CPU
] = "LimitCPU",
2916 [RLIMIT_FSIZE
] = "LimitFSIZE",
2917 [RLIMIT_DATA
] = "LimitDATA",
2918 [RLIMIT_STACK
] = "LimitSTACK",
2919 [RLIMIT_CORE
] = "LimitCORE",
2920 [RLIMIT_RSS
] = "LimitRSS",
2921 [RLIMIT_NOFILE
] = "LimitNOFILE",
2922 [RLIMIT_AS
] = "LimitAS",
2923 [RLIMIT_NPROC
] = "LimitNPROC",
2924 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
2925 [RLIMIT_LOCKS
] = "LimitLOCKS",
2926 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
2927 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
2928 [RLIMIT_NICE
] = "LimitNICE",
2929 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
2930 [RLIMIT_RTTIME
] = "LimitRTTIME"
2933 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
2935 static const char* const ip_tos_table
[] = {
2936 [IPTOS_LOWDELAY
] = "low-delay",
2937 [IPTOS_THROUGHPUT
] = "throughput",
2938 [IPTOS_RELIABILITY
] = "reliability",
2939 [IPTOS_LOWCOST
] = "low-cost",
2942 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
2944 bool kexec_loaded(void) {
2945 bool loaded
= false;
2948 if (read_one_line_file("/sys/kernel/kexec_loaded", &s
) >= 0) {
2956 int prot_from_flags(int flags
) {
2958 switch (flags
& O_ACCMODE
) {
2967 return PROT_READ
|PROT_WRITE
;
2974 char *format_bytes(char *buf
, size_t l
, uint64_t t
) {
2977 static const struct {
2981 { "E", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2982 { "P", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2983 { "T", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2984 { "G", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2985 { "M", UINT64_C(1024)*UINT64_C(1024) },
2986 { "K", UINT64_C(1024) },
2989 if (t
== (uint64_t) -1)
2992 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
2994 if (t
>= table
[i
].factor
) {
2996 "%" PRIu64
".%" PRIu64
"%s",
2997 t
/ table
[i
].factor
,
2998 ((t
*UINT64_C(10)) / table
[i
].factor
) % UINT64_C(10),
3005 snprintf(buf
, l
, "%" PRIu64
"B", t
);
3013 void* memdup(const void *p
, size_t l
) {
3026 int fd_inc_sndbuf(int fd
, size_t n
) {
3028 socklen_t l
= sizeof(value
);
3030 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
3031 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
3034 /* If we have the privileges we will ignore the kernel limit. */
3037 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
3038 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
3044 int fd_inc_rcvbuf(int fd
, size_t n
) {
3046 socklen_t l
= sizeof(value
);
3048 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
3049 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
3052 /* If we have the privileges we will ignore the kernel limit. */
3055 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
3056 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
3061 int fork_agent(pid_t
*pid
, const int except
[], unsigned n_except
, const char *path
, ...) {
3062 bool stdout_is_tty
, stderr_is_tty
;
3063 pid_t parent_pid
, agent_pid
;
3064 sigset_t ss
, saved_ss
;
3072 /* Spawns a temporary TTY agent, making sure it goes away when
3075 parent_pid
= getpid();
3077 /* First we temporarily block all signals, so that the new
3078 * child has them blocked initially. This way, we can be sure
3079 * that SIGTERMs are not lost we might send to the agent. */
3080 assert_se(sigfillset(&ss
) >= 0);
3081 assert_se(sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) >= 0);
3084 if (agent_pid
< 0) {
3085 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
3089 if (agent_pid
!= 0) {
3090 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
3097 * Make sure the agent goes away when the parent dies */
3098 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
3099 _exit(EXIT_FAILURE
);
3101 /* Make sure we actually can kill the agent, if we need to, in
3102 * case somebody invoked us from a shell script that trapped
3103 * SIGTERM or so... */
3104 (void) reset_all_signal_handlers();
3105 (void) reset_signal_mask();
3107 /* Check whether our parent died before we were able
3108 * to set the death signal and unblock the signals */
3109 if (getppid() != parent_pid
)
3110 _exit(EXIT_SUCCESS
);
3112 /* Don't leak fds to the agent */
3113 close_all_fds(except
, n_except
);
3115 stdout_is_tty
= isatty(STDOUT_FILENO
);
3116 stderr_is_tty
= isatty(STDERR_FILENO
);
3118 if (!stdout_is_tty
|| !stderr_is_tty
) {
3121 /* Detach from stdout/stderr. and reopen
3122 * /dev/tty for them. This is important to
3123 * ensure that when systemctl is started via
3124 * popen() or a similar call that expects to
3125 * read EOF we actually do generate EOF and
3126 * not delay this indefinitely by because we
3127 * keep an unused copy of stdin around. */
3128 fd
= open("/dev/tty", O_WRONLY
);
3130 log_error_errno(errno
, "Failed to open /dev/tty: %m");
3131 _exit(EXIT_FAILURE
);
3135 dup2(fd
, STDOUT_FILENO
);
3138 dup2(fd
, STDERR_FILENO
);
3144 /* Count arguments */
3146 for (n
= 0; va_arg(ap
, char*); n
++)
3151 l
= alloca(sizeof(char *) * (n
+ 1));
3153 /* Fill in arguments */
3155 for (i
= 0; i
<= n
; i
++)
3156 l
[i
] = va_arg(ap
, char*);
3160 _exit(EXIT_FAILURE
);
3163 int setrlimit_closest(int resource
, const struct rlimit
*rlim
) {
3164 struct rlimit highest
, fixed
;
3168 if (setrlimit(resource
, rlim
) >= 0)
3174 /* So we failed to set the desired setrlimit, then let's try
3175 * to get as close as we can */
3176 assert_se(getrlimit(resource
, &highest
) == 0);
3178 fixed
.rlim_cur
= MIN(rlim
->rlim_cur
, highest
.rlim_max
);
3179 fixed
.rlim_max
= MIN(rlim
->rlim_max
, highest
.rlim_max
);
3181 if (setrlimit(resource
, &fixed
) < 0)
3187 bool http_etag_is_valid(const char *etag
) {
3191 if (!endswith(etag
, "\""))
3194 if (!startswith(etag
, "\"") && !startswith(etag
, "W/\""))
3200 bool http_url_is_valid(const char *url
) {
3206 p
= startswith(url
, "http://");
3208 p
= startswith(url
, "https://");
3215 return ascii_is_valid(p
);
3218 bool documentation_url_is_valid(const char *url
) {
3224 if (http_url_is_valid(url
))
3227 p
= startswith(url
, "file:/");
3229 p
= startswith(url
, "info:");
3231 p
= startswith(url
, "man:");
3236 return ascii_is_valid(p
);
3239 bool in_initrd(void) {
3240 static int saved
= -1;
3246 /* We make two checks here:
3248 * 1. the flag file /etc/initrd-release must exist
3249 * 2. the root file system must be a memory file system
3251 * The second check is extra paranoia, since misdetecting an
3252 * initrd can have bad bad consequences due the initrd
3253 * emptying when transititioning to the main systemd.
3256 saved
= access("/etc/initrd-release", F_OK
) >= 0 &&
3257 statfs("/", &s
) >= 0 &&
3258 is_temporary_fs(&s
);
3263 int get_home_dir(char **_h
) {
3271 /* Take the user specified one */
3272 e
= secure_getenv("HOME");
3273 if (e
&& path_is_absolute(e
)) {
3282 /* Hardcode home directory for root to avoid NSS */
3285 h
= strdup("/root");
3293 /* Check the database... */
3297 return errno
> 0 ? -errno
: -ESRCH
;
3299 if (!path_is_absolute(p
->pw_dir
))
3302 h
= strdup(p
->pw_dir
);
3310 int get_shell(char **_s
) {
3318 /* Take the user specified one */
3319 e
= getenv("SHELL");
3329 /* Hardcode home directory for root to avoid NSS */
3332 s
= strdup("/bin/sh");
3340 /* Check the database... */
3344 return errno
> 0 ? -errno
: -ESRCH
;
3346 if (!path_is_absolute(p
->pw_shell
))
3349 s
= strdup(p
->pw_shell
);
3357 bool filename_is_valid(const char *p
) {
3371 if (strlen(p
) > FILENAME_MAX
)
3377 bool string_is_safe(const char *p
) {
3383 for (t
= p
; *t
; t
++) {
3384 if (*t
> 0 && *t
< ' ')
3387 if (strchr("\\\"\'\x7f", *t
))
3394 bool path_is_safe(const char *p
) {
3399 if (streq(p
, "..") || startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
3402 if (strlen(p
)+1 > PATH_MAX
)
3405 /* The following two checks are not really dangerous, but hey, they still are confusing */
3406 if (streq(p
, ".") || startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
3409 if (strstr(p
, "//"))
3415 /* hey glibc, APIs with callbacks without a user pointer are so useless */
3416 void *xbsearch_r(const void *key
, const void *base
, size_t nmemb
, size_t size
,
3417 int (*compar
) (const void *, const void *, void *), void *arg
) {
3426 p
= (void *)(((const char *) base
) + (idx
* size
));
3427 comparison
= compar(key
, p
, arg
);
3430 else if (comparison
> 0)
3438 void init_gettext(void) {
3439 setlocale(LC_ALL
, "");
3440 textdomain(GETTEXT_PACKAGE
);
3443 bool is_locale_utf8(void) {
3445 static int cached_answer
= -1;
3447 if (cached_answer
>= 0)
3450 if (!setlocale(LC_ALL
, "")) {
3451 cached_answer
= true;
3455 set
= nl_langinfo(CODESET
);
3457 cached_answer
= true;
3461 if (streq(set
, "UTF-8")) {
3462 cached_answer
= true;
3466 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
3467 * unset and everything can do to UTF-8 nowadays. */
3468 set
= setlocale(LC_CTYPE
, NULL
);
3470 cached_answer
= true;
3474 /* Check result, but ignore the result if C was set
3477 STR_IN_SET(set
, "C", "POSIX") &&
3478 !getenv("LC_ALL") &&
3479 !getenv("LC_CTYPE") &&
3483 return (bool) cached_answer
;
3486 const char *draw_special_char(DrawSpecialChar ch
) {
3487 static const char *draw_table
[2][_DRAW_SPECIAL_CHAR_MAX
] = {
3490 [DRAW_TREE_VERTICAL
] = "\342\224\202 ", /* │ */
3491 [DRAW_TREE_BRANCH
] = "\342\224\234\342\224\200", /* ├─ */
3492 [DRAW_TREE_RIGHT
] = "\342\224\224\342\224\200", /* └─ */
3493 [DRAW_TREE_SPACE
] = " ", /* */
3494 [DRAW_TRIANGULAR_BULLET
] = "\342\200\243", /* ‣ */
3495 [DRAW_BLACK_CIRCLE
] = "\342\227\217", /* ● */
3496 [DRAW_ARROW
] = "\342\206\222", /* → */
3497 [DRAW_DASH
] = "\342\200\223", /* – */
3500 /* ASCII fallback */ {
3501 [DRAW_TREE_VERTICAL
] = "| ",
3502 [DRAW_TREE_BRANCH
] = "|-",
3503 [DRAW_TREE_RIGHT
] = "`-",
3504 [DRAW_TREE_SPACE
] = " ",
3505 [DRAW_TRIANGULAR_BULLET
] = ">",
3506 [DRAW_BLACK_CIRCLE
] = "*",
3507 [DRAW_ARROW
] = "->",
3512 return draw_table
[!is_locale_utf8()][ch
];
3515 int on_ac_power(void) {
3516 bool found_offline
= false, found_online
= false;
3517 _cleanup_closedir_
DIR *d
= NULL
;
3519 d
= opendir("/sys/class/power_supply");
3521 return errno
== ENOENT
? true : -errno
;
3525 _cleanup_close_
int fd
= -1, device
= -1;
3531 if (!de
&& errno
!= 0)
3537 if (hidden_file(de
->d_name
))
3540 device
= openat(dirfd(d
), de
->d_name
, O_DIRECTORY
|O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
3542 if (errno
== ENOENT
|| errno
== ENOTDIR
)
3548 fd
= openat(device
, "type", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
3550 if (errno
== ENOENT
)
3556 n
= read(fd
, contents
, sizeof(contents
));
3560 if (n
!= 6 || memcmp(contents
, "Mains\n", 6))
3564 fd
= openat(device
, "online", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
3566 if (errno
== ENOENT
)
3572 n
= read(fd
, contents
, sizeof(contents
));
3576 if (n
!= 2 || contents
[1] != '\n')
3579 if (contents
[0] == '1') {
3580 found_online
= true;
3582 } else if (contents
[0] == '0')
3583 found_offline
= true;
3588 return found_online
|| !found_offline
;
3591 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
3598 if (!path_strv_resolve_uniq(search
, root
))
3601 STRV_FOREACH(i
, search
) {
3602 _cleanup_free_
char *p
= NULL
;
3606 p
= strjoin(root
, *i
, "/", path
, NULL
);
3608 p
= strjoin(*i
, "/", path
, NULL
);
3618 if (errno
!= ENOENT
)
3625 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
3626 _cleanup_strv_free_
char **copy
= NULL
;
3632 if (path_is_absolute(path
)) {
3635 f
= fopen(path
, mode
);
3644 copy
= strv_copy((char**) search
);
3648 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
3651 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
3652 _cleanup_strv_free_
char **s
= NULL
;
3654 if (path_is_absolute(path
)) {
3657 f
= fopen(path
, mode
);
3666 s
= strv_split_nulstr(search
);
3670 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
3673 void* greedy_realloc(void **p
, size_t *allocated
, size_t need
, size_t size
) {
3680 if (*allocated
>= need
)
3683 newalloc
= MAX(need
* 2, 64u / size
);
3684 a
= newalloc
* size
;
3686 /* check for overflows */
3687 if (a
< size
* need
)
3695 *allocated
= newalloc
;
3699 void* greedy_realloc0(void **p
, size_t *allocated
, size_t need
, size_t size
) {
3708 q
= greedy_realloc(p
, allocated
, need
, size
);
3712 if (*allocated
> prev
)
3713 memzero(q
+ prev
* size
, (*allocated
- prev
) * size
);
3718 bool id128_is_valid(const char *s
) {
3724 /* Simple formatted 128bit hex string */
3726 for (i
= 0; i
< l
; i
++) {
3729 if (!(c
>= '0' && c
<= '9') &&
3730 !(c
>= 'a' && c
<= 'z') &&
3731 !(c
>= 'A' && c
<= 'Z'))
3735 } else if (l
== 36) {
3737 /* Formatted UUID */
3739 for (i
= 0; i
< l
; i
++) {
3742 if ((i
== 8 || i
== 13 || i
== 18 || i
== 23)) {
3746 if (!(c
>= '0' && c
<= '9') &&
3747 !(c
>= 'a' && c
<= 'z') &&
3748 !(c
>= 'A' && c
<= 'Z'))
3759 int shall_restore_state(void) {
3760 _cleanup_free_
char *value
= NULL
;
3763 r
= get_proc_cmdline_key("systemd.restore_state=", &value
);
3769 return parse_boolean(value
) != 0;
3772 int proc_cmdline(char **ret
) {
3775 if (detect_container() > 0)
3776 return get_process_cmdline(1, 0, false, ret
);
3778 return read_one_line_file("/proc/cmdline", ret
);
3781 int parse_proc_cmdline(int (*parse_item
)(const char *key
, const char *value
)) {
3782 _cleanup_free_
char *line
= NULL
;
3788 r
= proc_cmdline(&line
);
3794 _cleanup_free_
char *word
= NULL
;
3797 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
3803 /* Filter out arguments that are intended only for the
3805 if (!in_initrd() && startswith(word
, "rd."))
3808 value
= strchr(word
, '=');
3812 r
= parse_item(word
, value
);
3820 int get_proc_cmdline_key(const char *key
, char **value
) {
3821 _cleanup_free_
char *line
= NULL
, *ret
= NULL
;
3828 r
= proc_cmdline(&line
);
3834 _cleanup_free_
char *word
= NULL
;
3837 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
3843 /* Filter out arguments that are intended only for the
3845 if (!in_initrd() && startswith(word
, "rd."))
3849 e
= startswith(word
, key
);
3853 r
= free_and_strdup(&ret
, e
);
3859 if (streq(word
, key
))
3873 int container_get_leader(const char *machine
, pid_t
*pid
) {
3874 _cleanup_free_
char *s
= NULL
, *class = NULL
;
3882 if (!machine_name_is_valid(machine
))
3885 p
= strjoina("/run/systemd/machines/", machine
);
3886 r
= parse_env_file(p
, NEWLINE
, "LEADER", &s
, "CLASS", &class, NULL
);
3894 if (!streq_ptr(class, "container"))
3897 r
= parse_pid(s
, &leader
);
3907 int namespace_open(pid_t pid
, int *pidns_fd
, int *mntns_fd
, int *netns_fd
, int *userns_fd
, int *root_fd
) {
3908 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, netnsfd
= -1, usernsfd
= -1;
3916 mntns
= procfs_file_alloca(pid
, "ns/mnt");
3917 mntnsfd
= open(mntns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
3925 pidns
= procfs_file_alloca(pid
, "ns/pid");
3926 pidnsfd
= open(pidns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
3934 netns
= procfs_file_alloca(pid
, "ns/net");
3935 netnsfd
= open(netns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
3943 userns
= procfs_file_alloca(pid
, "ns/user");
3944 usernsfd
= open(userns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
3945 if (usernsfd
< 0 && errno
!= ENOENT
)
3952 root
= procfs_file_alloca(pid
, "root");
3953 rfd
= open(root
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
|O_DIRECTORY
);
3959 *pidns_fd
= pidnsfd
;
3962 *mntns_fd
= mntnsfd
;
3965 *netns_fd
= netnsfd
;
3968 *userns_fd
= usernsfd
;
3973 pidnsfd
= mntnsfd
= netnsfd
= usernsfd
= -1;
3978 int namespace_enter(int pidns_fd
, int mntns_fd
, int netns_fd
, int userns_fd
, int root_fd
) {
3979 if (userns_fd
>= 0) {
3980 /* Can't setns to your own userns, since then you could
3981 * escalate from non-root to root in your own namespace, so
3982 * check if namespaces equal before attempting to enter. */
3983 _cleanup_free_
char *userns_fd_path
= NULL
;
3985 if (asprintf(&userns_fd_path
, "/proc/self/fd/%d", userns_fd
) < 0)
3988 r
= files_same(userns_fd_path
, "/proc/self/ns/user");
3996 if (setns(pidns_fd
, CLONE_NEWPID
) < 0)
4000 if (setns(mntns_fd
, CLONE_NEWNS
) < 0)
4004 if (setns(netns_fd
, CLONE_NEWNET
) < 0)
4008 if (setns(userns_fd
, CLONE_NEWUSER
) < 0)
4012 if (fchdir(root_fd
) < 0)
4015 if (chroot(".") < 0)
4019 return reset_uid_gid();
4022 int getpeercred(int fd
, struct ucred
*ucred
) {
4023 socklen_t n
= sizeof(struct ucred
);
4030 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
);
4034 if (n
!= sizeof(struct ucred
))
4037 /* Check if the data is actually useful and not suppressed due
4038 * to namespacing issues */
4041 if (u
.uid
== UID_INVALID
)
4043 if (u
.gid
== GID_INVALID
)
4050 int getpeersec(int fd
, char **ret
) {
4062 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
4066 if (errno
!= ERANGE
)
4073 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
4089 /* This is much like like mkostemp() but is subject to umask(). */
4090 int mkostemp_safe(char *pattern
, int flags
) {
4091 _cleanup_umask_ mode_t u
;
4098 fd
= mkostemp(pattern
, flags
);
4105 int open_tmpfile(const char *path
, int flags
) {
4112 /* Try O_TMPFILE first, if it is supported */
4113 fd
= open(path
, flags
|O_TMPFILE
|O_EXCL
, S_IRUSR
|S_IWUSR
);
4118 /* Fall back to unguessable name + unlinking */
4119 p
= strjoina(path
, "/systemd-tmp-XXXXXX");
4121 fd
= mkostemp_safe(p
, flags
);
4129 int fd_warn_permissions(const char *path
, int fd
) {
4132 if (fstat(fd
, &st
) < 0)
4135 if (st
.st_mode
& 0111)
4136 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path
);
4138 if (st
.st_mode
& 0002)
4139 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path
);
4141 if (getpid() == 1 && (st
.st_mode
& 0044) != 0044)
4142 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
);
4147 unsigned long personality_from_string(const char *p
) {
4149 /* Parse a personality specifier. We introduce our own
4150 * identifiers that indicate specific ABIs, rather than just
4151 * hints regarding the register size, since we want to keep
4152 * things open for multiple locally supported ABIs for the
4153 * same register size. We try to reuse the ABI identifiers
4154 * used by libseccomp. */
4156 #if defined(__x86_64__)
4158 if (streq(p
, "x86"))
4161 if (streq(p
, "x86-64"))
4164 #elif defined(__i386__)
4166 if (streq(p
, "x86"))
4169 #elif defined(__s390x__)
4171 if (streq(p
, "s390"))
4174 if (streq(p
, "s390x"))
4177 #elif defined(__s390__)
4179 if (streq(p
, "s390"))
4183 return PERSONALITY_INVALID
;
4186 const char* personality_to_string(unsigned long p
) {
4188 #if defined(__x86_64__)
4190 if (p
== PER_LINUX32
)
4196 #elif defined(__i386__)
4201 #elif defined(__s390x__)
4206 if (p
== PER_LINUX32
)
4209 #elif defined(__s390__)
4219 uint64_t physical_memory(void) {
4222 /* We return this as uint64_t in case we are running as 32bit
4223 * process on a 64bit kernel with huge amounts of memory */
4225 mem
= sysconf(_SC_PHYS_PAGES
);
4228 return (uint64_t) mem
* (uint64_t) page_size();
4231 void hexdump(FILE *f
, const void *p
, size_t s
) {
4232 const uint8_t *b
= p
;
4235 assert(s
== 0 || b
);
4240 fprintf(f
, "%04x ", n
);
4242 for (i
= 0; i
< 16; i
++) {
4247 fprintf(f
, "%02x ", b
[i
]);
4255 for (i
= 0; i
< 16; i
++) {
4260 fputc(isprint(b
[i
]) ? (char) b
[i
] : '.', f
);
4274 int update_reboot_param_file(const char *param
) {
4278 r
= write_string_file(REBOOT_PARAM_FILE
, param
, WRITE_STRING_FILE_CREATE
);
4280 return log_error_errno(r
, "Failed to write reboot param to "REBOOT_PARAM_FILE
": %m");
4282 (void) unlink(REBOOT_PARAM_FILE
);
4287 int umount_recursive(const char *prefix
, int flags
) {
4291 /* Try to umount everything recursively below a
4292 * directory. Also, take care of stacked mounts, and keep
4293 * unmounting them until they are gone. */
4296 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
4301 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
4302 if (!proc_self_mountinfo
)
4306 _cleanup_free_
char *path
= NULL
, *p
= NULL
;
4309 k
= fscanf(proc_self_mountinfo
,
4310 "%*s " /* (1) mount id */
4311 "%*s " /* (2) parent id */
4312 "%*s " /* (3) major:minor */
4313 "%*s " /* (4) root */
4314 "%ms " /* (5) mount point */
4315 "%*s" /* (6) mount options */
4316 "%*[^-]" /* (7) optional fields */
4317 "- " /* (8) separator */
4318 "%*s " /* (9) file system type */
4319 "%*s" /* (10) mount source */
4320 "%*s" /* (11) mount options 2 */
4321 "%*[^\n]", /* some rubbish at the end */
4330 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
4334 if (!path_startswith(p
, prefix
))
4337 if (umount2(p
, flags
) < 0) {
4353 static int get_mount_flags(const char *path
, unsigned long *flags
) {
4356 if (statvfs(path
, &buf
) < 0)
4358 *flags
= buf
.f_flag
;
4362 int bind_remount_recursive(const char *prefix
, bool ro
) {
4363 _cleanup_set_free_free_ Set
*done
= NULL
;
4364 _cleanup_free_
char *cleaned
= NULL
;
4367 /* Recursively remount a directory (and all its submounts)
4368 * read-only or read-write. If the directory is already
4369 * mounted, we reuse the mount and simply mark it
4370 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
4371 * operation). If it isn't we first make it one. Afterwards we
4372 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
4373 * submounts we can access, too. When mounts are stacked on
4374 * the same mount point we only care for each individual
4375 * "top-level" mount on each point, as we cannot
4376 * influence/access the underlying mounts anyway. We do not
4377 * have any effect on future submounts that might get
4378 * propagated, they migt be writable. This includes future
4379 * submounts that have been triggered via autofs. */
4381 cleaned
= strdup(prefix
);
4385 path_kill_slashes(cleaned
);
4387 done
= set_new(&string_hash_ops
);
4392 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
4393 _cleanup_set_free_free_ Set
*todo
= NULL
;
4394 bool top_autofs
= false;
4396 unsigned long orig_flags
;
4398 todo
= set_new(&string_hash_ops
);
4402 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
4403 if (!proc_self_mountinfo
)
4407 _cleanup_free_
char *path
= NULL
, *p
= NULL
, *type
= NULL
;
4410 k
= fscanf(proc_self_mountinfo
,
4411 "%*s " /* (1) mount id */
4412 "%*s " /* (2) parent id */
4413 "%*s " /* (3) major:minor */
4414 "%*s " /* (4) root */
4415 "%ms " /* (5) mount point */
4416 "%*s" /* (6) mount options (superblock) */
4417 "%*[^-]" /* (7) optional fields */
4418 "- " /* (8) separator */
4419 "%ms " /* (9) file system type */
4420 "%*s" /* (10) mount source */
4421 "%*s" /* (11) mount options (bind mount) */
4422 "%*[^\n]", /* some rubbish at the end */
4432 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
4436 /* Let's ignore autofs mounts. If they aren't
4437 * triggered yet, we want to avoid triggering
4438 * them, as we don't make any guarantees for
4439 * future submounts anyway. If they are
4440 * already triggered, then we will find
4441 * another entry for this. */
4442 if (streq(type
, "autofs")) {
4443 top_autofs
= top_autofs
|| path_equal(cleaned
, p
);
4447 if (path_startswith(p
, cleaned
) &&
4448 !set_contains(done
, p
)) {
4450 r
= set_consume(todo
, p
);
4460 /* If we have no submounts to process anymore and if
4461 * the root is either already done, or an autofs, we
4463 if (set_isempty(todo
) &&
4464 (top_autofs
|| set_contains(done
, cleaned
)))
4467 if (!set_contains(done
, cleaned
) &&
4468 !set_contains(todo
, cleaned
)) {
4469 /* The prefix directory itself is not yet a
4470 * mount, make it one. */
4471 if (mount(cleaned
, cleaned
, NULL
, MS_BIND
|MS_REC
, NULL
) < 0)
4475 (void) get_mount_flags(cleaned
, &orig_flags
);
4476 orig_flags
&= ~MS_RDONLY
;
4478 if (mount(NULL
, prefix
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0)
4481 x
= strdup(cleaned
);
4485 r
= set_consume(done
, x
);
4490 while ((x
= set_steal_first(todo
))) {
4492 r
= set_consume(done
, x
);
4493 if (r
== -EEXIST
|| r
== 0)
4498 /* Try to reuse the original flag set, but
4499 * don't care for errors, in case of
4500 * obstructed mounts */
4502 (void) get_mount_flags(x
, &orig_flags
);
4503 orig_flags
&= ~MS_RDONLY
;
4505 if (mount(NULL
, x
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0) {
4507 /* Deal with mount points that are
4508 * obstructed by a later mount */
4510 if (errno
!= ENOENT
)
4518 int fflush_and_check(FILE *f
) {
4525 return errno
? -errno
: -EIO
;
4530 int tempfn_xxxxxx(const char *p
, const char *extra
, char **ret
) {
4542 * /foo/bar/.#<extra>waldoXXXXXX
4546 if (!filename_is_valid(fn
))
4552 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 6 + 1);
4556 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
), "XXXXXX");
4558 *ret
= path_kill_slashes(t
);
4562 int tempfn_random(const char *p
, const char *extra
, char **ret
) {
4576 * /foo/bar/.#<extra>waldobaa2a261115984a9
4580 if (!filename_is_valid(fn
))
4586 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 16 + 1);
4590 x
= stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
);
4593 for (i
= 0; i
< 16; i
++) {
4594 *(x
++) = hexchar(u
& 0xF);
4600 *ret
= path_kill_slashes(t
);
4604 int tempfn_random_child(const char *p
, const char *extra
, char **ret
) {
4615 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
4621 t
= new(char, strlen(p
) + 3 + strlen(extra
) + 16 + 1);
4625 x
= stpcpy(stpcpy(stpcpy(t
, p
), "/.#"), extra
);
4628 for (i
= 0; i
< 16; i
++) {
4629 *(x
++) = hexchar(u
& 0xF);
4635 *ret
= path_kill_slashes(t
);
4639 int take_password_lock(const char *root
) {
4641 struct flock flock
= {
4643 .l_whence
= SEEK_SET
,
4651 /* This is roughly the same as lckpwdf(), but not as awful. We
4652 * don't want to use alarm() and signals, hence we implement
4653 * our own trivial version of this.
4655 * Note that shadow-utils also takes per-database locks in
4656 * addition to lckpwdf(). However, we don't given that they
4657 * are redundant as they they invoke lckpwdf() first and keep
4658 * it during everything they do. The per-database locks are
4659 * awfully racy, and thus we just won't do them. */
4662 path
= strjoina(root
, "/etc/.pwd.lock");
4664 path
= "/etc/.pwd.lock";
4666 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
4670 r
= fcntl(fd
, F_SETLKW
, &flock
);
4679 int is_symlink(const char *path
) {
4682 if (lstat(path
, &info
) < 0)
4685 return !!S_ISLNK(info
.st_mode
);
4688 int is_dir(const char* path
, bool follow
) {
4693 r
= stat(path
, &st
);
4695 r
= lstat(path
, &st
);
4699 return !!S_ISDIR(st
.st_mode
);
4702 int is_device_node(const char *path
) {
4705 if (lstat(path
, &info
) < 0)
4708 return !!(S_ISBLK(info
.st_mode
) || S_ISCHR(info
.st_mode
));
4711 ssize_t
fgetxattrat_fake(int dirfd
, const char *filename
, const char *attribute
, void *value
, size_t size
, int flags
) {
4712 char fn
[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(int) + 1];
4713 _cleanup_close_
int fd
= -1;
4716 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
4718 fd
= openat(dirfd
, filename
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_PATH
|(flags
& AT_SYMLINK_NOFOLLOW
? O_NOFOLLOW
: 0));
4722 xsprintf(fn
, "/proc/self/fd/%i", fd
);
4724 l
= getxattr(fn
, attribute
, value
, size
);
4731 static int parse_crtime(le64_t le
, usec_t
*usec
) {
4737 if (u
== 0 || u
== (uint64_t) -1)
4744 int fd_getcrtime(int fd
, usec_t
*usec
) {
4751 /* Until Linux gets a real concept of birthtime/creation time,
4752 * let's fake one with xattrs */
4754 n
= fgetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
));
4757 if (n
!= sizeof(le
))
4760 return parse_crtime(le
, usec
);
4763 int fd_getcrtime_at(int dirfd
, const char *name
, usec_t
*usec
, int flags
) {
4767 n
= fgetxattrat_fake(dirfd
, name
, "user.crtime_usec", &le
, sizeof(le
), flags
);
4770 if (n
!= sizeof(le
))
4773 return parse_crtime(le
, usec
);
4776 int path_getcrtime(const char *p
, usec_t
*usec
) {
4783 n
= getxattr(p
, "user.crtime_usec", &le
, sizeof(le
));
4786 if (n
!= sizeof(le
))
4789 return parse_crtime(le
, usec
);
4792 int fd_setcrtime(int fd
, usec_t usec
) {
4798 usec
= now(CLOCK_REALTIME
);
4800 le
= htole64((uint64_t) usec
);
4801 if (fsetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
), 0) < 0)
4807 int same_fd(int a
, int b
) {
4808 struct stat sta
, stb
;
4815 /* Compares two file descriptors. Note that semantics are
4816 * quite different depending on whether we have kcmp() or we
4817 * don't. If we have kcmp() this will only return true for
4818 * dup()ed file descriptors, but not otherwise. If we don't
4819 * have kcmp() this will also return true for two fds of the same
4820 * file, created by separate open() calls. Since we use this
4821 * call mostly for filtering out duplicates in the fd store
4822 * this difference hopefully doesn't matter too much. */
4827 /* Try to use kcmp() if we have it. */
4829 r
= kcmp(pid
, pid
, KCMP_FILE
, a
, b
);
4834 if (errno
!= ENOSYS
)
4837 /* We don't have kcmp(), use fstat() instead. */
4838 if (fstat(a
, &sta
) < 0)
4841 if (fstat(b
, &stb
) < 0)
4844 if ((sta
.st_mode
& S_IFMT
) != (stb
.st_mode
& S_IFMT
))
4847 /* We consider all device fds different, since two device fds
4848 * might refer to quite different device contexts even though
4849 * they share the same inode and backing dev_t. */
4851 if (S_ISCHR(sta
.st_mode
) || S_ISBLK(sta
.st_mode
))
4854 if (sta
.st_dev
!= stb
.st_dev
|| sta
.st_ino
!= stb
.st_ino
)
4857 /* The fds refer to the same inode on disk, let's also check
4858 * if they have the same fd flags. This is useful to
4859 * distinguish the read and write side of a pipe created with
4861 fa
= fcntl(a
, F_GETFL
);
4865 fb
= fcntl(b
, F_GETFL
);
4872 int chattr_fd(int fd
, unsigned value
, unsigned mask
) {
4873 unsigned old_attr
, new_attr
;
4878 if (fstat(fd
, &st
) < 0)
4881 /* Explicitly check whether this is a regular file or
4882 * directory. If it is anything else (such as a device node or
4883 * fifo), then the ioctl will not hit the file systems but
4884 * possibly drivers, where the ioctl might have different
4885 * effects. Notably, DRM is using the same ioctl() number. */
4887 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
4893 if (ioctl(fd
, FS_IOC_GETFLAGS
, &old_attr
) < 0)
4896 new_attr
= (old_attr
& ~mask
) | (value
& mask
);
4897 if (new_attr
== old_attr
)
4900 if (ioctl(fd
, FS_IOC_SETFLAGS
, &new_attr
) < 0)
4906 int chattr_path(const char *p
, unsigned value
, unsigned mask
) {
4907 _cleanup_close_
int fd
= -1;
4914 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
4918 return chattr_fd(fd
, value
, mask
);
4921 int read_attr_fd(int fd
, unsigned *ret
) {
4926 if (fstat(fd
, &st
) < 0)
4929 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
4932 if (ioctl(fd
, FS_IOC_GETFLAGS
, ret
) < 0)
4938 int read_attr_path(const char *p
, unsigned *ret
) {
4939 _cleanup_close_
int fd
= -1;
4944 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
4948 return read_attr_fd(fd
, ret
);
4951 static size_t nul_length(const uint8_t *p
, size_t sz
) {
4966 ssize_t
sparse_write(int fd
, const void *p
, size_t sz
, size_t run_length
) {
4967 const uint8_t *q
, *w
, *e
;
4975 n
= nul_length(q
, e
- q
);
4977 /* If there are more than the specified run length of
4978 * NUL bytes, or if this is the beginning or the end
4979 * of the buffer, then seek instead of write */
4980 if ((n
> run_length
) ||
4981 (n
> 0 && q
== p
) ||
4982 (n
> 0 && q
+ n
>= e
)) {
4984 l
= write(fd
, w
, q
- w
);
4991 if (lseek(fd
, n
, SEEK_CUR
) == (off_t
) -1)
5003 l
= write(fd
, w
, q
- w
);
5010 return q
- (const uint8_t*) p
;
5013 void sigkill_wait(pid_t
*pid
) {
5019 if (kill(*pid
, SIGKILL
) > 0)
5020 (void) wait_for_terminate(*pid
, NULL
);
5023 int syslog_parse_priority(const char **p
, int *priority
, bool with_facility
) {
5024 int a
= 0, b
= 0, c
= 0;
5034 if (!strchr(*p
, '>'))
5037 if ((*p
)[2] == '>') {
5038 c
= undecchar((*p
)[1]);
5040 } else if ((*p
)[3] == '>') {
5041 b
= undecchar((*p
)[1]);
5042 c
= undecchar((*p
)[2]);
5044 } else if ((*p
)[4] == '>') {
5045 a
= undecchar((*p
)[1]);
5046 b
= undecchar((*p
)[2]);
5047 c
= undecchar((*p
)[3]);
5052 if (a
< 0 || b
< 0 || c
< 0 ||
5053 (!with_facility
&& (a
|| b
|| c
> 7)))
5057 *priority
= a
*100 + b
*10 + c
;
5059 *priority
= (*priority
& LOG_FACMASK
) | c
;
5065 ssize_t
string_table_lookup(const char * const *table
, size_t len
, const char *key
) {
5071 for (i
= 0; i
< len
; ++i
)
5072 if (streq_ptr(table
[i
], key
))
5078 void cmsg_close_all(struct msghdr
*mh
) {
5079 struct cmsghdr
*cmsg
;
5083 CMSG_FOREACH(cmsg
, mh
)
5084 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
)
5085 close_many((int*) CMSG_DATA(cmsg
), (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int));
5088 int rename_noreplace(int olddirfd
, const char *oldpath
, int newdirfd
, const char *newpath
) {
5092 ret
= renameat2(olddirfd
, oldpath
, newdirfd
, newpath
, RENAME_NOREPLACE
);
5096 /* renameat2() exists since Linux 3.15, btrfs added support for it later.
5097 * If it is not implemented, fallback to another method. */
5098 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
5101 /* The link()/unlink() fallback does not work on directories. But
5102 * renameat() without RENAME_NOREPLACE gives the same semantics on
5103 * directories, except when newpath is an *empty* directory. This is
5105 ret
= fstatat(olddirfd
, oldpath
, &buf
, AT_SYMLINK_NOFOLLOW
);
5106 if (ret
>= 0 && S_ISDIR(buf
.st_mode
)) {
5107 ret
= renameat(olddirfd
, oldpath
, newdirfd
, newpath
);
5108 return ret
>= 0 ? 0 : -errno
;
5111 /* If it is not a directory, use the link()/unlink() fallback. */
5112 ret
= linkat(olddirfd
, oldpath
, newdirfd
, newpath
, 0);
5116 ret
= unlinkat(olddirfd
, oldpath
, 0);
5118 /* backup errno before the following unlinkat() alters it */
5120 (void) unlinkat(newdirfd
, newpath
, 0);
5128 int parse_mode(const char *s
, mode_t
*ret
) {
5136 l
= strtol(s
, &x
, 8);
5140 if (!x
|| x
== s
|| *x
)
5142 if (l
< 0 || l
> 07777)
5149 int mount_move_root(const char *path
) {
5152 if (chdir(path
) < 0)
5155 if (mount(path
, "/", NULL
, MS_MOVE
, NULL
) < 0)
5158 if (chroot(".") < 0)
5167 int reset_uid_gid(void) {
5169 if (setgroups(0, NULL
) < 0)
5172 if (setresgid(0, 0, 0) < 0)
5175 if (setresuid(0, 0, 0) < 0)
5181 int getxattr_malloc(const char *path
, const char *name
, char **value
, bool allow_symlink
) {
5190 for (l
= 100; ; l
= (size_t) n
+ 1) {
5196 n
= lgetxattr(path
, name
, v
, l
);
5198 n
= getxattr(path
, name
, v
, l
);
5200 if (n
>= 0 && (size_t) n
< l
) {
5207 if (n
< 0 && errno
!= ERANGE
)
5211 n
= lgetxattr(path
, name
, NULL
, 0);
5213 n
= getxattr(path
, name
, NULL
, 0);
5219 int fgetxattr_malloc(int fd
, const char *name
, char **value
) {
5228 for (l
= 100; ; l
= (size_t) n
+ 1) {
5233 n
= fgetxattr(fd
, name
, v
, l
);
5235 if (n
>= 0 && (size_t) n
< l
) {
5242 if (n
< 0 && errno
!= ERANGE
)
5245 n
= fgetxattr(fd
, name
, NULL
, 0);
5251 int send_one_fd(int transport_fd
, int fd
, int flags
) {
5253 struct cmsghdr cmsghdr
;
5254 uint8_t buf
[CMSG_SPACE(sizeof(int))];
5256 struct msghdr mh
= {
5257 .msg_control
= &control
,
5258 .msg_controllen
= sizeof(control
),
5260 struct cmsghdr
*cmsg
;
5262 assert(transport_fd
>= 0);
5265 cmsg
= CMSG_FIRSTHDR(&mh
);
5266 cmsg
->cmsg_level
= SOL_SOCKET
;
5267 cmsg
->cmsg_type
= SCM_RIGHTS
;
5268 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
5269 memcpy(CMSG_DATA(cmsg
), &fd
, sizeof(int));
5271 mh
.msg_controllen
= CMSG_SPACE(sizeof(int));
5272 if (sendmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| flags
) < 0)
5278 int receive_one_fd(int transport_fd
, int flags
) {
5280 struct cmsghdr cmsghdr
;
5281 uint8_t buf
[CMSG_SPACE(sizeof(int))];
5283 struct msghdr mh
= {
5284 .msg_control
= &control
,
5285 .msg_controllen
= sizeof(control
),
5287 struct cmsghdr
*cmsg
, *found
= NULL
;
5289 assert(transport_fd
>= 0);
5292 * Receive a single FD via @transport_fd. We don't care for
5293 * the transport-type. We retrieve a single FD at most, so for
5294 * packet-based transports, the caller must ensure to send
5295 * only a single FD per packet. This is best used in
5296 * combination with send_one_fd().
5299 if (recvmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| MSG_CMSG_CLOEXEC
| flags
) < 0)
5302 CMSG_FOREACH(cmsg
, &mh
) {
5303 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
5304 cmsg
->cmsg_type
== SCM_RIGHTS
&&
5305 cmsg
->cmsg_len
== CMSG_LEN(sizeof(int))) {
5313 cmsg_close_all(&mh
);
5317 return *(int*) CMSG_DATA(found
);
5320 void nop_signal_handler(int sig
) {
5325 puts(PACKAGE_STRING
"\n"
5330 bool fdname_is_valid(const char *s
) {
5333 /* Validates a name for $LISTEN_FDNAMES. We basically allow
5334 * everything ASCII that's not a control character. Also, as
5335 * special exception the ":" character is not allowed, as we
5336 * use that as field separator in $LISTEN_FDNAMES.
5338 * Note that the empty string is explicitly allowed
5339 * here. However, we limit the length of the names to 255
5345 for (p
= s
; *p
; p
++) {
5357 bool oom_score_adjust_is_valid(int oa
) {
5358 return oa
>= OOM_SCORE_ADJ_MIN
&& oa
<= OOM_SCORE_ADJ_MAX
;