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/sched.h>
34 #include <netinet/ip.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! */
76 #include "device-nodes.h"
78 #include "exit-status.h"
80 #include "formats-util.h"
83 #include "hostname-util.h"
89 #include "path-util.h"
90 #include "process-util.h"
91 #include "random-util.h"
92 #include "signal-util.h"
93 #include "sparse-endian.h"
95 #include "terminal-util.h"
100 /* Put this test here for a lack of better place */
101 assert_cc(EAGAIN
== EWOULDBLOCK
);
104 char **saved_argv
= NULL
;
106 size_t page_size(void) {
107 static thread_local
size_t pgsz
= 0;
110 if (_likely_(pgsz
> 0))
113 r
= sysconf(_SC_PAGESIZE
);
120 int strcmp_ptr(const char *a
, const char *b
) {
122 /* Like strcmp(), but tries to make sense of NULL pointers */
135 bool streq_ptr(const char *a
, const char *b
) {
136 return strcmp_ptr(a
, b
) == 0;
139 char* endswith(const char *s
, const char *postfix
) {
146 pl
= strlen(postfix
);
149 return (char*) s
+ sl
;
154 if (memcmp(s
+ sl
- pl
, postfix
, pl
) != 0)
157 return (char*) s
+ sl
- pl
;
160 char* endswith_no_case(const char *s
, const char *postfix
) {
167 pl
= strlen(postfix
);
170 return (char*) s
+ sl
;
175 if (strcasecmp(s
+ sl
- pl
, postfix
) != 0)
178 return (char*) s
+ sl
- pl
;
181 char* first_word(const char *s
, const char *word
) {
188 /* Checks if the string starts with the specified word, either
189 * followed by NUL or by whitespace. Returns a pointer to the
190 * NUL or the first character after the whitespace. */
201 if (memcmp(s
, word
, wl
) != 0)
208 if (!strchr(WHITESPACE
, *p
))
211 p
+= strspn(p
, WHITESPACE
);
215 size_t cescape_char(char c
, char *buf
) {
216 char * buf_old
= buf
;
262 /* For special chars we prefer octal over
263 * hexadecimal encoding, simply because glib's
264 * g_strescape() does the same */
265 if ((c
< ' ') || (c
>= 127)) {
267 *(buf
++) = octchar((unsigned char) c
>> 6);
268 *(buf
++) = octchar((unsigned char) c
>> 3);
269 *(buf
++) = octchar((unsigned char) c
);
275 return buf
- buf_old
;
278 int close_nointr(int fd
) {
285 * Just ignore EINTR; a retry loop is the wrong thing to do on
288 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
289 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
290 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
291 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
299 int safe_close(int fd
) {
302 * Like close_nointr() but cannot fail. Guarantees errno is
303 * unchanged. Is a NOP with negative fds passed, and returns
304 * -1, so that it can be used in this syntax:
306 * fd = safe_close(fd);
312 /* The kernel might return pretty much any error code
313 * via close(), but the fd will be closed anyway. The
314 * only condition we want to check for here is whether
315 * the fd was invalid at all... */
317 assert_se(close_nointr(fd
) != -EBADF
);
323 void close_many(const int fds
[], unsigned n_fd
) {
326 assert(fds
|| n_fd
<= 0);
328 for (i
= 0; i
< n_fd
; i
++)
332 int fclose_nointr(FILE *f
) {
335 /* Same as close_nointr(), but for fclose() */
346 FILE* safe_fclose(FILE *f
) {
348 /* Same as safe_close(), but for fclose() */
353 assert_se(fclose_nointr(f
) != EBADF
);
359 DIR* safe_closedir(DIR *d
) {
364 assert_se(closedir(d
) >= 0 || errno
!= EBADF
);
370 int unlink_noerrno(const char *path
) {
381 int parse_boolean(const char *v
) {
384 if (streq(v
, "1") || strcaseeq(v
, "yes") || strcaseeq(v
, "y") || strcaseeq(v
, "true") || strcaseeq(v
, "t") || strcaseeq(v
, "on"))
386 else if (streq(v
, "0") || strcaseeq(v
, "no") || strcaseeq(v
, "n") || strcaseeq(v
, "false") || strcaseeq(v
, "f") || strcaseeq(v
, "off"))
392 int parse_pid(const char *s
, pid_t
* ret_pid
) {
393 unsigned long ul
= 0;
400 r
= safe_atolu(s
, &ul
);
406 if ((unsigned long) pid
!= ul
)
416 bool uid_is_valid(uid_t uid
) {
418 /* Some libc APIs use UID_INVALID as special placeholder */
419 if (uid
== (uid_t
) 0xFFFFFFFF)
422 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
423 if (uid
== (uid_t
) 0xFFFF)
429 int parse_uid(const char *s
, uid_t
* ret_uid
) {
430 unsigned long ul
= 0;
436 r
= safe_atolu(s
, &ul
);
442 if ((unsigned long) uid
!= ul
)
445 if (!uid_is_valid(uid
))
446 return -ENXIO
; /* we return ENXIO instead of EINVAL
447 * here, to make it easy to distuingish
448 * invalid numeric uids invalid
457 int safe_atou(const char *s
, unsigned *ret_u
) {
465 l
= strtoul(s
, &x
, 0);
467 if (!x
|| x
== s
|| *x
|| errno
)
468 return errno
> 0 ? -errno
: -EINVAL
;
470 if ((unsigned long) (unsigned) l
!= l
)
473 *ret_u
= (unsigned) l
;
477 int safe_atoi(const char *s
, int *ret_i
) {
485 l
= strtol(s
, &x
, 0);
487 if (!x
|| x
== s
|| *x
|| errno
)
488 return errno
> 0 ? -errno
: -EINVAL
;
490 if ((long) (int) l
!= l
)
497 int safe_atou8(const char *s
, uint8_t *ret
) {
505 l
= strtoul(s
, &x
, 0);
507 if (!x
|| x
== s
|| *x
|| errno
)
508 return errno
> 0 ? -errno
: -EINVAL
;
510 if ((unsigned long) (uint8_t) l
!= l
)
517 int safe_atou16(const char *s
, uint16_t *ret
) {
525 l
= strtoul(s
, &x
, 0);
527 if (!x
|| x
== s
|| *x
|| errno
)
528 return errno
> 0 ? -errno
: -EINVAL
;
530 if ((unsigned long) (uint16_t) l
!= l
)
537 int safe_atoi16(const char *s
, int16_t *ret
) {
545 l
= strtol(s
, &x
, 0);
547 if (!x
|| x
== s
|| *x
|| errno
)
548 return errno
> 0 ? -errno
: -EINVAL
;
550 if ((long) (int16_t) l
!= l
)
557 int safe_atollu(const char *s
, long long unsigned *ret_llu
) {
559 unsigned long long l
;
565 l
= strtoull(s
, &x
, 0);
567 if (!x
|| x
== s
|| *x
|| errno
)
568 return errno
? -errno
: -EINVAL
;
574 int safe_atolli(const char *s
, long long int *ret_lli
) {
582 l
= strtoll(s
, &x
, 0);
584 if (!x
|| x
== s
|| *x
|| errno
)
585 return errno
? -errno
: -EINVAL
;
591 int safe_atod(const char *s
, double *ret_d
) {
599 loc
= newlocale(LC_NUMERIC_MASK
, "C", (locale_t
) 0);
600 if (loc
== (locale_t
) 0)
604 d
= strtod_l(s
, &x
, loc
);
606 if (!x
|| x
== s
|| *x
|| errno
) {
608 return errno
? -errno
: -EINVAL
;
616 static size_t strcspn_escaped(const char *s
, const char *reject
) {
617 bool escaped
= false;
620 for (n
=0; s
[n
]; n
++) {
623 else if (s
[n
] == '\\')
625 else if (strchr(reject
, s
[n
]))
629 /* if s ends in \, return index of previous char */
633 /* Split a string into words. */
634 const char* split(const char **state
, size_t *l
, const char *separator
, bool quoted
) {
640 assert(**state
== '\0');
644 current
+= strspn(current
, separator
);
650 if (quoted
&& strchr("\'\"", *current
)) {
651 char quotechars
[2] = {*current
, '\0'};
653 *l
= strcspn_escaped(current
+ 1, quotechars
);
654 if (current
[*l
+ 1] == '\0' || current
[*l
+ 1] != quotechars
[0] ||
655 (current
[*l
+ 2] && !strchr(separator
, current
[*l
+ 2]))) {
656 /* right quote missing or garbage at the end */
660 *state
= current
++ + *l
+ 2;
662 *l
= strcspn_escaped(current
, separator
);
663 if (current
[*l
] && !strchr(separator
, current
[*l
])) {
664 /* unfinished escape */
668 *state
= current
+ *l
;
670 *l
= strcspn(current
, separator
);
671 *state
= current
+ *l
;
677 int fchmod_umask(int fd
, mode_t m
) {
682 r
= fchmod(fd
, m
& (~u
)) < 0 ? -errno
: 0;
688 char *truncate_nl(char *s
) {
691 s
[strcspn(s
, NEWLINE
)] = 0;
695 char *strnappend(const char *s
, const char *suffix
, size_t b
) {
703 return strndup(suffix
, b
);
712 if (b
> ((size_t) -1) - a
)
715 r
= new(char, a
+b
+1);
720 memcpy(r
+a
, suffix
, b
);
726 char *strappend(const char *s
, const char *suffix
) {
727 return strnappend(s
, suffix
, suffix
? strlen(suffix
) : 0);
730 int readlinkat_malloc(int fd
, const char *p
, char **ret
) {
745 n
= readlinkat(fd
, p
, c
, l
-1);
752 if ((size_t) n
< l
-1) {
763 int readlink_malloc(const char *p
, char **ret
) {
764 return readlinkat_malloc(AT_FDCWD
, p
, ret
);
767 int readlink_value(const char *p
, char **ret
) {
768 _cleanup_free_
char *link
= NULL
;
772 r
= readlink_malloc(p
, &link
);
776 value
= basename(link
);
780 value
= strdup(value
);
789 int readlink_and_make_absolute(const char *p
, char **r
) {
790 _cleanup_free_
char *target
= NULL
;
797 j
= readlink_malloc(p
, &target
);
801 k
= file_in_same_dir(p
, target
);
809 int readlink_and_canonicalize(const char *p
, char **r
) {
816 j
= readlink_and_make_absolute(p
, &t
);
820 s
= canonicalize_file_name(t
);
827 path_kill_slashes(*r
);
832 char *strstrip(char *s
) {
835 /* Drops trailing whitespace. Modifies the string in
836 * place. Returns pointer to first non-space character */
838 s
+= strspn(s
, WHITESPACE
);
840 for (e
= strchr(s
, 0); e
> s
; e
--)
841 if (!strchr(WHITESPACE
, e
[-1]))
849 char *delete_chars(char *s
, const char *bad
) {
852 /* Drops all whitespace, regardless where in the string */
854 for (f
= s
, t
= s
; *f
; f
++) {
866 char *file_in_same_dir(const char *path
, const char *filename
) {
873 /* This removes the last component of path and appends
874 * filename, unless the latter is absolute anyway or the
877 if (path_is_absolute(filename
))
878 return strdup(filename
);
880 e
= strrchr(path
, '/');
882 return strdup(filename
);
884 k
= strlen(filename
);
885 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
889 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
893 int rmdir_parents(const char *path
, const char *stop
) {
902 /* Skip trailing slashes */
903 while (l
> 0 && path
[l
-1] == '/')
909 /* Skip last component */
910 while (l
> 0 && path
[l
-1] != '/')
913 /* Skip trailing slashes */
914 while (l
> 0 && path
[l
-1] == '/')
920 if (!(t
= strndup(path
, l
)))
923 if (path_startswith(stop
, t
)) {
939 char hexchar(int x
) {
940 static const char table
[16] = "0123456789abcdef";
942 return table
[x
& 15];
945 int unhexchar(char c
) {
947 if (c
>= '0' && c
<= '9')
950 if (c
>= 'a' && c
<= 'f')
953 if (c
>= 'A' && c
<= 'F')
959 char *hexmem(const void *p
, size_t l
) {
963 z
= r
= malloc(l
* 2 + 1);
967 for (x
= p
; x
< (const uint8_t*) p
+ l
; x
++) {
968 *(z
++) = hexchar(*x
>> 4);
969 *(z
++) = hexchar(*x
& 15);
976 int unhexmem(const char *p
, size_t l
, void **mem
, size_t *len
) {
977 _cleanup_free_
uint8_t *r
= NULL
;
985 z
= r
= malloc((l
+ 1) / 2 + 1);
989 for (x
= p
; x
< p
+ l
; x
+= 2) {
995 else if (x
+1 < p
+ l
) {
1002 *(z
++) = (uint8_t) a
<< 4 | (uint8_t) b
;
1014 /* https://tools.ietf.org/html/rfc4648#section-6
1015 * Notice that base32hex differs from base32 in the alphabet it uses.
1016 * The distinction is that the base32hex representation preserves the
1017 * order of the underlying data when compared as bytestrings, this is
1018 * useful when representing NSEC3 hashes, as one can then verify the
1019 * order of hashes directly from their representation. */
1020 char base32hexchar(int x
) {
1021 static const char table
[32] = "0123456789"
1022 "ABCDEFGHIJKLMNOPQRSTUV";
1024 return table
[x
& 31];
1027 int unbase32hexchar(char c
) {
1030 if (c
>= '0' && c
<= '9')
1033 offset
= '9' - '0' + 1;
1035 if (c
>= 'A' && c
<= 'V')
1036 return c
- 'A' + offset
;
1041 char *base32hexmem(const void *p
, size_t l
, bool padding
) {
1047 /* five input bytes makes eight output bytes, padding is added so we must round up */
1048 len
= 8 * (l
+ 4) / 5;
1050 /* same, but round down as there is no padding */
1069 z
= r
= malloc(len
+ 1);
1073 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 5) * 5; x
+= 5) {
1074 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ
1075 x[3] == QQQQQQQQ; x[4] == WWWWWWWW */
1076 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1077 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1078 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1079 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1080 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
1081 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
1082 *(z
++) = base32hexchar((x
[3] & 3) << 3 | x
[4] >> 5); /* 000QQWWW */
1083 *(z
++) = base32hexchar((x
[4] & 31)); /* 000WWWWW */
1088 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1089 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1090 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1091 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1092 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
1093 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
1094 *(z
++) = base32hexchar((x
[3] & 3) << 3); /* 000QQ000 */
1101 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1102 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1103 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1104 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1105 *(z
++) = base32hexchar((x
[2] & 15) << 1); /* 000ZZZZ0 */
1115 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1116 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1117 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1118 *(z
++) = base32hexchar((x
[1] & 1) << 4); /* 000Y0000 */
1129 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1130 *(z
++) = base32hexchar((x
[0] & 7) << 2); /* 000XXX00 */
1147 int unbase32hexmem(const char *p
, size_t l
, bool padding
, void **mem
, size_t *_len
) {
1148 _cleanup_free_
uint8_t *r
= NULL
;
1149 int a
, b
, c
, d
, e
, f
, g
, h
;
1157 /* padding ensures any base32hex input has input divisible by 8 */
1158 if (padding
&& l
% 8 != 0)
1162 /* strip the padding */
1163 while (l
> 0 && p
[l
- 1] == '=' && pad
< 7) {
1169 /* a group of eight input bytes needs five output bytes, in case of
1170 padding we need to add some extra bytes */
1192 z
= r
= malloc(len
+ 1);
1196 for (x
= p
; x
< p
+ (l
/ 8) * 8; x
+= 8) {
1197 /* a == 000XXXXX; b == 000YYYYY; c == 000ZZZZZ; d == 000WWWWW
1198 e == 000SSSSS; f == 000QQQQQ; g == 000VVVVV; h == 000RRRRR */
1199 a
= unbase32hexchar(x
[0]);
1203 b
= unbase32hexchar(x
[1]);
1207 c
= unbase32hexchar(x
[2]);
1211 d
= unbase32hexchar(x
[3]);
1215 e
= unbase32hexchar(x
[4]);
1219 f
= unbase32hexchar(x
[5]);
1223 g
= unbase32hexchar(x
[6]);
1227 h
= unbase32hexchar(x
[7]);
1231 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1232 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1233 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1234 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
1235 *(z
++) = (uint8_t) g
<< 5 | (uint8_t) h
; /* VVVRRRRR */
1240 a
= unbase32hexchar(x
[0]);
1244 b
= unbase32hexchar(x
[1]);
1248 c
= unbase32hexchar(x
[2]);
1252 d
= unbase32hexchar(x
[3]);
1256 e
= unbase32hexchar(x
[4]);
1260 f
= unbase32hexchar(x
[5]);
1264 g
= unbase32hexchar(x
[6]);
1272 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1273 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1274 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1275 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
1279 a
= unbase32hexchar(x
[0]);
1283 b
= unbase32hexchar(x
[1]);
1287 c
= unbase32hexchar(x
[2]);
1291 d
= unbase32hexchar(x
[3]);
1295 e
= unbase32hexchar(x
[4]);
1303 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1304 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1305 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1309 a
= unbase32hexchar(x
[0]);
1313 b
= unbase32hexchar(x
[1]);
1317 c
= unbase32hexchar(x
[2]);
1321 d
= unbase32hexchar(x
[3]);
1329 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1330 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1334 a
= unbase32hexchar(x
[0]);
1338 b
= unbase32hexchar(x
[1]);
1346 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1364 /* https://tools.ietf.org/html/rfc4648#section-4 */
1365 char base64char(int x
) {
1366 static const char table
[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1367 "abcdefghijklmnopqrstuvwxyz"
1369 return table
[x
& 63];
1372 int unbase64char(char c
) {
1375 if (c
>= 'A' && c
<= 'Z')
1378 offset
= 'Z' - 'A' + 1;
1380 if (c
>= 'a' && c
<= 'z')
1381 return c
- 'a' + offset
;
1383 offset
+= 'z' - 'a' + 1;
1385 if (c
>= '0' && c
<= '9')
1386 return c
- '0' + offset
;
1388 offset
+= '9' - '0' + 1;
1401 char *base64mem(const void *p
, size_t l
) {
1405 /* three input bytes makes four output bytes, padding is added so we must round up */
1406 z
= r
= malloc(4 * (l
+ 2) / 3 + 1);
1410 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 3) * 3; x
+= 3) {
1411 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ */
1412 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1413 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1414 *(z
++) = base64char((x
[1] & 15) << 2 | x
[2] >> 6); /* 00YYYYZZ */
1415 *(z
++) = base64char(x
[2] & 63); /* 00ZZZZZZ */
1420 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1421 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1422 *(z
++) = base64char((x
[1] & 15) << 2); /* 00YYYY00 */
1427 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1428 *(z
++) = base64char((x
[0] & 3) << 4); /* 00XX0000 */
1439 int unbase64mem(const char *p
, size_t l
, void **mem
, size_t *_len
) {
1440 _cleanup_free_
uint8_t *r
= NULL
;
1448 /* padding ensures any base63 input has input divisible by 4 */
1452 /* strip the padding */
1453 if (l
> 0 && p
[l
- 1] == '=')
1455 if (l
> 0 && p
[l
- 1] == '=')
1458 /* a group of four input bytes needs three output bytes, in case of
1459 padding we need to add two or three extra bytes */
1460 len
= (l
/ 4) * 3 + (l
% 4 ? (l
% 4) - 1 : 0);
1462 z
= r
= malloc(len
+ 1);
1466 for (x
= p
; x
< p
+ (l
/ 4) * 4; x
+= 4) {
1467 /* a == 00XXXXXX; b == 00YYYYYY; c == 00ZZZZZZ; d == 00WWWWWW */
1468 a
= unbase64char(x
[0]);
1472 b
= unbase64char(x
[1]);
1476 c
= unbase64char(x
[2]);
1480 d
= unbase64char(x
[3]);
1484 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1485 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1486 *(z
++) = (uint8_t) c
<< 6 | (uint8_t) d
; /* ZZWWWWWW */
1491 a
= unbase64char(x
[0]);
1495 b
= unbase64char(x
[1]);
1499 c
= unbase64char(x
[2]);
1507 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1508 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1512 a
= unbase64char(x
[0]);
1516 b
= unbase64char(x
[1]);
1524 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) (b
>> 4); /* XXXXXXYY */
1543 char octchar(int x
) {
1544 return '0' + (x
& 7);
1547 int unoctchar(char c
) {
1549 if (c
>= '0' && c
<= '7')
1555 char decchar(int x
) {
1556 return '0' + (x
% 10);
1559 int undecchar(char c
) {
1561 if (c
>= '0' && c
<= '9')
1567 char *cescape(const char *s
) {
1573 /* Does C style string escaping. May be reversed with
1576 r
= new(char, strlen(s
)*4 + 1);
1580 for (f
= s
, t
= r
; *f
; f
++)
1581 t
+= cescape_char(*f
, t
);
1588 static int cunescape_one(const char *p
, size_t length
, char *ret
, uint32_t *ret_unicode
) {
1595 /* Unescapes C style. Returns the unescaped character in ret,
1596 * unless we encountered a \u sequence in which case the full
1597 * unicode character is returned in ret_unicode, instead. */
1599 if (length
!= (size_t) -1 && length
< 1)
1636 /* This is an extension of the XDG syntax files */
1641 /* hexadecimal encoding */
1644 if (length
!= (size_t) -1 && length
< 3)
1647 a
= unhexchar(p
[1]);
1651 b
= unhexchar(p
[2]);
1655 /* Don't allow NUL bytes */
1656 if (a
== 0 && b
== 0)
1659 *ret
= (char) ((a
<< 4U) | b
);
1665 /* C++11 style 16bit unicode */
1671 if (length
!= (size_t) -1 && length
< 5)
1674 for (i
= 0; i
< 4; i
++) {
1675 a
[i
] = unhexchar(p
[1 + i
]);
1680 c
= ((uint32_t) a
[0] << 12U) | ((uint32_t) a
[1] << 8U) | ((uint32_t) a
[2] << 4U) | (uint32_t) a
[3];
1682 /* Don't allow 0 chars */
1701 /* C++11 style 32bit unicode */
1707 if (length
!= (size_t) -1 && length
< 9)
1710 for (i
= 0; i
< 8; i
++) {
1711 a
[i
] = unhexchar(p
[1 + i
]);
1716 c
= ((uint32_t) a
[0] << 28U) | ((uint32_t) a
[1] << 24U) | ((uint32_t) a
[2] << 20U) | ((uint32_t) a
[3] << 16U) |
1717 ((uint32_t) a
[4] << 12U) | ((uint32_t) a
[5] << 8U) | ((uint32_t) a
[6] << 4U) | (uint32_t) a
[7];
1719 /* Don't allow 0 chars */
1723 /* Don't allow invalid code points */
1724 if (!unichar_is_valid(c
))
1749 /* octal encoding */
1753 if (length
!= (size_t) -1 && length
< 3)
1756 a
= unoctchar(p
[0]);
1760 b
= unoctchar(p
[1]);
1764 c
= unoctchar(p
[2]);
1768 /* don't allow NUL bytes */
1769 if (a
== 0 && b
== 0 && c
== 0)
1772 /* Don't allow bytes above 255 */
1773 m
= ((uint32_t) a
<< 6U) | ((uint32_t) b
<< 3U) | (uint32_t) c
;
1789 int cunescape_length_with_prefix(const char *s
, size_t length
, const char *prefix
, UnescapeFlags flags
, char **ret
) {
1797 /* Undoes C style string escaping, and optionally prefixes it. */
1799 pl
= prefix
? strlen(prefix
) : 0;
1801 r
= new(char, pl
+length
+1);
1806 memcpy(r
, prefix
, pl
);
1808 for (f
= s
, t
= r
+ pl
; f
< s
+ length
; f
++) {
1814 remaining
= s
+ length
- f
;
1815 assert(remaining
> 0);
1818 /* A literal literal, copy verbatim */
1823 if (remaining
== 1) {
1824 if (flags
& UNESCAPE_RELAX
) {
1825 /* A trailing backslash, copy verbatim */
1834 k
= cunescape_one(f
+ 1, remaining
- 1, &c
, &u
);
1836 if (flags
& UNESCAPE_RELAX
) {
1837 /* Invalid escape code, let's take it literal then */
1847 /* Non-Unicode? Let's encode this directly */
1850 /* Unicode? Then let's encode this in UTF-8 */
1851 t
+= utf8_encode_unichar(t
, u
);
1862 int cunescape_length(const char *s
, size_t length
, UnescapeFlags flags
, char **ret
) {
1863 return cunescape_length_with_prefix(s
, length
, NULL
, flags
, ret
);
1866 int cunescape(const char *s
, UnescapeFlags flags
, char **ret
) {
1867 return cunescape_length(s
, strlen(s
), flags
, ret
);
1870 char *xescape(const char *s
, const char *bad
) {
1874 /* Escapes all chars in bad, in addition to \ and all special
1875 * chars, in \xFF style escaping. May be reversed with
1878 r
= new(char, strlen(s
) * 4 + 1);
1882 for (f
= s
, t
= r
; *f
; f
++) {
1884 if ((*f
< ' ') || (*f
>= 127) ||
1885 (*f
== '\\') || strchr(bad
, *f
)) {
1888 *(t
++) = hexchar(*f
>> 4);
1889 *(t
++) = hexchar(*f
);
1899 char *ascii_strlower(char *t
) {
1904 for (p
= t
; *p
; p
++)
1905 if (*p
>= 'A' && *p
<= 'Z')
1906 *p
= *p
- 'A' + 'a';
1911 _pure_
static bool hidden_file_allow_backup(const char *filename
) {
1915 filename
[0] == '.' ||
1916 streq(filename
, "lost+found") ||
1917 streq(filename
, "aquota.user") ||
1918 streq(filename
, "aquota.group") ||
1919 endswith(filename
, ".rpmnew") ||
1920 endswith(filename
, ".rpmsave") ||
1921 endswith(filename
, ".rpmorig") ||
1922 endswith(filename
, ".dpkg-old") ||
1923 endswith(filename
, ".dpkg-new") ||
1924 endswith(filename
, ".dpkg-tmp") ||
1925 endswith(filename
, ".dpkg-dist") ||
1926 endswith(filename
, ".dpkg-bak") ||
1927 endswith(filename
, ".dpkg-backup") ||
1928 endswith(filename
, ".dpkg-remove") ||
1929 endswith(filename
, ".swp");
1932 bool hidden_file(const char *filename
) {
1935 if (endswith(filename
, "~"))
1938 return hidden_file_allow_backup(filename
);
1941 int fd_nonblock(int fd
, bool nonblock
) {
1946 flags
= fcntl(fd
, F_GETFL
, 0);
1951 nflags
= flags
| O_NONBLOCK
;
1953 nflags
= flags
& ~O_NONBLOCK
;
1955 if (nflags
== flags
)
1958 if (fcntl(fd
, F_SETFL
, nflags
) < 0)
1964 int fd_cloexec(int fd
, bool cloexec
) {
1969 flags
= fcntl(fd
, F_GETFD
, 0);
1974 nflags
= flags
| FD_CLOEXEC
;
1976 nflags
= flags
& ~FD_CLOEXEC
;
1978 if (nflags
== flags
)
1981 if (fcntl(fd
, F_SETFD
, nflags
) < 0)
1987 _pure_
static bool fd_in_set(int fd
, const int fdset
[], unsigned n_fdset
) {
1990 assert(n_fdset
== 0 || fdset
);
1992 for (i
= 0; i
< n_fdset
; i
++)
1999 int close_all_fds(const int except
[], unsigned n_except
) {
2000 _cleanup_closedir_
DIR *d
= NULL
;
2004 assert(n_except
== 0 || except
);
2006 d
= opendir("/proc/self/fd");
2011 /* When /proc isn't available (for example in chroots)
2012 * the fallback is brute forcing through the fd
2015 assert_se(getrlimit(RLIMIT_NOFILE
, &rl
) >= 0);
2016 for (fd
= 3; fd
< (int) rl
.rlim_max
; fd
++) {
2018 if (fd_in_set(fd
, except
, n_except
))
2021 if (close_nointr(fd
) < 0)
2022 if (errno
!= EBADF
&& r
== 0)
2029 while ((de
= readdir(d
))) {
2032 if (hidden_file(de
->d_name
))
2035 if (safe_atoi(de
->d_name
, &fd
) < 0)
2036 /* Let's better ignore this, just in case */
2045 if (fd_in_set(fd
, except
, n_except
))
2048 if (close_nointr(fd
) < 0) {
2049 /* Valgrind has its own FD and doesn't want to have it closed */
2050 if (errno
!= EBADF
&& r
== 0)
2058 bool chars_intersect(const char *a
, const char *b
) {
2061 /* Returns true if any of the chars in a are in b. */
2062 for (p
= a
; *p
; p
++)
2069 bool fstype_is_network(const char *fstype
) {
2070 static const char table
[] =
2085 x
= startswith(fstype
, "fuse.");
2089 return nulstr_contains(table
, fstype
);
2092 int flush_fd(int fd
) {
2093 struct pollfd pollfd
= {
2103 r
= poll(&pollfd
, 1, 0);
2113 l
= read(fd
, buf
, sizeof(buf
));
2119 if (errno
== EAGAIN
)
2128 void safe_close_pair(int p
[]) {
2132 /* Special case pairs which use the same fd in both
2134 p
[0] = p
[1] = safe_close(p
[0]);
2138 p
[0] = safe_close(p
[0]);
2139 p
[1] = safe_close(p
[1]);
2142 ssize_t
loop_read(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2149 /* If called with nbytes == 0, let's call read() at least
2150 * once, to validate the operation */
2152 if (nbytes
> (size_t) SSIZE_MAX
)
2158 k
= read(fd
, p
, nbytes
);
2163 if (errno
== EAGAIN
&& do_poll
) {
2165 /* We knowingly ignore any return value here,
2166 * and expect that any error/EOF is reported
2169 (void) fd_wait_for_event(fd
, POLLIN
, USEC_INFINITY
);
2173 return n
> 0 ? n
: -errno
;
2179 assert((size_t) k
<= nbytes
);
2184 } while (nbytes
> 0);
2189 int loop_read_exact(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2192 n
= loop_read(fd
, buf
, nbytes
, do_poll
);
2195 if ((size_t) n
!= nbytes
)
2201 int loop_write(int fd
, const void *buf
, size_t nbytes
, bool do_poll
) {
2202 const uint8_t *p
= buf
;
2207 if (nbytes
> (size_t) SSIZE_MAX
)
2213 k
= write(fd
, p
, nbytes
);
2218 if (errno
== EAGAIN
&& do_poll
) {
2219 /* We knowingly ignore any return value here,
2220 * and expect that any error/EOF is reported
2223 (void) fd_wait_for_event(fd
, POLLOUT
, USEC_INFINITY
);
2230 if (_unlikely_(nbytes
> 0 && k
== 0)) /* Can't really happen */
2233 assert((size_t) k
<= nbytes
);
2237 } while (nbytes
> 0);
2242 int parse_size(const char *t
, uint64_t base
, uint64_t *size
) {
2244 /* Soo, sometimes we want to parse IEC binary suffixes, and
2245 * sometimes SI decimal suffixes. This function can parse
2246 * both. Which one is the right way depends on the
2247 * context. Wikipedia suggests that SI is customary for
2248 * hardware metrics and network speeds, while IEC is
2249 * customary for most data sizes used by software and volatile
2250 * (RAM) memory. Hence be careful which one you pick!
2252 * In either case we use just K, M, G as suffix, and not Ki,
2253 * Mi, Gi or so (as IEC would suggest). That's because that's
2254 * frickin' ugly. But this means you really need to make sure
2255 * to document which base you are parsing when you use this
2260 unsigned long long factor
;
2263 static const struct table iec
[] = {
2264 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2265 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2266 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2267 { "G", 1024ULL*1024ULL*1024ULL },
2268 { "M", 1024ULL*1024ULL },
2274 static const struct table si
[] = {
2275 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2276 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2277 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2278 { "G", 1000ULL*1000ULL*1000ULL },
2279 { "M", 1000ULL*1000ULL },
2285 const struct table
*table
;
2287 unsigned long long r
= 0;
2288 unsigned n_entries
, start_pos
= 0;
2291 assert(base
== 1000 || base
== 1024);
2296 n_entries
= ELEMENTSOF(si
);
2299 n_entries
= ELEMENTSOF(iec
);
2304 unsigned long long l
, tmp
;
2309 p
+= strspn(p
, WHITESPACE
);
2314 l
= strtoull(p
, &e
, 10);
2323 /* strtoull() itself would accept space/+/- */
2324 if (*e
>= '0' && *e
<= '9') {
2325 unsigned long long l2
;
2328 l2
= strtoull(e
, &e2
, 10);
2332 /* Ignore failure. E.g. 10.M is valid */
2339 e
+= strspn(e
, WHITESPACE
);
2341 for (i
= start_pos
; i
< n_entries
; i
++)
2342 if (startswith(e
, table
[i
].suffix
))
2348 if (l
+ (frac
> 0) > ULLONG_MAX
/ table
[i
].factor
)
2351 tmp
= l
* table
[i
].factor
+ (unsigned long long) (frac
* table
[i
].factor
);
2352 if (tmp
> ULLONG_MAX
- r
)
2356 if ((unsigned long long) (uint64_t) r
!= r
)
2359 p
= e
+ strlen(table
[i
].suffix
);
2370 bool is_device_path(const char *path
) {
2372 /* Returns true on paths that refer to a device, either in
2373 * sysfs or in /dev */
2376 path_startswith(path
, "/dev/") ||
2377 path_startswith(path
, "/sys/");
2380 int dir_is_empty(const char *path
) {
2381 _cleanup_closedir_
DIR *d
;
2392 if (!de
&& errno
!= 0)
2398 if (!hidden_file(de
->d_name
))
2403 char* dirname_malloc(const char *path
) {
2404 char *d
, *dir
, *dir2
;
2421 void rename_process(const char name
[8]) {
2424 /* This is a like a poor man's setproctitle(). It changes the
2425 * comm field, argv[0], and also the glibc's internally used
2426 * name of the process. For the first one a limit of 16 chars
2427 * applies, to the second one usually one of 10 (i.e. length
2428 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2429 * "systemd"). If you pass a longer string it will be
2432 prctl(PR_SET_NAME
, name
);
2434 if (program_invocation_name
)
2435 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
2437 if (saved_argc
> 0) {
2441 strncpy(saved_argv
[0], name
, strlen(saved_argv
[0]));
2443 for (i
= 1; i
< saved_argc
; i
++) {
2447 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
2452 char *lookup_uid(uid_t uid
) {
2455 _cleanup_free_
char *buf
= NULL
;
2456 struct passwd pwbuf
, *pw
= NULL
;
2458 /* Shortcut things to avoid NSS lookups */
2460 return strdup("root");
2462 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
2466 buf
= malloc(bufsize
);
2470 if (getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
) == 0 && pw
)
2471 return strdup(pw
->pw_name
);
2473 if (asprintf(&name
, UID_FMT
, uid
) < 0)
2479 char* getlogname_malloc(void) {
2483 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
2488 return lookup_uid(uid
);
2491 char *getusername_malloc(void) {
2498 return lookup_uid(getuid());
2501 bool is_temporary_fs(const struct statfs
*s
) {
2504 return F_TYPE_EQUAL(s
->f_type
, TMPFS_MAGIC
) ||
2505 F_TYPE_EQUAL(s
->f_type
, RAMFS_MAGIC
);
2508 int fd_is_temporary_fs(int fd
) {
2511 if (fstatfs(fd
, &s
) < 0)
2514 return is_temporary_fs(&s
);
2517 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
2520 /* Under the assumption that we are running privileged we
2521 * first change the access mode and only then hand out
2522 * ownership to avoid a window where access is too open. */
2524 if (mode
!= MODE_INVALID
)
2525 if (chmod(path
, mode
) < 0)
2528 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
2529 if (chown(path
, uid
, gid
) < 0)
2535 int fchmod_and_fchown(int fd
, mode_t mode
, uid_t uid
, gid_t gid
) {
2538 /* Under the assumption that we are running privileged we
2539 * first change the access mode and only then hand out
2540 * ownership to avoid a window where access is too open. */
2542 if (mode
!= MODE_INVALID
)
2543 if (fchmod(fd
, mode
) < 0)
2546 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
2547 if (fchown(fd
, uid
, gid
) < 0)
2553 cpu_set_t
* cpu_set_malloc(unsigned *ncpus
) {
2557 /* Allocates the cpuset in the right size */
2560 if (!(r
= CPU_ALLOC(n
)))
2563 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n
), r
) >= 0) {
2564 CPU_ZERO_S(CPU_ALLOC_SIZE(n
), r
);
2574 if (errno
!= EINVAL
)
2583 cpu_set_t
**cpu_set
,
2585 const char *filename
,
2587 const char *lvalue
) {
2589 const char *whole_rvalue
= rvalue
;
2590 _cleanup_cpu_free_ cpu_set_t
*c
= NULL
;
2598 _cleanup_free_
char *word
= NULL
;
2602 r
= extract_first_word(&rvalue
, &word
, WHITESPACE
, EXTRACT_QUOTES
);
2604 log_syntax(unit
, LOG_ERR
, filename
, line
, r
,
2605 "Invalid value for %s: %s", lvalue
, whole_rvalue
);
2611 r
= safe_atou(word
, &cpu
);
2614 if (!(c
= cpu_set_malloc(&ncpus
)))
2617 if (r
< 0 || cpu
>= ncpus
) {
2618 log_syntax(unit
, LOG_ERR
, filename
, line
, -r
,
2619 "Failed to parse CPU affinity '%s'", rvalue
);
2623 CPU_SET_S(cpu
, CPU_ALLOC_SIZE(ncpus
), c
);
2625 if (!isempty(rvalue
))
2626 log_syntax(unit
, LOG_ERR
, filename
, line
, EINVAL
,
2627 "Trailing garbage, ignoring.");
2629 /* On success, sets *cpu_set and returns ncpus for the system. */
2637 int files_same(const char *filea
, const char *fileb
) {
2640 if (stat(filea
, &a
) < 0)
2643 if (stat(fileb
, &b
) < 0)
2646 return a
.st_dev
== b
.st_dev
&&
2647 a
.st_ino
== b
.st_ino
;
2650 int running_in_chroot(void) {
2653 ret
= files_same("/proc/1/root", "/");
2660 static char *ascii_ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
2665 assert(percent
<= 100);
2666 assert(new_length
>= 3);
2668 if (old_length
<= 3 || old_length
<= new_length
)
2669 return strndup(s
, old_length
);
2671 r
= new0(char, new_length
+1);
2675 x
= (new_length
* percent
) / 100;
2677 if (x
> new_length
- 3)
2685 s
+ old_length
- (new_length
- x
- 3),
2686 new_length
- x
- 3);
2691 char *ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
2695 unsigned k
, len
, len2
;
2698 assert(percent
<= 100);
2699 assert(new_length
>= 3);
2701 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2702 if (ascii_is_valid(s
))
2703 return ascii_ellipsize_mem(s
, old_length
, new_length
, percent
);
2705 if (old_length
<= 3 || old_length
<= new_length
)
2706 return strndup(s
, old_length
);
2708 x
= (new_length
* percent
) / 100;
2710 if (x
> new_length
- 3)
2714 for (i
= s
; k
< x
&& i
< s
+ old_length
; i
= utf8_next_char(i
)) {
2717 c
= utf8_encoded_to_unichar(i
);
2720 k
+= unichar_iswide(c
) ? 2 : 1;
2723 if (k
> x
) /* last character was wide and went over quota */
2726 for (j
= s
+ old_length
; k
< new_length
&& j
> i
; ) {
2729 j
= utf8_prev_char(j
);
2730 c
= utf8_encoded_to_unichar(j
);
2733 k
+= unichar_iswide(c
) ? 2 : 1;
2737 /* we don't actually need to ellipsize */
2739 return memdup(s
, old_length
+ 1);
2741 /* make space for ellipsis */
2742 j
= utf8_next_char(j
);
2745 len2
= s
+ old_length
- j
;
2746 e
= new(char, len
+ 3 + len2
+ 1);
2751 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2752 old_length, new_length, x, len, len2, k);
2756 e
[len
] = 0xe2; /* tri-dot ellipsis: … */
2760 memcpy(e
+ len
+ 3, j
, len2
+ 1);
2765 char *ellipsize(const char *s
, size_t length
, unsigned percent
) {
2766 return ellipsize_mem(s
, strlen(s
), length
, percent
);
2769 int touch_file(const char *path
, bool parents
, usec_t stamp
, uid_t uid
, gid_t gid
, mode_t mode
) {
2770 _cleanup_close_
int fd
;
2776 mkdir_parents(path
, 0755);
2778 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, mode
> 0 ? mode
: 0644);
2783 r
= fchmod(fd
, mode
);
2788 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
) {
2789 r
= fchown(fd
, uid
, gid
);
2794 if (stamp
!= USEC_INFINITY
) {
2795 struct timespec ts
[2];
2797 timespec_store(&ts
[0], stamp
);
2799 r
= futimens(fd
, ts
);
2801 r
= futimens(fd
, NULL
);
2808 int touch(const char *path
) {
2809 return touch_file(path
, false, USEC_INFINITY
, UID_INVALID
, GID_INVALID
, 0);
2812 static char *unquote(const char *s
, const char* quotes
) {
2816 /* This is rather stupid, simply removes the heading and
2817 * trailing quotes if there is one. Doesn't care about
2818 * escaping or anything.
2820 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2826 if (strchr(quotes
, s
[0]) && s
[l
-1] == s
[0])
2827 return strndup(s
+1, l
-2);
2832 noreturn
void freeze(void) {
2834 /* Make sure nobody waits for us on a socket anymore */
2835 close_all_fds(NULL
, 0);
2843 bool null_or_empty(struct stat
*st
) {
2846 if (S_ISREG(st
->st_mode
) && st
->st_size
<= 0)
2849 if (S_ISCHR(st
->st_mode
) || S_ISBLK(st
->st_mode
))
2855 int null_or_empty_path(const char *fn
) {
2860 if (stat(fn
, &st
) < 0)
2863 return null_or_empty(&st
);
2866 int null_or_empty_fd(int fd
) {
2871 if (fstat(fd
, &st
) < 0)
2874 return null_or_empty(&st
);
2877 DIR *xopendirat(int fd
, const char *name
, int flags
) {
2881 assert(!(flags
& O_CREAT
));
2883 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
2896 static char *tag_to_udev_node(const char *tagvalue
, const char *by
) {
2897 _cleanup_free_
char *t
= NULL
, *u
= NULL
;
2900 u
= unquote(tagvalue
, QUOTES
);
2904 enc_len
= strlen(u
) * 4 + 1;
2905 t
= new(char, enc_len
);
2909 if (encode_devnode_name(u
, t
, enc_len
) < 0)
2912 return strjoin("/dev/disk/by-", by
, "/", t
, NULL
);
2915 char *fstab_node_to_udev_node(const char *p
) {
2918 if (startswith(p
, "LABEL="))
2919 return tag_to_udev_node(p
+6, "label");
2921 if (startswith(p
, "UUID="))
2922 return tag_to_udev_node(p
+5, "uuid");
2924 if (startswith(p
, "PARTUUID="))
2925 return tag_to_udev_node(p
+9, "partuuid");
2927 if (startswith(p
, "PARTLABEL="))
2928 return tag_to_udev_node(p
+10, "partlabel");
2933 bool dirent_is_file(const struct dirent
*de
) {
2936 if (hidden_file(de
->d_name
))
2939 if (de
->d_type
!= DT_REG
&&
2940 de
->d_type
!= DT_LNK
&&
2941 de
->d_type
!= DT_UNKNOWN
)
2947 bool dirent_is_file_with_suffix(const struct dirent
*de
, const char *suffix
) {
2950 if (de
->d_type
!= DT_REG
&&
2951 de
->d_type
!= DT_LNK
&&
2952 de
->d_type
!= DT_UNKNOWN
)
2955 if (hidden_file_allow_backup(de
->d_name
))
2958 return endswith(de
->d_name
, suffix
);
2961 static int do_execute(char **directories
, usec_t timeout
, char *argv
[]) {
2962 _cleanup_hashmap_free_free_ Hashmap
*pids
= NULL
;
2963 _cleanup_set_free_free_ Set
*seen
= NULL
;
2966 /* We fork this all off from a child process so that we can
2967 * somewhat cleanly make use of SIGALRM to set a time limit */
2969 (void) reset_all_signal_handlers();
2970 (void) reset_signal_mask();
2972 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
2974 pids
= hashmap_new(NULL
);
2978 seen
= set_new(&string_hash_ops
);
2982 STRV_FOREACH(directory
, directories
) {
2983 _cleanup_closedir_
DIR *d
;
2986 d
= opendir(*directory
);
2988 if (errno
== ENOENT
)
2991 return log_error_errno(errno
, "Failed to open directory %s: %m", *directory
);
2994 FOREACH_DIRENT(de
, d
, break) {
2995 _cleanup_free_
char *path
= NULL
;
2999 if (!dirent_is_file(de
))
3002 if (set_contains(seen
, de
->d_name
)) {
3003 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory
, de
->d_name
);
3007 r
= set_put_strdup(seen
, de
->d_name
);
3011 path
= strjoin(*directory
, "/", de
->d_name
, NULL
);
3015 if (null_or_empty_path(path
)) {
3016 log_debug("%s is empty (a mask).", path
);
3022 log_error_errno(errno
, "Failed to fork: %m");
3024 } else if (pid
== 0) {
3027 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
3037 return log_error_errno(errno
, "Failed to execute %s: %m", path
);
3040 log_debug("Spawned %s as " PID_FMT
".", path
, pid
);
3042 r
= hashmap_put(pids
, UINT_TO_PTR(pid
), path
);
3049 /* Abort execution of this process after the timout. We simply
3050 * rely on SIGALRM as default action terminating the process,
3051 * and turn on alarm(). */
3053 if (timeout
!= USEC_INFINITY
)
3054 alarm((timeout
+ USEC_PER_SEC
- 1) / USEC_PER_SEC
);
3056 while (!hashmap_isempty(pids
)) {
3057 _cleanup_free_
char *path
= NULL
;
3060 pid
= PTR_TO_UINT(hashmap_first_key(pids
));
3063 path
= hashmap_remove(pids
, UINT_TO_PTR(pid
));
3066 wait_for_terminate_and_warn(path
, pid
, true);
3072 void execute_directories(const char* const* directories
, usec_t timeout
, char *argv
[]) {
3076 char **dirs
= (char**) directories
;
3078 assert(!strv_isempty(dirs
));
3080 name
= basename(dirs
[0]);
3081 assert(!isempty(name
));
3083 /* Executes all binaries in the directories in parallel and waits
3084 * for them to finish. Optionally a timeout is applied. If a file
3085 * with the same name exists in more than one directory, the
3086 * earliest one wins. */
3088 executor_pid
= fork();
3089 if (executor_pid
< 0) {
3090 log_error_errno(errno
, "Failed to fork: %m");
3093 } else if (executor_pid
== 0) {
3094 r
= do_execute(dirs
, timeout
, argv
);
3095 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
3098 wait_for_terminate_and_warn(name
, executor_pid
, true);
3101 bool nulstr_contains(const char*nulstr
, const char *needle
) {
3107 NULSTR_FOREACH(i
, nulstr
)
3108 if (streq(i
, needle
))
3114 bool plymouth_running(void) {
3115 return access("/run/plymouth/pid", F_OK
) >= 0;
3118 char* strshorten(char *s
, size_t l
) {
3127 int pipe_eof(int fd
) {
3128 struct pollfd pollfd
= {
3130 .events
= POLLIN
|POLLHUP
,
3135 r
= poll(&pollfd
, 1, 0);
3142 return pollfd
.revents
& POLLHUP
;
3145 int fd_wait_for_event(int fd
, int event
, usec_t t
) {
3147 struct pollfd pollfd
= {
3155 r
= ppoll(&pollfd
, 1, t
== USEC_INFINITY
? NULL
: timespec_store(&ts
, t
), NULL
);
3162 return pollfd
.revents
;
3165 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
3174 r
= tempfn_xxxxxx(path
, NULL
, &t
);
3178 fd
= mkostemp_safe(t
, O_WRONLY
|O_CLOEXEC
);
3184 f
= fdopen(fd
, "we");
3198 int symlink_atomic(const char *from
, const char *to
) {
3199 _cleanup_free_
char *t
= NULL
;
3205 r
= tempfn_random(to
, NULL
, &t
);
3209 if (symlink(from
, t
) < 0)
3212 if (rename(t
, to
) < 0) {
3220 int symlink_idempotent(const char *from
, const char *to
) {
3221 _cleanup_free_
char *p
= NULL
;
3227 if (symlink(from
, to
) < 0) {
3228 if (errno
!= EEXIST
)
3231 r
= readlink_malloc(to
, &p
);
3235 if (!streq(p
, from
))
3242 int mknod_atomic(const char *path
, mode_t mode
, dev_t dev
) {
3243 _cleanup_free_
char *t
= NULL
;
3248 r
= tempfn_random(path
, NULL
, &t
);
3252 if (mknod(t
, mode
, dev
) < 0)
3255 if (rename(t
, path
) < 0) {
3263 int mkfifo_atomic(const char *path
, mode_t mode
) {
3264 _cleanup_free_
char *t
= NULL
;
3269 r
= tempfn_random(path
, NULL
, &t
);
3273 if (mkfifo(t
, mode
) < 0)
3276 if (rename(t
, path
) < 0) {
3284 bool display_is_local(const char *display
) {
3288 display
[0] == ':' &&
3289 display
[1] >= '0' &&
3293 int socket_from_display(const char *display
, char **path
) {
3300 if (!display_is_local(display
))
3303 k
= strspn(display
+1, "0123456789");
3305 f
= new(char, strlen("/tmp/.X11-unix/X") + k
+ 1);
3309 c
= stpcpy(f
, "/tmp/.X11-unix/X");
3310 memcpy(c
, display
+1, k
);
3319 const char **username
,
3320 uid_t
*uid
, gid_t
*gid
,
3322 const char **shell
) {
3330 /* We enforce some special rules for uid=0: in order to avoid
3331 * NSS lookups for root we hardcode its data. */
3333 if (streq(*username
, "root") || streq(*username
, "0")) {
3351 if (parse_uid(*username
, &u
) >= 0) {
3355 /* If there are multiple users with the same id, make
3356 * sure to leave $USER to the configured value instead
3357 * of the first occurrence in the database. However if
3358 * the uid was configured by a numeric uid, then let's
3359 * pick the real username from /etc/passwd. */
3361 *username
= p
->pw_name
;
3364 p
= getpwnam(*username
);
3368 return errno
> 0 ? -errno
: -ESRCH
;
3380 *shell
= p
->pw_shell
;
3385 char* uid_to_name(uid_t uid
) {
3390 return strdup("root");
3394 return strdup(p
->pw_name
);
3396 if (asprintf(&r
, UID_FMT
, uid
) < 0)
3402 char* gid_to_name(gid_t gid
) {
3407 return strdup("root");
3411 return strdup(p
->gr_name
);
3413 if (asprintf(&r
, GID_FMT
, gid
) < 0)
3419 int get_group_creds(const char **groupname
, gid_t
*gid
) {
3425 /* We enforce some special rules for gid=0: in order to avoid
3426 * NSS lookups for root we hardcode its data. */
3428 if (streq(*groupname
, "root") || streq(*groupname
, "0")) {
3429 *groupname
= "root";
3437 if (parse_gid(*groupname
, &id
) >= 0) {
3442 *groupname
= g
->gr_name
;
3445 g
= getgrnam(*groupname
);
3449 return errno
> 0 ? -errno
: -ESRCH
;
3457 int in_gid(gid_t gid
) {
3459 int ngroups_max
, r
, i
;
3461 if (getgid() == gid
)
3464 if (getegid() == gid
)
3467 ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
3468 assert(ngroups_max
> 0);
3470 gids
= alloca(sizeof(gid_t
) * ngroups_max
);
3472 r
= getgroups(ngroups_max
, gids
);
3476 for (i
= 0; i
< r
; i
++)
3483 int in_group(const char *name
) {
3487 r
= get_group_creds(&name
, &gid
);
3494 int glob_exists(const char *path
) {
3495 _cleanup_globfree_ glob_t g
= {};
3501 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
3503 if (k
== GLOB_NOMATCH
)
3505 else if (k
== GLOB_NOSPACE
)
3508 return !strv_isempty(g
.gl_pathv
);
3510 return errno
? -errno
: -EIO
;
3513 int glob_extend(char ***strv
, const char *path
) {
3514 _cleanup_globfree_ glob_t g
= {};
3519 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
3521 if (k
== GLOB_NOMATCH
)
3523 else if (k
== GLOB_NOSPACE
)
3525 else if (k
!= 0 || strv_isempty(g
.gl_pathv
))
3526 return errno
? -errno
: -EIO
;
3528 STRV_FOREACH(p
, g
.gl_pathv
) {
3529 k
= strv_extend(strv
, *p
);
3537 int dirent_ensure_type(DIR *d
, struct dirent
*de
) {
3543 if (de
->d_type
!= DT_UNKNOWN
)
3546 if (fstatat(dirfd(d
), de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
3550 S_ISREG(st
.st_mode
) ? DT_REG
:
3551 S_ISDIR(st
.st_mode
) ? DT_DIR
:
3552 S_ISLNK(st
.st_mode
) ? DT_LNK
:
3553 S_ISFIFO(st
.st_mode
) ? DT_FIFO
:
3554 S_ISSOCK(st
.st_mode
) ? DT_SOCK
:
3555 S_ISCHR(st
.st_mode
) ? DT_CHR
:
3556 S_ISBLK(st
.st_mode
) ? DT_BLK
:
3562 int get_files_in_directory(const char *path
, char ***list
) {
3563 _cleanup_closedir_
DIR *d
= NULL
;
3564 size_t bufsize
= 0, n
= 0;
3565 _cleanup_strv_free_
char **l
= NULL
;
3569 /* Returns all files in a directory in *list, and the number
3570 * of files as return value. If list is NULL returns only the
3582 if (!de
&& errno
!= 0)
3587 dirent_ensure_type(d
, de
);
3589 if (!dirent_is_file(de
))
3593 /* one extra slot is needed for the terminating NULL */
3594 if (!GREEDY_REALLOC(l
, bufsize
, n
+ 2))
3597 l
[n
] = strdup(de
->d_name
);
3608 l
= NULL
; /* avoid freeing */
3614 char *strjoin(const char *x
, ...) {
3628 t
= va_arg(ap
, const char *);
3633 if (n
> ((size_t) -1) - l
) {
3657 t
= va_arg(ap
, const char *);
3671 bool is_main_thread(void) {
3672 static thread_local
int cached
= 0;
3674 if (_unlikely_(cached
== 0))
3675 cached
= getpid() == gettid() ? 1 : -1;
3680 int block_get_whole_disk(dev_t d
, dev_t
*ret
) {
3687 /* If it has a queue this is good enough for us */
3688 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", major(d
), minor(d
)) < 0)
3691 r
= access(p
, F_OK
);
3699 /* If it is a partition find the originating device */
3700 if (asprintf(&p
, "/sys/dev/block/%u:%u/partition", major(d
), minor(d
)) < 0)
3703 r
= access(p
, F_OK
);
3709 /* Get parent dev_t */
3710 if (asprintf(&p
, "/sys/dev/block/%u:%u/../dev", major(d
), minor(d
)) < 0)
3713 r
= read_one_line_file(p
, &s
);
3719 r
= sscanf(s
, "%u:%u", &m
, &n
);
3725 /* Only return this if it is really good enough for us. */
3726 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", m
, n
) < 0)
3729 r
= access(p
, F_OK
);
3733 *ret
= makedev(m
, n
);
3740 static const char *const ioprio_class_table
[] = {
3741 [IOPRIO_CLASS_NONE
] = "none",
3742 [IOPRIO_CLASS_RT
] = "realtime",
3743 [IOPRIO_CLASS_BE
] = "best-effort",
3744 [IOPRIO_CLASS_IDLE
] = "idle"
3747 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, INT_MAX
);
3749 static const char *const sigchld_code_table
[] = {
3750 [CLD_EXITED
] = "exited",
3751 [CLD_KILLED
] = "killed",
3752 [CLD_DUMPED
] = "dumped",
3753 [CLD_TRAPPED
] = "trapped",
3754 [CLD_STOPPED
] = "stopped",
3755 [CLD_CONTINUED
] = "continued",
3758 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
3760 static const char *const log_facility_unshifted_table
[LOG_NFACILITIES
] = {
3761 [LOG_FAC(LOG_KERN
)] = "kern",
3762 [LOG_FAC(LOG_USER
)] = "user",
3763 [LOG_FAC(LOG_MAIL
)] = "mail",
3764 [LOG_FAC(LOG_DAEMON
)] = "daemon",
3765 [LOG_FAC(LOG_AUTH
)] = "auth",
3766 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
3767 [LOG_FAC(LOG_LPR
)] = "lpr",
3768 [LOG_FAC(LOG_NEWS
)] = "news",
3769 [LOG_FAC(LOG_UUCP
)] = "uucp",
3770 [LOG_FAC(LOG_CRON
)] = "cron",
3771 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
3772 [LOG_FAC(LOG_FTP
)] = "ftp",
3773 [LOG_FAC(LOG_LOCAL0
)] = "local0",
3774 [LOG_FAC(LOG_LOCAL1
)] = "local1",
3775 [LOG_FAC(LOG_LOCAL2
)] = "local2",
3776 [LOG_FAC(LOG_LOCAL3
)] = "local3",
3777 [LOG_FAC(LOG_LOCAL4
)] = "local4",
3778 [LOG_FAC(LOG_LOCAL5
)] = "local5",
3779 [LOG_FAC(LOG_LOCAL6
)] = "local6",
3780 [LOG_FAC(LOG_LOCAL7
)] = "local7"
3783 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted
, int, LOG_FAC(~0));
3785 static const char *const log_level_table
[] = {
3786 [LOG_EMERG
] = "emerg",
3787 [LOG_ALERT
] = "alert",
3788 [LOG_CRIT
] = "crit",
3790 [LOG_WARNING
] = "warning",
3791 [LOG_NOTICE
] = "notice",
3792 [LOG_INFO
] = "info",
3793 [LOG_DEBUG
] = "debug"
3796 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level
, int, LOG_DEBUG
);
3798 static const char* const sched_policy_table
[] = {
3799 [SCHED_OTHER
] = "other",
3800 [SCHED_BATCH
] = "batch",
3801 [SCHED_IDLE
] = "idle",
3802 [SCHED_FIFO
] = "fifo",
3806 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);
3808 static const char* const rlimit_table
[_RLIMIT_MAX
] = {
3809 [RLIMIT_CPU
] = "LimitCPU",
3810 [RLIMIT_FSIZE
] = "LimitFSIZE",
3811 [RLIMIT_DATA
] = "LimitDATA",
3812 [RLIMIT_STACK
] = "LimitSTACK",
3813 [RLIMIT_CORE
] = "LimitCORE",
3814 [RLIMIT_RSS
] = "LimitRSS",
3815 [RLIMIT_NOFILE
] = "LimitNOFILE",
3816 [RLIMIT_AS
] = "LimitAS",
3817 [RLIMIT_NPROC
] = "LimitNPROC",
3818 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
3819 [RLIMIT_LOCKS
] = "LimitLOCKS",
3820 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
3821 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
3822 [RLIMIT_NICE
] = "LimitNICE",
3823 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
3824 [RLIMIT_RTTIME
] = "LimitRTTIME"
3827 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
3829 static const char* const ip_tos_table
[] = {
3830 [IPTOS_LOWDELAY
] = "low-delay",
3831 [IPTOS_THROUGHPUT
] = "throughput",
3832 [IPTOS_RELIABILITY
] = "reliability",
3833 [IPTOS_LOWCOST
] = "low-cost",
3836 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
3838 bool kexec_loaded(void) {
3839 bool loaded
= false;
3842 if (read_one_line_file("/sys/kernel/kexec_loaded", &s
) >= 0) {
3850 int prot_from_flags(int flags
) {
3852 switch (flags
& O_ACCMODE
) {
3861 return PROT_READ
|PROT_WRITE
;
3868 char *format_bytes(char *buf
, size_t l
, uint64_t t
) {
3871 static const struct {
3875 { "E", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3876 { "P", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3877 { "T", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3878 { "G", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3879 { "M", UINT64_C(1024)*UINT64_C(1024) },
3880 { "K", UINT64_C(1024) },
3883 if (t
== (uint64_t) -1)
3886 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
3888 if (t
>= table
[i
].factor
) {
3890 "%" PRIu64
".%" PRIu64
"%s",
3891 t
/ table
[i
].factor
,
3892 ((t
*UINT64_C(10)) / table
[i
].factor
) % UINT64_C(10),
3899 snprintf(buf
, l
, "%" PRIu64
"B", t
);
3907 void* memdup(const void *p
, size_t l
) {
3920 int fd_inc_sndbuf(int fd
, size_t n
) {
3922 socklen_t l
= sizeof(value
);
3924 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
3925 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
3928 /* If we have the privileges we will ignore the kernel limit. */
3931 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
3932 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
3938 int fd_inc_rcvbuf(int fd
, size_t n
) {
3940 socklen_t l
= sizeof(value
);
3942 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
3943 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
3946 /* If we have the privileges we will ignore the kernel limit. */
3949 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
3950 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
3955 int fork_agent(pid_t
*pid
, const int except
[], unsigned n_except
, const char *path
, ...) {
3956 bool stdout_is_tty
, stderr_is_tty
;
3957 pid_t parent_pid
, agent_pid
;
3958 sigset_t ss
, saved_ss
;
3966 /* Spawns a temporary TTY agent, making sure it goes away when
3969 parent_pid
= getpid();
3971 /* First we temporarily block all signals, so that the new
3972 * child has them blocked initially. This way, we can be sure
3973 * that SIGTERMs are not lost we might send to the agent. */
3974 assert_se(sigfillset(&ss
) >= 0);
3975 assert_se(sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) >= 0);
3978 if (agent_pid
< 0) {
3979 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
3983 if (agent_pid
!= 0) {
3984 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
3991 * Make sure the agent goes away when the parent dies */
3992 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
3993 _exit(EXIT_FAILURE
);
3995 /* Make sure we actually can kill the agent, if we need to, in
3996 * case somebody invoked us from a shell script that trapped
3997 * SIGTERM or so... */
3998 (void) reset_all_signal_handlers();
3999 (void) reset_signal_mask();
4001 /* Check whether our parent died before we were able
4002 * to set the death signal and unblock the signals */
4003 if (getppid() != parent_pid
)
4004 _exit(EXIT_SUCCESS
);
4006 /* Don't leak fds to the agent */
4007 close_all_fds(except
, n_except
);
4009 stdout_is_tty
= isatty(STDOUT_FILENO
);
4010 stderr_is_tty
= isatty(STDERR_FILENO
);
4012 if (!stdout_is_tty
|| !stderr_is_tty
) {
4015 /* Detach from stdout/stderr. and reopen
4016 * /dev/tty for them. This is important to
4017 * ensure that when systemctl is started via
4018 * popen() or a similar call that expects to
4019 * read EOF we actually do generate EOF and
4020 * not delay this indefinitely by because we
4021 * keep an unused copy of stdin around. */
4022 fd
= open("/dev/tty", O_WRONLY
);
4024 log_error_errno(errno
, "Failed to open /dev/tty: %m");
4025 _exit(EXIT_FAILURE
);
4029 dup2(fd
, STDOUT_FILENO
);
4032 dup2(fd
, STDERR_FILENO
);
4038 /* Count arguments */
4040 for (n
= 0; va_arg(ap
, char*); n
++)
4045 l
= alloca(sizeof(char *) * (n
+ 1));
4047 /* Fill in arguments */
4049 for (i
= 0; i
<= n
; i
++)
4050 l
[i
] = va_arg(ap
, char*);
4054 _exit(EXIT_FAILURE
);
4057 int setrlimit_closest(int resource
, const struct rlimit
*rlim
) {
4058 struct rlimit highest
, fixed
;
4062 if (setrlimit(resource
, rlim
) >= 0)
4068 /* So we failed to set the desired setrlimit, then let's try
4069 * to get as close as we can */
4070 assert_se(getrlimit(resource
, &highest
) == 0);
4072 fixed
.rlim_cur
= MIN(rlim
->rlim_cur
, highest
.rlim_max
);
4073 fixed
.rlim_max
= MIN(rlim
->rlim_max
, highest
.rlim_max
);
4075 if (setrlimit(resource
, &fixed
) < 0)
4081 bool http_etag_is_valid(const char *etag
) {
4085 if (!endswith(etag
, "\""))
4088 if (!startswith(etag
, "\"") && !startswith(etag
, "W/\""))
4094 bool http_url_is_valid(const char *url
) {
4100 p
= startswith(url
, "http://");
4102 p
= startswith(url
, "https://");
4109 return ascii_is_valid(p
);
4112 bool documentation_url_is_valid(const char *url
) {
4118 if (http_url_is_valid(url
))
4121 p
= startswith(url
, "file:/");
4123 p
= startswith(url
, "info:");
4125 p
= startswith(url
, "man:");
4130 return ascii_is_valid(p
);
4133 bool in_initrd(void) {
4134 static int saved
= -1;
4140 /* We make two checks here:
4142 * 1. the flag file /etc/initrd-release must exist
4143 * 2. the root file system must be a memory file system
4145 * The second check is extra paranoia, since misdetecting an
4146 * initrd can have bad bad consequences due the initrd
4147 * emptying when transititioning to the main systemd.
4150 saved
= access("/etc/initrd-release", F_OK
) >= 0 &&
4151 statfs("/", &s
) >= 0 &&
4152 is_temporary_fs(&s
);
4157 int get_home_dir(char **_h
) {
4165 /* Take the user specified one */
4166 e
= secure_getenv("HOME");
4167 if (e
&& path_is_absolute(e
)) {
4176 /* Hardcode home directory for root to avoid NSS */
4179 h
= strdup("/root");
4187 /* Check the database... */
4191 return errno
> 0 ? -errno
: -ESRCH
;
4193 if (!path_is_absolute(p
->pw_dir
))
4196 h
= strdup(p
->pw_dir
);
4204 int get_shell(char **_s
) {
4212 /* Take the user specified one */
4213 e
= getenv("SHELL");
4223 /* Hardcode home directory for root to avoid NSS */
4226 s
= strdup("/bin/sh");
4234 /* Check the database... */
4238 return errno
> 0 ? -errno
: -ESRCH
;
4240 if (!path_is_absolute(p
->pw_shell
))
4243 s
= strdup(p
->pw_shell
);
4251 bool filename_is_valid(const char *p
) {
4265 if (strlen(p
) > FILENAME_MAX
)
4271 bool string_is_safe(const char *p
) {
4277 for (t
= p
; *t
; t
++) {
4278 if (*t
> 0 && *t
< ' ')
4281 if (strchr("\\\"\'\x7f", *t
))
4289 * Check if a string contains control characters. If 'ok' is non-NULL
4290 * it may be a string containing additional CCs to be considered OK.
4292 bool string_has_cc(const char *p
, const char *ok
) {
4297 for (t
= p
; *t
; t
++) {
4298 if (ok
&& strchr(ok
, *t
))
4301 if (*t
> 0 && *t
< ' ')
4311 bool path_is_safe(const char *p
) {
4316 if (streq(p
, "..") || startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
4319 if (strlen(p
)+1 > PATH_MAX
)
4322 /* The following two checks are not really dangerous, but hey, they still are confusing */
4323 if (streq(p
, ".") || startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
4326 if (strstr(p
, "//"))
4332 /* hey glibc, APIs with callbacks without a user pointer are so useless */
4333 void *xbsearch_r(const void *key
, const void *base
, size_t nmemb
, size_t size
,
4334 int (*compar
) (const void *, const void *, void *), void *arg
) {
4343 p
= (void *)(((const char *) base
) + (idx
* size
));
4344 comparison
= compar(key
, p
, arg
);
4347 else if (comparison
> 0)
4355 void init_gettext(void) {
4356 setlocale(LC_ALL
, "");
4357 textdomain(GETTEXT_PACKAGE
);
4360 bool is_locale_utf8(void) {
4362 static int cached_answer
= -1;
4364 if (cached_answer
>= 0)
4367 if (!setlocale(LC_ALL
, "")) {
4368 cached_answer
= true;
4372 set
= nl_langinfo(CODESET
);
4374 cached_answer
= true;
4378 if (streq(set
, "UTF-8")) {
4379 cached_answer
= true;
4383 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
4384 * unset and everything can do to UTF-8 nowadays. */
4385 set
= setlocale(LC_CTYPE
, NULL
);
4387 cached_answer
= true;
4391 /* Check result, but ignore the result if C was set
4394 STR_IN_SET(set
, "C", "POSIX") &&
4395 !getenv("LC_ALL") &&
4396 !getenv("LC_CTYPE") &&
4400 return (bool) cached_answer
;
4403 const char *draw_special_char(DrawSpecialChar ch
) {
4404 static const char *draw_table
[2][_DRAW_SPECIAL_CHAR_MAX
] = {
4407 [DRAW_TREE_VERTICAL
] = "\342\224\202 ", /* │ */
4408 [DRAW_TREE_BRANCH
] = "\342\224\234\342\224\200", /* ├─ */
4409 [DRAW_TREE_RIGHT
] = "\342\224\224\342\224\200", /* └─ */
4410 [DRAW_TREE_SPACE
] = " ", /* */
4411 [DRAW_TRIANGULAR_BULLET
] = "\342\200\243", /* ‣ */
4412 [DRAW_BLACK_CIRCLE
] = "\342\227\217", /* ● */
4413 [DRAW_ARROW
] = "\342\206\222", /* → */
4414 [DRAW_DASH
] = "\342\200\223", /* – */
4417 /* ASCII fallback */ {
4418 [DRAW_TREE_VERTICAL
] = "| ",
4419 [DRAW_TREE_BRANCH
] = "|-",
4420 [DRAW_TREE_RIGHT
] = "`-",
4421 [DRAW_TREE_SPACE
] = " ",
4422 [DRAW_TRIANGULAR_BULLET
] = ">",
4423 [DRAW_BLACK_CIRCLE
] = "*",
4424 [DRAW_ARROW
] = "->",
4429 return draw_table
[!is_locale_utf8()][ch
];
4432 char *strreplace(const char *text
, const char *old_string
, const char *new_string
) {
4435 size_t l
, old_len
, new_len
;
4441 old_len
= strlen(old_string
);
4442 new_len
= strlen(new_string
);
4455 if (!startswith(f
, old_string
)) {
4461 nl
= l
- old_len
+ new_len
;
4462 a
= realloc(r
, nl
+ 1);
4470 t
= stpcpy(t
, new_string
);
4482 char *strip_tab_ansi(char **ibuf
, size_t *_isz
) {
4483 const char *i
, *begin
= NULL
;
4488 } state
= STATE_OTHER
;
4490 size_t osz
= 0, isz
;
4496 /* Strips ANSI color and replaces TABs by 8 spaces */
4498 isz
= _isz
? *_isz
: strlen(*ibuf
);
4500 f
= open_memstream(&obuf
, &osz
);
4504 for (i
= *ibuf
; i
< *ibuf
+ isz
+ 1; i
++) {
4509 if (i
>= *ibuf
+ isz
) /* EOT */
4511 else if (*i
== '\x1B')
4512 state
= STATE_ESCAPE
;
4513 else if (*i
== '\t')
4520 if (i
>= *ibuf
+ isz
) { /* EOT */
4523 } else if (*i
== '[') {
4524 state
= STATE_BRACKET
;
4529 state
= STATE_OTHER
;
4536 if (i
>= *ibuf
+ isz
|| /* EOT */
4537 (!(*i
>= '0' && *i
<= '9') && *i
!= ';' && *i
!= 'm')) {
4540 state
= STATE_OTHER
;
4542 } else if (*i
== 'm')
4543 state
= STATE_OTHER
;
4565 int on_ac_power(void) {
4566 bool found_offline
= false, found_online
= false;
4567 _cleanup_closedir_
DIR *d
= NULL
;
4569 d
= opendir("/sys/class/power_supply");
4571 return errno
== ENOENT
? true : -errno
;
4575 _cleanup_close_
int fd
= -1, device
= -1;
4581 if (!de
&& errno
!= 0)
4587 if (hidden_file(de
->d_name
))
4590 device
= openat(dirfd(d
), de
->d_name
, O_DIRECTORY
|O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4592 if (errno
== ENOENT
|| errno
== ENOTDIR
)
4598 fd
= openat(device
, "type", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4600 if (errno
== ENOENT
)
4606 n
= read(fd
, contents
, sizeof(contents
));
4610 if (n
!= 6 || memcmp(contents
, "Mains\n", 6))
4614 fd
= openat(device
, "online", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4616 if (errno
== ENOENT
)
4622 n
= read(fd
, contents
, sizeof(contents
));
4626 if (n
!= 2 || contents
[1] != '\n')
4629 if (contents
[0] == '1') {
4630 found_online
= true;
4632 } else if (contents
[0] == '0')
4633 found_offline
= true;
4638 return found_online
|| !found_offline
;
4641 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
4648 if (!path_strv_resolve_uniq(search
, root
))
4651 STRV_FOREACH(i
, search
) {
4652 _cleanup_free_
char *p
= NULL
;
4656 p
= strjoin(root
, *i
, "/", path
, NULL
);
4658 p
= strjoin(*i
, "/", path
, NULL
);
4668 if (errno
!= ENOENT
)
4675 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
4676 _cleanup_strv_free_
char **copy
= NULL
;
4682 if (path_is_absolute(path
)) {
4685 f
= fopen(path
, mode
);
4694 copy
= strv_copy((char**) search
);
4698 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
4701 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
4702 _cleanup_strv_free_
char **s
= NULL
;
4704 if (path_is_absolute(path
)) {
4707 f
= fopen(path
, mode
);
4716 s
= strv_split_nulstr(search
);
4720 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
4723 char *strextend(char **x
, ...) {
4730 l
= f
= *x
? strlen(*x
) : 0;
4737 t
= va_arg(ap
, const char *);
4742 if (n
> ((size_t) -1) - l
) {
4751 r
= realloc(*x
, l
+1);
4761 t
= va_arg(ap
, const char *);
4775 char *strrep(const char *s
, unsigned n
) {
4783 p
= r
= malloc(l
* n
+ 1);
4787 for (i
= 0; i
< n
; i
++)
4794 void* greedy_realloc(void **p
, size_t *allocated
, size_t need
, size_t size
) {
4801 if (*allocated
>= need
)
4804 newalloc
= MAX(need
* 2, 64u / size
);
4805 a
= newalloc
* size
;
4807 /* check for overflows */
4808 if (a
< size
* need
)
4816 *allocated
= newalloc
;
4820 void* greedy_realloc0(void **p
, size_t *allocated
, size_t need
, size_t size
) {
4829 q
= greedy_realloc(p
, allocated
, need
, size
);
4833 if (*allocated
> prev
)
4834 memzero(q
+ prev
* size
, (*allocated
- prev
) * size
);
4839 bool id128_is_valid(const char *s
) {
4845 /* Simple formatted 128bit hex string */
4847 for (i
= 0; i
< l
; i
++) {
4850 if (!(c
>= '0' && c
<= '9') &&
4851 !(c
>= 'a' && c
<= 'z') &&
4852 !(c
>= 'A' && c
<= 'Z'))
4856 } else if (l
== 36) {
4858 /* Formatted UUID */
4860 for (i
= 0; i
< l
; i
++) {
4863 if ((i
== 8 || i
== 13 || i
== 18 || i
== 23)) {
4867 if (!(c
>= '0' && c
<= '9') &&
4868 !(c
>= 'a' && c
<= 'z') &&
4869 !(c
>= 'A' && c
<= 'Z'))
4880 int split_pair(const char *s
, const char *sep
, char **l
, char **r
) {
4895 a
= strndup(s
, x
- s
);
4899 b
= strdup(x
+ strlen(sep
));
4911 int shall_restore_state(void) {
4912 _cleanup_free_
char *value
= NULL
;
4915 r
= get_proc_cmdline_key("systemd.restore_state=", &value
);
4921 return parse_boolean(value
) != 0;
4924 int proc_cmdline(char **ret
) {
4927 if (detect_container() > 0)
4928 return get_process_cmdline(1, 0, false, ret
);
4930 return read_one_line_file("/proc/cmdline", ret
);
4933 int parse_proc_cmdline(int (*parse_item
)(const char *key
, const char *value
)) {
4934 _cleanup_free_
char *line
= NULL
;
4940 r
= proc_cmdline(&line
);
4946 _cleanup_free_
char *word
= NULL
;
4949 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
4955 /* Filter out arguments that are intended only for the
4957 if (!in_initrd() && startswith(word
, "rd."))
4960 value
= strchr(word
, '=');
4964 r
= parse_item(word
, value
);
4972 int get_proc_cmdline_key(const char *key
, char **value
) {
4973 _cleanup_free_
char *line
= NULL
, *ret
= NULL
;
4980 r
= proc_cmdline(&line
);
4986 _cleanup_free_
char *word
= NULL
;
4989 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
4995 /* Filter out arguments that are intended only for the
4997 if (!in_initrd() && startswith(word
, "rd."))
5001 e
= startswith(word
, key
);
5005 r
= free_and_strdup(&ret
, e
);
5011 if (streq(word
, key
))
5025 int container_get_leader(const char *machine
, pid_t
*pid
) {
5026 _cleanup_free_
char *s
= NULL
, *class = NULL
;
5034 if (!machine_name_is_valid(machine
))
5037 p
= strjoina("/run/systemd/machines/", machine
);
5038 r
= parse_env_file(p
, NEWLINE
, "LEADER", &s
, "CLASS", &class, NULL
);
5046 if (!streq_ptr(class, "container"))
5049 r
= parse_pid(s
, &leader
);
5059 int namespace_open(pid_t pid
, int *pidns_fd
, int *mntns_fd
, int *netns_fd
, int *userns_fd
, int *root_fd
) {
5060 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, netnsfd
= -1, usernsfd
= -1;
5068 mntns
= procfs_file_alloca(pid
, "ns/mnt");
5069 mntnsfd
= open(mntns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5077 pidns
= procfs_file_alloca(pid
, "ns/pid");
5078 pidnsfd
= open(pidns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5086 netns
= procfs_file_alloca(pid
, "ns/net");
5087 netnsfd
= open(netns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5095 userns
= procfs_file_alloca(pid
, "ns/user");
5096 usernsfd
= open(userns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5097 if (usernsfd
< 0 && errno
!= ENOENT
)
5104 root
= procfs_file_alloca(pid
, "root");
5105 rfd
= open(root
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
|O_DIRECTORY
);
5111 *pidns_fd
= pidnsfd
;
5114 *mntns_fd
= mntnsfd
;
5117 *netns_fd
= netnsfd
;
5120 *userns_fd
= usernsfd
;
5125 pidnsfd
= mntnsfd
= netnsfd
= usernsfd
= -1;
5130 int namespace_enter(int pidns_fd
, int mntns_fd
, int netns_fd
, int userns_fd
, int root_fd
) {
5131 if (userns_fd
>= 0) {
5132 /* Can't setns to your own userns, since then you could
5133 * escalate from non-root to root in your own namespace, so
5134 * check if namespaces equal before attempting to enter. */
5135 _cleanup_free_
char *userns_fd_path
= NULL
;
5137 if (asprintf(&userns_fd_path
, "/proc/self/fd/%d", userns_fd
) < 0)
5140 r
= files_same(userns_fd_path
, "/proc/self/ns/user");
5148 if (setns(pidns_fd
, CLONE_NEWPID
) < 0)
5152 if (setns(mntns_fd
, CLONE_NEWNS
) < 0)
5156 if (setns(netns_fd
, CLONE_NEWNET
) < 0)
5160 if (setns(userns_fd
, CLONE_NEWUSER
) < 0)
5164 if (fchdir(root_fd
) < 0)
5167 if (chroot(".") < 0)
5171 return reset_uid_gid();
5174 int getpeercred(int fd
, struct ucred
*ucred
) {
5175 socklen_t n
= sizeof(struct ucred
);
5182 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
);
5186 if (n
!= sizeof(struct ucred
))
5189 /* Check if the data is actually useful and not suppressed due
5190 * to namespacing issues */
5193 if (u
.uid
== UID_INVALID
)
5195 if (u
.gid
== GID_INVALID
)
5202 int getpeersec(int fd
, char **ret
) {
5214 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
5218 if (errno
!= ERANGE
)
5225 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
5241 /* This is much like like mkostemp() but is subject to umask(). */
5242 int mkostemp_safe(char *pattern
, int flags
) {
5243 _cleanup_umask_ mode_t u
;
5250 fd
= mkostemp(pattern
, flags
);
5257 int open_tmpfile(const char *path
, int flags
) {
5264 /* Try O_TMPFILE first, if it is supported */
5265 fd
= open(path
, flags
|O_TMPFILE
|O_EXCL
, S_IRUSR
|S_IWUSR
);
5270 /* Fall back to unguessable name + unlinking */
5271 p
= strjoina(path
, "/systemd-tmp-XXXXXX");
5273 fd
= mkostemp_safe(p
, flags
);
5281 int fd_warn_permissions(const char *path
, int fd
) {
5284 if (fstat(fd
, &st
) < 0)
5287 if (st
.st_mode
& 0111)
5288 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path
);
5290 if (st
.st_mode
& 0002)
5291 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path
);
5293 if (getpid() == 1 && (st
.st_mode
& 0044) != 0044)
5294 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
);
5299 unsigned long personality_from_string(const char *p
) {
5301 /* Parse a personality specifier. We introduce our own
5302 * identifiers that indicate specific ABIs, rather than just
5303 * hints regarding the register size, since we want to keep
5304 * things open for multiple locally supported ABIs for the
5305 * same register size. We try to reuse the ABI identifiers
5306 * used by libseccomp. */
5308 #if defined(__x86_64__)
5310 if (streq(p
, "x86"))
5313 if (streq(p
, "x86-64"))
5316 #elif defined(__i386__)
5318 if (streq(p
, "x86"))
5321 #elif defined(__s390x__)
5323 if (streq(p
, "s390"))
5326 if (streq(p
, "s390x"))
5329 #elif defined(__s390__)
5331 if (streq(p
, "s390"))
5335 return PERSONALITY_INVALID
;
5338 const char* personality_to_string(unsigned long p
) {
5340 #if defined(__x86_64__)
5342 if (p
== PER_LINUX32
)
5348 #elif defined(__i386__)
5353 #elif defined(__s390x__)
5358 if (p
== PER_LINUX32
)
5361 #elif defined(__s390__)
5371 uint64_t physical_memory(void) {
5374 /* We return this as uint64_t in case we are running as 32bit
5375 * process on a 64bit kernel with huge amounts of memory */
5377 mem
= sysconf(_SC_PHYS_PAGES
);
5380 return (uint64_t) mem
* (uint64_t) page_size();
5383 void hexdump(FILE *f
, const void *p
, size_t s
) {
5384 const uint8_t *b
= p
;
5387 assert(s
== 0 || b
);
5392 fprintf(f
, "%04x ", n
);
5394 for (i
= 0; i
< 16; i
++) {
5399 fprintf(f
, "%02x ", b
[i
]);
5407 for (i
= 0; i
< 16; i
++) {
5412 fputc(isprint(b
[i
]) ? (char) b
[i
] : '.', f
);
5426 int update_reboot_param_file(const char *param
) {
5431 r
= write_string_file(REBOOT_PARAM_FILE
, param
, WRITE_STRING_FILE_CREATE
);
5433 log_error("Failed to write reboot param to "
5434 REBOOT_PARAM_FILE
": %s", strerror(-r
));
5436 unlink(REBOOT_PARAM_FILE
);
5441 int umount_recursive(const char *prefix
, int flags
) {
5445 /* Try to umount everything recursively below a
5446 * directory. Also, take care of stacked mounts, and keep
5447 * unmounting them until they are gone. */
5450 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
5455 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
5456 if (!proc_self_mountinfo
)
5460 _cleanup_free_
char *path
= NULL
, *p
= NULL
;
5463 k
= fscanf(proc_self_mountinfo
,
5464 "%*s " /* (1) mount id */
5465 "%*s " /* (2) parent id */
5466 "%*s " /* (3) major:minor */
5467 "%*s " /* (4) root */
5468 "%ms " /* (5) mount point */
5469 "%*s" /* (6) mount options */
5470 "%*[^-]" /* (7) optional fields */
5471 "- " /* (8) separator */
5472 "%*s " /* (9) file system type */
5473 "%*s" /* (10) mount source */
5474 "%*s" /* (11) mount options 2 */
5475 "%*[^\n]", /* some rubbish at the end */
5484 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
5488 if (!path_startswith(p
, prefix
))
5491 if (umount2(p
, flags
) < 0) {
5507 static int get_mount_flags(const char *path
, unsigned long *flags
) {
5510 if (statvfs(path
, &buf
) < 0)
5512 *flags
= buf
.f_flag
;
5516 int bind_remount_recursive(const char *prefix
, bool ro
) {
5517 _cleanup_set_free_free_ Set
*done
= NULL
;
5518 _cleanup_free_
char *cleaned
= NULL
;
5521 /* Recursively remount a directory (and all its submounts)
5522 * read-only or read-write. If the directory is already
5523 * mounted, we reuse the mount and simply mark it
5524 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
5525 * operation). If it isn't we first make it one. Afterwards we
5526 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
5527 * submounts we can access, too. When mounts are stacked on
5528 * the same mount point we only care for each individual
5529 * "top-level" mount on each point, as we cannot
5530 * influence/access the underlying mounts anyway. We do not
5531 * have any effect on future submounts that might get
5532 * propagated, they migt be writable. This includes future
5533 * submounts that have been triggered via autofs. */
5535 cleaned
= strdup(prefix
);
5539 path_kill_slashes(cleaned
);
5541 done
= set_new(&string_hash_ops
);
5546 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
5547 _cleanup_set_free_free_ Set
*todo
= NULL
;
5548 bool top_autofs
= false;
5550 unsigned long orig_flags
;
5552 todo
= set_new(&string_hash_ops
);
5556 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
5557 if (!proc_self_mountinfo
)
5561 _cleanup_free_
char *path
= NULL
, *p
= NULL
, *type
= NULL
;
5564 k
= fscanf(proc_self_mountinfo
,
5565 "%*s " /* (1) mount id */
5566 "%*s " /* (2) parent id */
5567 "%*s " /* (3) major:minor */
5568 "%*s " /* (4) root */
5569 "%ms " /* (5) mount point */
5570 "%*s" /* (6) mount options (superblock) */
5571 "%*[^-]" /* (7) optional fields */
5572 "- " /* (8) separator */
5573 "%ms " /* (9) file system type */
5574 "%*s" /* (10) mount source */
5575 "%*s" /* (11) mount options (bind mount) */
5576 "%*[^\n]", /* some rubbish at the end */
5586 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
5590 /* Let's ignore autofs mounts. If they aren't
5591 * triggered yet, we want to avoid triggering
5592 * them, as we don't make any guarantees for
5593 * future submounts anyway. If they are
5594 * already triggered, then we will find
5595 * another entry for this. */
5596 if (streq(type
, "autofs")) {
5597 top_autofs
= top_autofs
|| path_equal(cleaned
, p
);
5601 if (path_startswith(p
, cleaned
) &&
5602 !set_contains(done
, p
)) {
5604 r
= set_consume(todo
, p
);
5614 /* If we have no submounts to process anymore and if
5615 * the root is either already done, or an autofs, we
5617 if (set_isempty(todo
) &&
5618 (top_autofs
|| set_contains(done
, cleaned
)))
5621 if (!set_contains(done
, cleaned
) &&
5622 !set_contains(todo
, cleaned
)) {
5623 /* The prefix directory itself is not yet a
5624 * mount, make it one. */
5625 if (mount(cleaned
, cleaned
, NULL
, MS_BIND
|MS_REC
, NULL
) < 0)
5629 (void) get_mount_flags(cleaned
, &orig_flags
);
5630 orig_flags
&= ~MS_RDONLY
;
5632 if (mount(NULL
, prefix
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0)
5635 x
= strdup(cleaned
);
5639 r
= set_consume(done
, x
);
5644 while ((x
= set_steal_first(todo
))) {
5646 r
= set_consume(done
, x
);
5647 if (r
== -EEXIST
|| r
== 0)
5652 /* Try to reuse the original flag set, but
5653 * don't care for errors, in case of
5654 * obstructed mounts */
5656 (void) get_mount_flags(x
, &orig_flags
);
5657 orig_flags
&= ~MS_RDONLY
;
5659 if (mount(NULL
, x
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0) {
5661 /* Deal with mount points that are
5662 * obstructed by a later mount */
5664 if (errno
!= ENOENT
)
5672 int fflush_and_check(FILE *f
) {
5679 return errno
? -errno
: -EIO
;
5684 int tempfn_xxxxxx(const char *p
, const char *extra
, char **ret
) {
5696 * /foo/bar/.#<extra>waldoXXXXXX
5700 if (!filename_is_valid(fn
))
5706 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 6 + 1);
5710 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
), "XXXXXX");
5712 *ret
= path_kill_slashes(t
);
5716 int tempfn_random(const char *p
, const char *extra
, char **ret
) {
5730 * /foo/bar/.#<extra>waldobaa2a261115984a9
5734 if (!filename_is_valid(fn
))
5740 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 16 + 1);
5744 x
= stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
);
5747 for (i
= 0; i
< 16; i
++) {
5748 *(x
++) = hexchar(u
& 0xF);
5754 *ret
= path_kill_slashes(t
);
5758 int tempfn_random_child(const char *p
, const char *extra
, char **ret
) {
5769 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
5775 t
= new(char, strlen(p
) + 3 + strlen(extra
) + 16 + 1);
5779 x
= stpcpy(stpcpy(stpcpy(t
, p
), "/.#"), extra
);
5782 for (i
= 0; i
< 16; i
++) {
5783 *(x
++) = hexchar(u
& 0xF);
5789 *ret
= path_kill_slashes(t
);
5793 int take_password_lock(const char *root
) {
5795 struct flock flock
= {
5797 .l_whence
= SEEK_SET
,
5805 /* This is roughly the same as lckpwdf(), but not as awful. We
5806 * don't want to use alarm() and signals, hence we implement
5807 * our own trivial version of this.
5809 * Note that shadow-utils also takes per-database locks in
5810 * addition to lckpwdf(). However, we don't given that they
5811 * are redundant as they they invoke lckpwdf() first and keep
5812 * it during everything they do. The per-database locks are
5813 * awfully racy, and thus we just won't do them. */
5816 path
= strjoina(root
, "/etc/.pwd.lock");
5818 path
= "/etc/.pwd.lock";
5820 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
5824 r
= fcntl(fd
, F_SETLKW
, &flock
);
5833 int is_symlink(const char *path
) {
5836 if (lstat(path
, &info
) < 0)
5839 return !!S_ISLNK(info
.st_mode
);
5842 int is_dir(const char* path
, bool follow
) {
5847 r
= stat(path
, &st
);
5849 r
= lstat(path
, &st
);
5853 return !!S_ISDIR(st
.st_mode
);
5856 int is_device_node(const char *path
) {
5859 if (lstat(path
, &info
) < 0)
5862 return !!(S_ISBLK(info
.st_mode
) || S_ISCHR(info
.st_mode
));
5865 int extract_first_word(const char **p
, char **ret
, const char *separators
, ExtractFlags flags
) {
5866 _cleanup_free_
char *s
= NULL
;
5867 size_t allocated
= 0, sz
= 0;
5875 SINGLE_QUOTE_ESCAPE
,
5877 DOUBLE_QUOTE_ESCAPE
,
5885 separators
= WHITESPACE
;
5887 /* Bail early if called after last value or with no input */
5889 goto finish_force_terminate
;
5891 /* Parses the first word of a string, and returns it in
5892 * *ret. Removes all quotes in the process. When parsing fails
5893 * (because of an uneven number of quotes or similar), leaves
5894 * the pointer *p at the first invalid character. */
5902 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
)
5903 if (!GREEDY_REALLOC(s
, allocated
, sz
+1))
5907 goto finish_force_terminate
;
5908 else if (strchr(separators
, c
)) {
5909 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
) {
5911 goto finish_force_next
;
5916 /* We found a non-blank character, so we will always
5917 * want to return a string (even if it is empty),
5918 * allocate it here. */
5919 if (!GREEDY_REALLOC(s
, allocated
, sz
+1))
5927 goto finish_force_terminate
;
5928 else if (c
== '\'' && (flags
& EXTRACT_QUOTES
))
5929 state
= SINGLE_QUOTE
;
5931 state
= VALUE_ESCAPE
;
5932 else if (c
== '\"' && (flags
& EXTRACT_QUOTES
))
5933 state
= DOUBLE_QUOTE
;
5934 else if (strchr(separators
, c
)) {
5935 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
) {
5937 goto finish_force_next
;
5941 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5951 if (flags
& EXTRACT_RELAX
)
5952 goto finish_force_terminate
;
5954 } else if (c
== '\'')
5957 state
= SINGLE_QUOTE_ESCAPE
;
5959 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5973 state
= DOUBLE_QUOTE_ESCAPE
;
5975 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5983 case SINGLE_QUOTE_ESCAPE
:
5984 case DOUBLE_QUOTE_ESCAPE
:
5986 if (!GREEDY_REALLOC(s
, allocated
, sz
+7))
5990 if ((flags
& EXTRACT_CUNESCAPE_RELAX
) &&
5991 (state
== VALUE_ESCAPE
|| flags
& EXTRACT_RELAX
)) {
5992 /* If we find an unquoted trailing backslash and we're in
5993 * EXTRACT_CUNESCAPE_RELAX mode, keep it verbatim in the
5996 * Unbalanced quotes will only be allowed in EXTRACT_RELAX
5997 * mode, EXTRACT_CUNESCAPE_RELAX mode does not allow them.
6000 goto finish_force_terminate
;
6002 if (flags
& EXTRACT_RELAX
)
6003 goto finish_force_terminate
;
6007 if (flags
& EXTRACT_CUNESCAPE
) {
6010 r
= cunescape_one(*p
, (size_t) -1, &c
, &u
);
6012 if (flags
& EXTRACT_CUNESCAPE_RELAX
) {
6023 s
[sz
++] = c
; /* normal explicit char */
6025 sz
+= utf8_encode_unichar(s
+ sz
, u
); /* unicode chars we'll encode as utf8 */
6030 state
= (state
== SINGLE_QUOTE_ESCAPE
) ? SINGLE_QUOTE
:
6031 (state
== DOUBLE_QUOTE_ESCAPE
) ? DOUBLE_QUOTE
:
6037 goto finish_force_terminate
;
6038 if (!strchr(separators
, c
))
6046 finish_force_terminate
:
6063 int extract_first_word_and_warn(
6066 const char *separators
,
6069 const char *filename
,
6071 const char *rvalue
) {
6072 /* Try to unquote it, if it fails, warn about it and try again but this
6073 * time using EXTRACT_CUNESCAPE_RELAX to keep the backslashes verbatim
6074 * in invalid escape sequences. */
6079 r
= extract_first_word(p
, ret
, separators
, flags
);
6080 if (r
< 0 && !(flags
&EXTRACT_CUNESCAPE_RELAX
)) {
6081 /* Retry it with EXTRACT_CUNESCAPE_RELAX. */
6083 r
= extract_first_word(p
, ret
, separators
, flags
|EXTRACT_CUNESCAPE_RELAX
);
6085 log_syntax(unit
, LOG_ERR
, filename
, line
, EINVAL
,
6086 "Unbalanced quoting in command line, ignoring: \"%s\"", rvalue
);
6088 log_syntax(unit
, LOG_WARNING
, filename
, line
, EINVAL
,
6089 "Invalid escape sequences in command line: \"%s\"", rvalue
);
6094 int extract_many_words(const char **p
, const char *separators
, ExtractFlags flags
, ...) {
6099 /* Parses a number of words from a string, stripping any
6100 * quotes if necessary. */
6104 /* Count how many words are expected */
6105 va_start(ap
, flags
);
6107 if (!va_arg(ap
, char **))
6116 /* Read all words into a temporary array */
6117 l
= newa0(char*, n
);
6118 for (c
= 0; c
< n
; c
++) {
6120 r
= extract_first_word(p
, &l
[c
], separators
, flags
);
6124 for (j
= 0; j
< c
; j
++)
6134 /* If we managed to parse all words, return them in the passed
6136 va_start(ap
, flags
);
6137 for (i
= 0; i
< n
; i
++) {
6140 v
= va_arg(ap
, char **);
6150 int free_and_strdup(char **p
, const char *s
) {
6155 /* Replaces a string pointer with an strdup()ed new string,
6156 * possibly freeing the old one. */
6158 if (streq_ptr(*p
, s
))
6174 int ptsname_malloc(int fd
, char **ret
) {
6187 if (ptsname_r(fd
, c
, l
) == 0) {
6191 if (errno
!= ERANGE
) {
6201 int openpt_in_namespace(pid_t pid
, int flags
) {
6202 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, usernsfd
= -1, rootfd
= -1;
6203 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
6210 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &usernsfd
, &rootfd
);
6214 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
6224 pair
[0] = safe_close(pair
[0]);
6226 r
= namespace_enter(pidnsfd
, mntnsfd
, -1, usernsfd
, rootfd
);
6228 _exit(EXIT_FAILURE
);
6230 master
= posix_openpt(flags
);
6232 _exit(EXIT_FAILURE
);
6234 if (unlockpt(master
) < 0)
6235 _exit(EXIT_FAILURE
);
6237 if (send_one_fd(pair
[1], master
, 0) < 0)
6238 _exit(EXIT_FAILURE
);
6240 _exit(EXIT_SUCCESS
);
6243 pair
[1] = safe_close(pair
[1]);
6245 r
= wait_for_terminate(child
, &si
);
6248 if (si
.si_code
!= CLD_EXITED
|| si
.si_status
!= EXIT_SUCCESS
)
6251 return receive_one_fd(pair
[0], 0);
6254 ssize_t
fgetxattrat_fake(int dirfd
, const char *filename
, const char *attribute
, void *value
, size_t size
, int flags
) {
6255 _cleanup_close_
int fd
= -1;
6258 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
6260 fd
= openat(dirfd
, filename
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOATIME
|(flags
& AT_SYMLINK_NOFOLLOW
? O_NOFOLLOW
: 0));
6264 l
= fgetxattr(fd
, attribute
, value
, size
);
6271 static int parse_crtime(le64_t le
, usec_t
*usec
) {
6277 if (u
== 0 || u
== (uint64_t) -1)
6284 int fd_getcrtime(int fd
, usec_t
*usec
) {
6291 /* Until Linux gets a real concept of birthtime/creation time,
6292 * let's fake one with xattrs */
6294 n
= fgetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
));
6297 if (n
!= sizeof(le
))
6300 return parse_crtime(le
, usec
);
6303 int fd_getcrtime_at(int dirfd
, const char *name
, usec_t
*usec
, int flags
) {
6307 n
= fgetxattrat_fake(dirfd
, name
, "user.crtime_usec", &le
, sizeof(le
), flags
);
6310 if (n
!= sizeof(le
))
6313 return parse_crtime(le
, usec
);
6316 int path_getcrtime(const char *p
, usec_t
*usec
) {
6323 n
= getxattr(p
, "user.crtime_usec", &le
, sizeof(le
));
6326 if (n
!= sizeof(le
))
6329 return parse_crtime(le
, usec
);
6332 int fd_setcrtime(int fd
, usec_t usec
) {
6338 usec
= now(CLOCK_REALTIME
);
6340 le
= htole64((uint64_t) usec
);
6341 if (fsetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
), 0) < 0)
6347 int same_fd(int a
, int b
) {
6348 struct stat sta
, stb
;
6355 /* Compares two file descriptors. Note that semantics are
6356 * quite different depending on whether we have kcmp() or we
6357 * don't. If we have kcmp() this will only return true for
6358 * dup()ed file descriptors, but not otherwise. If we don't
6359 * have kcmp() this will also return true for two fds of the same
6360 * file, created by separate open() calls. Since we use this
6361 * call mostly for filtering out duplicates in the fd store
6362 * this difference hopefully doesn't matter too much. */
6367 /* Try to use kcmp() if we have it. */
6369 r
= kcmp(pid
, pid
, KCMP_FILE
, a
, b
);
6374 if (errno
!= ENOSYS
)
6377 /* We don't have kcmp(), use fstat() instead. */
6378 if (fstat(a
, &sta
) < 0)
6381 if (fstat(b
, &stb
) < 0)
6384 if ((sta
.st_mode
& S_IFMT
) != (stb
.st_mode
& S_IFMT
))
6387 /* We consider all device fds different, since two device fds
6388 * might refer to quite different device contexts even though
6389 * they share the same inode and backing dev_t. */
6391 if (S_ISCHR(sta
.st_mode
) || S_ISBLK(sta
.st_mode
))
6394 if (sta
.st_dev
!= stb
.st_dev
|| sta
.st_ino
!= stb
.st_ino
)
6397 /* The fds refer to the same inode on disk, let's also check
6398 * if they have the same fd flags. This is useful to
6399 * distinguish the read and write side of a pipe created with
6401 fa
= fcntl(a
, F_GETFL
);
6405 fb
= fcntl(b
, F_GETFL
);
6412 int chattr_fd(int fd
, unsigned value
, unsigned mask
) {
6413 unsigned old_attr
, new_attr
;
6418 if (fstat(fd
, &st
) < 0)
6421 /* Explicitly check whether this is a regular file or
6422 * directory. If it is anything else (such as a device node or
6423 * fifo), then the ioctl will not hit the file systems but
6424 * possibly drivers, where the ioctl might have different
6425 * effects. Notably, DRM is using the same ioctl() number. */
6427 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
6433 if (ioctl(fd
, FS_IOC_GETFLAGS
, &old_attr
) < 0)
6436 new_attr
= (old_attr
& ~mask
) | (value
& mask
);
6437 if (new_attr
== old_attr
)
6440 if (ioctl(fd
, FS_IOC_SETFLAGS
, &new_attr
) < 0)
6446 int chattr_path(const char *p
, unsigned value
, unsigned mask
) {
6447 _cleanup_close_
int fd
= -1;
6454 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
6458 return chattr_fd(fd
, value
, mask
);
6461 int read_attr_fd(int fd
, unsigned *ret
) {
6466 if (fstat(fd
, &st
) < 0)
6469 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
6472 if (ioctl(fd
, FS_IOC_GETFLAGS
, ret
) < 0)
6478 int read_attr_path(const char *p
, unsigned *ret
) {
6479 _cleanup_close_
int fd
= -1;
6484 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
6488 return read_attr_fd(fd
, ret
);
6491 static size_t nul_length(const uint8_t *p
, size_t sz
) {
6506 ssize_t
sparse_write(int fd
, const void *p
, size_t sz
, size_t run_length
) {
6507 const uint8_t *q
, *w
, *e
;
6515 n
= nul_length(q
, e
- q
);
6517 /* If there are more than the specified run length of
6518 * NUL bytes, or if this is the beginning or the end
6519 * of the buffer, then seek instead of write */
6520 if ((n
> run_length
) ||
6521 (n
> 0 && q
== p
) ||
6522 (n
> 0 && q
+ n
>= e
)) {
6524 l
= write(fd
, w
, q
- w
);
6531 if (lseek(fd
, n
, SEEK_CUR
) == (off_t
) -1)
6543 l
= write(fd
, w
, q
- w
);
6550 return q
- (const uint8_t*) p
;
6553 void sigkill_wait(pid_t
*pid
) {
6559 if (kill(*pid
, SIGKILL
) > 0)
6560 (void) wait_for_terminate(*pid
, NULL
);
6563 int syslog_parse_priority(const char **p
, int *priority
, bool with_facility
) {
6564 int a
= 0, b
= 0, c
= 0;
6574 if (!strchr(*p
, '>'))
6577 if ((*p
)[2] == '>') {
6578 c
= undecchar((*p
)[1]);
6580 } else if ((*p
)[3] == '>') {
6581 b
= undecchar((*p
)[1]);
6582 c
= undecchar((*p
)[2]);
6584 } else if ((*p
)[4] == '>') {
6585 a
= undecchar((*p
)[1]);
6586 b
= undecchar((*p
)[2]);
6587 c
= undecchar((*p
)[3]);
6592 if (a
< 0 || b
< 0 || c
< 0 ||
6593 (!with_facility
&& (a
|| b
|| c
> 7)))
6597 *priority
= a
*100 + b
*10 + c
;
6599 *priority
= (*priority
& LOG_FACMASK
) | c
;
6605 ssize_t
string_table_lookup(const char * const *table
, size_t len
, const char *key
) {
6611 for (i
= 0; i
< len
; ++i
)
6612 if (streq_ptr(table
[i
], key
))
6618 void cmsg_close_all(struct msghdr
*mh
) {
6619 struct cmsghdr
*cmsg
;
6623 CMSG_FOREACH(cmsg
, mh
)
6624 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
)
6625 close_many((int*) CMSG_DATA(cmsg
), (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int));
6628 int rename_noreplace(int olddirfd
, const char *oldpath
, int newdirfd
, const char *newpath
) {
6632 ret
= renameat2(olddirfd
, oldpath
, newdirfd
, newpath
, RENAME_NOREPLACE
);
6636 /* renameat2() exists since Linux 3.15, btrfs added support for it later.
6637 * If it is not implemented, fallback to another method. */
6638 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
6641 /* The link()/unlink() fallback does not work on directories. But
6642 * renameat() without RENAME_NOREPLACE gives the same semantics on
6643 * directories, except when newpath is an *empty* directory. This is
6645 ret
= fstatat(olddirfd
, oldpath
, &buf
, AT_SYMLINK_NOFOLLOW
);
6646 if (ret
>= 0 && S_ISDIR(buf
.st_mode
)) {
6647 ret
= renameat(olddirfd
, oldpath
, newdirfd
, newpath
);
6648 return ret
>= 0 ? 0 : -errno
;
6651 /* If it is not a directory, use the link()/unlink() fallback. */
6652 ret
= linkat(olddirfd
, oldpath
, newdirfd
, newpath
, 0);
6656 ret
= unlinkat(olddirfd
, oldpath
, 0);
6658 /* backup errno before the following unlinkat() alters it */
6660 (void) unlinkat(newdirfd
, newpath
, 0);
6668 static char *strcpy_backslash_escaped(char *t
, const char *s
, const char *bad
) {
6672 if (*s
== '\\' || strchr(bad
, *s
))
6681 char *shell_escape(const char *s
, const char *bad
) {
6684 r
= new(char, strlen(s
)*2+1);
6688 t
= strcpy_backslash_escaped(r
, s
, bad
);
6694 char *shell_maybe_quote(const char *s
) {
6700 /* Encloses a string in double quotes if necessary to make it
6701 * OK as shell string. */
6703 for (p
= s
; *p
; p
++)
6706 strchr(SHELL_NEED_QUOTES
, *p
))
6712 r
= new(char, 1+strlen(s
)*2+1+1);
6718 t
= mempcpy(t
, s
, p
- s
);
6720 t
= strcpy_backslash_escaped(t
, p
, SHELL_NEED_ESCAPE
);
6728 int parse_mode(const char *s
, mode_t
*ret
) {
6736 l
= strtol(s
, &x
, 8);
6740 if (!x
|| x
== s
|| *x
)
6742 if (l
< 0 || l
> 07777)
6749 int mount_move_root(const char *path
) {
6752 if (chdir(path
) < 0)
6755 if (mount(path
, "/", NULL
, MS_MOVE
, NULL
) < 0)
6758 if (chroot(".") < 0)
6767 int reset_uid_gid(void) {
6769 if (setgroups(0, NULL
) < 0)
6772 if (setresgid(0, 0, 0) < 0)
6775 if (setresuid(0, 0, 0) < 0)
6781 int getxattr_malloc(const char *path
, const char *name
, char **value
, bool allow_symlink
) {
6790 for (l
= 100; ; l
= (size_t) n
+ 1) {
6796 n
= lgetxattr(path
, name
, v
, l
);
6798 n
= getxattr(path
, name
, v
, l
);
6800 if (n
>= 0 && (size_t) n
< l
) {
6807 if (n
< 0 && errno
!= ERANGE
)
6811 n
= lgetxattr(path
, name
, NULL
, 0);
6813 n
= getxattr(path
, name
, NULL
, 0);
6819 int fgetxattr_malloc(int fd
, const char *name
, char **value
) {
6828 for (l
= 100; ; l
= (size_t) n
+ 1) {
6833 n
= fgetxattr(fd
, name
, v
, l
);
6835 if (n
>= 0 && (size_t) n
< l
) {
6842 if (n
< 0 && errno
!= ERANGE
)
6845 n
= fgetxattr(fd
, name
, NULL
, 0);
6851 int send_one_fd(int transport_fd
, int fd
, int flags
) {
6853 struct cmsghdr cmsghdr
;
6854 uint8_t buf
[CMSG_SPACE(sizeof(int))];
6856 struct msghdr mh
= {
6857 .msg_control
= &control
,
6858 .msg_controllen
= sizeof(control
),
6860 struct cmsghdr
*cmsg
;
6862 assert(transport_fd
>= 0);
6865 cmsg
= CMSG_FIRSTHDR(&mh
);
6866 cmsg
->cmsg_level
= SOL_SOCKET
;
6867 cmsg
->cmsg_type
= SCM_RIGHTS
;
6868 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
6869 memcpy(CMSG_DATA(cmsg
), &fd
, sizeof(int));
6871 mh
.msg_controllen
= CMSG_SPACE(sizeof(int));
6872 if (sendmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| flags
) < 0)
6878 int receive_one_fd(int transport_fd
, int flags
) {
6880 struct cmsghdr cmsghdr
;
6881 uint8_t buf
[CMSG_SPACE(sizeof(int))];
6883 struct msghdr mh
= {
6884 .msg_control
= &control
,
6885 .msg_controllen
= sizeof(control
),
6887 struct cmsghdr
*cmsg
, *found
= NULL
;
6889 assert(transport_fd
>= 0);
6892 * Receive a single FD via @transport_fd. We don't care for
6893 * the transport-type. We retrieve a single FD at most, so for
6894 * packet-based transports, the caller must ensure to send
6895 * only a single FD per packet. This is best used in
6896 * combination with send_one_fd().
6899 if (recvmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| MSG_CMSG_CLOEXEC
| flags
) < 0)
6902 CMSG_FOREACH(cmsg
, &mh
) {
6903 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
6904 cmsg
->cmsg_type
== SCM_RIGHTS
&&
6905 cmsg
->cmsg_len
== CMSG_LEN(sizeof(int))) {
6913 cmsg_close_all(&mh
);
6917 return *(int*) CMSG_DATA(found
);
6920 void nop_signal_handler(int sig
) {