1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <linux/magic.h>
32 #include <linux/oom.h>
33 #include <linux/sched.h>
44 #include <sys/ioctl.h>
46 #include <sys/mount.h>
47 #include <sys/personality.h>
48 #include <sys/prctl.h>
50 #include <sys/statvfs.h>
52 #include <sys/types.h>
53 #include <sys/utsname.h>
56 #include <sys/xattr.h>
60 /* When we include libgen.h because we need dirname() we immediately
61 * undefine basename() since libgen.h defines it as a macro to the
62 * POSIX version which is really broken. We prefer GNU basename(). */
66 #ifdef HAVE_SYS_AUXV_H
70 /* We include linux/fs.h as last of the system headers, as it
71 * otherwise conflicts with sys/mount.h. Yay, Linux is great! */
76 #include "device-nodes.h"
79 #include "exit-status.h"
82 #include "formats-util.h"
85 #include "hostname-util.h"
91 #include "hexdecoct.h"
92 #include "parse-util.h"
93 #include "path-util.h"
94 #include "process-util.h"
95 #include "random-util.h"
96 #include "signal-util.h"
97 #include "sparse-endian.h"
98 #include "string-util.h"
100 #include "terminal-util.h"
101 #include "user-util.h"
105 #include "dirent-util.h"
107 /* Put this test here for a lack of better place */
108 assert_cc(EAGAIN
== EWOULDBLOCK
);
111 char **saved_argv
= NULL
;
113 size_t page_size(void) {
114 static thread_local
size_t pgsz
= 0;
117 if (_likely_(pgsz
> 0))
120 r
= sysconf(_SC_PAGESIZE
);
127 int unlink_noerrno(const char *path
) {
138 int fchmod_umask(int fd
, mode_t m
) {
143 r
= fchmod(fd
, m
& (~u
)) < 0 ? -errno
: 0;
149 int readlinkat_malloc(int fd
, const char *p
, char **ret
) {
164 n
= readlinkat(fd
, p
, c
, l
-1);
171 if ((size_t) n
< l
-1) {
182 int readlink_malloc(const char *p
, char **ret
) {
183 return readlinkat_malloc(AT_FDCWD
, p
, ret
);
186 int readlink_value(const char *p
, char **ret
) {
187 _cleanup_free_
char *link
= NULL
;
191 r
= readlink_malloc(p
, &link
);
195 value
= basename(link
);
199 value
= strdup(value
);
208 int readlink_and_make_absolute(const char *p
, char **r
) {
209 _cleanup_free_
char *target
= NULL
;
216 j
= readlink_malloc(p
, &target
);
220 k
= file_in_same_dir(p
, target
);
228 int readlink_and_canonicalize(const char *p
, char **r
) {
235 j
= readlink_and_make_absolute(p
, &t
);
239 s
= canonicalize_file_name(t
);
246 path_kill_slashes(*r
);
251 int rmdir_parents(const char *path
, const char *stop
) {
260 /* Skip trailing slashes */
261 while (l
> 0 && path
[l
-1] == '/')
267 /* Skip last component */
268 while (l
> 0 && path
[l
-1] != '/')
271 /* Skip trailing slashes */
272 while (l
> 0 && path
[l
-1] == '/')
278 if (!(t
= strndup(path
, l
)))
281 if (path_startswith(stop
, t
)) {
297 bool fstype_is_network(const char *fstype
) {
298 static const char table
[] =
313 x
= startswith(fstype
, "fuse.");
317 return nulstr_contains(table
, fstype
);
320 int dir_is_empty(const char *path
) {
321 _cleanup_closedir_
DIR *d
;
328 FOREACH_DIRENT(de
, d
, return -errno
)
334 void rename_process(const char name
[8]) {
337 /* This is a like a poor man's setproctitle(). It changes the
338 * comm field, argv[0], and also the glibc's internally used
339 * name of the process. For the first one a limit of 16 chars
340 * applies, to the second one usually one of 10 (i.e. length
341 * of "/sbin/init"), to the third one one of 7 (i.e. length of
342 * "systemd"). If you pass a longer string it will be
345 prctl(PR_SET_NAME
, name
);
347 if (program_invocation_name
)
348 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
350 if (saved_argc
> 0) {
354 strncpy(saved_argv
[0], name
, strlen(saved_argv
[0]));
356 for (i
= 1; i
< saved_argc
; i
++) {
360 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
365 bool is_fs_type(const struct statfs
*s
, statfs_f_type_t magic_value
) {
367 assert_cc(sizeof(statfs_f_type_t
) >= sizeof(s
->f_type
));
369 return F_TYPE_EQUAL(s
->f_type
, magic_value
);
372 int fd_check_fstype(int fd
, statfs_f_type_t magic_value
) {
375 if (fstatfs(fd
, &s
) < 0)
378 return is_fs_type(&s
, magic_value
);
381 int path_check_fstype(const char *path
, statfs_f_type_t magic_value
) {
382 _cleanup_close_
int fd
= -1;
384 fd
= open(path
, O_RDONLY
);
388 return fd_check_fstype(fd
, magic_value
);
391 bool is_temporary_fs(const struct statfs
*s
) {
392 return is_fs_type(s
, TMPFS_MAGIC
) ||
393 is_fs_type(s
, RAMFS_MAGIC
);
396 int fd_is_temporary_fs(int fd
) {
399 if (fstatfs(fd
, &s
) < 0)
402 return is_temporary_fs(&s
);
405 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
408 /* Under the assumption that we are running privileged we
409 * first change the access mode and only then hand out
410 * ownership to avoid a window where access is too open. */
412 if (mode
!= MODE_INVALID
)
413 if (chmod(path
, mode
) < 0)
416 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
417 if (chown(path
, uid
, gid
) < 0)
423 int fchmod_and_fchown(int fd
, mode_t mode
, uid_t uid
, gid_t gid
) {
426 /* Under the assumption that we are running privileged we
427 * first change the access mode and only then hand out
428 * ownership to avoid a window where access is too open. */
430 if (mode
!= MODE_INVALID
)
431 if (fchmod(fd
, mode
) < 0)
434 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
435 if (fchown(fd
, uid
, gid
) < 0)
441 int files_same(const char *filea
, const char *fileb
) {
444 if (stat(filea
, &a
) < 0)
447 if (stat(fileb
, &b
) < 0)
450 return a
.st_dev
== b
.st_dev
&&
451 a
.st_ino
== b
.st_ino
;
454 int running_in_chroot(void) {
457 ret
= files_same("/proc/1/root", "/");
464 int touch_file(const char *path
, bool parents
, usec_t stamp
, uid_t uid
, gid_t gid
, mode_t mode
) {
465 _cleanup_close_
int fd
;
471 mkdir_parents(path
, 0755);
473 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, mode
> 0 ? mode
: 0644);
478 r
= fchmod(fd
, mode
);
483 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
) {
484 r
= fchown(fd
, uid
, gid
);
489 if (stamp
!= USEC_INFINITY
) {
490 struct timespec ts
[2];
492 timespec_store(&ts
[0], stamp
);
494 r
= futimens(fd
, ts
);
496 r
= futimens(fd
, NULL
);
503 int touch(const char *path
) {
504 return touch_file(path
, false, USEC_INFINITY
, UID_INVALID
, GID_INVALID
, 0);
507 noreturn
void freeze(void) {
509 /* Make sure nobody waits for us on a socket anymore */
510 close_all_fds(NULL
, 0);
518 bool null_or_empty(struct stat
*st
) {
521 if (S_ISREG(st
->st_mode
) && st
->st_size
<= 0)
524 if (S_ISCHR(st
->st_mode
) || S_ISBLK(st
->st_mode
))
530 int null_or_empty_path(const char *fn
) {
535 if (stat(fn
, &st
) < 0)
538 return null_or_empty(&st
);
541 int null_or_empty_fd(int fd
) {
546 if (fstat(fd
, &st
) < 0)
549 return null_or_empty(&st
);
552 static int do_execute(char **directories
, usec_t timeout
, char *argv
[]) {
553 _cleanup_hashmap_free_free_ Hashmap
*pids
= NULL
;
554 _cleanup_set_free_free_ Set
*seen
= NULL
;
557 /* We fork this all off from a child process so that we can
558 * somewhat cleanly make use of SIGALRM to set a time limit */
560 (void) reset_all_signal_handlers();
561 (void) reset_signal_mask();
563 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
565 pids
= hashmap_new(NULL
);
569 seen
= set_new(&string_hash_ops
);
573 STRV_FOREACH(directory
, directories
) {
574 _cleanup_closedir_
DIR *d
;
577 d
= opendir(*directory
);
582 return log_error_errno(errno
, "Failed to open directory %s: %m", *directory
);
585 FOREACH_DIRENT(de
, d
, break) {
586 _cleanup_free_
char *path
= NULL
;
590 if (!dirent_is_file(de
))
593 if (set_contains(seen
, de
->d_name
)) {
594 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory
, de
->d_name
);
598 r
= set_put_strdup(seen
, de
->d_name
);
602 path
= strjoin(*directory
, "/", de
->d_name
, NULL
);
606 if (null_or_empty_path(path
)) {
607 log_debug("%s is empty (a mask).", path
);
613 log_error_errno(errno
, "Failed to fork: %m");
615 } else if (pid
== 0) {
618 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
628 return log_error_errno(errno
, "Failed to execute %s: %m", path
);
631 log_debug("Spawned %s as " PID_FMT
".", path
, pid
);
633 r
= hashmap_put(pids
, UINT_TO_PTR(pid
), path
);
640 /* Abort execution of this process after the timout. We simply
641 * rely on SIGALRM as default action terminating the process,
642 * and turn on alarm(). */
644 if (timeout
!= USEC_INFINITY
)
645 alarm((timeout
+ USEC_PER_SEC
- 1) / USEC_PER_SEC
);
647 while (!hashmap_isempty(pids
)) {
648 _cleanup_free_
char *path
= NULL
;
651 pid
= PTR_TO_UINT(hashmap_first_key(pids
));
654 path
= hashmap_remove(pids
, UINT_TO_PTR(pid
));
657 wait_for_terminate_and_warn(path
, pid
, true);
663 void execute_directories(const char* const* directories
, usec_t timeout
, char *argv
[]) {
667 char **dirs
= (char**) directories
;
669 assert(!strv_isempty(dirs
));
671 name
= basename(dirs
[0]);
672 assert(!isempty(name
));
674 /* Executes all binaries in the directories in parallel and waits
675 * for them to finish. Optionally a timeout is applied. If a file
676 * with the same name exists in more than one directory, the
677 * earliest one wins. */
679 executor_pid
= fork();
680 if (executor_pid
< 0) {
681 log_error_errno(errno
, "Failed to fork: %m");
684 } else if (executor_pid
== 0) {
685 r
= do_execute(dirs
, timeout
, argv
);
686 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
689 wait_for_terminate_and_warn(name
, executor_pid
, true);
692 bool plymouth_running(void) {
693 return access("/run/plymouth/pid", F_OK
) >= 0;
696 int symlink_atomic(const char *from
, const char *to
) {
697 _cleanup_free_
char *t
= NULL
;
703 r
= tempfn_random(to
, NULL
, &t
);
707 if (symlink(from
, t
) < 0)
710 if (rename(t
, to
) < 0) {
718 int symlink_idempotent(const char *from
, const char *to
) {
719 _cleanup_free_
char *p
= NULL
;
725 if (symlink(from
, to
) < 0) {
729 r
= readlink_malloc(to
, &p
);
740 int mknod_atomic(const char *path
, mode_t mode
, dev_t dev
) {
741 _cleanup_free_
char *t
= NULL
;
746 r
= tempfn_random(path
, NULL
, &t
);
750 if (mknod(t
, mode
, dev
) < 0)
753 if (rename(t
, path
) < 0) {
761 int mkfifo_atomic(const char *path
, mode_t mode
) {
762 _cleanup_free_
char *t
= NULL
;
767 r
= tempfn_random(path
, NULL
, &t
);
771 if (mkfifo(t
, mode
) < 0)
774 if (rename(t
, path
) < 0) {
782 bool display_is_local(const char *display
) {
791 int socket_from_display(const char *display
, char **path
) {
798 if (!display_is_local(display
))
801 k
= strspn(display
+1, "0123456789");
803 f
= new(char, strlen("/tmp/.X11-unix/X") + k
+ 1);
807 c
= stpcpy(f
, "/tmp/.X11-unix/X");
808 memcpy(c
, display
+1, k
);
816 int glob_exists(const char *path
) {
817 _cleanup_globfree_ glob_t g
= {};
823 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
825 if (k
== GLOB_NOMATCH
)
827 else if (k
== GLOB_NOSPACE
)
830 return !strv_isempty(g
.gl_pathv
);
832 return errno
? -errno
: -EIO
;
835 int glob_extend(char ***strv
, const char *path
) {
836 _cleanup_globfree_ glob_t g
= {};
841 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
843 if (k
== GLOB_NOMATCH
)
845 else if (k
== GLOB_NOSPACE
)
847 else if (k
!= 0 || strv_isempty(g
.gl_pathv
))
848 return errno
? -errno
: -EIO
;
850 STRV_FOREACH(p
, g
.gl_pathv
) {
851 k
= strv_extend(strv
, *p
);
859 int get_files_in_directory(const char *path
, char ***list
) {
860 _cleanup_closedir_
DIR *d
= NULL
;
861 size_t bufsize
= 0, n
= 0;
862 _cleanup_strv_free_
char **l
= NULL
;
866 /* Returns all files in a directory in *list, and the number
867 * of files as return value. If list is NULL returns only the
879 if (!de
&& errno
!= 0)
884 dirent_ensure_type(d
, de
);
886 if (!dirent_is_file(de
))
890 /* one extra slot is needed for the terminating NULL */
891 if (!GREEDY_REALLOC(l
, bufsize
, n
+ 2))
894 l
[n
] = strdup(de
->d_name
);
905 l
= NULL
; /* avoid freeing */
911 bool is_main_thread(void) {
912 static thread_local
int cached
= 0;
914 if (_unlikely_(cached
== 0))
915 cached
= getpid() == gettid() ? 1 : -1;
920 int block_get_whole_disk(dev_t d
, dev_t
*ret
) {
927 /* If it has a queue this is good enough for us */
928 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", major(d
), minor(d
)) < 0)
939 /* If it is a partition find the originating device */
940 if (asprintf(&p
, "/sys/dev/block/%u:%u/partition", major(d
), minor(d
)) < 0)
949 /* Get parent dev_t */
950 if (asprintf(&p
, "/sys/dev/block/%u:%u/../dev", major(d
), minor(d
)) < 0)
953 r
= read_one_line_file(p
, &s
);
959 r
= sscanf(s
, "%u:%u", &m
, &n
);
965 /* Only return this if it is really good enough for us. */
966 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", m
, n
) < 0)
973 *ret
= makedev(m
, n
);
980 static const char *const ioprio_class_table
[] = {
981 [IOPRIO_CLASS_NONE
] = "none",
982 [IOPRIO_CLASS_RT
] = "realtime",
983 [IOPRIO_CLASS_BE
] = "best-effort",
984 [IOPRIO_CLASS_IDLE
] = "idle"
987 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, INT_MAX
);
989 static const char *const sigchld_code_table
[] = {
990 [CLD_EXITED
] = "exited",
991 [CLD_KILLED
] = "killed",
992 [CLD_DUMPED
] = "dumped",
993 [CLD_TRAPPED
] = "trapped",
994 [CLD_STOPPED
] = "stopped",
995 [CLD_CONTINUED
] = "continued",
998 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
1000 static const char *const log_facility_unshifted_table
[LOG_NFACILITIES
] = {
1001 [LOG_FAC(LOG_KERN
)] = "kern",
1002 [LOG_FAC(LOG_USER
)] = "user",
1003 [LOG_FAC(LOG_MAIL
)] = "mail",
1004 [LOG_FAC(LOG_DAEMON
)] = "daemon",
1005 [LOG_FAC(LOG_AUTH
)] = "auth",
1006 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
1007 [LOG_FAC(LOG_LPR
)] = "lpr",
1008 [LOG_FAC(LOG_NEWS
)] = "news",
1009 [LOG_FAC(LOG_UUCP
)] = "uucp",
1010 [LOG_FAC(LOG_CRON
)] = "cron",
1011 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
1012 [LOG_FAC(LOG_FTP
)] = "ftp",
1013 [LOG_FAC(LOG_LOCAL0
)] = "local0",
1014 [LOG_FAC(LOG_LOCAL1
)] = "local1",
1015 [LOG_FAC(LOG_LOCAL2
)] = "local2",
1016 [LOG_FAC(LOG_LOCAL3
)] = "local3",
1017 [LOG_FAC(LOG_LOCAL4
)] = "local4",
1018 [LOG_FAC(LOG_LOCAL5
)] = "local5",
1019 [LOG_FAC(LOG_LOCAL6
)] = "local6",
1020 [LOG_FAC(LOG_LOCAL7
)] = "local7"
1023 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted
, int, LOG_FAC(~0));
1025 bool log_facility_unshifted_is_valid(int facility
) {
1026 return facility
>= 0 && facility
<= LOG_FAC(~0);
1029 static const char *const log_level_table
[] = {
1030 [LOG_EMERG
] = "emerg",
1031 [LOG_ALERT
] = "alert",
1032 [LOG_CRIT
] = "crit",
1034 [LOG_WARNING
] = "warning",
1035 [LOG_NOTICE
] = "notice",
1036 [LOG_INFO
] = "info",
1037 [LOG_DEBUG
] = "debug"
1040 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level
, int, LOG_DEBUG
);
1042 bool log_level_is_valid(int level
) {
1043 return level
>= 0 && level
<= LOG_DEBUG
;
1046 static const char* const sched_policy_table
[] = {
1047 [SCHED_OTHER
] = "other",
1048 [SCHED_BATCH
] = "batch",
1049 [SCHED_IDLE
] = "idle",
1050 [SCHED_FIFO
] = "fifo",
1054 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);
1056 bool kexec_loaded(void) {
1057 bool loaded
= false;
1060 if (read_one_line_file("/sys/kernel/kexec_loaded", &s
) >= 0) {
1068 int prot_from_flags(int flags
) {
1070 switch (flags
& O_ACCMODE
) {
1079 return PROT_READ
|PROT_WRITE
;
1086 void* memdup(const void *p
, size_t l
) {
1099 int fork_agent(pid_t
*pid
, const int except
[], unsigned n_except
, const char *path
, ...) {
1100 bool stdout_is_tty
, stderr_is_tty
;
1101 pid_t parent_pid
, agent_pid
;
1102 sigset_t ss
, saved_ss
;
1110 /* Spawns a temporary TTY agent, making sure it goes away when
1113 parent_pid
= getpid();
1115 /* First we temporarily block all signals, so that the new
1116 * child has them blocked initially. This way, we can be sure
1117 * that SIGTERMs are not lost we might send to the agent. */
1118 assert_se(sigfillset(&ss
) >= 0);
1119 assert_se(sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) >= 0);
1122 if (agent_pid
< 0) {
1123 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
1127 if (agent_pid
!= 0) {
1128 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
1135 * Make sure the agent goes away when the parent dies */
1136 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
1137 _exit(EXIT_FAILURE
);
1139 /* Make sure we actually can kill the agent, if we need to, in
1140 * case somebody invoked us from a shell script that trapped
1141 * SIGTERM or so... */
1142 (void) reset_all_signal_handlers();
1143 (void) reset_signal_mask();
1145 /* Check whether our parent died before we were able
1146 * to set the death signal and unblock the signals */
1147 if (getppid() != parent_pid
)
1148 _exit(EXIT_SUCCESS
);
1150 /* Don't leak fds to the agent */
1151 close_all_fds(except
, n_except
);
1153 stdout_is_tty
= isatty(STDOUT_FILENO
);
1154 stderr_is_tty
= isatty(STDERR_FILENO
);
1156 if (!stdout_is_tty
|| !stderr_is_tty
) {
1159 /* Detach from stdout/stderr. and reopen
1160 * /dev/tty for them. This is important to
1161 * ensure that when systemctl is started via
1162 * popen() or a similar call that expects to
1163 * read EOF we actually do generate EOF and
1164 * not delay this indefinitely by because we
1165 * keep an unused copy of stdin around. */
1166 fd
= open("/dev/tty", O_WRONLY
);
1168 log_error_errno(errno
, "Failed to open /dev/tty: %m");
1169 _exit(EXIT_FAILURE
);
1173 dup2(fd
, STDOUT_FILENO
);
1176 dup2(fd
, STDERR_FILENO
);
1182 /* Count arguments */
1184 for (n
= 0; va_arg(ap
, char*); n
++)
1189 l
= alloca(sizeof(char *) * (n
+ 1));
1191 /* Fill in arguments */
1193 for (i
= 0; i
<= n
; i
++)
1194 l
[i
] = va_arg(ap
, char*);
1198 _exit(EXIT_FAILURE
);
1201 bool http_etag_is_valid(const char *etag
) {
1205 if (!endswith(etag
, "\""))
1208 if (!startswith(etag
, "\"") && !startswith(etag
, "W/\""))
1214 bool http_url_is_valid(const char *url
) {
1220 p
= startswith(url
, "http://");
1222 p
= startswith(url
, "https://");
1229 return ascii_is_valid(p
);
1232 bool documentation_url_is_valid(const char *url
) {
1238 if (http_url_is_valid(url
))
1241 p
= startswith(url
, "file:/");
1243 p
= startswith(url
, "info:");
1245 p
= startswith(url
, "man:");
1250 return ascii_is_valid(p
);
1253 bool in_initrd(void) {
1254 static int saved
= -1;
1260 /* We make two checks here:
1262 * 1. the flag file /etc/initrd-release must exist
1263 * 2. the root file system must be a memory file system
1265 * The second check is extra paranoia, since misdetecting an
1266 * initrd can have bad bad consequences due the initrd
1267 * emptying when transititioning to the main systemd.
1270 saved
= access("/etc/initrd-release", F_OK
) >= 0 &&
1271 statfs("/", &s
) >= 0 &&
1272 is_temporary_fs(&s
);
1277 bool string_is_safe(const char *p
) {
1283 for (t
= p
; *t
; t
++) {
1284 if (*t
> 0 && *t
< ' ')
1287 if (strchr("\\\"\'\x7f", *t
))
1294 /* hey glibc, APIs with callbacks without a user pointer are so useless */
1295 void *xbsearch_r(const void *key
, const void *base
, size_t nmemb
, size_t size
,
1296 int (*compar
) (const void *, const void *, void *), void *arg
) {
1305 p
= (void *)(((const char *) base
) + (idx
* size
));
1306 comparison
= compar(key
, p
, arg
);
1309 else if (comparison
> 0)
1317 void init_gettext(void) {
1318 setlocale(LC_ALL
, "");
1319 textdomain(GETTEXT_PACKAGE
);
1322 bool is_locale_utf8(void) {
1324 static int cached_answer
= -1;
1326 if (cached_answer
>= 0)
1329 if (!setlocale(LC_ALL
, "")) {
1330 cached_answer
= true;
1334 set
= nl_langinfo(CODESET
);
1336 cached_answer
= true;
1340 if (streq(set
, "UTF-8")) {
1341 cached_answer
= true;
1345 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
1346 * unset and everything can do to UTF-8 nowadays. */
1347 set
= setlocale(LC_CTYPE
, NULL
);
1349 cached_answer
= true;
1353 /* Check result, but ignore the result if C was set
1356 STR_IN_SET(set
, "C", "POSIX") &&
1357 !getenv("LC_ALL") &&
1358 !getenv("LC_CTYPE") &&
1362 return (bool) cached_answer
;
1365 const char *draw_special_char(DrawSpecialChar ch
) {
1366 static const char *draw_table
[2][_DRAW_SPECIAL_CHAR_MAX
] = {
1369 [DRAW_TREE_VERTICAL
] = "\342\224\202 ", /* │ */
1370 [DRAW_TREE_BRANCH
] = "\342\224\234\342\224\200", /* ├─ */
1371 [DRAW_TREE_RIGHT
] = "\342\224\224\342\224\200", /* └─ */
1372 [DRAW_TREE_SPACE
] = " ", /* */
1373 [DRAW_TRIANGULAR_BULLET
] = "\342\200\243", /* ‣ */
1374 [DRAW_BLACK_CIRCLE
] = "\342\227\217", /* ● */
1375 [DRAW_ARROW
] = "\342\206\222", /* → */
1376 [DRAW_DASH
] = "\342\200\223", /* – */
1379 /* ASCII fallback */ {
1380 [DRAW_TREE_VERTICAL
] = "| ",
1381 [DRAW_TREE_BRANCH
] = "|-",
1382 [DRAW_TREE_RIGHT
] = "`-",
1383 [DRAW_TREE_SPACE
] = " ",
1384 [DRAW_TRIANGULAR_BULLET
] = ">",
1385 [DRAW_BLACK_CIRCLE
] = "*",
1386 [DRAW_ARROW
] = "->",
1391 return draw_table
[!is_locale_utf8()][ch
];
1394 int on_ac_power(void) {
1395 bool found_offline
= false, found_online
= false;
1396 _cleanup_closedir_
DIR *d
= NULL
;
1398 d
= opendir("/sys/class/power_supply");
1400 return errno
== ENOENT
? true : -errno
;
1404 _cleanup_close_
int fd
= -1, device
= -1;
1410 if (!de
&& errno
!= 0)
1416 if (hidden_file(de
->d_name
))
1419 device
= openat(dirfd(d
), de
->d_name
, O_DIRECTORY
|O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
1421 if (errno
== ENOENT
|| errno
== ENOTDIR
)
1427 fd
= openat(device
, "type", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
1429 if (errno
== ENOENT
)
1435 n
= read(fd
, contents
, sizeof(contents
));
1439 if (n
!= 6 || memcmp(contents
, "Mains\n", 6))
1443 fd
= openat(device
, "online", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
1445 if (errno
== ENOENT
)
1451 n
= read(fd
, contents
, sizeof(contents
));
1455 if (n
!= 2 || contents
[1] != '\n')
1458 if (contents
[0] == '1') {
1459 found_online
= true;
1461 } else if (contents
[0] == '0')
1462 found_offline
= true;
1467 return found_online
|| !found_offline
;
1470 void* greedy_realloc(void **p
, size_t *allocated
, size_t need
, size_t size
) {
1477 if (*allocated
>= need
)
1480 newalloc
= MAX(need
* 2, 64u / size
);
1481 a
= newalloc
* size
;
1483 /* check for overflows */
1484 if (a
< size
* need
)
1492 *allocated
= newalloc
;
1496 void* greedy_realloc0(void **p
, size_t *allocated
, size_t need
, size_t size
) {
1505 q
= greedy_realloc(p
, allocated
, need
, size
);
1509 if (*allocated
> prev
)
1510 memzero(q
+ prev
* size
, (*allocated
- prev
) * size
);
1515 bool id128_is_valid(const char *s
) {
1521 /* Simple formatted 128bit hex string */
1523 for (i
= 0; i
< l
; i
++) {
1526 if (!(c
>= '0' && c
<= '9') &&
1527 !(c
>= 'a' && c
<= 'z') &&
1528 !(c
>= 'A' && c
<= 'Z'))
1532 } else if (l
== 36) {
1534 /* Formatted UUID */
1536 for (i
= 0; i
< l
; i
++) {
1539 if ((i
== 8 || i
== 13 || i
== 18 || i
== 23)) {
1543 if (!(c
>= '0' && c
<= '9') &&
1544 !(c
>= 'a' && c
<= 'z') &&
1545 !(c
>= 'A' && c
<= 'Z'))
1556 int shall_restore_state(void) {
1557 _cleanup_free_
char *value
= NULL
;
1560 r
= get_proc_cmdline_key("systemd.restore_state=", &value
);
1566 return parse_boolean(value
) != 0;
1569 int proc_cmdline(char **ret
) {
1572 if (detect_container() > 0)
1573 return get_process_cmdline(1, 0, false, ret
);
1575 return read_one_line_file("/proc/cmdline", ret
);
1578 int parse_proc_cmdline(int (*parse_item
)(const char *key
, const char *value
)) {
1579 _cleanup_free_
char *line
= NULL
;
1585 r
= proc_cmdline(&line
);
1591 _cleanup_free_
char *word
= NULL
;
1594 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
1600 /* Filter out arguments that are intended only for the
1602 if (!in_initrd() && startswith(word
, "rd."))
1605 value
= strchr(word
, '=');
1609 r
= parse_item(word
, value
);
1617 int get_proc_cmdline_key(const char *key
, char **value
) {
1618 _cleanup_free_
char *line
= NULL
, *ret
= NULL
;
1625 r
= proc_cmdline(&line
);
1631 _cleanup_free_
char *word
= NULL
;
1634 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
1640 /* Filter out arguments that are intended only for the
1642 if (!in_initrd() && startswith(word
, "rd."))
1646 e
= startswith(word
, key
);
1650 r
= free_and_strdup(&ret
, e
);
1656 if (streq(word
, key
))
1670 int container_get_leader(const char *machine
, pid_t
*pid
) {
1671 _cleanup_free_
char *s
= NULL
, *class = NULL
;
1679 if (!machine_name_is_valid(machine
))
1682 p
= strjoina("/run/systemd/machines/", machine
);
1683 r
= parse_env_file(p
, NEWLINE
, "LEADER", &s
, "CLASS", &class, NULL
);
1691 if (!streq_ptr(class, "container"))
1694 r
= parse_pid(s
, &leader
);
1704 int namespace_open(pid_t pid
, int *pidns_fd
, int *mntns_fd
, int *netns_fd
, int *userns_fd
, int *root_fd
) {
1705 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, netnsfd
= -1, usernsfd
= -1;
1713 mntns
= procfs_file_alloca(pid
, "ns/mnt");
1714 mntnsfd
= open(mntns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
1722 pidns
= procfs_file_alloca(pid
, "ns/pid");
1723 pidnsfd
= open(pidns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
1731 netns
= procfs_file_alloca(pid
, "ns/net");
1732 netnsfd
= open(netns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
1740 userns
= procfs_file_alloca(pid
, "ns/user");
1741 usernsfd
= open(userns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
1742 if (usernsfd
< 0 && errno
!= ENOENT
)
1749 root
= procfs_file_alloca(pid
, "root");
1750 rfd
= open(root
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
|O_DIRECTORY
);
1756 *pidns_fd
= pidnsfd
;
1759 *mntns_fd
= mntnsfd
;
1762 *netns_fd
= netnsfd
;
1765 *userns_fd
= usernsfd
;
1770 pidnsfd
= mntnsfd
= netnsfd
= usernsfd
= -1;
1775 int namespace_enter(int pidns_fd
, int mntns_fd
, int netns_fd
, int userns_fd
, int root_fd
) {
1776 if (userns_fd
>= 0) {
1777 /* Can't setns to your own userns, since then you could
1778 * escalate from non-root to root in your own namespace, so
1779 * check if namespaces equal before attempting to enter. */
1780 _cleanup_free_
char *userns_fd_path
= NULL
;
1782 if (asprintf(&userns_fd_path
, "/proc/self/fd/%d", userns_fd
) < 0)
1785 r
= files_same(userns_fd_path
, "/proc/self/ns/user");
1793 if (setns(pidns_fd
, CLONE_NEWPID
) < 0)
1797 if (setns(mntns_fd
, CLONE_NEWNS
) < 0)
1801 if (setns(netns_fd
, CLONE_NEWNET
) < 0)
1805 if (setns(userns_fd
, CLONE_NEWUSER
) < 0)
1809 if (fchdir(root_fd
) < 0)
1812 if (chroot(".") < 0)
1816 return reset_uid_gid();
1819 int fd_warn_permissions(const char *path
, int fd
) {
1822 if (fstat(fd
, &st
) < 0)
1825 if (st
.st_mode
& 0111)
1826 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path
);
1828 if (st
.st_mode
& 0002)
1829 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path
);
1831 if (getpid() == 1 && (st
.st_mode
& 0044) != 0044)
1832 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
);
1837 unsigned long personality_from_string(const char *p
) {
1839 /* Parse a personality specifier. We introduce our own
1840 * identifiers that indicate specific ABIs, rather than just
1841 * hints regarding the register size, since we want to keep
1842 * things open for multiple locally supported ABIs for the
1843 * same register size. We try to reuse the ABI identifiers
1844 * used by libseccomp. */
1846 #if defined(__x86_64__)
1848 if (streq(p
, "x86"))
1851 if (streq(p
, "x86-64"))
1854 #elif defined(__i386__)
1856 if (streq(p
, "x86"))
1859 #elif defined(__s390x__)
1861 if (streq(p
, "s390"))
1864 if (streq(p
, "s390x"))
1867 #elif defined(__s390__)
1869 if (streq(p
, "s390"))
1873 return PERSONALITY_INVALID
;
1876 const char* personality_to_string(unsigned long p
) {
1878 #if defined(__x86_64__)
1880 if (p
== PER_LINUX32
)
1886 #elif defined(__i386__)
1891 #elif defined(__s390x__)
1896 if (p
== PER_LINUX32
)
1899 #elif defined(__s390__)
1909 uint64_t physical_memory(void) {
1912 /* We return this as uint64_t in case we are running as 32bit
1913 * process on a 64bit kernel with huge amounts of memory */
1915 mem
= sysconf(_SC_PHYS_PAGES
);
1918 return (uint64_t) mem
* (uint64_t) page_size();
1921 int update_reboot_param_file(const char *param
) {
1925 r
= write_string_file(REBOOT_PARAM_FILE
, param
, WRITE_STRING_FILE_CREATE
);
1927 return log_error_errno(r
, "Failed to write reboot param to "REBOOT_PARAM_FILE
": %m");
1929 (void) unlink(REBOOT_PARAM_FILE
);
1934 int is_symlink(const char *path
) {
1937 if (lstat(path
, &info
) < 0)
1940 return !!S_ISLNK(info
.st_mode
);
1943 int is_dir(const char* path
, bool follow
) {
1948 r
= stat(path
, &st
);
1950 r
= lstat(path
, &st
);
1954 return !!S_ISDIR(st
.st_mode
);
1957 int is_device_node(const char *path
) {
1960 if (lstat(path
, &info
) < 0)
1963 return !!(S_ISBLK(info
.st_mode
) || S_ISCHR(info
.st_mode
));
1966 ssize_t
fgetxattrat_fake(int dirfd
, const char *filename
, const char *attribute
, void *value
, size_t size
, int flags
) {
1967 char fn
[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(int) + 1];
1968 _cleanup_close_
int fd
= -1;
1971 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
1973 fd
= openat(dirfd
, filename
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_PATH
|(flags
& AT_SYMLINK_NOFOLLOW
? O_NOFOLLOW
: 0));
1977 xsprintf(fn
, "/proc/self/fd/%i", fd
);
1979 l
= getxattr(fn
, attribute
, value
, size
);
1986 static int parse_crtime(le64_t le
, usec_t
*usec
) {
1992 if (u
== 0 || u
== (uint64_t) -1)
1999 int fd_getcrtime(int fd
, usec_t
*usec
) {
2006 /* Until Linux gets a real concept of birthtime/creation time,
2007 * let's fake one with xattrs */
2009 n
= fgetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
));
2012 if (n
!= sizeof(le
))
2015 return parse_crtime(le
, usec
);
2018 int fd_getcrtime_at(int dirfd
, const char *name
, usec_t
*usec
, int flags
) {
2022 n
= fgetxattrat_fake(dirfd
, name
, "user.crtime_usec", &le
, sizeof(le
), flags
);
2025 if (n
!= sizeof(le
))
2028 return parse_crtime(le
, usec
);
2031 int path_getcrtime(const char *p
, usec_t
*usec
) {
2038 n
= getxattr(p
, "user.crtime_usec", &le
, sizeof(le
));
2041 if (n
!= sizeof(le
))
2044 return parse_crtime(le
, usec
);
2047 int fd_setcrtime(int fd
, usec_t usec
) {
2053 usec
= now(CLOCK_REALTIME
);
2055 le
= htole64((uint64_t) usec
);
2056 if (fsetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
), 0) < 0)
2062 int chattr_fd(int fd
, unsigned value
, unsigned mask
) {
2063 unsigned old_attr
, new_attr
;
2068 if (fstat(fd
, &st
) < 0)
2071 /* Explicitly check whether this is a regular file or
2072 * directory. If it is anything else (such as a device node or
2073 * fifo), then the ioctl will not hit the file systems but
2074 * possibly drivers, where the ioctl might have different
2075 * effects. Notably, DRM is using the same ioctl() number. */
2077 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
2083 if (ioctl(fd
, FS_IOC_GETFLAGS
, &old_attr
) < 0)
2086 new_attr
= (old_attr
& ~mask
) | (value
& mask
);
2087 if (new_attr
== old_attr
)
2090 if (ioctl(fd
, FS_IOC_SETFLAGS
, &new_attr
) < 0)
2096 int chattr_path(const char *p
, unsigned value
, unsigned mask
) {
2097 _cleanup_close_
int fd
= -1;
2104 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
2108 return chattr_fd(fd
, value
, mask
);
2111 int read_attr_fd(int fd
, unsigned *ret
) {
2116 if (fstat(fd
, &st
) < 0)
2119 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
2122 if (ioctl(fd
, FS_IOC_GETFLAGS
, ret
) < 0)
2128 int read_attr_path(const char *p
, unsigned *ret
) {
2129 _cleanup_close_
int fd
= -1;
2134 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
2138 return read_attr_fd(fd
, ret
);
2141 int syslog_parse_priority(const char **p
, int *priority
, bool with_facility
) {
2142 int a
= 0, b
= 0, c
= 0;
2152 if (!strchr(*p
, '>'))
2155 if ((*p
)[2] == '>') {
2156 c
= undecchar((*p
)[1]);
2158 } else if ((*p
)[3] == '>') {
2159 b
= undecchar((*p
)[1]);
2160 c
= undecchar((*p
)[2]);
2162 } else if ((*p
)[4] == '>') {
2163 a
= undecchar((*p
)[1]);
2164 b
= undecchar((*p
)[2]);
2165 c
= undecchar((*p
)[3]);
2170 if (a
< 0 || b
< 0 || c
< 0 ||
2171 (!with_facility
&& (a
|| b
|| c
> 7)))
2175 *priority
= a
*100 + b
*10 + c
;
2177 *priority
= (*priority
& LOG_FACMASK
) | c
;
2183 ssize_t
string_table_lookup(const char * const *table
, size_t len
, const char *key
) {
2189 for (i
= 0; i
< len
; ++i
)
2190 if (streq_ptr(table
[i
], key
))
2196 int rename_noreplace(int olddirfd
, const char *oldpath
, int newdirfd
, const char *newpath
) {
2200 ret
= renameat2(olddirfd
, oldpath
, newdirfd
, newpath
, RENAME_NOREPLACE
);
2204 /* renameat2() exists since Linux 3.15, btrfs added support for it later.
2205 * If it is not implemented, fallback to another method. */
2206 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
2209 /* The link()/unlink() fallback does not work on directories. But
2210 * renameat() without RENAME_NOREPLACE gives the same semantics on
2211 * directories, except when newpath is an *empty* directory. This is
2213 ret
= fstatat(olddirfd
, oldpath
, &buf
, AT_SYMLINK_NOFOLLOW
);
2214 if (ret
>= 0 && S_ISDIR(buf
.st_mode
)) {
2215 ret
= renameat(olddirfd
, oldpath
, newdirfd
, newpath
);
2216 return ret
>= 0 ? 0 : -errno
;
2219 /* If it is not a directory, use the link()/unlink() fallback. */
2220 ret
= linkat(olddirfd
, oldpath
, newdirfd
, newpath
, 0);
2224 ret
= unlinkat(olddirfd
, oldpath
, 0);
2226 /* backup errno before the following unlinkat() alters it */
2228 (void) unlinkat(newdirfd
, newpath
, 0);
2236 int getxattr_malloc(const char *path
, const char *name
, char **value
, bool allow_symlink
) {
2245 for (l
= 100; ; l
= (size_t) n
+ 1) {
2251 n
= lgetxattr(path
, name
, v
, l
);
2253 n
= getxattr(path
, name
, v
, l
);
2255 if (n
>= 0 && (size_t) n
< l
) {
2262 if (n
< 0 && errno
!= ERANGE
)
2266 n
= lgetxattr(path
, name
, NULL
, 0);
2268 n
= getxattr(path
, name
, NULL
, 0);
2274 int fgetxattr_malloc(int fd
, const char *name
, char **value
) {
2283 for (l
= 100; ; l
= (size_t) n
+ 1) {
2288 n
= fgetxattr(fd
, name
, v
, l
);
2290 if (n
>= 0 && (size_t) n
< l
) {
2297 if (n
< 0 && errno
!= ERANGE
)
2300 n
= fgetxattr(fd
, name
, NULL
, 0);
2307 puts(PACKAGE_STRING
"\n"
2312 bool fdname_is_valid(const char *s
) {
2315 /* Validates a name for $LISTEN_FDNAMES. We basically allow
2316 * everything ASCII that's not a control character. Also, as
2317 * special exception the ":" character is not allowed, as we
2318 * use that as field separator in $LISTEN_FDNAMES.
2320 * Note that the empty string is explicitly allowed
2321 * here. However, we limit the length of the names to 255
2327 for (p
= s
; *p
; p
++) {
2339 bool oom_score_adjust_is_valid(int oa
) {
2340 return oa
>= OOM_SCORE_ADJ_MIN
&& oa
<= OOM_SCORE_ADJ_MAX
;