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 DIR* safe_closedir(DIR *d
) {
362 assert_se(closedir(d
) >= 0 || errno
!= EBADF
);
368 int unlink_noerrno(const char *path
) {
379 int parse_boolean(const char *v
) {
382 if (streq(v
, "1") || strcaseeq(v
, "yes") || strcaseeq(v
, "y") || strcaseeq(v
, "true") || strcaseeq(v
, "t") || strcaseeq(v
, "on"))
384 else if (streq(v
, "0") || strcaseeq(v
, "no") || strcaseeq(v
, "n") || strcaseeq(v
, "false") || strcaseeq(v
, "f") || strcaseeq(v
, "off"))
390 int parse_pid(const char *s
, pid_t
* ret_pid
) {
391 unsigned long ul
= 0;
398 r
= safe_atolu(s
, &ul
);
404 if ((unsigned long) pid
!= ul
)
414 bool uid_is_valid(uid_t uid
) {
416 /* Some libc APIs use UID_INVALID as special placeholder */
417 if (uid
== (uid_t
) 0xFFFFFFFF)
420 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
421 if (uid
== (uid_t
) 0xFFFF)
427 int parse_uid(const char *s
, uid_t
* ret_uid
) {
428 unsigned long ul
= 0;
434 r
= safe_atolu(s
, &ul
);
440 if ((unsigned long) uid
!= ul
)
443 if (!uid_is_valid(uid
))
444 return -ENXIO
; /* we return ENXIO instead of EINVAL
445 * here, to make it easy to distuingish
446 * invalid numeric uids invalid
455 int safe_atou(const char *s
, unsigned *ret_u
) {
463 l
= strtoul(s
, &x
, 0);
465 if (!x
|| x
== s
|| *x
|| errno
)
466 return errno
> 0 ? -errno
: -EINVAL
;
468 if ((unsigned long) (unsigned) l
!= l
)
471 *ret_u
= (unsigned) l
;
475 int safe_atoi(const char *s
, int *ret_i
) {
483 l
= strtol(s
, &x
, 0);
485 if (!x
|| x
== s
|| *x
|| errno
)
486 return errno
> 0 ? -errno
: -EINVAL
;
488 if ((long) (int) l
!= l
)
495 int safe_atou8(const char *s
, uint8_t *ret
) {
503 l
= strtoul(s
, &x
, 0);
505 if (!x
|| x
== s
|| *x
|| errno
)
506 return errno
> 0 ? -errno
: -EINVAL
;
508 if ((unsigned long) (uint8_t) l
!= l
)
515 int safe_atou16(const char *s
, uint16_t *ret
) {
523 l
= strtoul(s
, &x
, 0);
525 if (!x
|| x
== s
|| *x
|| errno
)
526 return errno
> 0 ? -errno
: -EINVAL
;
528 if ((unsigned long) (uint16_t) l
!= l
)
535 int safe_atoi16(const char *s
, int16_t *ret
) {
543 l
= strtol(s
, &x
, 0);
545 if (!x
|| x
== s
|| *x
|| errno
)
546 return errno
> 0 ? -errno
: -EINVAL
;
548 if ((long) (int16_t) l
!= l
)
555 int safe_atollu(const char *s
, long long unsigned *ret_llu
) {
557 unsigned long long l
;
563 l
= strtoull(s
, &x
, 0);
565 if (!x
|| x
== s
|| *x
|| errno
)
566 return errno
? -errno
: -EINVAL
;
572 int safe_atolli(const char *s
, long long int *ret_lli
) {
580 l
= strtoll(s
, &x
, 0);
582 if (!x
|| x
== s
|| *x
|| errno
)
583 return errno
? -errno
: -EINVAL
;
589 int safe_atod(const char *s
, double *ret_d
) {
597 loc
= newlocale(LC_NUMERIC_MASK
, "C", (locale_t
) 0);
598 if (loc
== (locale_t
) 0)
602 d
= strtod_l(s
, &x
, loc
);
604 if (!x
|| x
== s
|| *x
|| errno
) {
606 return errno
? -errno
: -EINVAL
;
614 static size_t strcspn_escaped(const char *s
, const char *reject
) {
615 bool escaped
= false;
618 for (n
=0; s
[n
]; n
++) {
621 else if (s
[n
] == '\\')
623 else if (strchr(reject
, s
[n
]))
627 /* if s ends in \, return index of previous char */
631 /* Split a string into words. */
632 const char* split(const char **state
, size_t *l
, const char *separator
, bool quoted
) {
638 assert(**state
== '\0');
642 current
+= strspn(current
, separator
);
648 if (quoted
&& strchr("\'\"", *current
)) {
649 char quotechars
[2] = {*current
, '\0'};
651 *l
= strcspn_escaped(current
+ 1, quotechars
);
652 if (current
[*l
+ 1] == '\0' || current
[*l
+ 1] != quotechars
[0] ||
653 (current
[*l
+ 2] && !strchr(separator
, current
[*l
+ 2]))) {
654 /* right quote missing or garbage at the end */
658 *state
= current
++ + *l
+ 2;
660 *l
= strcspn_escaped(current
, separator
);
661 if (current
[*l
] && !strchr(separator
, current
[*l
])) {
662 /* unfinished escape */
666 *state
= current
+ *l
;
668 *l
= strcspn(current
, separator
);
669 *state
= current
+ *l
;
675 int fchmod_umask(int fd
, mode_t m
) {
680 r
= fchmod(fd
, m
& (~u
)) < 0 ? -errno
: 0;
686 char *truncate_nl(char *s
) {
689 s
[strcspn(s
, NEWLINE
)] = 0;
693 char *strnappend(const char *s
, const char *suffix
, size_t b
) {
701 return strndup(suffix
, b
);
710 if (b
> ((size_t) -1) - a
)
713 r
= new(char, a
+b
+1);
718 memcpy(r
+a
, suffix
, b
);
724 char *strappend(const char *s
, const char *suffix
) {
725 return strnappend(s
, suffix
, suffix
? strlen(suffix
) : 0);
728 int readlinkat_malloc(int fd
, const char *p
, char **ret
) {
743 n
= readlinkat(fd
, p
, c
, l
-1);
750 if ((size_t) n
< l
-1) {
761 int readlink_malloc(const char *p
, char **ret
) {
762 return readlinkat_malloc(AT_FDCWD
, p
, ret
);
765 int readlink_value(const char *p
, char **ret
) {
766 _cleanup_free_
char *link
= NULL
;
770 r
= readlink_malloc(p
, &link
);
774 value
= basename(link
);
778 value
= strdup(value
);
787 int readlink_and_make_absolute(const char *p
, char **r
) {
788 _cleanup_free_
char *target
= NULL
;
795 j
= readlink_malloc(p
, &target
);
799 k
= file_in_same_dir(p
, target
);
807 int readlink_and_canonicalize(const char *p
, char **r
) {
814 j
= readlink_and_make_absolute(p
, &t
);
818 s
= canonicalize_file_name(t
);
825 path_kill_slashes(*r
);
830 char *strstrip(char *s
) {
833 /* Drops trailing whitespace. Modifies the string in
834 * place. Returns pointer to first non-space character */
836 s
+= strspn(s
, WHITESPACE
);
838 for (e
= strchr(s
, 0); e
> s
; e
--)
839 if (!strchr(WHITESPACE
, e
[-1]))
847 char *delete_chars(char *s
, const char *bad
) {
850 /* Drops all whitespace, regardless where in the string */
852 for (f
= s
, t
= s
; *f
; f
++) {
864 char *file_in_same_dir(const char *path
, const char *filename
) {
871 /* This removes the last component of path and appends
872 * filename, unless the latter is absolute anyway or the
875 if (path_is_absolute(filename
))
876 return strdup(filename
);
878 e
= strrchr(path
, '/');
880 return strdup(filename
);
882 k
= strlen(filename
);
883 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
887 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
891 int rmdir_parents(const char *path
, const char *stop
) {
900 /* Skip trailing slashes */
901 while (l
> 0 && path
[l
-1] == '/')
907 /* Skip last component */
908 while (l
> 0 && path
[l
-1] != '/')
911 /* Skip trailing slashes */
912 while (l
> 0 && path
[l
-1] == '/')
918 if (!(t
= strndup(path
, l
)))
921 if (path_startswith(stop
, t
)) {
937 char hexchar(int x
) {
938 static const char table
[16] = "0123456789abcdef";
940 return table
[x
& 15];
943 int unhexchar(char c
) {
945 if (c
>= '0' && c
<= '9')
948 if (c
>= 'a' && c
<= 'f')
951 if (c
>= 'A' && c
<= 'F')
957 char *hexmem(const void *p
, size_t l
) {
961 z
= r
= malloc(l
* 2 + 1);
965 for (x
= p
; x
< (const uint8_t*) p
+ l
; x
++) {
966 *(z
++) = hexchar(*x
>> 4);
967 *(z
++) = hexchar(*x
& 15);
974 int unhexmem(const char *p
, size_t l
, void **mem
, size_t *len
) {
975 _cleanup_free_
uint8_t *r
= NULL
;
983 z
= r
= malloc((l
+ 1) / 2 + 1);
987 for (x
= p
; x
< p
+ l
; x
+= 2) {
993 else if (x
+1 < p
+ l
) {
1000 *(z
++) = (uint8_t) a
<< 4 | (uint8_t) b
;
1012 /* https://tools.ietf.org/html/rfc4648#section-6
1013 * Notice that base32hex differs from base32 in the alphabet it uses.
1014 * The distinction is that the base32hex representation preserves the
1015 * order of the underlying data when compared as bytestrings, this is
1016 * useful when representing NSEC3 hashes, as one can then verify the
1017 * order of hashes directly from their representation. */
1018 char base32hexchar(int x
) {
1019 static const char table
[32] = "0123456789"
1020 "ABCDEFGHIJKLMNOPQRSTUV";
1022 return table
[x
& 31];
1025 int unbase32hexchar(char c
) {
1028 if (c
>= '0' && c
<= '9')
1031 offset
= '9' - '0' + 1;
1033 if (c
>= 'A' && c
<= 'V')
1034 return c
- 'A' + offset
;
1039 char *base32hexmem(const void *p
, size_t l
, bool padding
) {
1045 /* five input bytes makes eight output bytes, padding is added so we must round up */
1046 len
= 8 * (l
+ 4) / 5;
1048 /* same, but round down as there is no padding */
1067 z
= r
= malloc(len
+ 1);
1071 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 5) * 5; x
+= 5) {
1072 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ
1073 x[3] == QQQQQQQQ; x[4] == WWWWWWWW */
1074 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1075 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1076 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1077 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1078 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
1079 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
1080 *(z
++) = base32hexchar((x
[3] & 3) << 3 | x
[4] >> 5); /* 000QQWWW */
1081 *(z
++) = base32hexchar((x
[4] & 31)); /* 000WWWWW */
1086 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1087 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1088 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1089 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1090 *(z
++) = base32hexchar((x
[2] & 15) << 1 | x
[3] >> 7); /* 000ZZZZQ */
1091 *(z
++) = base32hexchar((x
[3] & 127) >> 2); /* 000QQQQQ */
1092 *(z
++) = base32hexchar((x
[3] & 3) << 3); /* 000QQ000 */
1099 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1100 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1101 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1102 *(z
++) = base32hexchar((x
[1] & 1) << 4 | x
[2] >> 4); /* 000YZZZZ */
1103 *(z
++) = base32hexchar((x
[2] & 15) << 1); /* 000ZZZZ0 */
1113 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1114 *(z
++) = base32hexchar((x
[0] & 7) << 2 | x
[1] >> 6); /* 000XXXYY */
1115 *(z
++) = base32hexchar((x
[1] & 63) >> 1); /* 000YYYYY */
1116 *(z
++) = base32hexchar((x
[1] & 1) << 4); /* 000Y0000 */
1127 *(z
++) = base32hexchar(x
[0] >> 3); /* 000XXXXX */
1128 *(z
++) = base32hexchar((x
[0] & 7) << 2); /* 000XXX00 */
1145 int unbase32hexmem(const char *p
, size_t l
, bool padding
, void **mem
, size_t *_len
) {
1146 _cleanup_free_
uint8_t *r
= NULL
;
1147 int a
, b
, c
, d
, e
, f
, g
, h
;
1155 /* padding ensures any base32hex input has input divisible by 8 */
1156 if (padding
&& l
% 8 != 0)
1160 /* strip the padding */
1161 while (l
> 0 && p
[l
- 1] == '=' && pad
< 7) {
1167 /* a group of eight input bytes needs five output bytes, in case of
1168 padding we need to add some extra bytes */
1190 z
= r
= malloc(len
+ 1);
1194 for (x
= p
; x
< p
+ (l
/ 8) * 8; x
+= 8) {
1195 /* a == 000XXXXX; b == 000YYYYY; c == 000ZZZZZ; d == 000WWWWW
1196 e == 000SSSSS; f == 000QQQQQ; g == 000VVVVV; h == 000RRRRR */
1197 a
= unbase32hexchar(x
[0]);
1201 b
= unbase32hexchar(x
[1]);
1205 c
= unbase32hexchar(x
[2]);
1209 d
= unbase32hexchar(x
[3]);
1213 e
= unbase32hexchar(x
[4]);
1217 f
= unbase32hexchar(x
[5]);
1221 g
= unbase32hexchar(x
[6]);
1225 h
= unbase32hexchar(x
[7]);
1229 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1230 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1231 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1232 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
1233 *(z
++) = (uint8_t) g
<< 5 | (uint8_t) h
; /* VVVRRRRR */
1238 a
= unbase32hexchar(x
[0]);
1242 b
= unbase32hexchar(x
[1]);
1246 c
= unbase32hexchar(x
[2]);
1250 d
= unbase32hexchar(x
[3]);
1254 e
= unbase32hexchar(x
[4]);
1258 f
= unbase32hexchar(x
[5]);
1262 g
= unbase32hexchar(x
[6]);
1270 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1271 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1272 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1273 *(z
++) = (uint8_t) e
<< 7 | (uint8_t) f
<< 2 | (uint8_t) g
>> 3; /* SQQQQQVV */
1277 a
= unbase32hexchar(x
[0]);
1281 b
= unbase32hexchar(x
[1]);
1285 c
= unbase32hexchar(x
[2]);
1289 d
= unbase32hexchar(x
[3]);
1293 e
= unbase32hexchar(x
[4]);
1301 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1302 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1303 *(z
++) = (uint8_t) d
<< 4 | (uint8_t) e
>> 1; /* WWWWSSSS */
1307 a
= unbase32hexchar(x
[0]);
1311 b
= unbase32hexchar(x
[1]);
1315 c
= unbase32hexchar(x
[2]);
1319 d
= unbase32hexchar(x
[3]);
1327 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1328 *(z
++) = (uint8_t) b
<< 6 | (uint8_t) c
<< 1 | (uint8_t) d
>> 4; /* YYZZZZZW */
1332 a
= unbase32hexchar(x
[0]);
1336 b
= unbase32hexchar(x
[1]);
1344 *(z
++) = (uint8_t) a
<< 3 | (uint8_t) b
>> 2; /* XXXXXYYY */
1362 /* https://tools.ietf.org/html/rfc4648#section-4 */
1363 char base64char(int x
) {
1364 static const char table
[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1365 "abcdefghijklmnopqrstuvwxyz"
1367 return table
[x
& 63];
1370 int unbase64char(char c
) {
1373 if (c
>= 'A' && c
<= 'Z')
1376 offset
= 'Z' - 'A' + 1;
1378 if (c
>= 'a' && c
<= 'z')
1379 return c
- 'a' + offset
;
1381 offset
+= 'z' - 'a' + 1;
1383 if (c
>= '0' && c
<= '9')
1384 return c
- '0' + offset
;
1386 offset
+= '9' - '0' + 1;
1399 char *base64mem(const void *p
, size_t l
) {
1403 /* three input bytes makes four output bytes, padding is added so we must round up */
1404 z
= r
= malloc(4 * (l
+ 2) / 3 + 1);
1408 for (x
= p
; x
< (const uint8_t*) p
+ (l
/ 3) * 3; x
+= 3) {
1409 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ */
1410 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1411 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1412 *(z
++) = base64char((x
[1] & 15) << 2 | x
[2] >> 6); /* 00YYYYZZ */
1413 *(z
++) = base64char(x
[2] & 63); /* 00ZZZZZZ */
1418 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1419 *(z
++) = base64char((x
[0] & 3) << 4 | x
[1] >> 4); /* 00XXYYYY */
1420 *(z
++) = base64char((x
[1] & 15) << 2); /* 00YYYY00 */
1425 *(z
++) = base64char(x
[0] >> 2); /* 00XXXXXX */
1426 *(z
++) = base64char((x
[0] & 3) << 4); /* 00XX0000 */
1437 int unbase64mem(const char *p
, size_t l
, void **mem
, size_t *_len
) {
1438 _cleanup_free_
uint8_t *r
= NULL
;
1446 /* padding ensures any base63 input has input divisible by 4 */
1450 /* strip the padding */
1451 if (l
> 0 && p
[l
- 1] == '=')
1453 if (l
> 0 && p
[l
- 1] == '=')
1456 /* a group of four input bytes needs three output bytes, in case of
1457 padding we need to add two or three extra bytes */
1458 len
= (l
/ 4) * 3 + (l
% 4 ? (l
% 4) - 1 : 0);
1460 z
= r
= malloc(len
+ 1);
1464 for (x
= p
; x
< p
+ (l
/ 4) * 4; x
+= 4) {
1465 /* a == 00XXXXXX; b == 00YYYYYY; c == 00ZZZZZZ; d == 00WWWWWW */
1466 a
= unbase64char(x
[0]);
1470 b
= unbase64char(x
[1]);
1474 c
= unbase64char(x
[2]);
1478 d
= unbase64char(x
[3]);
1482 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1483 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1484 *(z
++) = (uint8_t) c
<< 6 | (uint8_t) d
; /* ZZWWWWWW */
1489 a
= unbase64char(x
[0]);
1493 b
= unbase64char(x
[1]);
1497 c
= unbase64char(x
[2]);
1505 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) b
>> 4; /* XXXXXXYY */
1506 *(z
++) = (uint8_t) b
<< 4 | (uint8_t) c
>> 2; /* YYYYZZZZ */
1510 a
= unbase64char(x
[0]);
1514 b
= unbase64char(x
[1]);
1522 *(z
++) = (uint8_t) a
<< 2 | (uint8_t) (b
>> 4); /* XXXXXXYY */
1541 char octchar(int x
) {
1542 return '0' + (x
& 7);
1545 int unoctchar(char c
) {
1547 if (c
>= '0' && c
<= '7')
1553 char decchar(int x
) {
1554 return '0' + (x
% 10);
1557 int undecchar(char c
) {
1559 if (c
>= '0' && c
<= '9')
1565 char *cescape(const char *s
) {
1571 /* Does C style string escaping. May be reversed with
1574 r
= new(char, strlen(s
)*4 + 1);
1578 for (f
= s
, t
= r
; *f
; f
++)
1579 t
+= cescape_char(*f
, t
);
1586 static int cunescape_one(const char *p
, size_t length
, char *ret
, uint32_t *ret_unicode
) {
1593 /* Unescapes C style. Returns the unescaped character in ret,
1594 * unless we encountered a \u sequence in which case the full
1595 * unicode character is returned in ret_unicode, instead. */
1597 if (length
!= (size_t) -1 && length
< 1)
1634 /* This is an extension of the XDG syntax files */
1639 /* hexadecimal encoding */
1642 if (length
!= (size_t) -1 && length
< 3)
1645 a
= unhexchar(p
[1]);
1649 b
= unhexchar(p
[2]);
1653 /* Don't allow NUL bytes */
1654 if (a
== 0 && b
== 0)
1657 *ret
= (char) ((a
<< 4U) | b
);
1663 /* C++11 style 16bit unicode */
1669 if (length
!= (size_t) -1 && length
< 5)
1672 for (i
= 0; i
< 4; i
++) {
1673 a
[i
] = unhexchar(p
[1 + i
]);
1678 c
= ((uint32_t) a
[0] << 12U) | ((uint32_t) a
[1] << 8U) | ((uint32_t) a
[2] << 4U) | (uint32_t) a
[3];
1680 /* Don't allow 0 chars */
1699 /* C++11 style 32bit unicode */
1705 if (length
!= (size_t) -1 && length
< 9)
1708 for (i
= 0; i
< 8; i
++) {
1709 a
[i
] = unhexchar(p
[1 + i
]);
1714 c
= ((uint32_t) a
[0] << 28U) | ((uint32_t) a
[1] << 24U) | ((uint32_t) a
[2] << 20U) | ((uint32_t) a
[3] << 16U) |
1715 ((uint32_t) a
[4] << 12U) | ((uint32_t) a
[5] << 8U) | ((uint32_t) a
[6] << 4U) | (uint32_t) a
[7];
1717 /* Don't allow 0 chars */
1721 /* Don't allow invalid code points */
1722 if (!unichar_is_valid(c
))
1747 /* octal encoding */
1751 if (length
!= (size_t) -1 && length
< 3)
1754 a
= unoctchar(p
[0]);
1758 b
= unoctchar(p
[1]);
1762 c
= unoctchar(p
[2]);
1766 /* don't allow NUL bytes */
1767 if (a
== 0 && b
== 0 && c
== 0)
1770 /* Don't allow bytes above 255 */
1771 m
= ((uint32_t) a
<< 6U) | ((uint32_t) b
<< 3U) | (uint32_t) c
;
1787 int cunescape_length_with_prefix(const char *s
, size_t length
, const char *prefix
, UnescapeFlags flags
, char **ret
) {
1795 /* Undoes C style string escaping, and optionally prefixes it. */
1797 pl
= prefix
? strlen(prefix
) : 0;
1799 r
= new(char, pl
+length
+1);
1804 memcpy(r
, prefix
, pl
);
1806 for (f
= s
, t
= r
+ pl
; f
< s
+ length
; f
++) {
1812 remaining
= s
+ length
- f
;
1813 assert(remaining
> 0);
1816 /* A literal literal, copy verbatim */
1821 if (remaining
== 1) {
1822 if (flags
& UNESCAPE_RELAX
) {
1823 /* A trailing backslash, copy verbatim */
1832 k
= cunescape_one(f
+ 1, remaining
- 1, &c
, &u
);
1834 if (flags
& UNESCAPE_RELAX
) {
1835 /* Invalid escape code, let's take it literal then */
1845 /* Non-Unicode? Let's encode this directly */
1848 /* Unicode? Then let's encode this in UTF-8 */
1849 t
+= utf8_encode_unichar(t
, u
);
1860 int cunescape_length(const char *s
, size_t length
, UnescapeFlags flags
, char **ret
) {
1861 return cunescape_length_with_prefix(s
, length
, NULL
, flags
, ret
);
1864 int cunescape(const char *s
, UnescapeFlags flags
, char **ret
) {
1865 return cunescape_length(s
, strlen(s
), flags
, ret
);
1868 char *xescape(const char *s
, const char *bad
) {
1872 /* Escapes all chars in bad, in addition to \ and all special
1873 * chars, in \xFF style escaping. May be reversed with
1876 r
= new(char, strlen(s
) * 4 + 1);
1880 for (f
= s
, t
= r
; *f
; f
++) {
1882 if ((*f
< ' ') || (*f
>= 127) ||
1883 (*f
== '\\') || strchr(bad
, *f
)) {
1886 *(t
++) = hexchar(*f
>> 4);
1887 *(t
++) = hexchar(*f
);
1897 char *ascii_strlower(char *t
) {
1902 for (p
= t
; *p
; p
++)
1903 if (*p
>= 'A' && *p
<= 'Z')
1904 *p
= *p
- 'A' + 'a';
1909 _pure_
static bool hidden_file_allow_backup(const char *filename
) {
1913 filename
[0] == '.' ||
1914 streq(filename
, "lost+found") ||
1915 streq(filename
, "aquota.user") ||
1916 streq(filename
, "aquota.group") ||
1917 endswith(filename
, ".rpmnew") ||
1918 endswith(filename
, ".rpmsave") ||
1919 endswith(filename
, ".rpmorig") ||
1920 endswith(filename
, ".dpkg-old") ||
1921 endswith(filename
, ".dpkg-new") ||
1922 endswith(filename
, ".dpkg-tmp") ||
1923 endswith(filename
, ".dpkg-dist") ||
1924 endswith(filename
, ".dpkg-bak") ||
1925 endswith(filename
, ".dpkg-backup") ||
1926 endswith(filename
, ".dpkg-remove") ||
1927 endswith(filename
, ".swp");
1930 bool hidden_file(const char *filename
) {
1933 if (endswith(filename
, "~"))
1936 return hidden_file_allow_backup(filename
);
1939 int fd_nonblock(int fd
, bool nonblock
) {
1944 flags
= fcntl(fd
, F_GETFL
, 0);
1949 nflags
= flags
| O_NONBLOCK
;
1951 nflags
= flags
& ~O_NONBLOCK
;
1953 if (nflags
== flags
)
1956 if (fcntl(fd
, F_SETFL
, nflags
) < 0)
1962 int fd_cloexec(int fd
, bool cloexec
) {
1967 flags
= fcntl(fd
, F_GETFD
, 0);
1972 nflags
= flags
| FD_CLOEXEC
;
1974 nflags
= flags
& ~FD_CLOEXEC
;
1976 if (nflags
== flags
)
1979 if (fcntl(fd
, F_SETFD
, nflags
) < 0)
1985 _pure_
static bool fd_in_set(int fd
, const int fdset
[], unsigned n_fdset
) {
1988 assert(n_fdset
== 0 || fdset
);
1990 for (i
= 0; i
< n_fdset
; i
++)
1997 int close_all_fds(const int except
[], unsigned n_except
) {
1998 _cleanup_closedir_
DIR *d
= NULL
;
2002 assert(n_except
== 0 || except
);
2004 d
= opendir("/proc/self/fd");
2009 /* When /proc isn't available (for example in chroots)
2010 * the fallback is brute forcing through the fd
2013 assert_se(getrlimit(RLIMIT_NOFILE
, &rl
) >= 0);
2014 for (fd
= 3; fd
< (int) rl
.rlim_max
; fd
++) {
2016 if (fd_in_set(fd
, except
, n_except
))
2019 if (close_nointr(fd
) < 0)
2020 if (errno
!= EBADF
&& r
== 0)
2027 while ((de
= readdir(d
))) {
2030 if (hidden_file(de
->d_name
))
2033 if (safe_atoi(de
->d_name
, &fd
) < 0)
2034 /* Let's better ignore this, just in case */
2043 if (fd_in_set(fd
, except
, n_except
))
2046 if (close_nointr(fd
) < 0) {
2047 /* Valgrind has its own FD and doesn't want to have it closed */
2048 if (errno
!= EBADF
&& r
== 0)
2056 bool chars_intersect(const char *a
, const char *b
) {
2059 /* Returns true if any of the chars in a are in b. */
2060 for (p
= a
; *p
; p
++)
2067 bool fstype_is_network(const char *fstype
) {
2068 static const char table
[] =
2083 x
= startswith(fstype
, "fuse.");
2087 return nulstr_contains(table
, fstype
);
2090 int flush_fd(int fd
) {
2091 struct pollfd pollfd
= {
2101 r
= poll(&pollfd
, 1, 0);
2111 l
= read(fd
, buf
, sizeof(buf
));
2117 if (errno
== EAGAIN
)
2126 void safe_close_pair(int p
[]) {
2130 /* Special case pairs which use the same fd in both
2132 p
[0] = p
[1] = safe_close(p
[0]);
2136 p
[0] = safe_close(p
[0]);
2137 p
[1] = safe_close(p
[1]);
2140 ssize_t
loop_read(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2147 while (nbytes
> 0) {
2150 k
= read(fd
, p
, nbytes
);
2155 if (errno
== EAGAIN
&& do_poll
) {
2157 /* We knowingly ignore any return value here,
2158 * and expect that any error/EOF is reported
2161 fd_wait_for_event(fd
, POLLIN
, USEC_INFINITY
);
2165 return n
> 0 ? n
: -errno
;
2179 int loop_read_exact(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2182 n
= loop_read(fd
, buf
, nbytes
, do_poll
);
2185 if ((size_t) n
!= nbytes
)
2190 int loop_write(int fd
, const void *buf
, size_t nbytes
, bool do_poll
) {
2191 const uint8_t *p
= buf
;
2201 k
= write(fd
, p
, nbytes
);
2206 if (errno
== EAGAIN
&& do_poll
) {
2207 /* We knowingly ignore any return value here,
2208 * and expect that any error/EOF is reported
2211 fd_wait_for_event(fd
, POLLOUT
, USEC_INFINITY
);
2218 if (nbytes
> 0 && k
== 0) /* Can't really happen */
2223 } while (nbytes
> 0);
2228 int parse_size(const char *t
, uint64_t base
, uint64_t *size
) {
2230 /* Soo, sometimes we want to parse IEC binary suffixes, and
2231 * sometimes SI decimal suffixes. This function can parse
2232 * both. Which one is the right way depends on the
2233 * context. Wikipedia suggests that SI is customary for
2234 * hardware metrics and network speeds, while IEC is
2235 * customary for most data sizes used by software and volatile
2236 * (RAM) memory. Hence be careful which one you pick!
2238 * In either case we use just K, M, G as suffix, and not Ki,
2239 * Mi, Gi or so (as IEC would suggest). That's because that's
2240 * frickin' ugly. But this means you really need to make sure
2241 * to document which base you are parsing when you use this
2246 unsigned long long factor
;
2249 static const struct table iec
[] = {
2250 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2251 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2252 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2253 { "G", 1024ULL*1024ULL*1024ULL },
2254 { "M", 1024ULL*1024ULL },
2260 static const struct table si
[] = {
2261 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2262 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2263 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2264 { "G", 1000ULL*1000ULL*1000ULL },
2265 { "M", 1000ULL*1000ULL },
2271 const struct table
*table
;
2273 unsigned long long r
= 0;
2274 unsigned n_entries
, start_pos
= 0;
2277 assert(base
== 1000 || base
== 1024);
2282 n_entries
= ELEMENTSOF(si
);
2285 n_entries
= ELEMENTSOF(iec
);
2290 unsigned long long l
, tmp
;
2295 p
+= strspn(p
, WHITESPACE
);
2300 l
= strtoull(p
, &e
, 10);
2309 /* strtoull() itself would accept space/+/- */
2310 if (*e
>= '0' && *e
<= '9') {
2311 unsigned long long l2
;
2314 l2
= strtoull(e
, &e2
, 10);
2318 /* Ignore failure. E.g. 10.M is valid */
2325 e
+= strspn(e
, WHITESPACE
);
2327 for (i
= start_pos
; i
< n_entries
; i
++)
2328 if (startswith(e
, table
[i
].suffix
))
2334 if (l
+ (frac
> 0) > ULLONG_MAX
/ table
[i
].factor
)
2337 tmp
= l
* table
[i
].factor
+ (unsigned long long) (frac
* table
[i
].factor
);
2338 if (tmp
> ULLONG_MAX
- r
)
2342 if ((unsigned long long) (uint64_t) r
!= r
)
2345 p
= e
+ strlen(table
[i
].suffix
);
2356 bool is_device_path(const char *path
) {
2358 /* Returns true on paths that refer to a device, either in
2359 * sysfs or in /dev */
2362 path_startswith(path
, "/dev/") ||
2363 path_startswith(path
, "/sys/");
2366 int dir_is_empty(const char *path
) {
2367 _cleanup_closedir_
DIR *d
;
2378 if (!de
&& errno
!= 0)
2384 if (!hidden_file(de
->d_name
))
2389 char* dirname_malloc(const char *path
) {
2390 char *d
, *dir
, *dir2
;
2407 void rename_process(const char name
[8]) {
2410 /* This is a like a poor man's setproctitle(). It changes the
2411 * comm field, argv[0], and also the glibc's internally used
2412 * name of the process. For the first one a limit of 16 chars
2413 * applies, to the second one usually one of 10 (i.e. length
2414 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2415 * "systemd"). If you pass a longer string it will be
2418 prctl(PR_SET_NAME
, name
);
2420 if (program_invocation_name
)
2421 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
2423 if (saved_argc
> 0) {
2427 strncpy(saved_argv
[0], name
, strlen(saved_argv
[0]));
2429 for (i
= 1; i
< saved_argc
; i
++) {
2433 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
2438 char *lookup_uid(uid_t uid
) {
2441 _cleanup_free_
char *buf
= NULL
;
2442 struct passwd pwbuf
, *pw
= NULL
;
2444 /* Shortcut things to avoid NSS lookups */
2446 return strdup("root");
2448 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
2452 buf
= malloc(bufsize
);
2456 if (getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
) == 0 && pw
)
2457 return strdup(pw
->pw_name
);
2459 if (asprintf(&name
, UID_FMT
, uid
) < 0)
2465 char* getlogname_malloc(void) {
2469 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
2474 return lookup_uid(uid
);
2477 char *getusername_malloc(void) {
2484 return lookup_uid(getuid());
2487 bool is_temporary_fs(const struct statfs
*s
) {
2490 return F_TYPE_EQUAL(s
->f_type
, TMPFS_MAGIC
) ||
2491 F_TYPE_EQUAL(s
->f_type
, RAMFS_MAGIC
);
2494 int fd_is_temporary_fs(int fd
) {
2497 if (fstatfs(fd
, &s
) < 0)
2500 return is_temporary_fs(&s
);
2503 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
2506 /* Under the assumption that we are running privileged we
2507 * first change the access mode and only then hand out
2508 * ownership to avoid a window where access is too open. */
2510 if (mode
!= MODE_INVALID
)
2511 if (chmod(path
, mode
) < 0)
2514 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
2515 if (chown(path
, uid
, gid
) < 0)
2521 int fchmod_and_fchown(int fd
, mode_t mode
, uid_t uid
, gid_t gid
) {
2524 /* Under the assumption that we are running privileged we
2525 * first change the access mode and only then hand out
2526 * ownership to avoid a window where access is too open. */
2528 if (mode
!= MODE_INVALID
)
2529 if (fchmod(fd
, mode
) < 0)
2532 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
2533 if (fchown(fd
, uid
, gid
) < 0)
2539 cpu_set_t
* cpu_set_malloc(unsigned *ncpus
) {
2543 /* Allocates the cpuset in the right size */
2546 if (!(r
= CPU_ALLOC(n
)))
2549 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n
), r
) >= 0) {
2550 CPU_ZERO_S(CPU_ALLOC_SIZE(n
), r
);
2560 if (errno
!= EINVAL
)
2567 int files_same(const char *filea
, const char *fileb
) {
2570 if (stat(filea
, &a
) < 0)
2573 if (stat(fileb
, &b
) < 0)
2576 return a
.st_dev
== b
.st_dev
&&
2577 a
.st_ino
== b
.st_ino
;
2580 int running_in_chroot(void) {
2583 ret
= files_same("/proc/1/root", "/");
2590 static char *ascii_ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
2595 assert(percent
<= 100);
2596 assert(new_length
>= 3);
2598 if (old_length
<= 3 || old_length
<= new_length
)
2599 return strndup(s
, old_length
);
2601 r
= new0(char, new_length
+1);
2605 x
= (new_length
* percent
) / 100;
2607 if (x
> new_length
- 3)
2615 s
+ old_length
- (new_length
- x
- 3),
2616 new_length
- x
- 3);
2621 char *ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
2625 unsigned k
, len
, len2
;
2628 assert(percent
<= 100);
2629 assert(new_length
>= 3);
2631 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2632 if (ascii_is_valid(s
))
2633 return ascii_ellipsize_mem(s
, old_length
, new_length
, percent
);
2635 if (old_length
<= 3 || old_length
<= new_length
)
2636 return strndup(s
, old_length
);
2638 x
= (new_length
* percent
) / 100;
2640 if (x
> new_length
- 3)
2644 for (i
= s
; k
< x
&& i
< s
+ old_length
; i
= utf8_next_char(i
)) {
2647 c
= utf8_encoded_to_unichar(i
);
2650 k
+= unichar_iswide(c
) ? 2 : 1;
2653 if (k
> x
) /* last character was wide and went over quota */
2656 for (j
= s
+ old_length
; k
< new_length
&& j
> i
; ) {
2659 j
= utf8_prev_char(j
);
2660 c
= utf8_encoded_to_unichar(j
);
2663 k
+= unichar_iswide(c
) ? 2 : 1;
2667 /* we don't actually need to ellipsize */
2669 return memdup(s
, old_length
+ 1);
2671 /* make space for ellipsis */
2672 j
= utf8_next_char(j
);
2675 len2
= s
+ old_length
- j
;
2676 e
= new(char, len
+ 3 + len2
+ 1);
2681 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2682 old_length, new_length, x, len, len2, k);
2686 e
[len
] = 0xe2; /* tri-dot ellipsis: … */
2690 memcpy(e
+ len
+ 3, j
, len2
+ 1);
2695 char *ellipsize(const char *s
, size_t length
, unsigned percent
) {
2696 return ellipsize_mem(s
, strlen(s
), length
, percent
);
2699 int touch_file(const char *path
, bool parents
, usec_t stamp
, uid_t uid
, gid_t gid
, mode_t mode
) {
2700 _cleanup_close_
int fd
;
2706 mkdir_parents(path
, 0755);
2708 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, mode
> 0 ? mode
: 0644);
2713 r
= fchmod(fd
, mode
);
2718 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
) {
2719 r
= fchown(fd
, uid
, gid
);
2724 if (stamp
!= USEC_INFINITY
) {
2725 struct timespec ts
[2];
2727 timespec_store(&ts
[0], stamp
);
2729 r
= futimens(fd
, ts
);
2731 r
= futimens(fd
, NULL
);
2738 int touch(const char *path
) {
2739 return touch_file(path
, false, USEC_INFINITY
, UID_INVALID
, GID_INVALID
, 0);
2742 static char *unquote(const char *s
, const char* quotes
) {
2746 /* This is rather stupid, simply removes the heading and
2747 * trailing quotes if there is one. Doesn't care about
2748 * escaping or anything.
2750 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2756 if (strchr(quotes
, s
[0]) && s
[l
-1] == s
[0])
2757 return strndup(s
+1, l
-2);
2762 noreturn
void freeze(void) {
2764 /* Make sure nobody waits for us on a socket anymore */
2765 close_all_fds(NULL
, 0);
2773 bool null_or_empty(struct stat
*st
) {
2776 if (S_ISREG(st
->st_mode
) && st
->st_size
<= 0)
2779 if (S_ISCHR(st
->st_mode
) || S_ISBLK(st
->st_mode
))
2785 int null_or_empty_path(const char *fn
) {
2790 if (stat(fn
, &st
) < 0)
2793 return null_or_empty(&st
);
2796 int null_or_empty_fd(int fd
) {
2801 if (fstat(fd
, &st
) < 0)
2804 return null_or_empty(&st
);
2807 DIR *xopendirat(int fd
, const char *name
, int flags
) {
2811 assert(!(flags
& O_CREAT
));
2813 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
2826 static char *tag_to_udev_node(const char *tagvalue
, const char *by
) {
2827 _cleanup_free_
char *t
= NULL
, *u
= NULL
;
2830 u
= unquote(tagvalue
, QUOTES
);
2834 enc_len
= strlen(u
) * 4 + 1;
2835 t
= new(char, enc_len
);
2839 if (encode_devnode_name(u
, t
, enc_len
) < 0)
2842 return strjoin("/dev/disk/by-", by
, "/", t
, NULL
);
2845 char *fstab_node_to_udev_node(const char *p
) {
2848 if (startswith(p
, "LABEL="))
2849 return tag_to_udev_node(p
+6, "label");
2851 if (startswith(p
, "UUID="))
2852 return tag_to_udev_node(p
+5, "uuid");
2854 if (startswith(p
, "PARTUUID="))
2855 return tag_to_udev_node(p
+9, "partuuid");
2857 if (startswith(p
, "PARTLABEL="))
2858 return tag_to_udev_node(p
+10, "partlabel");
2863 bool dirent_is_file(const struct dirent
*de
) {
2866 if (hidden_file(de
->d_name
))
2869 if (de
->d_type
!= DT_REG
&&
2870 de
->d_type
!= DT_LNK
&&
2871 de
->d_type
!= DT_UNKNOWN
)
2877 bool dirent_is_file_with_suffix(const struct dirent
*de
, const char *suffix
) {
2880 if (de
->d_type
!= DT_REG
&&
2881 de
->d_type
!= DT_LNK
&&
2882 de
->d_type
!= DT_UNKNOWN
)
2885 if (hidden_file_allow_backup(de
->d_name
))
2888 return endswith(de
->d_name
, suffix
);
2891 static int do_execute(char **directories
, usec_t timeout
, char *argv
[]) {
2892 _cleanup_hashmap_free_free_ Hashmap
*pids
= NULL
;
2893 _cleanup_set_free_free_ Set
*seen
= NULL
;
2896 /* We fork this all off from a child process so that we can
2897 * somewhat cleanly make use of SIGALRM to set a time limit */
2899 (void) reset_all_signal_handlers();
2900 (void) reset_signal_mask();
2902 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
2904 pids
= hashmap_new(NULL
);
2908 seen
= set_new(&string_hash_ops
);
2912 STRV_FOREACH(directory
, directories
) {
2913 _cleanup_closedir_
DIR *d
;
2916 d
= opendir(*directory
);
2918 if (errno
== ENOENT
)
2921 return log_error_errno(errno
, "Failed to open directory %s: %m", *directory
);
2924 FOREACH_DIRENT(de
, d
, break) {
2925 _cleanup_free_
char *path
= NULL
;
2929 if (!dirent_is_file(de
))
2932 if (set_contains(seen
, de
->d_name
)) {
2933 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory
, de
->d_name
);
2937 r
= set_put_strdup(seen
, de
->d_name
);
2941 path
= strjoin(*directory
, "/", de
->d_name
, NULL
);
2945 if (null_or_empty_path(path
)) {
2946 log_debug("%s is empty (a mask).", path
);
2952 log_error_errno(errno
, "Failed to fork: %m");
2954 } else if (pid
== 0) {
2957 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
2967 return log_error_errno(errno
, "Failed to execute %s: %m", path
);
2970 log_debug("Spawned %s as " PID_FMT
".", path
, pid
);
2972 r
= hashmap_put(pids
, UINT_TO_PTR(pid
), path
);
2979 /* Abort execution of this process after the timout. We simply
2980 * rely on SIGALRM as default action terminating the process,
2981 * and turn on alarm(). */
2983 if (timeout
!= USEC_INFINITY
)
2984 alarm((timeout
+ USEC_PER_SEC
- 1) / USEC_PER_SEC
);
2986 while (!hashmap_isempty(pids
)) {
2987 _cleanup_free_
char *path
= NULL
;
2990 pid
= PTR_TO_UINT(hashmap_first_key(pids
));
2993 path
= hashmap_remove(pids
, UINT_TO_PTR(pid
));
2996 wait_for_terminate_and_warn(path
, pid
, true);
3002 void execute_directories(const char* const* directories
, usec_t timeout
, char *argv
[]) {
3006 char **dirs
= (char**) directories
;
3008 assert(!strv_isempty(dirs
));
3010 name
= basename(dirs
[0]);
3011 assert(!isempty(name
));
3013 /* Executes all binaries in the directories in parallel and waits
3014 * for them to finish. Optionally a timeout is applied. If a file
3015 * with the same name exists in more than one directory, the
3016 * earliest one wins. */
3018 executor_pid
= fork();
3019 if (executor_pid
< 0) {
3020 log_error_errno(errno
, "Failed to fork: %m");
3023 } else if (executor_pid
== 0) {
3024 r
= do_execute(dirs
, timeout
, argv
);
3025 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
3028 wait_for_terminate_and_warn(name
, executor_pid
, true);
3031 bool nulstr_contains(const char*nulstr
, const char *needle
) {
3037 NULSTR_FOREACH(i
, nulstr
)
3038 if (streq(i
, needle
))
3044 bool plymouth_running(void) {
3045 return access("/run/plymouth/pid", F_OK
) >= 0;
3048 char* strshorten(char *s
, size_t l
) {
3057 int pipe_eof(int fd
) {
3058 struct pollfd pollfd
= {
3060 .events
= POLLIN
|POLLHUP
,
3065 r
= poll(&pollfd
, 1, 0);
3072 return pollfd
.revents
& POLLHUP
;
3075 int fd_wait_for_event(int fd
, int event
, usec_t t
) {
3077 struct pollfd pollfd
= {
3085 r
= ppoll(&pollfd
, 1, t
== USEC_INFINITY
? NULL
: timespec_store(&ts
, t
), NULL
);
3092 return pollfd
.revents
;
3095 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
3104 r
= tempfn_xxxxxx(path
, NULL
, &t
);
3108 fd
= mkostemp_safe(t
, O_WRONLY
|O_CLOEXEC
);
3114 f
= fdopen(fd
, "we");
3128 int symlink_atomic(const char *from
, const char *to
) {
3129 _cleanup_free_
char *t
= NULL
;
3135 r
= tempfn_random(to
, NULL
, &t
);
3139 if (symlink(from
, t
) < 0)
3142 if (rename(t
, to
) < 0) {
3150 int symlink_idempotent(const char *from
, const char *to
) {
3151 _cleanup_free_
char *p
= NULL
;
3157 if (symlink(from
, to
) < 0) {
3158 if (errno
!= EEXIST
)
3161 r
= readlink_malloc(to
, &p
);
3165 if (!streq(p
, from
))
3172 int mknod_atomic(const char *path
, mode_t mode
, dev_t dev
) {
3173 _cleanup_free_
char *t
= NULL
;
3178 r
= tempfn_random(path
, NULL
, &t
);
3182 if (mknod(t
, mode
, dev
) < 0)
3185 if (rename(t
, path
) < 0) {
3193 int mkfifo_atomic(const char *path
, mode_t mode
) {
3194 _cleanup_free_
char *t
= NULL
;
3199 r
= tempfn_random(path
, NULL
, &t
);
3203 if (mkfifo(t
, mode
) < 0)
3206 if (rename(t
, path
) < 0) {
3214 bool display_is_local(const char *display
) {
3218 display
[0] == ':' &&
3219 display
[1] >= '0' &&
3223 int socket_from_display(const char *display
, char **path
) {
3230 if (!display_is_local(display
))
3233 k
= strspn(display
+1, "0123456789");
3235 f
= new(char, strlen("/tmp/.X11-unix/X") + k
+ 1);
3239 c
= stpcpy(f
, "/tmp/.X11-unix/X");
3240 memcpy(c
, display
+1, k
);
3249 const char **username
,
3250 uid_t
*uid
, gid_t
*gid
,
3252 const char **shell
) {
3260 /* We enforce some special rules for uid=0: in order to avoid
3261 * NSS lookups for root we hardcode its data. */
3263 if (streq(*username
, "root") || streq(*username
, "0")) {
3281 if (parse_uid(*username
, &u
) >= 0) {
3285 /* If there are multiple users with the same id, make
3286 * sure to leave $USER to the configured value instead
3287 * of the first occurrence in the database. However if
3288 * the uid was configured by a numeric uid, then let's
3289 * pick the real username from /etc/passwd. */
3291 *username
= p
->pw_name
;
3294 p
= getpwnam(*username
);
3298 return errno
> 0 ? -errno
: -ESRCH
;
3310 *shell
= p
->pw_shell
;
3315 char* uid_to_name(uid_t uid
) {
3320 return strdup("root");
3324 return strdup(p
->pw_name
);
3326 if (asprintf(&r
, UID_FMT
, uid
) < 0)
3332 char* gid_to_name(gid_t gid
) {
3337 return strdup("root");
3341 return strdup(p
->gr_name
);
3343 if (asprintf(&r
, GID_FMT
, gid
) < 0)
3349 int get_group_creds(const char **groupname
, gid_t
*gid
) {
3355 /* We enforce some special rules for gid=0: in order to avoid
3356 * NSS lookups for root we hardcode its data. */
3358 if (streq(*groupname
, "root") || streq(*groupname
, "0")) {
3359 *groupname
= "root";
3367 if (parse_gid(*groupname
, &id
) >= 0) {
3372 *groupname
= g
->gr_name
;
3375 g
= getgrnam(*groupname
);
3379 return errno
> 0 ? -errno
: -ESRCH
;
3387 int in_gid(gid_t gid
) {
3389 int ngroups_max
, r
, i
;
3391 if (getgid() == gid
)
3394 if (getegid() == gid
)
3397 ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
3398 assert(ngroups_max
> 0);
3400 gids
= alloca(sizeof(gid_t
) * ngroups_max
);
3402 r
= getgroups(ngroups_max
, gids
);
3406 for (i
= 0; i
< r
; i
++)
3413 int in_group(const char *name
) {
3417 r
= get_group_creds(&name
, &gid
);
3424 int glob_exists(const char *path
) {
3425 _cleanup_globfree_ glob_t g
= {};
3431 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
3433 if (k
== GLOB_NOMATCH
)
3435 else if (k
== GLOB_NOSPACE
)
3438 return !strv_isempty(g
.gl_pathv
);
3440 return errno
? -errno
: -EIO
;
3443 int glob_extend(char ***strv
, const char *path
) {
3444 _cleanup_globfree_ glob_t g
= {};
3449 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
3451 if (k
== GLOB_NOMATCH
)
3453 else if (k
== GLOB_NOSPACE
)
3455 else if (k
!= 0 || strv_isempty(g
.gl_pathv
))
3456 return errno
? -errno
: -EIO
;
3458 STRV_FOREACH(p
, g
.gl_pathv
) {
3459 k
= strv_extend(strv
, *p
);
3467 int dirent_ensure_type(DIR *d
, struct dirent
*de
) {
3473 if (de
->d_type
!= DT_UNKNOWN
)
3476 if (fstatat(dirfd(d
), de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
3480 S_ISREG(st
.st_mode
) ? DT_REG
:
3481 S_ISDIR(st
.st_mode
) ? DT_DIR
:
3482 S_ISLNK(st
.st_mode
) ? DT_LNK
:
3483 S_ISFIFO(st
.st_mode
) ? DT_FIFO
:
3484 S_ISSOCK(st
.st_mode
) ? DT_SOCK
:
3485 S_ISCHR(st
.st_mode
) ? DT_CHR
:
3486 S_ISBLK(st
.st_mode
) ? DT_BLK
:
3492 int get_files_in_directory(const char *path
, char ***list
) {
3493 _cleanup_closedir_
DIR *d
= NULL
;
3494 size_t bufsize
= 0, n
= 0;
3495 _cleanup_strv_free_
char **l
= NULL
;
3499 /* Returns all files in a directory in *list, and the number
3500 * of files as return value. If list is NULL returns only the
3512 if (!de
&& errno
!= 0)
3517 dirent_ensure_type(d
, de
);
3519 if (!dirent_is_file(de
))
3523 /* one extra slot is needed for the terminating NULL */
3524 if (!GREEDY_REALLOC(l
, bufsize
, n
+ 2))
3527 l
[n
] = strdup(de
->d_name
);
3538 l
= NULL
; /* avoid freeing */
3544 char *strjoin(const char *x
, ...) {
3558 t
= va_arg(ap
, const char *);
3563 if (n
> ((size_t) -1) - l
) {
3587 t
= va_arg(ap
, const char *);
3601 bool is_main_thread(void) {
3602 static thread_local
int cached
= 0;
3604 if (_unlikely_(cached
== 0))
3605 cached
= getpid() == gettid() ? 1 : -1;
3610 int block_get_whole_disk(dev_t d
, dev_t
*ret
) {
3617 /* If it has a queue this is good enough for us */
3618 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", major(d
), minor(d
)) < 0)
3621 r
= access(p
, F_OK
);
3629 /* If it is a partition find the originating device */
3630 if (asprintf(&p
, "/sys/dev/block/%u:%u/partition", major(d
), minor(d
)) < 0)
3633 r
= access(p
, F_OK
);
3639 /* Get parent dev_t */
3640 if (asprintf(&p
, "/sys/dev/block/%u:%u/../dev", major(d
), minor(d
)) < 0)
3643 r
= read_one_line_file(p
, &s
);
3649 r
= sscanf(s
, "%u:%u", &m
, &n
);
3655 /* Only return this if it is really good enough for us. */
3656 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", m
, n
) < 0)
3659 r
= access(p
, F_OK
);
3663 *ret
= makedev(m
, n
);
3670 static const char *const ioprio_class_table
[] = {
3671 [IOPRIO_CLASS_NONE
] = "none",
3672 [IOPRIO_CLASS_RT
] = "realtime",
3673 [IOPRIO_CLASS_BE
] = "best-effort",
3674 [IOPRIO_CLASS_IDLE
] = "idle"
3677 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, INT_MAX
);
3679 static const char *const sigchld_code_table
[] = {
3680 [CLD_EXITED
] = "exited",
3681 [CLD_KILLED
] = "killed",
3682 [CLD_DUMPED
] = "dumped",
3683 [CLD_TRAPPED
] = "trapped",
3684 [CLD_STOPPED
] = "stopped",
3685 [CLD_CONTINUED
] = "continued",
3688 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
3690 static const char *const log_facility_unshifted_table
[LOG_NFACILITIES
] = {
3691 [LOG_FAC(LOG_KERN
)] = "kern",
3692 [LOG_FAC(LOG_USER
)] = "user",
3693 [LOG_FAC(LOG_MAIL
)] = "mail",
3694 [LOG_FAC(LOG_DAEMON
)] = "daemon",
3695 [LOG_FAC(LOG_AUTH
)] = "auth",
3696 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
3697 [LOG_FAC(LOG_LPR
)] = "lpr",
3698 [LOG_FAC(LOG_NEWS
)] = "news",
3699 [LOG_FAC(LOG_UUCP
)] = "uucp",
3700 [LOG_FAC(LOG_CRON
)] = "cron",
3701 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
3702 [LOG_FAC(LOG_FTP
)] = "ftp",
3703 [LOG_FAC(LOG_LOCAL0
)] = "local0",
3704 [LOG_FAC(LOG_LOCAL1
)] = "local1",
3705 [LOG_FAC(LOG_LOCAL2
)] = "local2",
3706 [LOG_FAC(LOG_LOCAL3
)] = "local3",
3707 [LOG_FAC(LOG_LOCAL4
)] = "local4",
3708 [LOG_FAC(LOG_LOCAL5
)] = "local5",
3709 [LOG_FAC(LOG_LOCAL6
)] = "local6",
3710 [LOG_FAC(LOG_LOCAL7
)] = "local7"
3713 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted
, int, LOG_FAC(~0));
3715 static const char *const log_level_table
[] = {
3716 [LOG_EMERG
] = "emerg",
3717 [LOG_ALERT
] = "alert",
3718 [LOG_CRIT
] = "crit",
3720 [LOG_WARNING
] = "warning",
3721 [LOG_NOTICE
] = "notice",
3722 [LOG_INFO
] = "info",
3723 [LOG_DEBUG
] = "debug"
3726 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level
, int, LOG_DEBUG
);
3728 static const char* const sched_policy_table
[] = {
3729 [SCHED_OTHER
] = "other",
3730 [SCHED_BATCH
] = "batch",
3731 [SCHED_IDLE
] = "idle",
3732 [SCHED_FIFO
] = "fifo",
3736 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);
3738 static const char* const rlimit_table
[_RLIMIT_MAX
] = {
3739 [RLIMIT_CPU
] = "LimitCPU",
3740 [RLIMIT_FSIZE
] = "LimitFSIZE",
3741 [RLIMIT_DATA
] = "LimitDATA",
3742 [RLIMIT_STACK
] = "LimitSTACK",
3743 [RLIMIT_CORE
] = "LimitCORE",
3744 [RLIMIT_RSS
] = "LimitRSS",
3745 [RLIMIT_NOFILE
] = "LimitNOFILE",
3746 [RLIMIT_AS
] = "LimitAS",
3747 [RLIMIT_NPROC
] = "LimitNPROC",
3748 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
3749 [RLIMIT_LOCKS
] = "LimitLOCKS",
3750 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
3751 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
3752 [RLIMIT_NICE
] = "LimitNICE",
3753 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
3754 [RLIMIT_RTTIME
] = "LimitRTTIME"
3757 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
3759 static const char* const ip_tos_table
[] = {
3760 [IPTOS_LOWDELAY
] = "low-delay",
3761 [IPTOS_THROUGHPUT
] = "throughput",
3762 [IPTOS_RELIABILITY
] = "reliability",
3763 [IPTOS_LOWCOST
] = "low-cost",
3766 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
3768 bool kexec_loaded(void) {
3769 bool loaded
= false;
3772 if (read_one_line_file("/sys/kernel/kexec_loaded", &s
) >= 0) {
3780 int prot_from_flags(int flags
) {
3782 switch (flags
& O_ACCMODE
) {
3791 return PROT_READ
|PROT_WRITE
;
3798 char *format_bytes(char *buf
, size_t l
, uint64_t t
) {
3801 static const struct {
3805 { "E", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3806 { "P", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3807 { "T", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3808 { "G", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3809 { "M", UINT64_C(1024)*UINT64_C(1024) },
3810 { "K", UINT64_C(1024) },
3813 if (t
== (uint64_t) -1)
3816 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
3818 if (t
>= table
[i
].factor
) {
3820 "%" PRIu64
".%" PRIu64
"%s",
3821 t
/ table
[i
].factor
,
3822 ((t
*UINT64_C(10)) / table
[i
].factor
) % UINT64_C(10),
3829 snprintf(buf
, l
, "%" PRIu64
"B", t
);
3837 void* memdup(const void *p
, size_t l
) {
3850 int fd_inc_sndbuf(int fd
, size_t n
) {
3852 socklen_t l
= sizeof(value
);
3854 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
3855 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
3858 /* If we have the privileges we will ignore the kernel limit. */
3861 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
3862 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
3868 int fd_inc_rcvbuf(int fd
, size_t n
) {
3870 socklen_t l
= sizeof(value
);
3872 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
3873 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
3876 /* If we have the privileges we will ignore the kernel limit. */
3879 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
3880 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
3885 int fork_agent(pid_t
*pid
, const int except
[], unsigned n_except
, const char *path
, ...) {
3886 bool stdout_is_tty
, stderr_is_tty
;
3887 pid_t parent_pid
, agent_pid
;
3888 sigset_t ss
, saved_ss
;
3896 /* Spawns a temporary TTY agent, making sure it goes away when
3899 parent_pid
= getpid();
3901 /* First we temporarily block all signals, so that the new
3902 * child has them blocked initially. This way, we can be sure
3903 * that SIGTERMs are not lost we might send to the agent. */
3904 assert_se(sigfillset(&ss
) >= 0);
3905 assert_se(sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) >= 0);
3908 if (agent_pid
< 0) {
3909 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
3913 if (agent_pid
!= 0) {
3914 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
3921 * Make sure the agent goes away when the parent dies */
3922 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
3923 _exit(EXIT_FAILURE
);
3925 /* Make sure we actually can kill the agent, if we need to, in
3926 * case somebody invoked us from a shell script that trapped
3927 * SIGTERM or so... */
3928 (void) reset_all_signal_handlers();
3929 (void) reset_signal_mask();
3931 /* Check whether our parent died before we were able
3932 * to set the death signal and unblock the signals */
3933 if (getppid() != parent_pid
)
3934 _exit(EXIT_SUCCESS
);
3936 /* Don't leak fds to the agent */
3937 close_all_fds(except
, n_except
);
3939 stdout_is_tty
= isatty(STDOUT_FILENO
);
3940 stderr_is_tty
= isatty(STDERR_FILENO
);
3942 if (!stdout_is_tty
|| !stderr_is_tty
) {
3945 /* Detach from stdout/stderr. and reopen
3946 * /dev/tty for them. This is important to
3947 * ensure that when systemctl is started via
3948 * popen() or a similar call that expects to
3949 * read EOF we actually do generate EOF and
3950 * not delay this indefinitely by because we
3951 * keep an unused copy of stdin around. */
3952 fd
= open("/dev/tty", O_WRONLY
);
3954 log_error_errno(errno
, "Failed to open /dev/tty: %m");
3955 _exit(EXIT_FAILURE
);
3959 dup2(fd
, STDOUT_FILENO
);
3962 dup2(fd
, STDERR_FILENO
);
3968 /* Count arguments */
3970 for (n
= 0; va_arg(ap
, char*); n
++)
3975 l
= alloca(sizeof(char *) * (n
+ 1));
3977 /* Fill in arguments */
3979 for (i
= 0; i
<= n
; i
++)
3980 l
[i
] = va_arg(ap
, char*);
3984 _exit(EXIT_FAILURE
);
3987 int setrlimit_closest(int resource
, const struct rlimit
*rlim
) {
3988 struct rlimit highest
, fixed
;
3992 if (setrlimit(resource
, rlim
) >= 0)
3998 /* So we failed to set the desired setrlimit, then let's try
3999 * to get as close as we can */
4000 assert_se(getrlimit(resource
, &highest
) == 0);
4002 fixed
.rlim_cur
= MIN(rlim
->rlim_cur
, highest
.rlim_max
);
4003 fixed
.rlim_max
= MIN(rlim
->rlim_max
, highest
.rlim_max
);
4005 if (setrlimit(resource
, &fixed
) < 0)
4011 bool http_etag_is_valid(const char *etag
) {
4015 if (!endswith(etag
, "\""))
4018 if (!startswith(etag
, "\"") && !startswith(etag
, "W/\""))
4024 bool http_url_is_valid(const char *url
) {
4030 p
= startswith(url
, "http://");
4032 p
= startswith(url
, "https://");
4039 return ascii_is_valid(p
);
4042 bool documentation_url_is_valid(const char *url
) {
4048 if (http_url_is_valid(url
))
4051 p
= startswith(url
, "file:/");
4053 p
= startswith(url
, "info:");
4055 p
= startswith(url
, "man:");
4060 return ascii_is_valid(p
);
4063 bool in_initrd(void) {
4064 static int saved
= -1;
4070 /* We make two checks here:
4072 * 1. the flag file /etc/initrd-release must exist
4073 * 2. the root file system must be a memory file system
4075 * The second check is extra paranoia, since misdetecting an
4076 * initrd can have bad bad consequences due the initrd
4077 * emptying when transititioning to the main systemd.
4080 saved
= access("/etc/initrd-release", F_OK
) >= 0 &&
4081 statfs("/", &s
) >= 0 &&
4082 is_temporary_fs(&s
);
4087 int get_home_dir(char **_h
) {
4095 /* Take the user specified one */
4096 e
= secure_getenv("HOME");
4097 if (e
&& path_is_absolute(e
)) {
4106 /* Hardcode home directory for root to avoid NSS */
4109 h
= strdup("/root");
4117 /* Check the database... */
4121 return errno
> 0 ? -errno
: -ESRCH
;
4123 if (!path_is_absolute(p
->pw_dir
))
4126 h
= strdup(p
->pw_dir
);
4134 int get_shell(char **_s
) {
4142 /* Take the user specified one */
4143 e
= getenv("SHELL");
4153 /* Hardcode home directory for root to avoid NSS */
4156 s
= strdup("/bin/sh");
4164 /* Check the database... */
4168 return errno
> 0 ? -errno
: -ESRCH
;
4170 if (!path_is_absolute(p
->pw_shell
))
4173 s
= strdup(p
->pw_shell
);
4181 bool filename_is_valid(const char *p
) {
4195 if (strlen(p
) > FILENAME_MAX
)
4201 bool string_is_safe(const char *p
) {
4207 for (t
= p
; *t
; t
++) {
4208 if (*t
> 0 && *t
< ' ')
4211 if (strchr("\\\"\'\x7f", *t
))
4219 * Check if a string contains control characters. If 'ok' is non-NULL
4220 * it may be a string containing additional CCs to be considered OK.
4222 bool string_has_cc(const char *p
, const char *ok
) {
4227 for (t
= p
; *t
; t
++) {
4228 if (ok
&& strchr(ok
, *t
))
4231 if (*t
> 0 && *t
< ' ')
4241 bool path_is_safe(const char *p
) {
4246 if (streq(p
, "..") || startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
4249 if (strlen(p
)+1 > PATH_MAX
)
4252 /* The following two checks are not really dangerous, but hey, they still are confusing */
4253 if (streq(p
, ".") || startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
4256 if (strstr(p
, "//"))
4262 /* hey glibc, APIs with callbacks without a user pointer are so useless */
4263 void *xbsearch_r(const void *key
, const void *base
, size_t nmemb
, size_t size
,
4264 int (*compar
) (const void *, const void *, void *), void *arg
) {
4273 p
= (void *)(((const char *) base
) + (idx
* size
));
4274 comparison
= compar(key
, p
, arg
);
4277 else if (comparison
> 0)
4285 void init_gettext(void) {
4286 setlocale(LC_ALL
, "");
4287 textdomain(GETTEXT_PACKAGE
);
4290 bool is_locale_utf8(void) {
4292 static int cached_answer
= -1;
4294 if (cached_answer
>= 0)
4297 if (!setlocale(LC_ALL
, "")) {
4298 cached_answer
= true;
4302 set
= nl_langinfo(CODESET
);
4304 cached_answer
= true;
4308 if (streq(set
, "UTF-8")) {
4309 cached_answer
= true;
4313 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
4314 * unset and everything can do to UTF-8 nowadays. */
4315 set
= setlocale(LC_CTYPE
, NULL
);
4317 cached_answer
= true;
4321 /* Check result, but ignore the result if C was set
4324 STR_IN_SET(set
, "C", "POSIX") &&
4325 !getenv("LC_ALL") &&
4326 !getenv("LC_CTYPE") &&
4330 return (bool) cached_answer
;
4333 const char *draw_special_char(DrawSpecialChar ch
) {
4334 static const char *draw_table
[2][_DRAW_SPECIAL_CHAR_MAX
] = {
4337 [DRAW_TREE_VERTICAL
] = "\342\224\202 ", /* │ */
4338 [DRAW_TREE_BRANCH
] = "\342\224\234\342\224\200", /* ├─ */
4339 [DRAW_TREE_RIGHT
] = "\342\224\224\342\224\200", /* └─ */
4340 [DRAW_TREE_SPACE
] = " ", /* */
4341 [DRAW_TRIANGULAR_BULLET
] = "\342\200\243", /* ‣ */
4342 [DRAW_BLACK_CIRCLE
] = "\342\227\217", /* ● */
4343 [DRAW_ARROW
] = "\342\206\222", /* → */
4344 [DRAW_DASH
] = "\342\200\223", /* – */
4347 /* ASCII fallback */ {
4348 [DRAW_TREE_VERTICAL
] = "| ",
4349 [DRAW_TREE_BRANCH
] = "|-",
4350 [DRAW_TREE_RIGHT
] = "`-",
4351 [DRAW_TREE_SPACE
] = " ",
4352 [DRAW_TRIANGULAR_BULLET
] = ">",
4353 [DRAW_BLACK_CIRCLE
] = "*",
4354 [DRAW_ARROW
] = "->",
4359 return draw_table
[!is_locale_utf8()][ch
];
4362 char *strreplace(const char *text
, const char *old_string
, const char *new_string
) {
4365 size_t l
, old_len
, new_len
;
4371 old_len
= strlen(old_string
);
4372 new_len
= strlen(new_string
);
4385 if (!startswith(f
, old_string
)) {
4391 nl
= l
- old_len
+ new_len
;
4392 a
= realloc(r
, nl
+ 1);
4400 t
= stpcpy(t
, new_string
);
4412 char *strip_tab_ansi(char **ibuf
, size_t *_isz
) {
4413 const char *i
, *begin
= NULL
;
4418 } state
= STATE_OTHER
;
4420 size_t osz
= 0, isz
;
4426 /* Strips ANSI color and replaces TABs by 8 spaces */
4428 isz
= _isz
? *_isz
: strlen(*ibuf
);
4430 f
= open_memstream(&obuf
, &osz
);
4434 for (i
= *ibuf
; i
< *ibuf
+ isz
+ 1; i
++) {
4439 if (i
>= *ibuf
+ isz
) /* EOT */
4441 else if (*i
== '\x1B')
4442 state
= STATE_ESCAPE
;
4443 else if (*i
== '\t')
4450 if (i
>= *ibuf
+ isz
) { /* EOT */
4453 } else if (*i
== '[') {
4454 state
= STATE_BRACKET
;
4459 state
= STATE_OTHER
;
4466 if (i
>= *ibuf
+ isz
|| /* EOT */
4467 (!(*i
>= '0' && *i
<= '9') && *i
!= ';' && *i
!= 'm')) {
4470 state
= STATE_OTHER
;
4472 } else if (*i
== 'm')
4473 state
= STATE_OTHER
;
4495 int on_ac_power(void) {
4496 bool found_offline
= false, found_online
= false;
4497 _cleanup_closedir_
DIR *d
= NULL
;
4499 d
= opendir("/sys/class/power_supply");
4501 return errno
== ENOENT
? true : -errno
;
4505 _cleanup_close_
int fd
= -1, device
= -1;
4511 if (!de
&& errno
!= 0)
4517 if (hidden_file(de
->d_name
))
4520 device
= openat(dirfd(d
), de
->d_name
, O_DIRECTORY
|O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4522 if (errno
== ENOENT
|| errno
== ENOTDIR
)
4528 fd
= openat(device
, "type", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4530 if (errno
== ENOENT
)
4536 n
= read(fd
, contents
, sizeof(contents
));
4540 if (n
!= 6 || memcmp(contents
, "Mains\n", 6))
4544 fd
= openat(device
, "online", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4546 if (errno
== ENOENT
)
4552 n
= read(fd
, contents
, sizeof(contents
));
4556 if (n
!= 2 || contents
[1] != '\n')
4559 if (contents
[0] == '1') {
4560 found_online
= true;
4562 } else if (contents
[0] == '0')
4563 found_offline
= true;
4568 return found_online
|| !found_offline
;
4571 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
4578 if (!path_strv_resolve_uniq(search
, root
))
4581 STRV_FOREACH(i
, search
) {
4582 _cleanup_free_
char *p
= NULL
;
4586 p
= strjoin(root
, *i
, "/", path
, NULL
);
4588 p
= strjoin(*i
, "/", path
, NULL
);
4598 if (errno
!= ENOENT
)
4605 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
4606 _cleanup_strv_free_
char **copy
= NULL
;
4612 if (path_is_absolute(path
)) {
4615 f
= fopen(path
, mode
);
4624 copy
= strv_copy((char**) search
);
4628 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
4631 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
4632 _cleanup_strv_free_
char **s
= NULL
;
4634 if (path_is_absolute(path
)) {
4637 f
= fopen(path
, mode
);
4646 s
= strv_split_nulstr(search
);
4650 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
4653 char *strextend(char **x
, ...) {
4660 l
= f
= *x
? strlen(*x
) : 0;
4667 t
= va_arg(ap
, const char *);
4672 if (n
> ((size_t) -1) - l
) {
4681 r
= realloc(*x
, l
+1);
4691 t
= va_arg(ap
, const char *);
4705 char *strrep(const char *s
, unsigned n
) {
4713 p
= r
= malloc(l
* n
+ 1);
4717 for (i
= 0; i
< n
; i
++)
4724 void* greedy_realloc(void **p
, size_t *allocated
, size_t need
, size_t size
) {
4731 if (*allocated
>= need
)
4734 newalloc
= MAX(need
* 2, 64u / size
);
4735 a
= newalloc
* size
;
4737 /* check for overflows */
4738 if (a
< size
* need
)
4746 *allocated
= newalloc
;
4750 void* greedy_realloc0(void **p
, size_t *allocated
, size_t need
, size_t size
) {
4759 q
= greedy_realloc(p
, allocated
, need
, size
);
4763 if (*allocated
> prev
)
4764 memzero(q
+ prev
* size
, (*allocated
- prev
) * size
);
4769 bool id128_is_valid(const char *s
) {
4775 /* Simple formatted 128bit hex string */
4777 for (i
= 0; i
< l
; i
++) {
4780 if (!(c
>= '0' && c
<= '9') &&
4781 !(c
>= 'a' && c
<= 'z') &&
4782 !(c
>= 'A' && c
<= 'Z'))
4786 } else if (l
== 36) {
4788 /* Formatted UUID */
4790 for (i
= 0; i
< l
; i
++) {
4793 if ((i
== 8 || i
== 13 || i
== 18 || i
== 23)) {
4797 if (!(c
>= '0' && c
<= '9') &&
4798 !(c
>= 'a' && c
<= 'z') &&
4799 !(c
>= 'A' && c
<= 'Z'))
4810 int split_pair(const char *s
, const char *sep
, char **l
, char **r
) {
4825 a
= strndup(s
, x
- s
);
4829 b
= strdup(x
+ strlen(sep
));
4841 int shall_restore_state(void) {
4842 _cleanup_free_
char *value
= NULL
;
4845 r
= get_proc_cmdline_key("systemd.restore_state=", &value
);
4851 return parse_boolean(value
) != 0;
4854 int proc_cmdline(char **ret
) {
4857 if (detect_container() > 0)
4858 return get_process_cmdline(1, 0, false, ret
);
4860 return read_one_line_file("/proc/cmdline", ret
);
4863 int parse_proc_cmdline(int (*parse_item
)(const char *key
, const char *value
)) {
4864 _cleanup_free_
char *line
= NULL
;
4870 r
= proc_cmdline(&line
);
4876 _cleanup_free_
char *word
= NULL
;
4879 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
4885 /* Filter out arguments that are intended only for the
4887 if (!in_initrd() && startswith(word
, "rd."))
4890 value
= strchr(word
, '=');
4894 r
= parse_item(word
, value
);
4902 int get_proc_cmdline_key(const char *key
, char **value
) {
4903 _cleanup_free_
char *line
= NULL
, *ret
= NULL
;
4910 r
= proc_cmdline(&line
);
4916 _cleanup_free_
char *word
= NULL
;
4919 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
4925 /* Filter out arguments that are intended only for the
4927 if (!in_initrd() && startswith(word
, "rd."))
4931 e
= startswith(word
, key
);
4935 r
= free_and_strdup(&ret
, e
);
4941 if (streq(word
, key
))
4955 int container_get_leader(const char *machine
, pid_t
*pid
) {
4956 _cleanup_free_
char *s
= NULL
, *class = NULL
;
4964 if (!machine_name_is_valid(machine
))
4967 p
= strjoina("/run/systemd/machines/", machine
);
4968 r
= parse_env_file(p
, NEWLINE
, "LEADER", &s
, "CLASS", &class, NULL
);
4976 if (!streq_ptr(class, "container"))
4979 r
= parse_pid(s
, &leader
);
4989 int namespace_open(pid_t pid
, int *pidns_fd
, int *mntns_fd
, int *netns_fd
, int *userns_fd
, int *root_fd
) {
4990 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, netnsfd
= -1, usernsfd
= -1;
4998 mntns
= procfs_file_alloca(pid
, "ns/mnt");
4999 mntnsfd
= open(mntns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5007 pidns
= procfs_file_alloca(pid
, "ns/pid");
5008 pidnsfd
= open(pidns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5016 netns
= procfs_file_alloca(pid
, "ns/net");
5017 netnsfd
= open(netns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5025 userns
= procfs_file_alloca(pid
, "ns/user");
5026 usernsfd
= open(userns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
5027 if (usernsfd
< 0 && errno
!= ENOENT
)
5034 root
= procfs_file_alloca(pid
, "root");
5035 rfd
= open(root
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
|O_DIRECTORY
);
5041 *pidns_fd
= pidnsfd
;
5044 *mntns_fd
= mntnsfd
;
5047 *netns_fd
= netnsfd
;
5050 *userns_fd
= usernsfd
;
5055 pidnsfd
= mntnsfd
= netnsfd
= usernsfd
= -1;
5060 int namespace_enter(int pidns_fd
, int mntns_fd
, int netns_fd
, int userns_fd
, int root_fd
) {
5061 if (userns_fd
>= 0) {
5062 /* Can't setns to your own userns, since then you could
5063 * escalate from non-root to root in your own namespace, so
5064 * check if namespaces equal before attempting to enter. */
5065 _cleanup_free_
char *userns_fd_path
= NULL
;
5067 if (asprintf(&userns_fd_path
, "/proc/self/fd/%d", userns_fd
) < 0)
5070 r
= files_same(userns_fd_path
, "/proc/self/ns/user");
5078 if (setns(pidns_fd
, CLONE_NEWPID
) < 0)
5082 if (setns(mntns_fd
, CLONE_NEWNS
) < 0)
5086 if (setns(netns_fd
, CLONE_NEWNET
) < 0)
5090 if (setns(userns_fd
, CLONE_NEWUSER
) < 0)
5094 if (fchdir(root_fd
) < 0)
5097 if (chroot(".") < 0)
5101 return reset_uid_gid();
5104 int getpeercred(int fd
, struct ucred
*ucred
) {
5105 socklen_t n
= sizeof(struct ucred
);
5112 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
);
5116 if (n
!= sizeof(struct ucred
))
5119 /* Check if the data is actually useful and not suppressed due
5120 * to namespacing issues */
5123 if (u
.uid
== UID_INVALID
)
5125 if (u
.gid
== GID_INVALID
)
5132 int getpeersec(int fd
, char **ret
) {
5144 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
5148 if (errno
!= ERANGE
)
5155 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
5171 /* This is much like like mkostemp() but is subject to umask(). */
5172 int mkostemp_safe(char *pattern
, int flags
) {
5173 _cleanup_umask_ mode_t u
;
5180 fd
= mkostemp(pattern
, flags
);
5187 int open_tmpfile(const char *path
, int flags
) {
5194 /* Try O_TMPFILE first, if it is supported */
5195 fd
= open(path
, flags
|O_TMPFILE
|O_EXCL
, S_IRUSR
|S_IWUSR
);
5200 /* Fall back to unguessable name + unlinking */
5201 p
= strjoina(path
, "/systemd-tmp-XXXXXX");
5203 fd
= mkostemp_safe(p
, flags
);
5211 int fd_warn_permissions(const char *path
, int fd
) {
5214 if (fstat(fd
, &st
) < 0)
5217 if (st
.st_mode
& 0111)
5218 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path
);
5220 if (st
.st_mode
& 0002)
5221 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path
);
5223 if (getpid() == 1 && (st
.st_mode
& 0044) != 0044)
5224 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
);
5229 unsigned long personality_from_string(const char *p
) {
5231 /* Parse a personality specifier. We introduce our own
5232 * identifiers that indicate specific ABIs, rather than just
5233 * hints regarding the register size, since we want to keep
5234 * things open for multiple locally supported ABIs for the
5235 * same register size. We try to reuse the ABI identifiers
5236 * used by libseccomp. */
5238 #if defined(__x86_64__)
5240 if (streq(p
, "x86"))
5243 if (streq(p
, "x86-64"))
5246 #elif defined(__i386__)
5248 if (streq(p
, "x86"))
5252 return PERSONALITY_INVALID
;
5255 const char* personality_to_string(unsigned long p
) {
5257 #if defined(__x86_64__)
5259 if (p
== PER_LINUX32
)
5265 #elif defined(__i386__)
5274 uint64_t physical_memory(void) {
5277 /* We return this as uint64_t in case we are running as 32bit
5278 * process on a 64bit kernel with huge amounts of memory */
5280 mem
= sysconf(_SC_PHYS_PAGES
);
5283 return (uint64_t) mem
* (uint64_t) page_size();
5286 void hexdump(FILE *f
, const void *p
, size_t s
) {
5287 const uint8_t *b
= p
;
5290 assert(s
== 0 || b
);
5295 fprintf(f
, "%04x ", n
);
5297 for (i
= 0; i
< 16; i
++) {
5302 fprintf(f
, "%02x ", b
[i
]);
5310 for (i
= 0; i
< 16; i
++) {
5315 fputc(isprint(b
[i
]) ? (char) b
[i
] : '.', f
);
5329 int update_reboot_param_file(const char *param
) {
5334 r
= write_string_file(REBOOT_PARAM_FILE
, param
, WRITE_STRING_FILE_CREATE
);
5336 log_error("Failed to write reboot param to "
5337 REBOOT_PARAM_FILE
": %s", strerror(-r
));
5339 unlink(REBOOT_PARAM_FILE
);
5344 int umount_recursive(const char *prefix
, int flags
) {
5348 /* Try to umount everything recursively below a
5349 * directory. Also, take care of stacked mounts, and keep
5350 * unmounting them until they are gone. */
5353 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
5358 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
5359 if (!proc_self_mountinfo
)
5363 _cleanup_free_
char *path
= NULL
, *p
= NULL
;
5366 k
= fscanf(proc_self_mountinfo
,
5367 "%*s " /* (1) mount id */
5368 "%*s " /* (2) parent id */
5369 "%*s " /* (3) major:minor */
5370 "%*s " /* (4) root */
5371 "%ms " /* (5) mount point */
5372 "%*s" /* (6) mount options */
5373 "%*[^-]" /* (7) optional fields */
5374 "- " /* (8) separator */
5375 "%*s " /* (9) file system type */
5376 "%*s" /* (10) mount source */
5377 "%*s" /* (11) mount options 2 */
5378 "%*[^\n]", /* some rubbish at the end */
5387 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
5391 if (!path_startswith(p
, prefix
))
5394 if (umount2(p
, flags
) < 0) {
5410 static int get_mount_flags(const char *path
, unsigned long *flags
) {
5413 if (statvfs(path
, &buf
) < 0)
5415 *flags
= buf
.f_flag
;
5419 int bind_remount_recursive(const char *prefix
, bool ro
) {
5420 _cleanup_set_free_free_ Set
*done
= NULL
;
5421 _cleanup_free_
char *cleaned
= NULL
;
5424 /* Recursively remount a directory (and all its submounts)
5425 * read-only or read-write. If the directory is already
5426 * mounted, we reuse the mount and simply mark it
5427 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
5428 * operation). If it isn't we first make it one. Afterwards we
5429 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
5430 * submounts we can access, too. When mounts are stacked on
5431 * the same mount point we only care for each individual
5432 * "top-level" mount on each point, as we cannot
5433 * influence/access the underlying mounts anyway. We do not
5434 * have any effect on future submounts that might get
5435 * propagated, they migt be writable. This includes future
5436 * submounts that have been triggered via autofs. */
5438 cleaned
= strdup(prefix
);
5442 path_kill_slashes(cleaned
);
5444 done
= set_new(&string_hash_ops
);
5449 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
5450 _cleanup_set_free_free_ Set
*todo
= NULL
;
5451 bool top_autofs
= false;
5453 unsigned long orig_flags
;
5455 todo
= set_new(&string_hash_ops
);
5459 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
5460 if (!proc_self_mountinfo
)
5464 _cleanup_free_
char *path
= NULL
, *p
= NULL
, *type
= NULL
;
5467 k
= fscanf(proc_self_mountinfo
,
5468 "%*s " /* (1) mount id */
5469 "%*s " /* (2) parent id */
5470 "%*s " /* (3) major:minor */
5471 "%*s " /* (4) root */
5472 "%ms " /* (5) mount point */
5473 "%*s" /* (6) mount options (superblock) */
5474 "%*[^-]" /* (7) optional fields */
5475 "- " /* (8) separator */
5476 "%ms " /* (9) file system type */
5477 "%*s" /* (10) mount source */
5478 "%*s" /* (11) mount options (bind mount) */
5479 "%*[^\n]", /* some rubbish at the end */
5489 r
= cunescape(path
, UNESCAPE_RELAX
, &p
);
5493 /* Let's ignore autofs mounts. If they aren't
5494 * triggered yet, we want to avoid triggering
5495 * them, as we don't make any guarantees for
5496 * future submounts anyway. If they are
5497 * already triggered, then we will find
5498 * another entry for this. */
5499 if (streq(type
, "autofs")) {
5500 top_autofs
= top_autofs
|| path_equal(cleaned
, p
);
5504 if (path_startswith(p
, cleaned
) &&
5505 !set_contains(done
, p
)) {
5507 r
= set_consume(todo
, p
);
5517 /* If we have no submounts to process anymore and if
5518 * the root is either already done, or an autofs, we
5520 if (set_isempty(todo
) &&
5521 (top_autofs
|| set_contains(done
, cleaned
)))
5524 if (!set_contains(done
, cleaned
) &&
5525 !set_contains(todo
, cleaned
)) {
5526 /* The prefix directory itself is not yet a
5527 * mount, make it one. */
5528 if (mount(cleaned
, cleaned
, NULL
, MS_BIND
|MS_REC
, NULL
) < 0)
5532 (void) get_mount_flags(cleaned
, &orig_flags
);
5533 orig_flags
&= ~MS_RDONLY
;
5535 if (mount(NULL
, prefix
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0)
5538 x
= strdup(cleaned
);
5542 r
= set_consume(done
, x
);
5547 while ((x
= set_steal_first(todo
))) {
5549 r
= set_consume(done
, x
);
5550 if (r
== -EEXIST
|| r
== 0)
5555 /* Try to reuse the original flag set, but
5556 * don't care for errors, in case of
5557 * obstructed mounts */
5559 (void) get_mount_flags(x
, &orig_flags
);
5560 orig_flags
&= ~MS_RDONLY
;
5562 if (mount(NULL
, x
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0) {
5564 /* Deal with mount points that are
5565 * obstructed by a later mount */
5567 if (errno
!= ENOENT
)
5575 int fflush_and_check(FILE *f
) {
5582 return errno
? -errno
: -EIO
;
5587 int tempfn_xxxxxx(const char *p
, const char *extra
, char **ret
) {
5599 * /foo/bar/.#<extra>waldoXXXXXX
5603 if (!filename_is_valid(fn
))
5609 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 6 + 1);
5613 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
), "XXXXXX");
5615 *ret
= path_kill_slashes(t
);
5619 int tempfn_random(const char *p
, const char *extra
, char **ret
) {
5633 * /foo/bar/.#<extra>waldobaa2a261115984a9
5637 if (!filename_is_valid(fn
))
5643 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 16 + 1);
5647 x
= stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
);
5650 for (i
= 0; i
< 16; i
++) {
5651 *(x
++) = hexchar(u
& 0xF);
5657 *ret
= path_kill_slashes(t
);
5661 int tempfn_random_child(const char *p
, const char *extra
, char **ret
) {
5672 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
5678 t
= new(char, strlen(p
) + 3 + strlen(extra
) + 16 + 1);
5682 x
= stpcpy(stpcpy(stpcpy(t
, p
), "/.#"), extra
);
5685 for (i
= 0; i
< 16; i
++) {
5686 *(x
++) = hexchar(u
& 0xF);
5692 *ret
= path_kill_slashes(t
);
5696 int take_password_lock(const char *root
) {
5698 struct flock flock
= {
5700 .l_whence
= SEEK_SET
,
5708 /* This is roughly the same as lckpwdf(), but not as awful. We
5709 * don't want to use alarm() and signals, hence we implement
5710 * our own trivial version of this.
5712 * Note that shadow-utils also takes per-database locks in
5713 * addition to lckpwdf(). However, we don't given that they
5714 * are redundant as they they invoke lckpwdf() first and keep
5715 * it during everything they do. The per-database locks are
5716 * awfully racy, and thus we just won't do them. */
5719 path
= strjoina(root
, "/etc/.pwd.lock");
5721 path
= "/etc/.pwd.lock";
5723 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
5727 r
= fcntl(fd
, F_SETLKW
, &flock
);
5736 int is_symlink(const char *path
) {
5739 if (lstat(path
, &info
) < 0)
5742 return !!S_ISLNK(info
.st_mode
);
5745 int is_dir(const char* path
, bool follow
) {
5750 r
= stat(path
, &st
);
5752 r
= lstat(path
, &st
);
5756 return !!S_ISDIR(st
.st_mode
);
5759 int is_device_node(const char *path
) {
5762 if (lstat(path
, &info
) < 0)
5765 return !!(S_ISBLK(info
.st_mode
) || S_ISCHR(info
.st_mode
));
5768 int extract_first_word(const char **p
, char **ret
, const char *separators
, ExtractFlags flags
) {
5769 _cleanup_free_
char *s
= NULL
;
5770 size_t allocated
= 0, sz
= 0;
5778 SINGLE_QUOTE_ESCAPE
,
5780 DOUBLE_QUOTE_ESCAPE
,
5788 separators
= WHITESPACE
;
5790 /* Bail early if called after last value or with no input */
5792 goto finish_force_terminate
;
5794 /* Parses the first word of a string, and returns it in
5795 * *ret. Removes all quotes in the process. When parsing fails
5796 * (because of an uneven number of quotes or similar), leaves
5797 * the pointer *p at the first invalid character. */
5805 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
)
5806 if (!GREEDY_REALLOC(s
, allocated
, sz
+1))
5810 goto finish_force_terminate
;
5811 else if (strchr(separators
, c
)) {
5812 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
) {
5814 goto finish_force_next
;
5819 /* We found a non-blank character, so we will always
5820 * want to return a string (even if it is empty),
5821 * allocate it here. */
5822 if (!GREEDY_REALLOC(s
, allocated
, sz
+1))
5830 goto finish_force_terminate
;
5831 else if (c
== '\'' && (flags
& EXTRACT_QUOTES
))
5832 state
= SINGLE_QUOTE
;
5834 state
= VALUE_ESCAPE
;
5835 else if (c
== '\"' && (flags
& EXTRACT_QUOTES
))
5836 state
= DOUBLE_QUOTE
;
5837 else if (strchr(separators
, c
)) {
5838 if (flags
& EXTRACT_DONT_COALESCE_SEPARATORS
) {
5840 goto finish_force_next
;
5844 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5854 if (flags
& EXTRACT_RELAX
)
5855 goto finish_force_terminate
;
5857 } else if (c
== '\'')
5860 state
= SINGLE_QUOTE_ESCAPE
;
5862 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5876 state
= DOUBLE_QUOTE_ESCAPE
;
5878 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
5886 case SINGLE_QUOTE_ESCAPE
:
5887 case DOUBLE_QUOTE_ESCAPE
:
5889 if (!GREEDY_REALLOC(s
, allocated
, sz
+7))
5893 if ((flags
& EXTRACT_CUNESCAPE_RELAX
) &&
5894 (state
== VALUE_ESCAPE
|| flags
& EXTRACT_RELAX
)) {
5895 /* If we find an unquoted trailing backslash and we're in
5896 * EXTRACT_CUNESCAPE_RELAX mode, keep it verbatim in the
5899 * Unbalanced quotes will only be allowed in EXTRACT_RELAX
5900 * mode, EXTRACT_CUNESCAPE_RELAX mode does not allow them.
5903 goto finish_force_terminate
;
5905 if (flags
& EXTRACT_RELAX
)
5906 goto finish_force_terminate
;
5910 if (flags
& EXTRACT_CUNESCAPE
) {
5913 r
= cunescape_one(*p
, (size_t) -1, &c
, &u
);
5915 if (flags
& EXTRACT_CUNESCAPE_RELAX
) {
5926 s
[sz
++] = c
; /* normal explicit char */
5928 sz
+= utf8_encode_unichar(s
+ sz
, u
); /* unicode chars we'll encode as utf8 */
5933 state
= (state
== SINGLE_QUOTE_ESCAPE
) ? SINGLE_QUOTE
:
5934 (state
== DOUBLE_QUOTE_ESCAPE
) ? DOUBLE_QUOTE
:
5940 goto finish_force_terminate
;
5941 if (!strchr(separators
, c
))
5949 finish_force_terminate
:
5966 int extract_first_word_and_warn(
5969 const char *separators
,
5972 const char *filename
,
5974 const char *rvalue
) {
5975 /* Try to unquote it, if it fails, warn about it and try again but this
5976 * time using EXTRACT_CUNESCAPE_RELAX to keep the backslashes verbatim
5977 * in invalid escape sequences. */
5982 r
= extract_first_word(p
, ret
, separators
, flags
);
5983 if (r
< 0 && !(flags
&EXTRACT_CUNESCAPE_RELAX
)) {
5984 /* Retry it with EXTRACT_CUNESCAPE_RELAX. */
5986 r
= extract_first_word(p
, ret
, separators
, flags
|EXTRACT_CUNESCAPE_RELAX
);
5988 log_syntax(unit
, LOG_ERR
, filename
, line
, EINVAL
,
5989 "Unbalanced quoting in command line, ignoring: \"%s\"", rvalue
);
5991 log_syntax(unit
, LOG_WARNING
, filename
, line
, EINVAL
,
5992 "Invalid escape sequences in command line: \"%s\"", rvalue
);
5997 int extract_many_words(const char **p
, const char *separators
, ExtractFlags flags
, ...) {
6002 /* Parses a number of words from a string, stripping any
6003 * quotes if necessary. */
6007 /* Count how many words are expected */
6008 va_start(ap
, flags
);
6010 if (!va_arg(ap
, char **))
6019 /* Read all words into a temporary array */
6020 l
= newa0(char*, n
);
6021 for (c
= 0; c
< n
; c
++) {
6023 r
= extract_first_word(p
, &l
[c
], separators
, flags
);
6027 for (j
= 0; j
< c
; j
++)
6037 /* If we managed to parse all words, return them in the passed
6039 va_start(ap
, flags
);
6040 for (i
= 0; i
< n
; i
++) {
6043 v
= va_arg(ap
, char **);
6053 int free_and_strdup(char **p
, const char *s
) {
6058 /* Replaces a string pointer with an strdup()ed new string,
6059 * possibly freeing the old one. */
6061 if (streq_ptr(*p
, s
))
6077 int ptsname_malloc(int fd
, char **ret
) {
6090 if (ptsname_r(fd
, c
, l
) == 0) {
6094 if (errno
!= ERANGE
) {
6104 int openpt_in_namespace(pid_t pid
, int flags
) {
6105 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, usernsfd
= -1, rootfd
= -1;
6106 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
6108 struct cmsghdr cmsghdr
;
6109 uint8_t buf
[CMSG_SPACE(sizeof(int))];
6111 struct msghdr mh
= {
6112 .msg_control
= &control
,
6113 .msg_controllen
= sizeof(control
),
6115 struct cmsghdr
*cmsg
;
6122 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &usernsfd
, &rootfd
);
6126 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
6136 pair
[0] = safe_close(pair
[0]);
6138 r
= namespace_enter(pidnsfd
, mntnsfd
, -1, usernsfd
, rootfd
);
6140 _exit(EXIT_FAILURE
);
6142 master
= posix_openpt(flags
);
6144 _exit(EXIT_FAILURE
);
6146 if (unlockpt(master
) < 0)
6147 _exit(EXIT_FAILURE
);
6149 cmsg
= CMSG_FIRSTHDR(&mh
);
6150 cmsg
->cmsg_level
= SOL_SOCKET
;
6151 cmsg
->cmsg_type
= SCM_RIGHTS
;
6152 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
6153 memcpy(CMSG_DATA(cmsg
), &master
, sizeof(int));
6155 mh
.msg_controllen
= cmsg
->cmsg_len
;
6157 if (sendmsg(pair
[1], &mh
, MSG_NOSIGNAL
) < 0)
6158 _exit(EXIT_FAILURE
);
6160 _exit(EXIT_SUCCESS
);
6163 pair
[1] = safe_close(pair
[1]);
6165 r
= wait_for_terminate(child
, &si
);
6168 if (si
.si_code
!= CLD_EXITED
|| si
.si_status
!= EXIT_SUCCESS
)
6171 if (recvmsg(pair
[0], &mh
, MSG_NOSIGNAL
|MSG_CMSG_CLOEXEC
) < 0)
6174 CMSG_FOREACH(cmsg
, &mh
)
6175 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
) {
6179 fds
= (int*) CMSG_DATA(cmsg
);
6180 n_fds
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
6183 close_many(fds
, n_fds
);
6193 ssize_t
fgetxattrat_fake(int dirfd
, const char *filename
, const char *attribute
, void *value
, size_t size
, int flags
) {
6194 _cleanup_close_
int fd
= -1;
6197 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
6199 fd
= openat(dirfd
, filename
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOATIME
|(flags
& AT_SYMLINK_NOFOLLOW
? O_NOFOLLOW
: 0));
6203 l
= fgetxattr(fd
, attribute
, value
, size
);
6210 static int parse_crtime(le64_t le
, usec_t
*usec
) {
6216 if (u
== 0 || u
== (uint64_t) -1)
6223 int fd_getcrtime(int fd
, usec_t
*usec
) {
6230 /* Until Linux gets a real concept of birthtime/creation time,
6231 * let's fake one with xattrs */
6233 n
= fgetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
));
6236 if (n
!= sizeof(le
))
6239 return parse_crtime(le
, usec
);
6242 int fd_getcrtime_at(int dirfd
, const char *name
, usec_t
*usec
, int flags
) {
6246 n
= fgetxattrat_fake(dirfd
, name
, "user.crtime_usec", &le
, sizeof(le
), flags
);
6249 if (n
!= sizeof(le
))
6252 return parse_crtime(le
, usec
);
6255 int path_getcrtime(const char *p
, usec_t
*usec
) {
6262 n
= getxattr(p
, "user.crtime_usec", &le
, sizeof(le
));
6265 if (n
!= sizeof(le
))
6268 return parse_crtime(le
, usec
);
6271 int fd_setcrtime(int fd
, usec_t usec
) {
6277 usec
= now(CLOCK_REALTIME
);
6279 le
= htole64((uint64_t) usec
);
6280 if (fsetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
), 0) < 0)
6286 int same_fd(int a
, int b
) {
6287 struct stat sta
, stb
;
6294 /* Compares two file descriptors. Note that semantics are
6295 * quite different depending on whether we have kcmp() or we
6296 * don't. If we have kcmp() this will only return true for
6297 * dup()ed file descriptors, but not otherwise. If we don't
6298 * have kcmp() this will also return true for two fds of the same
6299 * file, created by separate open() calls. Since we use this
6300 * call mostly for filtering out duplicates in the fd store
6301 * this difference hopefully doesn't matter too much. */
6306 /* Try to use kcmp() if we have it. */
6308 r
= kcmp(pid
, pid
, KCMP_FILE
, a
, b
);
6313 if (errno
!= ENOSYS
)
6316 /* We don't have kcmp(), use fstat() instead. */
6317 if (fstat(a
, &sta
) < 0)
6320 if (fstat(b
, &stb
) < 0)
6323 if ((sta
.st_mode
& S_IFMT
) != (stb
.st_mode
& S_IFMT
))
6326 /* We consider all device fds different, since two device fds
6327 * might refer to quite different device contexts even though
6328 * they share the same inode and backing dev_t. */
6330 if (S_ISCHR(sta
.st_mode
) || S_ISBLK(sta
.st_mode
))
6333 if (sta
.st_dev
!= stb
.st_dev
|| sta
.st_ino
!= stb
.st_ino
)
6336 /* The fds refer to the same inode on disk, let's also check
6337 * if they have the same fd flags. This is useful to
6338 * distinguish the read and write side of a pipe created with
6340 fa
= fcntl(a
, F_GETFL
);
6344 fb
= fcntl(b
, F_GETFL
);
6351 int chattr_fd(int fd
, unsigned value
, unsigned mask
) {
6352 unsigned old_attr
, new_attr
;
6357 if (fstat(fd
, &st
) < 0)
6360 /* Explicitly check whether this is a regular file or
6361 * directory. If it is anything else (such as a device node or
6362 * fifo), then the ioctl will not hit the file systems but
6363 * possibly drivers, where the ioctl might have different
6364 * effects. Notably, DRM is using the same ioctl() number. */
6366 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
6372 if (ioctl(fd
, FS_IOC_GETFLAGS
, &old_attr
) < 0)
6375 new_attr
= (old_attr
& ~mask
) | (value
& mask
);
6376 if (new_attr
== old_attr
)
6379 if (ioctl(fd
, FS_IOC_SETFLAGS
, &new_attr
) < 0)
6385 int chattr_path(const char *p
, unsigned value
, unsigned mask
) {
6386 _cleanup_close_
int fd
= -1;
6393 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
6397 return chattr_fd(fd
, value
, mask
);
6400 int read_attr_fd(int fd
, unsigned *ret
) {
6405 if (fstat(fd
, &st
) < 0)
6408 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
6411 if (ioctl(fd
, FS_IOC_GETFLAGS
, ret
) < 0)
6417 int read_attr_path(const char *p
, unsigned *ret
) {
6418 _cleanup_close_
int fd
= -1;
6423 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
6427 return read_attr_fd(fd
, ret
);
6430 static size_t nul_length(const uint8_t *p
, size_t sz
) {
6445 ssize_t
sparse_write(int fd
, const void *p
, size_t sz
, size_t run_length
) {
6446 const uint8_t *q
, *w
, *e
;
6454 n
= nul_length(q
, e
- q
);
6456 /* If there are more than the specified run length of
6457 * NUL bytes, or if this is the beginning or the end
6458 * of the buffer, then seek instead of write */
6459 if ((n
> run_length
) ||
6460 (n
> 0 && q
== p
) ||
6461 (n
> 0 && q
+ n
>= e
)) {
6463 l
= write(fd
, w
, q
- w
);
6470 if (lseek(fd
, n
, SEEK_CUR
) == (off_t
) -1)
6482 l
= write(fd
, w
, q
- w
);
6489 return q
- (const uint8_t*) p
;
6492 void sigkill_wait(pid_t
*pid
) {
6498 if (kill(*pid
, SIGKILL
) > 0)
6499 (void) wait_for_terminate(*pid
, NULL
);
6502 int syslog_parse_priority(const char **p
, int *priority
, bool with_facility
) {
6503 int a
= 0, b
= 0, c
= 0;
6513 if (!strchr(*p
, '>'))
6516 if ((*p
)[2] == '>') {
6517 c
= undecchar((*p
)[1]);
6519 } else if ((*p
)[3] == '>') {
6520 b
= undecchar((*p
)[1]);
6521 c
= undecchar((*p
)[2]);
6523 } else if ((*p
)[4] == '>') {
6524 a
= undecchar((*p
)[1]);
6525 b
= undecchar((*p
)[2]);
6526 c
= undecchar((*p
)[3]);
6531 if (a
< 0 || b
< 0 || c
< 0 ||
6532 (!with_facility
&& (a
|| b
|| c
> 7)))
6536 *priority
= a
*100 + b
*10 + c
;
6538 *priority
= (*priority
& LOG_FACMASK
) | c
;
6544 ssize_t
string_table_lookup(const char * const *table
, size_t len
, const char *key
) {
6550 for (i
= 0; i
< len
; ++i
)
6551 if (streq_ptr(table
[i
], key
))
6557 void cmsg_close_all(struct msghdr
*mh
) {
6558 struct cmsghdr
*cmsg
;
6562 CMSG_FOREACH(cmsg
, mh
)
6563 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
)
6564 close_many((int*) CMSG_DATA(cmsg
), (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int));
6567 int rename_noreplace(int olddirfd
, const char *oldpath
, int newdirfd
, const char *newpath
) {
6571 ret
= renameat2(olddirfd
, oldpath
, newdirfd
, newpath
, RENAME_NOREPLACE
);
6575 /* renameat2() exists since Linux 3.15, btrfs added support for it later.
6576 * If it is not implemented, fallback to another method. */
6577 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
6580 /* The link()/unlink() fallback does not work on directories. But
6581 * renameat() without RENAME_NOREPLACE gives the same semantics on
6582 * directories, except when newpath is an *empty* directory. This is
6584 ret
= fstatat(olddirfd
, oldpath
, &buf
, AT_SYMLINK_NOFOLLOW
);
6585 if (ret
>= 0 && S_ISDIR(buf
.st_mode
)) {
6586 ret
= renameat(olddirfd
, oldpath
, newdirfd
, newpath
);
6587 return ret
>= 0 ? 0 : -errno
;
6590 /* If it is not a directory, use the link()/unlink() fallback. */
6591 ret
= linkat(olddirfd
, oldpath
, newdirfd
, newpath
, 0);
6595 ret
= unlinkat(olddirfd
, oldpath
, 0);
6597 /* backup errno before the following unlinkat() alters it */
6599 (void) unlinkat(newdirfd
, newpath
, 0);
6607 static char *strcpy_backslash_escaped(char *t
, const char *s
, const char *bad
) {
6611 if (*s
== '\\' || strchr(bad
, *s
))
6620 char *shell_escape(const char *s
, const char *bad
) {
6623 r
= new(char, strlen(s
)*2+1);
6627 t
= strcpy_backslash_escaped(r
, s
, bad
);
6633 char *shell_maybe_quote(const char *s
) {
6639 /* Encloses a string in double quotes if necessary to make it
6640 * OK as shell string. */
6642 for (p
= s
; *p
; p
++)
6645 strchr(SHELL_NEED_QUOTES
, *p
))
6651 r
= new(char, 1+strlen(s
)*2+1+1);
6657 t
= mempcpy(t
, s
, p
- s
);
6659 t
= strcpy_backslash_escaped(t
, p
, SHELL_NEED_ESCAPE
);
6667 int parse_mode(const char *s
, mode_t
*ret
) {
6675 l
= strtol(s
, &x
, 8);
6679 if (!x
|| x
== s
|| *x
)
6681 if (l
< 0 || l
> 07777)
6688 int mount_move_root(const char *path
) {
6691 if (chdir(path
) < 0)
6694 if (mount(path
, "/", NULL
, MS_MOVE
, NULL
) < 0)
6697 if (chroot(".") < 0)
6706 int reset_uid_gid(void) {
6708 if (setgroups(0, NULL
) < 0)
6711 if (setresgid(0, 0, 0) < 0)
6714 if (setresuid(0, 0, 0) < 0)
6720 int getxattr_malloc(const char *path
, const char *name
, char **value
, bool allow_symlink
) {
6729 for (l
= 100; ; l
= (size_t) n
+ 1) {
6735 n
= lgetxattr(path
, name
, v
, l
);
6737 n
= getxattr(path
, name
, v
, l
);
6739 if (n
>= 0 && (size_t) n
< l
) {
6746 if (n
< 0 && errno
!= ERANGE
)
6750 n
= lgetxattr(path
, name
, NULL
, 0);
6752 n
= getxattr(path
, name
, NULL
, 0);
6758 int fgetxattr_malloc(int fd
, const char *name
, char **value
) {
6767 for (l
= 100; ; l
= (size_t) n
+ 1) {
6772 n
= fgetxattr(fd
, name
, v
, l
);
6774 if (n
>= 0 && (size_t) n
< l
) {
6781 if (n
< 0 && errno
!= ERANGE
)
6784 n
= fgetxattr(fd
, name
, NULL
, 0);