util.c revision 25ea79fe0756c3c46a16c0c19bf3380a30382a1c
/*-*- 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 <libgen.h>
#include <ctype.h>
#include <pwd.h>
#include <dlfcn.h>
#include <glob.h>
#include <grp.h>
#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"
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;
}
return timespec_load(&ts);
}
return ts;
}
if (u == 0)
else {
else
}
return ts;
}
return
}
return ts;
}
return
}
return tv;
}
assert(s);
if (pl == 0)
return true;
return false;
}
bool startswith(const char *s, const char *prefix) {
assert(s);
if (pl == 0)
return true;
return false;
}
bool startswith_no_case(const char *s, const char *prefix) {
unsigned i;
assert(s);
if (pl == 0)
return true;
return false;
for(i = 0; i < pl; ++i)
return false;
return true;
}
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) {
for (;;) {
int r;
if (r >= 0)
return r;
return -errno;
}
}
void close_nointr_nofail(int fd) {
int saved_errno = errno;
/* like close_nointr() but cannot fail, and guarantees errno
* is unchanged */
errno = saved_errno;
}
unsigned i;
for (i = 0; i < n_fd; i++)
close_nointr_nofail(fds[i]);
}
int parse_boolean(const char *v) {
assert(v);
if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
return 1;
else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(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 || 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 || 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 || 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 || errno)
*ret_lli = l;
return 0;
}
/* Split a string into words. */
char *current;
if (!*current || *c == 0)
return NULL;
return (char*) current;
}
/* Split a string into words, but consider strings enclosed in '' and
* "" as words even if they include spaces. */
char *current, *e;
bool escaped = false;
if (!*current || *c == 0)
return NULL;
if (*current == '\'') {
current ++;
for (e = current; *e; e++) {
if (escaped)
escaped = false;
else if (*e == '\\')
escaped = true;
else if (*e == '\'')
break;
}
*l = e-current;
*state = *e == 0 ? e : e+1;
} else if (*current == '\"') {
current ++;
for (e = current; *e; e++) {
if (escaped)
escaped = false;
else if (*e == '\\')
escaped = true;
else if (*e == '\"')
break;
}
*l = e-current;
*state = *e == 0 ? e : e+1;
} else {
for (e = current; *e; e++) {
if (escaped)
escaped = false;
else if (*e == '\\')
escaped = true;
else if (strchr(WHITESPACE, *e))
break;
}
*l = e-current;
*state = e;
}
return (char*) current;
}
int r;
long unsigned ppid;
assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
if (!f)
return -errno;
fclose(f);
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;
}
assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
if (!f)
return -errno;
if (ferror(f))
return -errno;
return -EIO;
}
/* 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;
}
if (!f)
return -errno;
errno = 0;
fputc('\n', f);
fflush(f);
if (ferror(f))
return 0;
}
mode_t u;
int r;
u = umask(0777);
umask(u);
return r;
}
FILE *f;
int r;
char *p;
r = fopen_temporary(fn, &f, &p);
if (r < 0)
return r;
errno = 0;
r = -errno;
goto finish;
}
fputc('\n', f);
fflush(f);
if (ferror(f)) {
if (errno != 0)
r = -errno;
else
r = -EIO;
} else {
r = -errno;
else
r = 0;
}
if (r < 0)
unlink(p);
fclose(f);
free(p);
return r;
}
char t[LINE_MAX], *c;
if (!f)
return -errno;
if (!fgets(t, sizeof(t), f)) {
if (ferror(f))
t[0] = 0;
}
c = strdup(t);
if (!c)
return -ENOMEM;
truncate_nl(c);
*line = c;
return 0;
}
size_t n, l;
if (!f)
return -errno;
return -errno;
/* Safety check */
return -E2BIG;
l = 0;
for (;;) {
char *t;
size_t k;
if (!t)
return -ENOMEM;
buf = t;
if (k <= 0) {
if (ferror(f))
return -errno;
break;
}
l += k;
n *= 2;
/* Safety check */
if (n > 4*1024*1024)
return -E2BIG;
}
buf[l] = 0;
if (size)
*size = l;
return 0;
}
int parse_env_file(
const char *fname,
const char *separator, ...) {
int r = 0;
return r;
p = contents;
for (;;) {
p += strspn(p, WHITESPACE);
if (!*p)
break;
char **value;
size_t n;
char *v;
p[n] != '=')
continue;
p += n + 1;
if (n >= 2 &&
p[n-1] == p[0])
else
v = strndup(p, n);
if (!v) {
r = -ENOMEM;
goto fail;
}
if (v[0] == '\0') {
/* return empty value strings as NULL */
free(v);
v = NULL;
}
*value = v;
p += n;
r ++;
break;
}
}
if (!key)
}
fail:
return r;
}
int load_env_file(
const char *fname,
char ***rl) {
FILE *f;
char **m = NULL;
int r;
return -errno;
while (!feof(f)) {
char l[LINE_MAX], *p, *u;
char **t;
if (!fgets(l, sizeof(l), f)) {
if (feof(f))
break;
r = -errno;
goto finish;
}
p = strstrip(l);
if (!*p)
continue;
continue;
if (!(u = normalize_env_assignment(p))) {
r = log_oom();
goto finish;
}
t = strv_append(m, u);
free(u);
if (!t) {
r = log_oom();
goto finish;
}
strv_free(m);
m = t;
}
r = 0;
*rl = m;
m = NULL;
if (f)
fclose(f);
strv_free(m);
return r;
}
int write_env_file(const char *fname, char **l) {
char **i, *p;
FILE *f;
int r;
r = fopen_temporary(fname, &f, &p);
if (r < 0)
return r;
errno = 0;
STRV_FOREACH(i, l) {
fputs(*i, f);
fputc('\n', f);
}
fflush(f);
if (ferror(f)) {
if (errno != 0)
r = -errno;
else
r = -EIO;
} else {
r = -errno;
else
r = 0;
}
if (r < 0)
unlink(p);
fclose(f);
free(p);
return r;
}
char *truncate_nl(char *s) {
assert(s);
return s;
}
int r;
if (pid == 0)
else {
char *p;
return -ENOMEM;
r = read_one_line_file(p, name);
free(p);
}
return r;
}
char *r, *k;
int c;
bool space = false;
FILE *f;
assert(max_length > 0);
if (pid == 0)
else {
char *p;
return -ENOMEM;
f = fopen(p, "re");
free(p);
}
if (!f)
return -errno;
r = new(char, max_length);
if (!r) {
fclose(f);
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;
fclose(f);
/* Kernel threads have no argv[] */
if (r[0] == 0) {
char *t;
int h;
free(r);
if (!comm_fallback)
return -ENOENT;
h = get_process_comm(pid, &t);
if (h < 0)
return h;
free(t);
if (!r)
return -ENOMEM;
}
*line = r;
return 0;
}
char *p;
char c;
bool eof;
FILE *f;
if (pid == 0)
return 0;
return -ENOMEM;
f = fopen(p, "re");
free(p);
if (!f)
return -errno;
fclose(f);
/* Kernel threads have an empty cmdline */
if (count <= 0)
return 0;
}
int r;
if (pid == 0)
else {
char *p;
return -ENOMEM;
r = readlink_malloc(p, name);
free(p);
}
return r;
}
char *p;
FILE *f;
int r;
if (pid == 0)
return getuid();
return -ENOMEM;
f = fopen(p, "re");
free(p);
if (!f)
return -errno;
while (!feof(f)) {
if (feof(f))
break;
r = -errno;
goto finish;
}
if (startswith(l, "Uid:")) {
l += 4;
l += strspn(l, WHITESPACE);
l[strcspn(l, WHITESPACE)] = 0;
goto finish;
}
}
r = -EIO;
fclose(f);
return r;
}
size_t a;
char *r;
if (!s && !suffix)
return strdup("");
if (!s)
if (!suffix)
return strdup(s);
assert(s);
a = strlen(s);
if (!(r = new(char, a+b+1)))
return NULL;
memcpy(r, s, a);
r[a+b] = 0;
return r;
}
}
int readlink_malloc(const char *p, char **r) {
size_t l = 100;
assert(p);
assert(r);
for (;;) {
char *c;
ssize_t n;
if (!(c = new(char, l)))
return -ENOMEM;
if ((n = readlink(p, c, l-1)) < 0) {
free(c);
return ret;
}
if ((size_t) n < l-1) {
c[n] = 0;
*r = c;
return 0;
}
free(c);
l *= 2;
}
}
int readlink_and_make_absolute(const char *p, char **r) {
char *target, *k;
int j;
assert(p);
assert(r);
if ((j = readlink_malloc(p, &target)) < 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;
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 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. */
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 *bus_path_escape(const char *s) {
char *r, *t;
const char *f;
assert(s);
/* Escapes all chars that D-Bus' object path cannot deal
* with. Can be reverse with bus_path_unescape() */
return NULL;
for (f = s, t = r; *f; f++) {
if (!(*f >= 'A' && *f <= 'Z') &&
!(*f >= 'a' && *f <= 'z') &&
!(*f >= '0' && *f <= '9')) {
*(t++) = '_';
*(t++) = hexchar(*f >> 4);
*(t++) = hexchar(*f);
} else
*(t++) = *f;
}
*t = 0;
return r;
}
char *bus_path_unescape(const char *f) {
char *r, *t;
assert(f);
if (!(r = strdup(f)))
return NULL;
for (t = r; *f; f++) {
if (*f == '_') {
int a, b;
if ((a = unhexchar(f[1])) < 0 ||
(b = unhexchar(f[2])) < 0) {
/* Invalid escape code, let's take it literal then */
*(t++) = '_';
} else {
*(t++) = (char) ((a << 4) | b);
f += 2;
}
} 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;
}
static bool ignore_file_allow_backup(const char *filename) {
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;
}
assert(l > 0);
if (t <= 0)
return NULL;
return NULL;
return buf;
}
usec_t n, d;
n = now(CLOCK_REALTIME);
if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
return NULL;
d = n - t;
if (d >= USEC_PER_YEAR)
(unsigned long long) (d / USEC_PER_YEAR),
(unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
else if (d >= USEC_PER_MONTH)
(unsigned long long) (d / USEC_PER_MONTH),
(unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
else if (d >= USEC_PER_WEEK)
(unsigned long long) (d / USEC_PER_WEEK),
(unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
else if (d >= 2*USEC_PER_DAY)
else if (d >= 25*USEC_PER_HOUR)
(unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
else if (d >= 6*USEC_PER_HOUR)
(unsigned long long) (d / USEC_PER_HOUR));
else if (d >= USEC_PER_HOUR)
(unsigned long long) (d / USEC_PER_HOUR),
(unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
else if (d >= 5*USEC_PER_MINUTE)
(unsigned long long) (d / USEC_PER_MINUTE));
else if (d >= USEC_PER_MINUTE)
(unsigned long long) (d / USEC_PER_MINUTE),
(unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
else if (d >= USEC_PER_SEC)
(unsigned long long) (d / USEC_PER_SEC));
else if (d >= USEC_PER_MSEC)
(unsigned long long) (d / USEC_PER_MSEC));
else if (d > 0)
(unsigned long long) d);
else
buf[l-1] = 0;
return buf;
}
static const struct {
const char *suffix;
} table[] = {
{ "w", USEC_PER_WEEK },
{ "d", USEC_PER_DAY },
{ "h", USEC_PER_HOUR },
{ "min", USEC_PER_MINUTE },
{ "s", USEC_PER_SEC },
{ "ms", USEC_PER_MSEC },
{ "us", 1 },
};
unsigned i;
char *p = buf;
assert(l > 0);
if (t == (usec_t) -1)
return NULL;
if (t == 0) {
snprintf(p, l, "0");
p[l-1] = 0;
return p;
}
/* The result of this function can be parsed with parse_usec */
for (i = 0; i < ELEMENTSOF(table); i++) {
int k;
size_t n;
continue;
if (l <= 1)
break;
k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
l -= n;
p += n;
}
*p = 0;
return buf;
}
bool fstype_is_network(const char *fstype) {
static const char table[] =
"cifs\0"
"smbfs\0"
"ncpfs\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;
}
bool on_tty;
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;
continue;
return -errno;
}
if (r == 0)
return 0;
continue;
return 0;
return -errno;
}
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 (;;) {
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, fd;
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, ...) {
int r = 0;
r = -errno;
r = -errno;
return r;
}
int default_signals(int sig, ...) {
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;
}
uint8_t *p;
ssize_t n = 0;
p = buf;
while (nbytes > 0) {
ssize_t k;
continue;
continue;
return n > 0 ? n : -errno;
}
return n > 0 ? n : -EIO;
continue;
}
return n > 0 ? n : (k < 0 ? -errno : 0);
}
p += k;
nbytes -= k;
n += k;
}
return n;
}
const uint8_t *p;
ssize_t n = 0;
p = buf;
while (nbytes > 0) {
ssize_t k;
if (k <= 0) {
continue;
continue;
return n > 0 ? n : -errno;
}
return n > 0 ? n : -EIO;
continue;
}
return n > 0 ? n : (k < 0 ? -errno : 0);
}
p += k;
nbytes -= k;
n += k;
}
return n;
}
static const struct {
const char *suffix;
} table[] = {
{ "sec", USEC_PER_SEC },
{ "s", USEC_PER_SEC },
{ "min", USEC_PER_MINUTE },
{ "hr", USEC_PER_HOUR },
{ "h", USEC_PER_HOUR },
{ "d", USEC_PER_DAY },
{ "w", USEC_PER_WEEK },
{ "msec", USEC_PER_MSEC },
{ "ms", USEC_PER_MSEC },
{ "m", USEC_PER_MINUTE },
{ "usec", 1ULL },
{ "us", 1ULL },
};
const char *p;
usec_t 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++)
break;
}
if (i >= ELEMENTSOF(table))
return -EINVAL;
} while (*p != 0);
*usec = r;
return 0;
}
static const struct {
const char *suffix;
} table[] = {
{ "sec", NSEC_PER_SEC },
{ "s", NSEC_PER_SEC },
{ "min", NSEC_PER_MINUTE },
{ "hr", NSEC_PER_HOUR },
{ "h", NSEC_PER_HOUR },
{ "d", NSEC_PER_DAY },
{ "w", NSEC_PER_WEEK },
{ "msec", NSEC_PER_MSEC },
{ "ms", NSEC_PER_MSEC },
{ "m", NSEC_PER_MINUTE },
{ "usec", NSEC_PER_USEC },
{ "us", NSEC_PER_USEC },
{ "nsec", 1ULL },
{ "ns", 1ULL },
{ "", 1ULL }, /* default is nsec */
};
const char *p;
nsec_t 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++)
break;
}
if (i >= ELEMENTSOF(table))
return -EINVAL;
} while (*p != 0);
*nsec = r;
return 0;
}
static const struct {
const char *suffix;
} 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;
off_t 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++)
break;
}
if (i >= ELEMENTSOF(table))
return -EINVAL;
} while (*p != 0);
*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) {
int r;
if (!d)
return -errno;
for (;;) {
if (r > 0)
return -r;
if (!de)
return 1;
return 0;
}
}
unsigned long long random_ull(void) {
_cleanup_close_ int fd;
ssize_t r;
if (fd < 0)
goto fallback;
if (r != sizeof(ull))
goto fallback;
return ull;
}
/* 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 k;
unsigned long ttynr;
FILE *f;
return -ENOMEM;
if (!f)
return -errno;
fclose(f);
return k;
}
fclose(f);
if (!p)
return -EIO;
p++;
if (sscanf(p, " "
"%*c " /* state */
"%*d " /* ppid */
"%*d " /* pgrp */
"%*d " /* session */
"%lu ", /* ttynr */
&ttynr) != 1)
return -EIO;
return 0;
}
int k;
assert(r);
if (k < 0)
return k;
if ((k = readlink_malloc(fn, &s)) < 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. */
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;
if (r != 0 && ret == 0) {
ret = -r;
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;
}
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 (s.f_type != TMPFS_MAGIC &&
s.f_type != RAMFS_MAGIC) {
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 (s.f_type != TMPFS_MAGIC &&
s.f_type != RAMFS_MAGIC) {
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 (s.f_type != TMPFS_MAGIC &&
s.f_type != RAMFS_MAGIC) {
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;
}
}
char *s = NULL;
int fd = -1;
int n = 0;
/* This is independent of logging, as status messages are
* optional and go exclusively to the console. */
goto finish;
if (fd < 0)
goto finish;
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 (status) {
} else
}
IOVEC_SET_STRING(iovec[n++], s);
free(s);
if (fd >= 0)
}
}
void status_welcome(void) {
int r;
"PRETTY_NAME", &pretty_name,
"ANSI_COLOR", &ansi_color,
NULL)) < 0) {
if (r != -ENOENT)
}
if (!pretty_name && !const_pretty)
const_pretty = "Linux";
if (!ansi_color && !const_color)
const_color = "1";
false,
"\nWelcome to \x1B[%sm%s\x1B[0m!\n",
}
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;
t = "";
if (!(k = strappend(r, t)))
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 (!(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;
}
static unsigned columns_cached(bool cached) {
const char *e;
return parsed_columns;
e = getenv("COLUMNS");
if (e)
env_columns = atoi(e);
else
env_columns = 0;
}
if (env_columns > 0) {
return parsed_columns;
}
if (parsed_columns <= 0 || !cached)
if (parsed_columns <= 0)
parsed_columns = 80;
return parsed_columns;
}
unsigned columns(void) {
return columns_cached(true);
}
unsigned columns_uncached(void) {
return columns_cached(false);
}
return -errno;
return -EIO;
}
unsigned lines(void) {
static __thread int parsed_lines = 0;
const char *e;
if (_likely_(parsed_lines > 0))
return parsed_lines;
e = getenv("LINES");
if (e)
parsed_lines = atoi(e);
if (parsed_lines <= 0)
if (parsed_lines <= 0)
parsed_lines = 25;
return parsed_lines;
}
int running_in_chroot(void) {
struct stat a, b;
zero(a);
zero(b);
/* Only works as root */
if (stat("/proc/1/root", &a) < 0)
return -errno;
if (stat("/", &b) < 0)
return -errno;
return
}
size_t x;
char *r;
assert(s);
return strndup(s, old_length);
if (!r)
return r;
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;
}
}
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. */
l = strlen(s);
if (l < 2)
return strdup(s);
return strdup(s);
}
char *normalize_env_assignment(const char *s) {
p = strchr(s, '=');
if (!p) {
if (!(r = strdup(s)))
return NULL;
return strstrip(r);
}
return NULL;
if (!(p = strdup(p+1))) {
return NULL;
}
free(p);
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;
}
_noreturn_ void freeze(void) {
/* 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;
}
assert(f);
assert(t);
if (!dual_timestamp_is_set(t))
return;
fprintf(f, "%s=%llu %llu\n",
name,
(unsigned long long) t->realtime,
(unsigned long long) t->monotonic);
}
unsigned long long a, b;
assert(t);
else {
t->realtime = a;
t->monotonic = b;
}
}
char *dn, *t, *u;
int r;
/* FIXME: to follow udev's logic 100% we need to leave valid
* UTF8 chars unescaped */
if (u == NULL)
return NULL;
t = xescape(u, "/ ");
free(u);
if (t == NULL)
return NULL;
free(t);
if (r < 0)
return NULL;
return dn;
}
char *fstab_node_to_udev_node(const char *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;
}
bool tty_is_vc_resolve(const char *tty) {
bool b;
tty += 5;
* actually ours (i.e. not read-only-mounted which is a sign
* for container setups) */
/* If multiple log outputs are configured the
if (tty)
tty++;
else
}
return b;
}
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
* until all they all finished. */
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;
if (isempty(s))
return false;
for (p = s; *p; p++)
if (!hostname_valid_char(*p))
return false;
if (p-s > HOST_NAME_MAX)
return false;
return true;
}
char* hostname_cleanup(char *s) {
char *p, *d;
for (p = s, d = s; *p; p++)
if ((*p >= 'a' && *p <= 'z') ||
(*p >= 'A' && *p <= 'Z') ||
(*p >= '0' && *p <= '9') ||
*p == '-' ||
*p == '_' ||
*p == '.')
*(d++) = *p;
*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;
}
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;
unsigned long long ull;
unsigned i;
int r;
if (!t)
return -ENOMEM;
t[k] = '.';
ull = random_ull();
for (i = 0; i < 16; i++) {
ull >>= 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 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;
if (r < 0)
return r;
return 1;
return 1;
assert(ngroups_max > 0);
if (r < 0)
return -errno;
for (i = 0; i < r; i++)
return 1;
return 0;
}
int glob_exists(const char *path) {
glob_t g;
int r, k;
zero(g);
errno = 0;
if (k == GLOB_NOMATCH)
r = 0;
else if (k == GLOB_NOSPACE)
r = -ENOMEM;
else if (k == 0)
r = !strv_isempty(g.gl_pathv);
else
globfree(&g);
return r;
}
assert(d);
return 0;
return -errno;
return 0;
}
char **i, *parent;
int r;
if (r < 0)
return r;
r = 0;
STRV_FOREACH(i, search) {
if (path_equal(parent, *i)) {
r = 1;
break;
}
}
return r;
}
DIR *d;
int r = 0;
unsigned n = 0;
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 (;;) {
int k;
if (k != 0) {
r = -k;
goto finish;
}
if (!de)
break;
dirent_ensure_type(d, de);
if (!dirent_is_file(de))
continue;
if (list) {
if ((unsigned) r >= n) {
char **t;
t = realloc(l, sizeof(char*) * n);
if (!t) {
r = -ENOMEM;
goto finish;
}
l = t;
}
assert((unsigned) r < n);
if (!l[r]) {
r = -ENOMEM;
goto finish;
}
l[++r] = NULL;
} else
r++;
}
if (d)
closedir(d);
if (r >= 0) {
if (list)
*list = l;
} else
strv_free(l);
return r;
}
char *strjoin(const char *x, ...) {
size_t l;
char *r, *p;
if (x) {
l = strlen(x);
for (;;) {
const char *t;
if (!t)
break;
l += strlen(t);
}
} 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) {
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",
};
DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
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;
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;
if (r >= 0 &&
l == sizeof(value) &&
return 0;
value = (int) n;
if (r < 0)
return -errno;
return 1;
}
int r, value;
if (r >= 0 &&
l == sizeof(value) &&
return 0;
value = (int) n;
if (r < 0)
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;
FILE *f;
bool done = false;
size_t l;
if (pid == 0)
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) {
r = -ENOMEM;
break;
}
r = 1;
break;
}
} while (!done);
fclose(f);
if (r >= 0)
return r;
}
char *w, *state;
size_t l, k;
int r;
_cleanup_free_ char *p = NULL;
r = read_one_line_file("/sys/power/state", &p);
if (r < 0)
return r == -ENOENT ? 0 : r;
return true;
return false;
}
bool is_valid_documentation_url(const char *url) {
return true;
return true;
return true;
return true;
return true;
return false;
}
bool in_initrd(void) {
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 &&
return saved;
}
void warn_melody(void) {
if (fd < 0)
return;
/* Yeah, this is synchronous. Kinda sucks. Bute 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) {
char *h;
const char *e;
uid_t u;
struct passwd *p;
/* 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;
}
char *sh;
const char *e;
uid_t u;
struct passwd *p;
/* Take the user specified one */
e = getenv("SHELL");
if (e) {
if (!sh)
return -ENOMEM;
return 0;
}
/* Hardcode home directory for root to avoid NSS */
u = getuid();
if (u == 0) {
if (!sh)
return -ENOMEM;
return 0;
}
/* Check the database... */
errno = 0;
p = getpwuid(u);
if (!p)
if (!path_is_absolute(p->pw_shell))
return -EINVAL;
if (!sh)
return -ENOMEM;
return 0;
}
void freep(void *p) {
free(*(void**) p);
}
if (*f)
fclose(*f);
}
if (*fd >= 0)
}
if (*d)
closedir(*d);
}
umask(*u);
}