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>
49 #include <sys/resource.h>
51 #include <sys/statvfs.h>
53 #include <sys/types.h>
54 #include <sys/utsname.h>
57 #include <sys/xattr.h>
61 /* When we include libgen.h because we need dirname() we immediately
62 * undefine basename() since libgen.h defines it as a macro to the
63 * POSIX version which is really broken. We prefer GNU basename(). */
67 #ifdef HAVE_SYS_AUXV_H
71 /* We include linux/fs.h as last of the system headers, as it
72 * otherwise conflicts with sys/mount.h. Yay, Linux is great! */
77 #include "device-nodes.h"
80 #include "exit-status.h"
83 #include "formats-util.h"
86 #include "hostname-util.h"
92 #include "hexdecoct.h"
93 #include "parse-util.h"
94 #include "path-util.h"
95 #include "process-util.h"
96 #include "random-util.h"
97 #include "signal-util.h"
98 #include "sparse-endian.h"
99 #include "string-util.h"
101 #include "terminal-util.h"
102 #include "user-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 char *file_in_same_dir(const char *path
, const char *filename
) {
258 /* This removes the last component of path and appends
259 * filename, unless the latter is absolute anyway or the
262 if (path_is_absolute(filename
))
263 return strdup(filename
);
265 e
= strrchr(path
, '/');
267 return strdup(filename
);
269 k
= strlen(filename
);
270 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
274 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
278 int rmdir_parents(const char *path
, const char *stop
) {
287 /* Skip trailing slashes */
288 while (l
> 0 && path
[l
-1] == '/')
294 /* Skip last component */
295 while (l
> 0 && path
[l
-1] != '/')
298 /* Skip trailing slashes */
299 while (l
> 0 && path
[l
-1] == '/')
305 if (!(t
= strndup(path
, l
)))
308 if (path_startswith(stop
, t
)) {
324 _pure_
static bool hidden_file_allow_backup(const char *filename
) {
328 filename
[0] == '.' ||
329 streq(filename
, "lost+found") ||
330 streq(filename
, "aquota.user") ||
331 streq(filename
, "aquota.group") ||
332 endswith(filename
, ".rpmnew") ||
333 endswith(filename
, ".rpmsave") ||
334 endswith(filename
, ".rpmorig") ||
335 endswith(filename
, ".dpkg-old") ||
336 endswith(filename
, ".dpkg-new") ||
337 endswith(filename
, ".dpkg-tmp") ||
338 endswith(filename
, ".dpkg-dist") ||
339 endswith(filename
, ".dpkg-bak") ||
340 endswith(filename
, ".dpkg-backup") ||
341 endswith(filename
, ".dpkg-remove") ||
342 endswith(filename
, ".swp");
345 bool hidden_file(const char *filename
) {
348 if (endswith(filename
, "~"))
351 return hidden_file_allow_backup(filename
);
354 bool fstype_is_network(const char *fstype
) {
355 static const char table
[] =
370 x
= startswith(fstype
, "fuse.");
374 return nulstr_contains(table
, fstype
);
377 bool is_device_path(const char *path
) {
379 /* Returns true on paths that refer to a device, either in
380 * sysfs or in /dev */
383 path_startswith(path
, "/dev/") ||
384 path_startswith(path
, "/sys/");
387 int dir_is_empty(const char *path
) {
388 _cleanup_closedir_
DIR *d
;
395 FOREACH_DIRENT(de
, d
, return -errno
)
401 void rename_process(const char name
[8]) {
404 /* This is a like a poor man's setproctitle(). It changes the
405 * comm field, argv[0], and also the glibc's internally used
406 * name of the process. For the first one a limit of 16 chars
407 * applies, to the second one usually one of 10 (i.e. length
408 * of "/sbin/init"), to the third one one of 7 (i.e. length of
409 * "systemd"). If you pass a longer string it will be
412 prctl(PR_SET_NAME
, name
);
414 if (program_invocation_name
)
415 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
417 if (saved_argc
> 0) {
421 strncpy(saved_argv
[0], name
, strlen(saved_argv
[0]));
423 for (i
= 1; i
< saved_argc
; i
++) {
427 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
432 bool is_fs_type(const struct statfs
*s
, statfs_f_type_t magic_value
) {
434 assert_cc(sizeof(statfs_f_type_t
) >= sizeof(s
->f_type
));
436 return F_TYPE_EQUAL(s
->f_type
, magic_value
);
439 int fd_check_fstype(int fd
, statfs_f_type_t magic_value
) {
442 if (fstatfs(fd
, &s
) < 0)
445 return is_fs_type(&s
, magic_value
);
448 int path_check_fstype(const char *path
, statfs_f_type_t magic_value
) {
449 _cleanup_close_
int fd
= -1;
451 fd
= open(path
, O_RDONLY
);
455 return fd_check_fstype(fd
, magic_value
);
458 bool is_temporary_fs(const struct statfs
*s
) {
459 return is_fs_type(s
, TMPFS_MAGIC
) ||
460 is_fs_type(s
, RAMFS_MAGIC
);
463 int fd_is_temporary_fs(int fd
) {
466 if (fstatfs(fd
, &s
) < 0)
469 return is_temporary_fs(&s
);
472 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
475 /* Under the assumption that we are running privileged we
476 * first change the access mode and only then hand out
477 * ownership to avoid a window where access is too open. */
479 if (mode
!= MODE_INVALID
)
480 if (chmod(path
, mode
) < 0)
483 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
484 if (chown(path
, uid
, gid
) < 0)
490 int fchmod_and_fchown(int fd
, mode_t mode
, uid_t uid
, gid_t gid
) {
493 /* Under the assumption that we are running privileged we
494 * first change the access mode and only then hand out
495 * ownership to avoid a window where access is too open. */
497 if (mode
!= MODE_INVALID
)
498 if (fchmod(fd
, mode
) < 0)
501 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
502 if (fchown(fd
, uid
, gid
) < 0)
508 int files_same(const char *filea
, const char *fileb
) {
511 if (stat(filea
, &a
) < 0)
514 if (stat(fileb
, &b
) < 0)
517 return a
.st_dev
== b
.st_dev
&&
518 a
.st_ino
== b
.st_ino
;
521 int running_in_chroot(void) {
524 ret
= files_same("/proc/1/root", "/");
531 int touch_file(const char *path
, bool parents
, usec_t stamp
, uid_t uid
, gid_t gid
, mode_t mode
) {
532 _cleanup_close_
int fd
;
538 mkdir_parents(path
, 0755);
540 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, mode
> 0 ? mode
: 0644);
545 r
= fchmod(fd
, mode
);
550 if (uid
!= UID_INVALID
|| gid
!= GID_INVALID
) {
551 r
= fchown(fd
, uid
, gid
);
556 if (stamp
!= USEC_INFINITY
) {
557 struct timespec ts
[2];
559 timespec_store(&ts
[0], stamp
);
561 r
= futimens(fd
, ts
);
563 r
= futimens(fd
, NULL
);
570 int touch(const char *path
) {
571 return touch_file(path
, false, USEC_INFINITY
, UID_INVALID
, GID_INVALID
, 0);
574 noreturn
void freeze(void) {
576 /* Make sure nobody waits for us on a socket anymore */
577 close_all_fds(NULL
, 0);
585 bool null_or_empty(struct stat
*st
) {
588 if (S_ISREG(st
->st_mode
) && st
->st_size
<= 0)
591 if (S_ISCHR(st
->st_mode
) || S_ISBLK(st
->st_mode
))
597 int null_or_empty_path(const char *fn
) {
602 if (stat(fn
, &st
) < 0)
605 return null_or_empty(&st
);
608 int null_or_empty_fd(int fd
) {
613 if (fstat(fd
, &st
) < 0)
616 return null_or_empty(&st
);
619 bool dirent_is_file(const struct dirent
*de
) {
622 if (hidden_file(de
->d_name
))
625 if (de
->d_type
!= DT_REG
&&
626 de
->d_type
!= DT_LNK
&&
627 de
->d_type
!= DT_UNKNOWN
)
633 bool dirent_is_file_with_suffix(const struct dirent
*de
, const char *suffix
) {
636 if (de
->d_type
!= DT_REG
&&
637 de
->d_type
!= DT_LNK
&&
638 de
->d_type
!= DT_UNKNOWN
)
641 if (hidden_file_allow_backup(de
->d_name
))
644 return endswith(de
->d_name
, suffix
);
647 static int do_execute(char **directories
, usec_t timeout
, char *argv
[]) {
648 _cleanup_hashmap_free_free_ Hashmap
*pids
= NULL
;
649 _cleanup_set_free_free_ Set
*seen
= NULL
;
652 /* We fork this all off from a child process so that we can
653 * somewhat cleanly make use of SIGALRM to set a time limit */
655 (void) reset_all_signal_handlers();
656 (void) reset_signal_mask();
658 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
660 pids
= hashmap_new(NULL
);
664 seen
= set_new(&string_hash_ops
);
668 STRV_FOREACH(directory
, directories
) {
669 _cleanup_closedir_
DIR *d
;
672 d
= opendir(*directory
);
677 return log_error_errno(errno
, "Failed to open directory %s: %m", *directory
);
680 FOREACH_DIRENT(de
, d
, break) {
681 _cleanup_free_
char *path
= NULL
;
685 if (!dirent_is_file(de
))
688 if (set_contains(seen
, de
->d_name
)) {
689 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory
, de
->d_name
);
693 r
= set_put_strdup(seen
, de
->d_name
);
697 path
= strjoin(*directory
, "/", de
->d_name
, NULL
);
701 if (null_or_empty_path(path
)) {
702 log_debug("%s is empty (a mask).", path
);
708 log_error_errno(errno
, "Failed to fork: %m");
710 } else if (pid
== 0) {
713 assert_se(prctl(PR_SET_PDEATHSIG
, SIGTERM
) == 0);
723 return log_error_errno(errno
, "Failed to execute %s: %m", path
);
726 log_debug("Spawned %s as " PID_FMT
".", path
, pid
);
728 r
= hashmap_put(pids
, UINT_TO_PTR(pid
), path
);
735 /* Abort execution of this process after the timout. We simply
736 * rely on SIGALRM as default action terminating the process,
737 * and turn on alarm(). */
739 if (timeout
!= USEC_INFINITY
)
740 alarm((timeout
+ USEC_PER_SEC
- 1) / USEC_PER_SEC
);
742 while (!hashmap_isempty(pids
)) {
743 _cleanup_free_
char *path
= NULL
;
746 pid
= PTR_TO_UINT(hashmap_first_key(pids
));
749 path
= hashmap_remove(pids
, UINT_TO_PTR(pid
));
752 wait_for_terminate_and_warn(path
, pid
, true);
758 void execute_directories(const char* const* directories
, usec_t timeout
, char *argv
[]) {
762 char **dirs
= (char**) directories
;
764 assert(!strv_isempty(dirs
));
766 name
= basename(dirs
[0]);
767 assert(!isempty(name
));
769 /* Executes all binaries in the directories in parallel and waits
770 * for them to finish. Optionally a timeout is applied. If a file
771 * with the same name exists in more than one directory, the
772 * earliest one wins. */
774 executor_pid
= fork();
775 if (executor_pid
< 0) {
776 log_error_errno(errno
, "Failed to fork: %m");
779 } else if (executor_pid
== 0) {
780 r
= do_execute(dirs
, timeout
, argv
);
781 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
784 wait_for_terminate_and_warn(name
, executor_pid
, true);
787 bool plymouth_running(void) {
788 return access("/run/plymouth/pid", F_OK
) >= 0;
791 int symlink_atomic(const char *from
, const char *to
) {
792 _cleanup_free_
char *t
= NULL
;
798 r
= tempfn_random(to
, NULL
, &t
);
802 if (symlink(from
, t
) < 0)
805 if (rename(t
, to
) < 0) {
813 int symlink_idempotent(const char *from
, const char *to
) {
814 _cleanup_free_
char *p
= NULL
;
820 if (symlink(from
, to
) < 0) {
824 r
= readlink_malloc(to
, &p
);
835 int mknod_atomic(const char *path
, mode_t mode
, dev_t dev
) {
836 _cleanup_free_
char *t
= NULL
;
841 r
= tempfn_random(path
, NULL
, &t
);
845 if (mknod(t
, mode
, dev
) < 0)
848 if (rename(t
, path
) < 0) {
856 int mkfifo_atomic(const char *path
, mode_t mode
) {
857 _cleanup_free_
char *t
= NULL
;
862 r
= tempfn_random(path
, NULL
, &t
);
866 if (mkfifo(t
, mode
) < 0)
869 if (rename(t
, path
) < 0) {
877 bool display_is_local(const char *display
) {
886 int socket_from_display(const char *display
, char **path
) {
893 if (!display_is_local(display
))
896 k
= strspn(display
+1, "0123456789");
898 f
= new(char, strlen("/tmp/.X11-unix/X") + k
+ 1);
902 c
= stpcpy(f
, "/tmp/.X11-unix/X");
903 memcpy(c
, display
+1, k
);
911 int glob_exists(const char *path
) {
912 _cleanup_globfree_ glob_t g
= {};
918 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
920 if (k
== GLOB_NOMATCH
)
922 else if (k
== GLOB_NOSPACE
)
925 return !strv_isempty(g
.gl_pathv
);
927 return errno
? -errno
: -EIO
;
930 int glob_extend(char ***strv
, const char *path
) {
931 _cleanup_globfree_ glob_t g
= {};
936 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
938 if (k
== GLOB_NOMATCH
)
940 else if (k
== GLOB_NOSPACE
)
942 else if (k
!= 0 || strv_isempty(g
.gl_pathv
))
943 return errno
? -errno
: -EIO
;
945 STRV_FOREACH(p
, g
.gl_pathv
) {
946 k
= strv_extend(strv
, *p
);
954 int dirent_ensure_type(DIR *d
, struct dirent
*de
) {
960 if (de
->d_type
!= DT_UNKNOWN
)
963 if (fstatat(dirfd(d
), de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
967 S_ISREG(st
.st_mode
) ? DT_REG
:
968 S_ISDIR(st
.st_mode
) ? DT_DIR
:
969 S_ISLNK(st
.st_mode
) ? DT_LNK
:
970 S_ISFIFO(st
.st_mode
) ? DT_FIFO
:
971 S_ISSOCK(st
.st_mode
) ? DT_SOCK
:
972 S_ISCHR(st
.st_mode
) ? DT_CHR
:
973 S_ISBLK(st
.st_mode
) ? DT_BLK
:
979 int get_files_in_directory(const char *path
, char ***list
) {
980 _cleanup_closedir_
DIR *d
= NULL
;
981 size_t bufsize
= 0, n
= 0;
982 _cleanup_strv_free_
char **l
= NULL
;
986 /* Returns all files in a directory in *list, and the number
987 * of files as return value. If list is NULL returns only the
999 if (!de
&& errno
!= 0)
1004 dirent_ensure_type(d
, de
);
1006 if (!dirent_is_file(de
))
1010 /* one extra slot is needed for the terminating NULL */
1011 if (!GREEDY_REALLOC(l
, bufsize
, n
+ 2))
1014 l
[n
] = strdup(de
->d_name
);
1025 l
= NULL
; /* avoid freeing */
1031 bool is_main_thread(void) {
1032 static thread_local
int cached
= 0;
1034 if (_unlikely_(cached
== 0))
1035 cached
= getpid() == gettid() ? 1 : -1;
1040 int block_get_whole_disk(dev_t d
, dev_t
*ret
) {
1047 /* If it has a queue this is good enough for us */
1048 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", major(d
), minor(d
)) < 0)
1051 r
= access(p
, F_OK
);
1059 /* If it is a partition find the originating device */
1060 if (asprintf(&p
, "/sys/dev/block/%u:%u/partition", major(d
), minor(d
)) < 0)
1063 r
= access(p
, F_OK
);
1069 /* Get parent dev_t */
1070 if (asprintf(&p
, "/sys/dev/block/%u:%u/../dev", major(d
), minor(d
)) < 0)
1073 r
= read_one_line_file(p
, &s
);
1079 r
= sscanf(s
, "%u:%u", &m
, &n
);
1085 /* Only return this if it is really good enough for us. */
1086 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", m
, n
) < 0)
1089 r
= access(p
, F_OK
);
1093 *ret
= makedev(m
, n
);
1100 static const char *const ioprio_class_table
[] = {
1101 [IOPRIO_CLASS_NONE
] = "none",
1102 [IOPRIO_CLASS_RT
] = "realtime",
1103 [IOPRIO_CLASS_BE
] = "best-effort",
1104 [IOPRIO_CLASS_IDLE
] = "idle"
1107 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, INT_MAX
);
1109 static const char *const sigchld_code_table
[] = {
1110 [CLD_EXITED
] = "exited",
1111 [CLD_KILLED
] = "killed",
1112 [CLD_DUMPED
] = "dumped",
1113 [CLD_TRAPPED
] = "trapped",
1114 [CLD_STOPPED
] = "stopped",
1115 [CLD_CONTINUED
] = "continued",
1118 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
1120 static const char *const log_facility_unshifted_table
[LOG_NFACILITIES
] = {
1121 [LOG_FAC(LOG_KERN
)] = "kern",
1122 [LOG_FAC(LOG_USER
)] = "user",
1123 [LOG_FAC(LOG_MAIL
)] = "mail",
1124 [LOG_FAC(LOG_DAEMON
)] = "daemon",
1125 [LOG_FAC(LOG_AUTH
)] = "auth",
1126 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
1127 [LOG_FAC(LOG_LPR
)] = "lpr",
1128 [LOG_FAC(LOG_NEWS
)] = "news",
1129 [LOG_FAC(LOG_UUCP
)] = "uucp",
1130 [LOG_FAC(LOG_CRON
)] = "cron",
1131 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
1132 [LOG_FAC(LOG_FTP
)] = "ftp",
1133 [LOG_FAC(LOG_LOCAL0
)] = "local0",
1134 [LOG_FAC(LOG_LOCAL1
)] = "local1",
1135 [LOG_FAC(LOG_LOCAL2
)] = "local2",
1136 [LOG_FAC(LOG_LOCAL3
)] = "local3",
1137 [LOG_FAC(LOG_LOCAL4
)] = "local4",
1138 [LOG_FAC(LOG_LOCAL5
)] = "local5",
1139 [LOG_FAC(LOG_LOCAL6
)] = "local6",
1140 [LOG_FAC(LOG_LOCAL7
)] = "local7"
1143 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted
, int, LOG_FAC(~0));
1145 bool log_facility_unshifted_is_valid(int facility
) {
1146 return facility
>= 0 && facility
<= LOG_FAC(~0);
1149 static const char *const log_level_table
[] = {
1150 [LOG_EMERG
] = "emerg",
1151 [LOG_ALERT
] = "alert",
1152 [LOG_CRIT
] = "crit",
1154 [LOG_WARNING
] = "warning",
1155 [LOG_NOTICE
] = "notice",
1156 [LOG_INFO
] = "info",
1157 [LOG_DEBUG
] = "debug"
1160 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level
, int, LOG_DEBUG
);
1162 bool log_level_is_valid(int level
) {
1163 return level
>= 0 && level
<= LOG_DEBUG
;
1166 static const char* const sched_policy_table
[] = {
1167 [SCHED_OTHER
] = "other",
1168 [SCHED_BATCH
] = "batch",
1169 [SCHED_IDLE
] = "idle",
1170 [SCHED_FIFO
] = "fifo",
1174 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);
1176 static const char* const rlimit_table
[_RLIMIT_MAX
] = {
1177 [RLIMIT_CPU
] = "LimitCPU",
1178 [RLIMIT_FSIZE
] = "LimitFSIZE",
1179 [RLIMIT_DATA
] = "LimitDATA",
1180 [RLIMIT_STACK
] = "LimitSTACK",
1181 [RLIMIT_CORE
] = "LimitCORE",
1182 [RLIMIT_RSS
] = "LimitRSS",
1183 [RLIMIT_NOFILE
] = "LimitNOFILE",
1184 [RLIMIT_AS
] = "LimitAS",
1185 [RLIMIT_NPROC
] = "LimitNPROC",
1186 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
1187 [RLIMIT_LOCKS
] = "LimitLOCKS",
1188 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
1189 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
1190 [RLIMIT_NICE
] = "LimitNICE",
1191 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
1192 [RLIMIT_RTTIME
] = "LimitRTTIME"
1195 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
1197 bool kexec_loaded(void) {
1198 bool loaded
= false;
1201 if (read_one_line_file("/sys/kernel/kexec_loaded", &s
) >= 0) {
1209 int prot_from_flags(int flags
) {
1211 switch (flags
& O_ACCMODE
) {
1220 return PROT_READ
|PROT_WRITE
;
1227 void* memdup(const void *p
, size_t l
) {
1240 int fork_agent(pid_t
*pid
, const int except
[], unsigned n_except
, const char *path
, ...) {
1241 bool stdout_is_tty
, stderr_is_tty
;
1242 pid_t parent_pid
, agent_pid
;
1243 sigset_t ss
, saved_ss
;
1251 /* Spawns a temporary TTY agent, making sure it goes away when
1254 parent_pid
= getpid();
1256 /* First we temporarily block all signals, so that the new
1257 * child has them blocked initially. This way, we can be sure
1258 * that SIGTERMs are not lost we might send to the agent. */
1259 assert_se(sigfillset(&ss
) >= 0);
1260 assert_se(sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) >= 0);
1263 if (agent_pid
< 0) {
1264 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
1268 if (agent_pid
!= 0) {
1269 assert_se(sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) >= 0);
1276 * Make sure the agent goes away when the parent dies */
1277 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
1278 _exit(EXIT_FAILURE
);
1280 /* Make sure we actually can kill the agent, if we need to, in
1281 * case somebody invoked us from a shell script that trapped
1282 * SIGTERM or so... */
1283 (void) reset_all_signal_handlers();
1284 (void) reset_signal_mask();
1286 /* Check whether our parent died before we were able
1287 * to set the death signal and unblock the signals */
1288 if (getppid() != parent_pid
)
1289 _exit(EXIT_SUCCESS
);
1291 /* Don't leak fds to the agent */
1292 close_all_fds(except
, n_except
);
1294 stdout_is_tty
= isatty(STDOUT_FILENO
);
1295 stderr_is_tty
= isatty(STDERR_FILENO
);
1297 if (!stdout_is_tty
|| !stderr_is_tty
) {
1300 /* Detach from stdout/stderr. and reopen
1301 * /dev/tty for them. This is important to
1302 * ensure that when systemctl is started via
1303 * popen() or a similar call that expects to
1304 * read EOF we actually do generate EOF and
1305 * not delay this indefinitely by because we
1306 * keep an unused copy of stdin around. */
1307 fd
= open("/dev/tty", O_WRONLY
);
1309 log_error_errno(errno
, "Failed to open /dev/tty: %m");
1310 _exit(EXIT_FAILURE
);
1314 dup2(fd
, STDOUT_FILENO
);
1317 dup2(fd
, STDERR_FILENO
);
1323 /* Count arguments */
1325 for (n
= 0; va_arg(ap
, char*); n
++)
1330 l
= alloca(sizeof(char *) * (n
+ 1));
1332 /* Fill in arguments */
1334 for (i
= 0; i
<= n
; i
++)
1335 l
[i
] = va_arg(ap
, char*);
1339 _exit(EXIT_FAILURE
);
1342 int setrlimit_closest(int resource
, const struct rlimit
*rlim
) {
1343 struct rlimit highest
, fixed
;
1347 if (setrlimit(resource
, rlim
) >= 0)
1353 /* So we failed to set the desired setrlimit, then let's try
1354 * to get as close as we can */
1355 assert_se(getrlimit(resource
, &highest
) == 0);
1357 fixed
.rlim_cur
= MIN(rlim
->rlim_cur
, highest
.rlim_max
);
1358 fixed
.rlim_max
= MIN(rlim
->rlim_max
, highest
.rlim_max
);
1360 if (setrlimit(resource
, &fixed
) < 0)
1366 bool http_etag_is_valid(const char *etag
) {
1370 if (!endswith(etag
, "\""))
1373 if (!startswith(etag
, "\"") && !startswith(etag
, "W/\""))
1379 bool http_url_is_valid(const char *url
) {
1385 p
= startswith(url
, "http://");
1387 p
= startswith(url
, "https://");
1394 return ascii_is_valid(p
);
1397 bool documentation_url_is_valid(const char *url
) {
1403 if (http_url_is_valid(url
))
1406 p
= startswith(url
, "file:/");
1408 p
= startswith(url
, "info:");
1410 p
= startswith(url
, "man:");
1415 return ascii_is_valid(p
);
1418 bool in_initrd(void) {
1419 static int saved
= -1;
1425 /* We make two checks here:
1427 * 1. the flag file /etc/initrd-release must exist
1428 * 2. the root file system must be a memory file system
1430 * The second check is extra paranoia, since misdetecting an
1431 * initrd can have bad bad consequences due the initrd
1432 * emptying when transititioning to the main systemd.
1435 saved
= access("/etc/initrd-release", F_OK
) >= 0 &&
1436 statfs("/", &s
) >= 0 &&
1437 is_temporary_fs(&s
);
1442 bool string_is_safe(const char *p
) {
1448 for (t
= p
; *t
; t
++) {
1449 if (*t
> 0 && *t
< ' ')
1452 if (strchr("\\\"\'\x7f", *t
))
1459 /* hey glibc, APIs with callbacks without a user pointer are so useless */
1460 void *xbsearch_r(const void *key
, const void *base
, size_t nmemb
, size_t size
,
1461 int (*compar
) (const void *, const void *, void *), void *arg
) {
1470 p
= (void *)(((const char *) base
) + (idx
* size
));
1471 comparison
= compar(key
, p
, arg
);
1474 else if (comparison
> 0)
1482 void init_gettext(void) {
1483 setlocale(LC_ALL
, "");
1484 textdomain(GETTEXT_PACKAGE
);
1487 bool is_locale_utf8(void) {
1489 static int cached_answer
= -1;
1491 if (cached_answer
>= 0)
1494 if (!setlocale(LC_ALL
, "")) {
1495 cached_answer
= true;
1499 set
= nl_langinfo(CODESET
);
1501 cached_answer
= true;
1505 if (streq(set
, "UTF-8")) {
1506 cached_answer
= true;
1510 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
1511 * unset and everything can do to UTF-8 nowadays. */
1512 set
= setlocale(LC_CTYPE
, NULL
);
1514 cached_answer
= true;
1518 /* Check result, but ignore the result if C was set
1521 STR_IN_SET(set
, "C", "POSIX") &&
1522 !getenv("LC_ALL") &&
1523 !getenv("LC_CTYPE") &&
1527 return (bool) cached_answer
;
1530 const char *draw_special_char(DrawSpecialChar ch
) {
1531 static const char *draw_table
[2][_DRAW_SPECIAL_CHAR_MAX
] = {
1534 [DRAW_TREE_VERTICAL
] = "\342\224\202 ", /* │ */
1535 [DRAW_TREE_BRANCH
] = "\342\224\234\342\224\200", /* ├─ */
1536 [DRAW_TREE_RIGHT
] = "\342\224\224\342\224\200", /* └─ */
1537 [DRAW_TREE_SPACE
] = " ", /* */
1538 [DRAW_TRIANGULAR_BULLET
] = "\342\200\243", /* ‣ */
1539 [DRAW_BLACK_CIRCLE
] = "\342\227\217", /* ● */
1540 [DRAW_ARROW
] = "\342\206\222", /* → */
1541 [DRAW_DASH
] = "\342\200\223", /* – */
1544 /* ASCII fallback */ {
1545 [DRAW_TREE_VERTICAL
] = "| ",
1546 [DRAW_TREE_BRANCH
] = "|-",
1547 [DRAW_TREE_RIGHT
] = "`-",
1548 [DRAW_TREE_SPACE
] = " ",
1549 [DRAW_TRIANGULAR_BULLET
] = ">",
1550 [DRAW_BLACK_CIRCLE
] = "*",
1551 [DRAW_ARROW
] = "->",
1556 return draw_table
[!is_locale_utf8()][ch
];
1559 int on_ac_power(void) {
1560 bool found_offline
= false, found_online
= false;
1561 _cleanup_closedir_
DIR *d
= NULL
;
1563 d
= opendir("/sys/class/power_supply");
1565 return errno
== ENOENT
? true : -errno
;
1569 _cleanup_close_
int fd
= -1, device
= -1;
1575 if (!de
&& errno
!= 0)
1581 if (hidden_file(de
->d_name
))
1584 device
= openat(dirfd(d
), de
->d_name
, O_DIRECTORY
|O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
1586 if (errno
== ENOENT
|| errno
== ENOTDIR
)
1592 fd
= openat(device
, "type", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
1594 if (errno
== ENOENT
)
1600 n
= read(fd
, contents
, sizeof(contents
));
1604 if (n
!= 6 || memcmp(contents
, "Mains\n", 6))
1608 fd
= openat(device
, "online", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
1610 if (errno
== ENOENT
)
1616 n
= read(fd
, contents
, sizeof(contents
));
1620 if (n
!= 2 || contents
[1] != '\n')
1623 if (contents
[0] == '1') {
1624 found_online
= true;
1626 } else if (contents
[0] == '0')
1627 found_offline
= true;
1632 return found_online
|| !found_offline
;
1635 void* greedy_realloc(void **p
, size_t *allocated
, size_t need
, size_t size
) {
1642 if (*allocated
>= need
)
1645 newalloc
= MAX(need
* 2, 64u / size
);
1646 a
= newalloc
* size
;
1648 /* check for overflows */
1649 if (a
< size
* need
)
1657 *allocated
= newalloc
;
1661 void* greedy_realloc0(void **p
, size_t *allocated
, size_t need
, size_t size
) {
1670 q
= greedy_realloc(p
, allocated
, need
, size
);
1674 if (*allocated
> prev
)
1675 memzero(q
+ prev
* size
, (*allocated
- prev
) * size
);
1680 bool id128_is_valid(const char *s
) {
1686 /* Simple formatted 128bit hex string */
1688 for (i
= 0; i
< l
; i
++) {
1691 if (!(c
>= '0' && c
<= '9') &&
1692 !(c
>= 'a' && c
<= 'z') &&
1693 !(c
>= 'A' && c
<= 'Z'))
1697 } else if (l
== 36) {
1699 /* Formatted UUID */
1701 for (i
= 0; i
< l
; i
++) {
1704 if ((i
== 8 || i
== 13 || i
== 18 || i
== 23)) {
1708 if (!(c
>= '0' && c
<= '9') &&
1709 !(c
>= 'a' && c
<= 'z') &&
1710 !(c
>= 'A' && c
<= 'Z'))
1721 int shall_restore_state(void) {
1722 _cleanup_free_
char *value
= NULL
;
1725 r
= get_proc_cmdline_key("systemd.restore_state=", &value
);
1731 return parse_boolean(value
) != 0;
1734 int proc_cmdline(char **ret
) {
1737 if (detect_container() > 0)
1738 return get_process_cmdline(1, 0, false, ret
);
1740 return read_one_line_file("/proc/cmdline", ret
);
1743 int parse_proc_cmdline(int (*parse_item
)(const char *key
, const char *value
)) {
1744 _cleanup_free_
char *line
= NULL
;
1750 r
= proc_cmdline(&line
);
1756 _cleanup_free_
char *word
= NULL
;
1759 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
1765 /* Filter out arguments that are intended only for the
1767 if (!in_initrd() && startswith(word
, "rd."))
1770 value
= strchr(word
, '=');
1774 r
= parse_item(word
, value
);
1782 int get_proc_cmdline_key(const char *key
, char **value
) {
1783 _cleanup_free_
char *line
= NULL
, *ret
= NULL
;
1790 r
= proc_cmdline(&line
);
1796 _cleanup_free_
char *word
= NULL
;
1799 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
1805 /* Filter out arguments that are intended only for the
1807 if (!in_initrd() && startswith(word
, "rd."))
1811 e
= startswith(word
, key
);
1815 r
= free_and_strdup(&ret
, e
);
1821 if (streq(word
, key
))
1835 int container_get_leader(const char *machine
, pid_t
*pid
) {
1836 _cleanup_free_
char *s
= NULL
, *class = NULL
;
1844 if (!machine_name_is_valid(machine
))
1847 p
= strjoina("/run/systemd/machines/", machine
);
1848 r
= parse_env_file(p
, NEWLINE
, "LEADER", &s
, "CLASS", &class, NULL
);
1856 if (!streq_ptr(class, "container"))
1859 r
= parse_pid(s
, &leader
);
1869 int namespace_open(pid_t pid
, int *pidns_fd
, int *mntns_fd
, int *netns_fd
, int *userns_fd
, int *root_fd
) {
1870 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, netnsfd
= -1, usernsfd
= -1;
1878 mntns
= procfs_file_alloca(pid
, "ns/mnt");
1879 mntnsfd
= open(mntns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
1887 pidns
= procfs_file_alloca(pid
, "ns/pid");
1888 pidnsfd
= open(pidns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
1896 netns
= procfs_file_alloca(pid
, "ns/net");
1897 netnsfd
= open(netns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
1905 userns
= procfs_file_alloca(pid
, "ns/user");
1906 usernsfd
= open(userns
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
1907 if (usernsfd
< 0 && errno
!= ENOENT
)
1914 root
= procfs_file_alloca(pid
, "root");
1915 rfd
= open(root
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
|O_DIRECTORY
);
1921 *pidns_fd
= pidnsfd
;
1924 *mntns_fd
= mntnsfd
;
1927 *netns_fd
= netnsfd
;
1930 *userns_fd
= usernsfd
;
1935 pidnsfd
= mntnsfd
= netnsfd
= usernsfd
= -1;
1940 int namespace_enter(int pidns_fd
, int mntns_fd
, int netns_fd
, int userns_fd
, int root_fd
) {
1941 if (userns_fd
>= 0) {
1942 /* Can't setns to your own userns, since then you could
1943 * escalate from non-root to root in your own namespace, so
1944 * check if namespaces equal before attempting to enter. */
1945 _cleanup_free_
char *userns_fd_path
= NULL
;
1947 if (asprintf(&userns_fd_path
, "/proc/self/fd/%d", userns_fd
) < 0)
1950 r
= files_same(userns_fd_path
, "/proc/self/ns/user");
1958 if (setns(pidns_fd
, CLONE_NEWPID
) < 0)
1962 if (setns(mntns_fd
, CLONE_NEWNS
) < 0)
1966 if (setns(netns_fd
, CLONE_NEWNET
) < 0)
1970 if (setns(userns_fd
, CLONE_NEWUSER
) < 0)
1974 if (fchdir(root_fd
) < 0)
1977 if (chroot(".") < 0)
1981 return reset_uid_gid();
1984 int fd_warn_permissions(const char *path
, int fd
) {
1987 if (fstat(fd
, &st
) < 0)
1990 if (st
.st_mode
& 0111)
1991 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path
);
1993 if (st
.st_mode
& 0002)
1994 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path
);
1996 if (getpid() == 1 && (st
.st_mode
& 0044) != 0044)
1997 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
);
2002 unsigned long personality_from_string(const char *p
) {
2004 /* Parse a personality specifier. We introduce our own
2005 * identifiers that indicate specific ABIs, rather than just
2006 * hints regarding the register size, since we want to keep
2007 * things open for multiple locally supported ABIs for the
2008 * same register size. We try to reuse the ABI identifiers
2009 * used by libseccomp. */
2011 #if defined(__x86_64__)
2013 if (streq(p
, "x86"))
2016 if (streq(p
, "x86-64"))
2019 #elif defined(__i386__)
2021 if (streq(p
, "x86"))
2024 #elif defined(__s390x__)
2026 if (streq(p
, "s390"))
2029 if (streq(p
, "s390x"))
2032 #elif defined(__s390__)
2034 if (streq(p
, "s390"))
2038 return PERSONALITY_INVALID
;
2041 const char* personality_to_string(unsigned long p
) {
2043 #if defined(__x86_64__)
2045 if (p
== PER_LINUX32
)
2051 #elif defined(__i386__)
2056 #elif defined(__s390x__)
2061 if (p
== PER_LINUX32
)
2064 #elif defined(__s390__)
2074 uint64_t physical_memory(void) {
2077 /* We return this as uint64_t in case we are running as 32bit
2078 * process on a 64bit kernel with huge amounts of memory */
2080 mem
= sysconf(_SC_PHYS_PAGES
);
2083 return (uint64_t) mem
* (uint64_t) page_size();
2086 int update_reboot_param_file(const char *param
) {
2090 r
= write_string_file(REBOOT_PARAM_FILE
, param
, WRITE_STRING_FILE_CREATE
);
2092 return log_error_errno(r
, "Failed to write reboot param to "REBOOT_PARAM_FILE
": %m");
2094 (void) unlink(REBOOT_PARAM_FILE
);
2099 int is_symlink(const char *path
) {
2102 if (lstat(path
, &info
) < 0)
2105 return !!S_ISLNK(info
.st_mode
);
2108 int is_dir(const char* path
, bool follow
) {
2113 r
= stat(path
, &st
);
2115 r
= lstat(path
, &st
);
2119 return !!S_ISDIR(st
.st_mode
);
2122 int is_device_node(const char *path
) {
2125 if (lstat(path
, &info
) < 0)
2128 return !!(S_ISBLK(info
.st_mode
) || S_ISCHR(info
.st_mode
));
2131 ssize_t
fgetxattrat_fake(int dirfd
, const char *filename
, const char *attribute
, void *value
, size_t size
, int flags
) {
2132 char fn
[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(int) + 1];
2133 _cleanup_close_
int fd
= -1;
2136 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
2138 fd
= openat(dirfd
, filename
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_PATH
|(flags
& AT_SYMLINK_NOFOLLOW
? O_NOFOLLOW
: 0));
2142 xsprintf(fn
, "/proc/self/fd/%i", fd
);
2144 l
= getxattr(fn
, attribute
, value
, size
);
2151 static int parse_crtime(le64_t le
, usec_t
*usec
) {
2157 if (u
== 0 || u
== (uint64_t) -1)
2164 int fd_getcrtime(int fd
, usec_t
*usec
) {
2171 /* Until Linux gets a real concept of birthtime/creation time,
2172 * let's fake one with xattrs */
2174 n
= fgetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
));
2177 if (n
!= sizeof(le
))
2180 return parse_crtime(le
, usec
);
2183 int fd_getcrtime_at(int dirfd
, const char *name
, usec_t
*usec
, int flags
) {
2187 n
= fgetxattrat_fake(dirfd
, name
, "user.crtime_usec", &le
, sizeof(le
), flags
);
2190 if (n
!= sizeof(le
))
2193 return parse_crtime(le
, usec
);
2196 int path_getcrtime(const char *p
, usec_t
*usec
) {
2203 n
= getxattr(p
, "user.crtime_usec", &le
, sizeof(le
));
2206 if (n
!= sizeof(le
))
2209 return parse_crtime(le
, usec
);
2212 int fd_setcrtime(int fd
, usec_t usec
) {
2218 usec
= now(CLOCK_REALTIME
);
2220 le
= htole64((uint64_t) usec
);
2221 if (fsetxattr(fd
, "user.crtime_usec", &le
, sizeof(le
), 0) < 0)
2227 int chattr_fd(int fd
, unsigned value
, unsigned mask
) {
2228 unsigned old_attr
, new_attr
;
2233 if (fstat(fd
, &st
) < 0)
2236 /* Explicitly check whether this is a regular file or
2237 * directory. If it is anything else (such as a device node or
2238 * fifo), then the ioctl will not hit the file systems but
2239 * possibly drivers, where the ioctl might have different
2240 * effects. Notably, DRM is using the same ioctl() number. */
2242 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
2248 if (ioctl(fd
, FS_IOC_GETFLAGS
, &old_attr
) < 0)
2251 new_attr
= (old_attr
& ~mask
) | (value
& mask
);
2252 if (new_attr
== old_attr
)
2255 if (ioctl(fd
, FS_IOC_SETFLAGS
, &new_attr
) < 0)
2261 int chattr_path(const char *p
, unsigned value
, unsigned mask
) {
2262 _cleanup_close_
int fd
= -1;
2269 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
2273 return chattr_fd(fd
, value
, mask
);
2276 int read_attr_fd(int fd
, unsigned *ret
) {
2281 if (fstat(fd
, &st
) < 0)
2284 if (!S_ISDIR(st
.st_mode
) && !S_ISREG(st
.st_mode
))
2287 if (ioctl(fd
, FS_IOC_GETFLAGS
, ret
) < 0)
2293 int read_attr_path(const char *p
, unsigned *ret
) {
2294 _cleanup_close_
int fd
= -1;
2299 fd
= open(p
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
2303 return read_attr_fd(fd
, ret
);
2306 int syslog_parse_priority(const char **p
, int *priority
, bool with_facility
) {
2307 int a
= 0, b
= 0, c
= 0;
2317 if (!strchr(*p
, '>'))
2320 if ((*p
)[2] == '>') {
2321 c
= undecchar((*p
)[1]);
2323 } else if ((*p
)[3] == '>') {
2324 b
= undecchar((*p
)[1]);
2325 c
= undecchar((*p
)[2]);
2327 } else if ((*p
)[4] == '>') {
2328 a
= undecchar((*p
)[1]);
2329 b
= undecchar((*p
)[2]);
2330 c
= undecchar((*p
)[3]);
2335 if (a
< 0 || b
< 0 || c
< 0 ||
2336 (!with_facility
&& (a
|| b
|| c
> 7)))
2340 *priority
= a
*100 + b
*10 + c
;
2342 *priority
= (*priority
& LOG_FACMASK
) | c
;
2348 ssize_t
string_table_lookup(const char * const *table
, size_t len
, const char *key
) {
2354 for (i
= 0; i
< len
; ++i
)
2355 if (streq_ptr(table
[i
], key
))
2361 int rename_noreplace(int olddirfd
, const char *oldpath
, int newdirfd
, const char *newpath
) {
2365 ret
= renameat2(olddirfd
, oldpath
, newdirfd
, newpath
, RENAME_NOREPLACE
);
2369 /* renameat2() exists since Linux 3.15, btrfs added support for it later.
2370 * If it is not implemented, fallback to another method. */
2371 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
2374 /* The link()/unlink() fallback does not work on directories. But
2375 * renameat() without RENAME_NOREPLACE gives the same semantics on
2376 * directories, except when newpath is an *empty* directory. This is
2378 ret
= fstatat(olddirfd
, oldpath
, &buf
, AT_SYMLINK_NOFOLLOW
);
2379 if (ret
>= 0 && S_ISDIR(buf
.st_mode
)) {
2380 ret
= renameat(olddirfd
, oldpath
, newdirfd
, newpath
);
2381 return ret
>= 0 ? 0 : -errno
;
2384 /* If it is not a directory, use the link()/unlink() fallback. */
2385 ret
= linkat(olddirfd
, oldpath
, newdirfd
, newpath
, 0);
2389 ret
= unlinkat(olddirfd
, oldpath
, 0);
2391 /* backup errno before the following unlinkat() alters it */
2393 (void) unlinkat(newdirfd
, newpath
, 0);
2401 int getxattr_malloc(const char *path
, const char *name
, char **value
, bool allow_symlink
) {
2410 for (l
= 100; ; l
= (size_t) n
+ 1) {
2416 n
= lgetxattr(path
, name
, v
, l
);
2418 n
= getxattr(path
, name
, v
, l
);
2420 if (n
>= 0 && (size_t) n
< l
) {
2427 if (n
< 0 && errno
!= ERANGE
)
2431 n
= lgetxattr(path
, name
, NULL
, 0);
2433 n
= getxattr(path
, name
, NULL
, 0);
2439 int fgetxattr_malloc(int fd
, const char *name
, char **value
) {
2448 for (l
= 100; ; l
= (size_t) n
+ 1) {
2453 n
= fgetxattr(fd
, name
, v
, l
);
2455 if (n
>= 0 && (size_t) n
< l
) {
2462 if (n
< 0 && errno
!= ERANGE
)
2465 n
= fgetxattr(fd
, name
, NULL
, 0);
2472 puts(PACKAGE_STRING
"\n"
2477 bool fdname_is_valid(const char *s
) {
2480 /* Validates a name for $LISTEN_FDNAMES. We basically allow
2481 * everything ASCII that's not a control character. Also, as
2482 * special exception the ":" character is not allowed, as we
2483 * use that as field separator in $LISTEN_FDNAMES.
2485 * Note that the empty string is explicitly allowed
2486 * here. However, we limit the length of the names to 255
2492 for (p
= s
; *p
; p
++) {
2504 bool oom_score_adjust_is_valid(int oa
) {
2505 return oa
>= OOM_SCORE_ADJ_MIN
&& oa
<= OOM_SCORE_ADJ_MAX
;