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! */
77 #include "device-nodes.h"
79 #include "exit-status.h"
81 #include "formats-util.h"
84 #include "hostname-util.h"
90 #include "path-util.h"
91 #include "process-util.h"
92 #include "random-util.h"
93 #include "signal-util.h"
94 #include "sparse-endian.h"
96 #include "terminal-util.h"
101 /* Put this test here for a lack of better place */
102 assert_cc(EAGAIN
== EWOULDBLOCK
);
105 char **saved_argv
= NULL
;
107 size_t page_size(void) {
108 static thread_local
size_t pgsz
= 0;
111 if (_likely_(pgsz
> 0))
114 r
= sysconf(_SC_PAGESIZE
);
121 int strcmp_ptr(const char *a
, const char *b
) {
123 /* Like strcmp(), but tries to make sense of NULL pointers */
136 bool streq_ptr(const char *a
, const char *b
) {
137 return strcmp_ptr(a
, b
) == 0;
140 char* endswith(const char *s
, const char *postfix
) {
147 pl
= strlen(postfix
);
150 return (char*) s
+ sl
;
155 if (memcmp(s
+ sl
- pl
, postfix
, pl
) != 0)
158 return (char*) s
+ sl
- pl
;
161 char* endswith_no_case(const char *s
, const char *postfix
) {
168 pl
= strlen(postfix
);
171 return (char*) s
+ sl
;
176 if (strcasecmp(s
+ sl
- pl
, postfix
) != 0)
179 return (char*) s
+ sl
- pl
;
182 char* first_word(const char *s
, const char *word
) {
189 /* Checks if the string starts with the specified word, either
190 * followed by NUL or by whitespace. Returns a pointer to the
191 * NUL or the first character after the whitespace. */
202 if (memcmp(s
, word
, wl
) != 0)
209 if (!strchr(WHITESPACE
, *p
))
212 p
+= strspn(p
, WHITESPACE
);
216 size_t cescape_char(char c
, char *buf
) {
217 char * buf_old
= buf
;
263 /* For special chars we prefer octal over
264 * hexadecimal encoding, simply because glib's
265 * g_strescape() does the same */
266 if ((c
< ' ') || (c
>= 127)) {
268 *(buf
++) = octchar((unsigned char) c
>> 6);
269 *(buf
++) = octchar((unsigned char) c
>> 3);
270 *(buf
++) = octchar((unsigned char) c
);
276 return buf
- buf_old
;
279 int close_nointr(int fd
) {
286 * Just ignore EINTR; a retry loop is the wrong thing to do on
289 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
290 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
291 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
292 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
300 int safe_close(int fd
) {
303 * Like close_nointr() but cannot fail. Guarantees errno is
304 * unchanged. Is a NOP with negative fds passed, and returns
305 * -1, so that it can be used in this syntax:
307 * fd = safe_close(fd);
313 /* The kernel might return pretty much any error code
314 * via close(), but the fd will be closed anyway. The
315 * only condition we want to check for here is whether
316 * the fd was invalid at all... */
318 assert_se(close_nointr(fd
) != -EBADF
);
324 void close_many(const int fds
[], unsigned n_fd
) {
327 assert(fds
|| n_fd
<= 0);
329 for (i
= 0; i
< n_fd
; i
++)
333 int fclose_nointr(FILE *f
) {
336 /* Same as close_nointr(), but for fclose() */
347 FILE* safe_fclose(FILE *f
) {
349 /* Same as safe_close(), but for fclose() */
354 assert_se(fclose_nointr(f
) != EBADF
);
360 DIR* safe_closedir(DIR *d
) {
365 assert_se(closedir(d
) >= 0 || errno
!= EBADF
);
371 int unlink_noerrno(const char *path
) {
382 int parse_boolean(const char *v
) {
385 if (streq(v
, "1") || strcaseeq(v
, "yes") || strcaseeq(v
, "y") || strcaseeq(v
, "true") || strcaseeq(v
, "t") || strcaseeq(v
, "on"))
387 else if (streq(v
, "0") || strcaseeq(v
, "no") || strcaseeq(v
, "n") || strcaseeq(v
, "false") || strcaseeq(v
, "f") || strcaseeq(v
, "off"))
393 int parse_pid(const char *s
, pid_t
* ret_pid
) {
394 unsigned long ul
= 0;
401 r
= safe_atolu(s
, &ul
);
407 if ((unsigned long) pid
!= ul
)
417 bool uid_is_valid(uid_t uid
) {
419 /* Some libc APIs use UID_INVALID as special placeholder */
420 if (uid
== (uid_t
) 0xFFFFFFFF)
423 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
424 if (uid
== (uid_t
) 0xFFFF)
430 int parse_uid(const char *s
, uid_t
* ret_uid
) {
431 unsigned long ul
= 0;
437 r
= safe_atolu(s
, &ul
);
443 if ((unsigned long) uid
!= ul
)
446 if (!uid_is_valid(uid
))
447 return -ENXIO
; /* we return ENXIO instead of EINVAL
448 * here, to make it easy to distuingish
449 * invalid numeric uids invalid
458 int safe_atou(const char *s
, unsigned *ret_u
) {
466 l
= strtoul(s
, &x
, 0);
468 if (!x
|| x
== s
|| *x
|| errno
)
469 return errno
> 0 ? -errno
: -EINVAL
;
471 if ((unsigned long) (unsigned) l
!= l
)
474 *ret_u
= (unsigned) l
;
478 int safe_atoi(const char *s
, int *ret_i
) {
486 l
= strtol(s
, &x
, 0);
488 if (!x
|| x
== s
|| *x
|| errno
)
489 return errno
> 0 ? -errno
: -EINVAL
;
491 if ((long) (int) l
!= l
)
498 int safe_atou8(const char *s
, uint8_t *ret
) {
506 l
= strtoul(s
, &x
, 0);
508 if (!x
|| x
== s
|| *x
|| errno
)
509 return errno
> 0 ? -errno
: -EINVAL
;
511 if ((unsigned long) (uint8_t) l
!= l
)
518 int safe_atou16(const char *s
, uint16_t *ret
) {
526 l
= strtoul(s
, &x
, 0);
528 if (!x
|| x
== s
|| *x
|| errno
)
529 return errno
> 0 ? -errno
: -EINVAL
;
531 if ((unsigned long) (uint16_t) l
!= l
)
538 int safe_atoi16(const char *s
, int16_t *ret
) {
546 l
= strtol(s
, &x
, 0);
548 if (!x
|| x
== s
|| *x
|| errno
)
549 return errno
> 0 ? -errno
: -EINVAL
;
551 if ((long) (int16_t) l
!= l
)
558 int safe_atollu(const char *s
, long long unsigned *ret_llu
) {
560 unsigned long long l
;
566 l
= strtoull(s
, &x
, 0);
568 if (!x
|| x
== s
|| *x
|| errno
)
569 return errno
? -errno
: -EINVAL
;
575 int safe_atolli(const char *s
, long long int *ret_lli
) {
583 l
= strtoll(s
, &x
, 0);
585 if (!x
|| x
== s
|| *x
|| errno
)
586 return errno
? -errno
: -EINVAL
;
592 int safe_atod(const char *s
, double *ret_d
) {
600 loc
= newlocale(LC_NUMERIC_MASK
, "C", (locale_t
) 0);
601 if (loc
== (locale_t
) 0)
605 d
= strtod_l(s
, &x
, loc
);
607 if (!x
|| x
== s
|| *x
|| errno
) {
609 return errno
? -errno
: -EINVAL
;
617 static size_t strcspn_escaped(const char *s
, const char *reject
) {
618 bool escaped
= false;
621 for (n
=0; s
[n
]; n
++) {
624 else if (s
[n
] == '\\')
626 else if (strchr(reject
, s
[n
]))
630 /* if s ends in \, return index of previous char */
634 /* Split a string into words. */
635 const char* split(const char **state
, size_t *l
, const char *separator
, bool quoted
) {
641 assert(**state
== '\0');
645 current
+= strspn(current
, separator
);
651 if (quoted
&& strchr("\'\"", *current
)) {
652 char quotechars
[2] = {*current
, '\0'};
654 *l
= strcspn_escaped(current
+ 1, quotechars
);
655 if (current
[*l
+ 1] == '\0' || current
[*l
+ 1] != quotechars
[0] ||
656 (current
[*l
+ 2] && !strchr(separator
, current
[*l
+ 2]))) {
657 /* right quote missing or garbage at the end */
661 *state
= current
++ + *l
+ 2;
663 *l
= strcspn_escaped(current
, separator
);
664 if (current
[*l
] && !strchr(separator
, current
[*l
])) {
665 /* unfinished escape */
669 *state
= current
+ *l
;
671 *l
= strcspn(current
, separator
);
672 *state
= current
+ *l
;
678 int fchmod_umask(int fd
, mode_t m
) {
683 r
= fchmod(fd
, m
& (~u
)) < 0 ? -errno
: 0;
689 char *truncate_nl(char *s
) {
692 s
[strcspn(s
, NEWLINE
)] = 0;
696 char *strnappend(const char *s
, const char *suffix
, size_t b
) {
704 return strndup(suffix
, b
);
713 if (b
> ((size_t) -1) - a
)
716 r
= new(char, a
+b
+1);
721 memcpy(r
+a
, suffix
, b
);
727 char *strappend(const char *s
, const char *suffix
) {
728 return strnappend(s
, suffix
, suffix
? strlen(suffix
) : 0);
731 int readlinkat_malloc(int fd
, const char *p
, char **ret
) {
746 n
= readlinkat(fd
, p
, c
, l
-1);
753 if ((size_t) n
< l
-1) {
764 int readlink_malloc(const char *p
, char **ret
) {
765 return readlinkat_malloc(AT_FDCWD
, p
, ret
);
768 int readlink_value(const char *p
, char **ret
) {
769 _cleanup_free_
char *link
= NULL
;
773 r
= readlink_malloc(p
, &link
);
777 value
= basename(link
);
781 value
= strdup(value
);
790 int readlink_and_make_absolute(const char *p
, char **r
) {
791 _cleanup_free_
char *target
= NULL
;
798 j
= readlink_malloc(p
, &target
);
802 k
= file_in_same_dir(p
, target
);
810 int readlink_and_canonicalize(const char *p
, char **r
) {
817 j
= readlink_and_make_absolute(p
, &t
);
821 s
= canonicalize_file_name(t
);
828 path_kill_slashes(*r
);
833 char *strstrip(char *s
) {
836 /* Drops trailing whitespace. Modifies the string in
837 * place. Returns pointer to first non-space character */
839 s
+= strspn(s
, WHITESPACE
);
841 for (e
= strchr(s
, 0); e
> s
; e
--)
842 if (!strchr(WHITESPACE
, e
[-1]))
850 char *delete_chars(char *s
, const char *bad
) {
853 /* Drops all whitespace, regardless where in the string */
855 for (f
= s
, t
= s
; *f
; f
++) {
867 char *file_in_same_dir(const char *path
, const char *filename
) {
874 /* This removes the last component of path and appends
875 * filename, unless the latter is absolute anyway or the
878 if (path_is_absolute(filename
))
879 return strdup(filename
);
881 e
= strrchr(path
, '/');
883 return strdup(filename
);
885 k
= strlen(filename
);
886 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
890 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
894 int rmdir_parents(const char *path
, const char *stop
) {
903 /* Skip trailing slashes */
904 while (l
> 0 && path
[l
-1] == '/')
910 /* Skip last component */
911 while (l
> 0 && path
[l
-1] != '/')
914 /* Skip trailing slashes */
915 while (l
> 0 && path
[l
-1] == '/')
921 if (!(t
= strndup(path
, l
)))
924 if (path_startswith(stop
, t
)) {
940 char hexchar(int x
) {
941 static const char table
[16] = "0123456789abcdef";
943 return table
[x
& 15];
946 int unhexchar(char c
) {
948 if (c
>= '0' && c
<= '9')
951 if (c
>= 'a' && c
<= 'f')
954 if (c
>= 'A' && c
<= 'F')
960 char *hexmem(const void *p
, size_t l
) {
964 z
= r
= malloc(l
* 2 + 1);
968 for (x
= p
; x
< (const uint8_t*) p
+ l
; x
++) {
969 *(z
++) = hexchar(*x
>> 4);
970 *(z
++) = hexchar(*x
& 15);
977 int unhexmem(const char *p
, size_t l
, void **mem
, size_t *len
) {
978 _cleanup_free_
uint8_t *r
= NULL
;
986 z
= r
= malloc((l
+ 1) / 2 + 1);
990 for (x
= p
; x
< p
+ l
; x
+= 2) {
996 else if (x
+1 < p
+ l
) {
1003 *(z
++) = (uint8_t) a
<< 4 | (uint8_t) b
;
1015 /* https://tools.ietf.org/html/rfc4648#section-6
1016 * Notice that base32hex differs from base32 in the alphabet it uses.
1017 * The distinction is that the base32hex representation preserves the
1018 * order of the underlying data when compared as bytestrings, this is
1019 * useful when representing NSEC3 hashes, as one can then verify the
1020 * order of hashes directly from their representation. */
1021 char base32hexchar(int x
) {
1022 static const char table
[32] = "0123456789"
1023 "ABCDEFGHIJKLMNOPQRSTUV";
1025 return table
[x
& 31];
1028 int unbase32hexchar(char c
) {
1031 if (c
>= '0' && c
<= '9')
1034 offset
= '9' - '0' + 1;
1036 if (c
>= 'A' && c
<= 'V')
1037 return c
- 'A' + offset
;
1042 char *base32hexmem(const void *p
, size_t l
, bool padding
) {
1048 /* five input bytes makes eight output bytes, padding is added so we must round up */
1049 len
= 8 * (l
+ 4) / 5;
1051 /* same, but round down as there is no padding */
1070 z
= r
= malloc(len
+ 1);
1074 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 5) * 5; x
+= 5) {
1075 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ
1076 x[3] == QQQQQQQQ; x[4] == WWWWWWWW */
1077 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1078 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1079 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1080 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1081 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
1082 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
1083 *(z
++) = base32hexchar((x
[3] & 3) << 3 | x
[4] >> 5); /* 000QQWWW */
1084 *(z
++) = base32hexchar((x
[4] & 31)); /* 000WWWWW */
1089 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1090 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1091 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1092 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1093 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
1094 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
1095 *(z
++) = base32hexchar((x
[3] & 3) << 3); /* 000QQ000 */
1102 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1103 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1104 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1105 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1106 *(z
++) = base32hexchar((x
[2] & 15) << 1); /* 000ZZZZ0 */
1116 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1117 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1118 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1119 *(z
++) = base32hexchar((x
[1] & 1) << 4); /* 000Y0000 */
1130 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1131 *(z
++) = base32hexchar((x
[0] & 7) << 2); /* 000XXX00 */
1148 int unbase32hexmem(const char *p
, size_t l
, bool padding
, void **mem
, size_t *_len
) {
1149 _cleanup_free_
uint8_t *r
= NULL
;
1150 int a
, b
, c
, d
, e
, f
, g
, h
;
1158 /* padding ensures any base32hex input has input divisible by 8 */
1159 if (padding
&& l
% 8 != 0)
1163 /* strip the padding */
1164 while (l
> 0 && p
[l
- 1] == '=' && pad
< 7) {
1170 /* a group of eight input bytes needs five output bytes, in case of
1171 padding we need to add some extra bytes */
1193 z
= r
= malloc(len
+ 1);
1197 for (x
= p
; x
< p
+ (l
/ 8) * 8; x
+= 8) {
1198 /* a == 000XXXXX; b == 000YYYYY; c == 000ZZZZZ; d == 000WWWWW
1199 e == 000SSSSS; f == 000QQQQQ; g == 000VVVVV; h == 000RRRRR */
1200 a
= unbase32hexchar(x
[0]);
1204 b
= unbase32hexchar(x
[1]);
1208 c
= unbase32hexchar(x
[2]);
1212 d
= unbase32hexchar(x
[3]);
1216 e
= unbase32hexchar(x
[4]);
1220 f
= unbase32hexchar(x
[5]);
1224 g
= unbase32hexchar(x
[6]);
1228 h
= unbase32hexchar(x
[7]);
1232 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1233 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1234 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1235 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
1236 *(z
++) = (uint8_t) g
<< 5 | (uint8_t) h
; /* VVVRRRRR */
1241 a
= unbase32hexchar(x
[0]);
1245 b
= unbase32hexchar(x
[1]);
1249 c
= unbase32hexchar(x
[2]);
1253 d
= unbase32hexchar(x
[3]);
1257 e
= unbase32hexchar(x
[4]);
1261 f
= unbase32hexchar(x
[5]);
1265 g
= unbase32hexchar(x
[6]);
1273 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1274 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1275 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1276 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
1280 a
= unbase32hexchar(x
[0]);
1284 b
= unbase32hexchar(x
[1]);
1288 c
= unbase32hexchar(x
[2]);
1292 d
= unbase32hexchar(x
[3]);
1296 e
= unbase32hexchar(x
[4]);
1304 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1305 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1306 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1310 a
= unbase32hexchar(x
[0]);
1314 b
= unbase32hexchar(x
[1]);
1318 c
= unbase32hexchar(x
[2]);
1322 d
= unbase32hexchar(x
[3]);
1330 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1331 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1335 a
= unbase32hexchar(x
[0]);
1339 b
= unbase32hexchar(x
[1]);
1347 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1365 /* https://tools.ietf.org/html/rfc4648#section-4 */
1366 char base64char(int x
) {
1367 static const char table
[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1368 "abcdefghijklmnopqrstuvwxyz"
1370 return table
[x
& 63];
1373 int unbase64char(char c
) {
1376 if (c
>= 'A' && c
<= 'Z')
1379 offset
= 'Z' - 'A' + 1;
1381 if (c
>= 'a' && c
<= 'z')
1382 return c
- 'a' + offset
;
1384 offset
+= 'z' - 'a' + 1;
1386 if (c
>= '0' && c
<= '9')
1387 return c
- '0' + offset
;
1389 offset
+= '9' - '0' + 1;
1402 char *base64mem(const void *p
, size_t l
) {
1406 /* three input bytes makes four output bytes, padding is added so we must round up */
1407 z
= r
= malloc(4 * (l
+ 2) / 3 + 1);
1411 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 3) * 3; x
+= 3) {
1412 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ */
1413 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1414 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1415 *(z
++) = base64char((x
[1] & 15) << 2 | x
[2] >> 6); /* 00YYYYZZ */
1416 *(z
++) = base64char(x
[2] & 63); /* 00ZZZZZZ */
1421 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1422 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1423 *(z
++) = base64char((x
[1] & 15) << 2); /* 00YYYY00 */
1428 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1429 *(z
++) = base64char((x
[0] & 3) << 4); /* 00XX0000 */
1440 int unbase64mem(const char *p
, size_t l
, void **mem
, size_t *_len
) {
1441 _cleanup_free_
uint8_t *r
= NULL
;
1449 /* padding ensures any base63 input has input divisible by 4 */
1453 /* strip the padding */
1454 if (l
> 0 && p
[l
- 1] == '=')
1456 if (l
> 0 && p
[l
- 1] == '=')
1459 /* a group of four input bytes needs three output bytes, in case of
1460 padding we need to add two or three extra bytes */
1461 len
= (l
/ 4) * 3 + (l
% 4 ? (l
% 4) - 1 : 0);
1463 z
= r
= malloc(len
+ 1);
1467 for (x
= p
; x
< p
+ (l
/ 4) * 4; x
+= 4) {
1468 /* a == 00XXXXXX; b == 00YYYYYY; c == 00ZZZZZZ; d == 00WWWWWW */
1469 a
= unbase64char(x
[0]);
1473 b
= unbase64char(x
[1]);
1477 c
= unbase64char(x
[2]);
1481 d
= unbase64char(x
[3]);
1485 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1486 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1487 *(z
++) = (uint8_t) c
<< 6 | (uint8_t) d
; /* ZZWWWWWW */
1492 a
= unbase64char(x
[0]);
1496 b
= unbase64char(x
[1]);
1500 c
= unbase64char(x
[2]);
1508 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1509 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1513 a
= unbase64char(x
[0]);
1517 b
= unbase64char(x
[1]);
1525 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) (b
>> 4); /* XXXXXXYY */
1544 char octchar(int x
) {
1545 return '0' + (x
& 7);
1548 int unoctchar(char c
) {
1550 if (c
>= '0' && c
<= '7')
1556 char decchar(int x
) {
1557 return '0' + (x
% 10);
1560 int undecchar(char c
) {
1562 if (c
>= '0' && c
<= '9')
1568 char *cescape(const char *s
) {
1574 /* Does C style string escaping. May be reversed with
1577 r
= new(char, strlen(s
)*4 + 1);
1581 for (f
= s
, t
= r
; *f
; f
++)
1582 t
+= cescape_char(*f
, t
);
1589 static int cunescape_one(const char *p
, size_t length
, char *ret
, uint32_t *ret_unicode
) {
1596 /* Unescapes C style. Returns the unescaped character in ret,
1597 * unless we encountered a \u sequence in which case the full
1598 * unicode character is returned in ret_unicode, instead. */
1600 if (length
!= (size_t) -1 && length
< 1)
1637 /* This is an extension of the XDG syntax files */
1642 /* hexadecimal encoding */
1645 if (length
!= (size_t) -1 && length
< 3)
1648 a
= unhexchar(p
[1]);
1652 b
= unhexchar(p
[2]);
1656 /* Don't allow NUL bytes */
1657 if (a
== 0 && b
== 0)
1660 *ret
= (char) ((a
<< 4U) | b
);
1666 /* C++11 style 16bit unicode */
1672 if (length
!= (size_t) -1 && length
< 5)
1675 for (i
= 0; i
< 4; i
++) {
1676 a
[i
] = unhexchar(p
[1 + i
]);
1681 c
= ((uint32_t) a
[0] << 12U) | ((uint32_t) a
[1] << 8U) | ((uint32_t) a
[2] << 4U) | (uint32_t) a
[3];
1683 /* Don't allow 0 chars */
1702 /* C++11 style 32bit unicode */
1708 if (length
!= (size_t) -1 && length
< 9)
1711 for (i
= 0; i
< 8; i
++) {
1712 a
[i
] = unhexchar(p
[1 + i
]);
1717 c
= ((uint32_t) a
[0] << 28U) | ((uint32_t) a
[1] << 24U) | ((uint32_t) a
[2] << 20U) | ((uint32_t) a
[3] << 16U) |
1718 ((uint32_t) a
[4] << 12U) | ((uint32_t) a
[5] << 8U) | ((uint32_t) a
[6] << 4U) | (uint32_t) a
[7];
1720 /* Don't allow 0 chars */
1724 /* Don't allow invalid code points */
1725 if (!unichar_is_valid(c
))
1750 /* octal encoding */
1754 if (length
!= (size_t) -1 && length
< 3)
1757 a
= unoctchar(p
[0]);
1761 b
= unoctchar(p
[1]);
1765 c
= unoctchar(p
[2]);
1769 /* don't allow NUL bytes */
1770 if (a
== 0 && b
== 0 && c
== 0)
1773 /* Don't allow bytes above 255 */
1774 m
= ((uint32_t) a
<< 6U) | ((uint32_t) b
<< 3U) | (uint32_t) c
;
1790 int cunescape_length_with_prefix(const char *s
, size_t length
, const char *prefix
, UnescapeFlags flags
, char **ret
) {
1798 /* Undoes C style string escaping, and optionally prefixes it. */
1800 pl
= prefix
? strlen(prefix
) : 0;
1802 r
= new(char, pl
+length
+1);
1807 memcpy(r
, prefix
, pl
);
1809 for (f
= s
, t
= r
+ pl
; f
< s
+ length
; f
++) {
1815 remaining
= s
+ length
- f
;
1816 assert(remaining
> 0);
1819 /* A literal literal, copy verbatim */
1824 if (remaining
== 1) {
1825 if (flags
& UNESCAPE_RELAX
) {
1826 /* A trailing backslash, copy verbatim */
1835 k
= cunescape_one(f
+ 1, remaining
- 1, &c
, &u
);
1837 if (flags
& UNESCAPE_RELAX
) {
1838 /* Invalid escape code, let's take it literal then */
1848 /* Non-Unicode? Let's encode this directly */
1851 /* Unicode? Then let's encode this in UTF-8 */
1852 t
+= utf8_encode_unichar(t
, u
);
1863 int cunescape_length(const char *s
, size_t length
, UnescapeFlags flags
, char **ret
) {
1864 return cunescape_length_with_prefix(s
, length
, NULL
, flags
, ret
);
1867 int cunescape(const char *s
, UnescapeFlags flags
, char **ret
) {
1868 return cunescape_length(s
, strlen(s
), flags
, ret
);
1871 char *xescape(const char *s
, const char *bad
) {
1875 /* Escapes all chars in bad, in addition to \ and all special
1876 * chars, in \xFF style escaping. May be reversed with
1879 r
= new(char, strlen(s
) * 4 + 1);
1883 for (f
= s
, t
= r
; *f
; f
++) {
1885 if ((*f
< ' ') || (*f
>= 127) ||
1886 (*f
== '\\') || strchr(bad
, *f
)) {
1889 *(t
++) = hexchar(*f
>> 4);
1890 *(t
++) = hexchar(*f
);
1900 char *ascii_strlower(char *t
) {
1905 for (p
= t
; *p
; p
++)
1906 if (*p
>= 'A' && *p
<= 'Z')
1907 *p
= *p
- 'A' + 'a';
1912 _pure_
static bool hidden_file_allow_backup(const char *filename
) {
1916 filename
[0] == '.' ||
1917 streq(filename
, "lost+found") ||
1918 streq(filename
, "aquota.user") ||
1919 streq(filename
, "aquota.group") ||
1920 endswith(filename
, ".rpmnew") ||
1921 endswith(filename
, ".rpmsave") ||
1922 endswith(filename
, ".rpmorig") ||
1923 endswith(filename
, ".dpkg-old") ||
1924 endswith(filename
, ".dpkg-new") ||
1925 endswith(filename
, ".dpkg-tmp") ||
1926 endswith(filename
, ".dpkg-dist") ||
1927 endswith(filename
, ".dpkg-bak") ||
1928 endswith(filename
, ".dpkg-backup") ||
1929 endswith(filename
, ".dpkg-remove") ||
1930 endswith(filename
, ".swp");
1933 bool hidden_file(const char *filename
) {
1936 if (endswith(filename
, "~"))
1939 return hidden_file_allow_backup(filename
);
1942 int fd_nonblock(int fd
, bool nonblock
) {
1947 flags
= fcntl(fd
, F_GETFL
, 0);
1952 nflags
= flags
| O_NONBLOCK
;
1954 nflags
= flags
& ~O_NONBLOCK
;
1956 if (nflags
== flags
)
1959 if (fcntl(fd
, F_SETFL
, nflags
) < 0)
1965 int fd_cloexec(int fd
, bool cloexec
) {
1970 flags
= fcntl(fd
, F_GETFD
, 0);
1975 nflags
= flags
| FD_CLOEXEC
;
1977 nflags
= flags
& ~FD_CLOEXEC
;
1979 if (nflags
== flags
)
1982 if (fcntl(fd
, F_SETFD
, nflags
) < 0)
1988 _pure_
static bool fd_in_set(int fd
, const int fdset
[], unsigned n_fdset
) {
1991 assert(n_fdset
== 0 || fdset
);
1993 for (i
= 0; i
< n_fdset
; i
++)
2000 int close_all_fds(const int except
[], unsigned n_except
) {
2001 _cleanup_closedir_
DIR *d
= NULL
;
2005 assert(n_except
== 0 || except
);
2007 d
= opendir("/proc/self/fd");
2012 /* When /proc isn't available (for example in chroots)
2013 * the fallback is brute forcing through the fd
2016 assert_se(getrlimit(RLIMIT_NOFILE
, &rl
) >= 0);
2017 for (fd
= 3; fd
< (int) rl
.rlim_max
; fd
++) {
2019 if (fd_in_set(fd
, except
, n_except
))
2022 if (close_nointr(fd
) < 0)
2023 if (errno
!= EBADF
&& r
== 0)
2030 while ((de
= readdir(d
))) {
2033 if (hidden_file(de
->d_name
))
2036 if (safe_atoi(de
->d_name
, &fd
) < 0)
2037 /* Let's better ignore this, just in case */
2046 if (fd_in_set(fd
, except
, n_except
))
2049 if (close_nointr(fd
) < 0) {
2050 /* Valgrind has its own FD and doesn't want to have it closed */
2051 if (errno
!= EBADF
&& r
== 0)
2059 bool chars_intersect(const char *a
, const char *b
) {
2062 /* Returns true if any of the chars in a are in b. */
2063 for (p
= a
; *p
; p
++)
2070 bool fstype_is_network(const char *fstype
) {
2071 static const char table
[] =
2086 x
= startswith(fstype
, "fuse.");
2090 return nulstr_contains(table
, fstype
);
2093 int flush_fd(int fd
) {
2094 struct pollfd pollfd
= {
2104 r
= poll(&pollfd
, 1, 0);
2114 l
= read(fd
, buf
, sizeof(buf
));
2120 if (errno
== EAGAIN
)
2129 void safe_close_pair(int p
[]) {
2133 /* Special case pairs which use the same fd in both
2135 p
[0] = p
[1] = safe_close(p
[0]);
2139 p
[0] = safe_close(p
[0]);
2140 p
[1] = safe_close(p
[1]);
2143 ssize_t
loop_read(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2150 /* If called with nbytes == 0, let's call read() at least
2151 * once, to validate the operation */
2153 if (nbytes
> (size_t) SSIZE_MAX
)
2159 k
= read(fd
, p
, nbytes
);
2164 if (errno
== EAGAIN
&& do_poll
) {
2166 /* We knowingly ignore any return value here,
2167 * and expect that any error/EOF is reported
2170 (void) fd_wait_for_event(fd
, POLLIN
, USEC_INFINITY
);
2174 return n
> 0 ? n
: -errno
;
2180 assert((size_t) k
<= nbytes
);
2185 } while (nbytes
> 0);
2190 int loop_read_exact(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2193 n
= loop_read(fd
, buf
, nbytes
, do_poll
);
2196 if ((size_t) n
!= nbytes
)
2202 int loop_write(int fd
, const void *buf
, size_t nbytes
, bool do_poll
) {
2203 const uint8_t *p
= buf
;
2208 if (nbytes
> (size_t) SSIZE_MAX
)
2214 k
= write(fd
, p
, nbytes
);
2219 if (errno
== EAGAIN
&& do_poll
) {
2220 /* We knowingly ignore any return value here,
2221 * and expect that any error/EOF is reported
2224 (void) fd_wait_for_event(fd
, POLLOUT
, USEC_INFINITY
);
2231 if (_unlikely_(nbytes
> 0 && k
== 0)) /* Can't really happen */
2234 assert((size_t) k
<= nbytes
);
2238 } while (nbytes
> 0);
2243 int parse_size(const char *t
, uint64_t base
, uint64_t *size
) {
2245 /* Soo, sometimes we want to parse IEC binary suffixes, and
2246 * sometimes SI decimal suffixes. This function can parse
2247 * both. Which one is the right way depends on the
2248 * context. Wikipedia suggests that SI is customary for
2249 * hardware metrics and network speeds, while IEC is
2250 * customary for most data sizes used by software and volatile
2251 * (RAM) memory. Hence be careful which one you pick!
2253 * In either case we use just K, M, G as suffix, and not Ki,
2254 * Mi, Gi or so (as IEC would suggest). That's because that's
2255 * frickin' ugly. But this means you really need to make sure
2256 * to document which base you are parsing when you use this
2261 unsigned long long factor
;
2264 static const struct table iec
[] = {
2265 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2266 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2267 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2268 { "G", 1024ULL*1024ULL*1024ULL },
2269 { "M", 1024ULL*1024ULL },
2275 static const struct table si
[] = {
2276 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2277 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2278 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2279 { "G", 1000ULL*1000ULL*1000ULL },
2280 { "M", 1000ULL*1000ULL },
2286 const struct table
*table
;
2288 unsigned long long r
= 0;
2289 unsigned n_entries
, start_pos
= 0;
2292 assert(base
== 1000 || base
== 1024);
2297 n_entries
= ELEMENTSOF(si
);
2300 n_entries
= ELEMENTSOF(iec
);
2305 unsigned long long l
, tmp
;
2310 p
+= strspn(p
, WHITESPACE
);
2315 l
= strtoull(p
, &e
, 10);
2324 /* strtoull() itself would accept space/+/- */
2325 if (*e
>= '0' && *e
<= '9') {
2326 unsigned long long l2
;
2329 l2
= strtoull(e
, &e2
, 10);
2333 /* Ignore failure. E.g. 10.M is valid */
2340 e
+= strspn(e
, WHITESPACE
);
2342 for (i
= start_pos
; i
< n_entries
; i
++)
2343 if (startswith(e
, table
[i
].suffix
))
2349 if (l
+ (frac
> 0) > ULLONG_MAX
/ table
[i
].factor
)
2352 tmp
= l
* table
[i
].factor
+ (unsigned long long) (frac
* table
[i
].factor
);
2353 if (tmp
> ULLONG_MAX
- r
)
2357 if ((unsigned long long) (uint64_t) r
!= r
)
2360 p
= e
+ strlen(table
[i
].suffix
);
2371 bool is_device_path(const char *path
) {
2373 /* Returns true on paths that refer to a device, either in
2374 * sysfs or in /dev */
2377 path_startswith(path
, "/dev/") ||
2378 path_startswith(path
, "/sys/");
2381 int dir_is_empty(const char *path
) {
2382 _cleanup_closedir_
DIR *d
;
2393 if (!de
&& errno
!= 0)
2399 if (!hidden_file(de
->d_name
))
2404 char* dirname_malloc(const char *path
) {
2405 char *d
, *dir
, *dir2
;
2422 void rename_process(const char name
[8]) {
2425 /* This is a like a poor man's setproctitle(). It changes the
2426 * comm field, argv[0], and also the glibc's internally used
2427 * name of the process. For the first one a limit of 16 chars
2428 * applies, to the second one usually one of 10 (i.e. length
2429 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2430 * "systemd"). If you pass a longer string it will be
2433 prctl(PR_SET_NAME
, name
);
2435 if (program_invocation_name
)
2436 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
2438 if (saved_argc
> 0) {
2442 strncpy(saved_argv
[0], name
, strlen(saved_argv
[0]));
2444 for (i
= 1; i
< saved_argc
; i
++) {
2448 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
2453 char *lookup_uid(uid_t uid
) {
2456 _cleanup_free_
char *buf
= NULL
;
2457 struct passwd pwbuf
, *pw
= NULL
;
2459 /* Shortcut things to avoid NSS lookups */
2461 return strdup("root");
2463 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
2467 buf
= malloc(bufsize
);
2471 if (getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
) == 0 && pw
)
2472 return strdup(pw
->pw_name
);
2474 if (asprintf(&name
, UID_FMT
, uid
) < 0)
2480 char* getlogname_malloc(void) {
2484 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
2489 return lookup_uid(uid
);
2492 char *getusername_malloc(void) {
2499 return lookup_uid(getuid());
2502 bool is_temporary_fs(const struct statfs
*s
) {
2505 return F_TYPE_EQUAL(s
->f_type
, TMPFS_MAGIC
) ||
2506 F_TYPE_EQUAL(s
->f_type
, RAMFS_MAGIC
);
2509 int fd_is_temporary_fs(int fd
) {
2512 if (fstatfs(fd
, &s
) < 0)
2515 return is_temporary_fs(&s
);
2518 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
2521 /* Under the assumption that we are running privileged we
2522 * first change the access mode and only then hand out
2523 * ownership to avoid a window where access is too open. */
2525 if (mode
!= MODE_INVALID
)
2526 if (chmod(path
, mode
) < 0)
2529 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
2530 if (chown(path
, uid
, gid
) < 0)
2536 int fchmod_and_fchown(int fd
, mode_t mode
, uid_t uid
, gid_t gid
) {
2539 /* Under the assumption that we are running privileged we
2540 * first change the access mode and only then hand out
2541 * ownership to avoid a window where access is too open. */
2543 if (mode
!= MODE_INVALID
)
2544 if (fchmod(fd
, mode
) < 0)
2547 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
2548 if (fchown(fd
, uid
, gid
) < 0)
2554 int files_same(const char *filea
, const char *fileb
) {
2557 if (stat(filea
, &a
) < 0)
2560 if (stat(fileb
, &b
) < 0)
2563 return a
.st_dev
== b
.st_dev
&&
2564 a
.st_ino
== b
.st_ino
;
2567 int running_in_chroot(void) {
2570 ret
= files_same("/proc/1/root", "/");
2577 static char *ascii_ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
2582 assert(percent
<= 100);
2583 assert(new_length
>= 3);
2585 if (old_length
<= 3 || old_length
<= new_length
)
2586 return strndup(s
, old_length
);
2588 r
= new0(char, new_length
+1);
2592 x
= (new_length
* percent
) / 100;
2594 if (x
> new_length
- 3)
2602 s
+ old_length
- (new_length
- x
- 3),
2603 new_length
- x
- 3);
2608 char *ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
2612 unsigned k
, len
, len2
;
2615 assert(percent
<= 100);
2616 assert(new_length
>= 3);
2618 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2619 if (ascii_is_valid(s
))
2620 return ascii_ellipsize_mem(s
, old_length
, new_length
, percent
);
2622 if (old_length
<= 3 || old_length
<= new_length
)
2623 return strndup(s
, old_length
);
2625 x
= (new_length
* percent
) / 100;
2627 if (x
> new_length
- 3)
2631 for (i
= s
; k
< x
&& i
< s
+ old_length
; i
= utf8_next_char(i
)) {
2634 c
= utf8_encoded_to_unichar(i
);
2637 k
+= unichar_iswide(c
) ? 2 : 1;
2640 if (k
> x
) /* last character was wide and went over quota */
2643 for (j
= s
+ old_length
; k
< new_length
&& j
> i
; ) {
2646 j
= utf8_prev_char(j
);
2647 c
= utf8_encoded_to_unichar(j
);
2650 k
+= unichar_iswide(c
) ? 2 : 1;
2654 /* we don't actually need to ellipsize */
2656 return memdup(s
, old_length
+ 1);
2658 /* make space for ellipsis */
2659 j
= utf8_next_char(j
);
2662 len2
= s
+ old_length
- j
;
2663 e
= new(char, len
+ 3 + len2
+ 1);
2668 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2669 old_length, new_length, x, len, len2, k);
2673 e
[len
] = 0xe2; /* tri-dot ellipsis: … */
2677 memcpy(e
+ len
+ 3, j
, len2
+ 1);
2682 char *ellipsize(const char *s
, size_t length
, unsigned percent
) {
2683 return ellipsize_mem(s
, strlen(s
), length
, percent
);
2686 int touch_file(const char *path
, bool parents
, usec_t stamp
, uid_t uid
, gid_t gid
, mode_t mode
) {
2687 _cleanup_close_
int fd
;
2693 mkdir_parents(path
, 0755);
2695 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, mode
> 0 ? mode
: 0644);
2700 r
= fchmod(fd
, mode
);
2705 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
) {
2706 r
= fchown(fd
, uid
, gid
);
2711 if (stamp
!= USEC_INFINITY
) {
2712 struct timespec ts
[2];
2714 timespec_store(&ts
[0], stamp
);
2716 r
= futimens(fd
, ts
);
2718 r
= futimens(fd
, NULL
);
2725 int touch(const char *path
) {
2726 return touch_file(path
, false, USEC_INFINITY
, UID_INVALID
, GID_INVALID
, 0);
2729 static char *unquote(const char *s
, const char* quotes
) {
2733 /* This is rather stupid, simply removes the heading and
2734 * trailing quotes if there is one. Doesn't care about
2735 * escaping or anything.
2737 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2743 if (strchr(quotes
, s
[0]) && s
[l
-1] == s
[0])
2744 return strndup(s
+1, l
-2);
2749 noreturn
void freeze(void) {
2751 /* Make sure nobody waits for us on a socket anymore */
2752 close_all_fds(NULL
, 0);
2760 bool null_or_empty(struct stat
*st
) {
2763 if (S_ISREG(st
->st_mode
) && st
->st_size
<= 0)
2766 if (S_ISCHR(st
->st_mode
) || S_ISBLK(st
->st_mode
))
2772 int null_or_empty_path(const char *fn
) {
2777 if (stat(fn
, &st
) < 0)
2780 return null_or_empty(&st
);
2783 int null_or_empty_fd(int fd
) {
2788 if (fstat(fd
, &st
) < 0)
2791 return null_or_empty(&st
);
2794 DIR *xopendirat(int fd
, const char *name
, int flags
) {
2798 assert(!(flags
& O_CREAT
));
2800 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
2813 static char *tag_to_udev_node(const char *tagvalue
, const char *by
) {
2814 _cleanup_free_
char *t
= NULL
, *u
= NULL
;
2817 u
= unquote(tagvalue
, QUOTES
);
2821 enc_len
= strlen(u
) * 4 + 1;
2822 t
= new(char, enc_len
);
2826 if (encode_devnode_name(u
, t
, enc_len
) < 0)
2829 return strjoin("/dev/disk/by-", by
, "/", t
, NULL
);
2832 char *fstab_node_to_udev_node(const char *p
) {
2835 if (startswith(p
, "LABEL="))
2836 return tag_to_udev_node(p
+6, "label");
2838 if (startswith(p
, "UUID="))
2839 return tag_to_udev_node(p
+5, "uuid");
2841 if (startswith(p
, "PARTUUID="))
2842 return tag_to_udev_node(p
+9, "partuuid");
2844 if (startswith(p
, "PARTLABEL="))
2845 return tag_to_udev_node(p
+10, "partlabel");
2850 bool dirent_is_file(const struct dirent
*de
) {
2853 if (hidden_file(de
->d_name
))
2856 if (de
->d_type
!= DT_REG
&&
2857 de
->d_type
!= DT_LNK
&&
2858 de
->d_type
!= DT_UNKNOWN
)
2864 bool dirent_is_file_with_suffix(const struct dirent
*de
, const char *suffix
) {
2867 if (de
->d_type
!= DT_REG
&&
2868 de
->d_type
!= DT_LNK
&&
2869 de
->d_type
!= DT_UNKNOWN
)
2872 if (hidden_file_allow_backup(de
->d_name
))
2875 return endswith(de
->d_name
, suffix
);
2878 static int do_execute(char **directories
, usec_t timeout
, char *argv
[]) {
2879 _cleanup_hashmap_free_free_ Hashmap
*pids
= NULL
;
2880 _cleanup_set_free_free_ Set
*seen
= NULL
;
2883 /* We fork this all off from a child process so that we can
2884 * somewhat cleanly make use of SIGALRM to set a time limit */
2886 (void) reset_all_signal_handlers();
2887 (void) reset_signal_mask();
2889 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
2891 pids
= hashmap_new(NULL
);
2895 seen
= set_new(&string_hash_ops
);
2899 STRV_FOREACH(directory
, directories
) {
2900 _cleanup_closedir_
DIR *d
;
2903 d
= opendir(*directory
);
2905 if (errno
== ENOENT
)
2908 return log_error_errno(errno
, "Failed to open directory %s: %m", *directory
);
2911 FOREACH_DIRENT(de
, d
, break) {
2912 _cleanup_free_
char *path
= NULL
;
2916 if (!dirent_is_file(de
))
2919 if (set_contains(seen
, de
->d_name
)) {
2920 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory
, de
->d_name
);
2924 r
= set_put_strdup(seen
, de
->d_name
);
2928 path
= strjoin(*directory
, "/", de
->d_name
, NULL
);
2932 if (null_or_empty_path(path
)) {
2933 log_debug("%s is empty (a mask).", path
);
2939 log_error_errno(errno
, "Failed to fork: %m");
2941 } else if (pid
== 0) {
2944 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
2954 return log_error_errno(errno
, "Failed to execute %s: %m", path
);
2957 log_debug("Spawned %s as " PID_FMT
".", path
, pid
);
2959 r
= hashmap_put(pids
, UINT_TO_PTR(pid
), path
);
2966 /* Abort execution of this process after the timout. We simply
2967 * rely on SIGALRM as default action terminating the process,
2968 * and turn on alarm(). */
2970 if (timeout
!= USEC_INFINITY
)
2971 alarm((timeout
+ USEC_PER_SEC
- 1) / USEC_PER_SEC
);
2973 while (!hashmap_isempty(pids
)) {
2974 _cleanup_free_
char *path
= NULL
;
2977 pid
= PTR_TO_UINT(hashmap_first_key(pids
));
2980 path
= hashmap_remove(pids
, UINT_TO_PTR(pid
));
2983 wait_for_terminate_and_warn(path
, pid
, true);
2989 void execute_directories(const char* const* directories
, usec_t timeout
, char *argv
[]) {
2993 char **dirs
= (char**) directories
;
2995 assert(!strv_isempty(dirs
));
2997 name
= basename(dirs
[0]);
2998 assert(!isempty(name
));
3000 /* Executes all binaries in the directories in parallel and waits
3001 * for them to finish. Optionally a timeout is applied. If a file
3002 * with the same name exists in more than one directory, the
3003 * earliest one wins. */
3005 executor_pid
= fork();
3006 if (executor_pid
< 0) {
3007 log_error_errno(errno
, "Failed to fork: %m");
3010 } else if (executor_pid
== 0) {
3011 r
= do_execute(dirs
, timeout
, argv
);
3012 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
3015 wait_for_terminate_and_warn(name
, executor_pid
, true);
3018 bool nulstr_contains(const char*nulstr
, const char *needle
) {
3024 NULSTR_FOREACH(i
, nulstr
)
3025 if (streq(i
, needle
))
3031 bool plymouth_running(void) {
3032 return access("/run/plymouth/pid", F_OK
) >= 0;
3035 char* strshorten(char *s
, size_t l
) {
3044 int pipe_eof(int fd
) {
3045 struct pollfd pollfd
= {
3047 .events
= POLLIN
|POLLHUP
,
3052 r
= poll(&pollfd
, 1, 0);
3059 return pollfd
.revents
& POLLHUP
;
3062 int fd_wait_for_event(int fd
, int event
, usec_t t
) {
3064 struct pollfd pollfd
= {
3072 r
= ppoll(&pollfd
, 1, t
== USEC_INFINITY
? NULL
: timespec_store(&ts
, t
), NULL
);
3079 return pollfd
.revents
;
3082 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
3091 r
= tempfn_xxxxxx(path
, NULL
, &t
);
3095 fd
= mkostemp_safe(t
, O_WRONLY
|O_CLOEXEC
);
3101 f
= fdopen(fd
, "we");
3115 int symlink_atomic(const char *from
, const char *to
) {
3116 _cleanup_free_
char *t
= NULL
;
3122 r
= tempfn_random(to
, NULL
, &t
);
3126 if (symlink(from
, t
) < 0)
3129 if (rename(t
, to
) < 0) {
3137 int symlink_idempotent(const char *from
, const char *to
) {
3138 _cleanup_free_
char *p
= NULL
;
3144 if (symlink(from
, to
) < 0) {
3145 if (errno
!= EEXIST
)
3148 r
= readlink_malloc(to
, &p
);
3152 if (!streq(p
, from
))
3159 int mknod_atomic(const char *path
, mode_t mode
, dev_t dev
) {
3160 _cleanup_free_
char *t
= NULL
;
3165 r
= tempfn_random(path
, NULL
, &t
);
3169 if (mknod(t
, mode
, dev
) < 0)
3172 if (rename(t
, path
) < 0) {
3180 int mkfifo_atomic(const char *path
, mode_t mode
) {
3181 _cleanup_free_
char *t
= NULL
;
3186 r
= tempfn_random(path
, NULL
, &t
);
3190 if (mkfifo(t
, mode
) < 0)
3193 if (rename(t
, path
) < 0) {
3201 bool display_is_local(const char *display
) {
3205 display
[0] == ':' &&
3206 display
[1] >= '0' &&
3210 int socket_from_display(const char *display
, char **path
) {
3217 if (!display_is_local(display
))
3220 k
= strspn(display
+1, "0123456789");
3222 f
= new(char, strlen("/tmp/.X11-unix/X") + k
+ 1);
3226 c
= stpcpy(f
, "/tmp/.X11-unix/X");
3227 memcpy(c
, display
+1, k
);
3236 const char **username
,
3237 uid_t
*uid
, gid_t
*gid
,
3239 const char **shell
) {
3247 /* We enforce some special rules for uid=0: in order to avoid
3248 * NSS lookups for root we hardcode its data. */
3250 if (streq(*username
, "root") || streq(*username
, "0")) {
3268 if (parse_uid(*username
, &u
) >= 0) {
3272 /* If there are multiple users with the same id, make
3273 * sure to leave $USER to the configured value instead
3274 * of the first occurrence in the database. However if
3275 * the uid was configured by a numeric uid, then let's
3276 * pick the real username from /etc/passwd. */
3278 *username
= p
->pw_name
;
3281 p
= getpwnam(*username
);
3285 return errno
> 0 ? -errno
: -ESRCH
;
3297 *shell
= p
->pw_shell
;
3302 char* uid_to_name(uid_t uid
) {
3307 return strdup("root");
3311 return strdup(p
->pw_name
);
3313 if (asprintf(&r
, UID_FMT
, uid
) < 0)
3319 char* gid_to_name(gid_t gid
) {
3324 return strdup("root");
3328 return strdup(p
->gr_name
);
3330 if (asprintf(&r
, GID_FMT
, gid
) < 0)
3336 int get_group_creds(const char **groupname
, gid_t
*gid
) {
3342 /* We enforce some special rules for gid=0: in order to avoid
3343 * NSS lookups for root we hardcode its data. */
3345 if (streq(*groupname
, "root") || streq(*groupname
, "0")) {
3346 *groupname
= "root";
3354 if (parse_gid(*groupname
, &id
) >= 0) {
3359 *groupname
= g
->gr_name
;
3362 g
= getgrnam(*groupname
);
3366 return errno
> 0 ? -errno
: -ESRCH
;
3374 int in_gid(gid_t gid
) {
3376 int ngroups_max
, r
, i
;
3378 if (getgid() == gid
)
3381 if (getegid() == gid
)
3384 ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
3385 assert(ngroups_max
> 0);
3387 gids
= alloca(sizeof(gid_t
) * ngroups_max
);
3389 r
= getgroups(ngroups_max
, gids
);
3393 for (i
= 0; i
< r
; i
++)
3400 int in_group(const char *name
) {
3404 r
= get_group_creds(&name
, &gid
);
3411 int glob_exists(const char *path
) {
3412 _cleanup_globfree_ glob_t g
= {};
3418 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
3420 if (k
== GLOB_NOMATCH
)
3422 else if (k
== GLOB_NOSPACE
)
3425 return !strv_isempty(g
.gl_pathv
);
3427 return errno
? -errno
: -EIO
;
3430 int glob_extend(char ***strv
, const char *path
) {
3431 _cleanup_globfree_ glob_t g
= {};
3436 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
3438 if (k
== GLOB_NOMATCH
)
3440 else if (k
== GLOB_NOSPACE
)
3442 else if (k
!= 0 || strv_isempty(g
.gl_pathv
))
3443 return errno
? -errno
: -EIO
;
3445 STRV_FOREACH(p
, g
.gl_pathv
) {
3446 k
= strv_extend(strv
, *p
);
3454 int dirent_ensure_type(DIR *d
, struct dirent
*de
) {
3460 if (de
->d_type
!= DT_UNKNOWN
)
3463 if (fstatat(dirfd(d
), de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
3467 S_ISREG(st
.st_mode
) ? DT_REG
:
3468 S_ISDIR(st
.st_mode
) ? DT_DIR
:
3469 S_ISLNK(st
.st_mode
) ? DT_LNK
:
3470 S_ISFIFO(st
.st_mode
) ? DT_FIFO
:
3471 S_ISSOCK(st
.st_mode
) ? DT_SOCK
:
3472 S_ISCHR(st
.st_mode
) ? DT_CHR
:
3473 S_ISBLK(st
.st_mode
) ? DT_BLK
:
3479 int get_files_in_directory(const char *path
, char ***list
) {
3480 _cleanup_closedir_
DIR *d
= NULL
;
3481 size_t bufsize
= 0, n
= 0;
3482 _cleanup_strv_free_
char **l
= NULL
;
3486 /* Returns all files in a directory in *list, and the number
3487 * of files as return value. If list is NULL returns only the
3499 if (!de
&& errno
!= 0)
3504 dirent_ensure_type(d
, de
);
3506 if (!dirent_is_file(de
))
3510 /* one extra slot is needed for the terminating NULL */
3511 if (!GREEDY_REALLOC(l
, bufsize
, n
+ 2))
3514 l
[n
] = strdup(de
->d_name
);
3525 l
= NULL
; /* avoid freeing */
3531 char *strjoin(const char *x
, ...) {
3545 t
= va_arg(ap
, const char *);
3550 if (n
> ((size_t) -1) - l
) {
3574 t
= va_arg(ap
, const char *);
3588 bool is_main_thread(void) {
3589 static thread_local
int cached
= 0;
3591 if (_unlikely_(cached
== 0))
3592 cached
= getpid() == gettid() ? 1 : -1;
3597 int block_get_whole_disk(dev_t d
, dev_t
*ret
) {
3604 /* If it has a queue this is good enough for us */
3605 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", major(d
), minor(d
)) < 0)
3608 r
= access(p
, F_OK
);
3616 /* If it is a partition find the originating device */
3617 if (asprintf(&p
, "/sys/dev/block/%u:%u/partition", major(d
), minor(d
)) < 0)
3620 r
= access(p
, F_OK
);
3626 /* Get parent dev_t */
3627 if (asprintf(&p
, "/sys/dev/block/%u:%u/../dev", major(d
), minor(d
)) < 0)
3630 r
= read_one_line_file(p
, &s
);
3636 r
= sscanf(s
, "%u:%u", &m
, &n
);
3642 /* Only return this if it is really good enough for us. */
3643 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", m
, n
) < 0)
3646 r
= access(p
, F_OK
);
3650 *ret
= makedev(m
, n
);
3657 static const char *const ioprio_class_table
[] = {
3658 [IOPRIO_CLASS_NONE
] = "none",
3659 [IOPRIO_CLASS_RT
] = "realtime",
3660 [IOPRIO_CLASS_BE
] = "best-effort",
3661 [IOPRIO_CLASS_IDLE
] = "idle"
3664 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, INT_MAX
);
3666 static const char *const sigchld_code_table
[] = {
3667 [CLD_EXITED
] = "exited",
3668 [CLD_KILLED
] = "killed",
3669 [CLD_DUMPED
] = "dumped",
3670 [CLD_TRAPPED
] = "trapped",
3671 [CLD_STOPPED
] = "stopped",
3672 [CLD_CONTINUED
] = "continued",
3675 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
3677 static const char *const log_facility_unshifted_table
[LOG_NFACILITIES
] = {
3678 [LOG_FAC(LOG_KERN
)] = "kern",
3679 [LOG_FAC(LOG_USER
)] = "user",
3680 [LOG_FAC(LOG_MAIL
)] = "mail",
3681 [LOG_FAC(LOG_DAEMON
)] = "daemon",
3682 [LOG_FAC(LOG_AUTH
)] = "auth",
3683 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
3684 [LOG_FAC(LOG_LPR
)] = "lpr",
3685 [LOG_FAC(LOG_NEWS
)] = "news",
3686 [LOG_FAC(LOG_UUCP
)] = "uucp",
3687 [LOG_FAC(LOG_CRON
)] = "cron",
3688 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
3689 [LOG_FAC(LOG_FTP
)] = "ftp",
3690 [LOG_FAC(LOG_LOCAL0
)] = "local0",
3691 [LOG_FAC(LOG_LOCAL1
)] = "local1",
3692 [LOG_FAC(LOG_LOCAL2
)] = "local2",
3693 [LOG_FAC(LOG_LOCAL3
)] = "local3",
3694 [LOG_FAC(LOG_LOCAL4
)] = "local4",
3695 [LOG_FAC(LOG_LOCAL5
)] = "local5",
3696 [LOG_FAC(LOG_LOCAL6
)] = "local6",
3697 [LOG_FAC(LOG_LOCAL7
)] = "local7"
3700 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted
, int, LOG_FAC(~0));
3702 static const char *const log_level_table
[] = {
3703 [LOG_EMERG
] = "emerg",
3704 [LOG_ALERT
] = "alert",
3705 [LOG_CRIT
] = "crit",
3707 [LOG_WARNING
] = "warning",
3708 [LOG_NOTICE
] = "notice",
3709 [LOG_INFO
] = "info",
3710 [LOG_DEBUG
] = "debug"
3713 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level
, int, LOG_DEBUG
);
3715 static const char* const sched_policy_table
[] = {
3716 [SCHED_OTHER
] = "other",
3717 [SCHED_BATCH
] = "batch",
3718 [SCHED_IDLE
] = "idle",
3719 [SCHED_FIFO
] = "fifo",
3723 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);
3725 static const char* const rlimit_table
[_RLIMIT_MAX
] = {
3726 [RLIMIT_CPU
] = "LimitCPU",
3727 [RLIMIT_FSIZE
] = "LimitFSIZE",
3728 [RLIMIT_DATA
] = "LimitDATA",
3729 [RLIMIT_STACK
] = "LimitSTACK",
3730 [RLIMIT_CORE
] = "LimitCORE",
3731 [RLIMIT_RSS
] = "LimitRSS",
3732 [RLIMIT_NOFILE
] = "LimitNOFILE",
3733 [RLIMIT_AS
] = "LimitAS",
3734 [RLIMIT_NPROC
] = "LimitNPROC",
3735 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
3736 [RLIMIT_LOCKS
] = "LimitLOCKS",
3737 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
3738 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
3739 [RLIMIT_NICE
] = "LimitNICE",
3740 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
3741 [RLIMIT_RTTIME
] = "LimitRTTIME"
3744 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
3746 static const char* const ip_tos_table
[] = {
3747 [IPTOS_LOWDELAY
] = "low-delay",
3748 [IPTOS_THROUGHPUT
] = "throughput",
3749 [IPTOS_RELIABILITY
] = "reliability",
3750 [IPTOS_LOWCOST
] = "low-cost",
3753 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
3755 bool kexec_loaded(void) {
3756 bool loaded
= false;
3759 if (read_one_line_file("/sys/kernel/kexec_loaded", &s
) >= 0) {
3767 int prot_from_flags(int flags
) {
3769 switch (flags
& O_ACCMODE
) {
3778 return PROT_READ
|PROT_WRITE
;
3785 char *format_bytes(char *buf
, size_t l
, uint64_t t
) {
3788 static const struct {
3792 { "E", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3793 { "P", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3794 { "T", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3795 { "G", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3796 { "M", UINT64_C(1024)*UINT64_C(1024) },
3797 { "K", UINT64_C(1024) },
3800 if (t
== (uint64_t) -1)
3803 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
3805 if (t
>= table
[i
].factor
) {
3807 "%" PRIu64
".%" PRIu64
"%s",
3808 t
/ table
[i
].factor
,
3809 ((t
*UINT64_C(10)) / table
[i
].factor
) % UINT64_C(10),
3816 snprintf(buf
, l
, "%" PRIu64
"B", t
);
3824 void* memdup(const void *p
, size_t l
) {
3837 int fd_inc_sndbuf(int fd
, size_t n
) {
3839 socklen_t l
= sizeof(value
);
3841 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
3842 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
3845 /* If we have the privileges we will ignore the kernel limit. */
3848 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
3849 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
3855 int fd_inc_rcvbuf(int fd
, size_t n
) {
3857 socklen_t l
= sizeof(value
);
3859 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
3860 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
3863 /* If we have the privileges we will ignore the kernel limit. */
3866 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
3867 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
3872 int fork_agent(pid_t
*pid
, const int except
[], unsigned n_except
, const char *path
, ...) {
3873 bool stdout_is_tty
, stderr_is_tty
;
3874 pid_t parent_pid
, agent_pid
;
3875 sigset_t ss
, saved_ss
;
3883 /* Spawns a temporary TTY agent, making sure it goes away when
3886 parent_pid
= getpid();
3888 /* First we temporarily block all signals, so that the new
3889 * child has them blocked initially. This way, we can be sure
3890 * that SIGTERMs are not lost we might send to the agent. */
3891 assert_se(sigfillset(&ss
) >= 0);
3892 assert_se(sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) >= 0);
3895 if (agent_pid
< 0) {
3896 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
3900 if (agent_pid
!= 0) {
3901 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
3908 * Make sure the agent goes away when the parent dies */
3909 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
3910 _exit(EXIT_FAILURE
);
3912 /* Make sure we actually can kill the agent, if we need to, in
3913 * case somebody invoked us from a shell script that trapped
3914 * SIGTERM or so... */
3915 (void) reset_all_signal_handlers();
3916 (void) reset_signal_mask();
3918 /* Check whether our parent died before we were able
3919 * to set the death signal and unblock the signals */
3920 if (getppid() != parent_pid
)
3921 _exit(EXIT_SUCCESS
);
3923 /* Don't leak fds to the agent */
3924 close_all_fds(except
, n_except
);
3926 stdout_is_tty
= isatty(STDOUT_FILENO
);
3927 stderr_is_tty
= isatty(STDERR_FILENO
);
3929 if (!stdout_is_tty
|| !stderr_is_tty
) {
3932 /* Detach from stdout/stderr. and reopen
3933 * /dev/tty for them. This is important to
3934 * ensure that when systemctl is started via
3935 * popen() or a similar call that expects to
3936 * read EOF we actually do generate EOF and
3937 * not delay this indefinitely by because we
3938 * keep an unused copy of stdin around. */
3939 fd
= open("/dev/tty", O_WRONLY
);
3941 log_error_errno(errno
, "Failed to open /dev/tty: %m");
3942 _exit(EXIT_FAILURE
);
3946 dup2(fd
, STDOUT_FILENO
);
3949 dup2(fd
, STDERR_FILENO
);
3955 /* Count arguments */
3957 for (n
= 0; va_arg(ap
, char*); n
++)
3962 l
= alloca(sizeof(char *) * (n
+ 1));
3964 /* Fill in arguments */
3966 for (i
= 0; i
<= n
; i
++)
3967 l
[i
] = va_arg(ap
, char*);
3971 _exit(EXIT_FAILURE
);
3974 int setrlimit_closest(int resource
, const struct rlimit
*rlim
) {
3975 struct rlimit highest
, fixed
;
3979 if (setrlimit(resource
, rlim
) >= 0)
3985 /* So we failed to set the desired setrlimit, then let's try
3986 * to get as close as we can */
3987 assert_se(getrlimit(resource
, &highest
) == 0);
3989 fixed
.rlim_cur
= MIN(rlim
->rlim_cur
, highest
.rlim_max
);
3990 fixed
.rlim_max
= MIN(rlim
->rlim_max
, highest
.rlim_max
);
3992 if (setrlimit(resource
, &fixed
) < 0)
3998 bool http_etag_is_valid(const char *etag
) {
4002 if (!endswith(etag
, "\""))
4005 if (!startswith(etag
, "\"") && !startswith(etag
, "W/\""))
4011 bool http_url_is_valid(const char *url
) {
4017 p
= startswith(url
, "http://");
4019 p
= startswith(url
, "https://");
4026 return ascii_is_valid(p
);
4029 bool documentation_url_is_valid(const char *url
) {
4035 if (http_url_is_valid(url
))
4038 p
= startswith(url
, "file:/");
4040 p
= startswith(url
, "info:");
4042 p
= startswith(url
, "man:");
4047 return ascii_is_valid(p
);
4050 bool in_initrd(void) {
4051 static int saved
= -1;
4057 /* We make two checks here:
4059 * 1. the flag file /etc/initrd-release must exist
4060 * 2. the root file system must be a memory file system
4062 * The second check is extra paranoia, since misdetecting an
4063 * initrd can have bad bad consequences due the initrd
4064 * emptying when transititioning to the main systemd.
4067 saved
= access("/etc/initrd-release", F_OK
) >= 0 &&
4068 statfs("/", &s
) >= 0 &&
4069 is_temporary_fs(&s
);
4074 int get_home_dir(char **_h
) {
4082 /* Take the user specified one */
4083 e
= secure_getenv("HOME");
4084 if (e
&& path_is_absolute(e
)) {
4093 /* Hardcode home directory for root to avoid NSS */
4096 h
= strdup("/root");
4104 /* Check the database... */
4108 return errno
> 0 ? -errno
: -ESRCH
;
4110 if (!path_is_absolute(p
->pw_dir
))
4113 h
= strdup(p
->pw_dir
);
4121 int get_shell(char **_s
) {
4129 /* Take the user specified one */
4130 e
= getenv("SHELL");
4140 /* Hardcode home directory for root to avoid NSS */
4143 s
= strdup("/bin/sh");
4151 /* Check the database... */
4155 return errno
> 0 ? -errno
: -ESRCH
;
4157 if (!path_is_absolute(p
->pw_shell
))
4160 s
= strdup(p
->pw_shell
);
4168 bool filename_is_valid(const char *p
) {
4182 if (strlen(p
) > FILENAME_MAX
)
4188 bool string_is_safe(const char *p
) {
4194 for (t
= p
; *t
; t
++) {
4195 if (*t
> 0 && *t
< ' ')
4198 if (strchr("\\\"\'\x7f", *t
))
4206 * Check if a string contains control characters. If 'ok' is non-NULL
4207 * it may be a string containing additional CCs to be considered OK.
4209 bool string_has_cc(const char *p
, const char *ok
) {
4214 for (t
= p
; *t
; t
++) {
4215 if (ok
&& strchr(ok
, *t
))
4218 if (*t
> 0 && *t
< ' ')
4228 bool path_is_safe(const char *p
) {
4233 if (streq(p
, "..") || startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
4236 if (strlen(p
)+1 > PATH_MAX
)
4239 /* The following two checks are not really dangerous, but hey, they still are confusing */
4240 if (streq(p
, ".") || startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
4243 if (strstr(p
, "//"))
4249 /* hey glibc, APIs with callbacks without a user pointer are so useless */
4250 void *xbsearch_r(const void *key
, const void *base
, size_t nmemb
, size_t size
,
4251 int (*compar
) (const void *, const void *, void *), void *arg
) {
4260 p
= (void *)(((const char *) base
) + (idx
* size
));
4261 comparison
= compar(key
, p
, arg
);
4264 else if (comparison
> 0)
4272 void init_gettext(void) {
4273 setlocale(LC_ALL
, "");
4274 textdomain(GETTEXT_PACKAGE
);
4277 bool is_locale_utf8(void) {
4279 static int cached_answer
= -1;
4281 if (cached_answer
>= 0)
4284 if (!setlocale(LC_ALL
, "")) {
4285 cached_answer
= true;
4289 set
= nl_langinfo(CODESET
);
4291 cached_answer
= true;
4295 if (streq(set
, "UTF-8")) {
4296 cached_answer
= true;
4300 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
4301 * unset and everything can do to UTF-8 nowadays. */
4302 set
= setlocale(LC_CTYPE
, NULL
);
4304 cached_answer
= true;
4308 /* Check result, but ignore the result if C was set
4311 STR_IN_SET(set
, "C", "POSIX") &&
4312 !getenv("LC_ALL") &&
4313 !getenv("LC_CTYPE") &&
4317 return (bool) cached_answer
;
4320 const char *draw_special_char(DrawSpecialChar ch
) {
4321 static const char *draw_table
[2][_DRAW_SPECIAL_CHAR_MAX
] = {
4324 [DRAW_TREE_VERTICAL
] = "\342\224\202 ", /* │ */
4325 [DRAW_TREE_BRANCH
] = "\342\224\234\342\224\200", /* ├─ */
4326 [DRAW_TREE_RIGHT
] = "\342\224\224\342\224\200", /* └─ */
4327 [DRAW_TREE_SPACE
] = " ", /* */
4328 [DRAW_TRIANGULAR_BULLET
] = "\342\200\243", /* ‣ */
4329 [DRAW_BLACK_CIRCLE
] = "\342\227\217", /* ● */
4330 [DRAW_ARROW
] = "\342\206\222", /* → */
4331 [DRAW_DASH
] = "\342\200\223", /* – */
4334 /* ASCII fallback */ {
4335 [DRAW_TREE_VERTICAL
] = "| ",
4336 [DRAW_TREE_BRANCH
] = "|-",
4337 [DRAW_TREE_RIGHT
] = "`-",
4338 [DRAW_TREE_SPACE
] = " ",
4339 [DRAW_TRIANGULAR_BULLET
] = ">",
4340 [DRAW_BLACK_CIRCLE
] = "*",
4341 [DRAW_ARROW
] = "->",
4346 return draw_table
[!is_locale_utf8()][ch
];
4349 char *strreplace(const char *text
, const char *old_string
, const char *new_string
) {
4352 size_t l
, old_len
, new_len
;
4358 old_len
= strlen(old_string
);
4359 new_len
= strlen(new_string
);
4372 if (!startswith(f
, old_string
)) {
4378 nl
= l
- old_len
+ new_len
;
4379 a
= realloc(r
, nl
+ 1);
4387 t
= stpcpy(t
, new_string
);
4399 char *strip_tab_ansi(char **ibuf
, size_t *_isz
) {
4400 const char *i
, *begin
= NULL
;
4405 } state
= STATE_OTHER
;
4407 size_t osz
= 0, isz
;
4413 /* Strips ANSI color and replaces TABs by 8 spaces */
4415 isz
= _isz
? *_isz
: strlen(*ibuf
);
4417 f
= open_memstream(&obuf
, &osz
);
4421 for (i
= *ibuf
; i
< *ibuf
+ isz
+ 1; i
++) {
4426 if (i
>= *ibuf
+ isz
) /* EOT */
4428 else if (*i
== '\x1B')
4429 state
= STATE_ESCAPE
;
4430 else if (*i
== '\t')
4437 if (i
>= *ibuf
+ isz
) { /* EOT */
4440 } else if (*i
== '[') {
4441 state
= STATE_BRACKET
;
4446 state
= STATE_OTHER
;
4453 if (i
>= *ibuf
+ isz
|| /* EOT */
4454 (!(*i
>= '0' && *i
<= '9') && *i
!= ';' && *i
!= 'm')) {
4457 state
= STATE_OTHER
;
4459 } else if (*i
== 'm')
4460 state
= STATE_OTHER
;
4482 int on_ac_power(void) {
4483 bool found_offline
= false, found_online
= false;
4484 _cleanup_closedir_
DIR *d
= NULL
;
4486 d
= opendir("/sys/class/power_supply");
4488 return errno
== ENOENT
? true : -errno
;
4492 _cleanup_close_
int fd
= -1, device
= -1;
4498 if (!de
&& errno
!= 0)
4504 if (hidden_file(de
->d_name
))
4507 device
= openat(dirfd(d
), de
->d_name
, O_DIRECTORY
|O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4509 if (errno
== ENOENT
|| errno
== ENOTDIR
)
4515 fd
= openat(device
, "type", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4517 if (errno
== ENOENT
)
4523 n
= read(fd
, contents
, sizeof(contents
));
4527 if (n
!= 6 || memcmp(contents
, "Mains\n", 6))
4531 fd
= openat(device
, "online", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4533 if (errno
== ENOENT
)
4539 n
= read(fd
, contents
, sizeof(contents
));
4543 if (n
!= 2 || contents
[1] != '\n')
4546 if (contents
[0] == '1') {
4547 found_online
= true;
4549 } else if (contents
[0] == '0')
4550 found_offline
= true;
4555 return found_online
|| !found_offline
;
4558 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
4565 if (!path_strv_resolve_uniq(search
, root
))
4568 STRV_FOREACH(i
, search
) {
4569 _cleanup_free_
char *p
= NULL
;
4573 p
= strjoin(root
, *i
, "/", path
, NULL
);
4575 p
= strjoin(*i
, "/", path
, NULL
);
4585 if (errno
!= ENOENT
)
4592 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
4593 _cleanup_strv_free_
char **copy
= NULL
;
4599 if (path_is_absolute(path
)) {
4602 f
= fopen(path
, mode
);
4611 copy
= strv_copy((char**) search
);
4615 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
4618 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
4619 _cleanup_strv_free_
char **s
= NULL
;
4621 if (path_is_absolute(path
)) {
4624 f
= fopen(path
, mode
);
4633 s
= strv_split_nulstr(search
);
4637 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
4640 char *strextend(char **x
, ...) {
4647 l
= f
= *x
? strlen(*x
) : 0;
4654 t
= va_arg(ap
, const char *);
4659 if (n
> ((size_t) -1) - l
) {
4668 r
= realloc(*x
, l
+1);
4678 t
= va_arg(ap
, const char *);
4692 char *strrep(const char *s
, unsigned n
) {
4700 p
= r
= malloc(l
* n
+ 1);
4704 for (i
= 0; i
< n
; i
++)
4711 void* greedy_realloc(void **p
, size_t *allocated
, size_t need
, size_t size
) {
4718 if (*allocated
>= need
)
4721 newalloc
= MAX(need
* 2, 64u / size
);
4722 a
= newalloc
* size
;
4724 /* check for overflows */
4725 if (a
< size
* need
)
4733 *allocated
= newalloc
;
4737 void* greedy_realloc0(void **p
, size_t *allocated
, size_t need
, size_t size
) {
4746 q
= greedy_realloc(p
, allocated
, need
, size
);
4750 if (*allocated
> prev
)
4751 memzero(q
+ prev
* size
, (*allocated
- prev
) * size
);
4756 bool id128_is_valid(const char *s
) {
4762 /* Simple formatted 128bit hex string */
4764 for (i
= 0; i
< l
; i
++) {
4767 if (!(c
>= '0' && c
<= '9') &&
4768 !(c
>= 'a' && c
<= 'z') &&
4769 !(c
>= 'A' && c
<= 'Z'))
4773 } else if (l
== 36) {
4775 /* Formatted UUID */
4777 for (i
= 0; i
< l
; i
++) {
4780 if ((i
== 8 || i
== 13 || i
== 18 || i
== 23)) {
4784 if (!(c
>= '0' && c
<= '9') &&
4785 !(c
>= 'a' && c
<= 'z') &&
4786 !(c
>= 'A' && c
<= 'Z'))
4797 int split_pair(const char *s
, const char *sep
, char **l
, char **r
) {
4812 a
= strndup(s
, x
- s
);
4816 b
= strdup(x
+ strlen(sep
));
4828 int shall_restore_state(void) {
4829 _cleanup_free_
char *value
= NULL
;
4832 r
= get_proc_cmdline_key("systemd.restore_state=", &value
);
4838 return parse_boolean(value
) != 0;
4841 int proc_cmdline(char **ret
) {
4844 if (detect_container() > 0)
4845 return get_process_cmdline(1, 0, false, ret
);
4847 return read_one_line_file("/proc/cmdline", ret
);
4850 int parse_proc_cmdline(int (*parse_item
)(const char *key
, const char *value
)) {
4851 _cleanup_free_
char *line
= NULL
;
4857 r
= proc_cmdline(&line
);
4863 _cleanup_free_
char *word
= NULL
;
4866 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
4872 /* Filter out arguments that are intended only for the
4874 if (!in_initrd() && startswith(word
, "rd."))
4877 value
= strchr(word
, '=');
4881 r
= parse_item(word
, value
);
4889 int get_proc_cmdline_key(const char *key
, char **value
) {
4890 _cleanup_free_
char *line
= NULL
, *ret
= NULL
;
4897 r
= proc_cmdline(&line
);
4903 _cleanup_free_
char *word
= NULL
;
4906 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
4912 /* Filter out arguments that are intended only for the
4914 if (!in_initrd() && startswith(word
, "rd."))
4918 e
= startswith(word
, key
);
4922 r
= free_and_strdup(&ret
, e
);
4928 if (streq(word
, key
))
4942 int container_get_leader(const char *machine
, pid_t
*pid
) {
4943 _cleanup_free_
char *s
= NULL
, *class = NULL
;
4951 if (!machine_name_is_valid(machine
))
4954 p
= strjoina("/run/systemd/machines/", machine
);
4955 r
= parse_env_file(p
, NEWLINE
, "LEADER", &s
, "CLASS", &class, NULL
);
4963 if (!streq_ptr(class, "container"))
4966 r
= parse_pid(s
, &leader
);
4976 int namespace_open(pid_t pid
, int *pidns_fd
, int *mntns_fd
, int *netns_fd
, int *userns_fd
, int *root_fd
) {
4977 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, netnsfd
= -1, usernsfd
= -1;
4985 mntns
= procfs_file_alloca(pid
, "ns/mnt");
4986 mntnsfd
= open(mntns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
4994 pidns
= procfs_file_alloca(pid
, "ns/pid");
4995 pidnsfd
= open(pidns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5003 netns
= procfs_file_alloca(pid
, "ns/net");
5004 netnsfd
= open(netns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5012 userns
= procfs_file_alloca(pid
, "ns/user");
5013 usernsfd
= open(userns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5014 if (usernsfd
< 0 && errno
!= ENOENT
)
5021 root
= procfs_file_alloca(pid
, "root");
5022 rfd
= open(root
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
|O_DIRECTORY
);
5028 *pidns_fd
= pidnsfd
;
5031 *mntns_fd
= mntnsfd
;
5034 *netns_fd
= netnsfd
;
5037 *userns_fd
= usernsfd
;
5042 pidnsfd
= mntnsfd
= netnsfd
= usernsfd
= -1;
5047 int namespace_enter(int pidns_fd
, int mntns_fd
, int netns_fd
, int userns_fd
, int root_fd
) {
5048 if (userns_fd
>= 0) {
5049 /* Can't setns to your own userns, since then you could
5050 * escalate from non-root to root in your own namespace, so
5051 * check if namespaces equal before attempting to enter. */
5052 _cleanup_free_
char *userns_fd_path
= NULL
;
5054 if (asprintf(&userns_fd_path
, "/proc/self/fd/%d", userns_fd
) < 0)
5057 r
= files_same(userns_fd_path
, "/proc/self/ns/user");
5065 if (setns(pidns_fd
, CLONE_NEWPID
) < 0)
5069 if (setns(mntns_fd
, CLONE_NEWNS
) < 0)
5073 if (setns(netns_fd
, CLONE_NEWNET
) < 0)
5077 if (setns(userns_fd
, CLONE_NEWUSER
) < 0)
5081 if (fchdir(root_fd
) < 0)
5084 if (chroot(".") < 0)
5088 return reset_uid_gid();
5091 int getpeercred(int fd
, struct ucred
*ucred
) {
5092 socklen_t n
= sizeof(struct ucred
);
5099 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
);
5103 if (n
!= sizeof(struct ucred
))
5106 /* Check if the data is actually useful and not suppressed due
5107 * to namespacing issues */
5110 if (u
.uid
== UID_INVALID
)
5112 if (u
.gid
== GID_INVALID
)
5119 int getpeersec(int fd
, char **ret
) {
5131 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
5135 if (errno
!= ERANGE
)
5142 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
5158 /* This is much like like mkostemp() but is subject to umask(). */
5159 int mkostemp_safe(char *pattern
, int flags
) {
5160 _cleanup_umask_ mode_t u
;
5167 fd
= mkostemp(pattern
, flags
);
5174 int open_tmpfile(const char *path
, int flags
) {
5181 /* Try O_TMPFILE first, if it is supported */
5182 fd
= open(path
, flags
|O_TMPFILE
|O_EXCL
, S_IRUSR
|S_IWUSR
);
5187 /* Fall back to unguessable name + unlinking */
5188 p
= strjoina(path
, "/systemd-tmp-XXXXXX");
5190 fd
= mkostemp_safe(p
, flags
);
5198 int fd_warn_permissions(const char *path
, int fd
) {
5201 if (fstat(fd
, &st
) < 0)
5204 if (st
.st_mode
& 0111)
5205 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path
);
5207 if (st
.st_mode
& 0002)
5208 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path
);
5210 if (getpid() == 1 && (st
.st_mode
& 0044) != 0044)
5211 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
);
5216 unsigned long personality_from_string(const char *p
) {
5218 /* Parse a personality specifier. We introduce our own
5219 * identifiers that indicate specific ABIs, rather than just
5220 * hints regarding the register size, since we want to keep
5221 * things open for multiple locally supported ABIs for the
5222 * same register size. We try to reuse the ABI identifiers
5223 * used by libseccomp. */
5225 #if defined(__x86_64__)
5227 if (streq(p
, "x86"))
5230 if (streq(p
, "x86-64"))
5233 #elif defined(__i386__)
5235 if (streq(p
, "x86"))
5238 #elif defined(__s390x__)
5240 if (streq(p
, "s390"))
5243 if (streq(p
, "s390x"))
5246 #elif defined(__s390__)
5248 if (streq(p
, "s390"))
5252 return PERSONALITY_INVALID
;
5255 const char* personality_to_string(unsigned long p
) {
5257 #if defined(__x86_64__)
5259 if (p
== PER_LINUX32
)
5265 #elif defined(__i386__)
5270 #elif defined(__s390x__)
5275 if (p
== PER_LINUX32
)
5278 #elif defined(__s390__)
5288 uint64_t physical_memory(void) {
5291 /* We return this as uint64_t in case we are running as 32bit
5292 * process on a 64bit kernel with huge amounts of memory */
5294 mem
= sysconf(_SC_PHYS_PAGES
);
5297 return (uint64_t) mem
* (uint64_t) page_size();
5300 void hexdump(FILE *f
, const void *p
, size_t s
) {
5301 const uint8_t *b
= p
;
5304 assert(s
== 0 || b
);
5309 fprintf(f
, "%04x ", n
);
5311 for (i
= 0; i
< 16; i
++) {
5316 fprintf(f
, "%02x ", b
[i
]);
5324 for (i
= 0; i
< 16; i
++) {
5329 fputc(isprint(b
[i
]) ? (char) b
[i
] : '.', f
);
5343 int update_reboot_param_file(const char *param
) {
5347 r
= write_string_file(REBOOT_PARAM_FILE
, param
, WRITE_STRING_FILE_CREATE
);
5349 return log_error_errno(r
, "Failed to write reboot param to "REBOOT_PARAM_FILE
": %m");
5351 (void) unlink(REBOOT_PARAM_FILE
);
5356 int umount_recursive(const char *prefix
, int flags
) {
5360 /* Try to umount everything recursively below a
5361 * directory. Also, take care of stacked mounts, and keep
5362 * unmounting them until they are gone. */
5365 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
5370 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
5371 if (!proc_self_mountinfo
)
5375 _cleanup_free_
char *path
= NULL
, *p
= NULL
;
5378 k
= fscanf(proc_self_mountinfo
,
5379 "%*s " /* (1) mount id */
5380 "%*s " /* (2) parent id */
5381 "%*s " /* (3) major:minor */
5382 "%*s " /* (4) root */
5383 "%ms " /* (5) mount point */
5384 "%*s" /* (6) mount options */
5385 "%*[^-]" /* (7) optional fields */
5386 "- " /* (8) separator */
5387 "%*s " /* (9) file system type */
5388 "%*s" /* (10) mount source */
5389 "%*s" /* (11) mount options 2 */
5390 "%*[^\n]", /* some rubbish at the end */
5399 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
5403 if (!path_startswith(p
, prefix
))
5406 if (umount2(p
, flags
) < 0) {
5422 static int get_mount_flags(const char *path
, unsigned long *flags
) {
5425 if (statvfs(path
, &buf
) < 0)
5427 *flags
= buf
.f_flag
;
5431 int bind_remount_recursive(const char *prefix
, bool ro
) {
5432 _cleanup_set_free_free_ Set
*done
= NULL
;
5433 _cleanup_free_
char *cleaned
= NULL
;
5436 /* Recursively remount a directory (and all its submounts)
5437 * read-only or read-write. If the directory is already
5438 * mounted, we reuse the mount and simply mark it
5439 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
5440 * operation). If it isn't we first make it one. Afterwards we
5441 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
5442 * submounts we can access, too. When mounts are stacked on
5443 * the same mount point we only care for each individual
5444 * "top-level" mount on each point, as we cannot
5445 * influence/access the underlying mounts anyway. We do not
5446 * have any effect on future submounts that might get
5447 * propagated, they migt be writable. This includes future
5448 * submounts that have been triggered via autofs. */
5450 cleaned
= strdup(prefix
);
5454 path_kill_slashes(cleaned
);
5456 done
= set_new(&string_hash_ops
);
5461 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
5462 _cleanup_set_free_free_ Set
*todo
= NULL
;
5463 bool top_autofs
= false;
5465 unsigned long orig_flags
;
5467 todo
= set_new(&string_hash_ops
);
5471 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
5472 if (!proc_self_mountinfo
)
5476 _cleanup_free_
char *path
= NULL
, *p
= NULL
, *type
= NULL
;
5479 k
= fscanf(proc_self_mountinfo
,
5480 "%*s " /* (1) mount id */
5481 "%*s " /* (2) parent id */
5482 "%*s " /* (3) major:minor */
5483 "%*s " /* (4) root */
5484 "%ms " /* (5) mount point */
5485 "%*s" /* (6) mount options (superblock) */
5486 "%*[^-]" /* (7) optional fields */
5487 "- " /* (8) separator */
5488 "%ms " /* (9) file system type */
5489 "%*s" /* (10) mount source */
5490 "%*s" /* (11) mount options (bind mount) */
5491 "%*[^\n]", /* some rubbish at the end */
5501 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
5505 /* Let's ignore autofs mounts. If they aren't
5506 * triggered yet, we want to avoid triggering
5507 * them, as we don't make any guarantees for
5508 * future submounts anyway. If they are
5509 * already triggered, then we will find
5510 * another entry for this. */
5511 if (streq(type
, "autofs")) {
5512 top_autofs
= top_autofs
|| path_equal(cleaned
, p
);
5516 if (path_startswith(p
, cleaned
) &&
5517 !set_contains(done
, p
)) {
5519 r
= set_consume(todo
, p
);
5529 /* If we have no submounts to process anymore and if
5530 * the root is either already done, or an autofs, we
5532 if (set_isempty(todo
) &&
5533 (top_autofs
|| set_contains(done
, cleaned
)))
5536 if (!set_contains(done
, cleaned
) &&
5537 !set_contains(todo
, cleaned
)) {
5538 /* The prefix directory itself is not yet a
5539 * mount, make it one. */
5540 if (mount(cleaned
, cleaned
, NULL
, MS_BIND
|MS_REC
, NULL
) < 0)
5544 (void) get_mount_flags(cleaned
, &orig_flags
);
5545 orig_flags
&= ~MS_RDONLY
;
5547 if (mount(NULL
, prefix
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0)
5550 x
= strdup(cleaned
);
5554 r
= set_consume(done
, x
);
5559 while ((x
= set_steal_first(todo
))) {
5561 r
= set_consume(done
, x
);
5562 if (r
== -EEXIST
|| r
== 0)
5567 /* Try to reuse the original flag set, but
5568 * don't care for errors, in case of
5569 * obstructed mounts */
5571 (void) get_mount_flags(x
, &orig_flags
);
5572 orig_flags
&= ~MS_RDONLY
;
5574 if (mount(NULL
, x
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0) {
5576 /* Deal with mount points that are
5577 * obstructed by a later mount */
5579 if (errno
!= ENOENT
)
5587 int fflush_and_check(FILE *f
) {
5594 return errno
? -errno
: -EIO
;
5599 int tempfn_xxxxxx(const char *p
, const char *extra
, char **ret
) {
5611 * /foo/bar/.#<extra>waldoXXXXXX
5615 if (!filename_is_valid(fn
))
5621 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 6 + 1);
5625 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
), "XXXXXX");
5627 *ret
= path_kill_slashes(t
);
5631 int tempfn_random(const char *p
, const char *extra
, char **ret
) {
5645 * /foo/bar/.#<extra>waldobaa2a261115984a9
5649 if (!filename_is_valid(fn
))
5655 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 16 + 1);
5659 x
= stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
);
5662 for (i
= 0; i
< 16; i
++) {
5663 *(x
++) = hexchar(u
& 0xF);
5669 *ret
= path_kill_slashes(t
);
5673 int tempfn_random_child(const char *p
, const char *extra
, char **ret
) {
5684 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
5690 t
= new(char, strlen(p
) + 3 + strlen(extra
) + 16 + 1);
5694 x
= stpcpy(stpcpy(stpcpy(t
, p
), "/.#"), extra
);
5697 for (i
= 0; i
< 16; i
++) {
5698 *(x
++) = hexchar(u
& 0xF);
5704 *ret
= path_kill_slashes(t
);
5708 int take_password_lock(const char *root
) {
5710 struct flock flock
= {
5712 .l_whence
= SEEK_SET
,
5720 /* This is roughly the same as lckpwdf(), but not as awful. We
5721 * don't want to use alarm() and signals, hence we implement
5722 * our own trivial version of this.
5724 * Note that shadow-utils also takes per-database locks in
5725 * addition to lckpwdf(). However, we don't given that they
5726 * are redundant as they they invoke lckpwdf() first and keep
5727 * it during everything they do. The per-database locks are
5728 * awfully racy, and thus we just won't do them. */
5731 path
= strjoina(root
, "/etc/.pwd.lock");
5733 path
= "/etc/.pwd.lock";
5735 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
5739 r
= fcntl(fd
, F_SETLKW
, &flock
);
5748 int is_symlink(const char *path
) {
5751 if (lstat(path
, &info
) < 0)
5754 return !!S_ISLNK(info
.st_mode
);
5757 int is_dir(const char* path
, bool follow
) {
5762 r
= stat(path
, &st
);
5764 r
= lstat(path
, &st
);
5768 return !!S_ISDIR(st
.st_mode
);
5771 int is_device_node(const char *path
) {
5774 if (lstat(path
, &info
) < 0)
5777 return !!(S_ISBLK(info
.st_mode
) || S_ISCHR(info
.st_mode
));
5780 int extract_first_word(const char **p
, char **ret
, const char *separators
, ExtractFlags flags
) {
5781 _cleanup_free_
char *s
= NULL
;
5782 size_t allocated
= 0, sz
= 0;
5790 SINGLE_QUOTE_ESCAPE
,
5792 DOUBLE_QUOTE_ESCAPE
,
5800 separators
= WHITESPACE
;
5802 /* Bail early if called after last value or with no input */
5804 goto finish_force_terminate
;
5806 /* Parses the first word of a string, and returns it in
5807 * *ret. Removes all quotes in the process. When parsing fails
5808 * (because of an uneven number of quotes or similar), leaves
5809 * the pointer *p at the first invalid character. */
5817 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
)
5818 if (!GREEDY_REALLOC(s
, allocated
, sz
+1))
5822 goto finish_force_terminate
;
5823 else if (strchr(separators
, c
)) {
5824 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
) {
5826 goto finish_force_next
;
5831 /* We found a non-blank character, so we will always
5832 * want to return a string (even if it is empty),
5833 * allocate it here. */
5834 if (!GREEDY_REALLOC(s
, allocated
, sz
+1))
5842 goto finish_force_terminate
;
5843 else if (c
== '\'' && (flags
& EXTRACT_QUOTES
))
5844 state
= SINGLE_QUOTE
;
5846 state
= VALUE_ESCAPE
;
5847 else if (c
== '\"' && (flags
& EXTRACT_QUOTES
))
5848 state
= DOUBLE_QUOTE
;
5849 else if (strchr(separators
, c
)) {
5850 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
) {
5852 goto finish_force_next
;
5856 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5866 if (flags
& EXTRACT_RELAX
)
5867 goto finish_force_terminate
;
5869 } else if (c
== '\'')
5872 state
= SINGLE_QUOTE_ESCAPE
;
5874 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5888 state
= DOUBLE_QUOTE_ESCAPE
;
5890 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5898 case SINGLE_QUOTE_ESCAPE
:
5899 case DOUBLE_QUOTE_ESCAPE
:
5901 if (!GREEDY_REALLOC(s
, allocated
, sz
+7))
5905 if ((flags
& EXTRACT_CUNESCAPE_RELAX
) &&
5906 (state
== VALUE_ESCAPE
|| flags
& EXTRACT_RELAX
)) {
5907 /* If we find an unquoted trailing backslash and we're in
5908 * EXTRACT_CUNESCAPE_RELAX mode, keep it verbatim in the
5911 * Unbalanced quotes will only be allowed in EXTRACT_RELAX
5912 * mode, EXTRACT_CUNESCAPE_RELAX mode does not allow them.
5915 goto finish_force_terminate
;
5917 if (flags
& EXTRACT_RELAX
)
5918 goto finish_force_terminate
;
5922 if (flags
& EXTRACT_CUNESCAPE
) {
5925 r
= cunescape_one(*p
, (size_t) -1, &c
, &u
);
5927 if (flags
& EXTRACT_CUNESCAPE_RELAX
) {
5938 s
[sz
++] = c
; /* normal explicit char */
5940 sz
+= utf8_encode_unichar(s
+ sz
, u
); /* unicode chars we'll encode as utf8 */
5945 state
= (state
== SINGLE_QUOTE_ESCAPE
) ? SINGLE_QUOTE
:
5946 (state
== DOUBLE_QUOTE_ESCAPE
) ? DOUBLE_QUOTE
:
5952 goto finish_force_terminate
;
5953 if (!strchr(separators
, c
))
5961 finish_force_terminate
:
5978 int extract_first_word_and_warn(
5981 const char *separators
,
5984 const char *filename
,
5986 const char *rvalue
) {
5988 /* Try to unquote it, if it fails, warn about it and try again but this
5989 * time using EXTRACT_CUNESCAPE_RELAX to keep the backslashes verbatim
5990 * in invalid escape sequences. */
5995 r
= extract_first_word(p
, ret
, separators
, flags
);
5996 if (r
< 0 && !(flags
& EXTRACT_CUNESCAPE_RELAX
)) {
5998 /* Retry it with EXTRACT_CUNESCAPE_RELAX. */
6000 r
= extract_first_word(p
, ret
, separators
, flags
|EXTRACT_CUNESCAPE_RELAX
);
6002 log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Unbalanced quoting in command line, ignoring: \"%s\"", rvalue
);
6004 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0, "Invalid escape sequences in command line: \"%s\"", rvalue
);
6010 int extract_many_words(const char **p
, const char *separators
, ExtractFlags flags
, ...) {
6015 /* Parses a number of words from a string, stripping any
6016 * quotes if necessary. */
6020 /* Count how many words are expected */
6021 va_start(ap
, flags
);
6023 if (!va_arg(ap
, char **))
6032 /* Read all words into a temporary array */
6033 l
= newa0(char*, n
);
6034 for (c
= 0; c
< n
; c
++) {
6036 r
= extract_first_word(p
, &l
[c
], separators
, flags
);
6040 for (j
= 0; j
< c
; j
++)
6050 /* If we managed to parse all words, return them in the passed
6052 va_start(ap
, flags
);
6053 for (i
= 0; i
< n
; i
++) {
6056 v
= va_arg(ap
, char **);
6066 int free_and_strdup(char **p
, const char *s
) {
6071 /* Replaces a string pointer with an strdup()ed new string,
6072 * possibly freeing the old one. */
6074 if (streq_ptr(*p
, s
))
6090 int ptsname_malloc(int fd
, char **ret
) {
6103 if (ptsname_r(fd
, c
, l
) == 0) {
6107 if (errno
!= ERANGE
) {
6117 int openpt_in_namespace(pid_t pid
, int flags
) {
6118 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, usernsfd
= -1, rootfd
= -1;
6119 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
6126 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &usernsfd
, &rootfd
);
6130 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
6140 pair
[0] = safe_close(pair
[0]);
6142 r
= namespace_enter(pidnsfd
, mntnsfd
, -1, usernsfd
, rootfd
);
6144 _exit(EXIT_FAILURE
);
6146 master
= posix_openpt(flags
);
6148 _exit(EXIT_FAILURE
);
6150 if (unlockpt(master
) < 0)
6151 _exit(EXIT_FAILURE
);
6153 if (send_one_fd(pair
[1], master
, 0) < 0)
6154 _exit(EXIT_FAILURE
);
6156 _exit(EXIT_SUCCESS
);
6159 pair
[1] = safe_close(pair
[1]);
6161 r
= wait_for_terminate(child
, &si
);
6164 if (si
.si_code
!= CLD_EXITED
|| si
.si_status
!= EXIT_SUCCESS
)
6167 return receive_one_fd(pair
[0], 0);
6170 ssize_t
fgetxattrat_fake(int dirfd
, const char *filename
, const char *attribute
, void *value
, size_t size
, int flags
) {
6171 char fn
[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(int) + 1];
6172 _cleanup_close_
int fd
= -1;
6175 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
6177 fd
= openat(dirfd
, filename
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_PATH
|(flags
& AT_SYMLINK_NOFOLLOW
? O_NOFOLLOW
: 0));
6181 xsprintf(fn
, "/proc/self/fd/%i", fd
);
6183 l
= getxattr(fn
, attribute
, value
, size
);
6190 static int parse_crtime(le64_t le
, usec_t
*usec
) {
6196 if (u
== 0 || u
== (uint64_t) -1)
6203 int fd_getcrtime(int fd
, usec_t
*usec
) {
6210 /* Until Linux gets a real concept of birthtime/creation time,
6211 * let's fake one with xattrs */
6213 n
= fgetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
));
6216 if (n
!= sizeof(le
))
6219 return parse_crtime(le
, usec
);
6222 int fd_getcrtime_at(int dirfd
, const char *name
, usec_t
*usec
, int flags
) {
6226 n
= fgetxattrat_fake(dirfd
, name
, "user.crtime_usec", &le
, sizeof(le
), flags
);
6229 if (n
!= sizeof(le
))
6232 return parse_crtime(le
, usec
);
6235 int path_getcrtime(const char *p
, usec_t
*usec
) {
6242 n
= getxattr(p
, "user.crtime_usec", &le
, sizeof(le
));
6245 if (n
!= sizeof(le
))
6248 return parse_crtime(le
, usec
);
6251 int fd_setcrtime(int fd
, usec_t usec
) {
6257 usec
= now(CLOCK_REALTIME
);
6259 le
= htole64((uint64_t) usec
);
6260 if (fsetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
), 0) < 0)
6266 int same_fd(int a
, int b
) {
6267 struct stat sta
, stb
;
6274 /* Compares two file descriptors. Note that semantics are
6275 * quite different depending on whether we have kcmp() or we
6276 * don't. If we have kcmp() this will only return true for
6277 * dup()ed file descriptors, but not otherwise. If we don't
6278 * have kcmp() this will also return true for two fds of the same
6279 * file, created by separate open() calls. Since we use this
6280 * call mostly for filtering out duplicates in the fd store
6281 * this difference hopefully doesn't matter too much. */
6286 /* Try to use kcmp() if we have it. */
6288 r
= kcmp(pid
, pid
, KCMP_FILE
, a
, b
);
6293 if (errno
!= ENOSYS
)
6296 /* We don't have kcmp(), use fstat() instead. */
6297 if (fstat(a
, &sta
) < 0)
6300 if (fstat(b
, &stb
) < 0)
6303 if ((sta
.st_mode
& S_IFMT
) != (stb
.st_mode
& S_IFMT
))
6306 /* We consider all device fds different, since two device fds
6307 * might refer to quite different device contexts even though
6308 * they share the same inode and backing dev_t. */
6310 if (S_ISCHR(sta
.st_mode
) || S_ISBLK(sta
.st_mode
))
6313 if (sta
.st_dev
!= stb
.st_dev
|| sta
.st_ino
!= stb
.st_ino
)
6316 /* The fds refer to the same inode on disk, let's also check
6317 * if they have the same fd flags. This is useful to
6318 * distinguish the read and write side of a pipe created with
6320 fa
= fcntl(a
, F_GETFL
);
6324 fb
= fcntl(b
, F_GETFL
);
6331 int chattr_fd(int fd
, unsigned value
, unsigned mask
) {
6332 unsigned old_attr
, new_attr
;
6337 if (fstat(fd
, &st
) < 0)
6340 /* Explicitly check whether this is a regular file or
6341 * directory. If it is anything else (such as a device node or
6342 * fifo), then the ioctl will not hit the file systems but
6343 * possibly drivers, where the ioctl might have different
6344 * effects. Notably, DRM is using the same ioctl() number. */
6346 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
6352 if (ioctl(fd
, FS_IOC_GETFLAGS
, &old_attr
) < 0)
6355 new_attr
= (old_attr
& ~mask
) | (value
& mask
);
6356 if (new_attr
== old_attr
)
6359 if (ioctl(fd
, FS_IOC_SETFLAGS
, &new_attr
) < 0)
6365 int chattr_path(const char *p
, unsigned value
, unsigned mask
) {
6366 _cleanup_close_
int fd
= -1;
6373 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
6377 return chattr_fd(fd
, value
, mask
);
6380 int read_attr_fd(int fd
, unsigned *ret
) {
6385 if (fstat(fd
, &st
) < 0)
6388 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
6391 if (ioctl(fd
, FS_IOC_GETFLAGS
, ret
) < 0)
6397 int read_attr_path(const char *p
, unsigned *ret
) {
6398 _cleanup_close_
int fd
= -1;
6403 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
6407 return read_attr_fd(fd
, ret
);
6410 static size_t nul_length(const uint8_t *p
, size_t sz
) {
6425 ssize_t
sparse_write(int fd
, const void *p
, size_t sz
, size_t run_length
) {
6426 const uint8_t *q
, *w
, *e
;
6434 n
= nul_length(q
, e
- q
);
6436 /* If there are more than the specified run length of
6437 * NUL bytes, or if this is the beginning or the end
6438 * of the buffer, then seek instead of write */
6439 if ((n
> run_length
) ||
6440 (n
> 0 && q
== p
) ||
6441 (n
> 0 && q
+ n
>= e
)) {
6443 l
= write(fd
, w
, q
- w
);
6450 if (lseek(fd
, n
, SEEK_CUR
) == (off_t
) -1)
6462 l
= write(fd
, w
, q
- w
);
6469 return q
- (const uint8_t*) p
;
6472 void sigkill_wait(pid_t
*pid
) {
6478 if (kill(*pid
, SIGKILL
) > 0)
6479 (void) wait_for_terminate(*pid
, NULL
);
6482 int syslog_parse_priority(const char **p
, int *priority
, bool with_facility
) {
6483 int a
= 0, b
= 0, c
= 0;
6493 if (!strchr(*p
, '>'))
6496 if ((*p
)[2] == '>') {
6497 c
= undecchar((*p
)[1]);
6499 } else if ((*p
)[3] == '>') {
6500 b
= undecchar((*p
)[1]);
6501 c
= undecchar((*p
)[2]);
6503 } else if ((*p
)[4] == '>') {
6504 a
= undecchar((*p
)[1]);
6505 b
= undecchar((*p
)[2]);
6506 c
= undecchar((*p
)[3]);
6511 if (a
< 0 || b
< 0 || c
< 0 ||
6512 (!with_facility
&& (a
|| b
|| c
> 7)))
6516 *priority
= a
*100 + b
*10 + c
;
6518 *priority
= (*priority
& LOG_FACMASK
) | c
;
6524 ssize_t
string_table_lookup(const char * const *table
, size_t len
, const char *key
) {
6530 for (i
= 0; i
< len
; ++i
)
6531 if (streq_ptr(table
[i
], key
))
6537 void cmsg_close_all(struct msghdr
*mh
) {
6538 struct cmsghdr
*cmsg
;
6542 CMSG_FOREACH(cmsg
, mh
)
6543 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
)
6544 close_many((int*) CMSG_DATA(cmsg
), (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int));
6547 int rename_noreplace(int olddirfd
, const char *oldpath
, int newdirfd
, const char *newpath
) {
6551 ret
= renameat2(olddirfd
, oldpath
, newdirfd
, newpath
, RENAME_NOREPLACE
);
6555 /* renameat2() exists since Linux 3.15, btrfs added support for it later.
6556 * If it is not implemented, fallback to another method. */
6557 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
6560 /* The link()/unlink() fallback does not work on directories. But
6561 * renameat() without RENAME_NOREPLACE gives the same semantics on
6562 * directories, except when newpath is an *empty* directory. This is
6564 ret
= fstatat(olddirfd
, oldpath
, &buf
, AT_SYMLINK_NOFOLLOW
);
6565 if (ret
>= 0 && S_ISDIR(buf
.st_mode
)) {
6566 ret
= renameat(olddirfd
, oldpath
, newdirfd
, newpath
);
6567 return ret
>= 0 ? 0 : -errno
;
6570 /* If it is not a directory, use the link()/unlink() fallback. */
6571 ret
= linkat(olddirfd
, oldpath
, newdirfd
, newpath
, 0);
6575 ret
= unlinkat(olddirfd
, oldpath
, 0);
6577 /* backup errno before the following unlinkat() alters it */
6579 (void) unlinkat(newdirfd
, newpath
, 0);
6587 static char *strcpy_backslash_escaped(char *t
, const char *s
, const char *bad
) {
6591 if (*s
== '\\' || strchr(bad
, *s
))
6600 char *shell_escape(const char *s
, const char *bad
) {
6603 r
= new(char, strlen(s
)*2+1);
6607 t
= strcpy_backslash_escaped(r
, s
, bad
);
6613 char *shell_maybe_quote(const char *s
) {
6619 /* Encloses a string in double quotes if necessary to make it
6620 * OK as shell string. */
6622 for (p
= s
; *p
; p
++)
6625 strchr(SHELL_NEED_QUOTES
, *p
))
6631 r
= new(char, 1+strlen(s
)*2+1+1);
6637 t
= mempcpy(t
, s
, p
- s
);
6639 t
= strcpy_backslash_escaped(t
, p
, SHELL_NEED_ESCAPE
);
6647 int parse_mode(const char *s
, mode_t
*ret
) {
6655 l
= strtol(s
, &x
, 8);
6659 if (!x
|| x
== s
|| *x
)
6661 if (l
< 0 || l
> 07777)
6668 int mount_move_root(const char *path
) {
6671 if (chdir(path
) < 0)
6674 if (mount(path
, "/", NULL
, MS_MOVE
, NULL
) < 0)
6677 if (chroot(".") < 0)
6686 int reset_uid_gid(void) {
6688 if (setgroups(0, NULL
) < 0)
6691 if (setresgid(0, 0, 0) < 0)
6694 if (setresuid(0, 0, 0) < 0)
6700 int getxattr_malloc(const char *path
, const char *name
, char **value
, bool allow_symlink
) {
6709 for (l
= 100; ; l
= (size_t) n
+ 1) {
6715 n
= lgetxattr(path
, name
, v
, l
);
6717 n
= getxattr(path
, name
, v
, l
);
6719 if (n
>= 0 && (size_t) n
< l
) {
6726 if (n
< 0 && errno
!= ERANGE
)
6730 n
= lgetxattr(path
, name
, NULL
, 0);
6732 n
= getxattr(path
, name
, NULL
, 0);
6738 int fgetxattr_malloc(int fd
, const char *name
, char **value
) {
6747 for (l
= 100; ; l
= (size_t) n
+ 1) {
6752 n
= fgetxattr(fd
, name
, v
, l
);
6754 if (n
>= 0 && (size_t) n
< l
) {
6761 if (n
< 0 && errno
!= ERANGE
)
6764 n
= fgetxattr(fd
, name
, NULL
, 0);
6770 int send_one_fd(int transport_fd
, int fd
, int flags
) {
6772 struct cmsghdr cmsghdr
;
6773 uint8_t buf
[CMSG_SPACE(sizeof(int))];
6775 struct msghdr mh
= {
6776 .msg_control
= &control
,
6777 .msg_controllen
= sizeof(control
),
6779 struct cmsghdr
*cmsg
;
6781 assert(transport_fd
>= 0);
6784 cmsg
= CMSG_FIRSTHDR(&mh
);
6785 cmsg
->cmsg_level
= SOL_SOCKET
;
6786 cmsg
->cmsg_type
= SCM_RIGHTS
;
6787 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
6788 memcpy(CMSG_DATA(cmsg
), &fd
, sizeof(int));
6790 mh
.msg_controllen
= CMSG_SPACE(sizeof(int));
6791 if (sendmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| flags
) < 0)
6797 int receive_one_fd(int transport_fd
, int flags
) {
6799 struct cmsghdr cmsghdr
;
6800 uint8_t buf
[CMSG_SPACE(sizeof(int))];
6802 struct msghdr mh
= {
6803 .msg_control
= &control
,
6804 .msg_controllen
= sizeof(control
),
6806 struct cmsghdr
*cmsg
, *found
= NULL
;
6808 assert(transport_fd
>= 0);
6811 * Receive a single FD via @transport_fd. We don't care for
6812 * the transport-type. We retrieve a single FD at most, so for
6813 * packet-based transports, the caller must ensure to send
6814 * only a single FD per packet. This is best used in
6815 * combination with send_one_fd().
6818 if (recvmsg(transport_fd
, &mh
, MSG_NOSIGNAL
| MSG_CMSG_CLOEXEC
| flags
) < 0)
6821 CMSG_FOREACH(cmsg
, &mh
) {
6822 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
6823 cmsg
->cmsg_type
== SCM_RIGHTS
&&
6824 cmsg
->cmsg_len
== CMSG_LEN(sizeof(int))) {
6832 cmsg_close_all(&mh
);
6836 return *(int*) CMSG_DATA(found
);
6839 void nop_signal_handler(int sig
) {
6844 puts(PACKAGE_STRING
"\n"