util.c revision ce5b3ad4508fa6d561fcccff0852afaace1d82ac
/*-*- 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 <string.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h>
#include <libintl.h>
#include <stdio.h>
#include <syslog.h>
#include <sched.h>
#include <sys/resource.h>
#include <fcntl.h>
#include <dirent.h>
#include <stdarg.h>
#include <poll.h>
#include <ctype.h>
#include <pwd.h>
#include <glob.h>
#include <grp.h>
#include <limits.h>
#include <langinfo.h>
#include <locale.h>
#include <sys/personality.h>
/* When we include libgen.h because we need dirname() we immediately
* undefine basename() since libgen.h defines it as a macro to the XDG
* version which is really broken. */
#include <libgen.h>
#ifdef HAVE_SYS_AUXV_H
#endif
#include "config.h"
#include "macro.h"
#include "util.h"
#include "ioprio.h"
#include "missing.h"
#include "log.h"
#include "strv.h"
#include "mkdir.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"
#include "sparse-endian.h"
#include "formats-util.h"
#include "process-util.h"
#include "random-util.h"
#include "terminal-util.h"
/* Put this test here for a lack of better place */
int saved_argc = 0;
char **saved_argv = NULL;
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;
}
char* first_word(const char *s, const char *word) {
const char *p;
assert(s);
/* Checks if the string starts with the specified word, either
* followed by NUL or by whitespace. Returns a pointer to the
* NUL or the first character after the whitespace. */
return NULL;
if (wl == 0)
return (char*) s;
return NULL;
p = s + wl;
if (*p == 0)
return (char*) p;
if (!strchr(WHITESPACE, *p))
return NULL;
p += strspn(p, WHITESPACE);
return (char*) p;
}
switch (c) {
case '\a':
*(buf++) = '\\';
*(buf++) = 'a';
break;
case '\b':
*(buf++) = '\\';
*(buf++) = 'b';
break;
case '\f':
*(buf++) = '\\';
*(buf++) = 'f';
break;
case '\n':
*(buf++) = '\\';
*(buf++) = 'n';
break;
case '\r':
*(buf++) = '\\';
*(buf++) = 'r';
break;
case '\t':
*(buf++) = '\\';
*(buf++) = 't';
break;
case '\v':
*(buf++) = '\\';
*(buf++) = 'v';
break;
case '\\':
*(buf++) = '\\';
*(buf++) = '\\';
break;
case '"':
*(buf++) = '\\';
*(buf++) = '"';
break;
case '\'':
*(buf++) = '\\';
*(buf++) = '\'';
break;
default:
/* For special chars we prefer octal over
* hexadecimal encoding, simply because glib's
* g_strescape() does the same */
if ((c < ' ') || (c >= 127)) {
*(buf++) = '\\';
} else
*(buf++) = c;
break;
}
}
int close_nointr(int fd) {
return 0;
/*
* Just ignore EINTR; a retry loop is the wrong thing to do on
* Linux.
*
*/
return 0;
return -errno;
}
int safe_close(int fd) {
/*
* Like close_nointr() but cannot fail. Guarantees errno is
* unchanged. Is a NOP with negative fds passed, and returns
* -1, so that it can be used in this syntax:
*
* fd = safe_close(fd);
*/
if (fd >= 0) {
/* The kernel might return pretty much any error code
* via close(), but the fd will be closed anyway. The
* only condition we want to check for here is whether
* the fd was invalid at all... */
}
return -1;
}
unsigned i;
for (i = 0; i < n_fd; i++)
safe_close(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") || strcaseeq(v, "yes") || strcaseeq(v, "y") || strcaseeq(v, "true") || strcaseeq(v, "t") || strcaseeq(v, "on"))
return 1;
else if (streq(v, "0") || strcaseeq(v, "no") || strcaseeq(v, "n") || strcaseeq(v, "false") || strcaseeq(v, "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;
/* Some libc APIs use UID_INVALID as special placeholder */
return -ENXIO;
/* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
return -ENXIO;
if (ret_uid)
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;
}
char *x = NULL;
unsigned long l;
assert(s);
errno = 0;
l = strtoul(s, &x, 0);
if (!x || x == s || *x || errno)
if ((unsigned long) (uint8_t) l != l)
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) (uint16_t) l != l)
return -ERANGE;
return 0;
}
char *x = NULL;
long l;
assert(s);
errno = 0;
l = strtol(s, &x, 0);
if (!x || x == s || *x || errno)
if ((long) (int16_t) l != l)
return -ERANGE;
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);
return -errno;
errno = 0;
if (!x || x == s || *x || errno) {
}
*ret_d = (double) d;
return 0;
}
bool escaped = false;
int n;
for (n=0; s[n]; n++) {
if (escaped)
escaped = false;
else if (s[n] == '\\')
escaped = true;
break;
}
/* if s ends in \, return index of previous char */
return n - escaped;
}
/* Split a string into words. */
const char *current;
if (!*current) {
return NULL;
}
if (!*current) {
return NULL;
}
/* right quote missing or garbage at the end */
return NULL;
}
} else if (quoted) {
/* unfinished escape */
return NULL;
}
} else {
}
return current;
}
mode_t u;
int r;
u = umask(0777);
umask(u);
return r;
}
char *truncate_nl(char *s) {
assert(s);
return s;
}
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;
}
}
size_t l = 100;
int r;
assert(p);
for (;;) {
char *c;
ssize_t n;
c = new(char, l);
if (!c)
return -ENOMEM;
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_malloc(const char *p, char **ret) {
}
int readlink_value(const char *p, char **ret) {
char *value;
int r;
r = readlink_malloc(p, &link);
if (r < 0)
return r;
if (!value)
return -ENOENT;
if (!value)
return -ENOMEM;
return 0;
}
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, r = 0;
.sa_handler = SIG_DFL,
.sa_flags = SA_RESTART,
};
/* These two cannot be caught... */
continue;
/* On Linux the first two RT signals are reserved by
* glibc, and sigaction() will return EINVAL for them. */
r = -errno;
}
return r;
}
int reset_signal_mask(void) {
if (sigemptyset(&ss) < 0)
return -errno;
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;
}
char *e, *ret;
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))
if (!e)
if (!ret)
return NULL;
return ret;
}
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 -EINVAL;
}
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 -EINVAL;
}
char decchar(int x) {
return '0' + (x % 10);
}
int undecchar(char c) {
if (c >= '0' && c <= '9')
return c - '0';
return -EINVAL;
}
char *cescape(const char *s) {
char *r, *t;
const char *f;
assert(s);
/* Does C style string escaping. May be reversed with
* cunescape(). */
if (!r)
return NULL;
for (f = s, t = r; *f; f++)
t += cescape_char(*f, t);
*t = 0;
return r;
}
int r = 1;
assert(p);
assert(*p);
/* Unescapes C style. Returns the unescaped character in ret,
* unless we encountered a \u sequence in which case the full
* unicode character is returned in ret_unicode, instead. */
return -EINVAL;
switch (p[0]) {
case 'a':
*ret = '\a';
break;
case 'b':
*ret = '\b';
break;
case 'f':
*ret = '\f';
break;
case 'n':
*ret = '\n';
break;
case 'r':
*ret = '\r';
break;
case 't':
*ret = '\t';
break;
case 'v':
*ret = '\v';
break;
case '\\':
*ret = '\\';
break;
case '"':
*ret = '"';
break;
case '\'':
*ret = '\'';
break;
case 's':
/* This is an extension of the XDG syntax files */
*ret = ' ';
break;
case 'x': {
/* hexadecimal encoding */
int a, b;
return -EINVAL;
a = unhexchar(p[1]);
if (a < 0)
return -EINVAL;
b = unhexchar(p[2]);
if (b < 0)
return -EINVAL;
/* Don't allow NUL bytes */
if (a == 0 && b == 0)
return -EINVAL;
*ret = (char) ((a << 4U) | b);
r = 3;
break;
}
case 'u': {
/* C++11 style 16bit unicode */
int a[4];
unsigned i;
uint32_t c;
return -EINVAL;
for (i = 0; i < 4; i++) {
a[i] = unhexchar(p[1 + i]);
if (a[i] < 0)
return a[i];
}
/* Don't allow 0 chars */
if (c == 0)
return -EINVAL;
if (c < 128)
*ret = c;
else {
if (!ret_unicode)
return -EINVAL;
*ret = 0;
*ret_unicode = c;
}
r = 5;
break;
}
case 'U': {
/* C++11 style 32bit unicode */
int a[8];
unsigned i;
uint32_t c;
return -EINVAL;
for (i = 0; i < 8; i++) {
a[i] = unhexchar(p[1 + i]);
if (a[i] < 0)
return a[i];
}
c = ((uint32_t) a[0] << 28U) | ((uint32_t) a[1] << 24U) | ((uint32_t) a[2] << 20U) | ((uint32_t) a[3] << 16U) |
/* Don't allow 0 chars */
if (c == 0)
return -EINVAL;
/* Don't allow invalid code points */
if (!unichar_is_valid(c))
return -EINVAL;
if (c < 128)
*ret = c;
else {
if (!ret_unicode)
return -EINVAL;
*ret = 0;
*ret_unicode = c;
}
r = 9;
break;
}
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7': {
/* octal encoding */
int a, b, c;
uint32_t m;
return -EINVAL;
a = unoctchar(p[0]);
if (a < 0)
return -EINVAL;
b = unoctchar(p[1]);
if (b < 0)
return -EINVAL;
c = unoctchar(p[2]);
if (c < 0)
return -EINVAL;
/* don't allow NUL bytes */
if (a == 0 && b == 0 && c == 0)
return -EINVAL;
/* Don't allow bytes above 255 */
if (m > 255)
return -EINVAL;
*ret = m;
r = 3;
break;
}
default:
return -EINVAL;
}
return r;
}
int cunescape_length_with_prefix(const char *s, size_t length, const char *prefix, UnescapeFlags flags, char **ret) {
char *r, *t;
const char *f;
assert(s);
/* Undoes C style string escaping, and optionally prefixes it. */
if (!r)
return -ENOMEM;
if (prefix)
uint32_t u;
char c;
int k;
if (*f != '\\') {
/* A literal literal, copy verbatim */
*(t++) = *f;
continue;
}
if (remaining == 1) {
if (flags & UNESCAPE_RELAX) {
/* A trailing backslash, copy verbatim */
*(t++) = *f;
continue;
}
free(r);
return -EINVAL;
}
if (k < 0) {
if (flags & UNESCAPE_RELAX) {
/* Invalid escape code, let's take it literal then */
*(t++) = '\\';
continue;
}
free(r);
return k;
}
if (c != 0)
/* Non-Unicode? Let's encode this directly */
*(t++) = c;
else
/* Unicode? Then let's encode this in UTF-8 */
t += utf8_encode_unichar(t, u);
f += k;
}
*t = 0;
*ret = r;
return t - r;
}
}
}
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 hidden_file(const char *filename) {
return true;
return hidden_file_allow_backup(filename);
}
if (flags < 0)
return -errno;
if (nonblock)
else
return 0;
return -errno;
return 0;
}
if (flags < 0)
return -errno;
if (cloexec)
else
return 0;
return -errno;
return 0;
}
unsigned i;
for (i = 0; i < n_fdset; i++)
return true;
return false;
}
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;
}
}
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[] =
"afs\0"
"cifs\0"
"smbfs\0"
"sshfs\0"
"ncpfs\0"
"ncp\0"
"nfs\0"
"nfs4\0"
"gfs\0"
"gfs2\0"
"glusterfs\0";
const char *x;
if (x)
fstype = x;
}
};
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 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;
}
void safe_close_pair(int p[]) {
assert(p);
if (p[0] == p[1]) {
/* Special case pairs which use the same fd in both
* directions... */
p[0] = p[1] = safe_close(p[0]);
return;
}
p[0] = safe_close(p[0]);
}
ssize_t n = 0;
while (nbytes > 0) {
ssize_t k;
if (k < 0) {
continue;
/* We knowingly ignore any return value here,
* via read() */
continue;
}
return n > 0 ? n : -errno;
}
if (k == 0)
return n;
p += k;
nbytes -= k;
n += k;
}
return n;
}
ssize_t n;
if (n < 0)
return n;
return -EIO;
return 0;
}
errno = 0;
while (nbytes > 0) {
ssize_t k;
if (k < 0) {
continue;
/* We knowingly ignore any return value here,
* via write() */
continue;
}
return -errno;
}
if (k == 0) /* Can't really happen */
return -EIO;
p += k;
nbytes -= k;
}
return 0;
}
/* Soo, sometimes we want to parse IEC binary suffxies, and
* sometimes SI decimal suffixes. This function can parse
* both. Which one is the right way depends on the
* context. Wikipedia suggests that SI is customary for
* hardware metrics and network speeds, while IEC is
* customary for most data sizes used by software and volatile
* (RAM) memory. Hence be careful which one you pick!
*
* In either case we use just K, M, G as suffix, and not Ki,
* Mi, Gi or so (as IEC would suggest). That's because that's
* frickin' ugly. But this means you really need to make sure
* to document which base you are parsing when you use this
* call. */
struct table {
const char *suffix;
unsigned long long factor;
};
{ "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 },
{ "B", 1 },
{ "", 1 },
};
{ "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
{ "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
{ "T", 1000ULL*1000ULL*1000ULL*1000ULL },
{ "G", 1000ULL*1000ULL*1000ULL },
{ "M", 1000ULL*1000ULL },
{ "K", 1000ULL },
{ "B", 1 },
{ "", 1 },
};
const char *p;
unsigned long long r = 0;
assert(t);
if (base == 1000) {
} else {
}
p = t;
do {
long long l;
unsigned long long l2;
double frac = 0;
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;
if (*e == '.') {
e++;
if (*e >= '0' && *e <= '9') {
char *e2;
/* strotoull itself would accept space/+/- */
return -errno;
/* Ignore failure. E.g. 10.M is valid */
for (; e < e2; e++)
frac /= 10;
}
}
e += strspn(e, WHITESPACE);
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;
start_pos = i + 1;
break;
}
if (i >= n_entries)
return -EINVAL;
} while (*p);
*size = r;
return 0;
}
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;
}
/* 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;
}
int sigprocmask_many(int how, ...) {
int sig;
return -errno;
return 0;
}
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());
}
bool is_temporary_fs(const struct statfs *s) {
assert(s);
}
int fd_is_temporary_fs(int fd) {
struct statfs s;
return -errno;
return is_temporary_fs(&s);
}
/* 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. */
if (mode != MODE_INVALID)
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. */
if (mode != MODE_INVALID)
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;
}
}
struct stat a, b;
return -errno;
return -errno;
}
int running_in_chroot(void) {
int ret;
if (ret < 0)
return ret;
return ret == 0;
}
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;
}
}
_cleanup_close_ int fd;
int r;
if (parents)
if (fd < 0)
return -errno;
if (mode > 0) {
if (r < 0)
return -errno;
}
if (r < 0)
return -errno;
}
if (stamp != USEC_INFINITY) {
} else
if (r < 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.
*
* DON'T USE THIS FOR NEW CODE ANYMORE!*/
l = strlen(s);
if (l < 2)
return strdup(s);
return strdup(s);
}
/* 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 null_or_empty_fd(int fd) {
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;
}
if (!u)
return NULL;
if (!t)
return NULL;
if (encode_devnode_name(u, t, enc_len) < 0)
return NULL;
}
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);
}
return false;
return false;
return true;
}
return false;
return false;
}
char **directory;
/* We fork this all off from a child process so that we can
* somewhat cleanly make use of SIGALRM to set a time limit */
if (!pids)
return log_oom();
if (!seen)
return log_oom();
if (!d) {
continue;
}
FOREACH_DIRENT(de, d, break) {
int r;
if (!dirent_is_file(de))
continue;
continue;
}
if (r < 0)
return log_oom();
if (!path)
return log_oom();
if (null_or_empty_path(path)) {
continue;
}
if (pid < 0) {
continue;
} else if (pid == 0) {
char *_argv[2];
if (!argv) {
} else
}
if (r < 0)
return log_oom();
}
}
/* Abort execution of this process after the timout. We simply
* rely on SIGALRM as default action terminating the process,
* and turn on alarm(). */
if (timeout != USEC_INFINITY)
while (!hashmap_isempty(pids)) {
}
return 0;
}
int r;
char *name;
char **dirs = (char**) directories;
/* Executes all binaries in the directories in parallel and waits
* for them to finish. Optionally a timeout is applied. If a file
* with the same name exists in more than one directory, the
* earliest one wins. */
executor_pid = fork();
if (executor_pid < 0) {
return;
} else if (executor_pid == 0) {
}
}
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;
/* Doesn't accept empty hostnames, hostnames with trailing or
* leading dots, and hostnames with multiple dots in a
* sequence. Also ensures that the length stays below
* HOST_NAME_MAX. */
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;
}
bool machine_name_is_valid(const char *s) {
if (!hostname_is_valid(s))
return false;
/* Machine names should be useful hostnames, but also be
* useful in unit names, hence we enforce a stricter length
* limitation. */
if (strlen(s) > 64)
return false;
return true;
}
};
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;
int r, fd;
r = tempfn_xxxxxx(path, &t);
if (r < 0)
return r;
if (fd < 0) {
free(t);
return -errno;
}
if (!f) {
unlink(t);
free(t);
return -errno;
}
*_f = f;
*_temp_path = t;
return 0;
}
_cleanup_free_ char *t = NULL;
int r;
r = tempfn_random(to, &t);
if (r < 0)
return r;
return -errno;
unlink_noerrno(t);
return -errno;
}
return 0;
}
_cleanup_free_ char *p = NULL;
int r;
return -errno;
r = readlink_malloc(to, &p);
if (r < 0)
return r;
return -EINVAL;
}
return 0;
}
_cleanup_free_ char *t = NULL;
int r;
r = tempfn_random(path, &t);
if (r < 0)
return r;
return -errno;
unlink_noerrno(t);
return -errno;
}
return 0;
}
_cleanup_free_ char *t = NULL;
int r;
r = tempfn_random(path, &t);
if (r < 0)
return r;
return -errno;
unlink_noerrno(t);
return -errno;
}
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;
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;
}
_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;
}
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_MAX] = {
[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 -EINVAL;
}
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 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 },
};
if (t == (off_t) -1)
return NULL;
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;
}
bool stdout_is_tty, stderr_is_tty;
unsigned n, i;
char **l;
/* Spawns a temporary TTY agent, making sure it goes away when
* we go away */
parent_pid = getpid();
/* First we temporarily block all signals, so that the new
* child has them blocked initially. This way, we can be sure
* that SIGTERMs are not lost we might send to the agent. */
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 */
/* Make sure we actually can kill the agent, if we need to, in
* case somebody invoked us from a shell script that trapped
* SIGTERM or so... */
/* Check whether our parent died before we were able
* to set the death signal and unblock the signals */
if (getppid() != parent_pid)
/* Don't leak fds to the agent */
if (!stdout_is_tty || !stderr_is_tty) {
int fd;
* 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;
}
bool http_etag_is_valid(const char *etag) {
return false;
return false;
return false;
return true;
}
bool http_url_is_valid(const char *url) {
const char *p;
return false;
if (!p)
if (!p)
return false;
if (isempty(p))
return false;
return ascii_is_valid(p);
}
bool documentation_url_is_valid(const char *url) {
const char *p;
return false;
if (http_url_is_valid(url))
return true;
if (!p)
if (!p)
if (isempty(p))
return false;
return ascii_is_valid(p);
}
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;
}
int get_home_dir(char **_h) {
struct passwd *p;
const char *e;
char *h;
uid_t u;
/* Take the user specified one */
e = secure_getenv("HOME");
if (e && path_is_absolute(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_valid(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;
if (!p)
return false;
for (t = p; *t; t++) {
if (*t > 0 && *t < ' ')
return false;
if (strchr("\\\"\'\0x7f", *t))
return false;
}
return true;
}
/**
* Check if a string contains control characters. If 'ok' is non-NULL
* it may be a string containing additional CCs to be considered OK.
*/
bool string_has_cc(const char *p, const char *ok) {
const char *t;
assert(p);
for (t = p; *t; t++) {
continue;
if (*t > 0 && *t < ' ')
return true;
if (*t == 127)
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;
}
void init_gettext(void) {
}
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_VERTICAL] = "| ",
[DRAW_TREE_BRANCH] = "|-",
[DRAW_TREE_RIGHT] = "`-",
[DRAW_TREE_SPACE] = " ",
[DRAW_TRIANGULAR_BULLET] = ">",
[DRAW_BLACK_CIRCLE] = "*",
[DRAW_ARROW] = "->",
[DRAW_DASH] = "-",
}
};
}
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)
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;
safe_close(fd);
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, const char *root, char **search, FILE **_f) {
char **i;
return -ENOMEM;
STRV_FOREACH(i, search) {
_cleanup_free_ char *p = NULL;
FILE *f;
if (root)
else
if (!p)
return -ENOMEM;
if (f) {
*_f = f;
return 0;
}
return -errno;
}
return -ENOENT;
}
int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
if (path_is_absolute(path)) {
FILE *f;
if (f) {
*_f = f;
return 0;
}
return -errno;
}
if (!copy)
return -ENOMEM;
}
int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
_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;
}
void *q;
assert(p);
return *p;
/* check for overflows */
return NULL;
q = realloc(*p, a);
if (!q)
return NULL;
*p = q;
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) {
int r;
if (r < 0)
return r;
if (r == 0)
return true;
return parse_boolean(value) != 0;
}
int proc_cmdline(char **ret) {
if (detect_container(NULL) > 0)
else
}
const char *p;
int r;
r = proc_cmdline(&line);
if (r < 0)
return r;
p = line;
for (;;) {
if (r < 0)
return r;
if (r == 0)
break;
/* Filter out arguments that are intended only for the
* initrd */
continue;
if (value)
*(value++) = 0;
if (r < 0)
return r;
}
return 0;
}
bool found = false;
const char *p;
int r;
r = proc_cmdline(&line);
if (r < 0)
return r;
p = line;
for (;;) {
const char *e;
if (r < 0)
return r;
if (r == 0)
break;
/* Filter out arguments that are intended only for the
* initrd */
continue;
if (value) {
if (!e)
continue;
r = free_and_strdup(&ret, e);
if (r < 0)
return r;
found = true;
} else {
found = true;
}
}
if (value) {
}
return found;
}
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 = -1;
if (mntns_fd) {
const char *mntns;
if (mntnsfd < 0)
return -errno;
}
if (pidns_fd) {
const char *pidns;
if (pidnsfd < 0)
return -errno;
}
if (netns_fd) {
const char *netns;
if (netnsfd < 0)
return -errno;
}
if (root_fd) {
const char *root;
if (rfd < 0)
return -errno;
}
if (pidns_fd)
if (mntns_fd)
if (netns_fd)
if (root_fd)
return 0;
}
if (pidns_fd >= 0)
return -errno;
if (mntns_fd >= 0)
return -errno;
if (netns_fd >= 0)
return -errno;
if (root_fd >= 0) {
return -errno;
if (chroot(".") < 0)
return -errno;
}
if (setresgid(0, 0, 0) < 0)
return -errno;
return -errno;
if (setresuid(0, 0, 0) < 0)
return -errno;
return 0;
}
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;
if (u.uid == UID_INVALID)
return -ENODATA;
if (u.gid == GID_INVALID)
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 -EOPNOTSUPP;
}
*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 personality_from_string(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;
}
const char* personality_to_string(unsigned long p) {
#if defined(__x86_64__)
if (p == PER_LINUX32)
return "x86";
if (p == PER_LINUX)
return "x86-64";
if (p == PER_LINUX)
return "x86";
#endif
return NULL;
}
uint64_t physical_memory(void) {
long mem;
/* We return this as uint64_t in case we are running as 32bit
* process on a 64bit kernel with huge amounts of memory */
}
const uint8_t *b = p;
unsigned n = 0;
assert(s == 0 || b);
while (s > 0) {
size_t i;
fprintf(f, "%04x ", n);
for (i = 0; i < 16; i++) {
if (i >= s)
fputs(" ", f);
else
fprintf(f, "%02x ", b[i]);
if (i == 7)
fputc(' ', f);
}
fputc(' ', f);
for (i = 0; i < 16; i++) {
if (i >= s)
fputc(' ', f);
else
}
fputc('\n', f);
if (s < 16)
break;
n += 16;
b += 16;
s -= 16;
}
}
int update_reboot_param_file(const char *param) {
int r = 0;
if (param) {
if (r < 0)
log_error("Failed to write reboot param to "
} else
return r;
}
bool again;
int n = 0, r;
/* Try to umount everything recursively below a
* directory. Also, take care of stacked mounts, and keep
* unmounting them until they are gone. */
do {
again = false;
r = 0;
if (!proc_self_mountinfo)
return -errno;
for (;;) {
int k;
"%*s " /* (1) mount id */
"%*s " /* (2) parent id */
"%*s " /* (3) major:minor */
"%*s " /* (4) root */
"%ms " /* (5) mount point */
"%*s" /* (6) mount options */
"%*[^-]" /* (7) optional fields */
"- " /* (8) separator */
"%*s " /* (9) file system type */
"%*s" /* (10) mount source */
"%*s" /* (11) mount options 2 */
"%*[^\n]", /* some rubbish at the end */
&path);
if (k != 1) {
if (k == EOF)
break;
continue;
}
if (r < 0)
return r;
if (!path_startswith(p, prefix))
continue;
r = -errno;
continue;
}
again = true;
n++;
break;
}
} while (again);
return r ? r : n;
}
return -errno;
return 0;
}
int r;
/* Recursively remount a directory (and all its submounts)
* read-only or read-write. If the directory is already
* mounted, we reuse the mount and simply mark it
* MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
* operation). If it isn't we first make it one. Afterwards we
* apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
* submounts we can access, too. When mounts are stacked on
* the same mount point we only care for each individual
* "top-level" mount on each point, as we cannot
* have any effect on future submounts that might get
* propagated, they migt be writable. This includes future
* submounts that have been triggered via autofs. */
if (!cleaned)
return -ENOMEM;
if (!done)
return -ENOMEM;
for (;;) {
bool top_autofs = false;
char *x;
unsigned long orig_flags;
if (!todo)
return -ENOMEM;
if (!proc_self_mountinfo)
return -errno;
for (;;) {
int k;
"%*s " /* (1) mount id */
"%*s " /* (2) parent id */
"%*s " /* (3) major:minor */
"%*s " /* (4) root */
"%ms " /* (5) mount point */
"%*s" /* (6) mount options (superblock) */
"%*[^-]" /* (7) optional fields */
"- " /* (8) separator */
"%ms " /* (9) file system type */
"%*s" /* (10) mount source */
"%*s" /* (11) mount options (bind mount) */
"%*[^\n]", /* some rubbish at the end */
&path,
&type);
if (k != 2) {
if (k == EOF)
break;
continue;
}
if (r < 0)
return r;
/* Let's ignore autofs mounts. If they aren't
* triggered yet, we want to avoid triggering
* them, as we don't make any guarantees for
* future submounts anyway. If they are
* already triggered, then we will find
* another entry for this. */
continue;
}
if (path_startswith(p, cleaned) &&
!set_contains(done, p)) {
r = set_consume(todo, p);
p = NULL;
if (r == -EEXIST)
continue;
if (r < 0)
return r;
}
}
/* If we have no submounts to process anymore and if
* the root is either already done, or an autofs, we
* are done */
if (set_isempty(todo) &&
return 0;
/* The prefix directory itself is not yet a
* mount, make it one. */
return -errno;
orig_flags = 0;
orig_flags &= ~MS_RDONLY;
return -errno;
if (!x)
return -ENOMEM;
r = set_consume(done, x);
if (r < 0)
return r;
}
while ((x = set_steal_first(todo))) {
r = set_consume(done, x);
if (r == -EEXIST)
continue;
if (r < 0)
return r;
/* Try to reuse the original flag set, but
* don't care for errors, in case of
* obstructed mounts */
orig_flags = 0;
(void) get_mount_flags(x, &orig_flags);
orig_flags &= ~MS_RDONLY;
/* Deal with mount points that are
* obstructed by a later mount */
return -errno;
}
}
}
}
int fflush_and_check(FILE *f) {
assert(f);
errno = 0;
fflush(f);
if (ferror(f))
return 0;
}
int tempfn_xxxxxx(const char *p, char **ret) {
const char *fn;
char *t;
assert(p);
/*
* Turns this:
*
* Into this:
*/
if (!filename_is_valid(fn))
return -EINVAL;
if (!t)
return -ENOMEM;
*ret = path_kill_slashes(t);
return 0;
}
int tempfn_random(const char *p, char **ret) {
const char *fn;
char *t, *x;
uint64_t u;
unsigned i;
assert(p);
/*
* Turns this:
*
* Into this:
*/
if (!filename_is_valid(fn))
return -EINVAL;
if (!t)
return -ENOMEM;
u = random_u64();
for (i = 0; i < 16; i++) {
*(x++) = hexchar(u & 0xF);
u >>= 4;
}
*x = 0;
*ret = path_kill_slashes(t);
return 0;
}
int tempfn_random_child(const char *p, char **ret) {
char *t, *x;
uint64_t u;
unsigned i;
assert(p);
/* Turns this:
* Into this:
*/
if (!t)
return -ENOMEM;
u = random_u64();
for (i = 0; i < 16; i++) {
*(x++) = hexchar(u & 0xF);
u >>= 4;
}
*x = 0;
*ret = path_kill_slashes(t);
return 0;
}
/* make sure the hostname is not "localhost" */
bool is_localhost(const char *hostname) {
/* This tries to identify local host and domain names
* described in RFC6761 plus the redhatism of .localdomain */
}
int take_password_lock(const char *root) {
.l_start = 0,
.l_len = 0,
};
const char *path;
int fd, r;
/* This is roughly the same as lckpwdf(), but not as awful. We
* don't want to use alarm() and signals, hence we implement
* our own trivial version of this.
*
* Note that shadow-utils also takes per-database locks in
* addition to lckpwdf(). However, we don't given that they
* are redundant as they they invoke lckpwdf() first and keep
* it during everything they do. The per-database locks are
* awfully racy, and thus we just won't do them. */
if (root)
else
path = "/etc/.pwd.lock";
if (fd < 0)
return -errno;
if (r < 0) {
safe_close(fd);
return -errno;
}
return fd;
}
int is_symlink(const char *path) {
return -errno;
}
int r;
if (follow)
else
if (r < 0)
return -errno;
}
int is_device_node(const char *path) {
return -errno;
}
_cleanup_free_ char *s = NULL;
int r;
enum {
assert(p);
assert(*p);
/* Parses the first word of a string, and returns it in
* *ret. Removes all quotes in the process. When parsing fails
* (because of an uneven number of quotes or similar), leaves
* the pointer *p at the first invalid character. */
for (;;) {
char c = **p;
switch (state) {
case START:
if (c == 0)
goto finish;
else if (strchr(WHITESPACE, c))
break;
/* fallthrough */
case VALUE:
if (c == 0)
goto finish;
else if (c == '\'')
else if (c == '\\')
else if (c == '\"')
else if (strchr(WHITESPACE, c))
else {
return -ENOMEM;
s[sz++] = c;
}
break;
case VALUE_ESCAPE:
if (c == 0) {
if (flags & UNQUOTE_RELAX)
goto finish;
return -EINVAL;
}
return -ENOMEM;
if (flags & UNQUOTE_CUNESCAPE) {
uint32_t u;
if (r < 0)
return -EINVAL;
(*p) += r - 1;
if (c != 0)
s[sz++] = c; /* normal explicit char */
else
} else
s[sz++] = c;
break;
case SINGLE_QUOTE:
if (c == 0) {
if (flags & UNQUOTE_RELAX)
goto finish;
return -EINVAL;
} else if (c == '\'')
else if (c == '\\')
else {
return -ENOMEM;
s[sz++] = c;
}
break;
case SINGLE_QUOTE_ESCAPE:
if (c == 0) {
if (flags & UNQUOTE_RELAX)
goto finish;
return -EINVAL;
}
return -ENOMEM;
if (flags & UNQUOTE_CUNESCAPE) {
uint32_t u;
if (r < 0)
return -EINVAL;
(*p) += r - 1;
if (c != 0)
s[sz++] = c;
else
} else
s[sz++] = c;
break;
case DOUBLE_QUOTE:
if (c == 0)
return -EINVAL;
else if (c == '\"')
else if (c == '\\')
else {
return -ENOMEM;
s[sz++] = c;
}
break;
case DOUBLE_QUOTE_ESCAPE:
if (c == 0) {
if (flags & UNQUOTE_RELAX)
goto finish;
return -EINVAL;
}
return -ENOMEM;
if (flags & UNQUOTE_CUNESCAPE) {
uint32_t u;
if (r < 0)
return -EINVAL;
(*p) += r - 1;
if (c != 0)
s[sz++] = c;
else
} else
s[sz++] = c;
break;
case SPACE:
if (c == 0)
goto finish;
if (!strchr(WHITESPACE, c))
goto finish;
break;
}
(*p) ++;
}
if (!s) {
return 0;
}
s[sz] = 0;
*ret = s;
s = NULL;
return 1;
}
char **l;
int n = 0, i, c, r;
/* Parses a number of words from a string, stripping any
* quotes if necessary. */
assert(p);
/* Count how many words are expected */
for (;;) {
break;
n++;
}
if (n <= 0)
return 0;
/* Read all words into a temporary array */
l = newa0(char*, n);
for (c = 0; c < n; c++) {
r = unquote_first_word(p, &l[c], flags);
if (r < 0) {
int j;
for (j = 0; j < c; j++)
free(l[j]);
return r;
}
if (r == 0)
break;
}
/* If we managed to parse all words, return them in the passed
* in parameters */
for (i = 0; i < n; i++) {
char **v;
assert(v);
*v = l[i];
}
return c;
}
int free_and_strdup(char **p, const char *s) {
char *t;
assert(p);
/* Replaces a string pointer with an strdup()ed new string,
* possibly freeing the old one. */
if (streq_ptr(*p, s))
return 0;
if (s) {
t = strdup(s);
if (!t)
return -ENOMEM;
} else
t = NULL;
free(*p);
*p = t;
return 1;
}
int sethostname_idempotent(const char *s) {
int r;
assert(s);
if (r < 0)
return -errno;
return 0;
r = sethostname(s, strlen(s));
if (r < 0)
return -errno;
return 1;
}
size_t l = 100;
for (;;) {
char *c;
c = new(char, l);
if (!c)
return -ENOMEM;
*ret = c;
return 0;
}
free(c);
return -errno;
}
free(c);
l *= 2;
}
}
union {
} control = {};
.msg_control = &control,
.msg_controllen = sizeof(control),
};
int r;
if (r < 0)
return r;
return -errno;
if (child < 0)
return -errno;
if (child == 0) {
int master;
if (r < 0)
if (master < 0)
}
if (r < 0)
return r;
return -EIO;
return -errno;
int *fds;
unsigned n_fds;
if (n_fds != 1) {
return -EIO;
}
return fds[0];
}
return -EIO;
}
ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
ssize_t l;
/* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
if (fd < 0)
return -errno;
if (l < 0)
return -errno;
return l;
}
uint64_t u;
if (u == 0 || u == (uint64_t) -1)
return -EIO;
return 0;
}
ssize_t n;
* let's fake one with xattrs */
if (n < 0)
return -errno;
if (n != sizeof(le))
return -EIO;
}
ssize_t n;
if (n < 0)
return -errno;
if (n != sizeof(le))
return -EIO;
}
ssize_t n;
assert(p);
if (n < 0)
return -errno;
if (n != sizeof(le))
return -EIO;
}
if (usec <= 0)
return -errno;
return 0;
}
int same_fd(int a, int b) {
assert(a >= 0);
assert(b >= 0);
/* Compares two file descriptors. Note that semantics are
* quite different depending on whether we have kcmp() or we
* don't. If we have kcmp() this will only return true for
* dup()ed file descriptors, but not otherwise. If we don't
* have kcmp() this will also return true for two fds of the same
* file, created by separate open() calls. Since we use this
* call mostly for filtering out duplicates in the fd store
* this difference hopefully doesn't matter too much. */
if (a == b)
return true;
/* Try to use kcmp() if we have it. */
if (r == 0)
return true;
if (r > 0)
return false;
return -errno;
/* We don't have kcmp(), use fstat() instead. */
return -errno;
return -errno;
return false;
/* We consider all device fds different, since two device fds
* might refer to quite different device contexts even though
* they share the same inode and backing dev_t. */
return false;
return false;
/* The fds refer to the same inode on disk, let's also check
* if they have the same fd flags. This is useful to
* distuingish the read and write side of a pipe created with
* pipe(). */
if (fa < 0)
return -errno;
if (fb < 0)
return -errno;
}
return -errno;
/* Explicitly check whether this is a regular file or
* directory. If it is anything else (such as a device node or
* fifo), then the ioctl will not hit the file systems but
* possibly drivers, where the ioctl might have different
* effects. Notably, DRM is using the same ioctl() number. */
return -ENOTTY;
if (mask == 0)
return 0;
return -errno;
return 0;
return -errno;
return 1;
}
assert(p);
if (mask == 0)
return 0;
if (fd < 0)
return -errno;
}
return -errno;
return -ENOTTY;
return -errno;
return 0;
}
int read_attr_path(const char *p, unsigned *ret) {
assert(p);
if (fd < 0)
return -errno;
}
size_t n = 0;
while (sz > 0) {
if (*p != 0)
break;
n++;
p++;
sz--;
}
return n;
}
const uint8_t *q, *w, *e;
ssize_t l;
q = w = p;
e = q + sz;
while (q < e) {
size_t n;
n = nul_length(q, e - q);
/* If there are more than the specified run length of
* NUL bytes, or if this is the beginning or the end
* of the buffer, then seek instead of write */
if ((n > run_length) ||
(n > 0 && q == p) ||
(n > 0 && q + n >= e)) {
if (q > w) {
if (l < 0)
return -errno;
if (l != q -w)
return -EIO;
}
return -errno;
q += n;
w = q;
} else if (n > 0)
q += n;
else
q ++;
}
if (q > w) {
if (l < 0)
return -errno;
if (l != q - w)
return -EIO;
}
return q - (const uint8_t*) p;
}
if (!pid)
return;
if (*pid <= 1)
return;
}
int a = 0, b = 0, c = 0;
int k;
assert(p);
assert(*p);
if ((*p)[0] != '<')
return 0;
if (!strchr(*p, '>'))
return 0;
if ((*p)[2] == '>') {
c = undecchar((*p)[1]);
k = 3;
} else if ((*p)[3] == '>') {
b = undecchar((*p)[1]);
c = undecchar((*p)[2]);
k = 4;
} else if ((*p)[4] == '>') {
a = undecchar((*p)[1]);
b = undecchar((*p)[2]);
c = undecchar((*p)[3]);
k = 5;
} else
return 0;
if (a < 0 || b < 0 || c < 0 ||
(!with_facility && (a || b || c > 7)))
return 0;
if (with_facility)
else
*p += k;
return 1;
}
size_t i;
if (!key)
return -1;
for (i = 0; i < len; ++i)
return (ssize_t)i;
return -1;
}
}
int ret;
if (ret >= 0)
return 0;
/* Even though renameat2() exists since Linux 3.15, btrfs added
* support for it later. If it is not implemented, fallback to another
* method. */
return -errno;
/* The link()/unlink() fallback does not work on directories. But
* renameat() without RENAME_NOREPLACE gives the same semantics on
* directories, except when newpath is an *empty* directory. This is
* good enough. */
}
/* If it is not a directory, use the link()/unlink() fallback. */
if (ret < 0)
return -errno;
if (ret < 0) {
/* backup errno before the following unlinkat() alters it */
return -errno;
}
return 0;
}
char *shell_maybe_quote(const char *s) {
const char *p;
char *r, *t;
assert(s);
/* Encloses a string in double quotes if necessary to make it
* OK as shell string. */
for (p = s; *p; p++)
if (*p <= ' ' ||
*p >= 127 ||
strchr(SHELL_NEED_QUOTES, *p))
break;
if (!*p)
return strdup(s);
if (!r)
return NULL;
t = r;
*(t++) = '"';
t = mempcpy(t, s, p - s);
for (; *p; p++) {
if (strchr(SHELL_NEED_ESCAPE, *p))
*(t++) = '\\';
*(t++) = *p;
}
*(t++)= '"';
*t = 0;
return r;
}
char *x;
long l;
assert(s);
errno = 0;
l = strtol(s, &x, 8);
if (errno != 0)
return -errno;
if (!x || x == s || *x)
return -EINVAL;
if (l < 0 || l > 07777)
return -ERANGE;
return 0;
}