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/>.
32 #include <sys/resource.h>
33 #include <linux/sched.h>
34 #include <sys/types.h>
38 #include <sys/ioctl.h>
40 #include <linux/tiocl.h>
45 #include <sys/prctl.h>
46 #include <sys/utsname.h>
48 #include <netinet/ip.h>
56 #include <sys/mount.h>
57 #include <linux/magic.h>
61 #include <sys/personality.h>
62 #include <sys/xattr.h>
63 #include <sys/statvfs.h>
67 /* When we include libgen.h because we need dirname() we immediately
68 * undefine basename() since libgen.h defines it as a macro to the XDG
69 * version which is really broken. */
73 #ifdef HAVE_SYS_AUXV_H
85 #include "path-util.h"
86 #include "exit-status.h"
90 #include "device-nodes.h"
95 #include "sparse-endian.h"
97 /* Put this test here for a lack of better place */
98 assert_cc(EAGAIN
== EWOULDBLOCK
);
101 char **saved_argv
= NULL
;
103 static volatile unsigned cached_columns
= 0;
104 static volatile unsigned cached_lines
= 0;
106 size_t page_size(void) {
107 static thread_local
size_t pgsz
= 0;
110 if (_likely_(pgsz
> 0))
113 r
= sysconf(_SC_PAGESIZE
);
120 bool streq_ptr(const char *a
, const char *b
) {
122 /* Like streq(), but tries to make sense of NULL pointers */
133 char* endswith(const char *s
, const char *postfix
) {
140 pl
= strlen(postfix
);
143 return (char*) s
+ sl
;
148 if (memcmp(s
+ sl
- pl
, postfix
, pl
) != 0)
151 return (char*) s
+ sl
- pl
;
154 char* first_word(const char *s
, const char *word
) {
161 /* Checks if the string starts with the specified word, either
162 * followed by NUL or by whitespace. Returns a pointer to the
163 * NUL or the first character after the whitespace. */
174 if (memcmp(s
, word
, wl
) != 0)
181 if (!strchr(WHITESPACE
, *p
))
184 p
+= strspn(p
, WHITESPACE
);
188 static size_t cescape_char(char c
, char *buf
) {
189 char * buf_old
= buf
;
235 /* For special chars we prefer octal over
236 * hexadecimal encoding, simply because glib's
237 * g_strescape() does the same */
238 if ((c
< ' ') || (c
>= 127)) {
240 *(buf
++) = octchar((unsigned char) c
>> 6);
241 *(buf
++) = octchar((unsigned char) c
>> 3);
242 *(buf
++) = octchar((unsigned char) c
);
248 return buf
- buf_old
;
251 int close_nointr(int fd
) {
258 * Just ignore EINTR; a retry loop is the wrong thing to do on
261 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
262 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
263 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
264 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
272 int safe_close(int fd
) {
275 * Like close_nointr() but cannot fail. Guarantees errno is
276 * unchanged. Is a NOP with negative fds passed, and returns
277 * -1, so that it can be used in this syntax:
279 * fd = safe_close(fd);
285 /* The kernel might return pretty much any error code
286 * via close(), but the fd will be closed anyway. The
287 * only condition we want to check for here is whether
288 * the fd was invalid at all... */
290 assert_se(close_nointr(fd
) != -EBADF
);
296 void close_many(const int fds
[], unsigned n_fd
) {
299 assert(fds
|| n_fd
<= 0);
301 for (i
= 0; i
< n_fd
; i
++)
305 int unlink_noerrno(const char *path
) {
316 int parse_boolean(const char *v
) {
319 if (streq(v
, "1") || strcaseeq(v
, "yes") || strcaseeq(v
, "y") || strcaseeq(v
, "true") || strcaseeq(v
, "t") || strcaseeq(v
, "on"))
321 else if (streq(v
, "0") || strcaseeq(v
, "no") || strcaseeq(v
, "n") || strcaseeq(v
, "false") || strcaseeq(v
, "f") || strcaseeq(v
, "off"))
327 int parse_pid(const char *s
, pid_t
* ret_pid
) {
328 unsigned long ul
= 0;
335 r
= safe_atolu(s
, &ul
);
341 if ((unsigned long) pid
!= ul
)
351 int parse_uid(const char *s
, uid_t
* ret_uid
) {
352 unsigned long ul
= 0;
359 r
= safe_atolu(s
, &ul
);
365 if ((unsigned long) uid
!= ul
)
368 /* Some libc APIs use UID_INVALID as special placeholder */
369 if (uid
== (uid_t
) 0xFFFFFFFF)
372 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
373 if (uid
== (uid_t
) 0xFFFF)
380 int safe_atou(const char *s
, unsigned *ret_u
) {
388 l
= strtoul(s
, &x
, 0);
390 if (!x
|| x
== s
|| *x
|| errno
)
391 return errno
> 0 ? -errno
: -EINVAL
;
393 if ((unsigned long) (unsigned) l
!= l
)
396 *ret_u
= (unsigned) l
;
400 int safe_atoi(const char *s
, int *ret_i
) {
408 l
= strtol(s
, &x
, 0);
410 if (!x
|| x
== s
|| *x
|| errno
)
411 return errno
> 0 ? -errno
: -EINVAL
;
413 if ((long) (int) l
!= l
)
420 int safe_atou8(const char *s
, uint8_t *ret
) {
428 l
= strtoul(s
, &x
, 0);
430 if (!x
|| x
== s
|| *x
|| errno
)
431 return errno
> 0 ? -errno
: -EINVAL
;
433 if ((unsigned long) (uint8_t) l
!= l
)
440 int safe_atou16(const char *s
, uint16_t *ret
) {
448 l
= strtoul(s
, &x
, 0);
450 if (!x
|| x
== s
|| *x
|| errno
)
451 return errno
> 0 ? -errno
: -EINVAL
;
453 if ((unsigned long) (uint16_t) l
!= l
)
460 int safe_atoi16(const char *s
, int16_t *ret
) {
468 l
= strtol(s
, &x
, 0);
470 if (!x
|| x
== s
|| *x
|| errno
)
471 return errno
> 0 ? -errno
: -EINVAL
;
473 if ((long) (int16_t) l
!= l
)
480 int safe_atollu(const char *s
, long long unsigned *ret_llu
) {
482 unsigned long long l
;
488 l
= strtoull(s
, &x
, 0);
490 if (!x
|| x
== s
|| *x
|| errno
)
491 return errno
? -errno
: -EINVAL
;
497 int safe_atolli(const char *s
, long long int *ret_lli
) {
505 l
= strtoll(s
, &x
, 0);
507 if (!x
|| x
== s
|| *x
|| errno
)
508 return errno
? -errno
: -EINVAL
;
514 int safe_atod(const char *s
, double *ret_d
) {
522 loc
= newlocale(LC_NUMERIC_MASK
, "C", (locale_t
) 0);
523 if (loc
== (locale_t
) 0)
527 d
= strtod_l(s
, &x
, loc
);
529 if (!x
|| x
== s
|| *x
|| errno
) {
531 return errno
? -errno
: -EINVAL
;
539 static size_t strcspn_escaped(const char *s
, const char *reject
) {
540 bool escaped
= false;
543 for (n
=0; s
[n
]; n
++) {
546 else if (s
[n
] == '\\')
548 else if (strchr(reject
, s
[n
]))
552 /* if s ends in \, return index of previous char */
556 /* Split a string into words. */
557 const char* split(const char **state
, size_t *l
, const char *separator
, bool quoted
) {
563 assert(**state
== '\0');
567 current
+= strspn(current
, separator
);
573 if (quoted
&& strchr("\'\"", *current
)) {
574 char quotechars
[2] = {*current
, '\0'};
576 *l
= strcspn_escaped(current
+ 1, quotechars
);
577 if (current
[*l
+ 1] == '\0' ||
578 (current
[*l
+ 2] && !strchr(separator
, current
[*l
+ 2]))) {
579 /* right quote missing or garbage at the end */
583 assert(current
[*l
+ 1] == quotechars
[0]);
584 *state
= current
++ + *l
+ 2;
586 *l
= strcspn_escaped(current
, separator
);
587 if (current
[*l
] && !strchr(separator
, current
[*l
])) {
588 /* unfinished escape */
592 *state
= current
+ *l
;
594 *l
= strcspn(current
, separator
);
595 *state
= current
+ *l
;
601 int get_parent_of_pid(pid_t pid
, pid_t
*_ppid
) {
603 _cleanup_free_
char *line
= NULL
;
615 p
= procfs_file_alloca(pid
, "stat");
616 r
= read_one_line_file(p
, &line
);
620 /* Let's skip the pid and comm fields. The latter is enclosed
621 * in () but does not escape any () in its value, so let's
622 * skip over it manually */
624 p
= strrchr(line
, ')');
636 if ((long unsigned) (pid_t
) ppid
!= ppid
)
639 *_ppid
= (pid_t
) ppid
;
644 int fchmod_umask(int fd
, mode_t m
) {
649 r
= fchmod(fd
, m
& (~u
)) < 0 ? -errno
: 0;
655 char *truncate_nl(char *s
) {
658 s
[strcspn(s
, NEWLINE
)] = 0;
662 int get_process_state(pid_t pid
) {
666 _cleanup_free_
char *line
= NULL
;
670 p
= procfs_file_alloca(pid
, "stat");
671 r
= read_one_line_file(p
, &line
);
675 p
= strrchr(line
, ')');
681 if (sscanf(p
, " %c", &state
) != 1)
684 return (unsigned char) state
;
687 int get_process_comm(pid_t pid
, char **name
) {
694 p
= procfs_file_alloca(pid
, "comm");
696 r
= read_one_line_file(p
, name
);
703 int get_process_cmdline(pid_t pid
, size_t max_length
, bool comm_fallback
, char **line
) {
704 _cleanup_fclose_
FILE *f
= NULL
;
712 p
= procfs_file_alloca(pid
, "cmdline");
718 if (max_length
== 0) {
719 size_t len
= 0, allocated
= 0;
721 while ((c
= getc(f
)) != EOF
) {
723 if (!GREEDY_REALLOC(r
, allocated
, len
+2)) {
728 r
[len
++] = isprint(c
) ? c
: ' ';
738 r
= new(char, max_length
);
744 while ((c
= getc(f
)) != EOF
) {
766 size_t n
= MIN(left
-1, 3U);
773 /* Kernel threads have no argv[] */
775 _cleanup_free_
char *t
= NULL
;
783 h
= get_process_comm(pid
, &t
);
787 r
= strjoin("[", t
, "]", NULL
);
796 int is_kernel_thread(pid_t pid
) {
808 p
= procfs_file_alloca(pid
, "cmdline");
813 count
= fread(&c
, 1, 1, f
);
817 /* Kernel threads have an empty cmdline */
820 return eof
? 1 : -errno
;
825 int get_process_capeff(pid_t pid
, char **capeff
) {
831 p
= procfs_file_alloca(pid
, "status");
833 return get_status_field(p
, "\nCapEff:", capeff
);
836 static int get_process_link_contents(const char *proc_file
, char **name
) {
842 r
= readlink_malloc(proc_file
, name
);
844 return r
== -ENOENT
? -ESRCH
: r
;
849 int get_process_exe(pid_t pid
, char **name
) {
856 p
= procfs_file_alloca(pid
, "exe");
857 r
= get_process_link_contents(p
, name
);
861 d
= endswith(*name
, " (deleted)");
868 static int get_process_id(pid_t pid
, const char *field
, uid_t
*uid
) {
869 _cleanup_fclose_
FILE *f
= NULL
;
879 p
= procfs_file_alloca(pid
, "status");
884 FOREACH_LINE(line
, f
, return -errno
) {
889 if (startswith(l
, field
)) {
891 l
+= strspn(l
, WHITESPACE
);
893 l
[strcspn(l
, WHITESPACE
)] = 0;
895 return parse_uid(l
, uid
);
902 int get_process_uid(pid_t pid
, uid_t
*uid
) {
903 return get_process_id(pid
, "Uid:", uid
);
906 int get_process_gid(pid_t pid
, gid_t
*gid
) {
907 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
908 return get_process_id(pid
, "Gid:", gid
);
911 int get_process_cwd(pid_t pid
, char **cwd
) {
916 p
= procfs_file_alloca(pid
, "cwd");
918 return get_process_link_contents(p
, cwd
);
921 int get_process_root(pid_t pid
, char **root
) {
926 p
= procfs_file_alloca(pid
, "root");
928 return get_process_link_contents(p
, root
);
931 int get_process_environ(pid_t pid
, char **env
) {
932 _cleanup_fclose_
FILE *f
= NULL
;
933 _cleanup_free_
char *outcome
= NULL
;
936 size_t allocated
= 0, sz
= 0;
941 p
= procfs_file_alloca(pid
, "environ");
947 while ((c
= fgetc(f
)) != EOF
) {
948 if (!GREEDY_REALLOC(outcome
, allocated
, sz
+ 5))
952 outcome
[sz
++] = '\n';
954 sz
+= cescape_char(c
, outcome
+ sz
);
964 char *strnappend(const char *s
, const char *suffix
, size_t b
) {
972 return strndup(suffix
, b
);
981 if (b
> ((size_t) -1) - a
)
984 r
= new(char, a
+b
+1);
989 memcpy(r
+a
, suffix
, b
);
995 char *strappend(const char *s
, const char *suffix
) {
996 return strnappend(s
, suffix
, suffix
? strlen(suffix
) : 0);
999 int readlinkat_malloc(int fd
, const char *p
, char **ret
) {
1014 n
= readlinkat(fd
, p
, c
, l
-1);
1021 if ((size_t) n
< l
-1) {
1032 int readlink_malloc(const char *p
, char **ret
) {
1033 return readlinkat_malloc(AT_FDCWD
, p
, ret
);
1036 int readlink_value(const char *p
, char **ret
) {
1037 _cleanup_free_
char *link
= NULL
;
1041 r
= readlink_malloc(p
, &link
);
1045 value
= basename(link
);
1049 value
= strdup(value
);
1058 int readlink_and_make_absolute(const char *p
, char **r
) {
1059 _cleanup_free_
char *target
= NULL
;
1066 j
= readlink_malloc(p
, &target
);
1070 k
= file_in_same_dir(p
, target
);
1078 int readlink_and_canonicalize(const char *p
, char **r
) {
1085 j
= readlink_and_make_absolute(p
, &t
);
1089 s
= canonicalize_file_name(t
);
1096 path_kill_slashes(*r
);
1101 int reset_all_signal_handlers(void) {
1104 for (sig
= 1; sig
< _NSIG
; sig
++) {
1105 struct sigaction sa
= {
1106 .sa_handler
= SIG_DFL
,
1107 .sa_flags
= SA_RESTART
,
1110 /* These two cannot be caught... */
1111 if (sig
== SIGKILL
|| sig
== SIGSTOP
)
1114 /* On Linux the first two RT signals are reserved by
1115 * glibc, and sigaction() will return EINVAL for them. */
1116 if ((sigaction(sig
, &sa
, NULL
) < 0))
1117 if (errno
!= EINVAL
&& r
== 0)
1124 int reset_signal_mask(void) {
1127 if (sigemptyset(&ss
) < 0)
1130 if (sigprocmask(SIG_SETMASK
, &ss
, NULL
) < 0)
1136 char *strstrip(char *s
) {
1139 /* Drops trailing whitespace. Modifies the string in
1140 * place. Returns pointer to first non-space character */
1142 s
+= strspn(s
, WHITESPACE
);
1144 for (e
= strchr(s
, 0); e
> s
; e
--)
1145 if (!strchr(WHITESPACE
, e
[-1]))
1153 char *delete_chars(char *s
, const char *bad
) {
1156 /* Drops all whitespace, regardless where in the string */
1158 for (f
= s
, t
= s
; *f
; f
++) {
1159 if (strchr(bad
, *f
))
1170 char *file_in_same_dir(const char *path
, const char *filename
) {
1177 /* This removes the last component of path and appends
1178 * filename, unless the latter is absolute anyway or the
1181 if (path_is_absolute(filename
))
1182 return strdup(filename
);
1184 e
= strrchr(path
, '/');
1186 return strdup(filename
);
1188 k
= strlen(filename
);
1189 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
1193 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
1197 int rmdir_parents(const char *path
, const char *stop
) {
1206 /* Skip trailing slashes */
1207 while (l
> 0 && path
[l
-1] == '/')
1213 /* Skip last component */
1214 while (l
> 0 && path
[l
-1] != '/')
1217 /* Skip trailing slashes */
1218 while (l
> 0 && path
[l
-1] == '/')
1224 if (!(t
= strndup(path
, l
)))
1227 if (path_startswith(stop
, t
)) {
1236 if (errno
!= ENOENT
)
1243 char hexchar(int x
) {
1244 static const char table
[16] = "0123456789abcdef";
1246 return table
[x
& 15];
1249 int unhexchar(char c
) {
1251 if (c
>= '0' && c
<= '9')
1254 if (c
>= 'a' && c
<= 'f')
1255 return c
- 'a' + 10;
1257 if (c
>= 'A' && c
<= 'F')
1258 return c
- 'A' + 10;
1263 char *hexmem(const void *p
, size_t l
) {
1267 z
= r
= malloc(l
* 2 + 1);
1271 for (x
= p
; x
< (const uint8_t*) p
+ l
; x
++) {
1272 *(z
++) = hexchar(*x
>> 4);
1273 *(z
++) = hexchar(*x
& 15);
1280 void *unhexmem(const char *p
, size_t l
) {
1286 z
= r
= malloc((l
+ 1) / 2 + 1);
1290 for (x
= p
; x
< p
+ l
; x
+= 2) {
1293 a
= unhexchar(x
[0]);
1295 b
= unhexchar(x
[1]);
1299 *(z
++) = (uint8_t) a
<< 4 | (uint8_t) b
;
1306 char octchar(int x
) {
1307 return '0' + (x
& 7);
1310 int unoctchar(char c
) {
1312 if (c
>= '0' && c
<= '7')
1318 char decchar(int x
) {
1319 return '0' + (x
% 10);
1322 int undecchar(char c
) {
1324 if (c
>= '0' && c
<= '9')
1330 char *cescape(const char *s
) {
1336 /* Does C style string escaping. */
1338 r
= new(char, strlen(s
)*4 + 1);
1342 for (f
= s
, t
= r
; *f
; f
++)
1343 t
+= cescape_char(*f
, t
);
1350 static int cunescape_one(const char *p
, size_t length
, char *ret
) {
1357 if (length
!= (size_t) -1 && length
< 1)
1394 /* This is an extension of the XDG syntax files */
1399 /* hexadecimal encoding */
1402 if (length
!= (size_t) -1 && length
< 3)
1405 a
= unhexchar(p
[1]);
1409 b
= unhexchar(p
[2]);
1413 /* don't allow NUL bytes */
1414 if (a
== 0 && b
== 0)
1417 *ret
= (char) ((a
<< 4) | b
);
1430 /* octal encoding */
1433 if (length
!= (size_t) -1 && length
< 4)
1436 a
= unoctchar(p
[0]);
1440 b
= unoctchar(p
[1]);
1444 c
= unoctchar(p
[2]);
1448 /* don't allow NUL bytes */
1449 if (a
== 0 && b
== 0 && c
== 0)
1452 /* Don't allow bytes above 255 */
1453 m
= (a
<< 6) | (b
<< 3) | c
;
1469 char *cunescape_length_with_prefix(const char *s
, size_t length
, const char *prefix
) {
1476 /* Undoes C style string escaping, and optionally prefixes it. */
1478 pl
= prefix
? strlen(prefix
) : 0;
1480 r
= new(char, pl
+length
+1);
1485 memcpy(r
, prefix
, pl
);
1487 for (f
= s
, t
= r
+ pl
; f
< s
+ length
; f
++) {
1491 remaining
= s
+ length
- f
;
1492 assert(remaining
> 0);
1494 if (*f
!= '\\' || remaining
== 1) {
1495 /* a literal literal, or a trailing backslash, copy verbatim */
1500 k
= cunescape_one(f
+ 1, remaining
- 1, t
);
1502 /* Invalid escape code, let's take it literal then */
1515 char *cunescape_length(const char *s
, size_t length
) {
1516 return cunescape_length_with_prefix(s
, length
, NULL
);
1519 char *cunescape(const char *s
) {
1522 return cunescape_length(s
, strlen(s
));
1525 char *xescape(const char *s
, const char *bad
) {
1529 /* Escapes all chars in bad, in addition to \ and all special
1530 * chars, in \xFF style escaping. May be reversed with
1533 r
= new(char, strlen(s
) * 4 + 1);
1537 for (f
= s
, t
= r
; *f
; f
++) {
1539 if ((*f
< ' ') || (*f
>= 127) ||
1540 (*f
== '\\') || strchr(bad
, *f
)) {
1543 *(t
++) = hexchar(*f
>> 4);
1544 *(t
++) = hexchar(*f
);
1554 char *ascii_strlower(char *t
) {
1559 for (p
= t
; *p
; p
++)
1560 if (*p
>= 'A' && *p
<= 'Z')
1561 *p
= *p
- 'A' + 'a';
1566 _pure_
static bool hidden_file_allow_backup(const char *filename
) {
1570 filename
[0] == '.' ||
1571 streq(filename
, "lost+found") ||
1572 streq(filename
, "aquota.user") ||
1573 streq(filename
, "aquota.group") ||
1574 endswith(filename
, ".rpmnew") ||
1575 endswith(filename
, ".rpmsave") ||
1576 endswith(filename
, ".rpmorig") ||
1577 endswith(filename
, ".dpkg-old") ||
1578 endswith(filename
, ".dpkg-new") ||
1579 endswith(filename
, ".dpkg-tmp") ||
1580 endswith(filename
, ".dpkg-dist") ||
1581 endswith(filename
, ".dpkg-bak") ||
1582 endswith(filename
, ".dpkg-backup") ||
1583 endswith(filename
, ".dpkg-remove") ||
1584 endswith(filename
, ".swp");
1587 bool hidden_file(const char *filename
) {
1590 if (endswith(filename
, "~"))
1593 return hidden_file_allow_backup(filename
);
1596 int fd_nonblock(int fd
, bool nonblock
) {
1601 flags
= fcntl(fd
, F_GETFL
, 0);
1606 nflags
= flags
| O_NONBLOCK
;
1608 nflags
= flags
& ~O_NONBLOCK
;
1610 if (nflags
== flags
)
1613 if (fcntl(fd
, F_SETFL
, nflags
) < 0)
1619 int fd_cloexec(int fd
, bool cloexec
) {
1624 flags
= fcntl(fd
, F_GETFD
, 0);
1629 nflags
= flags
| FD_CLOEXEC
;
1631 nflags
= flags
& ~FD_CLOEXEC
;
1633 if (nflags
== flags
)
1636 if (fcntl(fd
, F_SETFD
, nflags
) < 0)
1642 _pure_
static bool fd_in_set(int fd
, const int fdset
[], unsigned n_fdset
) {
1645 assert(n_fdset
== 0 || fdset
);
1647 for (i
= 0; i
< n_fdset
; i
++)
1654 int close_all_fds(const int except
[], unsigned n_except
) {
1655 _cleanup_closedir_
DIR *d
= NULL
;
1659 assert(n_except
== 0 || except
);
1661 d
= opendir("/proc/self/fd");
1666 /* When /proc isn't available (for example in chroots)
1667 * the fallback is brute forcing through the fd
1670 assert_se(getrlimit(RLIMIT_NOFILE
, &rl
) >= 0);
1671 for (fd
= 3; fd
< (int) rl
.rlim_max
; fd
++) {
1673 if (fd_in_set(fd
, except
, n_except
))
1676 if (close_nointr(fd
) < 0)
1677 if (errno
!= EBADF
&& r
== 0)
1684 while ((de
= readdir(d
))) {
1687 if (hidden_file(de
->d_name
))
1690 if (safe_atoi(de
->d_name
, &fd
) < 0)
1691 /* Let's better ignore this, just in case */
1700 if (fd_in_set(fd
, except
, n_except
))
1703 if (close_nointr(fd
) < 0) {
1704 /* Valgrind has its own FD and doesn't want to have it closed */
1705 if (errno
!= EBADF
&& r
== 0)
1713 bool chars_intersect(const char *a
, const char *b
) {
1716 /* Returns true if any of the chars in a are in b. */
1717 for (p
= a
; *p
; p
++)
1724 bool fstype_is_network(const char *fstype
) {
1725 static const char table
[] =
1740 x
= startswith(fstype
, "fuse.");
1744 return nulstr_contains(table
, fstype
);
1748 _cleanup_close_
int fd
;
1750 fd
= open_terminal("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
1756 TIOCL_GETKMSGREDIRECT
,
1760 if (ioctl(fd
, TIOCLINUX
, tiocl
) < 0)
1763 vt
= tiocl
[0] <= 0 ? 1 : tiocl
[0];
1766 if (ioctl(fd
, VT_ACTIVATE
, vt
) < 0)
1772 int read_one_char(FILE *f
, char *ret
, usec_t t
, bool *need_nl
) {
1773 struct termios old_termios
, new_termios
;
1774 char c
, line
[LINE_MAX
];
1779 if (tcgetattr(fileno(f
), &old_termios
) >= 0) {
1780 new_termios
= old_termios
;
1782 new_termios
.c_lflag
&= ~ICANON
;
1783 new_termios
.c_cc
[VMIN
] = 1;
1784 new_termios
.c_cc
[VTIME
] = 0;
1786 if (tcsetattr(fileno(f
), TCSADRAIN
, &new_termios
) >= 0) {
1789 if (t
!= USEC_INFINITY
) {
1790 if (fd_wait_for_event(fileno(f
), POLLIN
, t
) <= 0) {
1791 tcsetattr(fileno(f
), TCSADRAIN
, &old_termios
);
1796 k
= fread(&c
, 1, 1, f
);
1798 tcsetattr(fileno(f
), TCSADRAIN
, &old_termios
);
1804 *need_nl
= c
!= '\n';
1811 if (t
!= USEC_INFINITY
) {
1812 if (fd_wait_for_event(fileno(f
), POLLIN
, t
) <= 0)
1817 if (!fgets(line
, sizeof(line
), f
))
1818 return errno
? -errno
: -EIO
;
1822 if (strlen(line
) != 1)
1832 int ask_char(char *ret
, const char *replies
, const char *text
, ...) {
1842 bool need_nl
= true;
1845 fputs(ANSI_HIGHLIGHT_ON
, stdout
);
1852 fputs(ANSI_HIGHLIGHT_OFF
, stdout
);
1856 r
= read_one_char(stdin
, &c
, USEC_INFINITY
, &need_nl
);
1859 if (r
== -EBADMSG
) {
1860 puts("Bad input, please try again.");
1871 if (strchr(replies
, c
)) {
1876 puts("Read unexpected character, please try again.");
1880 int ask_string(char **ret
, const char *text
, ...) {
1885 char line
[LINE_MAX
];
1889 fputs(ANSI_HIGHLIGHT_ON
, stdout
);
1896 fputs(ANSI_HIGHLIGHT_OFF
, stdout
);
1901 if (!fgets(line
, sizeof(line
), stdin
))
1902 return errno
? -errno
: -EIO
;
1904 if (!endswith(line
, "\n"))
1923 int reset_terminal_fd(int fd
, bool switch_to_text
) {
1924 struct termios termios
;
1927 /* Set terminal to some sane defaults */
1931 /* We leave locked terminal attributes untouched, so that
1932 * Plymouth may set whatever it wants to set, and we don't
1933 * interfere with that. */
1935 /* Disable exclusive mode, just in case */
1936 ioctl(fd
, TIOCNXCL
);
1938 /* Switch to text mode */
1940 ioctl(fd
, KDSETMODE
, KD_TEXT
);
1942 /* Enable console unicode mode */
1943 ioctl(fd
, KDSKBMODE
, K_UNICODE
);
1945 if (tcgetattr(fd
, &termios
) < 0) {
1950 /* We only reset the stuff that matters to the software. How
1951 * hardware is set up we don't touch assuming that somebody
1952 * else will do that for us */
1954 termios
.c_iflag
&= ~(IGNBRK
| BRKINT
| ISTRIP
| INLCR
| IGNCR
| IUCLC
);
1955 termios
.c_iflag
|= ICRNL
| IMAXBEL
| IUTF8
;
1956 termios
.c_oflag
|= ONLCR
;
1957 termios
.c_cflag
|= CREAD
;
1958 termios
.c_lflag
= ISIG
| ICANON
| IEXTEN
| ECHO
| ECHOE
| ECHOK
| ECHOCTL
| ECHOPRT
| ECHOKE
;
1960 termios
.c_cc
[VINTR
] = 03; /* ^C */
1961 termios
.c_cc
[VQUIT
] = 034; /* ^\ */
1962 termios
.c_cc
[VERASE
] = 0177;
1963 termios
.c_cc
[VKILL
] = 025; /* ^X */
1964 termios
.c_cc
[VEOF
] = 04; /* ^D */
1965 termios
.c_cc
[VSTART
] = 021; /* ^Q */
1966 termios
.c_cc
[VSTOP
] = 023; /* ^S */
1967 termios
.c_cc
[VSUSP
] = 032; /* ^Z */
1968 termios
.c_cc
[VLNEXT
] = 026; /* ^V */
1969 termios
.c_cc
[VWERASE
] = 027; /* ^W */
1970 termios
.c_cc
[VREPRINT
] = 022; /* ^R */
1971 termios
.c_cc
[VEOL
] = 0;
1972 termios
.c_cc
[VEOL2
] = 0;
1974 termios
.c_cc
[VTIME
] = 0;
1975 termios
.c_cc
[VMIN
] = 1;
1977 if (tcsetattr(fd
, TCSANOW
, &termios
) < 0)
1981 /* Just in case, flush all crap out */
1982 tcflush(fd
, TCIOFLUSH
);
1987 int reset_terminal(const char *name
) {
1988 _cleanup_close_
int fd
= -1;
1990 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
1994 return reset_terminal_fd(fd
, true);
1997 int open_terminal(const char *name
, int mode
) {
2002 * If a TTY is in the process of being closed opening it might
2003 * cause EIO. This is horribly awful, but unlikely to be
2004 * changed in the kernel. Hence we work around this problem by
2005 * retrying a couple of times.
2007 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2010 assert(!(mode
& O_CREAT
));
2013 fd
= open(name
, mode
, 0);
2020 /* Max 1s in total */
2024 usleep(50 * USEC_PER_MSEC
);
2042 int flush_fd(int fd
) {
2043 struct pollfd pollfd
= {
2053 r
= poll(&pollfd
, 1, 0);
2063 l
= read(fd
, buf
, sizeof(buf
));
2069 if (errno
== EAGAIN
)
2078 int acquire_terminal(
2082 bool ignore_tiocstty_eperm
,
2085 int fd
= -1, notify
= -1, r
= 0, wd
= -1;
2090 /* We use inotify to be notified when the tty is closed. We
2091 * create the watch before checking if we can actually acquire
2092 * it, so that we don't lose any event.
2094 * Note: strictly speaking this actually watches for the
2095 * device being closed, it does *not* really watch whether a
2096 * tty loses its controlling process. However, unless some
2097 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2098 * its tty otherwise this will not become a problem. As long
2099 * as the administrator makes sure not configure any service
2100 * on the same tty as an untrusted user this should not be a
2101 * problem. (Which he probably should not do anyway.) */
2103 if (timeout
!= USEC_INFINITY
)
2104 ts
= now(CLOCK_MONOTONIC
);
2106 if (!fail
&& !force
) {
2107 notify
= inotify_init1(IN_CLOEXEC
| (timeout
!= USEC_INFINITY
? IN_NONBLOCK
: 0));
2113 wd
= inotify_add_watch(notify
, name
, IN_CLOSE
);
2121 struct sigaction sa_old
, sa_new
= {
2122 .sa_handler
= SIG_IGN
,
2123 .sa_flags
= SA_RESTART
,
2127 r
= flush_fd(notify
);
2132 /* We pass here O_NOCTTY only so that we can check the return
2133 * value TIOCSCTTY and have a reliable way to figure out if we
2134 * successfully became the controlling process of the tty */
2135 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
2139 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2140 * if we already own the tty. */
2141 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
2143 /* First, try to get the tty */
2144 if (ioctl(fd
, TIOCSCTTY
, force
) < 0)
2147 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
2149 /* Sometimes it makes sense to ignore TIOCSCTTY
2150 * returning EPERM, i.e. when very likely we already
2151 * are have this controlling terminal. */
2152 if (r
< 0 && r
== -EPERM
&& ignore_tiocstty_eperm
)
2155 if (r
< 0 && (force
|| fail
|| r
!= -EPERM
)) {
2164 assert(notify
>= 0);
2167 union inotify_event_buffer buffer
;
2168 struct inotify_event
*e
;
2171 if (timeout
!= USEC_INFINITY
) {
2174 n
= now(CLOCK_MONOTONIC
);
2175 if (ts
+ timeout
< n
) {
2180 r
= fd_wait_for_event(fd
, POLLIN
, ts
+ timeout
- n
);
2190 l
= read(notify
, &buffer
, sizeof(buffer
));
2192 if (errno
== EINTR
|| errno
== EAGAIN
)
2199 FOREACH_INOTIFY_EVENT(e
, buffer
, l
) {
2200 if (e
->wd
!= wd
|| !(e
->mask
& IN_CLOSE
)) {
2209 /* We close the tty fd here since if the old session
2210 * ended our handle will be dead. It's important that
2211 * we do this after sleeping, so that we don't enter
2212 * an endless loop. */
2213 fd
= safe_close(fd
);
2218 r
= reset_terminal_fd(fd
, true);
2220 log_warning_errno(r
, "Failed to reset terminal: %m");
2231 int release_terminal(void) {
2232 static const struct sigaction sa_new
= {
2233 .sa_handler
= SIG_IGN
,
2234 .sa_flags
= SA_RESTART
,
2237 _cleanup_close_
int fd
= -1;
2238 struct sigaction sa_old
;
2241 fd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_NDELAY
|O_CLOEXEC
);
2245 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2246 * by our own TIOCNOTTY */
2247 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
2249 if (ioctl(fd
, TIOCNOTTY
) < 0)
2252 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
2257 int sigaction_many(const struct sigaction
*sa
, ...) {
2262 while ((sig
= va_arg(ap
, int)) > 0)
2263 if (sigaction(sig
, sa
, NULL
) < 0)
2270 int ignore_signals(int sig
, ...) {
2271 struct sigaction sa
= {
2272 .sa_handler
= SIG_IGN
,
2273 .sa_flags
= SA_RESTART
,
2278 if (sigaction(sig
, &sa
, NULL
) < 0)
2282 while ((sig
= va_arg(ap
, int)) > 0)
2283 if (sigaction(sig
, &sa
, NULL
) < 0)
2290 int default_signals(int sig
, ...) {
2291 struct sigaction sa
= {
2292 .sa_handler
= SIG_DFL
,
2293 .sa_flags
= SA_RESTART
,
2298 if (sigaction(sig
, &sa
, NULL
) < 0)
2302 while ((sig
= va_arg(ap
, int)) > 0)
2303 if (sigaction(sig
, &sa
, NULL
) < 0)
2310 void safe_close_pair(int p
[]) {
2314 /* Special case pairs which use the same fd in both
2316 p
[0] = p
[1] = safe_close(p
[0]);
2320 p
[0] = safe_close(p
[0]);
2321 p
[1] = safe_close(p
[1]);
2324 ssize_t
loop_read(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2331 while (nbytes
> 0) {
2334 k
= read(fd
, p
, nbytes
);
2339 if (errno
== EAGAIN
&& do_poll
) {
2341 /* We knowingly ignore any return value here,
2342 * and expect that any error/EOF is reported
2345 fd_wait_for_event(fd
, POLLIN
, USEC_INFINITY
);
2349 return n
> 0 ? n
: -errno
;
2363 int loop_read_exact(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2366 n
= loop_read(fd
, buf
, nbytes
, do_poll
);
2369 if ((size_t) n
!= nbytes
)
2374 int loop_write(int fd
, const void *buf
, size_t nbytes
, bool do_poll
) {
2375 const uint8_t *p
= buf
;
2382 while (nbytes
> 0) {
2385 k
= write(fd
, p
, nbytes
);
2390 if (errno
== EAGAIN
&& do_poll
) {
2391 /* We knowingly ignore any return value here,
2392 * and expect that any error/EOF is reported
2395 fd_wait_for_event(fd
, POLLOUT
, USEC_INFINITY
);
2402 if (k
== 0) /* Can't really happen */
2412 int parse_size(const char *t
, off_t base
, off_t
*size
) {
2414 /* Soo, sometimes we want to parse IEC binary suffxies, and
2415 * sometimes SI decimal suffixes. This function can parse
2416 * both. Which one is the right way depends on the
2417 * context. Wikipedia suggests that SI is customary for
2418 * hardrware metrics and network speeds, while IEC is
2419 * customary for most data sizes used by software and volatile
2420 * (RAM) memory. Hence be careful which one you pick!
2422 * In either case we use just K, M, G as suffix, and not Ki,
2423 * Mi, Gi or so (as IEC would suggest). That's because that's
2424 * frickin' ugly. But this means you really need to make sure
2425 * to document which base you are parsing when you use this
2430 unsigned long long factor
;
2433 static const struct table iec
[] = {
2434 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2435 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2436 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2437 { "G", 1024ULL*1024ULL*1024ULL },
2438 { "M", 1024ULL*1024ULL },
2444 static const struct table si
[] = {
2445 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2446 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2447 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2448 { "G", 1000ULL*1000ULL*1000ULL },
2449 { "M", 1000ULL*1000ULL },
2455 const struct table
*table
;
2457 unsigned long long r
= 0;
2458 unsigned n_entries
, start_pos
= 0;
2461 assert(base
== 1000 || base
== 1024);
2466 n_entries
= ELEMENTSOF(si
);
2469 n_entries
= ELEMENTSOF(iec
);
2475 unsigned long long l2
;
2481 l
= strtoll(p
, &e
, 10);
2494 if (*e
>= '0' && *e
<= '9') {
2497 /* strotoull itself would accept space/+/- */
2498 l2
= strtoull(e
, &e2
, 10);
2500 if (errno
== ERANGE
)
2503 /* Ignore failure. E.g. 10.M is valid */
2510 e
+= strspn(e
, WHITESPACE
);
2512 for (i
= start_pos
; i
< n_entries
; i
++)
2513 if (startswith(e
, table
[i
].suffix
)) {
2514 unsigned long long tmp
;
2515 if ((unsigned long long) l
+ (frac
> 0) > ULLONG_MAX
/ table
[i
].factor
)
2517 tmp
= l
* table
[i
].factor
+ (unsigned long long) (frac
* table
[i
].factor
);
2518 if (tmp
> ULLONG_MAX
- r
)
2522 if ((unsigned long long) (off_t
) r
!= r
)
2525 p
= e
+ strlen(table
[i
].suffix
);
2541 int make_stdio(int fd
) {
2546 r
= dup2(fd
, STDIN_FILENO
);
2547 s
= dup2(fd
, STDOUT_FILENO
);
2548 t
= dup2(fd
, STDERR_FILENO
);
2553 if (r
< 0 || s
< 0 || t
< 0)
2556 /* Explicitly unset O_CLOEXEC, since if fd was < 3, then
2557 * dup2() was a NOP and the bit hence possibly set. */
2558 fd_cloexec(STDIN_FILENO
, false);
2559 fd_cloexec(STDOUT_FILENO
, false);
2560 fd_cloexec(STDERR_FILENO
, false);
2565 int make_null_stdio(void) {
2568 null_fd
= open("/dev/null", O_RDWR
|O_NOCTTY
);
2572 return make_stdio(null_fd
);
2575 bool is_device_path(const char *path
) {
2577 /* Returns true on paths that refer to a device, either in
2578 * sysfs or in /dev */
2581 path_startswith(path
, "/dev/") ||
2582 path_startswith(path
, "/sys/");
2585 int dir_is_empty(const char *path
) {
2586 _cleanup_closedir_
DIR *d
;
2597 if (!de
&& errno
!= 0)
2603 if (!hidden_file(de
->d_name
))
2608 char* dirname_malloc(const char *path
) {
2609 char *d
, *dir
, *dir2
;
2626 int dev_urandom(void *p
, size_t n
) {
2627 static int have_syscall
= -1;
2629 _cleanup_close_
int fd
= -1;
2632 /* Gathers some randomness from the kernel. This call will
2633 * never block, and will always return some data from the
2634 * kernel, regardless if the random pool is fully initialized
2635 * or not. It thus makes no guarantee for the quality of the
2636 * returned entropy, but is good enough for or usual usecases
2637 * of seeding the hash functions for hashtable */
2639 /* Use the getrandom() syscall unless we know we don't have
2640 * it, or when the requested size is too large for it. */
2641 if (have_syscall
!= 0 || (size_t) (int) n
!= n
) {
2642 r
= getrandom(p
, n
, GRND_NONBLOCK
);
2644 have_syscall
= true;
2649 if (errno
== ENOSYS
)
2650 /* we lack the syscall, continue with
2651 * reading from /dev/urandom */
2652 have_syscall
= false;
2653 else if (errno
== EAGAIN
)
2654 /* not enough entropy for now. Let's
2655 * remember to use the syscall the
2656 * next time, again, but also read
2657 * from /dev/urandom for now, which
2658 * doesn't care about the current
2659 * amount of entropy. */
2660 have_syscall
= true;
2664 /* too short read? */
2668 fd
= open("/dev/urandom", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
2670 return errno
== ENOENT
? -ENOSYS
: -errno
;
2672 return loop_read_exact(fd
, p
, n
, true);
2675 void initialize_srand(void) {
2676 static bool srand_called
= false;
2678 #ifdef HAVE_SYS_AUXV_H
2687 #ifdef HAVE_SYS_AUXV_H
2688 /* The kernel provides us with a bit of entropy in auxv, so
2689 * let's try to make use of that to seed the pseudo-random
2690 * generator. It's better than nothing... */
2692 auxv
= (void*) getauxval(AT_RANDOM
);
2694 x
^= *(unsigned*) auxv
;
2697 x
^= (unsigned) now(CLOCK_REALTIME
);
2698 x
^= (unsigned) gettid();
2701 srand_called
= true;
2704 void random_bytes(void *p
, size_t n
) {
2708 r
= dev_urandom(p
, n
);
2712 /* If some idiot made /dev/urandom unavailable to us, he'll
2713 * get a PRNG instead. */
2717 for (q
= p
; q
< (uint8_t*) p
+ n
; q
++)
2721 void rename_process(const char name
[8]) {
2724 /* This is a like a poor man's setproctitle(). It changes the
2725 * comm field, argv[0], and also the glibc's internally used
2726 * name of the process. For the first one a limit of 16 chars
2727 * applies, to the second one usually one of 10 (i.e. length
2728 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2729 * "systemd"). If you pass a longer string it will be
2732 prctl(PR_SET_NAME
, name
);
2734 if (program_invocation_name
)
2735 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
2737 if (saved_argc
> 0) {
2741 strncpy(saved_argv
[0], name
, strlen(saved_argv
[0]));
2743 for (i
= 1; i
< saved_argc
; i
++) {
2747 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
2752 void sigset_add_many(sigset_t
*ss
, ...) {
2759 while ((sig
= va_arg(ap
, int)) > 0)
2760 assert_se(sigaddset(ss
, sig
) == 0);
2764 int sigprocmask_many(int how
, ...) {
2769 assert_se(sigemptyset(&ss
) == 0);
2772 while ((sig
= va_arg(ap
, int)) > 0)
2773 assert_se(sigaddset(&ss
, sig
) == 0);
2776 if (sigprocmask(how
, &ss
, NULL
) < 0)
2782 char* gethostname_malloc(void) {
2785 assert_se(uname(&u
) >= 0);
2787 if (!isempty(u
.nodename
) && !streq(u
.nodename
, "(none)"))
2788 return strdup(u
.nodename
);
2790 return strdup(u
.sysname
);
2793 bool hostname_is_set(void) {
2796 assert_se(uname(&u
) >= 0);
2798 return !isempty(u
.nodename
) && !streq(u
.nodename
, "(none)");
2801 char *lookup_uid(uid_t uid
) {
2804 _cleanup_free_
char *buf
= NULL
;
2805 struct passwd pwbuf
, *pw
= NULL
;
2807 /* Shortcut things to avoid NSS lookups */
2809 return strdup("root");
2811 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
2815 buf
= malloc(bufsize
);
2819 if (getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
) == 0 && pw
)
2820 return strdup(pw
->pw_name
);
2822 if (asprintf(&name
, UID_FMT
, uid
) < 0)
2828 char* getlogname_malloc(void) {
2832 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
2837 return lookup_uid(uid
);
2840 char *getusername_malloc(void) {
2847 return lookup_uid(getuid());
2850 int getttyname_malloc(int fd
, char **ret
) {
2860 r
= ttyname_r(fd
, path
, sizeof(path
));
2865 p
= startswith(path
, "/dev/");
2866 c
= strdup(p
?: path
);
2883 int getttyname_harder(int fd
, char **r
) {
2887 k
= getttyname_malloc(fd
, &s
);
2891 if (streq(s
, "tty")) {
2893 return get_ctty(0, NULL
, r
);
2900 int get_ctty_devnr(pid_t pid
, dev_t
*d
) {
2902 _cleanup_free_
char *line
= NULL
;
2904 unsigned long ttynr
;
2908 p
= procfs_file_alloca(pid
, "stat");
2909 r
= read_one_line_file(p
, &line
);
2913 p
= strrchr(line
, ')');
2923 "%*d " /* session */
2928 if (major(ttynr
) == 0 && minor(ttynr
) == 0)
2937 int get_ctty(pid_t pid
, dev_t
*_devnr
, char **r
) {
2938 char fn
[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *b
= NULL
;
2939 _cleanup_free_
char *s
= NULL
;
2946 k
= get_ctty_devnr(pid
, &devnr
);
2950 sprintf(fn
, "/dev/char/%u:%u", major(devnr
), minor(devnr
));
2952 k
= readlink_malloc(fn
, &s
);
2958 /* This is an ugly hack */
2959 if (major(devnr
) == 136) {
2960 if (asprintf(&b
, "pts/%u", minor(devnr
)) < 0)
2963 /* Probably something like the ptys which have no
2964 * symlink in /dev/char. Let's return something
2965 * vaguely useful. */
2972 if (startswith(s
, "/dev/"))
2974 else if (startswith(s
, "../"))
2991 bool is_temporary_fs(const struct statfs
*s
) {
2994 return F_TYPE_EQUAL(s
->f_type
, TMPFS_MAGIC
) ||
2995 F_TYPE_EQUAL(s
->f_type
, RAMFS_MAGIC
);
2998 int fd_is_temporary_fs(int fd
) {
3001 if (fstatfs(fd
, &s
) < 0)
3004 return is_temporary_fs(&s
);
3007 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
3010 /* Under the assumption that we are running privileged we
3011 * first change the access mode and only then hand out
3012 * ownership to avoid a window where access is too open. */
3014 if (mode
!= MODE_INVALID
)
3015 if (chmod(path
, mode
) < 0)
3018 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
3019 if (chown(path
, uid
, gid
) < 0)
3025 int fchmod_and_fchown(int fd
, mode_t mode
, uid_t uid
, gid_t gid
) {
3028 /* Under the assumption that we are running privileged we
3029 * first change the access mode and only then hand out
3030 * ownership to avoid a window where access is too open. */
3032 if (mode
!= MODE_INVALID
)
3033 if (fchmod(fd
, mode
) < 0)
3036 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
3037 if (fchown(fd
, uid
, gid
) < 0)
3043 cpu_set_t
* cpu_set_malloc(unsigned *ncpus
) {
3047 /* Allocates the cpuset in the right size */
3050 if (!(r
= CPU_ALLOC(n
)))
3053 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n
), r
) >= 0) {
3054 CPU_ZERO_S(CPU_ALLOC_SIZE(n
), r
);
3064 if (errno
!= EINVAL
)
3071 int status_vprintf(const char *status
, bool ellipse
, bool ephemeral
, const char *format
, va_list ap
) {
3072 static const char status_indent
[] = " "; /* "[" STATUS "] " */
3073 _cleanup_free_
char *s
= NULL
;
3074 _cleanup_close_
int fd
= -1;
3075 struct iovec iovec
[6] = {};
3077 static bool prev_ephemeral
;
3081 /* This is independent of logging, as status messages are
3082 * optional and go exclusively to the console. */
3084 if (vasprintf(&s
, format
, ap
) < 0)
3087 fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
3100 sl
= status
? sizeof(status_indent
)-1 : 0;
3106 e
= ellipsize(s
, emax
, 50);
3114 IOVEC_SET_STRING(iovec
[n
++], "\r" ANSI_ERASE_TO_END_OF_LINE
);
3115 prev_ephemeral
= ephemeral
;
3118 if (!isempty(status
)) {
3119 IOVEC_SET_STRING(iovec
[n
++], "[");
3120 IOVEC_SET_STRING(iovec
[n
++], status
);
3121 IOVEC_SET_STRING(iovec
[n
++], "] ");
3123 IOVEC_SET_STRING(iovec
[n
++], status_indent
);
3126 IOVEC_SET_STRING(iovec
[n
++], s
);
3128 IOVEC_SET_STRING(iovec
[n
++], "\n");
3130 if (writev(fd
, iovec
, n
) < 0)
3136 int status_printf(const char *status
, bool ellipse
, bool ephemeral
, const char *format
, ...) {
3142 va_start(ap
, format
);
3143 r
= status_vprintf(status
, ellipse
, ephemeral
, format
, ap
);
3149 char *replace_env(const char *format
, char **env
) {
3156 const char *e
, *word
= format
;
3161 for (e
= format
; *e
; e
++) {
3172 k
= strnappend(r
, word
, e
-word
-1);
3182 } else if (*e
== '$') {
3183 k
= strnappend(r
, word
, e
-word
);
3200 t
= strempty(strv_env_get_n(env
, word
+2, e
-word
-2));
3202 k
= strappend(r
, t
);
3216 k
= strnappend(r
, word
, e
-word
);
3228 char **replace_env_argv(char **argv
, char **env
) {
3230 unsigned k
= 0, l
= 0;
3232 l
= strv_length(argv
);
3234 ret
= new(char*, l
+1);
3238 STRV_FOREACH(i
, argv
) {
3240 /* If $FOO appears as single word, replace it by the split up variable */
3241 if ((*i
)[0] == '$' && (*i
)[1] != '{') {
3243 char **w
, **m
= NULL
;
3246 e
= strv_env_get(env
, *i
+1);
3250 r
= strv_split_quoted(&m
, e
, UNQUOTE_RELAX
);
3262 w
= realloc(ret
, sizeof(char*) * (l
+1));
3272 memcpy(ret
+ k
, m
, q
* sizeof(char*));
3280 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3281 ret
[k
] = replace_env(*i
, env
);
3293 int fd_columns(int fd
) {
3294 struct winsize ws
= {};
3296 if (ioctl(fd
, TIOCGWINSZ
, &ws
) < 0)
3305 unsigned columns(void) {
3309 if (_likely_(cached_columns
> 0))
3310 return cached_columns
;
3313 e
= getenv("COLUMNS");
3315 (void) safe_atoi(e
, &c
);
3318 c
= fd_columns(STDOUT_FILENO
);
3324 return cached_columns
;
3327 int fd_lines(int fd
) {
3328 struct winsize ws
= {};
3330 if (ioctl(fd
, TIOCGWINSZ
, &ws
) < 0)
3339 unsigned lines(void) {
3343 if (_likely_(cached_lines
> 0))
3344 return cached_lines
;
3347 e
= getenv("LINES");
3349 (void) safe_atoi(e
, &l
);
3352 l
= fd_lines(STDOUT_FILENO
);
3358 return cached_lines
;
3361 /* intended to be used as a SIGWINCH sighandler */
3362 void columns_lines_cache_reset(int signum
) {
3368 static int cached_on_tty
= -1;
3370 if (_unlikely_(cached_on_tty
< 0))
3371 cached_on_tty
= isatty(STDOUT_FILENO
) > 0;
3373 return cached_on_tty
;
3376 int files_same(const char *filea
, const char *fileb
) {
3379 if (stat(filea
, &a
) < 0)
3382 if (stat(fileb
, &b
) < 0)
3385 return a
.st_dev
== b
.st_dev
&&
3386 a
.st_ino
== b
.st_ino
;
3389 int running_in_chroot(void) {
3392 ret
= files_same("/proc/1/root", "/");
3399 static char *ascii_ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
3404 assert(percent
<= 100);
3405 assert(new_length
>= 3);
3407 if (old_length
<= 3 || old_length
<= new_length
)
3408 return strndup(s
, old_length
);
3410 r
= new0(char, new_length
+1);
3414 x
= (new_length
* percent
) / 100;
3416 if (x
> new_length
- 3)
3424 s
+ old_length
- (new_length
- x
- 3),
3425 new_length
- x
- 3);
3430 char *ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
3434 unsigned k
, len
, len2
;
3437 assert(percent
<= 100);
3438 assert(new_length
>= 3);
3440 /* if no multibyte characters use ascii_ellipsize_mem for speed */
3441 if (ascii_is_valid(s
))
3442 return ascii_ellipsize_mem(s
, old_length
, new_length
, percent
);
3444 if (old_length
<= 3 || old_length
<= new_length
)
3445 return strndup(s
, old_length
);
3447 x
= (new_length
* percent
) / 100;
3449 if (x
> new_length
- 3)
3453 for (i
= s
; k
< x
&& i
< s
+ old_length
; i
= utf8_next_char(i
)) {
3456 c
= utf8_encoded_to_unichar(i
);
3459 k
+= unichar_iswide(c
) ? 2 : 1;
3462 if (k
> x
) /* last character was wide and went over quota */
3465 for (j
= s
+ old_length
; k
< new_length
&& j
> i
; ) {
3468 j
= utf8_prev_char(j
);
3469 c
= utf8_encoded_to_unichar(j
);
3472 k
+= unichar_iswide(c
) ? 2 : 1;
3476 /* we don't actually need to ellipsize */
3478 return memdup(s
, old_length
+ 1);
3480 /* make space for ellipsis */
3481 j
= utf8_next_char(j
);
3484 len2
= s
+ old_length
- j
;
3485 e
= new(char, len
+ 3 + len2
+ 1);
3490 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
3491 old_length, new_length, x, len, len2, k);
3495 e
[len
] = 0xe2; /* tri-dot ellipsis: … */
3499 memcpy(e
+ len
+ 3, j
, len2
+ 1);
3504 char *ellipsize(const char *s
, size_t length
, unsigned percent
) {
3505 return ellipsize_mem(s
, strlen(s
), length
, percent
);
3508 int touch_file(const char *path
, bool parents
, usec_t stamp
, uid_t uid
, gid_t gid
, mode_t mode
) {
3509 _cleanup_close_
int fd
;
3515 mkdir_parents(path
, 0755);
3517 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, mode
> 0 ? mode
: 0644);
3522 r
= fchmod(fd
, mode
);
3527 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
) {
3528 r
= fchown(fd
, uid
, gid
);
3533 if (stamp
!= USEC_INFINITY
) {
3534 struct timespec ts
[2];
3536 timespec_store(&ts
[0], stamp
);
3538 r
= futimens(fd
, ts
);
3540 r
= futimens(fd
, NULL
);
3547 int touch(const char *path
) {
3548 return touch_file(path
, false, USEC_INFINITY
, UID_INVALID
, GID_INVALID
, 0);
3551 char *unquote(const char *s
, const char* quotes
) {
3555 /* This is rather stupid, simply removes the heading and
3556 * trailing quotes if there is one. Doesn't care about
3557 * escaping or anything. We should make this smarter one
3564 if (strchr(quotes
, s
[0]) && s
[l
-1] == s
[0])
3565 return strndup(s
+1, l
-2);
3570 char *normalize_env_assignment(const char *s
) {
3571 _cleanup_free_
char *value
= NULL
;
3575 eq
= strchr(s
, '=');
3585 memmove(r
, t
, strlen(t
) + 1);
3590 name
= strndupa(s
, eq
- s
);
3591 p
= strdupa(eq
+ 1);
3593 value
= unquote(strstrip(p
), QUOTES
);
3597 return strjoin(strstrip(name
), "=", value
, NULL
);
3600 int wait_for_terminate(pid_t pid
, siginfo_t
*status
) {
3611 if (waitid(P_PID
, pid
, status
, WEXITED
) < 0) {
3625 * < 0 : wait_for_terminate() failed to get the state of the
3626 * process, the process was terminated by a signal, or
3627 * failed for an unknown reason.
3628 * >=0 : The process terminated normally, and its exit code is
3631 * That is, success is indicated by a return value of zero, and an
3632 * error is indicated by a non-zero value.
3634 * A warning is emitted if the process terminates abnormally,
3635 * and also if it returns non-zero unless check_exit_code is true.
3637 int wait_for_terminate_and_warn(const char *name
, pid_t pid
, bool check_exit_code
) {
3644 r
= wait_for_terminate(pid
, &status
);
3646 return log_warning_errno(r
, "Failed to wait for %s: %m", name
);
3648 if (status
.si_code
== CLD_EXITED
) {
3649 if (status
.si_status
!= 0)
3650 log_full(check_exit_code
? LOG_WARNING
: LOG_DEBUG
,
3651 "%s failed with error code %i.", name
, status
.si_status
);
3653 log_debug("%s succeeded.", name
);
3655 return status
.si_status
;
3656 } else if (status
.si_code
== CLD_KILLED
||
3657 status
.si_code
== CLD_DUMPED
) {
3659 log_warning("%s terminated by signal %s.", name
, signal_to_string(status
.si_status
));
3663 log_warning("%s failed due to unknown reason.", name
);
3667 noreturn
void freeze(void) {
3669 /* Make sure nobody waits for us on a socket anymore */
3670 close_all_fds(NULL
, 0);
3678 bool null_or_empty(struct stat
*st
) {
3681 if (S_ISREG(st
->st_mode
) && st
->st_size
<= 0)
3684 if (S_ISCHR(st
->st_mode
) || S_ISBLK(st
->st_mode
))
3690 int null_or_empty_path(const char *fn
) {
3695 if (stat(fn
, &st
) < 0)
3698 return null_or_empty(&st
);
3701 int null_or_empty_fd(int fd
) {
3706 if (fstat(fd
, &st
) < 0)
3709 return null_or_empty(&st
);
3712 DIR *xopendirat(int fd
, const char *name
, int flags
) {
3716 assert(!(flags
& O_CREAT
));
3718 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
3731 int signal_from_string_try_harder(const char *s
) {
3735 signo
= signal_from_string(s
);
3737 if (startswith(s
, "SIG"))
3738 return signal_from_string(s
+3);
3743 static char *tag_to_udev_node(const char *tagvalue
, const char *by
) {
3744 _cleanup_free_
char *t
= NULL
, *u
= NULL
;
3747 u
= unquote(tagvalue
, "\"\'");
3751 enc_len
= strlen(u
) * 4 + 1;
3752 t
= new(char, enc_len
);
3756 if (encode_devnode_name(u
, t
, enc_len
) < 0)
3759 return strjoin("/dev/disk/by-", by
, "/", t
, NULL
);
3762 char *fstab_node_to_udev_node(const char *p
) {
3765 if (startswith(p
, "LABEL="))
3766 return tag_to_udev_node(p
+6, "label");
3768 if (startswith(p
, "UUID="))
3769 return tag_to_udev_node(p
+5, "uuid");
3771 if (startswith(p
, "PARTUUID="))
3772 return tag_to_udev_node(p
+9, "partuuid");
3774 if (startswith(p
, "PARTLABEL="))
3775 return tag_to_udev_node(p
+10, "partlabel");
3780 bool tty_is_vc(const char *tty
) {
3783 return vtnr_from_tty(tty
) >= 0;
3786 bool tty_is_console(const char *tty
) {
3789 if (startswith(tty
, "/dev/"))
3792 return streq(tty
, "console");
3795 int vtnr_from_tty(const char *tty
) {
3800 if (startswith(tty
, "/dev/"))
3803 if (!startswith(tty
, "tty") )
3806 if (tty
[3] < '0' || tty
[3] > '9')
3809 r
= safe_atoi(tty
+3, &i
);
3813 if (i
< 0 || i
> 63)
3819 char *resolve_dev_console(char **active
) {
3822 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3823 * (i.e. not read-only-mounted which is a sign for container setups) */
3825 if (path_is_read_only_fs("/sys") > 0)
3828 if (read_one_line_file("/sys/class/tty/console/active", active
) < 0)
3831 /* If multiple log outputs are configured the last one is what
3832 * /dev/console points to */
3833 tty
= strrchr(*active
, ' ');
3839 if (streq(tty
, "tty0")) {
3842 /* Get the active VC (e.g. tty1) */
3843 if (read_one_line_file("/sys/class/tty/tty0/active", &tmp
) >= 0) {
3845 tty
= *active
= tmp
;
3852 bool tty_is_vc_resolve(const char *tty
) {
3853 _cleanup_free_
char *active
= NULL
;
3857 if (startswith(tty
, "/dev/"))
3860 if (streq(tty
, "console")) {
3861 tty
= resolve_dev_console(&active
);
3866 return tty_is_vc(tty
);
3869 const char *default_term_for_tty(const char *tty
) {
3872 return tty_is_vc_resolve(tty
) ? "TERM=linux" : "TERM=vt220";
3875 bool dirent_is_file(const struct dirent
*de
) {
3878 if (hidden_file(de
->d_name
))
3881 if (de
->d_type
!= DT_REG
&&
3882 de
->d_type
!= DT_LNK
&&
3883 de
->d_type
!= DT_UNKNOWN
)
3889 bool dirent_is_file_with_suffix(const struct dirent
*de
, const char *suffix
) {
3892 if (de
->d_type
!= DT_REG
&&
3893 de
->d_type
!= DT_LNK
&&
3894 de
->d_type
!= DT_UNKNOWN
)
3897 if (hidden_file_allow_backup(de
->d_name
))
3900 return endswith(de
->d_name
, suffix
);
3903 static int do_execute(char **directories
, usec_t timeout
, char *argv
[]) {
3904 _cleanup_hashmap_free_free_ Hashmap
*pids
= NULL
;
3905 _cleanup_set_free_free_ Set
*seen
= NULL
;
3908 /* We fork this all off from a child process so that we can
3909 * somewhat cleanly make use of SIGALRM to set a time limit */
3911 reset_all_signal_handlers();
3912 reset_signal_mask();
3914 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
3916 pids
= hashmap_new(NULL
);
3920 seen
= set_new(&string_hash_ops
);
3924 STRV_FOREACH(directory
, directories
) {
3925 _cleanup_closedir_
DIR *d
;
3928 d
= opendir(*directory
);
3930 if (errno
== ENOENT
)
3933 return log_error_errno(errno
, "Failed to open directory %s: %m", *directory
);
3936 FOREACH_DIRENT(de
, d
, break) {
3937 _cleanup_free_
char *path
= NULL
;
3941 if (!dirent_is_file(de
))
3944 if (set_contains(seen
, de
->d_name
)) {
3945 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory
, de
->d_name
);
3949 r
= set_put_strdup(seen
, de
->d_name
);
3953 path
= strjoin(*directory
, "/", de
->d_name
, NULL
);
3957 if (null_or_empty_path(path
)) {
3958 log_debug("%s is empty (a mask).", path
);
3964 log_error_errno(errno
, "Failed to fork: %m");
3966 } else if (pid
== 0) {
3969 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
3979 return log_error_errno(errno
, "Failed to execute %s: %m", path
);
3982 log_debug("Spawned %s as " PID_FMT
".", path
, pid
);
3984 r
= hashmap_put(pids
, UINT_TO_PTR(pid
), path
);
3991 /* Abort execution of this process after the timout. We simply
3992 * rely on SIGALRM as default action terminating the process,
3993 * and turn on alarm(). */
3995 if (timeout
!= USEC_INFINITY
)
3996 alarm((timeout
+ USEC_PER_SEC
- 1) / USEC_PER_SEC
);
3998 while (!hashmap_isempty(pids
)) {
3999 _cleanup_free_
char *path
= NULL
;
4002 pid
= PTR_TO_UINT(hashmap_first_key(pids
));
4005 path
= hashmap_remove(pids
, UINT_TO_PTR(pid
));
4008 wait_for_terminate_and_warn(path
, pid
, true);
4014 void execute_directories(const char* const* directories
, usec_t timeout
, char *argv
[]) {
4018 char **dirs
= (char**) directories
;
4020 assert(!strv_isempty(dirs
));
4022 name
= basename(dirs
[0]);
4023 assert(!isempty(name
));
4025 /* Executes all binaries in the directories in parallel and waits
4026 * for them to finish. Optionally a timeout is applied. If a file
4027 * with the same name exists in more than one directory, the
4028 * earliest one wins. */
4030 executor_pid
= fork();
4031 if (executor_pid
< 0) {
4032 log_error_errno(errno
, "Failed to fork: %m");
4035 } else if (executor_pid
== 0) {
4036 r
= do_execute(dirs
, timeout
, argv
);
4037 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
4040 wait_for_terminate_and_warn(name
, executor_pid
, true);
4043 int kill_and_sigcont(pid_t pid
, int sig
) {
4046 r
= kill(pid
, sig
) < 0 ? -errno
: 0;
4054 bool nulstr_contains(const char*nulstr
, const char *needle
) {
4060 NULSTR_FOREACH(i
, nulstr
)
4061 if (streq(i
, needle
))
4067 bool plymouth_running(void) {
4068 return access("/run/plymouth/pid", F_OK
) >= 0;
4071 char* strshorten(char *s
, size_t l
) {
4080 static bool hostname_valid_char(char c
) {
4082 (c
>= 'a' && c
<= 'z') ||
4083 (c
>= 'A' && c
<= 'Z') ||
4084 (c
>= '0' && c
<= '9') ||
4090 bool hostname_is_valid(const char *s
) {
4097 /* Doesn't accept empty hostnames, hostnames with trailing or
4098 * leading dots, and hostnames with multiple dots in a
4099 * sequence. Also ensures that the length stays below
4102 for (p
= s
, dot
= true; *p
; p
++) {
4109 if (!hostname_valid_char(*p
))
4119 if (p
-s
> HOST_NAME_MAX
)
4125 char* hostname_cleanup(char *s
, bool lowercase
) {
4129 for (p
= s
, d
= s
, dot
= true; *p
; p
++) {
4136 } else if (hostname_valid_char(*p
)) {
4137 *(d
++) = lowercase
? tolower(*p
) : *p
;
4148 strshorten(s
, HOST_NAME_MAX
);
4153 bool machine_name_is_valid(const char *s
) {
4155 if (!hostname_is_valid(s
))
4158 /* Machine names should be useful hostnames, but also be
4159 * useful in unit names, hence we enforce a stricter length
4168 int pipe_eof(int fd
) {
4169 struct pollfd pollfd
= {
4171 .events
= POLLIN
|POLLHUP
,
4176 r
= poll(&pollfd
, 1, 0);
4183 return pollfd
.revents
& POLLHUP
;
4186 int fd_wait_for_event(int fd
, int event
, usec_t t
) {
4188 struct pollfd pollfd
= {
4196 r
= ppoll(&pollfd
, 1, t
== USEC_INFINITY
? NULL
: timespec_store(&ts
, t
), NULL
);
4203 return pollfd
.revents
;
4206 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
4215 r
= tempfn_xxxxxx(path
, &t
);
4219 fd
= mkostemp_safe(t
, O_WRONLY
|O_CLOEXEC
);
4225 f
= fdopen(fd
, "we");
4238 int terminal_vhangup_fd(int fd
) {
4241 if (ioctl(fd
, TIOCVHANGUP
) < 0)
4247 int terminal_vhangup(const char *name
) {
4248 _cleanup_close_
int fd
;
4250 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
4254 return terminal_vhangup_fd(fd
);
4257 int vt_disallocate(const char *name
) {
4261 /* Deallocate the VT if possible. If not possible
4262 * (i.e. because it is the active one), at least clear it
4263 * entirely (including the scrollback buffer) */
4265 if (!startswith(name
, "/dev/"))
4268 if (!tty_is_vc(name
)) {
4269 /* So this is not a VT. I guess we cannot deallocate
4270 * it then. But let's at least clear the screen */
4272 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
4277 "\033[r" /* clear scrolling region */
4278 "\033[H" /* move home */
4279 "\033[2J", /* clear screen */
4286 if (!startswith(name
, "/dev/tty"))
4289 r
= safe_atou(name
+8, &u
);
4296 /* Try to deallocate */
4297 fd
= open_terminal("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
4301 r
= ioctl(fd
, VT_DISALLOCATE
, u
);
4310 /* Couldn't deallocate, so let's clear it fully with
4312 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
4317 "\033[r" /* clear scrolling region */
4318 "\033[H" /* move home */
4319 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4326 int symlink_atomic(const char *from
, const char *to
) {
4327 _cleanup_free_
char *t
= NULL
;
4333 r
= tempfn_random(to
, &t
);
4337 if (symlink(from
, t
) < 0)
4340 if (rename(t
, to
) < 0) {
4348 int mknod_atomic(const char *path
, mode_t mode
, dev_t dev
) {
4349 _cleanup_free_
char *t
= NULL
;
4354 r
= tempfn_random(path
, &t
);
4358 if (mknod(t
, mode
, dev
) < 0)
4361 if (rename(t
, path
) < 0) {
4369 int mkfifo_atomic(const char *path
, mode_t mode
) {
4370 _cleanup_free_
char *t
= NULL
;
4375 r
= tempfn_random(path
, &t
);
4379 if (mkfifo(t
, mode
) < 0)
4382 if (rename(t
, path
) < 0) {
4390 bool display_is_local(const char *display
) {
4394 display
[0] == ':' &&
4395 display
[1] >= '0' &&
4399 int socket_from_display(const char *display
, char **path
) {
4406 if (!display_is_local(display
))
4409 k
= strspn(display
+1, "0123456789");
4411 f
= new(char, strlen("/tmp/.X11-unix/X") + k
+ 1);
4415 c
= stpcpy(f
, "/tmp/.X11-unix/X");
4416 memcpy(c
, display
+1, k
);
4425 const char **username
,
4426 uid_t
*uid
, gid_t
*gid
,
4428 const char **shell
) {
4436 /* We enforce some special rules for uid=0: in order to avoid
4437 * NSS lookups for root we hardcode its data. */
4439 if (streq(*username
, "root") || streq(*username
, "0")) {
4457 if (parse_uid(*username
, &u
) >= 0) {
4461 /* If there are multiple users with the same id, make
4462 * sure to leave $USER to the configured value instead
4463 * of the first occurrence in the database. However if
4464 * the uid was configured by a numeric uid, then let's
4465 * pick the real username from /etc/passwd. */
4467 *username
= p
->pw_name
;
4470 p
= getpwnam(*username
);
4474 return errno
> 0 ? -errno
: -ESRCH
;
4486 *shell
= p
->pw_shell
;
4491 char* uid_to_name(uid_t uid
) {
4496 return strdup("root");
4500 return strdup(p
->pw_name
);
4502 if (asprintf(&r
, UID_FMT
, uid
) < 0)
4508 char* gid_to_name(gid_t gid
) {
4513 return strdup("root");
4517 return strdup(p
->gr_name
);
4519 if (asprintf(&r
, GID_FMT
, gid
) < 0)
4525 int get_group_creds(const char **groupname
, gid_t
*gid
) {
4531 /* We enforce some special rules for gid=0: in order to avoid
4532 * NSS lookups for root we hardcode its data. */
4534 if (streq(*groupname
, "root") || streq(*groupname
, "0")) {
4535 *groupname
= "root";
4543 if (parse_gid(*groupname
, &id
) >= 0) {
4548 *groupname
= g
->gr_name
;
4551 g
= getgrnam(*groupname
);
4555 return errno
> 0 ? -errno
: -ESRCH
;
4563 int in_gid(gid_t gid
) {
4565 int ngroups_max
, r
, i
;
4567 if (getgid() == gid
)
4570 if (getegid() == gid
)
4573 ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
4574 assert(ngroups_max
> 0);
4576 gids
= alloca(sizeof(gid_t
) * ngroups_max
);
4578 r
= getgroups(ngroups_max
, gids
);
4582 for (i
= 0; i
< r
; i
++)
4589 int in_group(const char *name
) {
4593 r
= get_group_creds(&name
, &gid
);
4600 int glob_exists(const char *path
) {
4601 _cleanup_globfree_ glob_t g
= {};
4607 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
4609 if (k
== GLOB_NOMATCH
)
4611 else if (k
== GLOB_NOSPACE
)
4614 return !strv_isempty(g
.gl_pathv
);
4616 return errno
? -errno
: -EIO
;
4619 int glob_extend(char ***strv
, const char *path
) {
4620 _cleanup_globfree_ glob_t g
= {};
4625 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
4627 if (k
== GLOB_NOMATCH
)
4629 else if (k
== GLOB_NOSPACE
)
4631 else if (k
!= 0 || strv_isempty(g
.gl_pathv
))
4632 return errno
? -errno
: -EIO
;
4634 STRV_FOREACH(p
, g
.gl_pathv
) {
4635 k
= strv_extend(strv
, *p
);
4643 int dirent_ensure_type(DIR *d
, struct dirent
*de
) {
4649 if (de
->d_type
!= DT_UNKNOWN
)
4652 if (fstatat(dirfd(d
), de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
4656 S_ISREG(st
.st_mode
) ? DT_REG
:
4657 S_ISDIR(st
.st_mode
) ? DT_DIR
:
4658 S_ISLNK(st
.st_mode
) ? DT_LNK
:
4659 S_ISFIFO(st
.st_mode
) ? DT_FIFO
:
4660 S_ISSOCK(st
.st_mode
) ? DT_SOCK
:
4661 S_ISCHR(st
.st_mode
) ? DT_CHR
:
4662 S_ISBLK(st
.st_mode
) ? DT_BLK
:
4668 int get_files_in_directory(const char *path
, char ***list
) {
4669 _cleanup_closedir_
DIR *d
= NULL
;
4670 size_t bufsize
= 0, n
= 0;
4671 _cleanup_strv_free_
char **l
= NULL
;
4675 /* Returns all files in a directory in *list, and the number
4676 * of files as return value. If list is NULL returns only the
4688 if (!de
&& errno
!= 0)
4693 dirent_ensure_type(d
, de
);
4695 if (!dirent_is_file(de
))
4699 /* one extra slot is needed for the terminating NULL */
4700 if (!GREEDY_REALLOC(l
, bufsize
, n
+ 2))
4703 l
[n
] = strdup(de
->d_name
);
4714 l
= NULL
; /* avoid freeing */
4720 char *strjoin(const char *x
, ...) {
4734 t
= va_arg(ap
, const char *);
4739 if (n
> ((size_t) -1) - l
) {
4763 t
= va_arg(ap
, const char *);
4777 bool is_main_thread(void) {
4778 static thread_local
int cached
= 0;
4780 if (_unlikely_(cached
== 0))
4781 cached
= getpid() == gettid() ? 1 : -1;
4786 int block_get_whole_disk(dev_t d
, dev_t
*ret
) {
4793 /* If it has a queue this is good enough for us */
4794 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", major(d
), minor(d
)) < 0)
4797 r
= access(p
, F_OK
);
4805 /* If it is a partition find the originating device */
4806 if (asprintf(&p
, "/sys/dev/block/%u:%u/partition", major(d
), minor(d
)) < 0)
4809 r
= access(p
, F_OK
);
4815 /* Get parent dev_t */
4816 if (asprintf(&p
, "/sys/dev/block/%u:%u/../dev", major(d
), minor(d
)) < 0)
4819 r
= read_one_line_file(p
, &s
);
4825 r
= sscanf(s
, "%u:%u", &m
, &n
);
4831 /* Only return this if it is really good enough for us. */
4832 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", m
, n
) < 0)
4835 r
= access(p
, F_OK
);
4839 *ret
= makedev(m
, n
);
4846 static const char *const ioprio_class_table
[] = {
4847 [IOPRIO_CLASS_NONE
] = "none",
4848 [IOPRIO_CLASS_RT
] = "realtime",
4849 [IOPRIO_CLASS_BE
] = "best-effort",
4850 [IOPRIO_CLASS_IDLE
] = "idle"
4853 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, INT_MAX
);
4855 static const char *const sigchld_code_table
[] = {
4856 [CLD_EXITED
] = "exited",
4857 [CLD_KILLED
] = "killed",
4858 [CLD_DUMPED
] = "dumped",
4859 [CLD_TRAPPED
] = "trapped",
4860 [CLD_STOPPED
] = "stopped",
4861 [CLD_CONTINUED
] = "continued",
4864 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
4866 static const char *const log_facility_unshifted_table
[LOG_NFACILITIES
] = {
4867 [LOG_FAC(LOG_KERN
)] = "kern",
4868 [LOG_FAC(LOG_USER
)] = "user",
4869 [LOG_FAC(LOG_MAIL
)] = "mail",
4870 [LOG_FAC(LOG_DAEMON
)] = "daemon",
4871 [LOG_FAC(LOG_AUTH
)] = "auth",
4872 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
4873 [LOG_FAC(LOG_LPR
)] = "lpr",
4874 [LOG_FAC(LOG_NEWS
)] = "news",
4875 [LOG_FAC(LOG_UUCP
)] = "uucp",
4876 [LOG_FAC(LOG_CRON
)] = "cron",
4877 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
4878 [LOG_FAC(LOG_FTP
)] = "ftp",
4879 [LOG_FAC(LOG_LOCAL0
)] = "local0",
4880 [LOG_FAC(LOG_LOCAL1
)] = "local1",
4881 [LOG_FAC(LOG_LOCAL2
)] = "local2",
4882 [LOG_FAC(LOG_LOCAL3
)] = "local3",
4883 [LOG_FAC(LOG_LOCAL4
)] = "local4",
4884 [LOG_FAC(LOG_LOCAL5
)] = "local5",
4885 [LOG_FAC(LOG_LOCAL6
)] = "local6",
4886 [LOG_FAC(LOG_LOCAL7
)] = "local7"
4889 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted
, int, LOG_FAC(~0));
4891 static const char *const log_level_table
[] = {
4892 [LOG_EMERG
] = "emerg",
4893 [LOG_ALERT
] = "alert",
4894 [LOG_CRIT
] = "crit",
4896 [LOG_WARNING
] = "warning",
4897 [LOG_NOTICE
] = "notice",
4898 [LOG_INFO
] = "info",
4899 [LOG_DEBUG
] = "debug"
4902 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level
, int, LOG_DEBUG
);
4904 static const char* const sched_policy_table
[] = {
4905 [SCHED_OTHER
] = "other",
4906 [SCHED_BATCH
] = "batch",
4907 [SCHED_IDLE
] = "idle",
4908 [SCHED_FIFO
] = "fifo",
4912 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);
4914 static const char* const rlimit_table
[_RLIMIT_MAX
] = {
4915 [RLIMIT_CPU
] = "LimitCPU",
4916 [RLIMIT_FSIZE
] = "LimitFSIZE",
4917 [RLIMIT_DATA
] = "LimitDATA",
4918 [RLIMIT_STACK
] = "LimitSTACK",
4919 [RLIMIT_CORE
] = "LimitCORE",
4920 [RLIMIT_RSS
] = "LimitRSS",
4921 [RLIMIT_NOFILE
] = "LimitNOFILE",
4922 [RLIMIT_AS
] = "LimitAS",
4923 [RLIMIT_NPROC
] = "LimitNPROC",
4924 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
4925 [RLIMIT_LOCKS
] = "LimitLOCKS",
4926 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
4927 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
4928 [RLIMIT_NICE
] = "LimitNICE",
4929 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
4930 [RLIMIT_RTTIME
] = "LimitRTTIME"
4933 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
4935 static const char* const ip_tos_table
[] = {
4936 [IPTOS_LOWDELAY
] = "low-delay",
4937 [IPTOS_THROUGHPUT
] = "throughput",
4938 [IPTOS_RELIABILITY
] = "reliability",
4939 [IPTOS_LOWCOST
] = "low-cost",
4942 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos
, int, 0xff);
4944 static const char *const __signal_table
[] = {
4961 [SIGSTKFLT
] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4972 [SIGVTALRM
] = "VTALRM",
4974 [SIGWINCH
] = "WINCH",
4980 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal
, int);
4982 const char *signal_to_string(int signo
) {
4983 static thread_local
char buf
[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4986 name
= __signal_to_string(signo
);
4990 if (signo
>= SIGRTMIN
&& signo
<= SIGRTMAX
)
4991 snprintf(buf
, sizeof(buf
), "RTMIN+%d", signo
- SIGRTMIN
);
4993 snprintf(buf
, sizeof(buf
), "%d", signo
);
4998 int signal_from_string(const char *s
) {
5003 signo
= __signal_from_string(s
);
5007 if (startswith(s
, "RTMIN+")) {
5011 if (safe_atou(s
, &u
) >= 0) {
5012 signo
= (int) u
+ offset
;
5013 if (signo
> 0 && signo
< _NSIG
)
5019 bool kexec_loaded(void) {
5020 bool loaded
= false;
5023 if (read_one_line_file("/sys/kernel/kexec_loaded", &s
) >= 0) {
5031 int prot_from_flags(int flags
) {
5033 switch (flags
& O_ACCMODE
) {
5042 return PROT_READ
|PROT_WRITE
;
5049 char *format_bytes(char *buf
, size_t l
, off_t t
) {
5052 static const struct {
5056 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5057 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5058 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5059 { "G", 1024ULL*1024ULL*1024ULL },
5060 { "M", 1024ULL*1024ULL },
5064 if (t
== (off_t
) -1)
5067 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
5069 if (t
>= table
[i
].factor
) {
5072 (unsigned long long) (t
/ table
[i
].factor
),
5073 (unsigned long long) (((t
*10ULL) / table
[i
].factor
) % 10ULL),
5080 snprintf(buf
, l
, "%lluB", (unsigned long long) t
);
5088 void* memdup(const void *p
, size_t l
) {
5101 int fd_inc_sndbuf(int fd
, size_t n
) {
5103 socklen_t l
= sizeof(value
);
5105 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
5106 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
5109 /* If we have the privileges we will ignore the kernel limit. */
5112 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
5113 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
5119 int fd_inc_rcvbuf(int fd
, size_t n
) {
5121 socklen_t l
= sizeof(value
);
5123 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
5124 if (r
>= 0 && l
== sizeof(value
) && (size_t) value
>= n
*2)
5127 /* If we have the privileges we will ignore the kernel limit. */
5130 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
5131 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
5136 int fork_agent(pid_t
*pid
, const int except
[], unsigned n_except
, const char *path
, ...) {
5137 bool stdout_is_tty
, stderr_is_tty
;
5138 pid_t parent_pid
, agent_pid
;
5139 sigset_t ss
, saved_ss
;
5147 /* Spawns a temporary TTY agent, making sure it goes away when
5150 parent_pid
= getpid();
5152 /* First we temporarily block all signals, so that the new
5153 * child has them blocked initially. This way, we can be sure
5154 * that SIGTERMs are not lost we might send to the agent. */
5155 assert_se(sigfillset(&ss
) >= 0);
5156 assert_se(sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) >= 0);
5159 if (agent_pid
< 0) {
5160 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
5164 if (agent_pid
!= 0) {
5165 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
5172 * Make sure the agent goes away when the parent dies */
5173 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
5174 _exit(EXIT_FAILURE
);
5176 /* Make sure we actually can kill the agent, if we need to, in
5177 * case somebody invoked us from a shell script that trapped
5178 * SIGTERM or so... */
5179 reset_all_signal_handlers();
5180 reset_signal_mask();
5182 /* Check whether our parent died before we were able
5183 * to set the death signal and unblock the signals */
5184 if (getppid() != parent_pid
)
5185 _exit(EXIT_SUCCESS
);
5187 /* Don't leak fds to the agent */
5188 close_all_fds(except
, n_except
);
5190 stdout_is_tty
= isatty(STDOUT_FILENO
);
5191 stderr_is_tty
= isatty(STDERR_FILENO
);
5193 if (!stdout_is_tty
|| !stderr_is_tty
) {
5196 /* Detach from stdout/stderr. and reopen
5197 * /dev/tty for them. This is important to
5198 * ensure that when systemctl is started via
5199 * popen() or a similar call that expects to
5200 * read EOF we actually do generate EOF and
5201 * not delay this indefinitely by because we
5202 * keep an unused copy of stdin around. */
5203 fd
= open("/dev/tty", O_WRONLY
);
5205 log_error_errno(errno
, "Failed to open /dev/tty: %m");
5206 _exit(EXIT_FAILURE
);
5210 dup2(fd
, STDOUT_FILENO
);
5213 dup2(fd
, STDERR_FILENO
);
5219 /* Count arguments */
5221 for (n
= 0; va_arg(ap
, char*); n
++)
5226 l
= alloca(sizeof(char *) * (n
+ 1));
5228 /* Fill in arguments */
5230 for (i
= 0; i
<= n
; i
++)
5231 l
[i
] = va_arg(ap
, char*);
5235 _exit(EXIT_FAILURE
);
5238 int setrlimit_closest(int resource
, const struct rlimit
*rlim
) {
5239 struct rlimit highest
, fixed
;
5243 if (setrlimit(resource
, rlim
) >= 0)
5249 /* So we failed to set the desired setrlimit, then let's try
5250 * to get as close as we can */
5251 assert_se(getrlimit(resource
, &highest
) == 0);
5253 fixed
.rlim_cur
= MIN(rlim
->rlim_cur
, highest
.rlim_max
);
5254 fixed
.rlim_max
= MIN(rlim
->rlim_max
, highest
.rlim_max
);
5256 if (setrlimit(resource
, &fixed
) < 0)
5262 int getenv_for_pid(pid_t pid
, const char *field
, char **_value
) {
5263 _cleanup_fclose_
FILE *f
= NULL
;
5274 path
= procfs_file_alloca(pid
, "environ");
5276 f
= fopen(path
, "re");
5284 char line
[LINE_MAX
];
5287 for (i
= 0; i
< sizeof(line
)-1; i
++) {
5291 if (_unlikely_(c
== EOF
)) {
5301 if (memcmp(line
, field
, l
) == 0 && line
[l
] == '=') {
5302 value
= strdup(line
+ l
+ 1);
5316 bool http_etag_is_valid(const char *etag
) {
5320 if (!endswith(etag
, "\""))
5323 if (!startswith(etag
, "\"") && !startswith(etag
, "W/\""))
5329 bool http_url_is_valid(const char *url
) {
5335 p
= startswith(url
, "http://");
5337 p
= startswith(url
, "https://");
5344 return ascii_is_valid(p
);
5347 bool documentation_url_is_valid(const char *url
) {
5353 if (http_url_is_valid(url
))
5356 p
= startswith(url
, "file:/");
5358 p
= startswith(url
, "info:");
5360 p
= startswith(url
, "man:");
5365 return ascii_is_valid(p
);
5368 bool in_initrd(void) {
5369 static int saved
= -1;
5375 /* We make two checks here:
5377 * 1. the flag file /etc/initrd-release must exist
5378 * 2. the root file system must be a memory file system
5380 * The second check is extra paranoia, since misdetecting an
5381 * initrd can have bad bad consequences due the initrd
5382 * emptying when transititioning to the main systemd.
5385 saved
= access("/etc/initrd-release", F_OK
) >= 0 &&
5386 statfs("/", &s
) >= 0 &&
5387 is_temporary_fs(&s
);
5392 void warn_melody(void) {
5393 _cleanup_close_
int fd
= -1;
5395 fd
= open("/dev/console", O_WRONLY
|O_CLOEXEC
|O_NOCTTY
);
5399 /* Yeah, this is synchronous. Kinda sucks. But well... */
5401 ioctl(fd
, KIOCSOUND
, (int)(1193180/440));
5402 usleep(125*USEC_PER_MSEC
);
5404 ioctl(fd
, KIOCSOUND
, (int)(1193180/220));
5405 usleep(125*USEC_PER_MSEC
);
5407 ioctl(fd
, KIOCSOUND
, (int)(1193180/220));
5408 usleep(125*USEC_PER_MSEC
);
5410 ioctl(fd
, KIOCSOUND
, 0);
5413 int make_console_stdio(void) {
5416 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5418 fd
= acquire_terminal("/dev/console", false, true, true, USEC_INFINITY
);
5420 return log_error_errno(fd
, "Failed to acquire terminal: %m");
5424 return log_error_errno(r
, "Failed to duplicate terminal fd: %m");
5429 int get_home_dir(char **_h
) {
5437 /* Take the user specified one */
5438 e
= secure_getenv("HOME");
5439 if (e
&& path_is_absolute(e
)) {
5448 /* Hardcode home directory for root to avoid NSS */
5451 h
= strdup("/root");
5459 /* Check the database... */
5463 return errno
> 0 ? -errno
: -ESRCH
;
5465 if (!path_is_absolute(p
->pw_dir
))
5468 h
= strdup(p
->pw_dir
);
5476 int get_shell(char **_s
) {
5484 /* Take the user specified one */
5485 e
= getenv("SHELL");
5495 /* Hardcode home directory for root to avoid NSS */
5498 s
= strdup("/bin/sh");
5506 /* Check the database... */
5510 return errno
> 0 ? -errno
: -ESRCH
;
5512 if (!path_is_absolute(p
->pw_shell
))
5515 s
= strdup(p
->pw_shell
);
5523 bool filename_is_valid(const char *p
) {
5537 if (strlen(p
) > FILENAME_MAX
)
5543 bool string_is_safe(const char *p
) {
5549 for (t
= p
; *t
; t
++) {
5550 if (*t
> 0 && *t
< ' ')
5553 if (strchr("\\\"\'\0x7f", *t
))
5561 * Check if a string contains control characters. If 'ok' is non-NULL
5562 * it may be a string containing additional CCs to be considered OK.
5564 bool string_has_cc(const char *p
, const char *ok
) {
5569 for (t
= p
; *t
; t
++) {
5570 if (ok
&& strchr(ok
, *t
))
5573 if (*t
> 0 && *t
< ' ')
5583 bool path_is_safe(const char *p
) {
5588 if (streq(p
, "..") || startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
5591 if (strlen(p
) > PATH_MAX
)
5594 /* The following two checks are not really dangerous, but hey, they still are confusing */
5595 if (streq(p
, ".") || startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
5598 if (strstr(p
, "//"))
5604 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5605 void *xbsearch_r(const void *key
, const void *base
, size_t nmemb
, size_t size
,
5606 int (*compar
) (const void *, const void *, void *), void *arg
) {
5615 p
= (void *)(((const char *) base
) + (idx
* size
));
5616 comparison
= compar(key
, p
, arg
);
5619 else if (comparison
> 0)
5627 void init_gettext(void) {
5628 setlocale(LC_ALL
, "");
5629 textdomain(GETTEXT_PACKAGE
);
5632 bool is_locale_utf8(void) {
5634 static int cached_answer
= -1;
5636 if (cached_answer
>= 0)
5639 if (!setlocale(LC_ALL
, "")) {
5640 cached_answer
= true;
5644 set
= nl_langinfo(CODESET
);
5646 cached_answer
= true;
5650 if (streq(set
, "UTF-8")) {
5651 cached_answer
= true;
5655 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
5656 * unset and everything can do to UTF-8 nowadays. */
5657 set
= setlocale(LC_CTYPE
, NULL
);
5659 cached_answer
= true;
5663 /* Check result, but ignore the result if C was set
5667 !getenv("LC_ALL") &&
5668 !getenv("LC_CTYPE") &&
5672 return (bool) cached_answer
;
5675 const char *draw_special_char(DrawSpecialChar ch
) {
5676 static const char *draw_table
[2][_DRAW_SPECIAL_CHAR_MAX
] = {
5679 [DRAW_TREE_VERTICAL
] = "\342\224\202 ", /* │ */
5680 [DRAW_TREE_BRANCH
] = "\342\224\234\342\224\200", /* ├─ */
5681 [DRAW_TREE_RIGHT
] = "\342\224\224\342\224\200", /* └─ */
5682 [DRAW_TREE_SPACE
] = " ", /* */
5683 [DRAW_TRIANGULAR_BULLET
] = "\342\200\243", /* ‣ */
5684 [DRAW_BLACK_CIRCLE
] = "\342\227\217", /* ● */
5685 [DRAW_ARROW
] = "\342\206\222", /* → */
5686 [DRAW_DASH
] = "\342\200\223", /* – */
5689 /* ASCII fallback */ {
5690 [DRAW_TREE_VERTICAL
] = "| ",
5691 [DRAW_TREE_BRANCH
] = "|-",
5692 [DRAW_TREE_RIGHT
] = "`-",
5693 [DRAW_TREE_SPACE
] = " ",
5694 [DRAW_TRIANGULAR_BULLET
] = ">",
5695 [DRAW_BLACK_CIRCLE
] = "*",
5696 [DRAW_ARROW
] = "->",
5701 return draw_table
[!is_locale_utf8()][ch
];
5704 char *strreplace(const char *text
, const char *old_string
, const char *new_string
) {
5707 size_t l
, old_len
, new_len
;
5713 old_len
= strlen(old_string
);
5714 new_len
= strlen(new_string
);
5727 if (!startswith(f
, old_string
)) {
5733 nl
= l
- old_len
+ new_len
;
5734 a
= realloc(r
, nl
+ 1);
5742 t
= stpcpy(t
, new_string
);
5754 char *strip_tab_ansi(char **ibuf
, size_t *_isz
) {
5755 const char *i
, *begin
= NULL
;
5760 } state
= STATE_OTHER
;
5762 size_t osz
= 0, isz
;
5768 /* Strips ANSI color and replaces TABs by 8 spaces */
5770 isz
= _isz
? *_isz
: strlen(*ibuf
);
5772 f
= open_memstream(&obuf
, &osz
);
5776 for (i
= *ibuf
; i
< *ibuf
+ isz
+ 1; i
++) {
5781 if (i
>= *ibuf
+ isz
) /* EOT */
5783 else if (*i
== '\x1B')
5784 state
= STATE_ESCAPE
;
5785 else if (*i
== '\t')
5792 if (i
>= *ibuf
+ isz
) { /* EOT */
5795 } else if (*i
== '[') {
5796 state
= STATE_BRACKET
;
5801 state
= STATE_OTHER
;
5808 if (i
>= *ibuf
+ isz
|| /* EOT */
5809 (!(*i
>= '0' && *i
<= '9') && *i
!= ';' && *i
!= 'm')) {
5812 state
= STATE_OTHER
;
5814 } else if (*i
== 'm')
5815 state
= STATE_OTHER
;
5837 int on_ac_power(void) {
5838 bool found_offline
= false, found_online
= false;
5839 _cleanup_closedir_
DIR *d
= NULL
;
5841 d
= opendir("/sys/class/power_supply");
5843 return errno
== ENOENT
? true : -errno
;
5847 _cleanup_close_
int fd
= -1, device
= -1;
5853 if (!de
&& errno
!= 0)
5859 if (hidden_file(de
->d_name
))
5862 device
= openat(dirfd(d
), de
->d_name
, O_DIRECTORY
|O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
5864 if (errno
== ENOENT
|| errno
== ENOTDIR
)
5870 fd
= openat(device
, "type", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
5872 if (errno
== ENOENT
)
5878 n
= read(fd
, contents
, sizeof(contents
));
5882 if (n
!= 6 || memcmp(contents
, "Mains\n", 6))
5886 fd
= openat(device
, "online", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
5888 if (errno
== ENOENT
)
5894 n
= read(fd
, contents
, sizeof(contents
));
5898 if (n
!= 2 || contents
[1] != '\n')
5901 if (contents
[0] == '1') {
5902 found_online
= true;
5904 } else if (contents
[0] == '0')
5905 found_offline
= true;
5910 return found_online
|| !found_offline
;
5913 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
5920 if (!path_strv_resolve_uniq(search
, root
))
5923 STRV_FOREACH(i
, search
) {
5924 _cleanup_free_
char *p
= NULL
;
5928 p
= strjoin(root
, *i
, "/", path
, NULL
);
5930 p
= strjoin(*i
, "/", path
, NULL
);
5940 if (errno
!= ENOENT
)
5947 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
5948 _cleanup_strv_free_
char **copy
= NULL
;
5954 if (path_is_absolute(path
)) {
5957 f
= fopen(path
, mode
);
5966 copy
= strv_copy((char**) search
);
5970 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
5973 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
5974 _cleanup_strv_free_
char **s
= NULL
;
5976 if (path_is_absolute(path
)) {
5979 f
= fopen(path
, mode
);
5988 s
= strv_split_nulstr(search
);
5992 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
5995 char *strextend(char **x
, ...) {
6002 l
= f
= *x
? strlen(*x
) : 0;
6009 t
= va_arg(ap
, const char *);
6014 if (n
> ((size_t) -1) - l
) {
6023 r
= realloc(*x
, l
+1);
6033 t
= va_arg(ap
, const char *);
6047 char *strrep(const char *s
, unsigned n
) {
6055 p
= r
= malloc(l
* n
+ 1);
6059 for (i
= 0; i
< n
; i
++)
6066 void* greedy_realloc(void **p
, size_t *allocated
, size_t need
, size_t size
) {
6073 if (*allocated
>= need
)
6076 newalloc
= MAX(need
* 2, 64u / size
);
6077 a
= newalloc
* size
;
6079 /* check for overflows */
6080 if (a
< size
* need
)
6088 *allocated
= newalloc
;
6092 void* greedy_realloc0(void **p
, size_t *allocated
, size_t need
, size_t size
) {
6101 q
= greedy_realloc(p
, allocated
, need
, size
);
6105 if (*allocated
> prev
)
6106 memzero(q
+ prev
* size
, (*allocated
- prev
) * size
);
6111 bool id128_is_valid(const char *s
) {
6117 /* Simple formatted 128bit hex string */
6119 for (i
= 0; i
< l
; i
++) {
6122 if (!(c
>= '0' && c
<= '9') &&
6123 !(c
>= 'a' && c
<= 'z') &&
6124 !(c
>= 'A' && c
<= 'Z'))
6128 } else if (l
== 36) {
6130 /* Formatted UUID */
6132 for (i
= 0; i
< l
; i
++) {
6135 if ((i
== 8 || i
== 13 || i
== 18 || i
== 23)) {
6139 if (!(c
>= '0' && c
<= '9') &&
6140 !(c
>= 'a' && c
<= 'z') &&
6141 !(c
>= 'A' && c
<= 'Z'))
6152 int split_pair(const char *s
, const char *sep
, char **l
, char **r
) {
6167 a
= strndup(s
, x
- s
);
6171 b
= strdup(x
+ strlen(sep
));
6183 int shall_restore_state(void) {
6184 _cleanup_free_
char *value
= NULL
;
6187 r
= get_proc_cmdline_key("systemd.restore_state=", &value
);
6193 return parse_boolean(value
) != 0;
6196 int proc_cmdline(char **ret
) {
6199 if (detect_container(NULL
) > 0)
6200 return get_process_cmdline(1, 0, false, ret
);
6202 return read_one_line_file("/proc/cmdline", ret
);
6205 int parse_proc_cmdline(int (*parse_item
)(const char *key
, const char *value
)) {
6206 _cleanup_free_
char *line
= NULL
;
6212 r
= proc_cmdline(&line
);
6218 _cleanup_free_
char *word
= NULL
;
6221 r
= unquote_first_word(&p
, &word
, UNQUOTE_RELAX
);
6227 /* Filter out arguments that are intended only for the
6229 if (!in_initrd() && startswith(word
, "rd."))
6232 value
= strchr(word
, '=');
6236 r
= parse_item(word
, value
);
6244 int get_proc_cmdline_key(const char *key
, char **value
) {
6245 _cleanup_free_
char *line
= NULL
, *ret
= NULL
;
6252 r
= proc_cmdline(&line
);
6258 _cleanup_free_
char *word
= NULL
;
6261 r
= unquote_first_word(&p
, &word
, UNQUOTE_RELAX
);
6267 /* Filter out arguments that are intended only for the
6269 if (!in_initrd() && startswith(word
, "rd."))
6273 e
= startswith(word
, key
);
6277 r
= free_and_strdup(&ret
, e
);
6283 if (streq(word
, key
))
6297 int container_get_leader(const char *machine
, pid_t
*pid
) {
6298 _cleanup_free_
char *s
= NULL
, *class = NULL
;
6306 p
= strjoina("/run/systemd/machines/", machine
);
6307 r
= parse_env_file(p
, NEWLINE
, "LEADER", &s
, "CLASS", &class, NULL
);
6315 if (!streq_ptr(class, "container"))
6318 r
= parse_pid(s
, &leader
);
6328 int namespace_open(pid_t pid
, int *pidns_fd
, int *mntns_fd
, int *netns_fd
, int *root_fd
) {
6329 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, netnsfd
= -1;
6337 mntns
= procfs_file_alloca(pid
, "ns/mnt");
6338 mntnsfd
= open(mntns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
6346 pidns
= procfs_file_alloca(pid
, "ns/pid");
6347 pidnsfd
= open(pidns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
6355 netns
= procfs_file_alloca(pid
, "ns/net");
6356 netnsfd
= open(netns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
6364 root
= procfs_file_alloca(pid
, "root");
6365 rfd
= open(root
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
|O_DIRECTORY
);
6371 *pidns_fd
= pidnsfd
;
6374 *mntns_fd
= mntnsfd
;
6377 *netns_fd
= netnsfd
;
6382 pidnsfd
= mntnsfd
= netnsfd
= -1;
6387 int namespace_enter(int pidns_fd
, int mntns_fd
, int netns_fd
, int root_fd
) {
6390 if (setns(pidns_fd
, CLONE_NEWPID
) < 0)
6394 if (setns(mntns_fd
, CLONE_NEWNS
) < 0)
6398 if (setns(netns_fd
, CLONE_NEWNET
) < 0)
6402 if (fchdir(root_fd
) < 0)
6405 if (chroot(".") < 0)
6409 if (setresgid(0, 0, 0) < 0)
6412 if (setgroups(0, NULL
) < 0)
6415 if (setresuid(0, 0, 0) < 0)
6421 bool pid_is_unwaited(pid_t pid
) {
6422 /* Checks whether a PID is still valid at all, including a zombie */
6427 if (kill(pid
, 0) >= 0)
6430 return errno
!= ESRCH
;
6433 bool pid_is_alive(pid_t pid
) {
6436 /* Checks whether a PID is still valid and not a zombie */
6441 r
= get_process_state(pid
);
6442 if (r
== -ENOENT
|| r
== 'Z')
6448 int getpeercred(int fd
, struct ucred
*ucred
) {
6449 socklen_t n
= sizeof(struct ucred
);
6456 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, &u
, &n
);
6460 if (n
!= sizeof(struct ucred
))
6463 /* Check if the data is actually useful and not suppressed due
6464 * to namespacing issues */
6467 if (u
.uid
== UID_INVALID
)
6469 if (u
.gid
== GID_INVALID
)
6476 int getpeersec(int fd
, char **ret
) {
6488 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
6492 if (errno
!= ERANGE
)
6499 r
= getsockopt(fd
, SOL_SOCKET
, SO_PEERSEC
, s
, &n
);
6515 /* This is much like like mkostemp() but is subject to umask(). */
6516 int mkostemp_safe(char *pattern
, int flags
) {
6517 _cleanup_umask_ mode_t u
;
6524 fd
= mkostemp(pattern
, flags
);
6531 int open_tmpfile(const char *path
, int flags
) {
6538 /* Try O_TMPFILE first, if it is supported */
6539 fd
= open(path
, flags
|O_TMPFILE
, S_IRUSR
|S_IWUSR
);
6544 /* Fall back to unguessable name + unlinking */
6545 p
= strjoina(path
, "/systemd-tmp-XXXXXX");
6547 fd
= mkostemp_safe(p
, flags
);
6555 int fd_warn_permissions(const char *path
, int fd
) {
6558 if (fstat(fd
, &st
) < 0)
6561 if (st
.st_mode
& 0111)
6562 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path
);
6564 if (st
.st_mode
& 0002)
6565 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path
);
6567 if (getpid() == 1 && (st
.st_mode
& 0044) != 0044)
6568 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
);
6573 unsigned long personality_from_string(const char *p
) {
6575 /* Parse a personality specifier. We introduce our own
6576 * identifiers that indicate specific ABIs, rather than just
6577 * hints regarding the register size, since we want to keep
6578 * things open for multiple locally supported ABIs for the
6579 * same register size. We try to reuse the ABI identifiers
6580 * used by libseccomp. */
6582 #if defined(__x86_64__)
6584 if (streq(p
, "x86"))
6587 if (streq(p
, "x86-64"))
6590 #elif defined(__i386__)
6592 if (streq(p
, "x86"))
6596 /* personality(7) documents that 0xffffffffUL is used for
6597 * querying the current personality, hence let's use that here
6598 * as error indicator. */
6599 return 0xffffffffUL
;
6602 const char* personality_to_string(unsigned long p
) {
6604 #if defined(__x86_64__)
6606 if (p
== PER_LINUX32
)
6612 #elif defined(__i386__)
6621 uint64_t physical_memory(void) {
6624 /* We return this as uint64_t in case we are running as 32bit
6625 * process on a 64bit kernel with huge amounts of memory */
6627 mem
= sysconf(_SC_PHYS_PAGES
);
6630 return (uint64_t) mem
* (uint64_t) page_size();
6633 void hexdump(FILE *f
, const void *p
, size_t s
) {
6634 const uint8_t *b
= p
;
6637 assert(s
== 0 || b
);
6642 fprintf(f
, "%04x ", n
);
6644 for (i
= 0; i
< 16; i
++) {
6649 fprintf(f
, "%02x ", b
[i
]);
6657 for (i
= 0; i
< 16; i
++) {
6662 fputc(isprint(b
[i
]) ? (char) b
[i
] : '.', f
);
6676 int update_reboot_param_file(const char *param
) {
6681 r
= write_string_file(REBOOT_PARAM_FILE
, param
);
6683 log_error("Failed to write reboot param to "
6684 REBOOT_PARAM_FILE
": %s", strerror(-r
));
6686 unlink(REBOOT_PARAM_FILE
);
6691 int umount_recursive(const char *prefix
, int flags
) {
6695 /* Try to umount everything recursively below a
6696 * directory. Also, take care of stacked mounts, and keep
6697 * unmounting them until they are gone. */
6700 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
6705 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
6706 if (!proc_self_mountinfo
)
6710 _cleanup_free_
char *path
= NULL
, *p
= NULL
;
6713 k
= fscanf(proc_self_mountinfo
,
6714 "%*s " /* (1) mount id */
6715 "%*s " /* (2) parent id */
6716 "%*s " /* (3) major:minor */
6717 "%*s " /* (4) root */
6718 "%ms " /* (5) mount point */
6719 "%*s" /* (6) mount options */
6720 "%*[^-]" /* (7) optional fields */
6721 "- " /* (8) separator */
6722 "%*s " /* (9) file system type */
6723 "%*s" /* (10) mount source */
6724 "%*s" /* (11) mount options 2 */
6725 "%*[^\n]", /* some rubbish at the end */
6734 p
= cunescape(path
);
6738 if (!path_startswith(p
, prefix
))
6741 if (umount2(p
, flags
) < 0) {
6757 static int get_mount_flags(const char *path
, unsigned long *flags
) {
6760 if (statvfs(path
, &buf
) < 0)
6762 *flags
= buf
.f_flag
;
6766 int bind_remount_recursive(const char *prefix
, bool ro
) {
6767 _cleanup_set_free_free_ Set
*done
= NULL
;
6768 _cleanup_free_
char *cleaned
= NULL
;
6771 /* Recursively remount a directory (and all its submounts)
6772 * read-only or read-write. If the directory is already
6773 * mounted, we reuse the mount and simply mark it
6774 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
6775 * operation). If it isn't we first make it one. Afterwards we
6776 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
6777 * submounts we can access, too. When mounts are stacked on
6778 * the same mount point we only care for each individual
6779 * "top-level" mount on each point, as we cannot
6780 * influence/access the underlying mounts anyway. We do not
6781 * have any effect on future submounts that might get
6782 * propagated, they migt be writable. This includes future
6783 * submounts that have been triggered via autofs. */
6785 cleaned
= strdup(prefix
);
6789 path_kill_slashes(cleaned
);
6791 done
= set_new(&string_hash_ops
);
6796 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
6797 _cleanup_set_free_free_ Set
*todo
= NULL
;
6798 bool top_autofs
= false;
6800 unsigned long orig_flags
;
6802 todo
= set_new(&string_hash_ops
);
6806 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
6807 if (!proc_self_mountinfo
)
6811 _cleanup_free_
char *path
= NULL
, *p
= NULL
, *type
= NULL
;
6814 k
= fscanf(proc_self_mountinfo
,
6815 "%*s " /* (1) mount id */
6816 "%*s " /* (2) parent id */
6817 "%*s " /* (3) major:minor */
6818 "%*s " /* (4) root */
6819 "%ms " /* (5) mount point */
6820 "%*s" /* (6) mount options (superblock) */
6821 "%*[^-]" /* (7) optional fields */
6822 "- " /* (8) separator */
6823 "%ms " /* (9) file system type */
6824 "%*s" /* (10) mount source */
6825 "%*s" /* (11) mount options (bind mount) */
6826 "%*[^\n]", /* some rubbish at the end */
6836 p
= cunescape(path
);
6840 /* Let's ignore autofs mounts. If they aren't
6841 * triggered yet, we want to avoid triggering
6842 * them, as we don't make any guarantees for
6843 * future submounts anyway. If they are
6844 * already triggered, then we will find
6845 * another entry for this. */
6846 if (streq(type
, "autofs")) {
6847 top_autofs
= top_autofs
|| path_equal(cleaned
, p
);
6851 if (path_startswith(p
, cleaned
) &&
6852 !set_contains(done
, p
)) {
6854 r
= set_consume(todo
, p
);
6864 /* If we have no submounts to process anymore and if
6865 * the root is either already done, or an autofs, we
6867 if (set_isempty(todo
) &&
6868 (top_autofs
|| set_contains(done
, cleaned
)))
6871 if (!set_contains(done
, cleaned
) &&
6872 !set_contains(todo
, cleaned
)) {
6873 /* The prefix directory itself is not yet a
6874 * mount, make it one. */
6875 if (mount(cleaned
, cleaned
, NULL
, MS_BIND
|MS_REC
, NULL
) < 0)
6879 (void) get_mount_flags(cleaned
, &orig_flags
);
6880 orig_flags
&= ~MS_RDONLY
;
6882 if (mount(NULL
, prefix
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0)
6885 x
= strdup(cleaned
);
6889 r
= set_consume(done
, x
);
6894 while ((x
= set_steal_first(todo
))) {
6896 r
= set_consume(done
, x
);
6902 /* Try to reuse the original flag set, but
6903 * don't care for errors, in case of
6904 * obstructed mounts */
6906 (void) get_mount_flags(x
, &orig_flags
);
6907 orig_flags
&= ~MS_RDONLY
;
6909 if (mount(NULL
, x
, NULL
, orig_flags
|MS_BIND
|MS_REMOUNT
|(ro
? MS_RDONLY
: 0), NULL
) < 0) {
6911 /* Deal with mount points that are
6912 * obstructed by a later mount */
6914 if (errno
!= ENOENT
)
6922 int fflush_and_check(FILE *f
) {
6929 return errno
? -errno
: -EIO
;
6934 int tempfn_xxxxxx(const char *p
, char **ret
) {
6946 * /foo/bar/.#waldoXXXXXX
6950 if (!filename_is_valid(fn
))
6953 t
= new(char, strlen(p
) + 2 + 6 + 1);
6957 strcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), fn
), "XXXXXX");
6959 *ret
= path_kill_slashes(t
);
6963 int tempfn_random(const char *p
, char **ret
) {
6977 * /foo/bar/.#waldobaa2a261115984a9
6981 if (!filename_is_valid(fn
))
6984 t
= new(char, strlen(p
) + 2 + 16 + 1);
6988 x
= stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), fn
);
6991 for (i
= 0; i
< 16; i
++) {
6992 *(x
++) = hexchar(u
& 0xF);
6998 *ret
= path_kill_slashes(t
);
7002 int tempfn_random_child(const char *p
, char **ret
) {
7013 * /foo/bar/waldo/.#3c2b6219aa75d7d0
7016 t
= new(char, strlen(p
) + 3 + 16 + 1);
7020 x
= stpcpy(stpcpy(t
, p
), "/.#");
7023 for (i
= 0; i
< 16; i
++) {
7024 *(x
++) = hexchar(u
& 0xF);
7030 *ret
= path_kill_slashes(t
);
7034 /* make sure the hostname is not "localhost" */
7035 bool is_localhost(const char *hostname
) {
7038 /* This tries to identify local host and domain names
7039 * described in RFC6761 plus the redhatism of .localdomain */
7041 return streq(hostname
, "localhost") ||
7042 streq(hostname
, "localhost.") ||
7043 streq(hostname
, "localdomain.") ||
7044 streq(hostname
, "localdomain") ||
7045 endswith(hostname
, ".localhost") ||
7046 endswith(hostname
, ".localhost.") ||
7047 endswith(hostname
, ".localdomain") ||
7048 endswith(hostname
, ".localdomain.");
7051 int take_password_lock(const char *root
) {
7053 struct flock flock
= {
7055 .l_whence
= SEEK_SET
,
7063 /* This is roughly the same as lckpwdf(), but not as awful. We
7064 * don't want to use alarm() and signals, hence we implement
7065 * our own trivial version of this.
7067 * Note that shadow-utils also takes per-database locks in
7068 * addition to lckpwdf(). However, we don't given that they
7069 * are redundant as they they invoke lckpwdf() first and keep
7070 * it during everything they do. The per-database locks are
7071 * awfully racy, and thus we just won't do them. */
7074 path
= strjoina(root
, "/etc/.pwd.lock");
7076 path
= "/etc/.pwd.lock";
7078 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
7082 r
= fcntl(fd
, F_SETLKW
, &flock
);
7091 int is_symlink(const char *path
) {
7094 if (lstat(path
, &info
) < 0)
7097 return !!S_ISLNK(info
.st_mode
);
7100 int is_dir(const char* path
, bool follow
) {
7105 r
= stat(path
, &st
);
7107 r
= lstat(path
, &st
);
7111 return !!S_ISDIR(st
.st_mode
);
7114 int unquote_first_word(const char **p
, char **ret
, UnquoteFlags flags
) {
7115 _cleanup_free_
char *s
= NULL
;
7116 size_t allocated
= 0, sz
= 0;
7124 SINGLE_QUOTE_ESCAPE
,
7126 DOUBLE_QUOTE_ESCAPE
,
7134 /* Parses the first word of a string, and returns it in
7135 * *ret. Removes all quotes in the process. When parsing fails
7136 * (because of an uneven number of quotes or similar), leaves
7137 * the pointer *p at the first invalid character. */
7147 else if (strchr(WHITESPACE
, c
))
7157 state
= SINGLE_QUOTE
;
7159 state
= VALUE_ESCAPE
;
7161 state
= DOUBLE_QUOTE
;
7162 else if (strchr(WHITESPACE
, c
))
7165 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
7175 if (flags
& UNQUOTE_RELAX
)
7180 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
7183 if (flags
& UNQUOTE_CUNESCAPE
) {
7184 r
= cunescape_one(*p
, (size_t) -1, &c
);
7198 if (flags
& UNQUOTE_RELAX
)
7201 } else if (c
== '\'')
7204 state
= SINGLE_QUOTE_ESCAPE
;
7206 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
7214 case SINGLE_QUOTE_ESCAPE
:
7216 if (flags
& UNQUOTE_RELAX
)
7221 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
7224 if (flags
& UNQUOTE_CUNESCAPE
) {
7225 r
= cunescape_one(*p
, (size_t) -1, &c
);
7233 state
= SINGLE_QUOTE
;
7242 state
= DOUBLE_QUOTE_ESCAPE
;
7244 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
7252 case DOUBLE_QUOTE_ESCAPE
:
7254 if (flags
& UNQUOTE_RELAX
)
7259 if (!GREEDY_REALLOC(s
, allocated
, sz
+2))
7262 if (flags
& UNQUOTE_CUNESCAPE
) {
7263 r
= cunescape_one(*p
, (size_t) -1, &c
);
7271 state
= DOUBLE_QUOTE
;
7277 if (!strchr(WHITESPACE
, c
))
7299 int unquote_many_words(const char **p
, UnquoteFlags flags
, ...) {
7304 /* Parses a number of words from a string, stripping any
7305 * quotes if necessary. */
7309 /* Count how many words are expected */
7310 va_start(ap
, flags
);
7312 if (!va_arg(ap
, char **))
7321 /* Read all words into a temporary array */
7322 l
= newa0(char*, n
);
7323 for (c
= 0; c
< n
; c
++) {
7325 r
= unquote_first_word(p
, &l
[c
], flags
);
7329 for (j
= 0; j
< c
; j
++)
7339 /* If we managed to parse all words, return them in the passed
7341 va_start(ap
, flags
);
7342 for (i
= 0; i
< n
; i
++) {
7345 v
= va_arg(ap
, char **);
7355 int free_and_strdup(char **p
, const char *s
) {
7360 /* Replaces a string pointer with an strdup()ed new string,
7361 * possibly freeing the old one. */
7376 int sethostname_idempotent(const char *s
) {
7378 char buf
[HOST_NAME_MAX
+ 1] = {};
7382 r
= gethostname(buf
, sizeof(buf
));
7389 r
= sethostname(s
, strlen(s
));
7396 int ptsname_malloc(int fd
, char **ret
) {
7409 if (ptsname_r(fd
, c
, l
) == 0) {
7413 if (errno
!= ERANGE
) {
7423 int openpt_in_namespace(pid_t pid
, int flags
) {
7424 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, rootfd
= -1;
7425 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
7427 struct cmsghdr cmsghdr
;
7428 uint8_t buf
[CMSG_SPACE(sizeof(int))];
7430 struct msghdr mh
= {
7431 .msg_control
= &control
,
7432 .msg_controllen
= sizeof(control
),
7434 struct cmsghdr
*cmsg
;
7441 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &rootfd
);
7445 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
7455 pair
[0] = safe_close(pair
[0]);
7457 r
= namespace_enter(pidnsfd
, mntnsfd
, -1, rootfd
);
7459 _exit(EXIT_FAILURE
);
7461 master
= posix_openpt(flags
);
7463 _exit(EXIT_FAILURE
);
7465 cmsg
= CMSG_FIRSTHDR(&mh
);
7466 cmsg
->cmsg_level
= SOL_SOCKET
;
7467 cmsg
->cmsg_type
= SCM_RIGHTS
;
7468 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
7469 memcpy(CMSG_DATA(cmsg
), &master
, sizeof(int));
7471 mh
.msg_controllen
= cmsg
->cmsg_len
;
7473 if (sendmsg(pair
[1], &mh
, MSG_NOSIGNAL
) < 0)
7474 _exit(EXIT_FAILURE
);
7476 _exit(EXIT_SUCCESS
);
7479 pair
[1] = safe_close(pair
[1]);
7481 r
= wait_for_terminate(child
, &si
);
7484 if (si
.si_code
!= CLD_EXITED
|| si
.si_status
!= EXIT_SUCCESS
)
7487 if (recvmsg(pair
[0], &mh
, MSG_NOSIGNAL
|MSG_CMSG_CLOEXEC
) < 0)
7490 for (cmsg
= CMSG_FIRSTHDR(&mh
); cmsg
; cmsg
= CMSG_NXTHDR(&mh
, cmsg
))
7491 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
) {
7495 fds
= (int*) CMSG_DATA(cmsg
);
7496 n_fds
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
7499 close_many(fds
, n_fds
);
7509 ssize_t
fgetxattrat_fake(int dirfd
, const char *filename
, const char *attribute
, void *value
, size_t size
, int flags
) {
7510 _cleanup_close_
int fd
= -1;
7513 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
7515 fd
= openat(dirfd
, filename
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOATIME
|(flags
& AT_SYMLINK_NOFOLLOW
? O_NOFOLLOW
: 0));
7519 l
= fgetxattr(fd
, attribute
, value
, size
);
7526 static int parse_crtime(le64_t le
, usec_t
*usec
) {
7532 if (u
== 0 || u
== (uint64_t) -1)
7539 int fd_getcrtime(int fd
, usec_t
*usec
) {
7546 /* Until Linux gets a real concept of birthtime/creation time,
7547 * let's fake one with xattrs */
7549 n
= fgetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
));
7552 if (n
!= sizeof(le
))
7555 return parse_crtime(le
, usec
);
7558 int fd_getcrtime_at(int dirfd
, const char *name
, usec_t
*usec
, int flags
) {
7562 n
= fgetxattrat_fake(dirfd
, name
, "user.crtime_usec", &le
, sizeof(le
), flags
);
7565 if (n
!= sizeof(le
))
7568 return parse_crtime(le
, usec
);
7571 int path_getcrtime(const char *p
, usec_t
*usec
) {
7578 n
= getxattr(p
, "user.crtime_usec", &le
, sizeof(le
));
7581 if (n
!= sizeof(le
))
7584 return parse_crtime(le
, usec
);
7587 int fd_setcrtime(int fd
, usec_t usec
) {
7593 usec
= now(CLOCK_REALTIME
);
7595 le
= htole64((uint64_t) usec
);
7596 if (fsetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
), 0) < 0)
7602 int same_fd(int a
, int b
) {
7603 struct stat sta
, stb
;
7610 /* Compares two file descriptors. Note that semantics are
7611 * quite different depending on whether we have kcmp() or we
7612 * don't. If we have kcmp() this will only return true for
7613 * dup()ed file descriptors, but not otherwise. If we don't
7614 * have kcmp() this will also return true for two fds of the same
7615 * file, created by separate open() calls. Since we use this
7616 * call mostly for filtering out duplicates in the fd store
7617 * this difference hopefully doesn't matter too much. */
7622 /* Try to use kcmp() if we have it. */
7624 r
= kcmp(pid
, pid
, KCMP_FILE
, a
, b
);
7629 if (errno
!= ENOSYS
)
7632 /* We don't have kcmp(), use fstat() instead. */
7633 if (fstat(a
, &sta
) < 0)
7636 if (fstat(b
, &stb
) < 0)
7639 if ((sta
.st_mode
& S_IFMT
) != (stb
.st_mode
& S_IFMT
))
7642 /* We consider all device fds different, since two device fds
7643 * might refer to quite different device contexts even though
7644 * they share the same inode and backing dev_t. */
7646 if (S_ISCHR(sta
.st_mode
) || S_ISBLK(sta
.st_mode
))
7649 if (sta
.st_dev
!= stb
.st_dev
|| sta
.st_ino
!= stb
.st_ino
)
7652 /* The fds refer to the same inode on disk, let's also check
7653 * if they have the same fd flags. This is useful to
7654 * distuingish the read and write side of a pipe created with
7656 fa
= fcntl(a
, F_GETFL
);
7660 fb
= fcntl(b
, F_GETFL
);
7667 int chattr_fd(int fd
, bool b
, unsigned mask
) {
7668 unsigned old_attr
, new_attr
;
7675 if (ioctl(fd
, FS_IOC_GETFLAGS
, &old_attr
) < 0)
7679 new_attr
= old_attr
| mask
;
7681 new_attr
= old_attr
& ~mask
;
7683 if (new_attr
== old_attr
)
7686 if (ioctl(fd
, FS_IOC_SETFLAGS
, &new_attr
) < 0)
7692 int chattr_path(const char *p
, bool b
, unsigned mask
) {
7693 _cleanup_close_
int fd
= -1;
7700 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
7704 return chattr_fd(fd
, b
, mask
);
7707 int change_attr_fd(int fd
, unsigned value
, unsigned mask
) {
7708 unsigned old_attr
, new_attr
;
7715 if (ioctl(fd
, FS_IOC_GETFLAGS
, &old_attr
) < 0)
7718 new_attr
= (old_attr
& ~mask
) |(value
& mask
);
7720 if (new_attr
== old_attr
)
7723 if (ioctl(fd
, FS_IOC_SETFLAGS
, &new_attr
) < 0)
7729 int read_attr_fd(int fd
, unsigned *ret
) {
7732 if (ioctl(fd
, FS_IOC_GETFLAGS
, ret
) < 0)
7738 int read_attr_path(const char *p
, unsigned *ret
) {
7739 _cleanup_close_
int fd
= -1;
7744 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
7748 return read_attr_fd(fd
, ret
);
7751 int make_lock_file(const char *p
, int operation
, LockFile
*ret
) {
7752 _cleanup_close_
int fd
= -1;
7753 _cleanup_free_
char *t
= NULL
;
7757 * We use UNPOSIX locks if they are available. They have nice
7758 * semantics, and are mostly compatible with NFS. However,
7759 * they are only available on new kernels. When we detect we
7760 * are running on an older kernel, then we fall back to good
7761 * old BSD locks. They also have nice semantics, but are
7762 * slightly problematic on NFS, where they are upgraded to
7763 * POSIX locks, even though locally they are orthogonal to
7773 .l_type
= (operation
& ~LOCK_NB
) == LOCK_EX
? F_WRLCK
: F_RDLCK
,
7774 .l_whence
= SEEK_SET
,
7778 fd
= open(p
, O_CREAT
|O_RDWR
|O_NOFOLLOW
|O_CLOEXEC
|O_NOCTTY
, 0600);
7782 r
= fcntl(fd
, (operation
& LOCK_NB
) ? F_OFD_SETLK
: F_OFD_SETLKW
, &fl
);
7785 /* If the kernel is too old, use good old BSD locks */
7786 if (errno
== EINVAL
)
7787 r
= flock(fd
, operation
);
7790 return errno
== EAGAIN
? -EBUSY
: -errno
;
7793 /* If we acquired the lock, let's check if the file
7794 * still exists in the file system. If not, then the
7795 * previous exclusive owner removed it and then closed
7796 * it. In such a case our acquired lock is worthless,
7797 * hence try again. */
7802 if (st
.st_nlink
> 0)
7805 fd
= safe_close(fd
);
7810 ret
->operation
= operation
;
7818 int make_lock_file_for(const char *p
, int operation
, LockFile
*ret
) {
7826 if (!filename_is_valid(fn
))
7829 t
= newa(char, strlen(p
) + 2 + 4 + 1);
7830 stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), fn
), ".lck");
7832 return make_lock_file(t
, operation
, ret
);
7835 void release_lock_file(LockFile
*f
) {
7843 /* If we are the exclusive owner we can safely delete
7844 * the lock file itself. If we are not the exclusive
7845 * owner, we can try becoming it. */
7848 (f
->operation
& ~LOCK_NB
) == LOCK_SH
) {
7849 static const struct flock fl
= {
7851 .l_whence
= SEEK_SET
,
7854 r
= fcntl(f
->fd
, F_OFD_SETLK
, &fl
);
7855 if (r
< 0 && errno
== EINVAL
)
7856 r
= flock(f
->fd
, LOCK_EX
|LOCK_NB
);
7859 f
->operation
= LOCK_EX
|LOCK_NB
;
7862 if ((f
->operation
& ~LOCK_NB
) == LOCK_EX
)
7863 unlink_noerrno(f
->path
);
7869 f
->fd
= safe_close(f
->fd
);
7873 static size_t nul_length(const uint8_t *p
, size_t sz
) {
7888 ssize_t
sparse_write(int fd
, const void *p
, size_t sz
, size_t run_length
) {
7889 const uint8_t *q
, *w
, *e
;
7897 n
= nul_length(q
, e
- q
);
7899 /* If there are more than the specified run length of
7900 * NUL bytes, or if this is the beginning or the end
7901 * of the buffer, then seek instead of write */
7902 if ((n
> run_length
) ||
7903 (n
> 0 && q
== p
) ||
7904 (n
> 0 && q
+ n
>= e
)) {
7906 l
= write(fd
, w
, q
- w
);
7913 if (lseek(fd
, n
, SEEK_CUR
) == (off_t
) -1)
7925 l
= write(fd
, w
, q
- w
);
7932 return q
- (const uint8_t*) p
;
7935 void sigkill_wait(pid_t
*pid
) {
7941 if (kill(*pid
, SIGKILL
) > 0)
7942 (void) wait_for_terminate(*pid
, NULL
);
7945 int syslog_parse_priority(const char **p
, int *priority
, bool with_facility
) {
7946 int a
= 0, b
= 0, c
= 0;
7956 if (!strchr(*p
, '>'))
7959 if ((*p
)[2] == '>') {
7960 c
= undecchar((*p
)[1]);
7962 } else if ((*p
)[3] == '>') {
7963 b
= undecchar((*p
)[1]);
7964 c
= undecchar((*p
)[2]);
7966 } else if ((*p
)[4] == '>') {
7967 a
= undecchar((*p
)[1]);
7968 b
= undecchar((*p
)[2]);
7969 c
= undecchar((*p
)[3]);
7974 if (a
< 0 || b
< 0 || c
< 0 ||
7975 (!with_facility
&& (a
|| b
|| c
> 7)))
7979 *priority
= a
*100 + b
*10 + c
;
7981 *priority
= (*priority
& LOG_FACMASK
) | c
;
7987 ssize_t
string_table_lookup(const char * const *table
, size_t len
, const char *key
) {
7993 for (i
= 0; i
< len
; ++i
)
7994 if (streq_ptr(table
[i
], key
))
8000 void cmsg_close_all(struct msghdr
*mh
) {
8001 struct cmsghdr
*cmsg
;
8005 for (cmsg
= CMSG_FIRSTHDR(mh
); cmsg
; cmsg
= CMSG_NXTHDR(mh
, cmsg
))
8006 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
)
8007 close_many((int*) CMSG_DATA(cmsg
), (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int));
8010 int rename_noreplace(int olddirfd
, const char *oldpath
, int newdirfd
, const char *newpath
) {
8014 ret
= renameat2(olddirfd
, oldpath
, newdirfd
, newpath
, RENAME_NOREPLACE
);
8018 /* Even though renameat2() exists since Linux 3.15, btrfs added
8019 * support for it later. If it is not implemented, fallback to another
8021 if (errno
!= EINVAL
)
8024 /* The link()/unlink() fallback does not work on directories. But
8025 * renameat() without RENAME_NOREPLACE gives the same semantics on
8026 * directories, except when newpath is an *empty* directory. This is
8028 ret
= fstatat(olddirfd
, oldpath
, &buf
, AT_SYMLINK_NOFOLLOW
);
8029 if (ret
>= 0 && S_ISDIR(buf
.st_mode
)) {
8030 ret
= renameat(olddirfd
, oldpath
, newdirfd
, newpath
);
8031 return ret
>= 0 ? 0 : -errno
;
8034 /* If it is not a directory, use the link()/unlink() fallback. */
8035 ret
= linkat(olddirfd
, oldpath
, newdirfd
, newpath
, 0);
8039 ret
= unlinkat(olddirfd
, oldpath
, 0);
8041 /* backup errno before the following unlinkat() alters it */
8043 (void) unlinkat(newdirfd
, newpath
, 0);