X-Git-Url: https://www.chiark.greenend.org.uk/ucgi/~ianmdlvl/git?p=elogind.git;a=blobdiff_plain;f=src%2Fshared%2Futil.c;h=8e1409671f258cc31968eb7ae42a382d9dce5fb6;hp=b48bad4c468a38068df2d504a7133d57e7ca4b8b;hb=86ed7ec58b9b6a0907bbb3b8d07c930e52915de0;hpb=7d5e9c0f60cddf01ec803012cbdc02d2f55b78c1 diff --git a/src/shared/util.c b/src/shared/util.c index b48bad4c4..8e1409671 100644 --- a/src/shared/util.c +++ b/src/shared/util.c @@ -56,6 +56,9 @@ #include #include #include +#include +#include +#include #include "macro.h" #include "util.h" @@ -71,6 +74,13 @@ int saved_argc = 0; char **saved_argv = NULL; +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; long r; @@ -98,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); @@ -181,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; + + if (memcmp(s + sl - pl, postfix, pl) != 0) + return NULL; - return memcmp(s + sl - pl, postfix, pl) == 0; + 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) { @@ -351,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) @@ -371,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) @@ -391,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; @@ -408,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; @@ -506,7 +439,6 @@ int get_parent_of_pid(pid_t pid, pid_t *_ppid) { if (!fgets(line, sizeof(line), f)) { r = feof(f) ? -EIO : -errno; - fclose(f); return r; } @@ -972,13 +904,10 @@ int get_process_comm(pid_t pid, char **name) { } int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) { - char *r, *k; + char *r = NULL, *k; int c; - bool space = false; - size_t left; FILE *f; - assert(max_length > 0); assert(line); if (pid == 0) @@ -994,47 +923,64 @@ int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char * if (!f) return -errno; + if (max_length == 0) { + size_t len = 1; + while ((c = getc(f)) != EOF) { + k = realloc(r, len+1); + if (k == NULL) { + free(r); + fclose(f); + return -ENOMEM; + } + r = k; + r[len-1] = isprint(c) ? c : ' '; + r[len] = 0; + len++; + } + } else { + bool space = false; + size_t left; + r = new(char, max_length); + if (!r) { + fclose(f); + return -ENOMEM; + } - r = new(char, max_length); - if (!r) { - fclose(f); - return -ENOMEM; - } + k = r; + left = max_length; + while ((c = getc(f)) != EOF) { - k = r; - left = max_length; - while ((c = getc(f)) != EOF) { + if (isprint(c)) { + if (space) { + if (left <= 4) + break; + + *(k++) = ' '; + left--; + space = false; + } - if (isprint(c)) { - if (space) { if (left <= 4) break; - *(k++) = ' '; + *(k++) = (char) c; left--; - space = false; - } - - if (left <= 4) - break; + } else + space = true; + } - *(k++) = (char) c; - left--; - } else - space = true; + if (left <= 4) { + size_t n = MIN(left-1, 3U); + memcpy(k, "...", n); + k[n] = 0; + } else + *k = 0; } - if (left <= 4) { - size_t n = MIN(left-1, 3U); - memcpy(k, "...", n); - k[n] = 0; - } else - *k = 0; - fclose(f); /* Kernel threads have no argv[] */ - if (r[0] == 0) { + if (r == NULL || r[0] == 0) { char *t; int h; @@ -1184,8 +1130,11 @@ char *strnappend(const char *s, const char *suffix, size_t b) { assert(suffix); a = strlen(s); + if (b > ((size_t) -1) - a) + return NULL; - if (!(r = new(char, a+b+1))) + r = new(char, a+b+1); + if (!r) return NULL; memcpy(r, s, a); @@ -1683,7 +1632,8 @@ char *xescape(const char *s, const char *bad) { * chars, in \xFF style escaping. May be reversed with * cunescape. */ - if (!(r = new(char, strlen(s)*4+1))) + r = new(char, strlen(s) * 4 + 1); + if (!r) return NULL; for (f = s, t = r; *f; f++) { @@ -1920,136 +1870,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" @@ -2148,28 +1968,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); @@ -2721,134 +2538,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; @@ -3175,6 +2864,9 @@ int get_ctty_devnr(pid_t pid, dev_t *d) { &ttynr) != 1) return -EIO; + if (major(ttynr) == 0 && minor(ttynr) == 0) + return -ENOENT; + *d = (dev_t) ttynr; return 0; } @@ -3193,7 +2885,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; @@ -3214,7 +2907,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; @@ -3337,6 +3031,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; @@ -3350,9 +3050,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; @@ -3385,8 +3083,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; } @@ -3405,8 +3102,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; @@ -3736,41 +3432,26 @@ int fd_columns(int fd) { return ws.ws_col; } -static unsigned columns_cached(bool cached) { - static __thread int parsed_columns = 0, 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 (_likely_(cached_columns > 0)) + return cached_columns; - if (parsed_columns <= 0 || !cached) - parsed_columns = fd_columns(STDOUT_FILENO); + c = 0; + e = getenv("COLUMNS"); + if (e) + safe_atoi(e, &c); - if (parsed_columns <= 0) - parsed_columns = 80; + if (c <= 0) + c = fd_columns(STDOUT_FILENO); - return parsed_columns; -} - -unsigned columns(void) { - return columns_cached(true); -} + if (c <= 0) + c = 80; -unsigned columns_uncached(void) { - return columns_cached(false); + cached_columns = c; + return c; } int fd_lines(int fd) { @@ -3787,23 +3468,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; +} + +/* intended to be used as a SIGWINCH sighandler */ +void columns_lines_cache_reset(int signum) { + cached_columns = 0; + cached_lines = 0; +} - if (parsed_lines <= 0) - parsed_lines = fd_lines(STDOUT_FILENO); +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) { @@ -4053,35 +3751,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; @@ -4788,6 +4457,23 @@ int get_user_creds( return 0; } +char* uid_to_name(uid_t uid) { + struct passwd *p; + char *r; + + if (uid == 0) + return strdup("root"); + + p = getpwuid(uid); + if (p) + return strdup(p->pw_name); + + if (asprintf(&r, "%lu", (unsigned long) uid) < 0) + return NULL; + + return r; +} + int get_group_creds(const char **groupname, gid_t *gid) { struct group *g; gid_t id; @@ -5014,12 +4700,19 @@ char *strjoin(const char *x, ...) { for (;;) { const char *t; + size_t n; t = va_arg(ap, const char *); if (!t) break; - l += strlen(t); + n = strlen(t); + if (n > ((size_t) -1) - l) { + va_end(ap); + return NULL; + } + + l += n; } } else l = 0; @@ -5141,7 +4834,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", @@ -5177,7 +4870,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", @@ -5190,7 +4883,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", @@ -5200,7 +4893,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", @@ -5230,7 +4923,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", @@ -5291,7 +4984,7 @@ int signal_from_string(const char *s) { int offset = 0; unsigned u; - signo =__signal_from_string(s); + signo = __signal_from_string(s); if (signo > 0) return signo; @@ -5619,9 +5312,13 @@ int can_sleep(const char *type) { assert(type); + /* If /sys is read-only we cannot sleep */ + if (access("/sys/power/state", W_OK) < 0) + return false; + r = read_one_line_file("/sys/power/state", &p); if (r < 0) - return r == -ENOENT ? 0 : r; + return false; k = strlen(type); FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) @@ -5631,6 +5328,35 @@ 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); + + /* If /sys is read-only we cannot sleep */ + if (access("/sys/power/state", W_OK) < 0 || + access("/sys/power/disk", W_OK) < 0) + return false; + + r = read_one_line_file("/sys/power/disk", &p); + if (r < 0) + return false; + + 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); @@ -5671,7 +5397,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; } @@ -5683,7 +5409,7 @@ void warn_melody(void) { if (fd < 0) return; - /* Yeah, this is synchronous. Kinda sucks. Bute well... */ + /* Yeah, this is synchronous. Kinda sucks. But well... */ ioctl(fd, KIOCSOUND, (int)(1193180/440)); usleep(125*USEC_PER_MSEC); @@ -5833,3 +5559,315 @@ void closedirp(DIR **d) { void umaskp(mode_t *u) { umask(*u); } + +bool filename_is_safe(const char *p) { + + if (isempty(p)) + return false; + + if (strchr(p, '/')) + return false; + + if (streq(p, ".")) + return false; + + if (streq(p, "..")) + return false; + + if (strlen(p) > FILENAME_MAX) + return false; + + return true; +} + +bool string_is_safe(const char *p) { + const char *t; + + assert(p); + + for (t = p; *t; t++) { + if (*t > 0 && *t < ' ') + return false; + + if (strchr("\\\"\'", *t)) + return false; + } + + return true; +} + +/* 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 = NULL; + 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; +} + +int on_ac_power(void) { + bool found_offline = false, found_online = false; + _cleanup_closedir_ DIR *d = NULL; + + d = opendir("/sys/class/power_supply"); + if (!d) + return -errno; + + for (;;) { + struct dirent *de; + union dirent_storage buf; + _cleanup_free_ char *p = NULL; + _cleanup_close_ int fd = -1, device = -1; + char contents[6]; + ssize_t n; + int k; + + k = readdir_r(d, &buf.de, &de); + if (k != 0) + return -k; + + if (!de) + break; + + if (ignore_file(de->d_name)) + continue; + + device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY); + if (device < 0) { + if (errno == ENOENT || errno == ENOTDIR) + continue; + + return -errno; + } + + fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY); + if (fd < 0) { + if (errno == ENOENT) + continue; + + return -errno; + } + + n = read(fd, contents, sizeof(contents)); + if (n < 0) + return -errno; + + if (n != 6 || memcmp(contents, "Mains\n", 6)) + continue; + + close_nointr_nofail(fd); + fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY); + if (fd < 0) { + if (errno == ENOENT) + continue; + + return -errno; + } + + n = read(fd, contents, sizeof(contents)); + if (n < 0) + return -errno; + + if (n != 2 || contents[1] != '\n') + return -EIO; + + if (contents[0] == '1') { + found_online = true; + break; + } else if (contents[0] == '0') + found_offline = true; + else + return -EIO; + } + + return found_online || !found_offline; +}