1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 #include <linux/tiocl.h>
42 #include <sys/inotify.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
49 #include <netinet/ip.h>
53 #include <sys/capability.h>
55 #include <linux/rtc.h>
66 #include "exit-status.h"
70 char **saved_argv = NULL;
72 size_t page_size(void) {
73 static __thread size_t pgsz = 0;
79 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
86 bool streq_ptr(const char *a, const char *b) {
88 /* Like streq(), but tries to make sense of NULL pointers */
99 usec_t now(clockid_t clock_id) {
102 assert_se(clock_gettime(clock_id, &ts) == 0);
104 return timespec_load(&ts);
107 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
110 ts->realtime = now(CLOCK_REALTIME);
111 ts->monotonic = now(CLOCK_MONOTONIC);
116 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
125 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
127 ts->monotonic = now(CLOCK_MONOTONIC);
129 if ((int64_t) ts->monotonic > delta)
130 ts->monotonic -= delta;
138 usec_t timespec_load(const struct timespec *ts) {
142 (usec_t) ts->tv_sec * USEC_PER_SEC +
143 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
146 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
149 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
150 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
155 usec_t timeval_load(const struct timeval *tv) {
159 (usec_t) tv->tv_sec * USEC_PER_SEC +
160 (usec_t) tv->tv_usec;
163 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
166 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
167 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
172 bool endswith(const char *s, const char *postfix) {
179 pl = strlen(postfix);
187 return memcmp(s + sl - pl, postfix, pl) == 0;
190 bool startswith(const char *s, const char *prefix) {
205 return memcmp(s, prefix, pl) == 0;
208 bool startswith_no_case(const char *s, const char *prefix) {
224 for(i = 0; i < pl; ++i) {
225 if (tolower(s[i]) != tolower(prefix[i]))
232 bool first_word(const char *s, const char *word) {
247 if (memcmp(s, word, wl) != 0)
251 strchr(WHITESPACE, s[wl]);
254 int close_nointr(int fd) {
269 void close_nointr_nofail(int fd) {
270 int saved_errno = errno;
272 /* like close_nointr() but cannot fail, and guarantees errno
275 assert_se(close_nointr(fd) == 0);
280 void close_many(const int fds[], unsigned n_fd) {
283 for (i = 0; i < n_fd; i++)
284 close_nointr_nofail(fds[i]);
287 int parse_boolean(const char *v) {
290 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
292 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
298 int parse_pid(const char *s, pid_t* ret_pid) {
299 unsigned long ul = 0;
306 if ((r = safe_atolu(s, &ul)) < 0)
311 if ((unsigned long) pid != ul)
321 int parse_uid(const char *s, uid_t* ret_uid) {
322 unsigned long ul = 0;
329 if ((r = safe_atolu(s, &ul)) < 0)
334 if ((unsigned long) uid != ul)
341 int safe_atou(const char *s, unsigned *ret_u) {
349 l = strtoul(s, &x, 0);
351 if (!x || *x || errno)
352 return errno ? -errno : -EINVAL;
354 if ((unsigned long) (unsigned) l != l)
357 *ret_u = (unsigned) l;
361 int safe_atoi(const char *s, int *ret_i) {
369 l = strtol(s, &x, 0);
371 if (!x || *x || errno)
372 return errno ? -errno : -EINVAL;
374 if ((long) (int) l != l)
381 int safe_atollu(const char *s, long long unsigned *ret_llu) {
383 unsigned long long l;
389 l = strtoull(s, &x, 0);
391 if (!x || *x || errno)
392 return errno ? -errno : -EINVAL;
398 int safe_atolli(const char *s, long long int *ret_lli) {
406 l = strtoll(s, &x, 0);
408 if (!x || *x || errno)
409 return errno ? -errno : -EINVAL;
415 /* Split a string into words. */
416 char *split(const char *c, size_t *l, const char *separator, char **state) {
419 current = *state ? *state : (char*) c;
421 if (!*current || *c == 0)
424 current += strspn(current, separator);
425 *l = strcspn(current, separator);
428 return (char*) current;
431 /* Split a string into words, but consider strings enclosed in '' and
432 * "" as words even if they include spaces. */
433 char *split_quoted(const char *c, size_t *l, char **state) {
435 bool escaped = false;
437 current = *state ? *state : (char*) c;
439 if (!*current || *c == 0)
442 current += strspn(current, WHITESPACE);
444 if (*current == '\'') {
447 for (e = current; *e; e++) {
457 *state = *e == 0 ? e : e+1;
458 } else if (*current == '\"') {
461 for (e = current; *e; e++) {
471 *state = *e == 0 ? e : e+1;
473 for (e = current; *e; e++) {
478 else if (strchr(WHITESPACE, *e))
485 return (char*) current;
488 char **split_path_and_make_absolute(const char *p) {
492 if (!(l = strv_split(p, ":")))
495 if (!strv_path_make_absolute_cwd(l)) {
503 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
506 char fn[PATH_MAX], line[LINE_MAX], *p;
512 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
515 if (!(f = fopen(fn, "re")))
518 if (!(fgets(line, sizeof(line), f))) {
526 /* Let's skip the pid and comm fields. The latter is enclosed
527 * in () but does not escape any () in its value, so let's
528 * skip over it manually */
530 if (!(p = strrchr(line, ')')))
541 if ((long unsigned) (pid_t) ppid != ppid)
544 *_ppid = (pid_t) ppid;
549 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
552 char fn[PATH_MAX], line[LINE_MAX], *p;
557 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
560 if (!(f = fopen(fn, "re")))
563 if (!(fgets(line, sizeof(line), f))) {
571 /* Let's skip the pid and comm fields. The latter is enclosed
572 * in () but does not escape any () in its value, so let's
573 * skip over it manually */
575 if (!(p = strrchr(line, ')')))
596 "%*d " /* priority */
598 "%*d " /* num_threads */
599 "%*d " /* itrealvalue */
600 "%llu " /* starttime */,
607 int write_one_line_file(const char *fn, const char *line) {
614 if (!(f = fopen(fn, "we")))
618 if (fputs(line, f) < 0) {
623 if (!endswith(line, "\n"))
641 int fchmod_umask(int fd, mode_t m) {
646 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
652 int write_one_line_file_atomic(const char *fn, const char *line) {
660 r = fopen_temporary(fn, &f, &p);
664 fchmod_umask(fileno(f), 0644);
667 if (fputs(line, f) < 0) {
672 if (!endswith(line, "\n"))
683 if (rename(p, fn) < 0)
699 int read_one_line_file(const char *fn, char **line) {
702 char t[LINE_MAX], *c;
707 if (!(f = fopen(fn, "re")))
710 if (!(fgets(t, sizeof(t), f))) {
715 if (!(c = strdup(t))) {
730 int read_full_file(const char *fn, char **contents, size_t *size) {
737 if (!(f = fopen(fn, "re")))
740 if (fstat(fileno(f), &st) < 0) {
746 if (st.st_size > 4*1024*1024) {
751 n = st.st_size > 0 ? st.st_size : LINE_MAX;
758 if (!(t = realloc(buf, n+1))) {
764 k = fread(buf + l, 1, n - l, f);
779 if (n > 4*1024*1024) {
803 const char *separator, ...) {
806 char *contents = NULL, *p;
811 if ((r = read_full_file(fname, &contents, NULL)) < 0)
816 const char *key = NULL;
818 p += strspn(p, separator);
819 p += strspn(p, WHITESPACE);
824 if (!strchr(COMMENTS, *p)) {
828 va_start(ap, separator);
829 while ((key = va_arg(ap, char *))) {
833 value = va_arg(ap, char **);
836 if (strncmp(p, key, n) != 0 ||
841 n = strcspn(p, separator);
844 strchr(QUOTES, p[0]) &&
846 v = strndup(p+1, n-2);
857 /* return empty value strings as NULL */
874 p += strcspn(p, separator);
893 if (!(f = fopen(fname, "re")))
897 char l[LINE_MAX], *p, *u;
900 if (!fgets(l, sizeof(l), f)) {
913 if (strchr(COMMENTS, *p))
916 if (!(u = normalize_env_assignment(p))) {
917 log_error("Out of memory");
922 t = strv_append(m, u);
926 log_error("Out of memory");
949 int write_env_file(const char *fname, char **l) {
954 r = fopen_temporary(fname, &f, &p);
958 fchmod_umask(fileno(f), 0644);
974 if (rename(p, fname) < 0)
989 char *truncate_nl(char *s) {
992 s[strcspn(s, NEWLINE)] = 0;
996 int get_process_name(pid_t pid, char **name) {
1003 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
1006 r = read_one_line_file(p, name);
1015 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
1023 assert(max_length > 0);
1026 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1035 if (!(r = new(char, max_length))) {
1042 while ((c = getc(f)) != EOF) {
1064 size_t n = MIN(left-1, 3U);
1065 memcpy(k, "...", n);
1072 /* Kernel threads have no argv[] */
1079 if ((h = get_process_name(pid, &t)) < 0)
1082 h = asprintf(&r, "[%s]", t);
1093 char *strnappend(const char *s, const char *suffix, size_t b) {
1101 return strndup(suffix, b);
1111 if (!(r = new(char, a+b+1)))
1115 memcpy(r+a, suffix, b);
1121 char *strappend(const char *s, const char *suffix) {
1122 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1125 int readlink_malloc(const char *p, char **r) {
1135 if (!(c = new(char, l)))
1138 if ((n = readlink(p, c, l-1)) < 0) {
1144 if ((size_t) n < l-1) {
1155 int readlink_and_make_absolute(const char *p, char **r) {
1162 if ((j = readlink_malloc(p, &target)) < 0)
1165 k = file_in_same_dir(p, target);
1175 int readlink_and_canonicalize(const char *p, char **r) {
1182 j = readlink_and_make_absolute(p, &t);
1186 s = canonicalize_file_name(t);
1193 path_kill_slashes(*r);
1198 int parent_of_path(const char *path, char **_r) {
1199 const char *e, *a = NULL, *b = NULL, *p;
1209 for (e = path; *e; e++) {
1211 if (!slash && *e == '/') {
1215 } else if (slash && *e != '/')
1230 r = strndup(path, p-path);
1240 char *file_name_from_path(const char *p) {
1245 if ((r = strrchr(p, '/')))
1251 bool path_is_absolute(const char *p) {
1257 bool is_path(const char *p) {
1259 return !!strchr(p, '/');
1262 char *path_make_absolute(const char *p, const char *prefix) {
1265 /* Makes every item in the list an absolute path by prepending
1266 * the prefix, if specified and necessary */
1268 if (path_is_absolute(p) || !prefix)
1271 return join(prefix, "/", p, NULL);
1274 char *path_make_absolute_cwd(const char *p) {
1279 /* Similar to path_make_absolute(), but prefixes with the
1280 * current working directory. */
1282 if (path_is_absolute(p))
1285 if (!(cwd = get_current_dir_name()))
1288 r = path_make_absolute(p, cwd);
1294 char **strv_path_make_absolute_cwd(char **l) {
1297 /* Goes through every item in the string list and makes it
1298 * absolute. This works in place and won't rollback any
1299 * changes on failure. */
1301 STRV_FOREACH(s, l) {
1304 if (!(t = path_make_absolute_cwd(*s)))
1314 char **strv_path_canonicalize(char **l) {
1317 bool enomem = false;
1319 if (strv_isempty(l))
1322 /* Goes through every item in the string list and canonicalize
1323 * the path. This works in place and won't rollback any
1324 * changes on failure. */
1326 STRV_FOREACH(s, l) {
1329 t = path_make_absolute_cwd(*s);
1338 u = canonicalize_file_name(t);
1342 if (errno == ENOMEM || !errno)
1359 char **strv_path_remove_empty(char **l) {
1365 for (f = t = l; *f; f++) {
1367 if (dir_is_empty(*f) > 0) {
1379 int reset_all_signal_handlers(void) {
1382 for (sig = 1; sig < _NSIG; sig++) {
1383 struct sigaction sa;
1385 if (sig == SIGKILL || sig == SIGSTOP)
1389 sa.sa_handler = SIG_DFL;
1390 sa.sa_flags = SA_RESTART;
1392 /* On Linux the first two RT signals are reserved by
1393 * glibc, and sigaction() will return EINVAL for them. */
1394 if ((sigaction(sig, &sa, NULL) < 0))
1395 if (errno != EINVAL)
1402 char *strstrip(char *s) {
1405 /* Drops trailing whitespace. Modifies the string in
1406 * place. Returns pointer to first non-space character */
1408 s += strspn(s, WHITESPACE);
1410 for (e = strchr(s, 0); e > s; e --)
1411 if (!strchr(WHITESPACE, e[-1]))
1419 char *delete_chars(char *s, const char *bad) {
1422 /* Drops all whitespace, regardless where in the string */
1424 for (f = s, t = s; *f; f++) {
1425 if (strchr(bad, *f))
1436 bool in_charset(const char *s, const char* charset) {
1442 for (i = s; *i; i++)
1443 if (!strchr(charset, *i))
1449 char *file_in_same_dir(const char *path, const char *filename) {
1456 /* This removes the last component of path and appends
1457 * filename, unless the latter is absolute anyway or the
1460 if (path_is_absolute(filename))
1461 return strdup(filename);
1463 if (!(e = strrchr(path, '/')))
1464 return strdup(filename);
1466 k = strlen(filename);
1467 if (!(r = new(char, e-path+1+k+1)))
1470 memcpy(r, path, e-path+1);
1471 memcpy(r+(e-path)+1, filename, k+1);
1476 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1479 if (label_mkdir(path, mode) >= 0)
1480 if (chmod_and_chown(path, mode, uid, gid) < 0)
1483 if (lstat(path, &st) < 0)
1486 if ((st.st_mode & 0777) != mode ||
1489 !S_ISDIR(st.st_mode)) {
1498 int mkdir_parents(const char *path, mode_t mode) {
1503 /* Creates every parent directory in the path except the last
1506 p = path + strspn(path, "/");
1511 e = p + strcspn(p, "/");
1512 p = e + strspn(e, "/");
1514 /* Is this the last component? If so, then we're
1519 if (!(t = strndup(path, e - path)))
1522 r = label_mkdir(t, mode);
1525 if (r < 0 && errno != EEXIST)
1530 int mkdir_p(const char *path, mode_t mode) {
1535 if ((r = mkdir_parents(path, mode)) < 0)
1538 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1544 int rmdir_parents(const char *path, const char *stop) {
1553 /* Skip trailing slashes */
1554 while (l > 0 && path[l-1] == '/')
1560 /* Skip last component */
1561 while (l > 0 && path[l-1] != '/')
1564 /* Skip trailing slashes */
1565 while (l > 0 && path[l-1] == '/')
1571 if (!(t = strndup(path, l)))
1574 if (path_startswith(stop, t)) {
1583 if (errno != ENOENT)
1591 char hexchar(int x) {
1592 static const char table[16] = "0123456789abcdef";
1594 return table[x & 15];
1597 int unhexchar(char c) {
1599 if (c >= '0' && c <= '9')
1602 if (c >= 'a' && c <= 'f')
1603 return c - 'a' + 10;
1605 if (c >= 'A' && c <= 'F')
1606 return c - 'A' + 10;
1611 char octchar(int x) {
1612 return '0' + (x & 7);
1615 int unoctchar(char c) {
1617 if (c >= '0' && c <= '7')
1623 char decchar(int x) {
1624 return '0' + (x % 10);
1627 int undecchar(char c) {
1629 if (c >= '0' && c <= '9')
1635 char *cescape(const char *s) {
1641 /* Does C style string escaping. */
1643 if (!(r = new(char, strlen(s)*4 + 1)))
1646 for (f = s, t = r; *f; f++)
1692 /* For special chars we prefer octal over
1693 * hexadecimal encoding, simply because glib's
1694 * g_strescape() does the same */
1695 if ((*f < ' ') || (*f >= 127)) {
1697 *(t++) = octchar((unsigned char) *f >> 6);
1698 *(t++) = octchar((unsigned char) *f >> 3);
1699 *(t++) = octchar((unsigned char) *f);
1710 char *cunescape_length(const char *s, size_t length) {
1716 /* Undoes C style string escaping */
1718 if (!(r = new(char, length+1)))
1721 for (f = s, t = r; f < s + length; f++) {
1764 /* This is an extension of the XDG syntax files */
1769 /* hexadecimal encoding */
1772 if ((a = unhexchar(f[1])) < 0 ||
1773 (b = unhexchar(f[2])) < 0) {
1774 /* Invalid escape code, let's take it literal then */
1778 *(t++) = (char) ((a << 4) | b);
1793 /* octal encoding */
1796 if ((a = unoctchar(f[0])) < 0 ||
1797 (b = unoctchar(f[1])) < 0 ||
1798 (c = unoctchar(f[2])) < 0) {
1799 /* Invalid escape code, let's take it literal then */
1803 *(t++) = (char) ((a << 6) | (b << 3) | c);
1811 /* premature end of string.*/
1816 /* Invalid escape code, let's take it literal then */
1828 char *cunescape(const char *s) {
1829 return cunescape_length(s, strlen(s));
1832 char *xescape(const char *s, const char *bad) {
1836 /* Escapes all chars in bad, in addition to \ and all special
1837 * chars, in \xFF style escaping. May be reversed with
1840 if (!(r = new(char, strlen(s)*4+1)))
1843 for (f = s, t = r; *f; f++) {
1845 if ((*f < ' ') || (*f >= 127) ||
1846 (*f == '\\') || strchr(bad, *f)) {
1849 *(t++) = hexchar(*f >> 4);
1850 *(t++) = hexchar(*f);
1860 char *bus_path_escape(const char *s) {
1866 /* Escapes all chars that D-Bus' object path cannot deal
1867 * with. Can be reverse with bus_path_unescape() */
1869 if (!(r = new(char, strlen(s)*3+1)))
1872 for (f = s, t = r; *f; f++) {
1874 if (!(*f >= 'A' && *f <= 'Z') &&
1875 !(*f >= 'a' && *f <= 'z') &&
1876 !(*f >= '0' && *f <= '9')) {
1878 *(t++) = hexchar(*f >> 4);
1879 *(t++) = hexchar(*f);
1889 char *bus_path_unescape(const char *f) {
1894 if (!(r = strdup(f)))
1897 for (t = r; *f; f++) {
1902 if ((a = unhexchar(f[1])) < 0 ||
1903 (b = unhexchar(f[2])) < 0) {
1904 /* Invalid escape code, let's take it literal then */
1907 *(t++) = (char) ((a << 4) | b);
1919 char *path_kill_slashes(char *path) {
1923 /* Removes redundant inner and trailing slashes. Modifies the
1924 * passed string in-place.
1926 * ///foo///bar/ becomes /foo/bar
1929 for (f = path, t = path; *f; f++) {
1944 /* Special rule, if we are talking of the root directory, a
1945 trailing slash is good */
1947 if (t == path && slash)
1954 bool path_startswith(const char *path, const char *prefix) {
1958 if ((path[0] == '/') != (prefix[0] == '/'))
1964 path += strspn(path, "/");
1965 prefix += strspn(prefix, "/");
1973 a = strcspn(path, "/");
1974 b = strcspn(prefix, "/");
1979 if (memcmp(path, prefix, a) != 0)
1987 bool path_equal(const char *a, const char *b) {
1991 if ((a[0] == '/') != (b[0] == '/'))
1997 a += strspn(a, "/");
1998 b += strspn(b, "/");
2000 if (*a == 0 && *b == 0)
2003 if (*a == 0 || *b == 0)
2006 j = strcspn(a, "/");
2007 k = strcspn(b, "/");
2012 if (memcmp(a, b, j) != 0)
2020 char *ascii_strlower(char *t) {
2025 for (p = t; *p; p++)
2026 if (*p >= 'A' && *p <= 'Z')
2027 *p = *p - 'A' + 'a';
2032 bool ignore_file(const char *filename) {
2036 filename[0] == '.' ||
2037 streq(filename, "lost+found") ||
2038 streq(filename, "aquota.user") ||
2039 streq(filename, "aquota.group") ||
2040 endswith(filename, "~") ||
2041 endswith(filename, ".rpmnew") ||
2042 endswith(filename, ".rpmsave") ||
2043 endswith(filename, ".rpmorig") ||
2044 endswith(filename, ".dpkg-old") ||
2045 endswith(filename, ".dpkg-new") ||
2046 endswith(filename, ".swp");
2049 int fd_nonblock(int fd, bool nonblock) {
2054 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2058 flags |= O_NONBLOCK;
2060 flags &= ~O_NONBLOCK;
2062 if (fcntl(fd, F_SETFL, flags) < 0)
2068 int fd_cloexec(int fd, bool cloexec) {
2073 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2077 flags |= FD_CLOEXEC;
2079 flags &= ~FD_CLOEXEC;
2081 if (fcntl(fd, F_SETFD, flags) < 0)
2087 int close_all_fds(const int except[], unsigned n_except) {
2092 if (!(d = opendir("/proc/self/fd")))
2095 while ((de = readdir(d))) {
2098 if (ignore_file(de->d_name))
2101 if (safe_atoi(de->d_name, &fd) < 0)
2102 /* Let's better ignore this, just in case */
2116 for (i = 0; i < n_except; i++)
2117 if (except[i] == fd) {
2126 if (close_nointr(fd) < 0) {
2127 /* Valgrind has its own FD and doesn't want to have it closed */
2128 if (errno != EBADF && r == 0)
2137 bool chars_intersect(const char *a, const char *b) {
2140 /* Returns true if any of the chars in a are in b. */
2141 for (p = a; *p; p++)
2148 char *format_timestamp(char *buf, size_t l, usec_t t) {
2158 sec = (time_t) (t / USEC_PER_SEC);
2160 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2166 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2169 n = now(CLOCK_REALTIME);
2171 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2176 if (d >= USEC_PER_YEAR)
2177 snprintf(buf, l, "%llu years and %llu months ago",
2178 (unsigned long long) (d / USEC_PER_YEAR),
2179 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2180 else if (d >= USEC_PER_MONTH)
2181 snprintf(buf, l, "%llu months and %llu days ago",
2182 (unsigned long long) (d / USEC_PER_MONTH),
2183 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2184 else if (d >= USEC_PER_WEEK)
2185 snprintf(buf, l, "%llu weeks and %llu days ago",
2186 (unsigned long long) (d / USEC_PER_WEEK),
2187 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2188 else if (d >= 2*USEC_PER_DAY)
2189 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2190 else if (d >= 25*USEC_PER_HOUR)
2191 snprintf(buf, l, "1 day and %lluh ago",
2192 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2193 else if (d >= 6*USEC_PER_HOUR)
2194 snprintf(buf, l, "%lluh ago",
2195 (unsigned long long) (d / USEC_PER_HOUR));
2196 else if (d >= USEC_PER_HOUR)
2197 snprintf(buf, l, "%lluh %llumin ago",
2198 (unsigned long long) (d / USEC_PER_HOUR),
2199 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2200 else if (d >= 5*USEC_PER_MINUTE)
2201 snprintf(buf, l, "%llumin ago",
2202 (unsigned long long) (d / USEC_PER_MINUTE));
2203 else if (d >= USEC_PER_MINUTE)
2204 snprintf(buf, l, "%llumin %llus ago",
2205 (unsigned long long) (d / USEC_PER_MINUTE),
2206 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2207 else if (d >= USEC_PER_SEC)
2208 snprintf(buf, l, "%llus ago",
2209 (unsigned long long) (d / USEC_PER_SEC));
2210 else if (d >= USEC_PER_MSEC)
2211 snprintf(buf, l, "%llums ago",
2212 (unsigned long long) (d / USEC_PER_MSEC));
2214 snprintf(buf, l, "%lluus ago",
2215 (unsigned long long) d);
2217 snprintf(buf, l, "now");
2223 char *format_timespan(char *buf, size_t l, usec_t t) {
2224 static const struct {
2228 { "w", USEC_PER_WEEK },
2229 { "d", USEC_PER_DAY },
2230 { "h", USEC_PER_HOUR },
2231 { "min", USEC_PER_MINUTE },
2232 { "s", USEC_PER_SEC },
2233 { "ms", USEC_PER_MSEC },
2243 if (t == (usec_t) -1)
2247 snprintf(p, l, "0");
2252 /* The result of this function can be parsed with parse_usec */
2254 for (i = 0; i < ELEMENTSOF(table); i++) {
2258 if (t < table[i].usec)
2264 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2265 n = MIN((size_t) k, l);
2278 bool fstype_is_network(const char *fstype) {
2279 static const char * const table[] = {
2291 for (i = 0; i < ELEMENTSOF(table); i++)
2292 if (streq(table[i], fstype))
2301 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2306 TIOCL_GETKMSGREDIRECT,
2310 if (ioctl(fd, TIOCLINUX, tiocl) < 0) {
2315 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2318 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2322 close_nointr_nofail(fd);
2326 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2327 struct termios old_termios, new_termios;
2329 char line[LINE_MAX];
2334 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2335 new_termios = old_termios;
2337 new_termios.c_lflag &= ~ICANON;
2338 new_termios.c_cc[VMIN] = 1;
2339 new_termios.c_cc[VTIME] = 0;
2341 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2344 k = fread(&c, 1, 1, f);
2346 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2352 *need_nl = c != '\n';
2359 if (!(fgets(line, sizeof(line), f)))
2364 if (strlen(line) != 1)
2374 int ask(char *ret, const char *replies, const char *text, ...) {
2381 on_tty = isatty(STDOUT_FILENO);
2387 bool need_nl = true;
2390 fputs("\x1B[1m", stdout);
2397 fputs("\x1B[0m", stdout);
2401 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2403 if (r == -EBADMSG) {
2404 puts("Bad input, please try again.");
2415 if (strchr(replies, c)) {
2420 puts("Read unexpected character, please try again.");
2424 int reset_terminal_fd(int fd) {
2425 struct termios termios;
2429 /* Set terminal to some sane defaults */
2433 /* We leave locked terminal attributes untouched, so that
2434 * Plymouth may set whatever it wants to set, and we don't
2435 * interfere with that. */
2437 /* Disable exclusive mode, just in case */
2438 ioctl(fd, TIOCNXCL);
2440 /* Enable console unicode mode */
2442 ioctl(fd, KDSKBMODE, &arg);
2444 if (tcgetattr(fd, &termios) < 0) {
2449 /* We only reset the stuff that matters to the software. How
2450 * hardware is set up we don't touch assuming that somebody
2451 * else will do that for us */
2453 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2454 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2455 termios.c_oflag |= ONLCR;
2456 termios.c_cflag |= CREAD;
2457 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2459 termios.c_cc[VINTR] = 03; /* ^C */
2460 termios.c_cc[VQUIT] = 034; /* ^\ */
2461 termios.c_cc[VERASE] = 0177;
2462 termios.c_cc[VKILL] = 025; /* ^X */
2463 termios.c_cc[VEOF] = 04; /* ^D */
2464 termios.c_cc[VSTART] = 021; /* ^Q */
2465 termios.c_cc[VSTOP] = 023; /* ^S */
2466 termios.c_cc[VSUSP] = 032; /* ^Z */
2467 termios.c_cc[VLNEXT] = 026; /* ^V */
2468 termios.c_cc[VWERASE] = 027; /* ^W */
2469 termios.c_cc[VREPRINT] = 022; /* ^R */
2470 termios.c_cc[VEOL] = 0;
2471 termios.c_cc[VEOL2] = 0;
2473 termios.c_cc[VTIME] = 0;
2474 termios.c_cc[VMIN] = 1;
2476 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2480 /* Just in case, flush all crap out */
2481 tcflush(fd, TCIOFLUSH);
2486 int reset_terminal(const char *name) {
2489 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2493 r = reset_terminal_fd(fd);
2494 close_nointr_nofail(fd);
2499 int open_terminal(const char *name, int mode) {
2504 * If a TTY is in the process of being closed opening it might
2505 * cause EIO. This is horribly awful, but unlikely to be
2506 * changed in the kernel. Hence we work around this problem by
2507 * retrying a couple of times.
2509 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2513 if ((fd = open(name, mode)) >= 0)
2522 usleep(50 * USEC_PER_MSEC);
2529 if ((r = isatty(fd)) < 0) {
2530 close_nointr_nofail(fd);
2535 close_nointr_nofail(fd);
2542 int flush_fd(int fd) {
2543 struct pollfd pollfd;
2547 pollfd.events = POLLIN;
2554 if ((r = poll(&pollfd, 1, 0)) < 0) {
2565 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2570 if (errno == EAGAIN)
2581 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2582 int fd = -1, notify = -1, r, wd = -1;
2586 /* We use inotify to be notified when the tty is closed. We
2587 * create the watch before checking if we can actually acquire
2588 * it, so that we don't lose any event.
2590 * Note: strictly speaking this actually watches for the
2591 * device being closed, it does *not* really watch whether a
2592 * tty loses its controlling process. However, unless some
2593 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2594 * its tty otherwise this will not become a problem. As long
2595 * as the administrator makes sure not configure any service
2596 * on the same tty as an untrusted user this should not be a
2597 * problem. (Which he probably should not do anyway.) */
2599 if (!fail && !force) {
2600 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2605 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2613 if ((r = flush_fd(notify)) < 0)
2616 /* We pass here O_NOCTTY only so that we can check the return
2617 * value TIOCSCTTY and have a reliable way to figure out if we
2618 * successfully became the controlling process of the tty */
2619 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2622 /* First, try to get the tty */
2623 r = ioctl(fd, TIOCSCTTY, force);
2625 /* Sometimes it makes sense to ignore TIOCSCTTY
2626 * returning EPERM, i.e. when very likely we already
2627 * are have this controlling terminal. */
2628 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2631 if (r < 0 && (force || fail || errno != EPERM)) {
2641 assert(notify >= 0);
2644 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2646 struct inotify_event *e;
2648 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2657 e = (struct inotify_event*) inotify_buffer;
2662 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2667 step = sizeof(struct inotify_event) + e->len;
2668 assert(step <= (size_t) l);
2670 e = (struct inotify_event*) ((uint8_t*) e + step);
2677 /* We close the tty fd here since if the old session
2678 * ended our handle will be dead. It's important that
2679 * we do this after sleeping, so that we don't enter
2680 * an endless loop. */
2681 close_nointr_nofail(fd);
2685 close_nointr_nofail(notify);
2687 if ((r = reset_terminal_fd(fd)) < 0)
2688 log_warning("Failed to reset terminal: %s", strerror(-r));
2694 close_nointr_nofail(fd);
2697 close_nointr_nofail(notify);
2702 int release_terminal(void) {
2704 struct sigaction sa_old, sa_new;
2706 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2709 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2710 * by our own TIOCNOTTY */
2713 sa_new.sa_handler = SIG_IGN;
2714 sa_new.sa_flags = SA_RESTART;
2715 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2717 if (ioctl(fd, TIOCNOTTY) < 0)
2720 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2722 close_nointr_nofail(fd);
2726 int sigaction_many(const struct sigaction *sa, ...) {
2731 while ((sig = va_arg(ap, int)) > 0)
2732 if (sigaction(sig, sa, NULL) < 0)
2739 int ignore_signals(int sig, ...) {
2740 struct sigaction sa;
2745 sa.sa_handler = SIG_IGN;
2746 sa.sa_flags = SA_RESTART;
2748 if (sigaction(sig, &sa, NULL) < 0)
2752 while ((sig = va_arg(ap, int)) > 0)
2753 if (sigaction(sig, &sa, NULL) < 0)
2760 int default_signals(int sig, ...) {
2761 struct sigaction sa;
2766 sa.sa_handler = SIG_DFL;
2767 sa.sa_flags = SA_RESTART;
2769 if (sigaction(sig, &sa, NULL) < 0)
2773 while ((sig = va_arg(ap, int)) > 0)
2774 if (sigaction(sig, &sa, NULL) < 0)
2781 int close_pipe(int p[]) {
2787 a = close_nointr(p[0]);
2792 b = close_nointr(p[1]);
2796 return a < 0 ? a : b;
2799 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2808 while (nbytes > 0) {
2811 if ((k = read(fd, p, nbytes)) <= 0) {
2813 if (k < 0 && errno == EINTR)
2816 if (k < 0 && errno == EAGAIN && do_poll) {
2817 struct pollfd pollfd;
2821 pollfd.events = POLLIN;
2823 if (poll(&pollfd, 1, -1) < 0) {
2827 return n > 0 ? n : -errno;
2830 if (pollfd.revents != POLLIN)
2831 return n > 0 ? n : -EIO;
2836 return n > 0 ? n : (k < 0 ? -errno : 0);
2847 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2856 while (nbytes > 0) {
2859 if ((k = write(fd, p, nbytes)) <= 0) {
2861 if (k < 0 && errno == EINTR)
2864 if (k < 0 && errno == EAGAIN && do_poll) {
2865 struct pollfd pollfd;
2869 pollfd.events = POLLOUT;
2871 if (poll(&pollfd, 1, -1) < 0) {
2875 return n > 0 ? n : -errno;
2878 if (pollfd.revents != POLLOUT)
2879 return n > 0 ? n : -EIO;
2884 return n > 0 ? n : (k < 0 ? -errno : 0);
2895 int path_is_mount_point(const char *t, bool allow_symlink) {
2906 if (errno == ENOENT)
2912 r = parent_of_path(t, &parent);
2916 r = lstat(parent, &b);
2922 return a.st_dev != b.st_dev;
2925 int parse_usec(const char *t, usec_t *usec) {
2926 static const struct {
2930 { "sec", USEC_PER_SEC },
2931 { "s", USEC_PER_SEC },
2932 { "min", USEC_PER_MINUTE },
2933 { "hr", USEC_PER_HOUR },
2934 { "h", USEC_PER_HOUR },
2935 { "d", USEC_PER_DAY },
2936 { "w", USEC_PER_WEEK },
2937 { "msec", USEC_PER_MSEC },
2938 { "ms", USEC_PER_MSEC },
2939 { "m", USEC_PER_MINUTE },
2942 { "", USEC_PER_SEC },
2958 l = strtoll(p, &e, 10);
2969 e += strspn(e, WHITESPACE);
2971 for (i = 0; i < ELEMENTSOF(table); i++)
2972 if (startswith(e, table[i].suffix)) {
2973 r += (usec_t) l * table[i].usec;
2974 p = e + strlen(table[i].suffix);
2978 if (i >= ELEMENTSOF(table))
2988 int parse_bytes(const char *t, off_t *bytes) {
2989 static const struct {
2995 { "M", 1024ULL*1024ULL },
2996 { "G", 1024ULL*1024ULL*1024ULL },
2997 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3014 l = strtoll(p, &e, 10);
3025 e += strspn(e, WHITESPACE);
3027 for (i = 0; i < ELEMENTSOF(table); i++)
3028 if (startswith(e, table[i].suffix)) {
3029 r += (off_t) l * table[i].factor;
3030 p = e + strlen(table[i].suffix);
3034 if (i >= ELEMENTSOF(table))
3044 int make_stdio(int fd) {
3049 r = dup2(fd, STDIN_FILENO);
3050 s = dup2(fd, STDOUT_FILENO);
3051 t = dup2(fd, STDERR_FILENO);
3054 close_nointr_nofail(fd);
3056 if (r < 0 || s < 0 || t < 0)
3059 fd_cloexec(STDIN_FILENO, false);
3060 fd_cloexec(STDOUT_FILENO, false);
3061 fd_cloexec(STDERR_FILENO, false);
3066 int make_null_stdio(void) {
3069 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3072 return make_stdio(null_fd);
3075 bool is_device_path(const char *path) {
3077 /* Returns true on paths that refer to a device, either in
3078 * sysfs or in /dev */
3081 path_startswith(path, "/dev/") ||
3082 path_startswith(path, "/sys/");
3085 int dir_is_empty(const char *path) {
3088 struct dirent buf, *de;
3090 if (!(d = opendir(path)))
3094 if ((r = readdir_r(d, &buf, &de)) > 0) {
3104 if (!ignore_file(de->d_name)) {
3114 unsigned long long random_ull(void) {
3119 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3122 r = loop_read(fd, &ull, sizeof(ull), true);
3123 close_nointr_nofail(fd);
3125 if (r != sizeof(ull))
3131 return random() * RAND_MAX + random();
3134 void rename_process(const char name[8]) {
3137 prctl(PR_SET_NAME, name);
3139 /* This is a like a poor man's setproctitle(). The string
3140 * passed should fit in 7 chars (i.e. the length of
3143 if (program_invocation_name)
3144 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3146 if (saved_argc > 0) {
3150 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3152 for (i = 1; i < saved_argc; i++) {
3156 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3161 void sigset_add_many(sigset_t *ss, ...) {
3168 while ((sig = va_arg(ap, int)) > 0)
3169 assert_se(sigaddset(ss, sig) == 0);
3173 char* gethostname_malloc(void) {
3176 assert_se(uname(&u) >= 0);
3179 return strdup(u.nodename);
3181 return strdup(u.sysname);
3184 char* getlogname_malloc(void) {
3188 struct passwd pwbuf, *pw = NULL;
3191 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3196 /* Shortcut things to avoid NSS lookups */
3198 return strdup("root");
3200 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3203 if (!(buf = malloc(bufsize)))
3206 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3207 name = strdup(pw->pw_name);
3214 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3220 int getttyname_malloc(int fd, char **r) {
3221 char path[PATH_MAX], *c;
3226 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3231 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3238 int getttyname_harder(int fd, char **r) {
3242 if ((k = getttyname_malloc(fd, &s)) < 0)
3245 if (streq(s, "tty")) {
3247 return get_ctty(0, NULL, r);
3254 int get_ctty_devnr(pid_t pid, dev_t *d) {
3256 char line[LINE_MAX], *p, *fn;
3257 unsigned long ttynr;
3260 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3263 f = fopen(fn, "re");
3268 if (!fgets(line, sizeof(line), f)) {
3276 p = strrchr(line, ')');
3286 "%*d " /* session */
3295 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3297 char fn[PATH_MAX], *s, *b, *p;
3302 k = get_ctty_devnr(pid, &devnr);
3306 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3309 if ((k = readlink_malloc(fn, &s)) < 0) {
3314 /* This is an ugly hack */
3315 if (major(devnr) == 136) {
3316 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3326 /* Probably something like the ptys which have no
3327 * symlink in /dev/char. Let's return something
3328 * vaguely useful. */
3330 if (!(b = strdup(fn + 5)))
3340 if (startswith(s, "/dev/"))
3342 else if (startswith(s, "../"))
3360 static int rm_rf_children(int fd, bool only_dirs, bool honour_sticky) {
3366 /* This returns the first error we run into, but nevertheless
3369 if (!(d = fdopendir(fd))) {
3370 close_nointr_nofail(fd);
3372 return errno == ENOENT ? 0 : -errno;
3376 struct dirent buf, *de;
3377 bool is_dir, keep_around = false;
3380 if ((r = readdir_r(d, &buf, &de)) != 0) {
3389 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3392 if (de->d_type == DT_UNKNOWN) {
3395 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3396 if (ret == 0 && errno != ENOENT)
3402 keep_around = st.st_uid == 0 && (st.st_mode & S_ISVTX);
3404 is_dir = S_ISDIR(st.st_mode);
3407 if (honour_sticky) {
3410 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3411 if (ret == 0 && errno != ENOENT)
3416 keep_around = st.st_uid == 0 && (st.st_mode & S_ISVTX);
3419 is_dir = de->d_type == DT_DIR;
3425 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3426 if (ret == 0 && errno != ENOENT)
3431 if ((r = rm_rf_children(subdir_fd, only_dirs, honour_sticky)) < 0) {
3437 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3438 if (ret == 0 && errno != ENOENT)
3442 } else if (!only_dirs && !keep_around) {
3444 if (unlinkat(fd, de->d_name, 0) < 0) {
3445 if (ret == 0 && errno != ENOENT)
3456 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3462 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3464 if (errno != ENOTDIR)
3467 if (delete_root && !only_dirs)
3468 if (unlink(path) < 0)
3474 r = rm_rf_children(fd, only_dirs, honour_sticky);
3478 if (honour_sticky && file_is_sticky(path) > 0)
3481 if (rmdir(path) < 0 && errno != ENOENT) {
3490 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3493 /* Under the assumption that we are running privileged we
3494 * first change the access mode and only then hand out
3495 * ownership to avoid a window where access is too open. */
3497 if (chmod(path, mode) < 0)
3500 if (chown(path, uid, gid) < 0)
3506 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3510 /* Allocates the cpuset in the right size */
3513 if (!(r = CPU_ALLOC(n)))
3516 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3517 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3527 if (errno != EINVAL)
3534 void status_vprintf(const char *format, va_list ap) {
3540 /* This independent of logging, as status messages are
3541 * optional and go exclusively to the console. */
3543 if (vasprintf(&s, format, ap) < 0)
3546 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3549 write(fd, s, strlen(s));
3555 close_nointr_nofail(fd);
3558 void status_printf(const char *format, ...) {
3563 va_start(ap, format);
3564 status_vprintf(format, ap);
3568 void status_welcome(void) {
3569 char *pretty_name = NULL, *ansi_color = NULL;
3570 const char *const_pretty = NULL, *const_color = NULL;
3573 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3574 "PRETTY_NAME", &pretty_name,
3575 "ANSI_COLOR", &ansi_color,
3579 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3582 #if defined(TARGET_FEDORA)
3584 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3587 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3591 if (!ansi_color && pretty_name) {
3593 /* This tries to mimic the color magic the old Red Hat sysinit
3596 if (startswith(pretty_name, "Red Hat"))
3597 const_color = "0;31"; /* Red for RHEL */
3598 else if (startswith(pretty_name, "Fedora"))
3599 const_color = "0;34"; /* Blue for Fedora */
3602 #elif defined(TARGET_SUSE)
3605 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3608 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3613 const_color = "0;32"; /* Green for openSUSE */
3615 #elif defined(TARGET_GENTOO)
3618 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3621 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3626 const_color = "1;34"; /* Light Blue for Gentoo */
3628 #elif defined(TARGET_ALTLINUX)
3631 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3634 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3639 const_color = "0;36"; /* Cyan for ALTLinux */
3642 #elif defined(TARGET_DEBIAN)
3647 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3650 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3652 pretty_name = strappend("Debian ", version);
3656 log_warning("Failed to allocate Debian version string.");
3661 const_color = "1;31"; /* Light Red for Debian */
3663 #elif defined(TARGET_UBUNTU)
3665 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3666 "DISTRIB_DESCRIPTION", &pretty_name,
3670 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3674 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3676 #elif defined(TARGET_MANDRIVA)
3681 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3683 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3685 p = strstr(s, " release ");
3689 p[strcspn(p, " ")] = '\0';
3691 /* This corresponds to standard rc.sysinit */
3692 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3693 const_color = "1;36";
3695 log_warning("Failed to allocate Mandriva version string.");
3697 log_warning("Failed to parse /etc/mandriva-release");
3701 #elif defined(TARGET_MEEGO)
3704 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3707 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3712 const_color = "1;35"; /* Bright Magenta for MeeGo */
3715 if (!pretty_name && !const_pretty)
3716 const_pretty = "Linux";
3718 if (!ansi_color && !const_color)
3721 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3722 const_color ? const_color : ansi_color,
3723 const_pretty ? const_pretty : pretty_name);
3729 char *replace_env(const char *format, char **env) {
3736 const char *e, *word = format;
3741 for (e = format; *e; e ++) {
3752 if (!(k = strnappend(r, word, e-word-1)))
3761 } else if (*e == '$') {
3762 if (!(k = strnappend(r, word, e-word)))
3778 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3781 if (!(k = strappend(r, t)))
3794 if (!(k = strnappend(r, word, e-word)))
3805 char **replace_env_argv(char **argv, char **env) {
3807 unsigned k = 0, l = 0;
3809 l = strv_length(argv);
3811 if (!(r = new(char*, l+1)))
3814 STRV_FOREACH(i, argv) {
3816 /* If $FOO appears as single word, replace it by the split up variable */
3817 if ((*i)[0] == '$' && (*i)[1] != '{') {
3822 if ((e = strv_env_get(env, *i+1))) {
3824 if (!(m = strv_split_quoted(e))) {
3835 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3844 memcpy(r + k, m, q * sizeof(char*));
3852 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3853 if (!(r[k++] = replace_env(*i, env))) {
3864 static __thread int parsed_columns = 0;
3867 if (_likely_(parsed_columns > 0))
3868 return parsed_columns;
3870 if ((e = getenv("COLUMNS")))
3871 parsed_columns = atoi(e);
3873 if (parsed_columns <= 0) {
3877 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3878 parsed_columns = ws.ws_col;
3881 if (parsed_columns <= 0)
3882 parsed_columns = 80;
3884 return parsed_columns;
3887 int running_in_chroot(void) {
3893 /* Only works as root */
3895 if (stat("/proc/1/root", &a) < 0)
3898 if (stat("/", &b) < 0)
3902 a.st_dev != b.st_dev ||
3903 a.st_ino != b.st_ino;
3906 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3911 assert(percent <= 100);
3912 assert(length >= 3);
3916 if (l <= 3 || l <= length)
3919 if (!(r = new0(char, length+1)))
3922 x = (length * percent) / 100;
3932 s + l - (length - x - 3),
3938 int touch(const char *path) {
3943 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3946 close_nointr_nofail(fd);
3950 char *unquote(const char *s, const char* quotes) {
3954 if ((l = strlen(s)) < 2)
3957 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3958 return strndup(s+1, l-2);
3963 char *normalize_env_assignment(const char *s) {
3964 char *name, *value, *p, *r;
3969 if (!(r = strdup(s)))
3975 if (!(name = strndup(s, p - s)))
3978 if (!(p = strdup(p+1))) {
3983 value = unquote(strstrip(p), QUOTES);
3991 if (asprintf(&r, "%s=%s", name, value) < 0)
4000 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4011 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4023 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4030 if ((r = wait_for_terminate(pid, &status)) < 0) {
4031 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4035 if (status.si_code == CLD_EXITED) {
4036 if (status.si_status != 0) {
4037 log_warning("%s failed with error code %i.", name, status.si_status);
4038 return status.si_status;
4041 log_debug("%s succeeded.", name);
4044 } else if (status.si_code == CLD_KILLED ||
4045 status.si_code == CLD_DUMPED) {
4047 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4051 log_warning("%s failed due to unknown reason.", name);
4058 /* Make sure nobody waits for us on a socket anymore */
4059 close_all_fds(NULL, 0);
4067 bool null_or_empty(struct stat *st) {
4070 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4073 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4079 int null_or_empty_path(const char *fn) {
4084 if (stat(fn, &st) < 0)
4087 return null_or_empty(&st);
4090 DIR *xopendirat(int fd, const char *name, int flags) {
4094 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4097 if (!(d = fdopendir(nfd))) {
4098 close_nointr_nofail(nfd);
4105 int signal_from_string_try_harder(const char *s) {
4109 if ((signo = signal_from_string(s)) <= 0)
4110 if (startswith(s, "SIG"))
4111 return signal_from_string(s+3);
4116 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4122 if (!dual_timestamp_is_set(t))
4125 fprintf(f, "%s=%llu %llu\n",
4127 (unsigned long long) t->realtime,
4128 (unsigned long long) t->monotonic);
4131 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4132 unsigned long long a, b;
4137 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4138 log_debug("Failed to parse finish timestamp value %s", value);
4145 char *fstab_node_to_udev_node(const char *p) {
4149 /* FIXME: to follow udev's logic 100% we need to leave valid
4150 * UTF8 chars unescaped */
4152 if (startswith(p, "LABEL=")) {
4154 if (!(u = unquote(p+6, "\"\'")))
4157 t = xescape(u, "/ ");
4163 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4172 if (startswith(p, "UUID=")) {
4174 if (!(u = unquote(p+5, "\"\'")))
4177 t = xescape(u, "/ ");
4183 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4195 void filter_environ(const char *prefix) {
4202 for (i = 0, j = 0; environ[i]; i++) {
4204 if (startswith(environ[i], prefix))
4207 environ[j++] = environ[i];
4213 bool tty_is_vc(const char *tty) {
4216 if (startswith(tty, "/dev/"))
4219 return vtnr_from_tty(tty) >= 0;
4222 int vtnr_from_tty(const char *tty) {
4227 if (startswith(tty, "/dev/"))
4230 if (!startswith(tty, "tty") )
4233 if (tty[3] < '0' || tty[3] > '9')
4236 r = safe_atoi(tty+3, &i);
4240 if (i < 0 || i > 63)
4246 const char *default_term_for_tty(const char *tty) {
4247 char *active = NULL;
4252 if (startswith(tty, "/dev/"))
4255 /* Resolve where /dev/console is pointing when determining
4257 if (streq(tty, "console"))
4258 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4259 /* If multiple log outputs are configured the
4260 * last one is what /dev/console points to */
4261 if ((tty = strrchr(active, ' ')))
4267 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
4273 bool dirent_is_file(struct dirent *de) {
4276 if (ignore_file(de->d_name))
4279 if (de->d_type != DT_REG &&
4280 de->d_type != DT_LNK &&
4281 de->d_type != DT_UNKNOWN)
4287 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4290 Hashmap *pids = NULL;
4294 /* Executes all binaries in a directory in parallel and waits
4295 * until all they all finished. */
4298 if (!(_d = opendir(directory))) {
4300 if (errno == ENOENT)
4303 log_error("Failed to enumerate directory %s: %m", directory);
4310 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4311 log_error("Failed to allocate set.");
4315 while ((de = readdir(d))) {
4320 if (!dirent_is_file(de))
4323 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4324 log_error("Out of memory");
4328 if ((pid = fork()) < 0) {
4329 log_error("Failed to fork: %m");
4348 log_error("Failed to execute %s: %m", path);
4349 _exit(EXIT_FAILURE);
4352 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4354 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4355 log_error("Failed to add PID to set: %s", strerror(-k));
4360 while (!hashmap_isempty(pids)) {
4365 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4370 log_error("waitid() failed: %m");
4374 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4375 if (!is_clean_exit(si.si_code, si.si_status)) {
4376 if (si.si_code == CLD_EXITED)
4377 log_error("%s exited with exit status %i.", path, si.si_status);
4379 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4381 log_debug("%s exited successfully.", path);
4392 hashmap_free_free(pids);
4395 int kill_and_sigcont(pid_t pid, int sig) {
4398 r = kill(pid, sig) < 0 ? -errno : 0;
4406 bool nulstr_contains(const char*nulstr, const char *needle) {
4412 NULSTR_FOREACH(i, nulstr)
4413 if (streq(i, needle))
4419 bool plymouth_running(void) {
4420 return access("/run/plymouth/pid", F_OK) >= 0;
4423 void parse_syslog_priority(char **p, int *priority) {
4424 int a = 0, b = 0, c = 0;
4434 if (!strchr(*p, '>'))
4437 if ((*p)[2] == '>') {
4438 c = undecchar((*p)[1]);
4440 } else if ((*p)[3] == '>') {
4441 b = undecchar((*p)[1]);
4442 c = undecchar((*p)[2]);
4444 } else if ((*p)[4] == '>') {
4445 a = undecchar((*p)[1]);
4446 b = undecchar((*p)[2]);
4447 c = undecchar((*p)[3]);
4452 if (a < 0 || b < 0 || c < 0)
4455 *priority = a*100+b*10+c;
4459 int have_effective_cap(int value) {
4461 cap_flag_value_t fv;
4464 if (!(cap = cap_get_proc()))
4467 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4476 char* strshorten(char *s, size_t l) {
4485 static bool hostname_valid_char(char c) {
4487 (c >= 'a' && c <= 'z') ||
4488 (c >= 'A' && c <= 'Z') ||
4489 (c >= '0' && c <= '9') ||
4495 bool hostname_is_valid(const char *s) {
4501 for (p = s; *p; p++)
4502 if (!hostname_valid_char(*p))
4505 if (p-s > HOST_NAME_MAX)
4511 char* hostname_cleanup(char *s) {
4514 for (p = s, d = s; *p; p++)
4515 if ((*p >= 'a' && *p <= 'z') ||
4516 (*p >= 'A' && *p <= 'Z') ||
4517 (*p >= '0' && *p <= '9') ||
4525 strshorten(s, HOST_NAME_MAX);
4529 int pipe_eof(int fd) {
4530 struct pollfd pollfd;
4535 pollfd.events = POLLIN|POLLHUP;
4537 r = poll(&pollfd, 1, 0);
4544 return pollfd.revents & POLLHUP;
4547 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4558 t = new(char, strlen(path) + 1 + 6 + 1);
4562 fn = file_name_from_path(path);
4566 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4568 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4574 f = fdopen(fd, "we");
4587 int terminal_vhangup_fd(int fd) {
4590 if (ioctl(fd, TIOCVHANGUP) < 0)
4596 int terminal_vhangup(const char *name) {
4599 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4603 r = terminal_vhangup_fd(fd);
4604 close_nointr_nofail(fd);
4609 int vt_disallocate(const char *name) {
4613 /* Deallocate the VT if possible. If not possible
4614 * (i.e. because it is the active one), at least clear it
4615 * entirely (including the scrollback buffer) */
4617 if (!startswith(name, "/dev/"))
4620 if (!tty_is_vc(name)) {
4621 /* So this is not a VT. I guess we cannot deallocate
4622 * it then. But let's at least clear the screen */
4624 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4629 "\033[r" /* clear scrolling region */
4630 "\033[H" /* move home */
4631 "\033[2J", /* clear screen */
4633 close_nointr_nofail(fd);
4638 if (!startswith(name, "/dev/tty"))
4641 r = safe_atou(name+8, &u);
4648 /* Try to deallocate */
4649 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4653 r = ioctl(fd, VT_DISALLOCATE, u);
4654 close_nointr_nofail(fd);
4662 /* Couldn't deallocate, so let's clear it fully with
4664 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4669 "\033[r" /* clear scrolling region */
4670 "\033[H" /* move home */
4671 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4673 close_nointr_nofail(fd);
4679 static int file_is_conf(const struct dirent *d, const char *suffix) {
4682 if (ignore_file(d->d_name))
4685 if (d->d_type != DT_REG &&
4686 d->d_type != DT_LNK &&
4687 d->d_type != DT_UNKNOWN)
4690 return endswith(d->d_name, suffix);
4693 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4695 struct dirent buffer, *de;
4698 dir = opendir(path);
4700 if (errno == ENOENT)
4709 k = readdir_r(dir, &buffer, &de);
4718 if (!file_is_conf(de, suffix))
4721 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4726 f = canonicalize_file_name(p);
4728 log_error("Failed to canonicalize file name '%s': %m", p);
4734 log_debug("found: %s\n", f);
4735 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
4744 static int base_cmp(const void *a, const void *b) {
4745 const char *s1, *s2;
4747 s1 = *(char * const *)a;
4748 s2 = *(char * const *)b;
4749 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4752 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
4755 char **files = NULL;
4761 dirs = strv_new_ap(dir, ap);
4767 if (!strv_path_canonicalize(dirs)) {
4771 if (!strv_uniq(dirs)) {
4776 fh = hashmap_new(string_hash_func, string_compare_func);
4782 STRV_FOREACH(p, dirs) {
4783 if (files_add(fh, *p, suffix) < 0) {
4784 log_error("Failed to search for files.");
4790 files = hashmap_get_strv(fh);
4791 if (files == NULL) {
4792 log_error("Failed to compose list of files.");
4797 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
4806 int hwclock_is_localtime(void) {
4811 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
4817 f = fopen("/etc/adjtime", "re");
4819 char line[LINE_MAX];
4822 b = fgets(line, sizeof(line), f) &&
4823 fgets(line, sizeof(line), f) &&
4824 fgets(line, sizeof(line), f);
4833 local = streq(line, "LOCAL");
4835 } else if (errno != -ENOENT)
4841 int hwclock_apply_localtime_delta(int *min) {
4842 const struct timeval *tv_null = NULL;
4848 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
4849 assert_se(tm = localtime(&ts.tv_sec));
4850 minuteswest = tm->tm_gmtoff / 60;
4852 tz.tz_minuteswest = -minuteswest;
4853 tz.tz_dsttime = 0; /* DST_NONE*/
4856 * If the hardware clock does not run in UTC, but in local time:
4857 * The very first time we set the kernel's timezone, it will warp
4858 * the clock so that it runs in UTC instead of local time.
4860 if (settimeofday(tv_null, &tz) < 0)
4867 int hwclock_reset_localtime_delta(void) {
4868 const struct timeval *tv_null = NULL;
4871 tz.tz_minuteswest = 0;
4872 tz.tz_dsttime = 0; /* DST_NONE*/
4874 if (settimeofday(tv_null, &tz) < 0)
4880 int hwclock_get_time(struct tm *tm) {
4886 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4890 /* This leaves the timezone fields of struct tm
4892 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
4895 /* We don't now daylight saving, so we reset this in order not
4896 * to confused mktime(). */
4899 close_nointr_nofail(fd);
4904 int hwclock_set_time(const struct tm *tm) {
4910 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4914 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
4917 close_nointr_nofail(fd);
4922 int copy_file(const char *from, const char *to) {
4928 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4932 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4934 close_nointr_nofail(fdf);
4942 n = read(fdf, buf, sizeof(buf));
4946 close_nointr_nofail(fdf);
4957 k = loop_write(fdt, buf, n, false);
4959 r = k < 0 ? k : (errno ? -errno : -EIO);
4961 close_nointr_nofail(fdf);
4969 close_nointr_nofail(fdf);
4970 r = close_nointr(fdt);
4980 int symlink_or_copy(const char *from, const char *to) {
4981 char *pf = NULL, *pt = NULL;
4988 if (parent_of_path(from, &pf) < 0 ||
4989 parent_of_path(to, &pt) < 0) {
4994 if (stat(pf, &a) < 0 ||
5000 if (a.st_dev != b.st_dev) {
5004 return copy_file(from, to);
5007 if (symlink(from, to) < 0) {
5021 int symlink_or_copy_atomic(const char *from, const char *to) {
5025 unsigned long long ull;
5032 t = new(char, strlen(to) + 1 + 16 + 1);
5036 fn = file_name_from_path(to);
5040 x = stpcpy(t+k+1, fn);
5043 for (i = 0; i < 16; i++) {
5044 *(x++) = hexchar(ull & 0xF);
5050 r = symlink_or_copy(from, t);
5057 if (rename(t, to) < 0) {
5068 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5076 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5079 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5082 r = read_one_line_file(p, &s);
5087 r = safe_atou32(s, &u);
5093 if (u == (uint32_t) -1 || u <= 0)
5100 bool display_is_local(const char *display) {
5104 display[0] == ':' &&
5105 display[1] >= '0' &&
5109 int socket_from_display(const char *display, char **path) {
5116 if (!display_is_local(display))
5119 k = strspn(display+1, "0123456789");
5121 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5125 c = stpcpy(f, "/tmp/.X11-unix/X");
5126 memcpy(c, display+1, k);
5134 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5141 /* We enforce some special rules for uid=0: in order to avoid
5142 * NSS lookups for root we hardcode its data. */
5144 if (streq(*username, "root") || streq(*username, "0")) {
5158 if (parse_uid(*username, &u) >= 0) {
5162 /* If there are multiple users with the same id, make
5163 * sure to leave $USER to the configured value instead
5164 * of the first occurrence in the database. However if
5165 * the uid was configured by a numeric uid, then let's
5166 * pick the real username from /etc/passwd. */
5168 *username = p->pw_name;
5171 p = getpwnam(*username);
5175 return errno != 0 ? -errno : -ESRCH;
5189 int get_group_creds(const char **groupname, gid_t *gid) {
5195 /* We enforce some special rules for gid=0: in order to avoid
5196 * NSS lookups for root we hardcode its data. */
5198 if (streq(*groupname, "root") || streq(*groupname, "0")) {
5199 *groupname = "root";
5207 if (parse_gid(*groupname, &id) >= 0) {
5212 *groupname = g->gr_name;
5215 g = getgrnam(*groupname);
5219 return errno != 0 ? -errno : -ESRCH;
5227 int glob_exists(const char *path) {
5235 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5237 if (k == GLOB_NOMATCH)
5239 else if (k == GLOB_NOSPACE)
5242 r = !strv_isempty(g.gl_pathv);
5244 r = errno ? -errno : -EIO;
5251 int dirent_ensure_type(DIR *d, struct dirent *de) {
5257 if (de->d_type != DT_UNKNOWN)
5260 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5264 S_ISREG(st.st_mode) ? DT_REG :
5265 S_ISDIR(st.st_mode) ? DT_DIR :
5266 S_ISLNK(st.st_mode) ? DT_LNK :
5267 S_ISFIFO(st.st_mode) ? DT_FIFO :
5268 S_ISSOCK(st.st_mode) ? DT_SOCK :
5269 S_ISCHR(st.st_mode) ? DT_CHR :
5270 S_ISBLK(st.st_mode) ? DT_BLK :
5276 int in_search_path(const char *path, char **search) {
5280 r = parent_of_path(path, &parent);
5286 STRV_FOREACH(i, search) {
5287 if (path_equal(parent, *i)) {
5298 int get_files_in_directory(const char *path, char ***list) {
5306 /* Returns all files in a directory in *list, and the number
5307 * of files as return value. If list is NULL returns only the
5315 struct dirent buffer, *de;
5318 k = readdir_r(d, &buffer, &de);
5327 dirent_ensure_type(d, de);
5329 if (!dirent_is_file(de))
5333 if ((unsigned) r >= n) {
5337 t = realloc(l, sizeof(char*) * n);
5346 assert((unsigned) r < n);
5348 l[r] = strdup(de->d_name);
5372 char *join(const char *x, ...) {
5385 t = va_arg(ap, const char *);
5408 t = va_arg(ap, const char *);
5422 bool is_main_thread(void) {
5423 static __thread int cached = 0;
5425 if (_unlikely_(cached == 0))
5426 cached = getpid() == gettid() ? 1 : -1;
5431 int block_get_whole_disk(dev_t d, dev_t *ret) {
5438 /* If it has a queue this is good enough for us */
5439 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5442 r = access(p, F_OK);
5450 /* If it is a partition find the originating device */
5451 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5454 r = access(p, F_OK);
5460 /* Get parent dev_t */
5461 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5464 r = read_one_line_file(p, &s);
5470 r = sscanf(s, "%u:%u", &m, &n);
5476 /* Only return this if it is really good enough for us. */
5477 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5480 r = access(p, F_OK);
5484 *ret = makedev(m, n);
5491 int file_is_sticky(const char *p) {
5496 if (lstat(p, &st) < 0)
5501 (st.st_mode & S_ISVTX);
5504 static const char *const ioprio_class_table[] = {
5505 [IOPRIO_CLASS_NONE] = "none",
5506 [IOPRIO_CLASS_RT] = "realtime",
5507 [IOPRIO_CLASS_BE] = "best-effort",
5508 [IOPRIO_CLASS_IDLE] = "idle"
5511 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5513 static const char *const sigchld_code_table[] = {
5514 [CLD_EXITED] = "exited",
5515 [CLD_KILLED] = "killed",
5516 [CLD_DUMPED] = "dumped",
5517 [CLD_TRAPPED] = "trapped",
5518 [CLD_STOPPED] = "stopped",
5519 [CLD_CONTINUED] = "continued",
5522 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5524 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5525 [LOG_FAC(LOG_KERN)] = "kern",
5526 [LOG_FAC(LOG_USER)] = "user",
5527 [LOG_FAC(LOG_MAIL)] = "mail",
5528 [LOG_FAC(LOG_DAEMON)] = "daemon",
5529 [LOG_FAC(LOG_AUTH)] = "auth",
5530 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5531 [LOG_FAC(LOG_LPR)] = "lpr",
5532 [LOG_FAC(LOG_NEWS)] = "news",
5533 [LOG_FAC(LOG_UUCP)] = "uucp",
5534 [LOG_FAC(LOG_CRON)] = "cron",
5535 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5536 [LOG_FAC(LOG_FTP)] = "ftp",
5537 [LOG_FAC(LOG_LOCAL0)] = "local0",
5538 [LOG_FAC(LOG_LOCAL1)] = "local1",
5539 [LOG_FAC(LOG_LOCAL2)] = "local2",
5540 [LOG_FAC(LOG_LOCAL3)] = "local3",
5541 [LOG_FAC(LOG_LOCAL4)] = "local4",
5542 [LOG_FAC(LOG_LOCAL5)] = "local5",
5543 [LOG_FAC(LOG_LOCAL6)] = "local6",
5544 [LOG_FAC(LOG_LOCAL7)] = "local7"
5547 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5549 static const char *const log_level_table[] = {
5550 [LOG_EMERG] = "emerg",
5551 [LOG_ALERT] = "alert",
5552 [LOG_CRIT] = "crit",
5554 [LOG_WARNING] = "warning",
5555 [LOG_NOTICE] = "notice",
5556 [LOG_INFO] = "info",
5557 [LOG_DEBUG] = "debug"
5560 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5562 static const char* const sched_policy_table[] = {
5563 [SCHED_OTHER] = "other",
5564 [SCHED_BATCH] = "batch",
5565 [SCHED_IDLE] = "idle",
5566 [SCHED_FIFO] = "fifo",
5570 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5572 static const char* const rlimit_table[] = {
5573 [RLIMIT_CPU] = "LimitCPU",
5574 [RLIMIT_FSIZE] = "LimitFSIZE",
5575 [RLIMIT_DATA] = "LimitDATA",
5576 [RLIMIT_STACK] = "LimitSTACK",
5577 [RLIMIT_CORE] = "LimitCORE",
5578 [RLIMIT_RSS] = "LimitRSS",
5579 [RLIMIT_NOFILE] = "LimitNOFILE",
5580 [RLIMIT_AS] = "LimitAS",
5581 [RLIMIT_NPROC] = "LimitNPROC",
5582 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5583 [RLIMIT_LOCKS] = "LimitLOCKS",
5584 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5585 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5586 [RLIMIT_NICE] = "LimitNICE",
5587 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5588 [RLIMIT_RTTIME] = "LimitRTTIME"
5591 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5593 static const char* const ip_tos_table[] = {
5594 [IPTOS_LOWDELAY] = "low-delay",
5595 [IPTOS_THROUGHPUT] = "throughput",
5596 [IPTOS_RELIABILITY] = "reliability",
5597 [IPTOS_LOWCOST] = "low-cost",
5600 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5602 static const char *const __signal_table[] = {
5619 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5630 [SIGVTALRM] = "VTALRM",
5632 [SIGWINCH] = "WINCH",
5638 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5640 const char *signal_to_string(int signo) {
5641 static __thread char buf[12];
5644 name = __signal_to_string(signo);
5648 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5649 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5651 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5656 int signal_from_string(const char *s) {
5661 signo =__signal_from_string(s);
5665 if (startswith(s, "RTMIN+")) {
5669 if (safe_atou(s, &u) >= 0) {
5670 signo = (int) u + offset;
5671 if (signo > 0 && signo < _NSIG)
5677 bool kexec_loaded(void) {
5678 bool loaded = false;
5681 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5689 int strdup_or_null(const char *a, char **b) {
5707 unsigned long cap_last_cap(void) {
5708 static __thread unsigned long saved;
5709 static __thread bool valid = false;
5715 p = (unsigned long) CAP_LAST_CAP;
5717 if (prctl(PR_CAPBSET_READ, p) < 0) {
5719 /* Hmm, look downwards, until we find one that
5721 for (p--; p > 0; p --)
5722 if (prctl(PR_CAPBSET_READ, p) >= 0)
5727 /* Hmm, look upwards, until we find one that doesn't
5730 if (prctl(PR_CAPBSET_READ, p+1) < 0)