chiark / gitweb /
logind: add support for automatic suspend/hibernate/shutdown on idle
[elogind.git] / src / shared / util.c
index 64d6e62a5323b573d87c3f32f2ee76618212be59..d01c2061b423c6b60a4dc422a1d358e46eb5dad5 100644 (file)
@@ -57,6 +57,8 @@
 #include <sys/vfs.h>
 #include <linux/magic.h>
 #include <limits.h>
+#include <langinfo.h>
+#include <locale.h>
 
 #include "macro.h"
 #include "util.h"
 int saved_argc = 0;
 char **saved_argv = NULL;
 
-static int parsed_columns = 0;
+static volatile unsigned cached_columns = 0;
+static volatile unsigned cached_lines = 0;
+
+bool is_efiboot(void) {
+        return access("/sys/firmware/efi", F_OK) >= 0;
+}
 
 size_t page_size(void) {
         static __thread size_t pgsz = 0;
@@ -101,80 +108,7 @@ bool streq_ptr(const char *a, const char *b) {
         return false;
 }
 
-usec_t now(clockid_t clock_id) {
-        struct timespec ts;
-
-        assert_se(clock_gettime(clock_id, &ts) == 0);
-
-        return timespec_load(&ts);
-}
-
-dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
-        assert(ts);
-
-        ts->realtime = now(CLOCK_REALTIME);
-        ts->monotonic = now(CLOCK_MONOTONIC);
-
-        return ts;
-}
-
-dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
-        int64_t delta;
-        assert(ts);
-
-        ts->realtime = u;
-
-        if (u == 0)
-                ts->monotonic = 0;
-        else {
-                delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
-
-                ts->monotonic = now(CLOCK_MONOTONIC);
-
-                if ((int64_t) ts->monotonic > delta)
-                        ts->monotonic -= delta;
-                else
-                        ts->monotonic = 0;
-        }
-
-        return ts;
-}
-
-usec_t timespec_load(const struct timespec *ts) {
-        assert(ts);
-
-        return
-                (usec_t) ts->tv_sec * USEC_PER_SEC +
-                (usec_t) ts->tv_nsec / NSEC_PER_USEC;
-}
-
-struct timespec *timespec_store(struct timespec *ts, usec_t u)  {
-        assert(ts);
-
-        ts->tv_sec = (time_t) (u / USEC_PER_SEC);
-        ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
-
-        return ts;
-}
-
-usec_t timeval_load(const struct timeval *tv) {
-        assert(tv);
-
-        return
-                (usec_t) tv->tv_sec * USEC_PER_SEC +
-                (usec_t) tv->tv_usec;
-}
-
-struct timeval *timeval_store(struct timeval *tv, usec_t u) {
-        assert(tv);
-
-        tv->tv_sec = (time_t) (u / USEC_PER_SEC);
-        tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
-
-        return tv;
-}
-
-bool endswith(const char *s, const char *postfix) {
+char* endswith(const char *s, const char *postfix) {
         size_t sl, pl;
 
         assert(s);
@@ -184,53 +118,49 @@ bool endswith(const char *s, const char *postfix) {
         pl = strlen(postfix);
 
         if (pl == 0)
-                return true;
+                return (char*) s + sl;
 
         if (sl < pl)
-                return false;
+                return NULL;
 
-        return memcmp(s + sl - pl, postfix, pl) == 0;
+        if (memcmp(s + sl - pl, postfix, pl) != 0)
+                return NULL;
+
+        return (char*) s + sl - pl;
 }
 
-bool startswith(const char *s, const char *prefix) {
-        size_t sl, pl;
+char* startswith(const char *s, const char *prefix) {
+        const char *a, *b;
 
         assert(s);
         assert(prefix);
 
-        sl = strlen(s);
-        pl = strlen(prefix);
-
-        if (pl == 0)
-                return true;
-
-        if (sl < pl)
-                return false;
+        a = s, b = prefix;
+        for (;;) {
+                if (*b == 0)
+                        return (char*) a;
+                if (*a != *b)
+                        return NULL;
 
-        return memcmp(s, prefix, pl) == 0;
+                a++, b++;
+        }
 }
 
-bool startswith_no_case(const char *s, const char *prefix) {
-        size_t sl, pl;
-        unsigned i;
+char* startswith_no_case(const char *s, const char *prefix) {
+        const char *a, *b;
 
         assert(s);
         assert(prefix);
 
-        sl = strlen(s);
-        pl = strlen(prefix);
-
-        if (pl == 0)
-                return true;
-
-        if (sl < pl)
-                return false;
-
-        for(i = 0; i < pl; ++i)
-                if (tolower(s[i]) != tolower(prefix[i]))
-                        return false;
+        a = s, b = prefix;
+        for (;;) {
+                if (*b == 0)
+                        return (char*) a;
+                if (tolower(*a) != tolower(*b))
+                        return NULL;
 
-        return true;
+                a++, b++;
+        }
 }
 
 bool first_word(const char *s, const char *word) {
@@ -354,7 +284,7 @@ int safe_atou(const char *s, unsigned *ret_u) {
         errno = 0;
         l = strtoul(s, &x, 0);
 
-        if (!x || *x || errno)
+        if (!x || x == s || *x || errno)
                 return errno ? -errno : -EINVAL;
 
         if ((unsigned long) (unsigned) l != l)
@@ -374,7 +304,7 @@ int safe_atoi(const char *s, int *ret_i) {
         errno = 0;
         l = strtol(s, &x, 0);
 
-        if (!x || *x || errno)
+        if (!x || x == s || *x || errno)
                 return errno ? -errno : -EINVAL;
 
         if ((long) (int) l != l)
@@ -394,7 +324,7 @@ int safe_atollu(const char *s, long long unsigned *ret_llu) {
         errno = 0;
         l = strtoull(s, &x, 0);
 
-        if (!x || *x || errno)
+        if (!x || x == s || *x || errno)
                 return errno ? -errno : -EINVAL;
 
         *ret_llu = l;
@@ -411,7 +341,7 @@ int safe_atolli(const char *s, long long int *ret_lli) {
         errno = 0;
         l = strtoll(s, &x, 0);
 
-        if (!x || *x || errno)
+        if (!x || x == s || *x || errno)
                 return errno ? -errno : -EINVAL;
 
         *ret_lli = l;
@@ -1927,136 +1857,6 @@ bool chars_intersect(const char *a, const char *b) {
         return false;
 }
 
-char *format_timestamp(char *buf, size_t l, usec_t t) {
-        struct tm tm;
-        time_t sec;
-
-        assert(buf);
-        assert(l > 0);
-
-        if (t <= 0)
-                return NULL;
-
-        sec = (time_t) (t / USEC_PER_SEC);
-
-        if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
-                return NULL;
-
-        return buf;
-}
-
-char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
-        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)
-                snprintf(buf, l, "%llu years and %llu months ago",
-                         (unsigned long long) (d / USEC_PER_YEAR),
-                         (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
-        else if (d >= USEC_PER_MONTH)
-                snprintf(buf, l, "%llu months and %llu days ago",
-                         (unsigned long long) (d / USEC_PER_MONTH),
-                         (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
-        else if (d >= USEC_PER_WEEK)
-                snprintf(buf, l, "%llu weeks and %llu days ago",
-                         (unsigned long long) (d / USEC_PER_WEEK),
-                         (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
-        else if (d >= 2*USEC_PER_DAY)
-                snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
-        else if (d >= 25*USEC_PER_HOUR)
-                snprintf(buf, l, "1 day and %lluh ago",
-                         (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
-        else if (d >= 6*USEC_PER_HOUR)
-                snprintf(buf, l, "%lluh ago",
-                         (unsigned long long) (d / USEC_PER_HOUR));
-        else if (d >= USEC_PER_HOUR)
-                snprintf(buf, l, "%lluh %llumin ago",
-                         (unsigned long long) (d / USEC_PER_HOUR),
-                         (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
-        else if (d >= 5*USEC_PER_MINUTE)
-                snprintf(buf, l, "%llumin ago",
-                         (unsigned long long) (d / USEC_PER_MINUTE));
-        else if (d >= USEC_PER_MINUTE)
-                snprintf(buf, l, "%llumin %llus ago",
-                         (unsigned long long) (d / USEC_PER_MINUTE),
-                         (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
-        else if (d >= USEC_PER_SEC)
-                snprintf(buf, l, "%llus ago",
-                         (unsigned long long) (d / USEC_PER_SEC));
-        else if (d >= USEC_PER_MSEC)
-                snprintf(buf, l, "%llums ago",
-                         (unsigned long long) (d / USEC_PER_MSEC));
-        else if (d > 0)
-                snprintf(buf, l, "%lluus ago",
-                         (unsigned long long) d);
-        else
-                snprintf(buf, l, "now");
-
-        buf[l-1] = 0;
-        return buf;
-}
-
-char *format_timespan(char *buf, size_t l, usec_t t) {
-        static const struct {
-                const char *suffix;
-                usec_t usec;
-        } 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(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;
-
-                if (t < table[i].usec)
-                        continue;
-
-                if (l <= 1)
-                        break;
-
-                k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
-                n = MIN((size_t) k, l);
-
-                l -= n;
-                p += n;
-
-                t %= table[i].usec;
-        }
-
-        *p = 0;
-
-        return buf;
-}
-
 bool fstype_is_network(const char *fstype) {
         static const char table[] =
                 "cifs\0"
@@ -2155,28 +1955,25 @@ int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
 }
 
 int ask(char *ret, const char *replies, const char *text, ...) {
-        bool on_tty;
 
         assert(ret);
         assert(replies);
         assert(text);
 
-        on_tty = isatty(STDOUT_FILENO);
-
         for (;;) {
                 va_list ap;
                 char c;
                 int r;
                 bool need_nl = true;
 
-                if (on_tty)
+                if (on_tty())
                         fputs(ANSI_HIGHLIGHT_ON, stdout);
 
                 va_start(ap, text);
                 vprintf(text, ap);
                 va_end(ap);
 
-                if (on_tty)
+                if (on_tty())
                         fputs(ANSI_HIGHLIGHT_OFF, stdout);
 
                 fflush(stdout);
@@ -2728,134 +2525,6 @@ ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
         return n;
 }
 
-int parse_usec(const char *t, usec_t *usec) {
-        static const struct {
-                const char *suffix;
-                usec_t usec;
-        } 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 },
-                { "", USEC_PER_SEC }, /* default is sec */
-        };
-
-        const char *p;
-        usec_t r = 0;
-
-        assert(t);
-        assert(usec);
-
-        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++)
-                        if (startswith(e, table[i].suffix)) {
-                                r += (usec_t) l * table[i].usec;
-                                p = e + strlen(table[i].suffix);
-                                break;
-                        }
-
-                if (i >= ELEMENTSOF(table))
-                        return -EINVAL;
-
-        } while (*p != 0);
-
-        *usec = r;
-
-        return 0;
-}
-
-int parse_nsec(const char *t, nsec_t *nsec) {
-        static const struct {
-                const char *suffix;
-                nsec_t nsec;
-        } 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);
-        assert(nsec);
-
-        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++)
-                        if (startswith(e, table[i].suffix)) {
-                                r += (nsec_t) l * table[i].nsec;
-                                p = e + strlen(table[i].suffix);
-                                break;
-                        }
-
-                if (i >= ELEMENTSOF(table))
-                        return -EINVAL;
-
-        } while (*p != 0);
-
-        *nsec = r;
-
-        return 0;
-}
-
 int parse_bytes(const char *t, off_t *bytes) {
         static const struct {
                 const char *suffix;
@@ -3200,7 +2869,8 @@ int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
         snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
         char_array_0(fn);
 
-        if ((k = readlink_malloc(fn, &s)) < 0) {
+        k = readlink_malloc(fn, &s);
+        if (k < 0) {
 
                 if (k != -ENOENT)
                         return k;
@@ -3221,7 +2891,8 @@ int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
                  * symlink in /dev/char. Let's return something
                  * vaguely useful. */
 
-                if (!(b = strdup(fn + 5)))
+                b = strdup(fn + 5);
+                if (!b)
                         return -ENOMEM;
 
                 *r = b;
@@ -3344,6 +3015,12 @@ int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct
         return ret;
 }
 
+static int is_temporary_fs(struct statfs *s) {
+        assert(s);
+        return s->f_type == TMPFS_MAGIC ||
+                (long)s->f_type == (long)RAMFS_MAGIC;
+}
+
 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
         struct statfs s;
 
@@ -3357,9 +3034,7 @@ int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root
         /* 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) {
+        if (!is_temporary_fs(&s)) {
                 log_error("Attempted to remove disk file system, and we can't allow that.");
                 close_nointr_nofail(fd);
                 return -EPERM;
@@ -3392,8 +3067,7 @@ static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bo
                         if (statfs(path, &s) < 0)
                                 return -errno;
 
-                        if (s.f_type != TMPFS_MAGIC &&
-                            s.f_type != RAMFS_MAGIC) {
+                        if (!is_temporary_fs(&s)) {
                                 log_error("Attempted to remove disk file system, and we can't allow that.");
                                 return -EPERM;
                         }
@@ -3412,8 +3086,7 @@ static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bo
                         return -errno;
                 }
 
-                if (s.f_type != TMPFS_MAGIC &&
-                    s.f_type != RAMFS_MAGIC) {
+                if (!is_temporary_fs(&s)) {
                         log_error("Attempted to remove disk file system, and we can't allow that.");
                         close_nointr_nofail(fd);
                         return -EPERM;
@@ -3743,46 +3416,26 @@ int fd_columns(int fd) {
         return ws.ws_col;
 }
 
-static unsigned columns_cached(bool cached) {
-        static __thread int env_columns = -1;
+unsigned columns(void) {
         const char *e;
+        int c;
 
-        if (_likely_(parsed_columns > 0 && cached))
-                return parsed_columns;
-
-        if (_unlikely_(env_columns == -1)) {
-                e = getenv("COLUMNS");
-                if (e)
-                        env_columns = atoi(e);
-                else
-                        env_columns = 0;
-        }
-
-        if (env_columns > 0) {
-                parsed_columns = env_columns;
-                return parsed_columns;
-        }
-
-        if (parsed_columns <= 0 || !cached)
-                parsed_columns = fd_columns(STDOUT_FILENO);
-
-        if (parsed_columns <= 0)
-                parsed_columns = 80;
+        if (_likely_(cached_columns > 0))
+                return cached_columns;
 
-        return parsed_columns;
-}
+        c = 0;
+        e = getenv("COLUMNS");
+        if (e)
+                safe_atoi(e, &c);
 
-unsigned columns(void) {
-        return columns_cached(true);
-}
+        if (c <= 0)
+                c = fd_columns(STDOUT_FILENO);
 
-unsigned columns_uncached(void) {
-        return columns_cached(false);
-}
+        if (c <= 0)
+                c = 80;
 
-/* intended to be used as a SIGWINCH sighandler */
-void columns_cache_reset(int signum) {
-        parsed_columns = 0;
+        cached_columns = c;
+        return c;
 }
 
 int fd_lines(int fd) {
@@ -3799,23 +3452,40 @@ int fd_lines(int fd) {
 }
 
 unsigned lines(void) {
-        static __thread int parsed_lines = 0;
         const char *e;
+        unsigned l;
 
-        if (_likely_(parsed_lines > 0))
-                return parsed_lines;
+        if (_likely_(cached_lines > 0))
+                return cached_lines;
 
+        l = 0;
         e = getenv("LINES");
         if (e)
-                parsed_lines = atoi(e);
+                safe_atou(e, &l);
+
+        if (l <= 0)
+                l = fd_lines(STDOUT_FILENO);
+
+        if (l <= 0)
+                l = 24;
+
+        cached_lines = l;
+        return cached_lines;
+}
 
-        if (parsed_lines <= 0)
-                parsed_lines = fd_lines(STDOUT_FILENO);
+/* intended to be used as a SIGWINCH sighandler */
+void columns_lines_cache_reset(int signum) {
+        cached_columns = 0;
+        cached_lines = 0;
+}
+
+bool on_tty(void) {
+        static int cached_on_tty = -1;
 
-        if (parsed_lines <= 0)
-                parsed_lines = 25;
+        if (_unlikely_(cached_on_tty < 0))
+                cached_on_tty = isatty(STDOUT_FILENO) > 0;
 
-        return parsed_lines;
+        return cached_on_tty;
 }
 
 int running_in_chroot(void) {
@@ -4065,35 +3735,6 @@ int signal_from_string_try_harder(const char *s) {
         return signo;
 }
 
-void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
-
-        assert(f);
-        assert(name);
-        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);
-}
-
-void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
-        unsigned long long a, b;
-
-        assert(value);
-        assert(t);
-
-        if (sscanf(value, "%lli %llu", &a, &b) != 2)
-                log_debug("Failed to parse finish timestamp value %s", value);
-        else {
-                t->realtime = a;
-                t->monotonic = b;
-        }
-}
-
 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
         char *dn, *t, *u;
         int r;
@@ -5160,7 +4801,7 @@ static const char *const ioprio_class_table[] = {
         [IOPRIO_CLASS_IDLE] = "idle"
 };
 
-DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
+DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
 
 static const char *const sigchld_code_table[] = {
         [CLD_EXITED] = "exited",
@@ -5196,7 +4837,7 @@ static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
         [LOG_FAC(LOG_LOCAL7)] = "local7"
 };
 
-DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
+DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
 
 static const char *const log_level_table[] = {
         [LOG_EMERG] = "emerg",
@@ -5209,7 +4850,7 @@ static const char *const log_level_table[] = {
         [LOG_DEBUG] = "debug"
 };
 
-DEFINE_STRING_TABLE_LOOKUP(log_level, int);
+DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
 
 static const char* const sched_policy_table[] = {
         [SCHED_OTHER] = "other",
@@ -5219,7 +4860,7 @@ static const char* const sched_policy_table[] = {
         [SCHED_RR] = "rr"
 };
 
-DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
+DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
 
 static const char* const rlimit_table[] = {
         [RLIMIT_CPU] = "LimitCPU",
@@ -5249,7 +4890,7 @@ static const char* const ip_tos_table[] = {
         [IPTOS_LOWCOST] = "low-cost",
 };
 
-DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
+DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
 
 static const char *const __signal_table[] = {
         [SIGHUP] = "HUP",
@@ -5650,6 +5291,30 @@ int can_sleep(const char *type) {
         return false;
 }
 
+int can_sleep_disk(const char *type) {
+        char *w, *state;
+        size_t l, k;
+        int r;
+        _cleanup_free_ char *p = NULL;
+
+        assert(type);
+
+        r = read_one_line_file("/sys/power/disk", &p);
+        if (r < 0)
+                return r == -ENOENT ? 0 : r;
+
+        k = strlen(type);
+        FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
+                if (l == k && memcmp(w, type, l) == 0)
+                        return true;
+
+                if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
+                        return true;
+        }
+
+        return false;
+}
+
 bool is_valid_documentation_url(const char *url) {
         assert(url);
 
@@ -5690,7 +5355,7 @@ bool in_initrd(void) {
 
         saved = access("/etc/initrd-release", F_OK) >= 0 &&
                 statfs("/", &s) >= 0 &&
-                (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
+                is_temporary_fs(&s);
 
         return saved;
 }
@@ -5879,12 +5544,210 @@ bool string_is_safe(const char *p) {
         assert(p);
 
         for (t = p; *t; t++) {
-                if (*p < ' ')
+                if (*t > 0 && *t < ' ')
                         return false;
 
-                if (strchr("\\\"\'", *p))
+                if (strchr("\\\"\'", *t))
                         return false;
         }
 
         return true;
 }
+
+/* hey glibc, APIs with callbacks without a user pointer are so useless */
+void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
+                 int (*compar) (const void *, const void *, void *), void *arg) {
+        size_t l, u, idx;
+        const void *p;
+        int comparison;
+
+        l = 0;
+        u = nmemb;
+        while (l < u) {
+                idx = (l + u) / 2;
+                p = (void *)(((const char *) base) + (idx * size));
+                comparison = compar(key, p, arg);
+                if (comparison < 0)
+                        u = idx;
+                else if (comparison > 0)
+                        l = idx + 1;
+                else
+                        return (void *)p;
+        }
+        return NULL;
+}
+
+bool is_locale_utf8(void) {
+        const char *set;
+        static int cached_answer = -1;
+
+        if (cached_answer >= 0)
+                goto out;
+
+        if (!setlocale(LC_ALL, "")) {
+                cached_answer = true;
+                goto out;
+        }
+
+        set = nl_langinfo(CODESET);
+        if (!set) {
+                cached_answer = true;
+                goto out;
+        }
+
+        cached_answer = streq(set, "UTF-8");
+out:
+        return (bool)cached_answer;
+}
+
+const char *draw_special_char(DrawSpecialChar ch) {
+        static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
+                /* UTF-8 */ {
+                        [DRAW_TREE_VERT]          = "\342\224\202 ",            /* │  */
+                        [DRAW_TREE_BRANCH]        = "\342\224\234\342\224\200", /* ├─ */
+                        [DRAW_TREE_RIGHT]         = "\342\224\224\342\224\200", /* └─ */
+                        [DRAW_TRIANGULAR_BULLET]  = "\342\200\243 ",            /* ‣  */
+                },
+                /* ASCII fallback */ {
+                        [DRAW_TREE_VERT]          = "| ",
+                        [DRAW_TREE_BRANCH]        = "|-",
+                        [DRAW_TREE_RIGHT]         = "`-",
+                        [DRAW_TRIANGULAR_BULLET]  = "> ",
+                }
+        };
+
+        return draw_table[!is_locale_utf8()][ch];
+}
+
+char *strreplace(const char *text, const char *old_string, const char *new_string) {
+        const char *f;
+        char *t, *r;
+        size_t l, old_len, new_len;
+
+        assert(text);
+        assert(old_string);
+        assert(new_string);
+
+        old_len = strlen(old_string);
+        new_len = strlen(new_string);
+
+        l = strlen(text);
+        r = new(char, l+1);
+        if (!r)
+                return NULL;
+
+        f = text;
+        t = r;
+        while (*f) {
+                char *a;
+                size_t d, nl;
+
+                if (!startswith(f, old_string)) {
+                        *(t++) = *(f++);
+                        continue;
+                }
+
+                d = t - r;
+                nl = l - old_len + new_len;
+                a = realloc(r, nl + 1);
+                if (!a)
+                        goto oom;
+
+                l = nl;
+                r = a;
+                t = r + d;
+
+                t = stpcpy(t, new_string);
+                f += old_len;
+        }
+
+        *t = 0;
+        return r;
+
+oom:
+        free(r);
+        return NULL;
+}
+
+char *strip_tab_ansi(char **ibuf, size_t *_isz) {
+        const char *i, *begin;
+        enum {
+                STATE_OTHER,
+                STATE_ESCAPE,
+                STATE_BRACKET
+        } state = STATE_OTHER;
+        char *obuf = NULL;
+        size_t osz = 0, isz;
+        FILE *f;
+
+        assert(ibuf);
+        assert(*ibuf);
+
+        /* Strips ANSI color and replaces TABs by 8 spaces */
+
+        isz = _isz ? *_isz : strlen(*ibuf);
+
+        f = open_memstream(&obuf, &osz);
+        if (!f)
+                return NULL;
+
+        for (i = *ibuf; i < *ibuf + isz + 1; i++) {
+
+                switch (state) {
+
+                case STATE_OTHER:
+                        if (i >= *ibuf + isz) /* EOT */
+                                break;
+                        else if (*i == '\x1B')
+                                state = STATE_ESCAPE;
+                        else if (*i == '\t')
+                                fputs("        ", f);
+                        else
+                                fputc(*i, f);
+                        break;
+
+                case STATE_ESCAPE:
+                        if (i >= *ibuf + isz) { /* EOT */
+                                fputc('\x1B', f);
+                                break;
+                        } else if (*i == '[') {
+                                state = STATE_BRACKET;
+                                begin = i + 1;
+                        } else {
+                                fputc('\x1B', f);
+                                fputc(*i, f);
+                                state = STATE_OTHER;
+                        }
+
+                        break;
+
+                case STATE_BRACKET:
+
+                        if (i >= *ibuf + isz || /* EOT */
+                            (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
+                                fputc('\x1B', f);
+                                fputc('[', f);
+                                state = STATE_OTHER;
+                                i = begin-1;
+                        } else if (*i == 'm')
+                                state = STATE_OTHER;
+                        break;
+                }
+        }
+
+        if (ferror(f)) {
+                fclose(f);
+                free(obuf);
+                return NULL;
+        }
+
+        fclose(f);
+
+        free(*ibuf);
+        *ibuf = obuf;
+
+        if (_isz)
+                *_isz = osz;
+
+        return obuf;
+}