util.c revision 6afc95b73605833e6e966af1c466b5c08feb953f
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2010 Lennart Poettering
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
systemd is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <syslog.h>
#include <sched.h>
#include <sys/resource.h>
#include <fcntl.h>
#include <dirent.h>
#include <termios.h>
#include <stdarg.h>
#include <ctype.h>
#include <pwd.h>
#include <dlfcn.h>
#include <glob.h>
#include <grp.h>
#include <limits.h>
#include <langinfo.h>
#include <locale.h>
#include <sys/personality.h>
#include <libgen.h>
#ifdef HAVE_SYS_AUXV_H
#endif
#include "macro.h"
#include "util.h"
#include "ioprio.h"
#include "missing.h"
#include "log.h"
#include "strv.h"
#include "label.h"
#include "path-util.h"
#include "exit-status.h"
#include "hashmap.h"
#include "env-util.h"
#include "fileio.h"
#include "device-nodes.h"
#include "utf8.h"
#include "gunicode.h"
#include "virt.h"
#include "def.h"
int saved_argc = 0;
char **saved_argv = NULL;
static volatile unsigned cached_columns = 0;
static volatile unsigned cached_lines = 0;
long r;
return pgsz;
r = sysconf(_SC_PAGESIZE);
assert(r > 0);
return pgsz;
}
bool streq_ptr(const char *a, const char *b) {
/* Like streq(), but tries to make sense of NULL pointers */
if (a && b)
return streq(a, b);
if (!a && !b)
return true;
return false;
}
assert(s);
if (pl == 0)
return (char*) s + sl;
return NULL;
return NULL;
}
bool first_word(const char *s, const char *word) {
assert(s);
return false;
if (wl == 0)
return true;
return false;
return s[wl] == 0 ||
}
int close_nointr(int fd) {
int r;
/* Just ignore EINTR; a retry loop is the wrong
* thing to do on Linux.
*
*/
return 0;
else if (r >= 0)
return r;
else
return -errno;
}
void close_nointr_nofail(int fd) {
/* like close_nointr() but cannot fail, and guarantees errno
* is unchanged */
}
unsigned i;
for (i = 0; i < n_fd; i++)
close_nointr_nofail(fds[i]);
}
int unlink_noerrno(const char *path) {
int r;
if (r < 0)
return -errno;
return 0;
}
int parse_boolean(const char *v) {
assert(v);
if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
return 1;
else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
return 0;
return -EINVAL;
}
unsigned long ul = 0;
int r;
assert(s);
r = safe_atolu(s, &ul);
if (r < 0)
return r;
return -ERANGE;
if (pid <= 0)
return -ERANGE;
return 0;
}
unsigned long ul = 0;
int r;
assert(s);
r = safe_atolu(s, &ul);
if (r < 0)
return r;
return -ERANGE;
return 0;
}
char *x = NULL;
unsigned long l;
assert(s);
errno = 0;
l = strtoul(s, &x, 0);
if (!x || x == s || *x || errno)
if ((unsigned long) (unsigned) l != l)
return -ERANGE;
*ret_u = (unsigned) l;
return 0;
}
char *x = NULL;
long l;
assert(s);
errno = 0;
l = strtol(s, &x, 0);
if (!x || x == s || *x || errno)
if ((long) (int) l != l)
return -ERANGE;
*ret_i = (int) l;
return 0;
}
int safe_atollu(const char *s, long long unsigned *ret_llu) {
char *x = NULL;
unsigned long long l;
assert(s);
errno = 0;
l = strtoull(s, &x, 0);
if (!x || x == s || *x || errno)
*ret_llu = l;
return 0;
}
int safe_atolli(const char *s, long long int *ret_lli) {
char *x = NULL;
long long l;
assert(s);
errno = 0;
l = strtoll(s, &x, 0);
if (!x || x == s || *x || errno)
*ret_lli = l;
return 0;
}
char *x = NULL;
double d = 0;
assert(s);
errno = 0;
d = strtod(s, &x);
}
if (!x || x == s || *x || errno)
*ret_d = (double) d;
return 0;
}
bool escaped = false;
size_t n;
for (n=0; s[n]; n++) {
if (escaped)
escaped = false;
else if (s[n] == '\\')
escaped = true;
return n;
}
return n;
}
/* Split a string into words. */
char *current;
if (!*current || *c == 0)
return NULL;
if (!*current)
return NULL;
} else if (quoted) {
} else {
}
return (char*) current;
}
int r;
long unsigned ppid;
const char *p;
if (pid == 0) {
return 0;
}
r = read_one_line_file(p, &line);
if (r < 0)
return r;
/* Let's skip the pid and comm fields. The latter is enclosed
* in () but does not escape any () in its value, so let's
* skip over it manually */
if (!p)
return -EIO;
p++;
if (sscanf(p, " "
"%*c " /* state */
"%lu ", /* ppid */
&ppid) != 1)
return -EIO;
return -ERANGE;
return 0;
}
int r;
const char *p;
r = read_one_line_file(p, &line);
if (r < 0)
return r;
/* Let's skip the pid and comm fields. The latter is enclosed
* in () but does not escape any () in its value, so let's
* skip over it manually */
if (!p)
return -EIO;
p++;
if (sscanf(p, " "
"%*c " /* state */
"%*d " /* ppid */
"%*d " /* pgrp */
"%*d " /* session */
"%*d " /* tty_nr */
"%*d " /* tpgid */
"%*u " /* flags */
"%*u " /* minflt */
"%*u " /* cminflt */
"%*u " /* majflt */
"%*u " /* cmajflt */
"%*u " /* utime */
"%*u " /* stime */
"%*d " /* cutime */
"%*d " /* cstime */
"%*d " /* priority */
"%*d " /* nice */
"%*d " /* num_threads */
"%*d " /* itrealvalue */
"%llu " /* starttime */,
st) != 1)
return -EIO;
return 0;
}
mode_t u;
int r;
u = umask(0777);
umask(u);
return r;
}
char *truncate_nl(char *s) {
assert(s);
return s;
}
const char *p;
char state;
int r;
r = read_one_line_file(p, &line);
if (r < 0)
return r;
if (!p)
return -EIO;
p++;
return -EIO;
return (unsigned char) state;
}
const char *p;
int r;
r = read_one_line_file(p, name);
if (r == -ENOENT)
return -ESRCH;
return r;
}
char *r = NULL, *k;
const char *p;
int c;
f = fopen(p, "re");
if (!f)
return -errno;
if (max_length == 0) {
free(r);
return -ENOMEM;
}
}
if (len > 0)
r[len-1] = 0;
} else {
bool space = false;
r = new(char, max_length);
if (!r)
return -ENOMEM;
k = r;
left = max_length;
if (isprint(c)) {
if (space) {
if (left <= 4)
break;
*(k++) = ' ';
left--;
space = false;
}
if (left <= 4)
break;
*(k++) = (char) c;
left--;
} else
space = true;
}
if (left <= 4) {
memcpy(k, "...", n);
k[n] = 0;
} else
*k = 0;
}
/* Kernel threads have no argv[] */
if (r == NULL || r[0] == 0) {
_cleanup_free_ char *t = NULL;
int h;
free(r);
if (!comm_fallback)
return -ENOENT;
h = get_process_comm(pid, &t);
if (h < 0)
return h;
if (!r)
return -ENOMEM;
}
*line = r;
return 0;
}
const char *p;
char c;
bool eof;
FILE *f;
if (pid == 0)
return 0;
f = fopen(p, "re");
if (!f)
return -errno;
fclose(f);
/* Kernel threads have an empty cmdline */
if (count <= 0)
return 0;
}
const char *p;
}
const char *p;
char *d;
int r;
r = readlink_malloc(p, name);
if (r < 0)
if (d)
*d = '\0';
return 0;
}
const char *p;
if (pid == 0)
return getuid();
f = fopen(p, "re");
if (!f)
return -errno;
char *l;
if (startswith(l, field)) {
l += strspn(l, WHITESPACE);
l[strcspn(l, WHITESPACE)] = 0;
}
}
return -EIO;
}
}
}
size_t a;
char *r;
if (!s && !suffix)
return strdup("");
if (!s)
if (!suffix)
return strdup(s);
assert(s);
a = strlen(s);
if (b > ((size_t) -1) - a)
return NULL;
r = new(char, a+b+1);
if (!r)
return NULL;
memcpy(r, s, a);
r[a+b] = 0;
return r;
}
}
int readlink_malloc(const char *p, char **ret) {
size_t l = 100;
int r;
assert(p);
for (;;) {
char *c;
ssize_t n;
c = new(char, l);
if (!c)
return -ENOMEM;
n = readlink(p, c, l-1);
if (n < 0) {
r = -errno;
free(c);
return r;
}
if ((size_t) n < l-1) {
c[n] = 0;
*ret = c;
return 0;
}
free(c);
l *= 2;
}
}
int readlink_and_make_absolute(const char *p, char **r) {
char *k;
int j;
assert(p);
assert(r);
j = readlink_malloc(p, &target);
if (j < 0)
return j;
k = file_in_same_dir(p, target);
if (!k)
return -ENOMEM;
*r = k;
return 0;
}
int readlink_and_canonicalize(const char *p, char **r) {
char *t, *s;
int j;
assert(p);
assert(r);
j = readlink_and_make_absolute(p, &t);
if (j < 0)
return j;
s = canonicalize_file_name(t);
if (s) {
free(t);
*r = s;
} else
*r = t;
path_kill_slashes(*r);
return 0;
}
int reset_all_signal_handlers(void) {
int sig;
.sa_handler = SIG_DFL,
.sa_flags = SA_RESTART,
};
continue;
/* On Linux the first two RT signals are reserved by
* glibc, and sigaction() will return EINVAL for them. */
return -errno;
}
return 0;
}
char *strstrip(char *s) {
char *e;
/* Drops trailing whitespace. Modifies the string in
* place. Returns pointer to first non-space character */
s += strspn(s, WHITESPACE);
for (e = strchr(s, 0); e > s; e --)
break;
*e = 0;
return s;
}
char *delete_chars(char *s, const char *bad) {
char *f, *t;
/* Drops all whitespace, regardless where in the string */
for (f = s, t = s; *f; f++) {
continue;
*(t++) = *f;
}
*t = 0;
return s;
}
bool in_charset(const char *s, const char* charset) {
const char *i;
assert(s);
for (i = s; *i; i++)
return false;
return true;
}
char *e, *r;
size_t k;
/* This removes the last component of path and appends
* filename, unless the latter is absolute anyway or the
* former isn't */
if (path_is_absolute(filename))
return NULL;
return r;
}
size_t l;
int r = 0;
/* Skip trailing slashes */
l--;
while (l > 0) {
char *t;
/* Skip last component */
l--;
/* Skip trailing slashes */
l--;
if (l <= 0)
break;
return -ENOMEM;
if (path_startswith(stop, t)) {
free(t);
return 0;
}
r = rmdir(t);
free(t);
if (r < 0)
return -errno;
}
return 0;
}
char hexchar(int x) {
return table[x & 15];
}
int unhexchar(char c) {
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return -1;
}
char *r, *z;
const uint8_t *x;
if (!r)
return NULL;
for (x = p; x < (const uint8_t*) p + l; x++) {
*(z++) = hexchar(*x >> 4);
*(z++) = hexchar(*x & 15);
}
*z = 0;
return r;
}
uint8_t *r, *z;
const char *x;
assert(p);
if (!r)
return NULL;
for (x = p; x < p + l; x += 2) {
int a, b;
a = unhexchar(x[0]);
if (x+1 < p + l)
b = unhexchar(x[1]);
else
b = 0;
}
*z = 0;
return r;
}
char octchar(int x) {
return '0' + (x & 7);
}
int unoctchar(char c) {
if (c >= '0' && c <= '7')
return c - '0';
return -1;
}
char decchar(int x) {
return '0' + (x % 10);
}
int undecchar(char c) {
if (c >= '0' && c <= '9')
return c - '0';
return -1;
}
char *cescape(const char *s) {
char *r, *t;
const char *f;
assert(s);
/* Does C style string escaping. */
if (!r)
return NULL;
for (f = s, t = r; *f; f++)
switch (*f) {
case '\a':
*(t++) = '\\';
*(t++) = 'a';
break;
case '\b':
*(t++) = '\\';
*(t++) = 'b';
break;
case '\f':
*(t++) = '\\';
*(t++) = 'f';
break;
case '\n':
*(t++) = '\\';
*(t++) = 'n';
break;
case '\r':
*(t++) = '\\';
*(t++) = 'r';
break;
case '\t':
*(t++) = '\\';
*(t++) = 't';
break;
case '\v':
*(t++) = '\\';
*(t++) = 'v';
break;
case '\\':
*(t++) = '\\';
*(t++) = '\\';
break;
case '"':
*(t++) = '\\';
*(t++) = '"';
break;
case '\'':
*(t++) = '\\';
*(t++) = '\'';
break;
default:
/* For special chars we prefer octal over
* hexadecimal encoding, simply because glib's
* g_strescape() does the same */
if ((*f < ' ') || (*f >= 127)) {
*(t++) = '\\';
*(t++) = octchar((unsigned char) *f >> 6);
*(t++) = octchar((unsigned char) *f >> 3);
*(t++) = octchar((unsigned char) *f);
} else
*(t++) = *f;
break;
}
*t = 0;
return r;
}
char *r, *t;
const char *f;
assert(s);
/* Undoes C style string escaping, and optionally prefixes it. */
if (!r)
return r;
if (prefix)
if (*f != '\\') {
*(t++) = *f;
continue;
}
f++;
switch (*f) {
case 'a':
*(t++) = '\a';
break;
case 'b':
*(t++) = '\b';
break;
case 'f':
*(t++) = '\f';
break;
case 'n':
*(t++) = '\n';
break;
case 'r':
*(t++) = '\r';
break;
case 't':
*(t++) = '\t';
break;
case 'v':
*(t++) = '\v';
break;
case '\\':
*(t++) = '\\';
break;
case '"':
*(t++) = '"';
break;
case '\'':
*(t++) = '\'';
break;
case 's':
/* This is an extension of the XDG syntax files */
*(t++) = ' ';
break;
case 'x': {
/* hexadecimal encoding */
int a, b;
a = unhexchar(f[1]);
b = unhexchar(f[2]);
if (a < 0 || b < 0) {
/* Invalid escape code, let's take it literal then */
*(t++) = '\\';
*(t++) = 'x';
} else {
*(t++) = (char) ((a << 4) | b);
f += 2;
}
break;
}
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7': {
/* octal encoding */
int a, b, c;
a = unoctchar(f[0]);
b = unoctchar(f[1]);
c = unoctchar(f[2]);
if (a < 0 || b < 0 || c < 0) {
/* Invalid escape code, let's take it literal then */
*(t++) = '\\';
*(t++) = f[0];
} else {
*(t++) = (char) ((a << 6) | (b << 3) | c);
f += 2;
}
break;
}
case 0:
/* premature end of string.*/
*(t++) = '\\';
goto finish;
default:
/* Invalid escape code, let's take it literal then */
*(t++) = '\\';
*(t++) = *f;
break;
}
}
*t = 0;
return r;
}
}
char *cunescape(const char *s) {
assert(s);
return cunescape_length(s, strlen(s));
}
char *r, *t;
const char *f;
/* Escapes all chars in bad, in addition to \ and all special
* chars, in \xFF style escaping. May be reversed with
* cunescape. */
if (!r)
return NULL;
for (f = s, t = r; *f; f++) {
if ((*f < ' ') || (*f >= 127) ||
*(t++) = '\\';
*(t++) = 'x';
*(t++) = hexchar(*f >> 4);
*(t++) = hexchar(*f);
} else
*(t++) = *f;
}
*t = 0;
return r;
}
char *ascii_strlower(char *t) {
char *p;
assert(t);
for (p = t; *p; p++)
if (*p >= 'A' && *p <= 'Z')
*p = *p - 'A' + 'a';
return t;
}
return
filename[0] == '.' ||
}
bool ignore_file(const char *filename) {
return false;
return ignore_file_allow_backup(filename);
}
int flags;
return -errno;
if (nonblock)
flags |= O_NONBLOCK;
else
flags &= ~O_NONBLOCK;
return -errno;
return 0;
}
int flags;
return -errno;
if (cloexec)
flags |= FD_CLOEXEC;
else
flags &= ~FD_CLOEXEC;
return -errno;
return 0;
}
unsigned i;
for (i = 0; i < n_fdset; i++)
return true;
return false;
}
DIR *d;
int r = 0;
if (!d) {
int fd;
/* When /proc isn't available (for example in chroots)
* the fallback is brute forcing through the fd
* table */
continue;
if (close_nointr(fd) < 0)
r = -errno;
}
return r;
}
int fd = -1;
continue;
/* Let's better ignore this, just in case */
continue;
if (fd < 3)
continue;
continue;
continue;
if (close_nointr(fd) < 0) {
/* Valgrind has its own FD and doesn't want to have it closed */
r = -errno;
}
}
closedir(d);
return r;
}
bool chars_intersect(const char *a, const char *b) {
const char *p;
/* Returns true if any of the chars in a are in b. */
for (p = a; *p; p++)
if (strchr(b, *p))
return true;
return false;
}
bool fstype_is_network(const char *fstype) {
static const char table[] =
"cifs\0"
"smbfs\0"
"ncpfs\0"
"ncp\0"
"nfs\0"
"nfs4\0"
"gfs\0"
"gfs2\0";
}
_cleanup_close_ int fd;
if (fd < 0)
return -errno;
if (vt < 0) {
int tiocl[2] = {
0
};
return -errno;
}
return -errno;
return 0;
}
char c;
assert(f);
size_t k;
if (t != (usec_t) -1) {
return -ETIMEDOUT;
}
}
if (k <= 0)
return -EIO;
if (need_nl)
*need_nl = c != '\n';
*ret = c;
return 0;
}
}
if (t != (usec_t) -1)
return -ETIMEDOUT;
return -EIO;
return -EBADMSG;
if (need_nl)
*need_nl = false;
return 0;
}
for (;;) {
char c;
int r;
bool need_nl = true;
if (on_tty())
if (on_tty())
if (r < 0) {
if (r == -EBADMSG) {
puts("Bad input, please try again.");
continue;
}
putchar('\n');
return r;
}
if (need_nl)
putchar('\n');
*ret = c;
return 0;
}
puts("Read unexpected character, please try again.");
}
}
int r = 0;
/* Set terminal to some sane defaults */
/* We leave locked terminal attributes untouched, so that
* Plymouth may set whatever it wants to set, and we don't
* interfere with that. */
/* Disable exclusive mode, just in case */
/* Switch to text mode */
if (switch_to_text)
/* Enable console unicode mode */
r = -errno;
goto finish;
}
/* We only reset the stuff that matters to the software. How
* hardware is set up we don't touch assuming that somebody
* else will do that for us */
r = -errno;
/* Just in case, flush all crap out */
return r;
}
int reset_terminal(const char *name) {
int fd, r;
if (fd < 0)
return fd;
r = reset_terminal_fd(fd, true);
return r;
}
int fd, r;
unsigned c = 0;
/*
* If a TTY is in the process of being closed opening it might
* cause EIO. This is horribly awful, but unlikely to be
* changed in the kernel. Hence we work around this problem by
* retrying a couple of times.
*
*/
for (;;) {
if (fd >= 0)
break;
return -errno;
/* Max 1s in total */
if (c >= 20)
return -errno;
c++;
}
if (fd < 0)
return -errno;
if (r < 0) {
return -errno;
}
if (!r) {
return -ENOTTY;
}
return fd;
}
};
for (;;) {
ssize_t l;
int r;
if (r < 0) {
continue;
return -errno;
} else if (r == 0)
return 0;
if (l < 0) {
continue;
return 0;
return -errno;
} else if (l == 0)
return 0;
}
}
int acquire_terminal(
const char *name,
bool fail,
bool force,
bool ignore_tiocstty_eperm,
/* We use inotify to be notified when the tty is closed. We
* create the watch before checking if we can actually acquire
* it, so that we don't lose any event.
*
* Note: strictly speaking this actually watches for the
* device being closed, it does *not* really watch whether a
* tty loses its controlling process. However, unless some
* its tty otherwise this will not become a problem. As long
* as the administrator makes sure not configure any service
* on the same tty as an untrusted user this should not be a
* problem. (Which he probably should not do anyway.) */
if (notify < 0) {
r = -errno;
goto fail;
}
if (wd < 0) {
r = -errno;
goto fail;
}
}
for (;;) {
.sa_handler = SIG_IGN,
.sa_flags = SA_RESTART,
};
if (notify >= 0) {
if (r < 0)
goto fail;
}
/* We pass here O_NOCTTY only so that we can check the return
* value TIOCSCTTY and have a reliable way to figure out if we
* successfully became the controlling process of the tty */
if (fd < 0)
return fd;
/* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
* if we already own the tty. */
/* First, try to get the tty */
r = -errno;
/* Sometimes it makes sense to ignore TIOCSCTTY
* returning EPERM, i.e. when very likely we already
* are have this controlling terminal. */
if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
r = 0;
goto fail;
}
if (r >= 0)
break;
for (;;) {
ssize_t l;
struct inotify_event *e;
usec_t n;
n = now(CLOCK_MONOTONIC);
r = -ETIMEDOUT;
goto fail;
}
if (r < 0)
goto fail;
if (r == 0) {
r = -ETIMEDOUT;
goto fail;
}
}
if (l < 0) {
continue;
r = -errno;
goto fail;
}
e = (struct inotify_event*) inotify_buffer;
while (l > 0) {
r = -EIO;
goto fail;
}
l -= step;
}
break;
}
/* We close the tty fd here since if the old session
* ended our handle will be dead. It's important that
* we do this after sleeping, so that we don't enter
* an endless loop. */
}
if (notify >= 0)
r = reset_terminal_fd(fd, true);
if (r < 0)
return fd;
fail:
if (fd >= 0)
if (notify >= 0)
return r;
}
int release_terminal(void) {
int r = 0;
.sa_handler = SIG_IGN,
.sa_flags = SA_RESTART,
};
_cleanup_close_ int fd;
if (fd < 0)
return -errno;
/* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
* by our own TIOCNOTTY */
r = -errno;
return r;
}
int r = 0, sig;
r = -errno;
return r;
}
int ignore_signals(int sig, ...) {
.sa_handler = SIG_IGN,
.sa_flags = SA_RESTART,
};
int r = 0;
r = -errno;
r = -errno;
return r;
}
int default_signals(int sig, ...) {
.sa_handler = SIG_DFL,
.sa_flags = SA_RESTART,
};
int r = 0;
r = -errno;
r = -errno;
return r;
}
int close_pipe(int p[]) {
int a = 0, b = 0;
assert(p);
if (p[0] >= 0) {
a = close_nointr(p[0]);
p[0] = -1;
}
if (p[1] >= 0) {
b = close_nointr(p[1]);
p[1] = -1;
}
return a < 0 ? a : b;
}
ssize_t n = 0;
while (nbytes > 0) {
ssize_t k;
continue;
/* We knowingly ignore any return value here,
* via read() */
continue;
}
if (k <= 0)
return n > 0 ? n : (k < 0 ? -errno : 0);
p += k;
nbytes -= k;
n += k;
}
return n;
}
ssize_t n = 0;
while (nbytes > 0) {
ssize_t k;
continue;
/* We knowingly ignore any return value here,
* via write() */
continue;
}
if (k <= 0)
return n > 0 ? n : (k < 0 ? -errno : 0);
p += k;
nbytes -= k;
n += k;
}
return n;
}
static const struct {
const char *suffix;
unsigned long long factor;
} table[] = {
{ "B", 1 },
{ "K", 1024ULL },
{ "M", 1024ULL*1024ULL },
{ "G", 1024ULL*1024ULL*1024ULL },
{ "T", 1024ULL*1024ULL*1024ULL*1024ULL },
{ "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
{ "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
{ "", 1 },
};
const char *p;
unsigned long long r = 0;
assert(t);
p = t;
do {
long long l;
char *e;
unsigned i;
errno = 0;
l = strtoll(p, &e, 10);
if (errno > 0)
return -errno;
if (l < 0)
return -ERANGE;
if (e == p)
return -EINVAL;
e += strspn(e, WHITESPACE);
for (i = 0; i < ELEMENTSOF(table); i++)
unsigned long long tmp;
return -ERANGE;
if (tmp > ULLONG_MAX - r)
return -ERANGE;
r += tmp;
if ((unsigned long long) (off_t) r != r)
return -ERANGE;
break;
}
if (i >= ELEMENTSOF(table))
return -EINVAL;
} while (*p);
*bytes = r;
return 0;
}
int make_stdio(int fd) {
int r, s, t;
if (fd >= 3)
if (r < 0 || s < 0 || t < 0)
return -errno;
/* We rely here that the new fd has O_CLOEXEC not set */
return 0;
}
int make_null_stdio(void) {
int null_fd;
if (null_fd < 0)
return -errno;
return make_stdio(null_fd);
}
bool is_device_path(const char *path) {
/* Returns true on paths that refer to a device, either in
* sysfs or in /dev */
return
}
int dir_is_empty(const char *path) {
if (!d)
return -errno;
for (;;) {
errno = 0;
return -errno;
if (!de)
return 1;
return 0;
}
}
char* dirname_malloc(const char *path) {
if (!d)
return NULL;
if (dir != d) {
free(d);
return dir2;
}
return dir;
}
int dev_urandom(void *p, size_t n) {
_cleanup_close_ int fd;
ssize_t k;
if (fd < 0)
if (k < 0)
return (int) k;
if ((size_t) k != n)
return -EIO;
return 0;
}
void random_bytes(void *p, size_t n) {
static bool srand_called = false;
uint8_t *q;
int r;
r = dev_urandom(p, n);
if (r >= 0)
return;
* get a PRNG instead. */
if (!srand_called) {
unsigned x = 0;
#ifdef HAVE_SYS_AUXV_H
/* The kernel provides us with a bit of entropy in
* auxv, so let's try to make use of that to seed the
* pseudo-random generator. It's better than
* nothing... */
void *auxv;
if (auxv)
x ^= *(unsigned*) auxv;
#endif
x ^= (unsigned) now(CLOCK_REALTIME);
x ^= (unsigned) gettid();
srand(x);
srand_called = true;
}
for (q = p; q < (uint8_t*) p + n; q ++)
*q = rand();
}
/* This is a like a poor man's setproctitle(). It changes the
* comm field, argv[0], and also the glibc's internally used
* name of the process. For the first one a limit of 16 chars
* applies, to the second one usually one of 10 (i.e. length
* "systemd"). If you pass a longer string it will be
* truncated */
if (saved_argc > 0) {
int i;
if (saved_argv[0])
for (i = 1; i < saved_argc; i++) {
if (!saved_argv[i])
break;
}
}
}
int sig;
}
char* gethostname_malloc(void) {
struct utsname u;
}
bool hostname_is_set(void) {
struct utsname u;
}
long bufsize;
char *name;
/* Shortcut things to avoid NSS lookups */
if (uid == 0)
return strdup("root");
if (bufsize <= 0)
bufsize = 4096;
if (!buf)
return NULL;
return NULL;
return name;
}
char* getlogname_malloc(void) {
else
return lookup_uid(uid);
}
char *getusername_malloc(void) {
const char *e;
e = getenv("USER");
if (e)
return strdup(e);
return lookup_uid(getuid());
}
int getttyname_malloc(int fd, char **r) {
int k;
assert(r);
if (k > 0)
return -k;
if (!c)
return -ENOMEM;
*r = c;
return 0;
}
int getttyname_harder(int fd, char **r) {
int k;
char *s;
k = getttyname_malloc(fd, &s);
if (k < 0)
return k;
if (streq(s, "tty")) {
free(s);
}
*r = s;
return 0;
}
int r;
const char *p;
unsigned long ttynr;
r = read_one_line_file(p, &line);
if (r < 0)
return r;
if (!p)
return -EIO;
p++;
if (sscanf(p, " "
"%*c " /* state */
"%*d " /* ppid */
"%*d " /* pgrp */
"%*d " /* session */
"%lu ", /* ttynr */
&ttynr) != 1)
return -EIO;
return -ENOENT;
if (d)
return 0;
}
int k;
assert(r);
if (k < 0)
return k;
k = readlink_malloc(fn, &s);
if (k < 0) {
if (k != -ENOENT)
return k;
/* This is an ugly hack */
return -ENOMEM;
*r = b;
if (_devnr)
return 0;
}
/* Probably something like the ptys which have no
* vaguely useful. */
if (!b)
return -ENOMEM;
*r = b;
if (_devnr)
return 0;
}
if (startswith(s, "/dev/"))
p = s + 5;
else if (startswith(s, "../"))
p = s + 3;
else
p = s;
b = strdup(p);
free(s);
if (!b)
return -ENOMEM;
*r = b;
if (_devnr)
return 0;
}
DIR *d;
int ret = 0;
/* This returns the first error we run into, but nevertheless
* tries to go on. This closes the passed fd. */
if (!d) {
}
for (;;) {
bool is_dir, keep_around;
int r;
errno = 0;
if (ret == 0)
break;
}
if (!de)
break;
continue;
continue;
}
} else {
keep_around = false;
}
if (is_dir) {
int subdir_fd;
/* if root_dev is set, remove subdirectories only, if device is same as dir */
continue;
if (subdir_fd < 0) {
continue;
}
if (r < 0 && ret == 0)
ret = r;
if (!keep_around)
}
} else if (!only_dirs && !keep_around) {
}
}
}
closedir(d);
return ret;
}
assert(s);
}
struct statfs s;
return -errno;
}
/* We refuse to clean disk file systems with this call. This
* is extra paranoia just to be sure we never ever remove
* non-state data */
if (!is_temporary_fs(&s)) {
log_error("Attempted to remove disk file system, and we can't allow that.");
return -EPERM;
}
}
static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
int fd, r;
struct statfs s;
/* We refuse to clean the root file system with this
* call. This is extra paranoia to never cause a really
* seriously broken system. */
log_error("Attempted to remove entire root file system, and we can't allow that.");
return -EPERM;
}
if (fd < 0) {
return -errno;
if (!dangerous) {
return -errno;
if (!is_temporary_fs(&s)) {
log_error("Attempted to remove disk file system, and we can't allow that.");
return -EPERM;
}
}
if (delete_root && !only_dirs)
return -errno;
return 0;
}
if (!dangerous) {
return -errno;
}
if (!is_temporary_fs(&s)) {
log_error("Attempted to remove disk file system, and we can't allow that.");
return -EPERM;
}
}
if (delete_root) {
return r;
if (r == 0)
r = -errno;
}
}
return r;
}
}
}
/* Under the assumption that we are running privileged we
* first change the access mode and only then hand out
* ownership to avoid a window where access is too open. */
return -errno;
return -errno;
return 0;
}
/* Under the assumption that we are running privileged we
* first change the access mode and only then hand out
* ownership to avoid a window where access is too open. */
return -errno;
return -errno;
return 0;
}
cpu_set_t *r;
unsigned n = 1024;
/* Allocates the cpuset in the right size */
for (;;) {
if (!(r = CPU_ALLOC(n)))
return NULL;
if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
if (ncpus)
*ncpus = n;
return r;
}
CPU_FREE(r);
return NULL;
n *= 2;
}
}
int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
_cleanup_free_ char *s = NULL;
int n = 0;
static bool prev_ephemeral;
/* This is independent of logging, as status messages are
* optional and go exclusively to the console. */
return log_oom();
if (fd < 0)
return fd;
if (ellipse) {
char *e;
int c;
c = fd_columns(fd);
if (c <= 0)
c = 80;
if (emax < 3)
emax = 3;
if (e) {
free(s);
s = e;
}
}
if (prev_ephemeral)
if (status) {
} else
}
IOVEC_SET_STRING(iovec[n++], s);
if (!ephemeral)
return -errno;
return 0;
}
int r;
return r;
}
enum {
WORD,
char *r = NULL, *k;
for (e = format; *e; e ++) {
switch (state) {
case WORD:
if (*e == '$')
break;
case CURLY:
if (*e == '{') {
goto fail;
free(r);
r = k;
word = e-1;
} else if (*e == '$') {
goto fail;
free(r);
r = k;
word = e+1;
} else
break;
case VARIABLE:
if (*e == '}') {
const char *t;
k = strappend(r, t);
if (!k)
goto fail;
free(r);
r = k;
word = e+1;
}
break;
}
}
goto fail;
free(r);
return k;
fail:
free(r);
return NULL;
}
char **r, **i;
unsigned k = 0, l = 0;
l = strv_length(argv);
if (!(r = new(char*, l+1)))
return NULL;
STRV_FOREACH(i, argv) {
/* If $FOO appears as single word, replace it by the split up variable */
if ((*i)[0] == '$' && (*i)[1] != '{') {
char *e;
char **w, **m;
unsigned q;
if (e) {
if (!(m = strv_split_quoted(e))) {
r[k] = NULL;
strv_free(r);
return NULL;
}
} else
m = NULL;
q = strv_length(m);
l = l + q - 1;
if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
r[k] = NULL;
strv_free(r);
strv_free(m);
return NULL;
}
r = w;
if (m) {
memcpy(r + k, m, q * sizeof(char*));
free(m);
}
k += q;
continue;
}
/* If ${FOO} appears as part of a word, replace it by the variable as-is */
if (!(r[k++] = replace_env(*i, env))) {
strv_free(r);
return NULL;
}
}
r[k] = NULL;
return r;
}
int fd_columns(int fd) {
return -errno;
return -EIO;
}
unsigned columns(void) {
const char *e;
int c;
if (_likely_(cached_columns > 0))
return cached_columns;
c = 0;
e = getenv("COLUMNS");
if (e)
safe_atoi(e, &c);
if (c <= 0)
c = fd_columns(STDOUT_FILENO);
if (c <= 0)
c = 80;
cached_columns = c;
return c;
}
return -errno;
return -EIO;
}
unsigned lines(void) {
const char *e;
unsigned l;
if (_likely_(cached_lines > 0))
return cached_lines;
l = 0;
e = getenv("LINES");
if (e)
safe_atou(e, &l);
if (l <= 0)
l = fd_lines(STDOUT_FILENO);
if (l <= 0)
l = 24;
cached_lines = l;
return cached_lines;
}
/* intended to be used as a SIGWINCH sighandler */
void columns_lines_cache_reset(int signum) {
cached_columns = 0;
cached_lines = 0;
}
bool on_tty(void) {
static int cached_on_tty = -1;
if (_unlikely_(cached_on_tty < 0))
return cached_on_tty;
}
int running_in_chroot(void) {
struct stat a = {}, b = {};
/* Only works as root */
if (stat("/proc/1/root", &a) < 0)
return -errno;
if (stat("/", &b) < 0)
return -errno;
return
}
static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
size_t x;
char *r;
assert(s);
return strndup(s, old_length);
if (!r)
return NULL;
if (x > new_length - 3)
x = new_length - 3;
memcpy(r, s, x);
r[x] = '.';
r[x+1] = '.';
r[x+2] = '.';
memcpy(r + x + 3,
new_length - x - 3);
return r;
}
size_t x;
char *e;
const char *i, *j;
assert(s);
/* if no multibyte characters use ascii_ellipsize_mem for speed */
if (ascii_is_valid(s))
return strndup(s, old_length);
if (x > new_length - 3)
x = new_length - 3;
k = 0;
for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
int c;
c = utf8_encoded_to_unichar(i);
if (c < 0)
return NULL;
}
if (k > x) /* last character was wide and went over quota */
x ++;
for (j = s + old_length; k < new_length && j > i; ) {
int c;
j = utf8_prev_char(j);
c = utf8_encoded_to_unichar(j);
if (c < 0)
return NULL;
}
assert(i <= j);
/* we don't actually need to ellipsize */
if (i == j)
/* make space for ellipsis */
j = utf8_next_char(j);
len = i - s;
len2 = s + old_length - j;
if (!e)
return NULL;
/*
printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
old_length, new_length, x, len, len2, k);
*/
return e;
}
}
int fd;
/* This just opens the file for writing, ensuring it
* does it. */
if (fd < 0)
return -errno;
return 0;
}
size_t l;
assert(s);
/* This is rather stupid, simply removes the heading and
* trailing quotes if there is one. Doesn't care about
* escaping or anything. We should make this smarter one
* day...*/
l = strlen(s);
if (l < 2)
return strdup(s);
return strdup(s);
}
char *normalize_env_assignment(const char *s) {
char *eq, *r;
if (!eq) {
char *t;
r = strdup(s);
if (!r)
return NULL;
t = strstrip(r);
if (t == r)
return r;
return r;
}
if (!name)
return NULL;
if (!p)
return NULL;
if (!value)
return NULL;
r = NULL;
return r;
}
if (!status)
for (;;) {
continue;
return -errno;
}
return 0;
}
}
int r;
if (r < 0) {
return r;
}
}
return 0;
return -EPROTO;
}
return -EPROTO;
}
/* Make sure nobody waits for us on a socket anymore */
close_all_fds(NULL, 0);
sync();
for (;;)
pause();
}
return true;
return true;
return false;
}
int null_or_empty_path(const char *fn) {
return -errno;
return null_or_empty(&st);
}
int nfd;
DIR *d;
if (nfd < 0)
return NULL;
if (!d) {
return NULL;
}
return d;
}
int signal_from_string_try_harder(const char *s) {
int signo;
assert(s);
signo = signal_from_string(s);
if (signo <= 0)
if (startswith(s, "SIG"))
return signal_from_string(s+3);
return signo;
}
char *dn;
if (u == NULL)
return NULL;
if (t == NULL)
return NULL;
if (encode_devnode_name(u, t, enc_len) < 0)
return NULL;
return NULL;
return dn;
}
char *fstab_node_to_udev_node(const char *p) {
assert(p);
if (startswith(p, "LABEL="))
if (startswith(p, "UUID="))
if (startswith(p, "PARTUUID="))
if (startswith(p, "PARTLABEL="))
return strdup(p);
}
tty += 5;
return vtnr_from_tty(tty) >= 0;
}
bool tty_is_console(const char *tty) {
tty += 5;
}
int vtnr_from_tty(const char *tty) {
int i, r;
tty += 5;
return -EINVAL;
return -EINVAL;
if (r < 0)
return r;
if (i < 0 || i > 63)
return -EINVAL;
return i;
}
char *resolve_dev_console(char **active) {
char *tty;
* (i.e. not read-only-mounted which is a sign for container setups) */
if (path_is_read_only_fs("/sys") > 0)
return NULL;
return NULL;
/* If multiple log outputs are configured the last one is what
if (tty)
tty++;
else
char *tmp;
/* Get the active VC (e.g. tty1) */
}
}
return tty;
}
bool tty_is_vc_resolve(const char *tty) {
tty += 5;
if (!tty)
return false;
}
}
const char *default_term_for_tty(const char *tty) {
}
return false;
return false;
return true;
}
return false;
return false;
}
/* Executes all binaries in a directory in parallel and
* waits for them to finish. */
if (!d) {
return;
return;
}
d = _d;
}
log_error("Failed to allocate set.");
goto finish;
}
char *path;
int k;
if (!dirent_is_file(de))
continue;
log_oom();
continue;
}
log_error("Failed to fork: %m");
continue;
}
if (pid == 0) {
char *_argv[2];
/* Child */
if (!argv) {
} else
}
}
}
while (!hashmap_isempty(pids)) {
char *path;
continue;
log_error("waitid() failed: %m");
goto finish;
}
else
} else
}
}
if (_d)
if (pids)
}
int r;
if (r >= 0)
return r;
}
const char *i;
if (!nulstr)
return false;
NULSTR_FOREACH(i, nulstr)
return true;
return false;
}
bool plymouth_running(void) {
}
char* strshorten(char *s, size_t l) {
assert(s);
if (l < strlen(s))
s[l] = 0;
return s;
}
static bool hostname_valid_char(char c) {
return
(c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
c == '-' ||
c == '_' ||
c == '.';
}
bool hostname_is_valid(const char *s) {
const char *p;
bool dot;
if (isempty(s))
return false;
for (p = s, dot = true; *p; p++) {
if (*p == '.') {
if (dot)
return false;
dot = true;
} else {
if (!hostname_valid_char(*p))
return false;
dot = false;
}
}
if (dot)
return false;
if (p-s > HOST_NAME_MAX)
return false;
return true;
}
char* hostname_cleanup(char *s, bool lowercase) {
char *p, *d;
bool dot;
for (p = s, d = s, dot = true; *p; p++) {
if (*p == '.') {
if (dot)
continue;
*(d++) = '.';
dot = true;
} else if (hostname_valid_char(*p)) {
dot = false;
}
}
if (dot && d > s)
d[-1] = 0;
else
*d = 0;
strshorten(s, HOST_NAME_MAX);
return s;
}
};
int r;
if (r < 0)
return -errno;
if (r == 0)
return 0;
}
};
int r;
if (r < 0)
return -errno;
if (r == 0)
return 0;
}
FILE *f;
char *t;
const char *fn;
size_t k;
int fd;
if (!t)
return -ENOMEM;
t[k] = '.';
if (fd < 0) {
free(t);
return -errno;
}
if (!f) {
unlink(t);
free(t);
return -errno;
}
*_f = f;
*_temp_path = t;
return 0;
}
int terminal_vhangup_fd(int fd) {
return -errno;
return 0;
}
int terminal_vhangup(const char *name) {
int fd, r;
if (fd < 0)
return fd;
r = terminal_vhangup_fd(fd);
return r;
}
int vt_disallocate(const char *name) {
int fd, r;
unsigned u;
/* Deallocate the VT if possible. If not possible
* (i.e. because it is the active one), at least clear it
* entirely (including the scrollback buffer) */
return -EINVAL;
/* So this is not a VT. I guess we cannot deallocate
* it then. But let's at least clear the screen */
if (fd < 0)
return fd;
"\033[r" /* clear scrolling region */
"\033[H" /* move home */
"\033[2J", /* clear screen */
10, false);
return 0;
}
return -EINVAL;
if (r < 0)
return r;
if (u <= 0)
return -EINVAL;
/* Try to deallocate */
if (fd < 0)
return fd;
if (r >= 0)
return 0;
return -errno;
/* Couldn't deallocate, so let's clear it fully with
* scrollback */
if (fd < 0)
return fd;
"\033[r" /* clear scrolling region */
"\033[H" /* move home */
"\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
10, false);
return 0;
}
int r, fdt;
if (fdf < 0)
return -errno;
if (fdt < 0)
return -errno;
for (;;) {
ssize_t n, k;
if (n < 0) {
r = -errno;
return r;
}
if (n == 0)
break;
errno = 0;
if (n != k) {
return r;
}
}
r = close_nointr(fdt);
if (r < 0) {
return r;
}
return 0;
}
char *x;
_cleanup_free_ char *t;
const char *fn;
size_t k;
uint64_t u;
unsigned i;
int r;
if (!t)
return -ENOMEM;
t[k] = '.';
u = random_u64();
for (i = 0; i < 16; i++) {
*(x++) = hexchar(u & 0xF);
u >>= 4;
}
*x = 0;
return -errno;
r = -errno;
unlink(t);
return r;
}
return 0;
}
bool display_is_local(const char *display) {
return
display[0] == ':' &&
}
size_t k;
char *f, *c;
if (!display_is_local(display))
return -EINVAL;
f = new(char, sizeof("/tmp/.X11-unix/X") + k);
if (!f)
return -ENOMEM;
c = stpcpy(f, "/tmp/.X11-unix/X");
c[k] = 0;
*path = f;
return 0;
}
int get_user_creds(
const char **username,
const char **home,
const char **shell) {
struct passwd *p;
uid_t u;
/* We enforce some special rules for uid=0: in order to avoid
* NSS lookups for root we hardcode its data. */
*username = "root";
if (uid)
*uid = 0;
if (gid)
*gid = 0;
if (home)
*home = "/root";
if (shell)
return 0;
}
errno = 0;
p = getpwuid(u);
/* If there are multiple users with the same id, make
* sure to leave $USER to the configured value instead
* of the first occurrence in the database. However if
* the uid was configured by a numeric uid, then let's
if (p)
} else {
errno = 0;
}
if (!p)
if (uid)
if (gid)
if (home)
if (shell)
return 0;
}
struct passwd *p;
char *r;
if (uid == 0)
return strdup("root");
if (p)
return NULL;
return r;
}
struct group *p;
char *r;
if (gid == 0)
return strdup("root");
if (p)
return NULL;
return r;
}
struct group *g;
/* We enforce some special rules for gid=0: in order to avoid
* NSS lookups for root we hardcode its data. */
*groupname = "root";
if (gid)
*gid = 0;
return 0;
}
errno = 0;
if (g)
} else {
errno = 0;
}
if (!g)
if (gid)
return 0;
}
int ngroups_max, r, i;
return 1;
return 1;
assert(ngroups_max > 0);
if (r < 0)
return -errno;
for (i = 0; i < r; i++)
return 1;
return 0;
}
int r;
if (r < 0)
return r;
}
int glob_exists(const char *path) {
_cleanup_globfree_ glob_t g = {};
int k;
errno = 0;
if (k == GLOB_NOMATCH)
return 0;
else if (k == GLOB_NOSPACE)
return -ENOMEM;
else if (k == 0)
return !strv_isempty(g.gl_pathv);
else
}
_cleanup_globfree_ glob_t g = {};
int k;
char **p;
errno = 0;
if (k == GLOB_NOMATCH)
return -ENOENT;
else if (k == GLOB_NOSPACE)
return -ENOMEM;
else if (k != 0 || strv_isempty(g.gl_pathv))
STRV_FOREACH(p, g.gl_pathv) {
k = strv_extend(strv, *p);
if (k < 0)
break;
}
return k;
}
assert(d);
return 0;
return -errno;
return 0;
}
char **i;
int r;
if (r < 0)
return r;
STRV_FOREACH(i, search)
if (path_equal(parent, *i))
return 1;
return 0;
}
_cleanup_strv_free_ char **l = NULL;
/* Returns all files in a directory in *list, and the number
* of files as return value. If list is NULL returns only the
* number. */
if (!d)
return -errno;
for (;;) {
errno = 0;
return -errno;
if (!de)
break;
dirent_ensure_type(d, de);
if (!dirent_is_file(de))
continue;
if (list) {
/* one extra slot is needed for the terminating NULL */
return -ENOMEM;
if (!l[n])
return -ENOMEM;
l[++n] = NULL;
} else
n++;
}
if (list) {
*list = l;
l = NULL; /* avoid freeing */
}
return n;
}
char *strjoin(const char *x, ...) {
size_t l;
char *r, *p;
if (x) {
l = strlen(x);
for (;;) {
const char *t;
size_t n;
if (!t)
break;
n = strlen(t);
if (n > ((size_t) -1) - l) {
return NULL;
}
l += n;
}
} else
l = 0;
r = new(char, l+1);
if (!r)
return NULL;
if (x) {
p = stpcpy(r, x);
for (;;) {
const char *t;
if (!t)
break;
p = stpcpy(p, t);
}
} else
r[0] = 0;
return r;
}
bool is_main_thread(void) {
static thread_local int cached = 0;
if (_unlikely_(cached == 0))
return cached > 0;
}
char *p, *s;
int r;
unsigned n, m;
/* If it has a queue this is good enough for us */
return -ENOMEM;
free(p);
if (r >= 0) {
*ret = d;
return 0;
}
/* If it is a partition find the originating device */
return -ENOMEM;
free(p);
if (r < 0)
return -ENOENT;
/* Get parent dev_t */
return -ENOMEM;
r = read_one_line_file(p, &s);
free(p);
if (r < 0)
return r;
r = sscanf(s, "%u:%u", &m, &n);
free(s);
if (r != 2)
return -EINVAL;
/* Only return this if it is really good enough for us. */
return -ENOMEM;
free(p);
if (r >= 0) {
return 0;
}
return -ENOENT;
}
int file_is_priv_sticky(const char *p) {
assert(p);
return -errno;
return
}
static const char *const ioprio_class_table[] = {
[IOPRIO_CLASS_NONE] = "none",
[IOPRIO_CLASS_RT] = "realtime",
[IOPRIO_CLASS_BE] = "best-effort",
[IOPRIO_CLASS_IDLE] = "idle"
};
static const char *const sigchld_code_table[] = {
[CLD_EXITED] = "exited",
[CLD_KILLED] = "killed",
[CLD_DUMPED] = "dumped",
[CLD_TRAPPED] = "trapped",
[CLD_STOPPED] = "stopped",
[CLD_CONTINUED] = "continued",
};
static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
};
static const char *const log_level_table[] = {
[LOG_EMERG] = "emerg",
[LOG_ALERT] = "alert",
[LOG_CRIT] = "crit",
[LOG_ERR] = "err",
[LOG_WARNING] = "warning",
[LOG_NOTICE] = "notice",
[LOG_INFO] = "info",
[LOG_DEBUG] = "debug"
};
static const char* const sched_policy_table[] = {
[SCHED_OTHER] = "other",
[SCHED_BATCH] = "batch",
[SCHED_IDLE] = "idle",
[SCHED_FIFO] = "fifo",
[SCHED_RR] = "rr"
};
static const char* const rlimit_table[] = {
[RLIMIT_CPU] = "LimitCPU",
[RLIMIT_FSIZE] = "LimitFSIZE",
[RLIMIT_DATA] = "LimitDATA",
[RLIMIT_STACK] = "LimitSTACK",
[RLIMIT_CORE] = "LimitCORE",
[RLIMIT_RSS] = "LimitRSS",
[RLIMIT_NOFILE] = "LimitNOFILE",
[RLIMIT_AS] = "LimitAS",
[RLIMIT_NPROC] = "LimitNPROC",
[RLIMIT_MEMLOCK] = "LimitMEMLOCK",
[RLIMIT_LOCKS] = "LimitLOCKS",
[RLIMIT_SIGPENDING] = "LimitSIGPENDING",
[RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
[RLIMIT_NICE] = "LimitNICE",
[RLIMIT_RTPRIO] = "LimitRTPRIO",
[RLIMIT_RTTIME] = "LimitRTTIME"
};
DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
static const char* const ip_tos_table[] = {
[IPTOS_LOWDELAY] = "low-delay",
[IPTOS_THROUGHPUT] = "throughput",
[IPTOS_RELIABILITY] = "reliability",
[IPTOS_LOWCOST] = "low-cost",
};
static const char *const __signal_table[] = {
[SIGHUP] = "HUP",
[SIGINT] = "INT",
[SIGQUIT] = "QUIT",
[SIGILL] = "ILL",
[SIGTRAP] = "TRAP",
[SIGABRT] = "ABRT",
[SIGBUS] = "BUS",
[SIGFPE] = "FPE",
[SIGKILL] = "KILL",
[SIGUSR1] = "USR1",
[SIGSEGV] = "SEGV",
[SIGUSR2] = "USR2",
[SIGPIPE] = "PIPE",
[SIGALRM] = "ALRM",
[SIGTERM] = "TERM",
#ifdef SIGSTKFLT
#endif
[SIGCHLD] = "CHLD",
[SIGCONT] = "CONT",
[SIGSTOP] = "STOP",
[SIGTSTP] = "TSTP",
[SIGTTIN] = "TTIN",
[SIGTTOU] = "TTOU",
[SIGURG] = "URG",
[SIGXCPU] = "XCPU",
[SIGXFSZ] = "XFSZ",
[SIGVTALRM] = "VTALRM",
[SIGPROF] = "PROF",
[SIGWINCH] = "WINCH",
[SIGIO] = "IO",
[SIGPWR] = "PWR",
[SIGSYS] = "SYS"
};
const char *signal_to_string(int signo) {
const char *name;
if (name)
return name;
else
return buf;
}
int signal_from_string(const char *s) {
int signo;
int offset = 0;
unsigned u;
signo = __signal_from_string(s);
if (signo > 0)
return signo;
if (startswith(s, "RTMIN+")) {
s += 6;
}
if (safe_atou(s, &u) >= 0) {
return signo;
}
return -1;
}
bool kexec_loaded(void) {
bool loaded = false;
char *s;
if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
if (s[0] == '1')
loaded = true;
free(s);
}
return loaded;
}
int strdup_or_null(const char *a, char **b) {
char *c;
assert(b);
if (!a) {
*b = NULL;
return 0;
}
c = strdup(a);
if (!c)
return -ENOMEM;
*b = c;
return 0;
}
int prot_from_flags(int flags) {
case O_RDONLY:
return PROT_READ;
case O_WRONLY:
return PROT_WRITE;
case O_RDWR:
return PROT_READ|PROT_WRITE;
default:
return -EINVAL;
}
}
unsigned i;
static const struct {
const char *suffix;
} table[] = {
{ "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
{ "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
{ "T", 1024ULL*1024ULL*1024ULL*1024ULL },
{ "G", 1024ULL*1024ULL*1024ULL },
{ "M", 1024ULL*1024ULL },
{ "K", 1024ULL },
};
for (i = 0; i < ELEMENTSOF(table); i++) {
"%llu.%llu%s",
goto finish;
}
}
buf[l-1] = 0;
return buf;
}
void *r;
assert(p);
r = malloc(l);
if (!r)
return NULL;
memcpy(r, p, l);
return r;
}
int r, value;
return 0;
/* If we have the privileges we will ignore the kernel limit. */
value = (int) n;
return -errno;
return 1;
}
int r, value;
return 0;
/* If we have the privileges we will ignore the kernel limit. */
value = (int) n;
return -errno;
return 1;
}
int fd;
bool stdout_is_tty, stderr_is_tty;
unsigned n, i;
char **l;
parent_pid = getpid();
/* Spawns a temporary TTY agent, making sure it goes away when
* we go away */
if (agent_pid < 0)
return -errno;
if (agent_pid != 0) {
return 0;
}
/* In the child:
*
* Make sure the agent goes away when the parent dies */
/* Check whether our parent died before we were able
* to set the death signal */
if (getppid() != parent_pid)
/* Don't leak fds to the agent */
if (!stdout_is_tty || !stderr_is_tty) {
* ensure that when systemctl is started via
* popen() or a similar call that expects to
* read EOF we actually do generate EOF and
* not delay this indefinitely by because we
* keep an unused copy of stdin around. */
if (fd < 0) {
}
if (!stdout_is_tty)
if (!stderr_is_tty)
if (fd > 2)
}
/* Count arguments */
;
/* Allocate strv */
l = alloca(sizeof(char *) * (n + 1));
/* Fill in arguments */
for (i = 0; i <= n; i++)
}
return 0;
return -errno;
/* So we failed to set the desired setrlimit, then let's try
* to get as close as we can */
return -errno;
return 0;
}
int r;
bool done = false;
size_t l;
const char *path;
if (!f)
return -errno;
r = 0;
do {
unsigned i;
for (i = 0; i < sizeof(line)-1; i++) {
int c;
c = getc(f);
if (_unlikely_(c == EOF)) {
done = true;
break;
} else if (c == 0)
break;
line[i] = c;
}
line[i] = 0;
if (!value)
return -ENOMEM;
r = 1;
break;
}
} while (!done);
return r;
}
bool is_valid_documentation_url(const char *url) {
return true;
return true;
return true;
return true;
return true;
return false;
}
bool in_initrd(void) {
static int saved = -1;
struct statfs s;
if (saved >= 0)
return saved;
/* We make two checks here:
*
* 1. the flag file /etc/initrd-release must exist
* 2. the root file system must be a memory file system
*
* The second check is extra paranoia, since misdetecting an
* initrd can have bad bad consequences due the initrd
* emptying when transititioning to the main systemd.
*/
statfs("/", &s) >= 0 &&
is_temporary_fs(&s);
return saved;
}
void warn_melody(void) {
if (fd < 0)
return;
/* Yeah, this is synchronous. Kinda sucks. But well... */
}
int make_console_stdio(void) {
int fd, r;
if (fd < 0) {
return fd;
}
r = make_stdio(fd);
if (r < 0) {
return r;
}
return 0;
}
int get_home_dir(char **_h) {
struct passwd *p;
const char *e;
char *h;
uid_t u;
/* Take the user specified one */
e = getenv("HOME");
if (e) {
h = strdup(e);
if (!h)
return -ENOMEM;
*_h = h;
return 0;
}
/* Hardcode home directory for root to avoid NSS */
u = getuid();
if (u == 0) {
h = strdup("/root");
if (!h)
return -ENOMEM;
*_h = h;
return 0;
}
/* Check the database... */
errno = 0;
p = getpwuid(u);
if (!p)
if (!path_is_absolute(p->pw_dir))
return -EINVAL;
if (!h)
return -ENOMEM;
*_h = h;
return 0;
}
struct passwd *p;
const char *e;
char *s;
uid_t u;
/* Take the user specified one */
e = getenv("SHELL");
if (e) {
s = strdup(e);
if (!s)
return -ENOMEM;
*_s = s;
return 0;
}
/* Hardcode home directory for root to avoid NSS */
u = getuid();
if (u == 0) {
if (!s)
return -ENOMEM;
*_s = s;
return 0;
}
/* Check the database... */
errno = 0;
p = getpwuid(u);
if (!p)
if (!path_is_absolute(p->pw_shell))
return -EINVAL;
if (!s)
return -ENOMEM;
*_s = s;
return 0;
}
bool filename_is_safe(const char *p) {
if (isempty(p))
return false;
if (strchr(p, '/'))
return false;
if (streq(p, "."))
return false;
if (streq(p, ".."))
return false;
if (strlen(p) > FILENAME_MAX)
return false;
return true;
}
bool string_is_safe(const char *p) {
const char *t;
assert(p);
for (t = p; *t; t++) {
if (*t > 0 && *t < ' ')
return false;
if (strchr("\\\"\'", *t))
return false;
}
return true;
}
/**
* Check if a string contains control characters.
* Spaces and tabs are not considered control characters.
*/
bool string_has_cc(const char *p) {
const char *t;
assert(p);
for (t = p; *t; t++)
if (*t > 0 && *t < ' ' && *t != '\t')
return true;
return false;
}
bool path_is_safe(const char *p) {
if (isempty(p))
return false;
return false;
return false;
/* The following two checks are not really dangerous, but hey, they still are confusing */
return false;
if (strstr(p, "//"))
return false;
return true;
}
/* hey glibc, APIs with callbacks without a user pointer are so useless */
const void *p;
int comparison;
l = 0;
u = nmemb;
while (l < u) {
idx = (l + u) / 2;
if (comparison < 0)
u = idx;
else if (comparison > 0)
l = idx + 1;
else
return (void *)p;
}
return NULL;
}
bool is_locale_utf8(void) {
const char *set;
static int cached_answer = -1;
if (cached_answer >= 0)
goto out;
cached_answer = true;
goto out;
}
if (!set) {
cached_answer = true;
goto out;
}
cached_answer = true;
goto out;
}
/* For LC_CTYPE=="C" return true, because CTYPE is effectly
* unset and everything can do to UTF-8 nowadays. */
if (!set) {
cached_answer = true;
goto out;
}
/* Check result, but ignore the result if C was set
* explicitly. */
!getenv("LC_ALL") &&
!getenv("LC_CTYPE") &&
!getenv("LANG");
out:
return (bool) cached_answer;
}
/* UTF-8 */ {
},
/* ASCII fallback */ {
[DRAW_TREE_VERT] = "| ",
[DRAW_TREE_BRANCH] = "|-",
[DRAW_TREE_RIGHT] = "`-",
[DRAW_TREE_SPACE] = " ",
[DRAW_TRIANGULAR_BULLET] = "> ",
[DRAW_BLACK_CIRCLE] = "* ",
}
};
}
const char *f;
char *t, *r;
r = new(char, l+1);
if (!r)
return NULL;
f = text;
t = r;
while (*f) {
char *a;
if (!startswith(f, old_string)) {
*(t++) = *(f++);
continue;
}
d = t - r;
if (!a)
goto oom;
l = nl;
r = a;
t = r + d;
t = stpcpy(t, new_string);
f += old_len;
}
*t = 0;
return r;
oom:
free(r);
return NULL;
}
enum {
} state = STATE_OTHER;
FILE *f;
/* Strips ANSI color and replaces TABs by 8 spaces */
if (!f)
return NULL;
switch (state) {
case STATE_OTHER:
break;
else if (*i == '\x1B')
else if (*i == '\t')
fputs(" ", f);
else
fputc(*i, f);
break;
case STATE_ESCAPE:
fputc('\x1B', f);
break;
} else if (*i == '[') {
begin = i + 1;
} else {
fputc('\x1B', f);
fputc(*i, f);
state = STATE_OTHER;
}
break;
case STATE_BRACKET:
(!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
fputc('\x1B', f);
fputc('[', f);
state = STATE_OTHER;
i = begin-1;
} else if (*i == 'm')
state = STATE_OTHER;
break;
}
}
if (ferror(f)) {
fclose(f);
return NULL;
}
fclose(f);
if (_isz)
return obuf;
}
int on_ac_power(void) {
bool found_offline = false, found_online = false;
d = opendir("/sys/class/power_supply");
if (!d)
return -errno;
for (;;) {
char contents[6];
ssize_t n;
errno = 0;
return -errno;
if (!de)
break;
continue;
if (device < 0) {
continue;
return -errno;
}
if (fd < 0) {
continue;
return -errno;
}
if (n < 0)
return -errno;
continue;
if (fd < 0) {
continue;
return -errno;
}
if (n < 0)
return -errno;
return -EIO;
if (contents[0] == '1') {
found_online = true;
break;
} else if (contents[0] == '0')
found_offline = true;
else
return -EIO;
}
return found_online || !found_offline;
}
static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
char **i;
return -ENOMEM;
STRV_FOREACH(i, search) {
_cleanup_free_ char *p = NULL;
FILE *f;
if (!p)
return -ENOMEM;
if (f) {
*_f = f;
return 0;
}
return -errno;
}
return -ENOENT;
}
if (path_is_absolute(path)) {
FILE *f;
if (f) {
*_f = f;
return 0;
}
return -errno;
}
if (!copy)
return -ENOMEM;
}
_cleanup_strv_free_ char **s = NULL;
if (path_is_absolute(path)) {
FILE *f;
if (f) {
*_f = f;
return 0;
}
return -errno;
}
s = strv_split_nulstr(search);
if (!s)
return -ENOMEM;
}
char *strextend(char **x, ...) {
size_t f, l;
char *r, *p;
assert(x);
l = f = *x ? strlen(*x) : 0;
for (;;) {
const char *t;
size_t n;
if (!t)
break;
n = strlen(t);
if (n > ((size_t) -1) - l) {
return NULL;
}
l += n;
}
r = realloc(*x, l+1);
if (!r)
return NULL;
p = r + f;
for (;;) {
const char *t;
if (!t)
break;
p = stpcpy(p, t);
}
*p = 0;
*x = r;
return r + l;
}
char *strrep(const char *s, unsigned n) {
size_t l;
char *r, *p;
unsigned i;
assert(s);
l = strlen(s);
p = r = malloc(l * n + 1);
if (!r)
return NULL;
for (i = 0; i < n; i++)
p = stpcpy(p, s);
*p = 0;
return r;
}
size_t a;
void *q;
assert(p);
return *p;
/* check for overflows */
if (a < need)
return NULL;
q = realloc(*p, a);
if (!q)
return NULL;
*p = q;
*allocated = a;
return q;
}
uint8_t *q;
assert(p);
if (!q)
return NULL;
return q;
}
bool id128_is_valid(const char *s) {
size_t i, l;
l = strlen(s);
if (l == 32) {
/* Simple formatted 128bit hex string */
for (i = 0; i < l; i++) {
char c = s[i];
if (!(c >= '0' && c <= '9') &&
!(c >= 'a' && c <= 'z') &&
!(c >= 'A' && c <= 'Z'))
return false;
}
} else if (l == 36) {
/* Formatted UUID */
for (i = 0; i < l; i++) {
char c = s[i];
if ((i == 8 || i == 13 || i == 18 || i == 23)) {
if (c != '-')
return false;
} else {
if (!(c >= '0' && c <= '9') &&
!(c >= 'a' && c <= 'z') &&
!(c >= 'A' && c <= 'Z'))
return false;
}
}
} else
return false;
return true;
}
int split_pair(const char *s, const char *sep, char **l, char **r) {
char *x, *a, *b;
assert(s);
assert(l);
assert(r);
return -EINVAL;
if (!x)
return -EINVAL;
a = strndup(s, x - s);
if (!a)
return -ENOMEM;
if (!b) {
free(a);
return -ENOMEM;
}
*l = a;
*r = b;
return 0;
}
int shall_restore_state(void) {
_cleanup_free_ char *line;
char *w, *state;
size_t l;
int r;
r = proc_cmdline(&line);
if (r < 0)
return r;
if (r == 0) /* Container ... */
return 1;
return 0;
return 1;
}
int proc_cmdline(char **ret) {
int r;
if (detect_container(NULL) > 0) {
char *buf, *p;
if (r < 0)
return r;
if (*p == 0)
*p = ' ';
*p = 0;
return 1;
}
if (r < 0)
return r;
return 1;
}
char *w, *state;
size_t l;
int r;
r = proc_cmdline(&line);
if (r < 0)
if (r <= 0)
return 0;
_cleanup_free_ char *word;
if (!word)
return log_oom();
r = parse_word(word);
if (r < 0) {
return r;
}
}
return 0;
}
const char *p;
int r;
if (r == -ENOENT)
return -EHOSTDOWN;
if (r < 0)
return r;
if (!s)
return -EIO;
return -EIO;
if (r < 0)
return r;
if (leader <= 1)
return -EIO;
return 0;
}
int rfd;
if (mntnsfd < 0)
return -errno;
if (pidnsfd < 0)
return -errno;
if (rfd < 0)
return -errno;
pidnsfd = -1;
mntnsfd = -1;
return 0;
}
return -errno;
return -errno;
return -errno;
if (chroot(".") < 0)
return -errno;
if (setresgid(0, 0, 0) < 0)
return -errno;
if (setresuid(0, 0, 0) < 0)
return -errno;
return 0;
}
/* Checks whether a PID is still valid at all, including a zombie */
if (pid <= 0)
return false;
return true;
}
int r;
/* Checks whether a PID is still valid and not a zombie */
if (pid <= 0)
return false;
r = get_process_state(pid);
if (r == -ENOENT || r == 'Z')
return false;
return true;
}
struct ucred u;
int r;
if (r < 0)
return -errno;
if (n != sizeof(struct ucred))
return -EIO;
/* Check if the data is actually useful and not suppressed due
* to namespacing issues */
if (u.pid <= 0)
return -ENODATA;
*ucred = u;
return 0;
}
socklen_t n = 64;
char *s;
int r;
s = new0(char, n);
if (!s)
return -ENOMEM;
if (r < 0) {
free(s);
return -errno;
s = new0(char, n);
if (!s)
return -ENOMEM;
if (r < 0) {
free(s);
return -errno;
}
}
if (isempty(s)) {
free(s);
return -ENOTSUP;
}
*ret = s;
return 0;
}
/* This is much like like mkostemp() but is subject to umask(). */
int fd;
u = umask(077);
if (fd < 0)
return -errno;
return fd;
}
char *p;
int fd;
#ifdef O_TMPFILE
/* Try O_TMPFILE first, if it is supported */
if (fd >= 0)
return fd;
#endif
/* Fall back to unguessable name + unlinking */
if (fd < 0)
return fd;
unlink(p);
return fd;
}
return -errno;
log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
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);
return 0;
}
unsigned long parse_personality(const char *p) {
/* Parse a personality specifier. We introduce our own
* identifiers that indicate specific ABIs, rather than just
* hints regarding the register size, since we want to keep
* things open for multiple locally supported ABIs for the
* same register size. We try to reuse the ABI identifiers
* used by libseccomp. */
#if defined(__x86_64__)
if (streq(p, "x86"))
return PER_LINUX32;
if (streq(p, "x86-64"))
return PER_LINUX;
if (streq(p, "x86"))
return PER_LINUX;
#endif
/* personality(7) documents that 0xffffffffUL is used for
* querying the current personality, hence let's use that here
* as error indicator. */
return 0xffffffffUL;
}