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>
44 #include <sys/ioctl.h>
46 #include <sys/mount.h>
47 #include <sys/personality.h>
48 #include <sys/prctl.h>
49 #include <sys/resource.h>
51 #include <sys/statvfs.h>
53 #include <sys/types.h>
54 #include <sys/utsname.h>
57 #include <sys/xattr.h>
61 /* When we include libgen.h because we need dirname() we immediately
62 * undefine basename() since libgen.h defines it as a macro to the
63 * POSIX version which is really broken. We prefer GNU basename(). */
67 #ifdef HAVE_SYS_AUXV_H
71 /* We include linux/fs.h as last of the system headers, as it
72 * otherwise conflicts with sys/mount.h. Yay, Linux is great! */
77 #include "device-nodes.h"
80 #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"
100 #include "user-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 int safe_atou(const char *s
, unsigned *ret_u
) {
179 l
= strtoul(s
, &x
, 0);
181 if (!x
|| x
== s
|| *x
|| errno
)
182 return errno
> 0 ? -errno
: -EINVAL
;
184 if ((unsigned long) (unsigned) l
!= l
)
187 *ret_u
= (unsigned) l
;
191 int safe_atoi(const char *s
, int *ret_i
) {
199 l
= strtol(s
, &x
, 0);
201 if (!x
|| x
== s
|| *x
|| errno
)
202 return errno
> 0 ? -errno
: -EINVAL
;
204 if ((long) (int) l
!= l
)
211 int safe_atou8(const char *s
, uint8_t *ret
) {
219 l
= strtoul(s
, &x
, 0);
221 if (!x
|| x
== s
|| *x
|| errno
)
222 return errno
> 0 ? -errno
: -EINVAL
;
224 if ((unsigned long) (uint8_t) l
!= l
)
231 int safe_atou16(const char *s
, uint16_t *ret
) {
239 l
= strtoul(s
, &x
, 0);
241 if (!x
|| x
== s
|| *x
|| errno
)
242 return errno
> 0 ? -errno
: -EINVAL
;
244 if ((unsigned long) (uint16_t) l
!= l
)
251 int safe_atoi16(const char *s
, int16_t *ret
) {
259 l
= strtol(s
, &x
, 0);
261 if (!x
|| x
== s
|| *x
|| errno
)
262 return errno
> 0 ? -errno
: -EINVAL
;
264 if ((long) (int16_t) l
!= l
)
271 int safe_atollu(const char *s
, long long unsigned *ret_llu
) {
273 unsigned long long l
;
279 l
= strtoull(s
, &x
, 0);
281 if (!x
|| x
== s
|| *x
|| errno
)
282 return errno
? -errno
: -EINVAL
;
288 int safe_atolli(const char *s
, long long int *ret_lli
) {
296 l
= strtoll(s
, &x
, 0);
298 if (!x
|| x
== s
|| *x
|| errno
)
299 return errno
? -errno
: -EINVAL
;
305 int safe_atod(const char *s
, double *ret_d
) {
313 loc
= newlocale(LC_NUMERIC_MASK
, "C", (locale_t
) 0);
314 if (loc
== (locale_t
) 0)
318 d
= strtod_l(s
, &x
, loc
);
320 if (!x
|| x
== s
|| *x
|| errno
) {
322 return errno
? -errno
: -EINVAL
;
331 int fchmod_umask(int fd
, mode_t m
) {
336 r
= fchmod(fd
, m
& (~u
)) < 0 ? -errno
: 0;
342 int readlinkat_malloc(int fd
, const char *p
, char **ret
) {
357 n
= readlinkat(fd
, p
, c
, l
-1);
364 if ((size_t) n
< l
-1) {
375 int readlink_malloc(const char *p
, char **ret
) {
376 return readlinkat_malloc(AT_FDCWD
, p
, ret
);
379 int readlink_value(const char *p
, char **ret
) {
380 _cleanup_free_
char *link
= NULL
;
384 r
= readlink_malloc(p
, &link
);
388 value
= basename(link
);
392 value
= strdup(value
);
401 int readlink_and_make_absolute(const char *p
, char **r
) {
402 _cleanup_free_
char *target
= NULL
;
409 j
= readlink_malloc(p
, &target
);
413 k
= file_in_same_dir(p
, target
);
421 int readlink_and_canonicalize(const char *p
, char **r
) {
428 j
= readlink_and_make_absolute(p
, &t
);
432 s
= canonicalize_file_name(t
);
439 path_kill_slashes(*r
);
444 char *file_in_same_dir(const char *path
, const char *filename
) {
451 /* This removes the last component of path and appends
452 * filename, unless the latter is absolute anyway or the
455 if (path_is_absolute(filename
))
456 return strdup(filename
);
458 e
= strrchr(path
, '/');
460 return strdup(filename
);
462 k
= strlen(filename
);
463 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
467 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
471 int rmdir_parents(const char *path
, const char *stop
) {
480 /* Skip trailing slashes */
481 while (l
> 0 && path
[l
-1] == '/')
487 /* Skip last component */
488 while (l
> 0 && path
[l
-1] != '/')
491 /* Skip trailing slashes */
492 while (l
> 0 && path
[l
-1] == '/')
498 if (!(t
= strndup(path
, l
)))
501 if (path_startswith(stop
, t
)) {
517 char hexchar(int x
) {
518 static const char table
[16] = "0123456789abcdef";
520 return table
[x
& 15];
523 int unhexchar(char c
) {
525 if (c
>= '0' && c
<= '9')
528 if (c
>= 'a' && c
<= 'f')
531 if (c
>= 'A' && c
<= 'F')
537 char *hexmem(const void *p
, size_t l
) {
541 z
= r
= malloc(l
* 2 + 1);
545 for (x
= p
; x
< (const uint8_t*) p
+ l
; x
++) {
546 *(z
++) = hexchar(*x
>> 4);
547 *(z
++) = hexchar(*x
& 15);
554 int unhexmem(const char *p
, size_t l
, void **mem
, size_t *len
) {
555 _cleanup_free_
uint8_t *r
= NULL
;
563 z
= r
= malloc((l
+ 1) / 2 + 1);
567 for (x
= p
; x
< p
+ l
; x
+= 2) {
573 else if (x
+1 < p
+ l
) {
580 *(z
++) = (uint8_t) a
<< 4 | (uint8_t) b
;
592 /* https://tools.ietf.org/html/rfc4648#section-6
593 * Notice that base32hex differs from base32 in the alphabet it uses.
594 * The distinction is that the base32hex representation preserves the
595 * order of the underlying data when compared as bytestrings, this is
596 * useful when representing NSEC3 hashes, as one can then verify the
597 * order of hashes directly from their representation. */
598 char base32hexchar(int x
) {
599 static const char table
[32] = "0123456789"
600 "ABCDEFGHIJKLMNOPQRSTUV";
602 return table
[x
& 31];
605 int unbase32hexchar(char c
) {
608 if (c
>= '0' && c
<= '9')
611 offset
= '9' - '0' + 1;
613 if (c
>= 'A' && c
<= 'V')
614 return c
- 'A' + offset
;
619 char *base32hexmem(const void *p
, size_t l
, bool padding
) {
625 /* five input bytes makes eight output bytes, padding is added so we must round up */
626 len
= 8 * (l
+ 4) / 5;
628 /* same, but round down as there is no padding */
647 z
= r
= malloc(len
+ 1);
651 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 5) * 5; x
+= 5) {
652 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ
653 x[3] == QQQQQQQQ; x[4] == WWWWWWWW */
654 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
655 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
656 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
657 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
658 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
659 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
660 *(z
++) = base32hexchar((x
[3] & 3) << 3 | x
[4] >> 5); /* 000QQWWW */
661 *(z
++) = base32hexchar((x
[4] & 31)); /* 000WWWWW */
666 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
667 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
668 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
669 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
670 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
671 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
672 *(z
++) = base32hexchar((x
[3] & 3) << 3); /* 000QQ000 */
679 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
680 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
681 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
682 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
683 *(z
++) = base32hexchar((x
[2] & 15) << 1); /* 000ZZZZ0 */
693 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
694 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
695 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
696 *(z
++) = base32hexchar((x
[1] & 1) << 4); /* 000Y0000 */
707 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
708 *(z
++) = base32hexchar((x
[0] & 7) << 2); /* 000XXX00 */
725 int unbase32hexmem(const char *p
, size_t l
, bool padding
, void **mem
, size_t *_len
) {
726 _cleanup_free_
uint8_t *r
= NULL
;
727 int a
, b
, c
, d
, e
, f
, g
, h
;
735 /* padding ensures any base32hex input has input divisible by 8 */
736 if (padding
&& l
% 8 != 0)
740 /* strip the padding */
741 while (l
> 0 && p
[l
- 1] == '=' && pad
< 7) {
747 /* a group of eight input bytes needs five output bytes, in case of
748 padding we need to add some extra bytes */
770 z
= r
= malloc(len
+ 1);
774 for (x
= p
; x
< p
+ (l
/ 8) * 8; x
+= 8) {
775 /* a == 000XXXXX; b == 000YYYYY; c == 000ZZZZZ; d == 000WWWWW
776 e == 000SSSSS; f == 000QQQQQ; g == 000VVVVV; h == 000RRRRR */
777 a
= unbase32hexchar(x
[0]);
781 b
= unbase32hexchar(x
[1]);
785 c
= unbase32hexchar(x
[2]);
789 d
= unbase32hexchar(x
[3]);
793 e
= unbase32hexchar(x
[4]);
797 f
= unbase32hexchar(x
[5]);
801 g
= unbase32hexchar(x
[6]);
805 h
= unbase32hexchar(x
[7]);
809 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
810 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
811 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
812 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
813 *(z
++) = (uint8_t) g
<< 5 | (uint8_t) h
; /* VVVRRRRR */
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]);
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 */
857 a
= unbase32hexchar(x
[0]);
861 b
= unbase32hexchar(x
[1]);
865 c
= unbase32hexchar(x
[2]);
869 d
= unbase32hexchar(x
[3]);
873 e
= unbase32hexchar(x
[4]);
881 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
882 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
883 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
887 a
= unbase32hexchar(x
[0]);
891 b
= unbase32hexchar(x
[1]);
895 c
= unbase32hexchar(x
[2]);
899 d
= unbase32hexchar(x
[3]);
907 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
908 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
912 a
= unbase32hexchar(x
[0]);
916 b
= unbase32hexchar(x
[1]);
924 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
942 /* https://tools.ietf.org/html/rfc4648#section-4 */
943 char base64char(int x
) {
944 static const char table
[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
945 "abcdefghijklmnopqrstuvwxyz"
947 return table
[x
& 63];
950 int unbase64char(char c
) {
953 if (c
>= 'A' && c
<= 'Z')
956 offset
= 'Z' - 'A' + 1;
958 if (c
>= 'a' && c
<= 'z')
959 return c
- 'a' + offset
;
961 offset
+= 'z' - 'a' + 1;
963 if (c
>= '0' && c
<= '9')
964 return c
- '0' + offset
;
966 offset
+= '9' - '0' + 1;
979 char *base64mem(const void *p
, size_t l
) {
983 /* three input bytes makes four output bytes, padding is added so we must round up */
984 z
= r
= malloc(4 * (l
+ 2) / 3 + 1);
988 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 3) * 3; x
+= 3) {
989 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ */
990 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
991 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
992 *(z
++) = base64char((x
[1] & 15) << 2 | x
[2] >> 6); /* 00YYYYZZ */
993 *(z
++) = base64char(x
[2] & 63); /* 00ZZZZZZ */
998 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
999 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1000 *(z
++) = base64char((x
[1] & 15) << 2); /* 00YYYY00 */
1005 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1006 *(z
++) = base64char((x
[0] & 3) << 4); /* 00XX0000 */
1017 int unbase64mem(const char *p
, size_t l
, void **mem
, size_t *_len
) {
1018 _cleanup_free_
uint8_t *r
= NULL
;
1026 /* padding ensures any base63 input has input divisible by 4 */
1030 /* strip the padding */
1031 if (l
> 0 && p
[l
- 1] == '=')
1033 if (l
> 0 && p
[l
- 1] == '=')
1036 /* a group of four input bytes needs three output bytes, in case of
1037 padding we need to add two or three extra bytes */
1038 len
= (l
/ 4) * 3 + (l
% 4 ? (l
% 4) - 1 : 0);
1040 z
= r
= malloc(len
+ 1);
1044 for (x
= p
; x
< p
+ (l
/ 4) * 4; x
+= 4) {
1045 /* a == 00XXXXXX; b == 00YYYYYY; c == 00ZZZZZZ; d == 00WWWWWW */
1046 a
= unbase64char(x
[0]);
1050 b
= unbase64char(x
[1]);
1054 c
= unbase64char(x
[2]);
1058 d
= unbase64char(x
[3]);
1062 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1063 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1064 *(z
++) = (uint8_t) c
<< 6 | (uint8_t) d
; /* ZZWWWWWW */
1069 a
= unbase64char(x
[0]);
1073 b
= unbase64char(x
[1]);
1077 c
= unbase64char(x
[2]);
1085 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1086 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1090 a
= unbase64char(x
[0]);
1094 b
= unbase64char(x
[1]);
1102 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) (b
>> 4); /* XXXXXXYY */
1121 char octchar(int x
) {
1122 return '0' + (x
& 7);
1125 int unoctchar(char c
) {
1127 if (c
>= '0' && c
<= '7')
1133 char decchar(int x
) {
1134 return '0' + (x
% 10);
1137 int undecchar(char c
) {
1139 if (c
>= '0' && c
<= '9')
1145 _pure_
static bool hidden_file_allow_backup(const char *filename
) {
1149 filename
[0] == '.' ||
1150 streq(filename
, "lost+found") ||
1151 streq(filename
, "aquota.user") ||
1152 streq(filename
, "aquota.group") ||
1153 endswith(filename
, ".rpmnew") ||
1154 endswith(filename
, ".rpmsave") ||
1155 endswith(filename
, ".rpmorig") ||
1156 endswith(filename
, ".dpkg-old") ||
1157 endswith(filename
, ".dpkg-new") ||
1158 endswith(filename
, ".dpkg-tmp") ||
1159 endswith(filename
, ".dpkg-dist") ||
1160 endswith(filename
, ".dpkg-bak") ||
1161 endswith(filename
, ".dpkg-backup") ||
1162 endswith(filename
, ".dpkg-remove") ||
1163 endswith(filename
, ".swp");
1166 bool hidden_file(const char *filename
) {
1169 if (endswith(filename
, "~"))
1172 return hidden_file_allow_backup(filename
);
1175 bool fstype_is_network(const char *fstype
) {
1176 static const char table
[] =
1191 x
= startswith(fstype
, "fuse.");
1195 return nulstr_contains(table
, fstype
);
1198 int parse_size(const char *t
, uint64_t base
, uint64_t *size
) {
1200 /* Soo, sometimes we want to parse IEC binary suffixes, and
1201 * sometimes SI decimal suffixes. This function can parse
1202 * both. Which one is the right way depends on the
1203 * context. Wikipedia suggests that SI is customary for
1204 * hardware metrics and network speeds, while IEC is
1205 * customary for most data sizes used by software and volatile
1206 * (RAM) memory. Hence be careful which one you pick!
1208 * In either case we use just K, M, G as suffix, and not Ki,
1209 * Mi, Gi or so (as IEC would suggest). That's because that's
1210 * frickin' ugly. But this means you really need to make sure
1211 * to document which base you are parsing when you use this
1216 unsigned long long factor
;
1219 static const struct table iec
[] = {
1220 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1221 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1222 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
1223 { "G", 1024ULL*1024ULL*1024ULL },
1224 { "M", 1024ULL*1024ULL },
1230 static const struct table si
[] = {
1231 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1232 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1233 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
1234 { "G", 1000ULL*1000ULL*1000ULL },
1235 { "M", 1000ULL*1000ULL },
1241 const struct table
*table
;
1243 unsigned long long r
= 0;
1244 unsigned n_entries
, start_pos
= 0;
1247 assert(base
== 1000 || base
== 1024);
1252 n_entries
= ELEMENTSOF(si
);
1255 n_entries
= ELEMENTSOF(iec
);
1260 unsigned long long l
, tmp
;
1265 p
+= strspn(p
, WHITESPACE
);
1270 l
= strtoull(p
, &e
, 10);
1279 /* strtoull() itself would accept space/+/- */
1280 if (*e
>= '0' && *e
<= '9') {
1281 unsigned long long l2
;
1284 l2
= strtoull(e
, &e2
, 10);
1288 /* Ignore failure. E.g. 10.M is valid */
1295 e
+= strspn(e
, WHITESPACE
);
1297 for (i
= start_pos
; i
< n_entries
; i
++)
1298 if (startswith(e
, table
[i
].suffix
))
1304 if (l
+ (frac
> 0) > ULLONG_MAX
/ table
[i
].factor
)
1307 tmp
= l
* table
[i
].factor
+ (unsigned long long) (frac
* table
[i
].factor
);
1308 if (tmp
> ULLONG_MAX
- r
)
1312 if ((unsigned long long) (uint64_t) r
!= r
)
1315 p
= e
+ strlen(table
[i
].suffix
);
1326 bool is_device_path(const char *path
) {
1328 /* Returns true on paths that refer to a device, either in
1329 * sysfs or in /dev */
1332 path_startswith(path
, "/dev/") ||
1333 path_startswith(path
, "/sys/");
1336 int dir_is_empty(const char *path
) {
1337 _cleanup_closedir_
DIR *d
;
1344 FOREACH_DIRENT(de
, d
, return -errno
)
1350 char* dirname_malloc(const char *path
) {
1351 char *d
, *dir
, *dir2
;
1368 void rename_process(const char name
[8]) {
1371 /* This is a like a poor man's setproctitle(). It changes the
1372 * comm field, argv[0], and also the glibc's internally used
1373 * name of the process. For the first one a limit of 16 chars
1374 * applies, to the second one usually one of 10 (i.e. length
1375 * of "/sbin/init"), to the third one one of 7 (i.e. length of
1376 * "systemd"). If you pass a longer string it will be
1379 prctl(PR_SET_NAME
, name
);
1381 if (program_invocation_name
)
1382 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
1384 if (saved_argc
> 0) {
1388 strncpy(saved_argv
[0], name
, strlen(saved_argv
[0]));
1390 for (i
= 1; i
< saved_argc
; i
++) {
1394 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
1399 bool is_fs_type(const struct statfs
*s
, statfs_f_type_t magic_value
) {
1401 assert_cc(sizeof(statfs_f_type_t
) >= sizeof(s
->f_type
));
1403 return F_TYPE_EQUAL(s
->f_type
, magic_value
);
1406 int fd_check_fstype(int fd
, statfs_f_type_t magic_value
) {
1409 if (fstatfs(fd
, &s
) < 0)
1412 return is_fs_type(&s
, magic_value
);
1415 int path_check_fstype(const char *path
, statfs_f_type_t magic_value
) {
1416 _cleanup_close_
int fd
= -1;
1418 fd
= open(path
, O_RDONLY
);
1422 return fd_check_fstype(fd
, magic_value
);
1425 bool is_temporary_fs(const struct statfs
*s
) {
1426 return is_fs_type(s
, TMPFS_MAGIC
) ||
1427 is_fs_type(s
, RAMFS_MAGIC
);
1430 int fd_is_temporary_fs(int fd
) {
1433 if (fstatfs(fd
, &s
) < 0)
1436 return is_temporary_fs(&s
);
1439 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
1442 /* Under the assumption that we are running privileged we
1443 * first change the access mode and only then hand out
1444 * ownership to avoid a window where access is too open. */
1446 if (mode
!= MODE_INVALID
)
1447 if (chmod(path
, mode
) < 0)
1450 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
1451 if (chown(path
, uid
, gid
) < 0)
1457 int fchmod_and_fchown(int fd
, mode_t mode
, uid_t uid
, gid_t gid
) {
1460 /* Under the assumption that we are running privileged we
1461 * first change the access mode and only then hand out
1462 * ownership to avoid a window where access is too open. */
1464 if (mode
!= MODE_INVALID
)
1465 if (fchmod(fd
, mode
) < 0)
1468 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
1469 if (fchown(fd
, uid
, gid
) < 0)
1475 int files_same(const char *filea
, const char *fileb
) {
1478 if (stat(filea
, &a
) < 0)
1481 if (stat(fileb
, &b
) < 0)
1484 return a
.st_dev
== b
.st_dev
&&
1485 a
.st_ino
== b
.st_ino
;
1488 int running_in_chroot(void) {
1491 ret
= files_same("/proc/1/root", "/");
1498 int touch_file(const char *path
, bool parents
, usec_t stamp
, uid_t uid
, gid_t gid
, mode_t mode
) {
1499 _cleanup_close_
int fd
;
1505 mkdir_parents(path
, 0755);
1507 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, mode
> 0 ? mode
: 0644);
1512 r
= fchmod(fd
, mode
);
1517 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
) {
1518 r
= fchown(fd
, uid
, gid
);
1523 if (stamp
!= USEC_INFINITY
) {
1524 struct timespec ts
[2];
1526 timespec_store(&ts
[0], stamp
);
1528 r
= futimens(fd
, ts
);
1530 r
= futimens(fd
, NULL
);
1537 int touch(const char *path
) {
1538 return touch_file(path
, false, USEC_INFINITY
, UID_INVALID
, GID_INVALID
, 0);
1541 static char *unquote(const char *s
, const char* quotes
) {
1545 /* This is rather stupid, simply removes the heading and
1546 * trailing quotes if there is one. Doesn't care about
1547 * escaping or anything.
1549 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
1555 if (strchr(quotes
, s
[0]) && s
[l
-1] == s
[0])
1556 return strndup(s
+1, l
-2);
1561 noreturn
void freeze(void) {
1563 /* Make sure nobody waits for us on a socket anymore */
1564 close_all_fds(NULL
, 0);
1572 bool null_or_empty(struct stat
*st
) {
1575 if (S_ISREG(st
->st_mode
) && st
->st_size
<= 0)
1578 if (S_ISCHR(st
->st_mode
) || S_ISBLK(st
->st_mode
))
1584 int null_or_empty_path(const char *fn
) {
1589 if (stat(fn
, &st
) < 0)
1592 return null_or_empty(&st
);
1595 int null_or_empty_fd(int fd
) {
1600 if (fstat(fd
, &st
) < 0)
1603 return null_or_empty(&st
);
1606 DIR *xopendirat(int fd
, const char *name
, int flags
) {
1610 assert(!(flags
& O_CREAT
));
1612 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
1625 static char *tag_to_udev_node(const char *tagvalue
, const char *by
) {
1626 _cleanup_free_
char *t
= NULL
, *u
= NULL
;
1629 u
= unquote(tagvalue
, QUOTES
);
1633 enc_len
= strlen(u
) * 4 + 1;
1634 t
= new(char, enc_len
);
1638 if (encode_devnode_name(u
, t
, enc_len
) < 0)
1641 return strjoin("/dev/disk/by-", by
, "/", t
, NULL
);
1644 char *fstab_node_to_udev_node(const char *p
) {
1647 if (startswith(p
, "LABEL="))
1648 return tag_to_udev_node(p
+6, "label");
1650 if (startswith(p
, "UUID="))
1651 return tag_to_udev_node(p
+5, "uuid");
1653 if (startswith(p
, "PARTUUID="))
1654 return tag_to_udev_node(p
+9, "partuuid");
1656 if (startswith(p
, "PARTLABEL="))
1657 return tag_to_udev_node(p
+10, "partlabel");
1662 bool dirent_is_file(const struct dirent
*de
) {
1665 if (hidden_file(de
->d_name
))
1668 if (de
->d_type
!= DT_REG
&&
1669 de
->d_type
!= DT_LNK
&&
1670 de
->d_type
!= DT_UNKNOWN
)
1676 bool dirent_is_file_with_suffix(const struct dirent
*de
, const char *suffix
) {
1679 if (de
->d_type
!= DT_REG
&&
1680 de
->d_type
!= DT_LNK
&&
1681 de
->d_type
!= DT_UNKNOWN
)
1684 if (hidden_file_allow_backup(de
->d_name
))
1687 return endswith(de
->d_name
, suffix
);
1690 static int do_execute(char **directories
, usec_t timeout
, char *argv
[]) {
1691 _cleanup_hashmap_free_free_ Hashmap
*pids
= NULL
;
1692 _cleanup_set_free_free_ Set
*seen
= NULL
;
1695 /* We fork this all off from a child process so that we can
1696 * somewhat cleanly make use of SIGALRM to set a time limit */
1698 (void) reset_all_signal_handlers();
1699 (void) reset_signal_mask();
1701 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
1703 pids
= hashmap_new(NULL
);
1707 seen
= set_new(&string_hash_ops
);
1711 STRV_FOREACH(directory
, directories
) {
1712 _cleanup_closedir_
DIR *d
;
1715 d
= opendir(*directory
);
1717 if (errno
== ENOENT
)
1720 return log_error_errno(errno
, "Failed to open directory %s: %m", *directory
);
1723 FOREACH_DIRENT(de
, d
, break) {
1724 _cleanup_free_
char *path
= NULL
;
1728 if (!dirent_is_file(de
))
1731 if (set_contains(seen
, de
->d_name
)) {
1732 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory
, de
->d_name
);
1736 r
= set_put_strdup(seen
, de
->d_name
);
1740 path
= strjoin(*directory
, "/", de
->d_name
, NULL
);
1744 if (null_or_empty_path(path
)) {
1745 log_debug("%s is empty (a mask).", path
);
1751 log_error_errno(errno
, "Failed to fork: %m");
1753 } else if (pid
== 0) {
1756 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
1766 return log_error_errno(errno
, "Failed to execute %s: %m", path
);
1769 log_debug("Spawned %s as " PID_FMT
".", path
, pid
);
1771 r
= hashmap_put(pids
, UINT_TO_PTR(pid
), path
);
1778 /* Abort execution of this process after the timout. We simply
1779 * rely on SIGALRM as default action terminating the process,
1780 * and turn on alarm(). */
1782 if (timeout
!= USEC_INFINITY
)
1783 alarm((timeout
+ USEC_PER_SEC
- 1) / USEC_PER_SEC
);
1785 while (!hashmap_isempty(pids
)) {
1786 _cleanup_free_
char *path
= NULL
;
1789 pid
= PTR_TO_UINT(hashmap_first_key(pids
));
1792 path
= hashmap_remove(pids
, UINT_TO_PTR(pid
));
1795 wait_for_terminate_and_warn(path
, pid
, true);
1801 void execute_directories(const char* const* directories
, usec_t timeout
, char *argv
[]) {
1805 char **dirs
= (char**) directories
;
1807 assert(!strv_isempty(dirs
));
1809 name
= basename(dirs
[0]);
1810 assert(!isempty(name
));
1812 /* Executes all binaries in the directories in parallel and waits
1813 * for them to finish. Optionally a timeout is applied. If a file
1814 * with the same name exists in more than one directory, the
1815 * earliest one wins. */
1817 executor_pid
= fork();
1818 if (executor_pid
< 0) {
1819 log_error_errno(errno
, "Failed to fork: %m");
1822 } else if (executor_pid
== 0) {
1823 r
= do_execute(dirs
, timeout
, argv
);
1824 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
1827 wait_for_terminate_and_warn(name
, executor_pid
, true);
1830 bool plymouth_running(void) {
1831 return access("/run/plymouth/pid", F_OK
) >= 0;
1834 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
1843 r
= tempfn_xxxxxx(path
, NULL
, &t
);
1847 fd
= mkostemp_safe(t
, O_WRONLY
|O_CLOEXEC
);
1853 f
= fdopen(fd
, "we");
1867 int symlink_atomic(const char *from
, const char *to
) {
1868 _cleanup_free_
char *t
= NULL
;
1874 r
= tempfn_random(to
, NULL
, &t
);
1878 if (symlink(from
, t
) < 0)
1881 if (rename(t
, to
) < 0) {
1889 int symlink_idempotent(const char *from
, const char *to
) {
1890 _cleanup_free_
char *p
= NULL
;
1896 if (symlink(from
, to
) < 0) {
1897 if (errno
!= EEXIST
)
1900 r
= readlink_malloc(to
, &p
);
1904 if (!streq(p
, from
))
1911 int mknod_atomic(const char *path
, mode_t mode
, dev_t dev
) {
1912 _cleanup_free_
char *t
= NULL
;
1917 r
= tempfn_random(path
, NULL
, &t
);
1921 if (mknod(t
, mode
, dev
) < 0)
1924 if (rename(t
, path
) < 0) {
1932 int mkfifo_atomic(const char *path
, mode_t mode
) {
1933 _cleanup_free_
char *t
= NULL
;
1938 r
= tempfn_random(path
, NULL
, &t
);
1942 if (mkfifo(t
, mode
) < 0)
1945 if (rename(t
, path
) < 0) {
1953 bool display_is_local(const char *display
) {
1957 display
[0] == ':' &&
1958 display
[1] >= '0' &&
1962 int socket_from_display(const char *display
, char **path
) {
1969 if (!display_is_local(display
))
1972 k
= strspn(display
+1, "0123456789");
1974 f
= new(char, strlen("/tmp/.X11-unix/X") + k
+ 1);
1978 c
= stpcpy(f
, "/tmp/.X11-unix/X");
1979 memcpy(c
, display
+1, k
);
1987 int glob_exists(const char *path
) {
1988 _cleanup_globfree_ glob_t g
= {};
1994 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
1996 if (k
== GLOB_NOMATCH
)
1998 else if (k
== GLOB_NOSPACE
)
2001 return !strv_isempty(g
.gl_pathv
);
2003 return errno
? -errno
: -EIO
;
2006 int glob_extend(char ***strv
, const char *path
) {
2007 _cleanup_globfree_ glob_t g
= {};
2012 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
2014 if (k
== GLOB_NOMATCH
)
2016 else if (k
== GLOB_NOSPACE
)
2018 else if (k
!= 0 || strv_isempty(g
.gl_pathv
))
2019 return errno
? -errno
: -EIO
;
2021 STRV_FOREACH(p
, g
.gl_pathv
) {
2022 k
= strv_extend(strv
, *p
);
2030 int dirent_ensure_type(DIR *d
, struct dirent
*de
) {
2036 if (de
->d_type
!= DT_UNKNOWN
)
2039 if (fstatat(dirfd(d
), de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
2043 S_ISREG(st
.st_mode
) ? DT_REG
:
2044 S_ISDIR(st
.st_mode
) ? DT_DIR
:
2045 S_ISLNK(st
.st_mode
) ? DT_LNK
:
2046 S_ISFIFO(st
.st_mode
) ? DT_FIFO
:
2047 S_ISSOCK(st
.st_mode
) ? DT_SOCK
:
2048 S_ISCHR(st
.st_mode
) ? DT_CHR
:
2049 S_ISBLK(st
.st_mode
) ? DT_BLK
:
2055 int get_files_in_directory(const char *path
, char ***list
) {
2056 _cleanup_closedir_
DIR *d
= NULL
;
2057 size_t bufsize
= 0, n
= 0;
2058 _cleanup_strv_free_
char **l
= NULL
;
2062 /* Returns all files in a directory in *list, and the number
2063 * of files as return value. If list is NULL returns only the
2075 if (!de
&& errno
!= 0)
2080 dirent_ensure_type(d
, de
);
2082 if (!dirent_is_file(de
))
2086 /* one extra slot is needed for the terminating NULL */
2087 if (!GREEDY_REALLOC(l
, bufsize
, n
+ 2))
2090 l
[n
] = strdup(de
->d_name
);
2101 l
= NULL
; /* avoid freeing */
2107 bool is_main_thread(void) {
2108 static thread_local
int cached
= 0;
2110 if (_unlikely_(cached
== 0))
2111 cached
= getpid() == gettid() ? 1 : -1;
2116 int block_get_whole_disk(dev_t d
, dev_t
*ret
) {
2123 /* If it has a queue this is good enough for us */
2124 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", major(d
), minor(d
)) < 0)
2127 r
= access(p
, F_OK
);
2135 /* If it is a partition find the originating device */
2136 if (asprintf(&p
, "/sys/dev/block/%u:%u/partition", major(d
), minor(d
)) < 0)
2139 r
= access(p
, F_OK
);
2145 /* Get parent dev_t */
2146 if (asprintf(&p
, "/sys/dev/block/%u:%u/../dev", major(d
), minor(d
)) < 0)
2149 r
= read_one_line_file(p
, &s
);
2155 r
= sscanf(s
, "%u:%u", &m
, &n
);
2161 /* Only return this if it is really good enough for us. */
2162 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", m
, n
) < 0)
2165 r
= access(p
, F_OK
);
2169 *ret
= makedev(m
, n
);
2176 static const char *const ioprio_class_table
[] = {
2177 [IOPRIO_CLASS_NONE
] = "none",
2178 [IOPRIO_CLASS_RT
] = "realtime",
2179 [IOPRIO_CLASS_BE
] = "best-effort",
2180 [IOPRIO_CLASS_IDLE
] = "idle"
2183 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, INT_MAX
);
2185 static const char *const sigchld_code_table
[] = {
2186 [CLD_EXITED
] = "exited",
2187 [CLD_KILLED
] = "killed",
2188 [CLD_DUMPED
] = "dumped",
2189 [CLD_TRAPPED
] = "trapped",
2190 [CLD_STOPPED
] = "stopped",
2191 [CLD_CONTINUED
] = "continued",
2194 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
2196 static const char *const log_facility_unshifted_table
[LOG_NFACILITIES
] = {
2197 [LOG_FAC(LOG_KERN
)] = "kern",
2198 [LOG_FAC(LOG_USER
)] = "user",
2199 [LOG_FAC(LOG_MAIL
)] = "mail",
2200 [LOG_FAC(LOG_DAEMON
)] = "daemon",
2201 [LOG_FAC(LOG_AUTH
)] = "auth",
2202 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
2203 [LOG_FAC(LOG_LPR
)] = "lpr",
2204 [LOG_FAC(LOG_NEWS
)] = "news",
2205 [LOG_FAC(LOG_UUCP
)] = "uucp",
2206 [LOG_FAC(LOG_CRON
)] = "cron",
2207 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
2208 [LOG_FAC(LOG_FTP
)] = "ftp",
2209 [LOG_FAC(LOG_LOCAL0
)] = "local0",
2210 [LOG_FAC(LOG_LOCAL1
)] = "local1",
2211 [LOG_FAC(LOG_LOCAL2
)] = "local2",
2212 [LOG_FAC(LOG_LOCAL3
)] = "local3",
2213 [LOG_FAC(LOG_LOCAL4
)] = "local4",
2214 [LOG_FAC(LOG_LOCAL5
)] = "local5",
2215 [LOG_FAC(LOG_LOCAL6
)] = "local6",
2216 [LOG_FAC(LOG_LOCAL7
)] = "local7"
2219 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted
, int, LOG_FAC(~0));
2221 bool log_facility_unshifted_is_valid(int facility
) {
2222 return facility
>= 0 && facility
<= LOG_FAC(~0);
2225 static const char *const log_level_table
[] = {
2226 [LOG_EMERG
] = "emerg",
2227 [LOG_ALERT
] = "alert",
2228 [LOG_CRIT
] = "crit",
2230 [LOG_WARNING
] = "warning",
2231 [LOG_NOTICE
] = "notice",
2232 [LOG_INFO
] = "info",
2233 [LOG_DEBUG
] = "debug"
2236 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level
, int, LOG_DEBUG
);
2238 bool log_level_is_valid(int level
) {
2239 return level
>= 0 && level
<= LOG_DEBUG
;
2242 static const char* const sched_policy_table
[] = {
2243 [SCHED_OTHER
] = "other",
2244 [SCHED_BATCH
] = "batch",
2245 [SCHED_IDLE
] = "idle",
2246 [SCHED_FIFO
] = "fifo",
2250 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);
2252 static const char* const rlimit_table
[_RLIMIT_MAX
] = {
2253 [RLIMIT_CPU
] = "LimitCPU",
2254 [RLIMIT_FSIZE
] = "LimitFSIZE",
2255 [RLIMIT_DATA
] = "LimitDATA",
2256 [RLIMIT_STACK
] = "LimitSTACK",
2257 [RLIMIT_CORE
] = "LimitCORE",
2258 [RLIMIT_RSS
] = "LimitRSS",
2259 [RLIMIT_NOFILE
] = "LimitNOFILE",
2260 [RLIMIT_AS
] = "LimitAS",
2261 [RLIMIT_NPROC
] = "LimitNPROC",
2262 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
2263 [RLIMIT_LOCKS
] = "LimitLOCKS",
2264 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
2265 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
2266 [RLIMIT_NICE
] = "LimitNICE",
2267 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
2268 [RLIMIT_RTTIME
] = "LimitRTTIME"
2271 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
2273 bool kexec_loaded(void) {
2274 bool loaded
= false;
2277 if (read_one_line_file("/sys/kernel/kexec_loaded", &s
) >= 0) {
2285 int prot_from_flags(int flags
) {
2287 switch (flags
& O_ACCMODE
) {
2296 return PROT_READ
|PROT_WRITE
;
2303 char *format_bytes(char *buf
, size_t l
, uint64_t t
) {
2306 static const struct {
2310 { "E", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2311 { "P", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2312 { "T", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2313 { "G", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2314 { "M", UINT64_C(1024)*UINT64_C(1024) },
2315 { "K", UINT64_C(1024) },
2318 if (t
== (uint64_t) -1)
2321 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
2323 if (t
>= table
[i
].factor
) {
2325 "%" PRIu64
".%" PRIu64
"%s",
2326 t
/ table
[i
].factor
,
2327 ((t
*UINT64_C(10)) / table
[i
].factor
) % UINT64_C(10),
2334 snprintf(buf
, l
, "%" PRIu64
"B", t
);
2342 void* memdup(const void *p
, size_t l
) {
2355 int fork_agent(pid_t
*pid
, const int except
[], unsigned n_except
, const char *path
, ...) {
2356 bool stdout_is_tty
, stderr_is_tty
;
2357 pid_t parent_pid
, agent_pid
;
2358 sigset_t ss
, saved_ss
;
2366 /* Spawns a temporary TTY agent, making sure it goes away when
2369 parent_pid
= getpid();
2371 /* First we temporarily block all signals, so that the new
2372 * child has them blocked initially. This way, we can be sure
2373 * that SIGTERMs are not lost we might send to the agent. */
2374 assert_se(sigfillset(&ss
) >= 0);
2375 assert_se(sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) >= 0);
2378 if (agent_pid
< 0) {
2379 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
2383 if (agent_pid
!= 0) {
2384 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
2391 * Make sure the agent goes away when the parent dies */
2392 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
2393 _exit(EXIT_FAILURE
);
2395 /* Make sure we actually can kill the agent, if we need to, in
2396 * case somebody invoked us from a shell script that trapped
2397 * SIGTERM or so... */
2398 (void) reset_all_signal_handlers();
2399 (void) reset_signal_mask();
2401 /* Check whether our parent died before we were able
2402 * to set the death signal and unblock the signals */
2403 if (getppid() != parent_pid
)
2404 _exit(EXIT_SUCCESS
);
2406 /* Don't leak fds to the agent */
2407 close_all_fds(except
, n_except
);
2409 stdout_is_tty
= isatty(STDOUT_FILENO
);
2410 stderr_is_tty
= isatty(STDERR_FILENO
);
2412 if (!stdout_is_tty
|| !stderr_is_tty
) {
2415 /* Detach from stdout/stderr. and reopen
2416 * /dev/tty for them. This is important to
2417 * ensure that when systemctl is started via
2418 * popen() or a similar call that expects to
2419 * read EOF we actually do generate EOF and
2420 * not delay this indefinitely by because we
2421 * keep an unused copy of stdin around. */
2422 fd
= open("/dev/tty", O_WRONLY
);
2424 log_error_errno(errno
, "Failed to open /dev/tty: %m");
2425 _exit(EXIT_FAILURE
);
2429 dup2(fd
, STDOUT_FILENO
);
2432 dup2(fd
, STDERR_FILENO
);
2438 /* Count arguments */
2440 for (n
= 0; va_arg(ap
, char*); n
++)
2445 l
= alloca(sizeof(char *) * (n
+ 1));
2447 /* Fill in arguments */
2449 for (i
= 0; i
<= n
; i
++)
2450 l
[i
] = va_arg(ap
, char*);
2454 _exit(EXIT_FAILURE
);
2457 int setrlimit_closest(int resource
, const struct rlimit
*rlim
) {
2458 struct rlimit highest
, fixed
;
2462 if (setrlimit(resource
, rlim
) >= 0)
2468 /* So we failed to set the desired setrlimit, then let's try
2469 * to get as close as we can */
2470 assert_se(getrlimit(resource
, &highest
) == 0);
2472 fixed
.rlim_cur
= MIN(rlim
->rlim_cur
, highest
.rlim_max
);
2473 fixed
.rlim_max
= MIN(rlim
->rlim_max
, highest
.rlim_max
);
2475 if (setrlimit(resource
, &fixed
) < 0)
2481 bool http_etag_is_valid(const char *etag
) {
2485 if (!endswith(etag
, "\""))
2488 if (!startswith(etag
, "\"") && !startswith(etag
, "W/\""))
2494 bool http_url_is_valid(const char *url
) {
2500 p
= startswith(url
, "http://");
2502 p
= startswith(url
, "https://");
2509 return ascii_is_valid(p
);
2512 bool documentation_url_is_valid(const char *url
) {
2518 if (http_url_is_valid(url
))
2521 p
= startswith(url
, "file:/");
2523 p
= startswith(url
, "info:");
2525 p
= startswith(url
, "man:");
2530 return ascii_is_valid(p
);
2533 bool in_initrd(void) {
2534 static int saved
= -1;
2540 /* We make two checks here:
2542 * 1. the flag file /etc/initrd-release must exist
2543 * 2. the root file system must be a memory file system
2545 * The second check is extra paranoia, since misdetecting an
2546 * initrd can have bad bad consequences due the initrd
2547 * emptying when transititioning to the main systemd.
2550 saved
= access("/etc/initrd-release", F_OK
) >= 0 &&
2551 statfs("/", &s
) >= 0 &&
2552 is_temporary_fs(&s
);
2557 bool filename_is_valid(const char *p
) {
2571 if (strlen(p
) > FILENAME_MAX
)
2577 bool string_is_safe(const char *p
) {
2583 for (t
= p
; *t
; t
++) {
2584 if (*t
> 0 && *t
< ' ')
2587 if (strchr("\\\"\'\x7f", *t
))
2594 bool path_is_safe(const char *p
) {
2599 if (streq(p
, "..") || startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
2602 if (strlen(p
)+1 > PATH_MAX
)
2605 /* The following two checks are not really dangerous, but hey, they still are confusing */
2606 if (streq(p
, ".") || startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
2609 if (strstr(p
, "//"))
2615 /* hey glibc, APIs with callbacks without a user pointer are so useless */
2616 void *xbsearch_r(const void *key
, const void *base
, size_t nmemb
, size_t size
,
2617 int (*compar
) (const void *, const void *, void *), void *arg
) {
2626 p
= (void *)(((const char *) base
) + (idx
* size
));
2627 comparison
= compar(key
, p
, arg
);
2630 else if (comparison
> 0)
2638 void init_gettext(void) {
2639 setlocale(LC_ALL
, "");
2640 textdomain(GETTEXT_PACKAGE
);
2643 bool is_locale_utf8(void) {
2645 static int cached_answer
= -1;
2647 if (cached_answer
>= 0)
2650 if (!setlocale(LC_ALL
, "")) {
2651 cached_answer
= true;
2655 set
= nl_langinfo(CODESET
);
2657 cached_answer
= true;
2661 if (streq(set
, "UTF-8")) {
2662 cached_answer
= true;
2666 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
2667 * unset and everything can do to UTF-8 nowadays. */
2668 set
= setlocale(LC_CTYPE
, NULL
);
2670 cached_answer
= true;
2674 /* Check result, but ignore the result if C was set
2677 STR_IN_SET(set
, "C", "POSIX") &&
2678 !getenv("LC_ALL") &&
2679 !getenv("LC_CTYPE") &&
2683 return (bool) cached_answer
;
2686 const char *draw_special_char(DrawSpecialChar ch
) {
2687 static const char *draw_table
[2][_DRAW_SPECIAL_CHAR_MAX
] = {
2690 [DRAW_TREE_VERTICAL
] = "\342\224\202 ", /* │ */
2691 [DRAW_TREE_BRANCH
] = "\342\224\234\342\224\200", /* ├─ */
2692 [DRAW_TREE_RIGHT
] = "\342\224\224\342\224\200", /* └─ */
2693 [DRAW_TREE_SPACE
] = " ", /* */
2694 [DRAW_TRIANGULAR_BULLET
] = "\342\200\243", /* ‣ */
2695 [DRAW_BLACK_CIRCLE
] = "\342\227\217", /* ● */
2696 [DRAW_ARROW
] = "\342\206\222", /* → */
2697 [DRAW_DASH
] = "\342\200\223", /* – */
2700 /* ASCII fallback */ {
2701 [DRAW_TREE_VERTICAL
] = "| ",
2702 [DRAW_TREE_BRANCH
] = "|-",
2703 [DRAW_TREE_RIGHT
] = "`-",
2704 [DRAW_TREE_SPACE
] = " ",
2705 [DRAW_TRIANGULAR_BULLET
] = ">",
2706 [DRAW_BLACK_CIRCLE
] = "*",
2707 [DRAW_ARROW
] = "->",
2712 return draw_table
[!is_locale_utf8()][ch
];
2715 int on_ac_power(void) {
2716 bool found_offline
= false, found_online
= false;
2717 _cleanup_closedir_
DIR *d
= NULL
;
2719 d
= opendir("/sys/class/power_supply");
2721 return errno
== ENOENT
? true : -errno
;
2725 _cleanup_close_
int fd
= -1, device
= -1;
2731 if (!de
&& errno
!= 0)
2737 if (hidden_file(de
->d_name
))
2740 device
= openat(dirfd(d
), de
->d_name
, O_DIRECTORY
|O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
2742 if (errno
== ENOENT
|| errno
== ENOTDIR
)
2748 fd
= openat(device
, "type", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
2750 if (errno
== ENOENT
)
2756 n
= read(fd
, contents
, sizeof(contents
));
2760 if (n
!= 6 || memcmp(contents
, "Mains\n", 6))
2764 fd
= openat(device
, "online", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
2766 if (errno
== ENOENT
)
2772 n
= read(fd
, contents
, sizeof(contents
));
2776 if (n
!= 2 || contents
[1] != '\n')
2779 if (contents
[0] == '1') {
2780 found_online
= true;
2782 } else if (contents
[0] == '0')
2783 found_offline
= true;
2788 return found_online
|| !found_offline
;
2791 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
2798 if (!path_strv_resolve_uniq(search
, root
))
2801 STRV_FOREACH(i
, search
) {
2802 _cleanup_free_
char *p
= NULL
;
2806 p
= strjoin(root
, *i
, "/", path
, NULL
);
2808 p
= strjoin(*i
, "/", path
, NULL
);
2818 if (errno
!= ENOENT
)
2825 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
2826 _cleanup_strv_free_
char **copy
= NULL
;
2832 if (path_is_absolute(path
)) {
2835 f
= fopen(path
, mode
);
2844 copy
= strv_copy((char**) search
);
2848 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
2851 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
2852 _cleanup_strv_free_
char **s
= NULL
;
2854 if (path_is_absolute(path
)) {
2857 f
= fopen(path
, mode
);
2866 s
= strv_split_nulstr(search
);
2870 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
2873 void* greedy_realloc(void **p
, size_t *allocated
, size_t need
, size_t size
) {
2880 if (*allocated
>= need
)
2883 newalloc
= MAX(need
* 2, 64u / size
);
2884 a
= newalloc
* size
;
2886 /* check for overflows */
2887 if (a
< size
* need
)
2895 *allocated
= newalloc
;
2899 void* greedy_realloc0(void **p
, size_t *allocated
, size_t need
, size_t size
) {
2908 q
= greedy_realloc(p
, allocated
, need
, size
);
2912 if (*allocated
> prev
)
2913 memzero(q
+ prev
* size
, (*allocated
- prev
) * size
);
2918 bool id128_is_valid(const char *s
) {
2924 /* Simple formatted 128bit hex string */
2926 for (i
= 0; i
< l
; i
++) {
2929 if (!(c
>= '0' && c
<= '9') &&
2930 !(c
>= 'a' && c
<= 'z') &&
2931 !(c
>= 'A' && c
<= 'Z'))
2935 } else if (l
== 36) {
2937 /* Formatted UUID */
2939 for (i
= 0; i
< l
; i
++) {
2942 if ((i
== 8 || i
== 13 || i
== 18 || i
== 23)) {
2946 if (!(c
>= '0' && c
<= '9') &&
2947 !(c
>= 'a' && c
<= 'z') &&
2948 !(c
>= 'A' && c
<= 'Z'))
2959 int shall_restore_state(void) {
2960 _cleanup_free_
char *value
= NULL
;
2963 r
= get_proc_cmdline_key("systemd.restore_state=", &value
);
2969 return parse_boolean(value
) != 0;
2972 int proc_cmdline(char **ret
) {
2975 if (detect_container() > 0)
2976 return get_process_cmdline(1, 0, false, ret
);
2978 return read_one_line_file("/proc/cmdline", ret
);
2981 int parse_proc_cmdline(int (*parse_item
)(const char *key
, const char *value
)) {
2982 _cleanup_free_
char *line
= NULL
;
2988 r
= proc_cmdline(&line
);
2994 _cleanup_free_
char *word
= NULL
;
2997 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
3003 /* Filter out arguments that are intended only for the
3005 if (!in_initrd() && startswith(word
, "rd."))
3008 value
= strchr(word
, '=');
3012 r
= parse_item(word
, value
);
3020 int get_proc_cmdline_key(const char *key
, char **value
) {
3021 _cleanup_free_
char *line
= NULL
, *ret
= NULL
;
3028 r
= proc_cmdline(&line
);
3034 _cleanup_free_
char *word
= NULL
;
3037 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
3043 /* Filter out arguments that are intended only for the
3045 if (!in_initrd() && startswith(word
, "rd."))
3049 e
= startswith(word
, key
);
3053 r
= free_and_strdup(&ret
, e
);
3059 if (streq(word
, key
))
3073 int container_get_leader(const char *machine
, pid_t
*pid
) {
3074 _cleanup_free_
char *s
= NULL
, *class = NULL
;
3082 if (!machine_name_is_valid(machine
))
3085 p
= strjoina("/run/systemd/machines/", machine
);
3086 r
= parse_env_file(p
, NEWLINE
, "LEADER", &s
, "CLASS", &class, NULL
);
3094 if (!streq_ptr(class, "container"))
3097 r
= parse_pid(s
, &leader
);
3107 int namespace_open(pid_t pid
, int *pidns_fd
, int *mntns_fd
, int *netns_fd
, int *userns_fd
, int *root_fd
) {
3108 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, netnsfd
= -1, usernsfd
= -1;
3116 mntns
= procfs_file_alloca(pid
, "ns/mnt");
3117 mntnsfd
= open(mntns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
3125 pidns
= procfs_file_alloca(pid
, "ns/pid");
3126 pidnsfd
= open(pidns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
3134 netns
= procfs_file_alloca(pid
, "ns/net");
3135 netnsfd
= open(netns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
3143 userns
= procfs_file_alloca(pid
, "ns/user");
3144 usernsfd
= open(userns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
3145 if (usernsfd
< 0 && errno
!= ENOENT
)
3152 root
= procfs_file_alloca(pid
, "root");
3153 rfd
= open(root
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
|O_DIRECTORY
);
3159 *pidns_fd
= pidnsfd
;
3162 *mntns_fd
= mntnsfd
;
3165 *netns_fd
= netnsfd
;
3168 *userns_fd
= usernsfd
;
3173 pidnsfd
= mntnsfd
= netnsfd
= usernsfd
= -1;
3178 int namespace_enter(int pidns_fd
, int mntns_fd
, int netns_fd
, int userns_fd
, int root_fd
) {
3179 if (userns_fd
>= 0) {
3180 /* Can't setns to your own userns, since then you could
3181 * escalate from non-root to root in your own namespace, so
3182 * check if namespaces equal before attempting to enter. */
3183 _cleanup_free_
char *userns_fd_path
= NULL
;
3185 if (asprintf(&userns_fd_path
, "/proc/self/fd/%d", userns_fd
) < 0)
3188 r
= files_same(userns_fd_path
, "/proc/self/ns/user");
3196 if (setns(pidns_fd
, CLONE_NEWPID
) < 0)
3200 if (setns(mntns_fd
, CLONE_NEWNS
) < 0)
3204 if (setns(netns_fd
, CLONE_NEWNET
) < 0)
3208 if (setns(userns_fd
, CLONE_NEWUSER
) < 0)
3212 if (fchdir(root_fd
) < 0)
3215 if (chroot(".") < 0)
3219 return reset_uid_gid();
3222 /* This is much like like mkostemp() but is subject to umask(). */
3223 int mkostemp_safe(char *pattern
, int flags
) {
3224 _cleanup_umask_ mode_t u
;
3231 fd
= mkostemp(pattern
, flags
);
3238 int open_tmpfile(const char *path
, int flags
) {
3245 /* Try O_TMPFILE first, if it is supported */
3246 fd
= open(path
, flags
|O_TMPFILE
|O_EXCL
, S_IRUSR
|S_IWUSR
);
3251 /* Fall back to unguessable name + unlinking */
3252 p
= strjoina(path
, "/systemd-tmp-XXXXXX");
3254 fd
= mkostemp_safe(p
, flags
);
3262 int fd_warn_permissions(const char *path
, int fd
) {
3265 if (fstat(fd
, &st
) < 0)
3268 if (st
.st_mode
& 0111)
3269 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path
);
3271 if (st
.st_mode
& 0002)
3272 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path
);
3274 if (getpid() == 1 && (st
.st_mode
& 0044) != 0044)
3275 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
);
3280 unsigned long personality_from_string(const char *p
) {
3282 /* Parse a personality specifier. We introduce our own
3283 * identifiers that indicate specific ABIs, rather than just
3284 * hints regarding the register size, since we want to keep
3285 * things open for multiple locally supported ABIs for the
3286 * same register size. We try to reuse the ABI identifiers
3287 * used by libseccomp. */
3289 #if defined(__x86_64__)
3291 if (streq(p
, "x86"))
3294 if (streq(p
, "x86-64"))
3297 #elif defined(__i386__)
3299 if (streq(p
, "x86"))
3302 #elif defined(__s390x__)
3304 if (streq(p
, "s390"))
3307 if (streq(p
, "s390x"))
3310 #elif defined(__s390__)
3312 if (streq(p
, "s390"))
3316 return PERSONALITY_INVALID
;
3319 const char* personality_to_string(unsigned long p
) {
3321 #if defined(__x86_64__)
3323 if (p
== PER_LINUX32
)
3329 #elif defined(__i386__)
3334 #elif defined(__s390x__)
3339 if (p
== PER_LINUX32
)
3342 #elif defined(__s390__)
3352 uint64_t physical_memory(void) {
3355 /* We return this as uint64_t in case we are running as 32bit
3356 * process on a 64bit kernel with huge amounts of memory */
3358 mem
= sysconf(_SC_PHYS_PAGES
);
3361 return (uint64_t) mem
* (uint64_t) page_size();
3364 void hexdump(FILE *f
, const void *p
, size_t s
) {
3365 const uint8_t *b
= p
;
3368 assert(s
== 0 || b
);
3373 fprintf(f
, "%04x ", n
);
3375 for (i
= 0; i
< 16; i
++) {
3380 fprintf(f
, "%02x ", b
[i
]);
3388 for (i
= 0; i
< 16; i
++) {
3393 fputc(isprint(b
[i
]) ? (char) b
[i
] : '.', f
);
3407 int update_reboot_param_file(const char *param
) {
3411 r
= write_string_file(REBOOT_PARAM_FILE
, param
, WRITE_STRING_FILE_CREATE
);
3413 return log_error_errno(r
, "Failed to write reboot param to "REBOOT_PARAM_FILE
": %m");
3415 (void) unlink(REBOOT_PARAM_FILE
);
3420 int umount_recursive(const char *prefix
, int flags
) {
3424 /* Try to umount everything recursively below a
3425 * directory. Also, take care of stacked mounts, and keep
3426 * unmounting them until they are gone. */
3429 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
3434 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
3435 if (!proc_self_mountinfo
)
3439 _cleanup_free_
char *path
= NULL
, *p
= NULL
;
3442 k
= fscanf(proc_self_mountinfo
,
3443 "%*s " /* (1) mount id */
3444 "%*s " /* (2) parent id */
3445 "%*s " /* (3) major:minor */
3446 "%*s " /* (4) root */
3447 "%ms " /* (5) mount point */
3448 "%*s" /* (6) mount options */
3449 "%*[^-]" /* (7) optional fields */
3450 "- " /* (8) separator */
3451 "%*s " /* (9) file system type */
3452 "%*s" /* (10) mount source */
3453 "%*s" /* (11) mount options 2 */
3454 "%*[^\n]", /* some rubbish at the end */
3463 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
3467 if (!path_startswith(p
, prefix
))
3470 if (umount2(p
, flags
) < 0) {
3486 static int get_mount_flags(const char *path
, unsigned long *flags
) {
3489 if (statvfs(path
, &buf
) < 0)
3491 *flags
= buf
.f_flag
;
3495 int bind_remount_recursive(const char *prefix
, bool ro
) {
3496 _cleanup_set_free_free_ Set
*done
= NULL
;
3497 _cleanup_free_
char *cleaned
= NULL
;
3500 /* Recursively remount a directory (and all its submounts)
3501 * read-only or read-write. If the directory is already
3502 * mounted, we reuse the mount and simply mark it
3503 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
3504 * operation). If it isn't we first make it one. Afterwards we
3505 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
3506 * submounts we can access, too. When mounts are stacked on
3507 * the same mount point we only care for each individual
3508 * "top-level" mount on each point, as we cannot
3509 * influence/access the underlying mounts anyway. We do not
3510 * have any effect on future submounts that might get
3511 * propagated, they migt be writable. This includes future
3512 * submounts that have been triggered via autofs. */
3514 cleaned
= strdup(prefix
);
3518 path_kill_slashes(cleaned
);
3520 done
= set_new(&string_hash_ops
);
3525 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
3526 _cleanup_set_free_free_ Set
*todo
= NULL
;
3527 bool top_autofs
= false;
3529 unsigned long orig_flags
;
3531 todo
= set_new(&string_hash_ops
);
3535 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
3536 if (!proc_self_mountinfo
)
3540 _cleanup_free_
char *path
= NULL
, *p
= NULL
, *type
= NULL
;
3543 k
= fscanf(proc_self_mountinfo
,
3544 "%*s " /* (1) mount id */
3545 "%*s " /* (2) parent id */
3546 "%*s " /* (3) major:minor */
3547 "%*s " /* (4) root */
3548 "%ms " /* (5) mount point */
3549 "%*s" /* (6) mount options (superblock) */
3550 "%*[^-]" /* (7) optional fields */
3551 "- " /* (8) separator */
3552 "%ms " /* (9) file system type */
3553 "%*s" /* (10) mount source */
3554 "%*s" /* (11) mount options (bind mount) */
3555 "%*[^\n]", /* some rubbish at the end */
3565 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
3569 /* Let's ignore autofs mounts. If they aren't
3570 * triggered yet, we want to avoid triggering
3571 * them, as we don't make any guarantees for
3572 * future submounts anyway. If they are
3573 * already triggered, then we will find
3574 * another entry for this. */
3575 if (streq(type
, "autofs")) {
3576 top_autofs
= top_autofs
|| path_equal(cleaned
, p
);
3580 if (path_startswith(p
, cleaned
) &&
3581 !set_contains(done
, p
)) {
3583 r
= set_consume(todo
, p
);
3593 /* If we have no submounts to process anymore and if
3594 * the root is either already done, or an autofs, we
3596 if (set_isempty(todo
) &&
3597 (top_autofs
|| set_contains(done
, cleaned
)))
3600 if (!set_contains(done
, cleaned
) &&
3601 !set_contains(todo
, cleaned
)) {
3602 /* The prefix directory itself is not yet a
3603 * mount, make it one. */
3604 if (mount(cleaned
, cleaned
, NULL
, MS_BIND
|MS_REC
, NULL
) < 0)
3608 (void) get_mount_flags(cleaned
, &orig_flags
);
3609 orig_flags
&= ~MS_RDONLY
;
3611 if (mount(NULL
, prefix
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0)
3614 x
= strdup(cleaned
);
3618 r
= set_consume(done
, x
);
3623 while ((x
= set_steal_first(todo
))) {
3625 r
= set_consume(done
, x
);
3626 if (r
== -EEXIST
|| r
== 0)
3631 /* Try to reuse the original flag set, but
3632 * don't care for errors, in case of
3633 * obstructed mounts */
3635 (void) get_mount_flags(x
, &orig_flags
);
3636 orig_flags
&= ~MS_RDONLY
;
3638 if (mount(NULL
, x
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0) {
3640 /* Deal with mount points that are
3641 * obstructed by a later mount */
3643 if (errno
!= ENOENT
)
3651 int fflush_and_check(FILE *f
) {
3658 return errno
? -errno
: -EIO
;
3663 int tempfn_xxxxxx(const char *p
, const char *extra
, char **ret
) {
3675 * /foo/bar/.#<extra>waldoXXXXXX
3679 if (!filename_is_valid(fn
))
3685 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 6 + 1);
3689 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
), "XXXXXX");
3691 *ret
= path_kill_slashes(t
);
3695 int tempfn_random(const char *p
, const char *extra
, char **ret
) {
3709 * /foo/bar/.#<extra>waldobaa2a261115984a9
3713 if (!filename_is_valid(fn
))
3719 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 16 + 1);
3723 x
= stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
);
3726 for (i
= 0; i
< 16; i
++) {
3727 *(x
++) = hexchar(u
& 0xF);
3733 *ret
= path_kill_slashes(t
);
3737 int tempfn_random_child(const char *p
, const char *extra
, char **ret
) {
3748 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
3754 t
= new(char, strlen(p
) + 3 + strlen(extra
) + 16 + 1);
3758 x
= stpcpy(stpcpy(stpcpy(t
, p
), "/.#"), extra
);
3761 for (i
= 0; i
< 16; i
++) {
3762 *(x
++) = hexchar(u
& 0xF);
3768 *ret
= path_kill_slashes(t
);
3772 int take_password_lock(const char *root
) {
3774 struct flock flock
= {
3776 .l_whence
= SEEK_SET
,
3784 /* This is roughly the same as lckpwdf(), but not as awful. We
3785 * don't want to use alarm() and signals, hence we implement
3786 * our own trivial version of this.
3788 * Note that shadow-utils also takes per-database locks in
3789 * addition to lckpwdf(). However, we don't given that they
3790 * are redundant as they they invoke lckpwdf() first and keep
3791 * it during everything they do. The per-database locks are
3792 * awfully racy, and thus we just won't do them. */
3795 path
= strjoina(root
, "/etc/.pwd.lock");
3797 path
= "/etc/.pwd.lock";
3799 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
3803 r
= fcntl(fd
, F_SETLKW
, &flock
);
3812 int is_symlink(const char *path
) {
3815 if (lstat(path
, &info
) < 0)
3818 return !!S_ISLNK(info
.st_mode
);
3821 int is_dir(const char* path
, bool follow
) {
3826 r
= stat(path
, &st
);
3828 r
= lstat(path
, &st
);
3832 return !!S_ISDIR(st
.st_mode
);
3835 int is_device_node(const char *path
) {
3838 if (lstat(path
, &info
) < 0)
3841 return !!(S_ISBLK(info
.st_mode
) || S_ISCHR(info
.st_mode
));
3844 ssize_t
fgetxattrat_fake(int dirfd
, const char *filename
, const char *attribute
, void *value
, size_t size
, int flags
) {
3845 char fn
[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(int) + 1];
3846 _cleanup_close_
int fd
= -1;
3849 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
3851 fd
= openat(dirfd
, filename
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_PATH
|(flags
& AT_SYMLINK_NOFOLLOW
? O_NOFOLLOW
: 0));
3855 xsprintf(fn
, "/proc/self/fd/%i", fd
);
3857 l
= getxattr(fn
, attribute
, value
, size
);
3864 static int parse_crtime(le64_t le
, usec_t
*usec
) {
3870 if (u
== 0 || u
== (uint64_t) -1)
3877 int fd_getcrtime(int fd
, usec_t
*usec
) {
3884 /* Until Linux gets a real concept of birthtime/creation time,
3885 * let's fake one with xattrs */
3887 n
= fgetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
));
3890 if (n
!= sizeof(le
))
3893 return parse_crtime(le
, usec
);
3896 int fd_getcrtime_at(int dirfd
, const char *name
, usec_t
*usec
, int flags
) {
3900 n
= fgetxattrat_fake(dirfd
, name
, "user.crtime_usec", &le
, sizeof(le
), flags
);
3903 if (n
!= sizeof(le
))
3906 return parse_crtime(le
, usec
);
3909 int path_getcrtime(const char *p
, usec_t
*usec
) {
3916 n
= getxattr(p
, "user.crtime_usec", &le
, sizeof(le
));
3919 if (n
!= sizeof(le
))
3922 return parse_crtime(le
, usec
);
3925 int fd_setcrtime(int fd
, usec_t usec
) {
3931 usec
= now(CLOCK_REALTIME
);
3933 le
= htole64((uint64_t) usec
);
3934 if (fsetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
), 0) < 0)
3940 int chattr_fd(int fd
, unsigned value
, unsigned mask
) {
3941 unsigned old_attr
, new_attr
;
3946 if (fstat(fd
, &st
) < 0)
3949 /* Explicitly check whether this is a regular file or
3950 * directory. If it is anything else (such as a device node or
3951 * fifo), then the ioctl will not hit the file systems but
3952 * possibly drivers, where the ioctl might have different
3953 * effects. Notably, DRM is using the same ioctl() number. */
3955 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
3961 if (ioctl(fd
, FS_IOC_GETFLAGS
, &old_attr
) < 0)
3964 new_attr
= (old_attr
& ~mask
) | (value
& mask
);
3965 if (new_attr
== old_attr
)
3968 if (ioctl(fd
, FS_IOC_SETFLAGS
, &new_attr
) < 0)
3974 int chattr_path(const char *p
, unsigned value
, unsigned mask
) {
3975 _cleanup_close_
int fd
= -1;
3982 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
3986 return chattr_fd(fd
, value
, mask
);
3989 int read_attr_fd(int fd
, unsigned *ret
) {
3994 if (fstat(fd
, &st
) < 0)
3997 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
4000 if (ioctl(fd
, FS_IOC_GETFLAGS
, ret
) < 0)
4006 int read_attr_path(const char *p
, unsigned *ret
) {
4007 _cleanup_close_
int fd
= -1;
4012 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
4016 return read_attr_fd(fd
, ret
);
4019 void sigkill_wait(pid_t
*pid
) {
4025 if (kill(*pid
, SIGKILL
) > 0)
4026 (void) wait_for_terminate(*pid
, NULL
);
4029 int syslog_parse_priority(const char **p
, int *priority
, bool with_facility
) {
4030 int a
= 0, b
= 0, c
= 0;
4040 if (!strchr(*p
, '>'))
4043 if ((*p
)[2] == '>') {
4044 c
= undecchar((*p
)[1]);
4046 } else if ((*p
)[3] == '>') {
4047 b
= undecchar((*p
)[1]);
4048 c
= undecchar((*p
)[2]);
4050 } else if ((*p
)[4] == '>') {
4051 a
= undecchar((*p
)[1]);
4052 b
= undecchar((*p
)[2]);
4053 c
= undecchar((*p
)[3]);
4058 if (a
< 0 || b
< 0 || c
< 0 ||
4059 (!with_facility
&& (a
|| b
|| c
> 7)))
4063 *priority
= a
*100 + b
*10 + c
;
4065 *priority
= (*priority
& LOG_FACMASK
) | c
;
4071 ssize_t
string_table_lookup(const char * const *table
, size_t len
, const char *key
) {
4077 for (i
= 0; i
< len
; ++i
)
4078 if (streq_ptr(table
[i
], key
))
4084 int rename_noreplace(int olddirfd
, const char *oldpath
, int newdirfd
, const char *newpath
) {
4088 ret
= renameat2(olddirfd
, oldpath
, newdirfd
, newpath
, RENAME_NOREPLACE
);
4092 /* renameat2() exists since Linux 3.15, btrfs added support for it later.
4093 * If it is not implemented, fallback to another method. */
4094 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
4097 /* The link()/unlink() fallback does not work on directories. But
4098 * renameat() without RENAME_NOREPLACE gives the same semantics on
4099 * directories, except when newpath is an *empty* directory. This is
4101 ret
= fstatat(olddirfd
, oldpath
, &buf
, AT_SYMLINK_NOFOLLOW
);
4102 if (ret
>= 0 && S_ISDIR(buf
.st_mode
)) {
4103 ret
= renameat(olddirfd
, oldpath
, newdirfd
, newpath
);
4104 return ret
>= 0 ? 0 : -errno
;
4107 /* If it is not a directory, use the link()/unlink() fallback. */
4108 ret
= linkat(olddirfd
, oldpath
, newdirfd
, newpath
, 0);
4112 ret
= unlinkat(olddirfd
, oldpath
, 0);
4114 /* backup errno before the following unlinkat() alters it */
4116 (void) unlinkat(newdirfd
, newpath
, 0);
4124 int parse_mode(const char *s
, mode_t
*ret
) {
4132 l
= strtol(s
, &x
, 8);
4136 if (!x
|| x
== s
|| *x
)
4138 if (l
< 0 || l
> 07777)
4145 int mount_move_root(const char *path
) {
4148 if (chdir(path
) < 0)
4151 if (mount(path
, "/", NULL
, MS_MOVE
, NULL
) < 0)
4154 if (chroot(".") < 0)
4163 int getxattr_malloc(const char *path
, const char *name
, char **value
, bool allow_symlink
) {
4172 for (l
= 100; ; l
= (size_t) n
+ 1) {
4178 n
= lgetxattr(path
, name
, v
, l
);
4180 n
= getxattr(path
, name
, v
, l
);
4182 if (n
>= 0 && (size_t) n
< l
) {
4189 if (n
< 0 && errno
!= ERANGE
)
4193 n
= lgetxattr(path
, name
, NULL
, 0);
4195 n
= getxattr(path
, name
, NULL
, 0);
4201 int fgetxattr_malloc(int fd
, const char *name
, char **value
) {
4210 for (l
= 100; ; l
= (size_t) n
+ 1) {
4215 n
= fgetxattr(fd
, name
, v
, l
);
4217 if (n
>= 0 && (size_t) n
< l
) {
4224 if (n
< 0 && errno
!= ERANGE
)
4227 n
= fgetxattr(fd
, name
, NULL
, 0);
4233 void nop_signal_handler(int sig
) {
4238 puts(PACKAGE_STRING
"\n"
4243 bool fdname_is_valid(const char *s
) {
4246 /* Validates a name for $LISTEN_FDNAMES. We basically allow
4247 * everything ASCII that's not a control character. Also, as
4248 * special exception the ":" character is not allowed, as we
4249 * use that as field separator in $LISTEN_FDNAMES.
4251 * Note that the empty string is explicitly allowed
4252 * here. However, we limit the length of the names to 255
4258 for (p
= s
; *p
; p
++) {
4270 bool oom_score_adjust_is_valid(int oa
) {
4271 return oa
>= OOM_SCORE_ADJ_MIN
&& oa
<= OOM_SCORE_ADJ_MAX
;