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 <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
41 #include <sys/prctl.h>
42 #include <sys/utsname.h>
44 #include <netinet/ip.h>
51 #include <sys/mount.h>
52 #include <linux/magic.h>
56 #include <sys/personality.h>
57 #include <sys/xattr.h>
58 #include <sys/statvfs.h>
62 /* When we include libgen.h because we need dirname() we immediately
63 * undefine basename() since libgen.h defines it as a macro to the POSIX
64 * version which is really broken. We prefer GNU basename(). */
68 #ifdef HAVE_SYS_AUXV_H
80 #include "path-util.h"
81 #include "exit-status.h"
85 #include "device-nodes.h"
90 #include "sparse-endian.h"
91 #include "formats-util.h"
92 #include "process-util.h"
93 #include "random-util.h"
94 #include "terminal-util.h"
95 #include "hostname-util.h"
96 #include "signal-util.h"
98 /* Put this test here for a lack of better place */
99 assert_cc(EAGAIN
== EWOULDBLOCK
);
102 char **saved_argv
= NULL
;
104 size_t page_size(void) {
105 static thread_local
size_t pgsz
= 0;
108 if (_likely_(pgsz
> 0))
111 r
= sysconf(_SC_PAGESIZE
);
118 int strcmp_ptr(const char *a
, const char *b
) {
120 /* Like strcmp(), but tries to make sense of NULL pointers */
133 bool streq_ptr(const char *a
, const char *b
) {
134 return strcmp_ptr(a
, b
) == 0;
137 char* endswith(const char *s
, const char *postfix
) {
144 pl
= strlen(postfix
);
147 return (char*) s
+ sl
;
152 if (memcmp(s
+ sl
- pl
, postfix
, pl
) != 0)
155 return (char*) s
+ sl
- pl
;
158 char* endswith_no_case(const char *s
, const char *postfix
) {
165 pl
= strlen(postfix
);
168 return (char*) s
+ sl
;
173 if (strcasecmp(s
+ sl
- pl
, postfix
) != 0)
176 return (char*) s
+ sl
- pl
;
179 char* first_word(const char *s
, const char *word
) {
186 /* Checks if the string starts with the specified word, either
187 * followed by NUL or by whitespace. Returns a pointer to the
188 * NUL or the first character after the whitespace. */
199 if (memcmp(s
, word
, wl
) != 0)
206 if (!strchr(WHITESPACE
, *p
))
209 p
+= strspn(p
, WHITESPACE
);
213 size_t cescape_char(char c
, char *buf
) {
214 char * buf_old
= buf
;
260 /* For special chars we prefer octal over
261 * hexadecimal encoding, simply because glib's
262 * g_strescape() does the same */
263 if ((c
< ' ') || (c
>= 127)) {
265 *(buf
++) = octchar((unsigned char) c
>> 6);
266 *(buf
++) = octchar((unsigned char) c
>> 3);
267 *(buf
++) = octchar((unsigned char) c
);
273 return buf
- buf_old
;
276 int close_nointr(int fd
) {
283 * Just ignore EINTR; a retry loop is the wrong thing to do on
286 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
287 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
288 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
289 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
297 int safe_close(int fd
) {
300 * Like close_nointr() but cannot fail. Guarantees errno is
301 * unchanged. Is a NOP with negative fds passed, and returns
302 * -1, so that it can be used in this syntax:
304 * fd = safe_close(fd);
310 /* The kernel might return pretty much any error code
311 * via close(), but the fd will be closed anyway. The
312 * only condition we want to check for here is whether
313 * the fd was invalid at all... */
315 assert_se(close_nointr(fd
) != -EBADF
);
321 void close_many(const int fds
[], unsigned n_fd
) {
324 assert(fds
|| n_fd
<= 0);
326 for (i
= 0; i
< n_fd
; i
++)
330 int fclose_nointr(FILE *f
) {
333 /* Same as close_nointr(), but for fclose() */
344 FILE* safe_fclose(FILE *f
) {
346 /* Same as safe_close(), but for fclose() */
351 assert_se(fclose_nointr(f
) != EBADF
);
357 int unlink_noerrno(const char *path
) {
368 int parse_boolean(const char *v
) {
371 if (streq(v
, "1") || strcaseeq(v
, "yes") || strcaseeq(v
, "y") || strcaseeq(v
, "true") || strcaseeq(v
, "t") || strcaseeq(v
, "on"))
373 else if (streq(v
, "0") || strcaseeq(v
, "no") || strcaseeq(v
, "n") || strcaseeq(v
, "false") || strcaseeq(v
, "f") || strcaseeq(v
, "off"))
379 int parse_pid(const char *s
, pid_t
* ret_pid
) {
380 unsigned long ul
= 0;
387 r
= safe_atolu(s
, &ul
);
393 if ((unsigned long) pid
!= ul
)
403 bool uid_is_valid(uid_t uid
) {
405 /* Some libc APIs use UID_INVALID as special placeholder */
406 if (uid
== (uid_t
) 0xFFFFFFFF)
409 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
410 if (uid
== (uid_t
) 0xFFFF)
416 int parse_uid(const char *s
, uid_t
* ret_uid
) {
417 unsigned long ul
= 0;
423 r
= safe_atolu(s
, &ul
);
429 if ((unsigned long) uid
!= ul
)
432 if (!uid_is_valid(uid
))
433 return -ENXIO
; /* we return ENXIO instead of EINVAL
434 * here, to make it easy to distuingish
435 * invalid numeric uids invalid
444 int safe_atou(const char *s
, unsigned *ret_u
) {
452 l
= strtoul(s
, &x
, 0);
454 if (!x
|| x
== s
|| *x
|| errno
)
455 return errno
> 0 ? -errno
: -EINVAL
;
457 if ((unsigned long) (unsigned) l
!= l
)
460 *ret_u
= (unsigned) l
;
464 int safe_atoi(const char *s
, int *ret_i
) {
472 l
= strtol(s
, &x
, 0);
474 if (!x
|| x
== s
|| *x
|| errno
)
475 return errno
> 0 ? -errno
: -EINVAL
;
477 if ((long) (int) l
!= l
)
484 int safe_atou8(const char *s
, uint8_t *ret
) {
492 l
= strtoul(s
, &x
, 0);
494 if (!x
|| x
== s
|| *x
|| errno
)
495 return errno
> 0 ? -errno
: -EINVAL
;
497 if ((unsigned long) (uint8_t) l
!= l
)
504 int safe_atou16(const char *s
, uint16_t *ret
) {
512 l
= strtoul(s
, &x
, 0);
514 if (!x
|| x
== s
|| *x
|| errno
)
515 return errno
> 0 ? -errno
: -EINVAL
;
517 if ((unsigned long) (uint16_t) l
!= l
)
524 int safe_atoi16(const char *s
, int16_t *ret
) {
532 l
= strtol(s
, &x
, 0);
534 if (!x
|| x
== s
|| *x
|| errno
)
535 return errno
> 0 ? -errno
: -EINVAL
;
537 if ((long) (int16_t) l
!= l
)
544 int safe_atollu(const char *s
, long long unsigned *ret_llu
) {
546 unsigned long long l
;
552 l
= strtoull(s
, &x
, 0);
554 if (!x
|| x
== s
|| *x
|| errno
)
555 return errno
? -errno
: -EINVAL
;
561 int safe_atolli(const char *s
, long long int *ret_lli
) {
569 l
= strtoll(s
, &x
, 0);
571 if (!x
|| x
== s
|| *x
|| errno
)
572 return errno
? -errno
: -EINVAL
;
578 int safe_atod(const char *s
, double *ret_d
) {
586 loc
= newlocale(LC_NUMERIC_MASK
, "C", (locale_t
) 0);
587 if (loc
== (locale_t
) 0)
591 d
= strtod_l(s
, &x
, loc
);
593 if (!x
|| x
== s
|| *x
|| errno
) {
595 return errno
? -errno
: -EINVAL
;
603 static size_t strcspn_escaped(const char *s
, const char *reject
) {
604 bool escaped
= false;
607 for (n
=0; s
[n
]; n
++) {
610 else if (s
[n
] == '\\')
612 else if (strchr(reject
, s
[n
]))
616 /* if s ends in \, return index of previous char */
620 /* Split a string into words. */
621 const char* split(const char **state
, size_t *l
, const char *separator
, bool quoted
) {
627 assert(**state
== '\0');
631 current
+= strspn(current
, separator
);
637 if (quoted
&& strchr("\'\"", *current
)) {
638 char quotechars
[2] = {*current
, '\0'};
640 *l
= strcspn_escaped(current
+ 1, quotechars
);
641 if (current
[*l
+ 1] == '\0' || current
[*l
+ 1] != quotechars
[0] ||
642 (current
[*l
+ 2] && !strchr(separator
, current
[*l
+ 2]))) {
643 /* right quote missing or garbage at the end */
647 *state
= current
++ + *l
+ 2;
649 *l
= strcspn_escaped(current
, separator
);
650 if (current
[*l
] && !strchr(separator
, current
[*l
])) {
651 /* unfinished escape */
655 *state
= current
+ *l
;
657 *l
= strcspn(current
, separator
);
658 *state
= current
+ *l
;
664 int fchmod_umask(int fd
, mode_t m
) {
669 r
= fchmod(fd
, m
& (~u
)) < 0 ? -errno
: 0;
675 char *truncate_nl(char *s
) {
678 s
[strcspn(s
, NEWLINE
)] = 0;
682 char *strnappend(const char *s
, const char *suffix
, size_t b
) {
690 return strndup(suffix
, b
);
699 if (b
> ((size_t) -1) - a
)
702 r
= new(char, a
+b
+1);
707 memcpy(r
+a
, suffix
, b
);
713 char *strappend(const char *s
, const char *suffix
) {
714 return strnappend(s
, suffix
, suffix
? strlen(suffix
) : 0);
717 int readlinkat_malloc(int fd
, const char *p
, char **ret
) {
732 n
= readlinkat(fd
, p
, c
, l
-1);
739 if ((size_t) n
< l
-1) {
750 int readlink_malloc(const char *p
, char **ret
) {
751 return readlinkat_malloc(AT_FDCWD
, p
, ret
);
754 int readlink_value(const char *p
, char **ret
) {
755 _cleanup_free_
char *link
= NULL
;
759 r
= readlink_malloc(p
, &link
);
763 value
= basename(link
);
767 value
= strdup(value
);
776 int readlink_and_make_absolute(const char *p
, char **r
) {
777 _cleanup_free_
char *target
= NULL
;
784 j
= readlink_malloc(p
, &target
);
788 k
= file_in_same_dir(p
, target
);
796 int readlink_and_canonicalize(const char *p
, char **r
) {
803 j
= readlink_and_make_absolute(p
, &t
);
807 s
= canonicalize_file_name(t
);
814 path_kill_slashes(*r
);
819 char *strstrip(char *s
) {
822 /* Drops trailing whitespace. Modifies the string in
823 * place. Returns pointer to first non-space character */
825 s
+= strspn(s
, WHITESPACE
);
827 for (e
= strchr(s
, 0); e
> s
; e
--)
828 if (!strchr(WHITESPACE
, e
[-1]))
836 char *delete_chars(char *s
, const char *bad
) {
839 /* Drops all whitespace, regardless where in the string */
841 for (f
= s
, t
= s
; *f
; f
++) {
853 char *file_in_same_dir(const char *path
, const char *filename
) {
860 /* This removes the last component of path and appends
861 * filename, unless the latter is absolute anyway or the
864 if (path_is_absolute(filename
))
865 return strdup(filename
);
867 e
= strrchr(path
, '/');
869 return strdup(filename
);
871 k
= strlen(filename
);
872 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
876 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
880 int rmdir_parents(const char *path
, const char *stop
) {
889 /* Skip trailing slashes */
890 while (l
> 0 && path
[l
-1] == '/')
896 /* Skip last component */
897 while (l
> 0 && path
[l
-1] != '/')
900 /* Skip trailing slashes */
901 while (l
> 0 && path
[l
-1] == '/')
907 if (!(t
= strndup(path
, l
)))
910 if (path_startswith(stop
, t
)) {
926 char hexchar(int x
) {
927 static const char table
[16] = "0123456789abcdef";
929 return table
[x
& 15];
932 int unhexchar(char c
) {
934 if (c
>= '0' && c
<= '9')
937 if (c
>= 'a' && c
<= 'f')
940 if (c
>= 'A' && c
<= 'F')
946 char *hexmem(const void *p
, size_t l
) {
950 z
= r
= malloc(l
* 2 + 1);
954 for (x
= p
; x
< (const uint8_t*) p
+ l
; x
++) {
955 *(z
++) = hexchar(*x
>> 4);
956 *(z
++) = hexchar(*x
& 15);
963 int unhexmem(const char *p
, size_t l
, void **mem
, size_t *len
) {
964 _cleanup_free_
uint8_t *r
= NULL
;
972 z
= r
= malloc((l
+ 1) / 2 + 1);
976 for (x
= p
; x
< p
+ l
; x
+= 2) {
982 else if (x
+1 < p
+ l
) {
989 *(z
++) = (uint8_t) a
<< 4 | (uint8_t) b
;
1001 /* https://tools.ietf.org/html/rfc4648#section-6
1002 * Notice that base32hex differs from base32 in the alphabet it uses.
1003 * The distinction is that the base32hex representation preserves the
1004 * order of the underlying data when compared as bytestrings, this is
1005 * useful when representing NSEC3 hashes, as one can then verify the
1006 * order of hashes directly from their representation. */
1007 char base32hexchar(int x
) {
1008 static const char table
[32] = "0123456789"
1009 "ABCDEFGHIJKLMNOPQRSTUV";
1011 return table
[x
& 31];
1014 int unbase32hexchar(char c
) {
1017 if (c
>= '0' && c
<= '9')
1020 offset
= '9' - '0' + 1;
1022 if (c
>= 'A' && c
<= 'V')
1023 return c
- 'A' + offset
;
1028 char *base32hexmem(const void *p
, size_t l
, bool padding
) {
1034 /* five input bytes makes eight output bytes, padding is added so we must round up */
1035 len
= 8 * (l
+ 4) / 5;
1037 /* same, but round down as there is no padding */
1056 z
= r
= malloc(len
+ 1);
1060 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 5) * 5; x
+= 5) {
1061 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ
1062 x[3] == QQQQQQQQ; x[4] == WWWWWWWW */
1063 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1064 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1065 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1066 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1067 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
1068 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
1069 *(z
++) = base32hexchar((x
[3] & 3) << 3 | x
[4] >> 5); /* 000QQWWW */
1070 *(z
++) = base32hexchar((x
[4] & 31)); /* 000WWWWW */
1075 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1076 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1077 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1078 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1079 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
1080 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
1081 *(z
++) = base32hexchar((x
[3] & 3) << 3); /* 000QQ000 */
1088 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1089 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1090 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1091 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1092 *(z
++) = base32hexchar((x
[2] & 15) << 1); /* 000ZZZZ0 */
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); /* 000Y0000 */
1116 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1117 *(z
++) = base32hexchar((x
[0] & 7) << 2); /* 000XXX00 */
1134 int unbase32hexmem(const char *p
, size_t l
, bool padding
, void **mem
, size_t *_len
) {
1135 _cleanup_free_
uint8_t *r
= NULL
;
1136 int a
, b
, c
, d
, e
, f
, g
, h
;
1144 /* padding ensures any base32hex input has input divisible by 8 */
1145 if (padding
&& l
% 8 != 0)
1149 /* strip the padding */
1150 while (l
> 0 && p
[l
- 1] == '=' && pad
< 7) {
1156 /* a group of eight input bytes needs five output bytes, in case of
1157 padding we need to add some extra bytes */
1179 z
= r
= malloc(len
+ 1);
1183 for (x
= p
; x
< p
+ (l
/ 8) * 8; x
+= 8) {
1184 /* a == 000XXXXX; b == 000YYYYY; c == 000ZZZZZ; d == 000WWWWW
1185 e == 000SSSSS; f == 000QQQQQ; g == 000VVVVV; h == 000RRRRR */
1186 a
= unbase32hexchar(x
[0]);
1190 b
= unbase32hexchar(x
[1]);
1194 c
= unbase32hexchar(x
[2]);
1198 d
= unbase32hexchar(x
[3]);
1202 e
= unbase32hexchar(x
[4]);
1206 f
= unbase32hexchar(x
[5]);
1210 g
= unbase32hexchar(x
[6]);
1214 h
= unbase32hexchar(x
[7]);
1218 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1219 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1220 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1221 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
1222 *(z
++) = (uint8_t) g
<< 5 | (uint8_t) h
; /* VVVRRRRR */
1227 a
= unbase32hexchar(x
[0]);
1231 b
= unbase32hexchar(x
[1]);
1235 c
= unbase32hexchar(x
[2]);
1239 d
= unbase32hexchar(x
[3]);
1243 e
= unbase32hexchar(x
[4]);
1247 f
= unbase32hexchar(x
[5]);
1251 g
= unbase32hexchar(x
[6]);
1259 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1260 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1261 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1262 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
1266 a
= unbase32hexchar(x
[0]);
1270 b
= unbase32hexchar(x
[1]);
1274 c
= unbase32hexchar(x
[2]);
1278 d
= unbase32hexchar(x
[3]);
1282 e
= unbase32hexchar(x
[4]);
1290 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1291 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1292 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1296 a
= unbase32hexchar(x
[0]);
1300 b
= unbase32hexchar(x
[1]);
1304 c
= unbase32hexchar(x
[2]);
1308 d
= unbase32hexchar(x
[3]);
1316 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1317 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1321 a
= unbase32hexchar(x
[0]);
1325 b
= unbase32hexchar(x
[1]);
1333 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1351 /* https://tools.ietf.org/html/rfc4648#section-4 */
1352 char base64char(int x
) {
1353 static const char table
[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1354 "abcdefghijklmnopqrstuvwxyz"
1356 return table
[x
& 63];
1359 int unbase64char(char c
) {
1362 if (c
>= 'A' && c
<= 'Z')
1365 offset
= 'Z' - 'A' + 1;
1367 if (c
>= 'a' && c
<= 'z')
1368 return c
- 'a' + offset
;
1370 offset
+= 'z' - 'a' + 1;
1372 if (c
>= '0' && c
<= '9')
1373 return c
- '0' + offset
;
1375 offset
+= '9' - '0' + 1;
1388 char *base64mem(const void *p
, size_t l
) {
1392 /* three input bytes makes four output bytes, padding is added so we must round up */
1393 z
= r
= malloc(4 * (l
+ 2) / 3 + 1);
1397 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 3) * 3; x
+= 3) {
1398 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ */
1399 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1400 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1401 *(z
++) = base64char((x
[1] & 15) << 2 | x
[2] >> 6); /* 00YYYYZZ */
1402 *(z
++) = base64char(x
[2] & 63); /* 00ZZZZZZ */
1407 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1408 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1409 *(z
++) = base64char((x
[1] & 15) << 2); /* 00YYYY00 */
1414 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1415 *(z
++) = base64char((x
[0] & 3) << 4); /* 00XX0000 */
1426 int unbase64mem(const char *p
, size_t l
, void **mem
, size_t *_len
) {
1427 _cleanup_free_
uint8_t *r
= NULL
;
1435 /* padding ensures any base63 input has input divisible by 4 */
1439 /* strip the padding */
1440 if (l
> 0 && p
[l
- 1] == '=')
1442 if (l
> 0 && p
[l
- 1] == '=')
1445 /* a group of four input bytes needs three output bytes, in case of
1446 padding we need to add two or three extra bytes */
1447 len
= (l
/ 4) * 3 + (l
% 4 ? (l
% 4) - 1 : 0);
1449 z
= r
= malloc(len
+ 1);
1453 for (x
= p
; x
< p
+ (l
/ 4) * 4; x
+= 4) {
1454 /* a == 00XXXXXX; b == 00YYYYYY; c == 00ZZZZZZ; d == 00WWWWWW */
1455 a
= unbase64char(x
[0]);
1459 b
= unbase64char(x
[1]);
1463 c
= unbase64char(x
[2]);
1467 d
= unbase64char(x
[3]);
1471 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1472 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1473 *(z
++) = (uint8_t) c
<< 6 | (uint8_t) d
; /* ZZWWWWWW */
1478 a
= unbase64char(x
[0]);
1482 b
= unbase64char(x
[1]);
1486 c
= unbase64char(x
[2]);
1494 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1495 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1499 a
= unbase64char(x
[0]);
1503 b
= unbase64char(x
[1]);
1511 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) (b
>> 4); /* XXXXXXYY */
1530 char octchar(int x
) {
1531 return '0' + (x
& 7);
1534 int unoctchar(char c
) {
1536 if (c
>= '0' && c
<= '7')
1542 char decchar(int x
) {
1543 return '0' + (x
% 10);
1546 int undecchar(char c
) {
1548 if (c
>= '0' && c
<= '9')
1554 char *cescape(const char *s
) {
1560 /* Does C style string escaping. May be reversed with
1563 r
= new(char, strlen(s
)*4 + 1);
1567 for (f
= s
, t
= r
; *f
; f
++)
1568 t
+= cescape_char(*f
, t
);
1575 static int cunescape_one(const char *p
, size_t length
, char *ret
, uint32_t *ret_unicode
) {
1582 /* Unescapes C style. Returns the unescaped character in ret,
1583 * unless we encountered a \u sequence in which case the full
1584 * unicode character is returned in ret_unicode, instead. */
1586 if (length
!= (size_t) -1 && length
< 1)
1623 /* This is an extension of the XDG syntax files */
1628 /* hexadecimal encoding */
1631 if (length
!= (size_t) -1 && length
< 3)
1634 a
= unhexchar(p
[1]);
1638 b
= unhexchar(p
[2]);
1642 /* Don't allow NUL bytes */
1643 if (a
== 0 && b
== 0)
1646 *ret
= (char) ((a
<< 4U) | b
);
1652 /* C++11 style 16bit unicode */
1658 if (length
!= (size_t) -1 && length
< 5)
1661 for (i
= 0; i
< 4; i
++) {
1662 a
[i
] = unhexchar(p
[1 + i
]);
1667 c
= ((uint32_t) a
[0] << 12U) | ((uint32_t) a
[1] << 8U) | ((uint32_t) a
[2] << 4U) | (uint32_t) a
[3];
1669 /* Don't allow 0 chars */
1688 /* C++11 style 32bit unicode */
1694 if (length
!= (size_t) -1 && length
< 9)
1697 for (i
= 0; i
< 8; i
++) {
1698 a
[i
] = unhexchar(p
[1 + i
]);
1703 c
= ((uint32_t) a
[0] << 28U) | ((uint32_t) a
[1] << 24U) | ((uint32_t) a
[2] << 20U) | ((uint32_t) a
[3] << 16U) |
1704 ((uint32_t) a
[4] << 12U) | ((uint32_t) a
[5] << 8U) | ((uint32_t) a
[6] << 4U) | (uint32_t) a
[7];
1706 /* Don't allow 0 chars */
1710 /* Don't allow invalid code points */
1711 if (!unichar_is_valid(c
))
1736 /* octal encoding */
1740 if (length
!= (size_t) -1 && length
< 3)
1743 a
= unoctchar(p
[0]);
1747 b
= unoctchar(p
[1]);
1751 c
= unoctchar(p
[2]);
1755 /* don't allow NUL bytes */
1756 if (a
== 0 && b
== 0 && c
== 0)
1759 /* Don't allow bytes above 255 */
1760 m
= ((uint32_t) a
<< 6U) | ((uint32_t) b
<< 3U) | (uint32_t) c
;
1776 int cunescape_length_with_prefix(const char *s
, size_t length
, const char *prefix
, UnescapeFlags flags
, char **ret
) {
1784 /* Undoes C style string escaping, and optionally prefixes it. */
1786 pl
= prefix
? strlen(prefix
) : 0;
1788 r
= new(char, pl
+length
+1);
1793 memcpy(r
, prefix
, pl
);
1795 for (f
= s
, t
= r
+ pl
; f
< s
+ length
; f
++) {
1801 remaining
= s
+ length
- f
;
1802 assert(remaining
> 0);
1805 /* A literal literal, copy verbatim */
1810 if (remaining
== 1) {
1811 if (flags
& UNESCAPE_RELAX
) {
1812 /* A trailing backslash, copy verbatim */
1821 k
= cunescape_one(f
+ 1, remaining
- 1, &c
, &u
);
1823 if (flags
& UNESCAPE_RELAX
) {
1824 /* Invalid escape code, let's take it literal then */
1834 /* Non-Unicode? Let's encode this directly */
1837 /* Unicode? Then let's encode this in UTF-8 */
1838 t
+= utf8_encode_unichar(t
, u
);
1849 int cunescape_length(const char *s
, size_t length
, UnescapeFlags flags
, char **ret
) {
1850 return cunescape_length_with_prefix(s
, length
, NULL
, flags
, ret
);
1853 int cunescape(const char *s
, UnescapeFlags flags
, char **ret
) {
1854 return cunescape_length(s
, strlen(s
), flags
, ret
);
1857 char *xescape(const char *s
, const char *bad
) {
1861 /* Escapes all chars in bad, in addition to \ and all special
1862 * chars, in \xFF style escaping. May be reversed with
1865 r
= new(char, strlen(s
) * 4 + 1);
1869 for (f
= s
, t
= r
; *f
; f
++) {
1871 if ((*f
< ' ') || (*f
>= 127) ||
1872 (*f
== '\\') || strchr(bad
, *f
)) {
1875 *(t
++) = hexchar(*f
>> 4);
1876 *(t
++) = hexchar(*f
);
1886 char *ascii_strlower(char *t
) {
1891 for (p
= t
; *p
; p
++)
1892 if (*p
>= 'A' && *p
<= 'Z')
1893 *p
= *p
- 'A' + 'a';
1898 _pure_
static bool hidden_file_allow_backup(const char *filename
) {
1902 filename
[0] == '.' ||
1903 streq(filename
, "lost+found") ||
1904 streq(filename
, "aquota.user") ||
1905 streq(filename
, "aquota.group") ||
1906 endswith(filename
, ".rpmnew") ||
1907 endswith(filename
, ".rpmsave") ||
1908 endswith(filename
, ".rpmorig") ||
1909 endswith(filename
, ".dpkg-old") ||
1910 endswith(filename
, ".dpkg-new") ||
1911 endswith(filename
, ".dpkg-tmp") ||
1912 endswith(filename
, ".dpkg-dist") ||
1913 endswith(filename
, ".dpkg-bak") ||
1914 endswith(filename
, ".dpkg-backup") ||
1915 endswith(filename
, ".dpkg-remove") ||
1916 endswith(filename
, ".swp");
1919 bool hidden_file(const char *filename
) {
1922 if (endswith(filename
, "~"))
1925 return hidden_file_allow_backup(filename
);
1928 int fd_nonblock(int fd
, bool nonblock
) {
1933 flags
= fcntl(fd
, F_GETFL
, 0);
1938 nflags
= flags
| O_NONBLOCK
;
1940 nflags
= flags
& ~O_NONBLOCK
;
1942 if (nflags
== flags
)
1945 if (fcntl(fd
, F_SETFL
, nflags
) < 0)
1951 int fd_cloexec(int fd
, bool cloexec
) {
1956 flags
= fcntl(fd
, F_GETFD
, 0);
1961 nflags
= flags
| FD_CLOEXEC
;
1963 nflags
= flags
& ~FD_CLOEXEC
;
1965 if (nflags
== flags
)
1968 if (fcntl(fd
, F_SETFD
, nflags
) < 0)
1974 _pure_
static bool fd_in_set(int fd
, const int fdset
[], unsigned n_fdset
) {
1977 assert(n_fdset
== 0 || fdset
);
1979 for (i
= 0; i
< n_fdset
; i
++)
1986 int close_all_fds(const int except
[], unsigned n_except
) {
1987 _cleanup_closedir_
DIR *d
= NULL
;
1991 assert(n_except
== 0 || except
);
1993 d
= opendir("/proc/self/fd");
1998 /* When /proc isn't available (for example in chroots)
1999 * the fallback is brute forcing through the fd
2002 assert_se(getrlimit(RLIMIT_NOFILE
, &rl
) >= 0);
2003 for (fd
= 3; fd
< (int) rl
.rlim_max
; fd
++) {
2005 if (fd_in_set(fd
, except
, n_except
))
2008 if (close_nointr(fd
) < 0)
2009 if (errno
!= EBADF
&& r
== 0)
2016 while ((de
= readdir(d
))) {
2019 if (hidden_file(de
->d_name
))
2022 if (safe_atoi(de
->d_name
, &fd
) < 0)
2023 /* Let's better ignore this, just in case */
2032 if (fd_in_set(fd
, except
, n_except
))
2035 if (close_nointr(fd
) < 0) {
2036 /* Valgrind has its own FD and doesn't want to have it closed */
2037 if (errno
!= EBADF
&& r
== 0)
2045 bool chars_intersect(const char *a
, const char *b
) {
2048 /* Returns true if any of the chars in a are in b. */
2049 for (p
= a
; *p
; p
++)
2056 bool fstype_is_network(const char *fstype
) {
2057 static const char table
[] =
2072 x
= startswith(fstype
, "fuse.");
2076 return nulstr_contains(table
, fstype
);
2079 int flush_fd(int fd
) {
2080 struct pollfd pollfd
= {
2090 r
= poll(&pollfd
, 1, 0);
2100 l
= read(fd
, buf
, sizeof(buf
));
2106 if (errno
== EAGAIN
)
2115 void safe_close_pair(int p
[]) {
2119 /* Special case pairs which use the same fd in both
2121 p
[0] = p
[1] = safe_close(p
[0]);
2125 p
[0] = safe_close(p
[0]);
2126 p
[1] = safe_close(p
[1]);
2129 ssize_t
loop_read(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2136 while (nbytes
> 0) {
2139 k
= read(fd
, p
, nbytes
);
2144 if (errno
== EAGAIN
&& do_poll
) {
2146 /* We knowingly ignore any return value here,
2147 * and expect that any error/EOF is reported
2150 fd_wait_for_event(fd
, POLLIN
, USEC_INFINITY
);
2154 return n
> 0 ? n
: -errno
;
2168 int loop_read_exact(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2171 n
= loop_read(fd
, buf
, nbytes
, do_poll
);
2174 if ((size_t) n
!= nbytes
)
2179 int loop_write(int fd
, const void *buf
, size_t nbytes
, bool do_poll
) {
2180 const uint8_t *p
= buf
;
2190 k
= write(fd
, p
, nbytes
);
2195 if (errno
== EAGAIN
&& do_poll
) {
2196 /* We knowingly ignore any return value here,
2197 * and expect that any error/EOF is reported
2200 fd_wait_for_event(fd
, POLLOUT
, USEC_INFINITY
);
2207 if (nbytes
> 0 && k
== 0) /* Can't really happen */
2212 } while (nbytes
> 0);
2217 int parse_size(const char *t
, off_t base
, off_t
*size
) {
2219 /* Soo, sometimes we want to parse IEC binary suffixes, and
2220 * sometimes SI decimal suffixes. This function can parse
2221 * both. Which one is the right way depends on the
2222 * context. Wikipedia suggests that SI is customary for
2223 * hardware metrics and network speeds, while IEC is
2224 * customary for most data sizes used by software and volatile
2225 * (RAM) memory. Hence be careful which one you pick!
2227 * In either case we use just K, M, G as suffix, and not Ki,
2228 * Mi, Gi or so (as IEC would suggest). That's because that's
2229 * frickin' ugly. But this means you really need to make sure
2230 * to document which base you are parsing when you use this
2235 unsigned long long factor
;
2238 static const struct table iec
[] = {
2239 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2240 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2241 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2242 { "G", 1024ULL*1024ULL*1024ULL },
2243 { "M", 1024ULL*1024ULL },
2249 static const struct table si
[] = {
2250 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2251 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2252 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2253 { "G", 1000ULL*1000ULL*1000ULL },
2254 { "M", 1000ULL*1000ULL },
2260 const struct table
*table
;
2262 unsigned long long r
= 0;
2263 unsigned n_entries
, start_pos
= 0;
2266 assert(base
== 1000 || base
== 1024);
2271 n_entries
= ELEMENTSOF(si
);
2274 n_entries
= ELEMENTSOF(iec
);
2280 unsigned long long l2
;
2286 l
= strtoll(p
, &e
, 10);
2299 if (*e
>= '0' && *e
<= '9') {
2302 /* strotoull itself would accept space/+/- */
2303 l2
= strtoull(e
, &e2
, 10);
2305 if (errno
== ERANGE
)
2308 /* Ignore failure. E.g. 10.M is valid */
2315 e
+= strspn(e
, WHITESPACE
);
2317 for (i
= start_pos
; i
< n_entries
; i
++)
2318 if (startswith(e
, table
[i
].suffix
)) {
2319 unsigned long long tmp
;
2320 if ((unsigned long long) l
+ (frac
> 0) > ULLONG_MAX
/ table
[i
].factor
)
2322 tmp
= l
* table
[i
].factor
+ (unsigned long long) (frac
* table
[i
].factor
);
2323 if (tmp
> ULLONG_MAX
- r
)
2327 if ((unsigned long long) (off_t
) r
!= r
)
2330 p
= e
+ strlen(table
[i
].suffix
);
2346 bool is_device_path(const char *path
) {
2348 /* Returns true on paths that refer to a device, either in
2349 * sysfs or in /dev */
2352 path_startswith(path
, "/dev/") ||
2353 path_startswith(path
, "/sys/");
2356 int dir_is_empty(const char *path
) {
2357 _cleanup_closedir_
DIR *d
;
2368 if (!de
&& errno
!= 0)
2374 if (!hidden_file(de
->d_name
))
2379 char* dirname_malloc(const char *path
) {
2380 char *d
, *dir
, *dir2
;
2397 void rename_process(const char name
[8]) {
2400 /* This is a like a poor man's setproctitle(). It changes the
2401 * comm field, argv[0], and also the glibc's internally used
2402 * name of the process. For the first one a limit of 16 chars
2403 * applies, to the second one usually one of 10 (i.e. length
2404 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2405 * "systemd"). If you pass a longer string it will be
2408 prctl(PR_SET_NAME
, name
);
2410 if (program_invocation_name
)
2411 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
2413 if (saved_argc
> 0) {
2417 strncpy(saved_argv
[0], name
, strlen(saved_argv
[0]));
2419 for (i
= 1; i
< saved_argc
; i
++) {
2423 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
2428 char *lookup_uid(uid_t uid
) {
2431 _cleanup_free_
char *buf
= NULL
;
2432 struct passwd pwbuf
, *pw
= NULL
;
2434 /* Shortcut things to avoid NSS lookups */
2436 return strdup("root");
2438 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
2442 buf
= malloc(bufsize
);
2446 if (getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
) == 0 && pw
)
2447 return strdup(pw
->pw_name
);
2449 if (asprintf(&name
, UID_FMT
, uid
) < 0)
2455 char* getlogname_malloc(void) {
2459 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
2464 return lookup_uid(uid
);
2467 char *getusername_malloc(void) {
2474 return lookup_uid(getuid());
2477 bool is_temporary_fs(const struct statfs
*s
) {
2480 return F_TYPE_EQUAL(s
->f_type
, TMPFS_MAGIC
) ||
2481 F_TYPE_EQUAL(s
->f_type
, RAMFS_MAGIC
);
2484 int fd_is_temporary_fs(int fd
) {
2487 if (fstatfs(fd
, &s
) < 0)
2490 return is_temporary_fs(&s
);
2493 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
2496 /* Under the assumption that we are running privileged we
2497 * first change the access mode and only then hand out
2498 * ownership to avoid a window where access is too open. */
2500 if (mode
!= MODE_INVALID
)
2501 if (chmod(path
, mode
) < 0)
2504 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
2505 if (chown(path
, uid
, gid
) < 0)
2511 int fchmod_and_fchown(int fd
, mode_t mode
, uid_t uid
, gid_t gid
) {
2514 /* Under the assumption that we are running privileged we
2515 * first change the access mode and only then hand out
2516 * ownership to avoid a window where access is too open. */
2518 if (mode
!= MODE_INVALID
)
2519 if (fchmod(fd
, mode
) < 0)
2522 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
2523 if (fchown(fd
, uid
, gid
) < 0)
2529 cpu_set_t
* cpu_set_malloc(unsigned *ncpus
) {
2533 /* Allocates the cpuset in the right size */
2536 if (!(r
= CPU_ALLOC(n
)))
2539 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n
), r
) >= 0) {
2540 CPU_ZERO_S(CPU_ALLOC_SIZE(n
), r
);
2550 if (errno
!= EINVAL
)
2557 int files_same(const char *filea
, const char *fileb
) {
2560 if (stat(filea
, &a
) < 0)
2563 if (stat(fileb
, &b
) < 0)
2566 return a
.st_dev
== b
.st_dev
&&
2567 a
.st_ino
== b
.st_ino
;
2570 int running_in_chroot(void) {
2573 ret
= files_same("/proc/1/root", "/");
2580 static char *ascii_ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
2585 assert(percent
<= 100);
2586 assert(new_length
>= 3);
2588 if (old_length
<= 3 || old_length
<= new_length
)
2589 return strndup(s
, old_length
);
2591 r
= new0(char, new_length
+1);
2595 x
= (new_length
* percent
) / 100;
2597 if (x
> new_length
- 3)
2605 s
+ old_length
- (new_length
- x
- 3),
2606 new_length
- x
- 3);
2611 char *ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
2615 unsigned k
, len
, len2
;
2618 assert(percent
<= 100);
2619 assert(new_length
>= 3);
2621 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2622 if (ascii_is_valid(s
))
2623 return ascii_ellipsize_mem(s
, old_length
, new_length
, percent
);
2625 if (old_length
<= 3 || old_length
<= new_length
)
2626 return strndup(s
, old_length
);
2628 x
= (new_length
* percent
) / 100;
2630 if (x
> new_length
- 3)
2634 for (i
= s
; k
< x
&& i
< s
+ old_length
; i
= utf8_next_char(i
)) {
2637 c
= utf8_encoded_to_unichar(i
);
2640 k
+= unichar_iswide(c
) ? 2 : 1;
2643 if (k
> x
) /* last character was wide and went over quota */
2646 for (j
= s
+ old_length
; k
< new_length
&& j
> i
; ) {
2649 j
= utf8_prev_char(j
);
2650 c
= utf8_encoded_to_unichar(j
);
2653 k
+= unichar_iswide(c
) ? 2 : 1;
2657 /* we don't actually need to ellipsize */
2659 return memdup(s
, old_length
+ 1);
2661 /* make space for ellipsis */
2662 j
= utf8_next_char(j
);
2665 len2
= s
+ old_length
- j
;
2666 e
= new(char, len
+ 3 + len2
+ 1);
2671 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2672 old_length, new_length, x, len, len2, k);
2676 e
[len
] = 0xe2; /* tri-dot ellipsis: … */
2680 memcpy(e
+ len
+ 3, j
, len2
+ 1);
2685 char *ellipsize(const char *s
, size_t length
, unsigned percent
) {
2686 return ellipsize_mem(s
, strlen(s
), length
, percent
);
2689 int touch_file(const char *path
, bool parents
, usec_t stamp
, uid_t uid
, gid_t gid
, mode_t mode
) {
2690 _cleanup_close_
int fd
;
2696 mkdir_parents(path
, 0755);
2698 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, mode
> 0 ? mode
: 0644);
2703 r
= fchmod(fd
, mode
);
2708 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
) {
2709 r
= fchown(fd
, uid
, gid
);
2714 if (stamp
!= USEC_INFINITY
) {
2715 struct timespec ts
[2];
2717 timespec_store(&ts
[0], stamp
);
2719 r
= futimens(fd
, ts
);
2721 r
= futimens(fd
, NULL
);
2728 int touch(const char *path
) {
2729 return touch_file(path
, false, USEC_INFINITY
, UID_INVALID
, GID_INVALID
, 0);
2732 static char *unquote(const char *s
, const char* quotes
) {
2736 /* This is rather stupid, simply removes the heading and
2737 * trailing quotes if there is one. Doesn't care about
2738 * escaping or anything.
2740 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2746 if (strchr(quotes
, s
[0]) && s
[l
-1] == s
[0])
2747 return strndup(s
+1, l
-2);
2752 noreturn
void freeze(void) {
2754 /* Make sure nobody waits for us on a socket anymore */
2755 close_all_fds(NULL
, 0);
2763 bool null_or_empty(struct stat
*st
) {
2766 if (S_ISREG(st
->st_mode
) && st
->st_size
<= 0)
2769 if (S_ISCHR(st
->st_mode
) || S_ISBLK(st
->st_mode
))
2775 int null_or_empty_path(const char *fn
) {
2780 if (stat(fn
, &st
) < 0)
2783 return null_or_empty(&st
);
2786 int null_or_empty_fd(int fd
) {
2791 if (fstat(fd
, &st
) < 0)
2794 return null_or_empty(&st
);
2797 DIR *xopendirat(int fd
, const char *name
, int flags
) {
2801 assert(!(flags
& O_CREAT
));
2803 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
2816 static char *tag_to_udev_node(const char *tagvalue
, const char *by
) {
2817 _cleanup_free_
char *t
= NULL
, *u
= NULL
;
2820 u
= unquote(tagvalue
, QUOTES
);
2824 enc_len
= strlen(u
) * 4 + 1;
2825 t
= new(char, enc_len
);
2829 if (encode_devnode_name(u
, t
, enc_len
) < 0)
2832 return strjoin("/dev/disk/by-", by
, "/", t
, NULL
);
2835 char *fstab_node_to_udev_node(const char *p
) {
2838 if (startswith(p
, "LABEL="))
2839 return tag_to_udev_node(p
+6, "label");
2841 if (startswith(p
, "UUID="))
2842 return tag_to_udev_node(p
+5, "uuid");
2844 if (startswith(p
, "PARTUUID="))
2845 return tag_to_udev_node(p
+9, "partuuid");
2847 if (startswith(p
, "PARTLABEL="))
2848 return tag_to_udev_node(p
+10, "partlabel");
2853 bool dirent_is_file(const struct dirent
*de
) {
2856 if (hidden_file(de
->d_name
))
2859 if (de
->d_type
!= DT_REG
&&
2860 de
->d_type
!= DT_LNK
&&
2861 de
->d_type
!= DT_UNKNOWN
)
2867 bool dirent_is_file_with_suffix(const struct dirent
*de
, const char *suffix
) {
2870 if (de
->d_type
!= DT_REG
&&
2871 de
->d_type
!= DT_LNK
&&
2872 de
->d_type
!= DT_UNKNOWN
)
2875 if (hidden_file_allow_backup(de
->d_name
))
2878 return endswith(de
->d_name
, suffix
);
2881 static int do_execute(char **directories
, usec_t timeout
, char *argv
[]) {
2882 _cleanup_hashmap_free_free_ Hashmap
*pids
= NULL
;
2883 _cleanup_set_free_free_ Set
*seen
= NULL
;
2886 /* We fork this all off from a child process so that we can
2887 * somewhat cleanly make use of SIGALRM to set a time limit */
2889 (void) reset_all_signal_handlers();
2890 (void) reset_signal_mask();
2892 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
2894 pids
= hashmap_new(NULL
);
2898 seen
= set_new(&string_hash_ops
);
2902 STRV_FOREACH(directory
, directories
) {
2903 _cleanup_closedir_
DIR *d
;
2906 d
= opendir(*directory
);
2908 if (errno
== ENOENT
)
2911 return log_error_errno(errno
, "Failed to open directory %s: %m", *directory
);
2914 FOREACH_DIRENT(de
, d
, break) {
2915 _cleanup_free_
char *path
= NULL
;
2919 if (!dirent_is_file(de
))
2922 if (set_contains(seen
, de
->d_name
)) {
2923 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory
, de
->d_name
);
2927 r
= set_put_strdup(seen
, de
->d_name
);
2931 path
= strjoin(*directory
, "/", de
->d_name
, NULL
);
2935 if (null_or_empty_path(path
)) {
2936 log_debug("%s is empty (a mask).", path
);
2942 log_error_errno(errno
, "Failed to fork: %m");
2944 } else if (pid
== 0) {
2947 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
2957 return log_error_errno(errno
, "Failed to execute %s: %m", path
);
2960 log_debug("Spawned %s as " PID_FMT
".", path
, pid
);
2962 r
= hashmap_put(pids
, UINT_TO_PTR(pid
), path
);
2969 /* Abort execution of this process after the timout. We simply
2970 * rely on SIGALRM as default action terminating the process,
2971 * and turn on alarm(). */
2973 if (timeout
!= USEC_INFINITY
)
2974 alarm((timeout
+ USEC_PER_SEC
- 1) / USEC_PER_SEC
);
2976 while (!hashmap_isempty(pids
)) {
2977 _cleanup_free_
char *path
= NULL
;
2980 pid
= PTR_TO_UINT(hashmap_first_key(pids
));
2983 path
= hashmap_remove(pids
, UINT_TO_PTR(pid
));
2986 wait_for_terminate_and_warn(path
, pid
, true);
2992 void execute_directories(const char* const* directories
, usec_t timeout
, char *argv
[]) {
2996 char **dirs
= (char**) directories
;
2998 assert(!strv_isempty(dirs
));
3000 name
= basename(dirs
[0]);
3001 assert(!isempty(name
));
3003 /* Executes all binaries in the directories in parallel and waits
3004 * for them to finish. Optionally a timeout is applied. If a file
3005 * with the same name exists in more than one directory, the
3006 * earliest one wins. */
3008 executor_pid
= fork();
3009 if (executor_pid
< 0) {
3010 log_error_errno(errno
, "Failed to fork: %m");
3013 } else if (executor_pid
== 0) {
3014 r
= do_execute(dirs
, timeout
, argv
);
3015 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
3018 wait_for_terminate_and_warn(name
, executor_pid
, true);
3021 bool nulstr_contains(const char*nulstr
, const char *needle
) {
3027 NULSTR_FOREACH(i
, nulstr
)
3028 if (streq(i
, needle
))
3034 bool plymouth_running(void) {
3035 return access("/run/plymouth/pid", F_OK
) >= 0;
3038 char* strshorten(char *s
, size_t l
) {
3047 int pipe_eof(int fd
) {
3048 struct pollfd pollfd
= {
3050 .events
= POLLIN
|POLLHUP
,
3055 r
= poll(&pollfd
, 1, 0);
3062 return pollfd
.revents
& POLLHUP
;
3065 int fd_wait_for_event(int fd
, int event
, usec_t t
) {
3067 struct pollfd pollfd
= {
3075 r
= ppoll(&pollfd
, 1, t
== USEC_INFINITY
? NULL
: timespec_store(&ts
, t
), NULL
);
3082 return pollfd
.revents
;
3085 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
3094 r
= tempfn_xxxxxx(path
, NULL
, &t
);
3098 fd
= mkostemp_safe(t
, O_WRONLY
|O_CLOEXEC
);
3104 f
= fdopen(fd
, "we");
3118 int symlink_atomic(const char *from
, const char *to
) {
3119 _cleanup_free_
char *t
= NULL
;
3125 r
= tempfn_random(to
, NULL
, &t
);
3129 if (symlink(from
, t
) < 0)
3132 if (rename(t
, to
) < 0) {
3140 int symlink_idempotent(const char *from
, const char *to
) {
3141 _cleanup_free_
char *p
= NULL
;
3147 if (symlink(from
, to
) < 0) {
3148 if (errno
!= EEXIST
)
3151 r
= readlink_malloc(to
, &p
);
3155 if (!streq(p
, from
))
3162 int mknod_atomic(const char *path
, mode_t mode
, dev_t dev
) {
3163 _cleanup_free_
char *t
= NULL
;
3168 r
= tempfn_random(path
, NULL
, &t
);
3172 if (mknod(t
, mode
, dev
) < 0)
3175 if (rename(t
, path
) < 0) {
3183 int mkfifo_atomic(const char *path
, mode_t mode
) {
3184 _cleanup_free_
char *t
= NULL
;
3189 r
= tempfn_random(path
, NULL
, &t
);
3193 if (mkfifo(t
, mode
) < 0)
3196 if (rename(t
, path
) < 0) {
3204 bool display_is_local(const char *display
) {
3208 display
[0] == ':' &&
3209 display
[1] >= '0' &&
3213 int socket_from_display(const char *display
, char **path
) {
3220 if (!display_is_local(display
))
3223 k
= strspn(display
+1, "0123456789");
3225 f
= new(char, strlen("/tmp/.X11-unix/X") + k
+ 1);
3229 c
= stpcpy(f
, "/tmp/.X11-unix/X");
3230 memcpy(c
, display
+1, k
);
3239 const char **username
,
3240 uid_t
*uid
, gid_t
*gid
,
3242 const char **shell
) {
3250 /* We enforce some special rules for uid=0: in order to avoid
3251 * NSS lookups for root we hardcode its data. */
3253 if (streq(*username
, "root") || streq(*username
, "0")) {
3271 if (parse_uid(*username
, &u
) >= 0) {
3275 /* If there are multiple users with the same id, make
3276 * sure to leave $USER to the configured value instead
3277 * of the first occurrence in the database. However if
3278 * the uid was configured by a numeric uid, then let's
3279 * pick the real username from /etc/passwd. */
3281 *username
= p
->pw_name
;
3284 p
= getpwnam(*username
);
3288 return errno
> 0 ? -errno
: -ESRCH
;
3300 *shell
= p
->pw_shell
;
3305 char* uid_to_name(uid_t uid
) {
3310 return strdup("root");
3314 return strdup(p
->pw_name
);
3316 if (asprintf(&r
, UID_FMT
, uid
) < 0)
3322 char* gid_to_name(gid_t gid
) {
3327 return strdup("root");
3331 return strdup(p
->gr_name
);
3333 if (asprintf(&r
, GID_FMT
, gid
) < 0)
3339 int get_group_creds(const char **groupname
, gid_t
*gid
) {
3345 /* We enforce some special rules for gid=0: in order to avoid
3346 * NSS lookups for root we hardcode its data. */
3348 if (streq(*groupname
, "root") || streq(*groupname
, "0")) {
3349 *groupname
= "root";
3357 if (parse_gid(*groupname
, &id
) >= 0) {
3362 *groupname
= g
->gr_name
;
3365 g
= getgrnam(*groupname
);
3369 return errno
> 0 ? -errno
: -ESRCH
;
3377 int in_gid(gid_t gid
) {
3379 int ngroups_max
, r
, i
;
3381 if (getgid() == gid
)
3384 if (getegid() == gid
)
3387 ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
3388 assert(ngroups_max
> 0);
3390 gids
= alloca(sizeof(gid_t
) * ngroups_max
);
3392 r
= getgroups(ngroups_max
, gids
);
3396 for (i
= 0; i
< r
; i
++)
3403 int in_group(const char *name
) {
3407 r
= get_group_creds(&name
, &gid
);
3414 int glob_exists(const char *path
) {
3415 _cleanup_globfree_ glob_t g
= {};
3421 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
3423 if (k
== GLOB_NOMATCH
)
3425 else if (k
== GLOB_NOSPACE
)
3428 return !strv_isempty(g
.gl_pathv
);
3430 return errno
? -errno
: -EIO
;
3433 int glob_extend(char ***strv
, const char *path
) {
3434 _cleanup_globfree_ glob_t g
= {};
3439 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
3441 if (k
== GLOB_NOMATCH
)
3443 else if (k
== GLOB_NOSPACE
)
3445 else if (k
!= 0 || strv_isempty(g
.gl_pathv
))
3446 return errno
? -errno
: -EIO
;
3448 STRV_FOREACH(p
, g
.gl_pathv
) {
3449 k
= strv_extend(strv
, *p
);
3457 int dirent_ensure_type(DIR *d
, struct dirent
*de
) {
3463 if (de
->d_type
!= DT_UNKNOWN
)
3466 if (fstatat(dirfd(d
), de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
3470 S_ISREG(st
.st_mode
) ? DT_REG
:
3471 S_ISDIR(st
.st_mode
) ? DT_DIR
:
3472 S_ISLNK(st
.st_mode
) ? DT_LNK
:
3473 S_ISFIFO(st
.st_mode
) ? DT_FIFO
:
3474 S_ISSOCK(st
.st_mode
) ? DT_SOCK
:
3475 S_ISCHR(st
.st_mode
) ? DT_CHR
:
3476 S_ISBLK(st
.st_mode
) ? DT_BLK
:
3482 int get_files_in_directory(const char *path
, char ***list
) {
3483 _cleanup_closedir_
DIR *d
= NULL
;
3484 size_t bufsize
= 0, n
= 0;
3485 _cleanup_strv_free_
char **l
= NULL
;
3489 /* Returns all files in a directory in *list, and the number
3490 * of files as return value. If list is NULL returns only the
3502 if (!de
&& errno
!= 0)
3507 dirent_ensure_type(d
, de
);
3509 if (!dirent_is_file(de
))
3513 /* one extra slot is needed for the terminating NULL */
3514 if (!GREEDY_REALLOC(l
, bufsize
, n
+ 2))
3517 l
[n
] = strdup(de
->d_name
);
3528 l
= NULL
; /* avoid freeing */
3534 char *strjoin(const char *x
, ...) {
3548 t
= va_arg(ap
, const char *);
3553 if (n
> ((size_t) -1) - l
) {
3577 t
= va_arg(ap
, const char *);
3591 bool is_main_thread(void) {
3592 static thread_local
int cached
= 0;
3594 if (_unlikely_(cached
== 0))
3595 cached
= getpid() == gettid() ? 1 : -1;
3600 int block_get_whole_disk(dev_t d
, dev_t
*ret
) {
3607 /* If it has a queue this is good enough for us */
3608 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", major(d
), minor(d
)) < 0)
3611 r
= access(p
, F_OK
);
3619 /* If it is a partition find the originating device */
3620 if (asprintf(&p
, "/sys/dev/block/%u:%u/partition", major(d
), minor(d
)) < 0)
3623 r
= access(p
, F_OK
);
3629 /* Get parent dev_t */
3630 if (asprintf(&p
, "/sys/dev/block/%u:%u/../dev", major(d
), minor(d
)) < 0)
3633 r
= read_one_line_file(p
, &s
);
3639 r
= sscanf(s
, "%u:%u", &m
, &n
);
3645 /* Only return this if it is really good enough for us. */
3646 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", m
, n
) < 0)
3649 r
= access(p
, F_OK
);
3653 *ret
= makedev(m
, n
);
3660 static const char *const ioprio_class_table
[] = {
3661 [IOPRIO_CLASS_NONE
] = "none",
3662 [IOPRIO_CLASS_RT
] = "realtime",
3663 [IOPRIO_CLASS_BE
] = "best-effort",
3664 [IOPRIO_CLASS_IDLE
] = "idle"
3667 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, INT_MAX
);
3669 static const char *const sigchld_code_table
[] = {
3670 [CLD_EXITED
] = "exited",
3671 [CLD_KILLED
] = "killed",
3672 [CLD_DUMPED
] = "dumped",
3673 [CLD_TRAPPED
] = "trapped",
3674 [CLD_STOPPED
] = "stopped",
3675 [CLD_CONTINUED
] = "continued",
3678 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
3680 static const char *const log_facility_unshifted_table
[LOG_NFACILITIES
] = {
3681 [LOG_FAC(LOG_KERN
)] = "kern",
3682 [LOG_FAC(LOG_USER
)] = "user",
3683 [LOG_FAC(LOG_MAIL
)] = "mail",
3684 [LOG_FAC(LOG_DAEMON
)] = "daemon",
3685 [LOG_FAC(LOG_AUTH
)] = "auth",
3686 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
3687 [LOG_FAC(LOG_LPR
)] = "lpr",
3688 [LOG_FAC(LOG_NEWS
)] = "news",
3689 [LOG_FAC(LOG_UUCP
)] = "uucp",
3690 [LOG_FAC(LOG_CRON
)] = "cron",
3691 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
3692 [LOG_FAC(LOG_FTP
)] = "ftp",
3693 [LOG_FAC(LOG_LOCAL0
)] = "local0",
3694 [LOG_FAC(LOG_LOCAL1
)] = "local1",
3695 [LOG_FAC(LOG_LOCAL2
)] = "local2",
3696 [LOG_FAC(LOG_LOCAL3
)] = "local3",
3697 [LOG_FAC(LOG_LOCAL4
)] = "local4",
3698 [LOG_FAC(LOG_LOCAL5
)] = "local5",
3699 [LOG_FAC(LOG_LOCAL6
)] = "local6",
3700 [LOG_FAC(LOG_LOCAL7
)] = "local7"
3703 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted
, int, LOG_FAC(~0));
3705 static const char *const log_level_table
[] = {
3706 [LOG_EMERG
] = "emerg",
3707 [LOG_ALERT
] = "alert",
3708 [LOG_CRIT
] = "crit",
3710 [LOG_WARNING
] = "warning",
3711 [LOG_NOTICE
] = "notice",
3712 [LOG_INFO
] = "info",
3713 [LOG_DEBUG
] = "debug"
3716 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level
, int, LOG_DEBUG
);
3718 static const char* const sched_policy_table
[] = {
3719 [SCHED_OTHER
] = "other",
3720 [SCHED_BATCH
] = "batch",
3721 [SCHED_IDLE
] = "idle",
3722 [SCHED_FIFO
] = "fifo",
3726 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);
3728 static const char* const rlimit_table
[_RLIMIT_MAX
] = {
3729 [RLIMIT_CPU
] = "LimitCPU",
3730 [RLIMIT_FSIZE
] = "LimitFSIZE",
3731 [RLIMIT_DATA
] = "LimitDATA",
3732 [RLIMIT_STACK
] = "LimitSTACK",
3733 [RLIMIT_CORE
] = "LimitCORE",
3734 [RLIMIT_RSS
] = "LimitRSS",
3735 [RLIMIT_NOFILE
] = "LimitNOFILE",
3736 [RLIMIT_AS
] = "LimitAS",
3737 [RLIMIT_NPROC
] = "LimitNPROC",
3738 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
3739 [RLIMIT_LOCKS
] = "LimitLOCKS",
3740 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
3741 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
3742 [RLIMIT_NICE
] = "LimitNICE",
3743 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
3744 [RLIMIT_RTTIME
] = "LimitRTTIME"
3747 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
3749 static const char* const ip_tos_table
[] = {
3750 [IPTOS_LOWDELAY
] = "low-delay",
3751 [IPTOS_THROUGHPUT
] = "throughput",
3752 [IPTOS_RELIABILITY
] = "reliability",
3753 [IPTOS_LOWCOST
] = "low-cost",
3756 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
3758 bool kexec_loaded(void) {
3759 bool loaded
= false;
3762 if (read_one_line_file("/sys/kernel/kexec_loaded", &s
) >= 0) {
3770 int prot_from_flags(int flags
) {
3772 switch (flags
& O_ACCMODE
) {
3781 return PROT_READ
|PROT_WRITE
;
3788 char *format_bytes(char *buf
, size_t l
, off_t t
) {
3791 static const struct {
3795 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3796 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3797 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3798 { "G", 1024ULL*1024ULL*1024ULL },
3799 { "M", 1024ULL*1024ULL },
3803 if (t
== (off_t
) -1)
3806 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
3808 if (t
>= table
[i
].factor
) {
3811 (unsigned long long) (t
/ table
[i
].factor
),
3812 (unsigned long long) (((t
*10ULL) / table
[i
].factor
) % 10ULL),
3819 snprintf(buf
, l
, "%lluB", (unsigned long long) t
);
3827 void* memdup(const void *p
, size_t l
) {
3840 int fd_inc_sndbuf(int fd
, size_t n
) {
3842 socklen_t l
= sizeof(value
);
3844 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
3845 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
3848 /* If we have the privileges we will ignore the kernel limit. */
3851 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
3852 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
3858 int fd_inc_rcvbuf(int fd
, size_t n
) {
3860 socklen_t l
= sizeof(value
);
3862 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
3863 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
3866 /* If we have the privileges we will ignore the kernel limit. */
3869 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
3870 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
3875 int fork_agent(pid_t
*pid
, const int except
[], unsigned n_except
, const char *path
, ...) {
3876 bool stdout_is_tty
, stderr_is_tty
;
3877 pid_t parent_pid
, agent_pid
;
3878 sigset_t ss
, saved_ss
;
3886 /* Spawns a temporary TTY agent, making sure it goes away when
3889 parent_pid
= getpid();
3891 /* First we temporarily block all signals, so that the new
3892 * child has them blocked initially. This way, we can be sure
3893 * that SIGTERMs are not lost we might send to the agent. */
3894 assert_se(sigfillset(&ss
) >= 0);
3895 assert_se(sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) >= 0);
3898 if (agent_pid
< 0) {
3899 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
3903 if (agent_pid
!= 0) {
3904 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
3911 * Make sure the agent goes away when the parent dies */
3912 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
3913 _exit(EXIT_FAILURE
);
3915 /* Make sure we actually can kill the agent, if we need to, in
3916 * case somebody invoked us from a shell script that trapped
3917 * SIGTERM or so... */
3918 (void) reset_all_signal_handlers();
3919 (void) reset_signal_mask();
3921 /* Check whether our parent died before we were able
3922 * to set the death signal and unblock the signals */
3923 if (getppid() != parent_pid
)
3924 _exit(EXIT_SUCCESS
);
3926 /* Don't leak fds to the agent */
3927 close_all_fds(except
, n_except
);
3929 stdout_is_tty
= isatty(STDOUT_FILENO
);
3930 stderr_is_tty
= isatty(STDERR_FILENO
);
3932 if (!stdout_is_tty
|| !stderr_is_tty
) {
3935 /* Detach from stdout/stderr. and reopen
3936 * /dev/tty for them. This is important to
3937 * ensure that when systemctl is started via
3938 * popen() or a similar call that expects to
3939 * read EOF we actually do generate EOF and
3940 * not delay this indefinitely by because we
3941 * keep an unused copy of stdin around. */
3942 fd
= open("/dev/tty", O_WRONLY
);
3944 log_error_errno(errno
, "Failed to open /dev/tty: %m");
3945 _exit(EXIT_FAILURE
);
3949 dup2(fd
, STDOUT_FILENO
);
3952 dup2(fd
, STDERR_FILENO
);
3958 /* Count arguments */
3960 for (n
= 0; va_arg(ap
, char*); n
++)
3965 l
= alloca(sizeof(char *) * (n
+ 1));
3967 /* Fill in arguments */
3969 for (i
= 0; i
<= n
; i
++)
3970 l
[i
] = va_arg(ap
, char*);
3974 _exit(EXIT_FAILURE
);
3977 int setrlimit_closest(int resource
, const struct rlimit
*rlim
) {
3978 struct rlimit highest
, fixed
;
3982 if (setrlimit(resource
, rlim
) >= 0)
3988 /* So we failed to set the desired setrlimit, then let's try
3989 * to get as close as we can */
3990 assert_se(getrlimit(resource
, &highest
) == 0);
3992 fixed
.rlim_cur
= MIN(rlim
->rlim_cur
, highest
.rlim_max
);
3993 fixed
.rlim_max
= MIN(rlim
->rlim_max
, highest
.rlim_max
);
3995 if (setrlimit(resource
, &fixed
) < 0)
4001 bool http_etag_is_valid(const char *etag
) {
4005 if (!endswith(etag
, "\""))
4008 if (!startswith(etag
, "\"") && !startswith(etag
, "W/\""))
4014 bool http_url_is_valid(const char *url
) {
4020 p
= startswith(url
, "http://");
4022 p
= startswith(url
, "https://");
4029 return ascii_is_valid(p
);
4032 bool documentation_url_is_valid(const char *url
) {
4038 if (http_url_is_valid(url
))
4041 p
= startswith(url
, "file:/");
4043 p
= startswith(url
, "info:");
4045 p
= startswith(url
, "man:");
4050 return ascii_is_valid(p
);
4053 bool in_initrd(void) {
4054 static int saved
= -1;
4060 /* We make two checks here:
4062 * 1. the flag file /etc/initrd-release must exist
4063 * 2. the root file system must be a memory file system
4065 * The second check is extra paranoia, since misdetecting an
4066 * initrd can have bad bad consequences due the initrd
4067 * emptying when transititioning to the main systemd.
4070 saved
= access("/etc/initrd-release", F_OK
) >= 0 &&
4071 statfs("/", &s
) >= 0 &&
4072 is_temporary_fs(&s
);
4077 int get_home_dir(char **_h
) {
4085 /* Take the user specified one */
4086 e
= secure_getenv("HOME");
4087 if (e
&& path_is_absolute(e
)) {
4096 /* Hardcode home directory for root to avoid NSS */
4099 h
= strdup("/root");
4107 /* Check the database... */
4111 return errno
> 0 ? -errno
: -ESRCH
;
4113 if (!path_is_absolute(p
->pw_dir
))
4116 h
= strdup(p
->pw_dir
);
4124 int get_shell(char **_s
) {
4132 /* Take the user specified one */
4133 e
= getenv("SHELL");
4143 /* Hardcode home directory for root to avoid NSS */
4146 s
= strdup("/bin/sh");
4154 /* Check the database... */
4158 return errno
> 0 ? -errno
: -ESRCH
;
4160 if (!path_is_absolute(p
->pw_shell
))
4163 s
= strdup(p
->pw_shell
);
4171 bool filename_is_valid(const char *p
) {
4185 if (strlen(p
) > FILENAME_MAX
)
4191 bool string_is_safe(const char *p
) {
4197 for (t
= p
; *t
; t
++) {
4198 if (*t
> 0 && *t
< ' ')
4201 if (strchr("\\\"\'\x7f", *t
))
4209 * Check if a string contains control characters. If 'ok' is non-NULL
4210 * it may be a string containing additional CCs to be considered OK.
4212 bool string_has_cc(const char *p
, const char *ok
) {
4217 for (t
= p
; *t
; t
++) {
4218 if (ok
&& strchr(ok
, *t
))
4221 if (*t
> 0 && *t
< ' ')
4231 bool path_is_safe(const char *p
) {
4236 if (streq(p
, "..") || startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
4239 if (strlen(p
)+1 > PATH_MAX
)
4242 /* The following two checks are not really dangerous, but hey, they still are confusing */
4243 if (streq(p
, ".") || startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
4246 if (strstr(p
, "//"))
4252 /* hey glibc, APIs with callbacks without a user pointer are so useless */
4253 void *xbsearch_r(const void *key
, const void *base
, size_t nmemb
, size_t size
,
4254 int (*compar
) (const void *, const void *, void *), void *arg
) {
4263 p
= (void *)(((const char *) base
) + (idx
* size
));
4264 comparison
= compar(key
, p
, arg
);
4267 else if (comparison
> 0)
4275 void init_gettext(void) {
4276 setlocale(LC_ALL
, "");
4277 textdomain(GETTEXT_PACKAGE
);
4280 bool is_locale_utf8(void) {
4282 static int cached_answer
= -1;
4284 if (cached_answer
>= 0)
4287 if (!setlocale(LC_ALL
, "")) {
4288 cached_answer
= true;
4292 set
= nl_langinfo(CODESET
);
4294 cached_answer
= true;
4298 if (streq(set
, "UTF-8")) {
4299 cached_answer
= true;
4303 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
4304 * unset and everything can do to UTF-8 nowadays. */
4305 set
= setlocale(LC_CTYPE
, NULL
);
4307 cached_answer
= true;
4311 /* Check result, but ignore the result if C was set
4314 STR_IN_SET(set
, "C", "POSIX") &&
4315 !getenv("LC_ALL") &&
4316 !getenv("LC_CTYPE") &&
4320 return (bool) cached_answer
;
4323 const char *draw_special_char(DrawSpecialChar ch
) {
4324 static const char *draw_table
[2][_DRAW_SPECIAL_CHAR_MAX
] = {
4327 [DRAW_TREE_VERTICAL
] = "\342\224\202 ", /* │ */
4328 [DRAW_TREE_BRANCH
] = "\342\224\234\342\224\200", /* ├─ */
4329 [DRAW_TREE_RIGHT
] = "\342\224\224\342\224\200", /* └─ */
4330 [DRAW_TREE_SPACE
] = " ", /* */
4331 [DRAW_TRIANGULAR_BULLET
] = "\342\200\243", /* ‣ */
4332 [DRAW_BLACK_CIRCLE
] = "\342\227\217", /* ● */
4333 [DRAW_ARROW
] = "\342\206\222", /* → */
4334 [DRAW_DASH
] = "\342\200\223", /* – */
4337 /* ASCII fallback */ {
4338 [DRAW_TREE_VERTICAL
] = "| ",
4339 [DRAW_TREE_BRANCH
] = "|-",
4340 [DRAW_TREE_RIGHT
] = "`-",
4341 [DRAW_TREE_SPACE
] = " ",
4342 [DRAW_TRIANGULAR_BULLET
] = ">",
4343 [DRAW_BLACK_CIRCLE
] = "*",
4344 [DRAW_ARROW
] = "->",
4349 return draw_table
[!is_locale_utf8()][ch
];
4352 char *strreplace(const char *text
, const char *old_string
, const char *new_string
) {
4355 size_t l
, old_len
, new_len
;
4361 old_len
= strlen(old_string
);
4362 new_len
= strlen(new_string
);
4375 if (!startswith(f
, old_string
)) {
4381 nl
= l
- old_len
+ new_len
;
4382 a
= realloc(r
, nl
+ 1);
4390 t
= stpcpy(t
, new_string
);
4402 char *strip_tab_ansi(char **ibuf
, size_t *_isz
) {
4403 const char *i
, *begin
= NULL
;
4408 } state
= STATE_OTHER
;
4410 size_t osz
= 0, isz
;
4416 /* Strips ANSI color and replaces TABs by 8 spaces */
4418 isz
= _isz
? *_isz
: strlen(*ibuf
);
4420 f
= open_memstream(&obuf
, &osz
);
4424 for (i
= *ibuf
; i
< *ibuf
+ isz
+ 1; i
++) {
4429 if (i
>= *ibuf
+ isz
) /* EOT */
4431 else if (*i
== '\x1B')
4432 state
= STATE_ESCAPE
;
4433 else if (*i
== '\t')
4440 if (i
>= *ibuf
+ isz
) { /* EOT */
4443 } else if (*i
== '[') {
4444 state
= STATE_BRACKET
;
4449 state
= STATE_OTHER
;
4456 if (i
>= *ibuf
+ isz
|| /* EOT */
4457 (!(*i
>= '0' && *i
<= '9') && *i
!= ';' && *i
!= 'm')) {
4460 state
= STATE_OTHER
;
4462 } else if (*i
== 'm')
4463 state
= STATE_OTHER
;
4485 int on_ac_power(void) {
4486 bool found_offline
= false, found_online
= false;
4487 _cleanup_closedir_
DIR *d
= NULL
;
4489 d
= opendir("/sys/class/power_supply");
4491 return errno
== ENOENT
? true : -errno
;
4495 _cleanup_close_
int fd
= -1, device
= -1;
4501 if (!de
&& errno
!= 0)
4507 if (hidden_file(de
->d_name
))
4510 device
= openat(dirfd(d
), de
->d_name
, O_DIRECTORY
|O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4512 if (errno
== ENOENT
|| errno
== ENOTDIR
)
4518 fd
= openat(device
, "type", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4520 if (errno
== ENOENT
)
4526 n
= read(fd
, contents
, sizeof(contents
));
4530 if (n
!= 6 || memcmp(contents
, "Mains\n", 6))
4534 fd
= openat(device
, "online", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4536 if (errno
== ENOENT
)
4542 n
= read(fd
, contents
, sizeof(contents
));
4546 if (n
!= 2 || contents
[1] != '\n')
4549 if (contents
[0] == '1') {
4550 found_online
= true;
4552 } else if (contents
[0] == '0')
4553 found_offline
= true;
4558 return found_online
|| !found_offline
;
4561 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
4568 if (!path_strv_resolve_uniq(search
, root
))
4571 STRV_FOREACH(i
, search
) {
4572 _cleanup_free_
char *p
= NULL
;
4576 p
= strjoin(root
, *i
, "/", path
, NULL
);
4578 p
= strjoin(*i
, "/", path
, NULL
);
4588 if (errno
!= ENOENT
)
4595 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
4596 _cleanup_strv_free_
char **copy
= NULL
;
4602 if (path_is_absolute(path
)) {
4605 f
= fopen(path
, mode
);
4614 copy
= strv_copy((char**) search
);
4618 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
4621 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
4622 _cleanup_strv_free_
char **s
= NULL
;
4624 if (path_is_absolute(path
)) {
4627 f
= fopen(path
, mode
);
4636 s
= strv_split_nulstr(search
);
4640 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
4643 char *strextend(char **x
, ...) {
4650 l
= f
= *x
? strlen(*x
) : 0;
4657 t
= va_arg(ap
, const char *);
4662 if (n
> ((size_t) -1) - l
) {
4671 r
= realloc(*x
, l
+1);
4681 t
= va_arg(ap
, const char *);
4695 char *strrep(const char *s
, unsigned n
) {
4703 p
= r
= malloc(l
* n
+ 1);
4707 for (i
= 0; i
< n
; i
++)
4714 void* greedy_realloc(void **p
, size_t *allocated
, size_t need
, size_t size
) {
4721 if (*allocated
>= need
)
4724 newalloc
= MAX(need
* 2, 64u / size
);
4725 a
= newalloc
* size
;
4727 /* check for overflows */
4728 if (a
< size
* need
)
4736 *allocated
= newalloc
;
4740 void* greedy_realloc0(void **p
, size_t *allocated
, size_t need
, size_t size
) {
4749 q
= greedy_realloc(p
, allocated
, need
, size
);
4753 if (*allocated
> prev
)
4754 memzero(q
+ prev
* size
, (*allocated
- prev
) * size
);
4759 bool id128_is_valid(const char *s
) {
4765 /* Simple formatted 128bit hex string */
4767 for (i
= 0; i
< l
; i
++) {
4770 if (!(c
>= '0' && c
<= '9') &&
4771 !(c
>= 'a' && c
<= 'z') &&
4772 !(c
>= 'A' && c
<= 'Z'))
4776 } else if (l
== 36) {
4778 /* Formatted UUID */
4780 for (i
= 0; i
< l
; i
++) {
4783 if ((i
== 8 || i
== 13 || i
== 18 || i
== 23)) {
4787 if (!(c
>= '0' && c
<= '9') &&
4788 !(c
>= 'a' && c
<= 'z') &&
4789 !(c
>= 'A' && c
<= 'Z'))
4800 int split_pair(const char *s
, const char *sep
, char **l
, char **r
) {
4815 a
= strndup(s
, x
- s
);
4819 b
= strdup(x
+ strlen(sep
));
4831 int shall_restore_state(void) {
4832 _cleanup_free_
char *value
= NULL
;
4835 r
= get_proc_cmdline_key("systemd.restore_state=", &value
);
4841 return parse_boolean(value
) != 0;
4844 int proc_cmdline(char **ret
) {
4847 if (detect_container() > 0)
4848 return get_process_cmdline(1, 0, false, ret
);
4850 return read_one_line_file("/proc/cmdline", ret
);
4853 int parse_proc_cmdline(int (*parse_item
)(const char *key
, const char *value
)) {
4854 _cleanup_free_
char *line
= NULL
;
4860 r
= proc_cmdline(&line
);
4866 _cleanup_free_
char *word
= NULL
;
4869 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
4875 /* Filter out arguments that are intended only for the
4877 if (!in_initrd() && startswith(word
, "rd."))
4880 value
= strchr(word
, '=');
4884 r
= parse_item(word
, value
);
4892 int get_proc_cmdline_key(const char *key
, char **value
) {
4893 _cleanup_free_
char *line
= NULL
, *ret
= NULL
;
4900 r
= proc_cmdline(&line
);
4906 _cleanup_free_
char *word
= NULL
;
4909 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
4915 /* Filter out arguments that are intended only for the
4917 if (!in_initrd() && startswith(word
, "rd."))
4921 e
= startswith(word
, key
);
4925 r
= free_and_strdup(&ret
, e
);
4931 if (streq(word
, key
))
4945 int container_get_leader(const char *machine
, pid_t
*pid
) {
4946 _cleanup_free_
char *s
= NULL
, *class = NULL
;
4954 if (!machine_name_is_valid(machine
))
4957 p
= strjoina("/run/systemd/machines/", machine
);
4958 r
= parse_env_file(p
, NEWLINE
, "LEADER", &s
, "CLASS", &class, NULL
);
4966 if (!streq_ptr(class, "container"))
4969 r
= parse_pid(s
, &leader
);
4979 int namespace_open(pid_t pid
, int *pidns_fd
, int *mntns_fd
, int *netns_fd
, int *userns_fd
, int *root_fd
) {
4980 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, netnsfd
= -1, usernsfd
= -1;
4988 mntns
= procfs_file_alloca(pid
, "ns/mnt");
4989 mntnsfd
= open(mntns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
4997 pidns
= procfs_file_alloca(pid
, "ns/pid");
4998 pidnsfd
= open(pidns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5006 netns
= procfs_file_alloca(pid
, "ns/net");
5007 netnsfd
= open(netns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5015 userns
= procfs_file_alloca(pid
, "ns/user");
5016 usernsfd
= open(userns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5017 if (usernsfd
< 0 && errno
!= ENOENT
)
5024 root
= procfs_file_alloca(pid
, "root");
5025 rfd
= open(root
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
|O_DIRECTORY
);
5031 *pidns_fd
= pidnsfd
;
5034 *mntns_fd
= mntnsfd
;
5037 *netns_fd
= netnsfd
;
5040 *userns_fd
= usernsfd
;
5045 pidnsfd
= mntnsfd
= netnsfd
= usernsfd
= -1;
5050 int namespace_enter(int pidns_fd
, int mntns_fd
, int netns_fd
, int userns_fd
, int root_fd
) {
5051 if (userns_fd
>= 0) {
5052 /* Can't setns to your own userns, since then you could
5053 * escalate from non-root to root in your own namespace, so
5054 * check if namespaces equal before attempting to enter. */
5055 _cleanup_free_
char *userns_fd_path
= NULL
;
5057 if (asprintf(&userns_fd_path
, "/proc/self/fd/%d", userns_fd
) < 0)
5060 r
= files_same(userns_fd_path
, "/proc/self/ns/user");
5068 if (setns(pidns_fd
, CLONE_NEWPID
) < 0)
5072 if (setns(mntns_fd
, CLONE_NEWNS
) < 0)
5076 if (setns(netns_fd
, CLONE_NEWNET
) < 0)
5080 if (setns(userns_fd
, CLONE_NEWUSER
) < 0)
5084 if (fchdir(root_fd
) < 0)
5087 if (chroot(".") < 0)
5091 return reset_uid_gid();
5094 int getpeercred(int fd
, struct ucred
*ucred
) {
5095 socklen_t n
= sizeof(struct ucred
);
5102 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
);
5106 if (n
!= sizeof(struct ucred
))
5109 /* Check if the data is actually useful and not suppressed due
5110 * to namespacing issues */
5113 if (u
.uid
== UID_INVALID
)
5115 if (u
.gid
== GID_INVALID
)
5122 int getpeersec(int fd
, char **ret
) {
5134 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
5138 if (errno
!= ERANGE
)
5145 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
5161 /* This is much like like mkostemp() but is subject to umask(). */
5162 int mkostemp_safe(char *pattern
, int flags
) {
5163 _cleanup_umask_ mode_t u
;
5170 fd
= mkostemp(pattern
, flags
);
5177 int open_tmpfile(const char *path
, int flags
) {
5184 /* Try O_TMPFILE first, if it is supported */
5185 fd
= open(path
, flags
|O_TMPFILE
|O_EXCL
, S_IRUSR
|S_IWUSR
);
5190 /* Fall back to unguessable name + unlinking */
5191 p
= strjoina(path
, "/systemd-tmp-XXXXXX");
5193 fd
= mkostemp_safe(p
, flags
);
5201 int fd_warn_permissions(const char *path
, int fd
) {
5204 if (fstat(fd
, &st
) < 0)
5207 if (st
.st_mode
& 0111)
5208 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path
);
5210 if (st
.st_mode
& 0002)
5211 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path
);
5213 if (getpid() == 1 && (st
.st_mode
& 0044) != 0044)
5214 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
);
5219 unsigned long personality_from_string(const char *p
) {
5221 /* Parse a personality specifier. We introduce our own
5222 * identifiers that indicate specific ABIs, rather than just
5223 * hints regarding the register size, since we want to keep
5224 * things open for multiple locally supported ABIs for the
5225 * same register size. We try to reuse the ABI identifiers
5226 * used by libseccomp. */
5228 #if defined(__x86_64__)
5230 if (streq(p
, "x86"))
5233 if (streq(p
, "x86-64"))
5236 #elif defined(__i386__)
5238 if (streq(p
, "x86"))
5242 return PERSONALITY_INVALID
;
5245 const char* personality_to_string(unsigned long p
) {
5247 #if defined(__x86_64__)
5249 if (p
== PER_LINUX32
)
5255 #elif defined(__i386__)
5264 uint64_t physical_memory(void) {
5267 /* We return this as uint64_t in case we are running as 32bit
5268 * process on a 64bit kernel with huge amounts of memory */
5270 mem
= sysconf(_SC_PHYS_PAGES
);
5273 return (uint64_t) mem
* (uint64_t) page_size();
5276 void hexdump(FILE *f
, const void *p
, size_t s
) {
5277 const uint8_t *b
= p
;
5280 assert(s
== 0 || b
);
5285 fprintf(f
, "%04x ", n
);
5287 for (i
= 0; i
< 16; i
++) {
5292 fprintf(f
, "%02x ", b
[i
]);
5300 for (i
= 0; i
< 16; i
++) {
5305 fputc(isprint(b
[i
]) ? (char) b
[i
] : '.', f
);
5319 int update_reboot_param_file(const char *param
) {
5324 r
= write_string_file(REBOOT_PARAM_FILE
, param
, WRITE_STRING_FILE_CREATE
);
5326 log_error("Failed to write reboot param to "
5327 REBOOT_PARAM_FILE
": %s", strerror(-r
));
5329 unlink(REBOOT_PARAM_FILE
);
5334 int umount_recursive(const char *prefix
, int flags
) {
5338 /* Try to umount everything recursively below a
5339 * directory. Also, take care of stacked mounts, and keep
5340 * unmounting them until they are gone. */
5343 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
5348 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
5349 if (!proc_self_mountinfo
)
5353 _cleanup_free_
char *path
= NULL
, *p
= NULL
;
5356 k
= fscanf(proc_self_mountinfo
,
5357 "%*s " /* (1) mount id */
5358 "%*s " /* (2) parent id */
5359 "%*s " /* (3) major:minor */
5360 "%*s " /* (4) root */
5361 "%ms " /* (5) mount point */
5362 "%*s" /* (6) mount options */
5363 "%*[^-]" /* (7) optional fields */
5364 "- " /* (8) separator */
5365 "%*s " /* (9) file system type */
5366 "%*s" /* (10) mount source */
5367 "%*s" /* (11) mount options 2 */
5368 "%*[^\n]", /* some rubbish at the end */
5377 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
5381 if (!path_startswith(p
, prefix
))
5384 if (umount2(p
, flags
) < 0) {
5400 static int get_mount_flags(const char *path
, unsigned long *flags
) {
5403 if (statvfs(path
, &buf
) < 0)
5405 *flags
= buf
.f_flag
;
5409 int bind_remount_recursive(const char *prefix
, bool ro
) {
5410 _cleanup_set_free_free_ Set
*done
= NULL
;
5411 _cleanup_free_
char *cleaned
= NULL
;
5414 /* Recursively remount a directory (and all its submounts)
5415 * read-only or read-write. If the directory is already
5416 * mounted, we reuse the mount and simply mark it
5417 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
5418 * operation). If it isn't we first make it one. Afterwards we
5419 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
5420 * submounts we can access, too. When mounts are stacked on
5421 * the same mount point we only care for each individual
5422 * "top-level" mount on each point, as we cannot
5423 * influence/access the underlying mounts anyway. We do not
5424 * have any effect on future submounts that might get
5425 * propagated, they migt be writable. This includes future
5426 * submounts that have been triggered via autofs. */
5428 cleaned
= strdup(prefix
);
5432 path_kill_slashes(cleaned
);
5434 done
= set_new(&string_hash_ops
);
5439 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
5440 _cleanup_set_free_free_ Set
*todo
= NULL
;
5441 bool top_autofs
= false;
5443 unsigned long orig_flags
;
5445 todo
= set_new(&string_hash_ops
);
5449 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
5450 if (!proc_self_mountinfo
)
5454 _cleanup_free_
char *path
= NULL
, *p
= NULL
, *type
= NULL
;
5457 k
= fscanf(proc_self_mountinfo
,
5458 "%*s " /* (1) mount id */
5459 "%*s " /* (2) parent id */
5460 "%*s " /* (3) major:minor */
5461 "%*s " /* (4) root */
5462 "%ms " /* (5) mount point */
5463 "%*s" /* (6) mount options (superblock) */
5464 "%*[^-]" /* (7) optional fields */
5465 "- " /* (8) separator */
5466 "%ms " /* (9) file system type */
5467 "%*s" /* (10) mount source */
5468 "%*s" /* (11) mount options (bind mount) */
5469 "%*[^\n]", /* some rubbish at the end */
5479 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
5483 /* Let's ignore autofs mounts. If they aren't
5484 * triggered yet, we want to avoid triggering
5485 * them, as we don't make any guarantees for
5486 * future submounts anyway. If they are
5487 * already triggered, then we will find
5488 * another entry for this. */
5489 if (streq(type
, "autofs")) {
5490 top_autofs
= top_autofs
|| path_equal(cleaned
, p
);
5494 if (path_startswith(p
, cleaned
) &&
5495 !set_contains(done
, p
)) {
5497 r
= set_consume(todo
, p
);
5507 /* If we have no submounts to process anymore and if
5508 * the root is either already done, or an autofs, we
5510 if (set_isempty(todo
) &&
5511 (top_autofs
|| set_contains(done
, cleaned
)))
5514 if (!set_contains(done
, cleaned
) &&
5515 !set_contains(todo
, cleaned
)) {
5516 /* The prefix directory itself is not yet a
5517 * mount, make it one. */
5518 if (mount(cleaned
, cleaned
, NULL
, MS_BIND
|MS_REC
, NULL
) < 0)
5522 (void) get_mount_flags(cleaned
, &orig_flags
);
5523 orig_flags
&= ~MS_RDONLY
;
5525 if (mount(NULL
, prefix
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0)
5528 x
= strdup(cleaned
);
5532 r
= set_consume(done
, x
);
5537 while ((x
= set_steal_first(todo
))) {
5539 r
= set_consume(done
, x
);
5540 if (r
== -EEXIST
|| r
== 0)
5545 /* Try to reuse the original flag set, but
5546 * don't care for errors, in case of
5547 * obstructed mounts */
5549 (void) get_mount_flags(x
, &orig_flags
);
5550 orig_flags
&= ~MS_RDONLY
;
5552 if (mount(NULL
, x
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0) {
5554 /* Deal with mount points that are
5555 * obstructed by a later mount */
5557 if (errno
!= ENOENT
)
5565 int fflush_and_check(FILE *f
) {
5572 return errno
? -errno
: -EIO
;
5577 int tempfn_xxxxxx(const char *p
, const char *extra
, char **ret
) {
5589 * /foo/bar/.#<extra>waldoXXXXXX
5593 if (!filename_is_valid(fn
))
5599 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 6 + 1);
5603 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
), "XXXXXX");
5605 *ret
= path_kill_slashes(t
);
5609 int tempfn_random(const char *p
, const char *extra
, char **ret
) {
5623 * /foo/bar/.#<extra>waldobaa2a261115984a9
5627 if (!filename_is_valid(fn
))
5633 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 16 + 1);
5637 x
= stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
);
5640 for (i
= 0; i
< 16; i
++) {
5641 *(x
++) = hexchar(u
& 0xF);
5647 *ret
= path_kill_slashes(t
);
5651 int tempfn_random_child(const char *p
, const char *extra
, char **ret
) {
5662 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
5668 t
= new(char, strlen(p
) + 3 + strlen(extra
) + 16 + 1);
5672 x
= stpcpy(stpcpy(stpcpy(t
, p
), "/.#"), extra
);
5675 for (i
= 0; i
< 16; i
++) {
5676 *(x
++) = hexchar(u
& 0xF);
5682 *ret
= path_kill_slashes(t
);
5686 int take_password_lock(const char *root
) {
5688 struct flock flock
= {
5690 .l_whence
= SEEK_SET
,
5698 /* This is roughly the same as lckpwdf(), but not as awful. We
5699 * don't want to use alarm() and signals, hence we implement
5700 * our own trivial version of this.
5702 * Note that shadow-utils also takes per-database locks in
5703 * addition to lckpwdf(). However, we don't given that they
5704 * are redundant as they they invoke lckpwdf() first and keep
5705 * it during everything they do. The per-database locks are
5706 * awfully racy, and thus we just won't do them. */
5709 path
= strjoina(root
, "/etc/.pwd.lock");
5711 path
= "/etc/.pwd.lock";
5713 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
5717 r
= fcntl(fd
, F_SETLKW
, &flock
);
5726 int is_symlink(const char *path
) {
5729 if (lstat(path
, &info
) < 0)
5732 return !!S_ISLNK(info
.st_mode
);
5735 int is_dir(const char* path
, bool follow
) {
5740 r
= stat(path
, &st
);
5742 r
= lstat(path
, &st
);
5746 return !!S_ISDIR(st
.st_mode
);
5749 int is_device_node(const char *path
) {
5752 if (lstat(path
, &info
) < 0)
5755 return !!(S_ISBLK(info
.st_mode
) || S_ISCHR(info
.st_mode
));
5758 int extract_first_word(const char **p
, char **ret
, const char *separators
, ExtractFlags flags
) {
5759 _cleanup_free_
char *s
= NULL
;
5760 size_t allocated
= 0, sz
= 0;
5768 SINGLE_QUOTE_ESCAPE
,
5770 DOUBLE_QUOTE_ESCAPE
,
5778 separators
= WHITESPACE
;
5780 /* Bail early if called after last value or with no input */
5782 goto finish_force_terminate
;
5784 /* Parses the first word of a string, and returns it in
5785 * *ret. Removes all quotes in the process. When parsing fails
5786 * (because of an uneven number of quotes or similar), leaves
5787 * the pointer *p at the first invalid character. */
5795 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
)
5796 if (!GREEDY_REALLOC(s
, allocated
, sz
+1))
5800 goto finish_force_terminate
;
5801 else if (strchr(separators
, c
)) {
5802 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
) {
5804 goto finish_force_next
;
5809 /* We found a non-blank character, so we will always
5810 * want to return a string (even if it is empty),
5811 * allocate it here. */
5812 if (!GREEDY_REALLOC(s
, allocated
, sz
+1))
5820 goto finish_force_terminate
;
5821 else if (c
== '\'' && (flags
& EXTRACT_QUOTES
))
5822 state
= SINGLE_QUOTE
;
5824 state
= VALUE_ESCAPE
;
5825 else if (c
== '\"' && (flags
& EXTRACT_QUOTES
))
5826 state
= DOUBLE_QUOTE
;
5827 else if (strchr(separators
, c
)) {
5828 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
) {
5830 goto finish_force_next
;
5834 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5844 if (flags
& EXTRACT_RELAX
)
5845 goto finish_force_terminate
;
5847 } else if (c
== '\'')
5850 state
= SINGLE_QUOTE_ESCAPE
;
5852 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5866 state
= DOUBLE_QUOTE_ESCAPE
;
5868 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5876 case SINGLE_QUOTE_ESCAPE
:
5877 case DOUBLE_QUOTE_ESCAPE
:
5879 if (!GREEDY_REALLOC(s
, allocated
, sz
+7))
5883 if ((flags
& EXTRACT_CUNESCAPE_RELAX
) &&
5884 (state
== VALUE_ESCAPE
|| flags
& EXTRACT_RELAX
)) {
5885 /* If we find an unquoted trailing backslash and we're in
5886 * EXTRACT_CUNESCAPE_RELAX mode, keep it verbatim in the
5889 * Unbalanced quotes will only be allowed in EXTRACT_RELAX
5890 * mode, EXTRACT_CUNESCAPE_RELAX mode does not allow them.
5893 goto finish_force_terminate
;
5895 if (flags
& EXTRACT_RELAX
)
5896 goto finish_force_terminate
;
5900 if (flags
& EXTRACT_CUNESCAPE
) {
5903 r
= cunescape_one(*p
, (size_t) -1, &c
, &u
);
5905 if (flags
& EXTRACT_CUNESCAPE_RELAX
) {
5916 s
[sz
++] = c
; /* normal explicit char */
5918 sz
+= utf8_encode_unichar(s
+ sz
, u
); /* unicode chars we'll encode as utf8 */
5923 state
= (state
== SINGLE_QUOTE_ESCAPE
) ? SINGLE_QUOTE
:
5924 (state
== DOUBLE_QUOTE_ESCAPE
) ? DOUBLE_QUOTE
:
5930 goto finish_force_terminate
;
5931 if (!strchr(separators
, c
))
5939 finish_force_terminate
:
5956 int extract_first_word_and_warn(
5959 const char *separators
,
5962 const char *filename
,
5964 const char *rvalue
) {
5965 /* Try to unquote it, if it fails, warn about it and try again but this
5966 * time using EXTRACT_CUNESCAPE_RELAX to keep the backslashes verbatim
5967 * in invalid escape sequences. */
5972 r
= extract_first_word(p
, ret
, separators
, flags
);
5973 if (r
< 0 && !(flags
&EXTRACT_CUNESCAPE_RELAX
)) {
5974 /* Retry it with EXTRACT_CUNESCAPE_RELAX. */
5976 r
= extract_first_word(p
, ret
, separators
, flags
|EXTRACT_CUNESCAPE_RELAX
);
5978 log_syntax(unit
, LOG_ERR
, filename
, line
, EINVAL
,
5979 "Unbalanced quoting in command line, ignoring: \"%s\"", rvalue
);
5981 log_syntax(unit
, LOG_WARNING
, filename
, line
, EINVAL
,
5982 "Invalid escape sequences in command line: \"%s\"", rvalue
);
5987 int extract_many_words(const char **p
, const char *separators
, ExtractFlags flags
, ...) {
5992 /* Parses a number of words from a string, stripping any
5993 * quotes if necessary. */
5997 /* Count how many words are expected */
5998 va_start(ap
, flags
);
6000 if (!va_arg(ap
, char **))
6009 /* Read all words into a temporary array */
6010 l
= newa0(char*, n
);
6011 for (c
= 0; c
< n
; c
++) {
6013 r
= extract_first_word(p
, &l
[c
], separators
, flags
);
6017 for (j
= 0; j
< c
; j
++)
6027 /* If we managed to parse all words, return them in the passed
6029 va_start(ap
, flags
);
6030 for (i
= 0; i
< n
; i
++) {
6033 v
= va_arg(ap
, char **);
6043 int free_and_strdup(char **p
, const char *s
) {
6048 /* Replaces a string pointer with an strdup()ed new string,
6049 * possibly freeing the old one. */
6051 if (streq_ptr(*p
, s
))
6067 int ptsname_malloc(int fd
, char **ret
) {
6080 if (ptsname_r(fd
, c
, l
) == 0) {
6084 if (errno
!= ERANGE
) {
6094 int openpt_in_namespace(pid_t pid
, int flags
) {
6095 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, usernsfd
= -1, rootfd
= -1;
6096 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
6098 struct cmsghdr cmsghdr
;
6099 uint8_t buf
[CMSG_SPACE(sizeof(int))];
6101 struct msghdr mh
= {
6102 .msg_control
= &control
,
6103 .msg_controllen
= sizeof(control
),
6105 struct cmsghdr
*cmsg
;
6112 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &usernsfd
, &rootfd
);
6116 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
6126 pair
[0] = safe_close(pair
[0]);
6128 r
= namespace_enter(pidnsfd
, mntnsfd
, -1, usernsfd
, rootfd
);
6130 _exit(EXIT_FAILURE
);
6132 master
= posix_openpt(flags
);
6134 _exit(EXIT_FAILURE
);
6136 if (unlockpt(master
) < 0)
6137 _exit(EXIT_FAILURE
);
6139 cmsg
= CMSG_FIRSTHDR(&mh
);
6140 cmsg
->cmsg_level
= SOL_SOCKET
;
6141 cmsg
->cmsg_type
= SCM_RIGHTS
;
6142 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
6143 memcpy(CMSG_DATA(cmsg
), &master
, sizeof(int));
6145 mh
.msg_controllen
= cmsg
->cmsg_len
;
6147 if (sendmsg(pair
[1], &mh
, MSG_NOSIGNAL
) < 0)
6148 _exit(EXIT_FAILURE
);
6150 _exit(EXIT_SUCCESS
);
6153 pair
[1] = safe_close(pair
[1]);
6155 r
= wait_for_terminate(child
, &si
);
6158 if (si
.si_code
!= CLD_EXITED
|| si
.si_status
!= EXIT_SUCCESS
)
6161 if (recvmsg(pair
[0], &mh
, MSG_NOSIGNAL
|MSG_CMSG_CLOEXEC
) < 0)
6164 CMSG_FOREACH(cmsg
, &mh
)
6165 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
) {
6169 fds
= (int*) CMSG_DATA(cmsg
);
6170 n_fds
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
6173 close_many(fds
, n_fds
);
6183 ssize_t
fgetxattrat_fake(int dirfd
, const char *filename
, const char *attribute
, void *value
, size_t size
, int flags
) {
6184 _cleanup_close_
int fd
= -1;
6187 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
6189 fd
= openat(dirfd
, filename
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOATIME
|(flags
& AT_SYMLINK_NOFOLLOW
? O_NOFOLLOW
: 0));
6193 l
= fgetxattr(fd
, attribute
, value
, size
);
6200 static int parse_crtime(le64_t le
, usec_t
*usec
) {
6206 if (u
== 0 || u
== (uint64_t) -1)
6213 int fd_getcrtime(int fd
, usec_t
*usec
) {
6220 /* Until Linux gets a real concept of birthtime/creation time,
6221 * let's fake one with xattrs */
6223 n
= fgetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
));
6226 if (n
!= sizeof(le
))
6229 return parse_crtime(le
, usec
);
6232 int fd_getcrtime_at(int dirfd
, const char *name
, usec_t
*usec
, int flags
) {
6236 n
= fgetxattrat_fake(dirfd
, name
, "user.crtime_usec", &le
, sizeof(le
), flags
);
6239 if (n
!= sizeof(le
))
6242 return parse_crtime(le
, usec
);
6245 int path_getcrtime(const char *p
, usec_t
*usec
) {
6252 n
= getxattr(p
, "user.crtime_usec", &le
, sizeof(le
));
6255 if (n
!= sizeof(le
))
6258 return parse_crtime(le
, usec
);
6261 int fd_setcrtime(int fd
, usec_t usec
) {
6267 usec
= now(CLOCK_REALTIME
);
6269 le
= htole64((uint64_t) usec
);
6270 if (fsetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
), 0) < 0)
6276 int same_fd(int a
, int b
) {
6277 struct stat sta
, stb
;
6284 /* Compares two file descriptors. Note that semantics are
6285 * quite different depending on whether we have kcmp() or we
6286 * don't. If we have kcmp() this will only return true for
6287 * dup()ed file descriptors, but not otherwise. If we don't
6288 * have kcmp() this will also return true for two fds of the same
6289 * file, created by separate open() calls. Since we use this
6290 * call mostly for filtering out duplicates in the fd store
6291 * this difference hopefully doesn't matter too much. */
6296 /* Try to use kcmp() if we have it. */
6298 r
= kcmp(pid
, pid
, KCMP_FILE
, a
, b
);
6303 if (errno
!= ENOSYS
)
6306 /* We don't have kcmp(), use fstat() instead. */
6307 if (fstat(a
, &sta
) < 0)
6310 if (fstat(b
, &stb
) < 0)
6313 if ((sta
.st_mode
& S_IFMT
) != (stb
.st_mode
& S_IFMT
))
6316 /* We consider all device fds different, since two device fds
6317 * might refer to quite different device contexts even though
6318 * they share the same inode and backing dev_t. */
6320 if (S_ISCHR(sta
.st_mode
) || S_ISBLK(sta
.st_mode
))
6323 if (sta
.st_dev
!= stb
.st_dev
|| sta
.st_ino
!= stb
.st_ino
)
6326 /* The fds refer to the same inode on disk, let's also check
6327 * if they have the same fd flags. This is useful to
6328 * distinguish the read and write side of a pipe created with
6330 fa
= fcntl(a
, F_GETFL
);
6334 fb
= fcntl(b
, F_GETFL
);
6341 int chattr_fd(int fd
, unsigned value
, unsigned mask
) {
6342 unsigned old_attr
, new_attr
;
6347 if (fstat(fd
, &st
) < 0)
6350 /* Explicitly check whether this is a regular file or
6351 * directory. If it is anything else (such as a device node or
6352 * fifo), then the ioctl will not hit the file systems but
6353 * possibly drivers, where the ioctl might have different
6354 * effects. Notably, DRM is using the same ioctl() number. */
6356 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
6362 if (ioctl(fd
, FS_IOC_GETFLAGS
, &old_attr
) < 0)
6365 new_attr
= (old_attr
& ~mask
) | (value
& mask
);
6366 if (new_attr
== old_attr
)
6369 if (ioctl(fd
, FS_IOC_SETFLAGS
, &new_attr
) < 0)
6375 int chattr_path(const char *p
, unsigned value
, unsigned mask
) {
6376 _cleanup_close_
int fd
= -1;
6383 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
6387 return chattr_fd(fd
, value
, mask
);
6390 int read_attr_fd(int fd
, unsigned *ret
) {
6395 if (fstat(fd
, &st
) < 0)
6398 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
6401 if (ioctl(fd
, FS_IOC_GETFLAGS
, ret
) < 0)
6407 int read_attr_path(const char *p
, unsigned *ret
) {
6408 _cleanup_close_
int fd
= -1;
6413 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
6417 return read_attr_fd(fd
, ret
);
6420 static size_t nul_length(const uint8_t *p
, size_t sz
) {
6435 ssize_t
sparse_write(int fd
, const void *p
, size_t sz
, size_t run_length
) {
6436 const uint8_t *q
, *w
, *e
;
6444 n
= nul_length(q
, e
- q
);
6446 /* If there are more than the specified run length of
6447 * NUL bytes, or if this is the beginning or the end
6448 * of the buffer, then seek instead of write */
6449 if ((n
> run_length
) ||
6450 (n
> 0 && q
== p
) ||
6451 (n
> 0 && q
+ n
>= e
)) {
6453 l
= write(fd
, w
, q
- w
);
6460 if (lseek(fd
, n
, SEEK_CUR
) == (off_t
) -1)
6472 l
= write(fd
, w
, q
- w
);
6479 return q
- (const uint8_t*) p
;
6482 void sigkill_wait(pid_t
*pid
) {
6488 if (kill(*pid
, SIGKILL
) > 0)
6489 (void) wait_for_terminate(*pid
, NULL
);
6492 int syslog_parse_priority(const char **p
, int *priority
, bool with_facility
) {
6493 int a
= 0, b
= 0, c
= 0;
6503 if (!strchr(*p
, '>'))
6506 if ((*p
)[2] == '>') {
6507 c
= undecchar((*p
)[1]);
6509 } else if ((*p
)[3] == '>') {
6510 b
= undecchar((*p
)[1]);
6511 c
= undecchar((*p
)[2]);
6513 } else if ((*p
)[4] == '>') {
6514 a
= undecchar((*p
)[1]);
6515 b
= undecchar((*p
)[2]);
6516 c
= undecchar((*p
)[3]);
6521 if (a
< 0 || b
< 0 || c
< 0 ||
6522 (!with_facility
&& (a
|| b
|| c
> 7)))
6526 *priority
= a
*100 + b
*10 + c
;
6528 *priority
= (*priority
& LOG_FACMASK
) | c
;
6534 ssize_t
string_table_lookup(const char * const *table
, size_t len
, const char *key
) {
6540 for (i
= 0; i
< len
; ++i
)
6541 if (streq_ptr(table
[i
], key
))
6547 void cmsg_close_all(struct msghdr
*mh
) {
6548 struct cmsghdr
*cmsg
;
6552 CMSG_FOREACH(cmsg
, mh
)
6553 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
)
6554 close_many((int*) CMSG_DATA(cmsg
), (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int));
6557 int rename_noreplace(int olddirfd
, const char *oldpath
, int newdirfd
, const char *newpath
) {
6561 ret
= renameat2(olddirfd
, oldpath
, newdirfd
, newpath
, RENAME_NOREPLACE
);
6565 /* renameat2() exists since Linux 3.15, btrfs added support for it later.
6566 * If it is not implemented, fallback to another method. */
6567 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
6570 /* The link()/unlink() fallback does not work on directories. But
6571 * renameat() without RENAME_NOREPLACE gives the same semantics on
6572 * directories, except when newpath is an *empty* directory. This is
6574 ret
= fstatat(olddirfd
, oldpath
, &buf
, AT_SYMLINK_NOFOLLOW
);
6575 if (ret
>= 0 && S_ISDIR(buf
.st_mode
)) {
6576 ret
= renameat(olddirfd
, oldpath
, newdirfd
, newpath
);
6577 return ret
>= 0 ? 0 : -errno
;
6580 /* If it is not a directory, use the link()/unlink() fallback. */
6581 ret
= linkat(olddirfd
, oldpath
, newdirfd
, newpath
, 0);
6585 ret
= unlinkat(olddirfd
, oldpath
, 0);
6587 /* backup errno before the following unlinkat() alters it */
6589 (void) unlinkat(newdirfd
, newpath
, 0);
6597 static char *strcpy_backslash_escaped(char *t
, const char *s
, const char *bad
) {
6601 if (*s
== '\\' || strchr(bad
, *s
))
6610 char *shell_escape(const char *s
, const char *bad
) {
6613 r
= new(char, strlen(s
)*2+1);
6617 t
= strcpy_backslash_escaped(r
, s
, bad
);
6623 char *shell_maybe_quote(const char *s
) {
6629 /* Encloses a string in double quotes if necessary to make it
6630 * OK as shell string. */
6632 for (p
= s
; *p
; p
++)
6635 strchr(SHELL_NEED_QUOTES
, *p
))
6641 r
= new(char, 1+strlen(s
)*2+1+1);
6647 t
= mempcpy(t
, s
, p
- s
);
6649 t
= strcpy_backslash_escaped(t
, p
, SHELL_NEED_ESCAPE
);
6657 int parse_mode(const char *s
, mode_t
*ret
) {
6665 l
= strtol(s
, &x
, 8);
6669 if (!x
|| x
== s
|| *x
)
6671 if (l
< 0 || l
> 07777)
6678 int mount_move_root(const char *path
) {
6681 if (chdir(path
) < 0)
6684 if (mount(path
, "/", NULL
, MS_MOVE
, NULL
) < 0)
6687 if (chroot(".") < 0)
6696 int reset_uid_gid(void) {
6698 if (setgroups(0, NULL
) < 0)
6701 if (setresgid(0, 0, 0) < 0)
6704 if (setresuid(0, 0, 0) < 0)
6710 int getxattr_malloc(const char *path
, const char *name
, char **value
, bool allow_symlink
) {
6719 for (l
= 100; ; l
= (size_t) n
+ 1) {
6725 n
= lgetxattr(path
, name
, v
, l
);
6727 n
= getxattr(path
, name
, v
, l
);
6729 if (n
>= 0 && (size_t) n
< l
) {
6736 if (n
< 0 && errno
!= ERANGE
)
6740 n
= lgetxattr(path
, name
, NULL
, 0);
6742 n
= getxattr(path
, name
, NULL
, 0);
6748 int fgetxattr_malloc(int fd
, const char *name
, char **value
) {
6757 for (l
= 100; ; l
= (size_t) n
+ 1) {
6762 n
= fgetxattr(fd
, name
, v
, l
);
6764 if (n
>= 0 && (size_t) n
< l
) {
6771 if (n
< 0 && errno
!= ERANGE
)
6774 n
= fgetxattr(fd
, name
, NULL
, 0);