X-Git-Url: https://www.chiark.greenend.org.uk/ucgi/~ianmdlvl/git?a=blobdiff_plain;f=src%2Fshared%2Futil.c;h=fd2c5b075f77649f943ccf4cb59d02a3fc673e9d;hb=55c0b89c575fcb2c075286d444ed4fb1cf8c8563;hp=43948ccbd8970c5076d2f00659d26f2d449fa4ce;hpb=3d9a412243035beeaaf3465a62065444a5adf21c;p=elogind.git diff --git a/src/shared/util.c b/src/shared/util.c index 43948ccbd..d5de59fce 100644 --- a/src/shared/util.c +++ b/src/shared/util.c @@ -50,13 +50,15 @@ #include #include #include -#include #include -#include #include #include #include -#include +#include +#include +#include +#include +#include #include "macro.h" #include "util.h" @@ -65,12 +67,20 @@ #include "log.h" #include "strv.h" #include "label.h" +#include "path-util.h" #include "exit-status.h" #include "hashmap.h" int saved_argc = 0; char **saved_argv = NULL; +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; @@ -78,10 +88,10 @@ size_t page_size(void) { if (_likely_(pgsz > 0)) return pgsz; - assert_se((r = sysconf(_SC_PAGESIZE)) > 0); + r = sysconf(_SC_PAGESIZE); + assert(r > 0); pgsz = (size_t) r; - return pgsz; } @@ -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,54 +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; + a = s, b = prefix; + for (;;) { + if (*b == 0) + return (char*) a; + if (tolower(*a) != tolower(*b)) + return NULL; - for(i = 0; i < pl; ++i) { - if (tolower(s[i]) != tolower(prefix[i])) - return false; + a++, b++; } - - return true; } bool first_word(const char *s, const char *word) { @@ -305,7 +237,8 @@ int parse_pid(const char *s, pid_t* ret_pid) { assert(s); assert(ret_pid); - if ((r = safe_atolu(s, &ul)) < 0) + r = safe_atolu(s, &ul); + if (r < 0) return r; pid = (pid_t) ul; @@ -328,7 +261,8 @@ int parse_uid(const char *s, uid_t* ret_uid) { assert(s); assert(ret_uid); - if ((r = safe_atolu(s, &ul)) < 0) + r = safe_atolu(s, &ul); + if (r < 0) return r; uid = (uid_t) ul; @@ -350,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) @@ -370,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) @@ -390,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; @@ -407,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; @@ -487,24 +421,9 @@ char *split_quoted(const char *c, size_t *l, char **state) { return (char*) current; } -char **split_path_and_make_absolute(const char *p) { - char **l; - assert(p); - - if (!(l = strv_split(p, ":"))) - return NULL; - - if (!strv_path_make_absolute_cwd(l)) { - strv_free(l); - return NULL; - } - - return l; -} - int get_parent_of_pid(pid_t pid, pid_t *_ppid) { int r; - FILE *f; + _cleanup_fclose_ FILE *f = NULL; char fn[PATH_MAX], line[LINE_MAX], *p; long unsigned ppid; @@ -514,22 +433,21 @@ int get_parent_of_pid(pid_t pid, pid_t *_ppid) { assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1)); char_array_0(fn); - if (!(f = fopen(fn, "re"))) + f = fopen(fn, "re"); + if (!f) return -errno; - if (!(fgets(line, sizeof(line), f))) { + if (!fgets(line, sizeof(line), f)) { r = feof(f) ? -EIO : -errno; - fclose(f); return r; } - fclose(f); - /* Let's skip the pid and comm fields. The latter is enclosed * in () but does not escape any () in its value, so let's * skip over it manually */ - if (!(p = strrchr(line, ')'))) + p = strrchr(line, ')'); + if (!p) return -EIO; p++; @@ -549,8 +467,7 @@ int get_parent_of_pid(pid_t pid, pid_t *_ppid) { } int get_starttime_of_pid(pid_t pid, unsigned long long *st) { - int r; - FILE *f; + _cleanup_fclose_ FILE *f = NULL; char fn[PATH_MAX], line[LINE_MAX], *p; assert(pid > 0); @@ -559,22 +476,23 @@ int get_starttime_of_pid(pid_t pid, unsigned long long *st) { assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1)); char_array_0(fn); - if (!(f = fopen(fn, "re"))) + f = fopen(fn, "re"); + if (!f) return -errno; - if (!(fgets(line, sizeof(line), f))) { - r = feof(f) ? -EIO : -errno; - fclose(f); - return r; - } + if (!fgets(line, sizeof(line), f)) { + if (ferror(f)) + return -errno; - fclose(f); + return -EIO; + } /* Let's skip the pid and comm fields. The latter is enclosed * in () but does not escape any () in its value, so let's * skip over it manually */ - if (!(p = strrchr(line, ')'))) + p = strrchr(line, ')'); + if (!p) return -EIO; p++; @@ -607,37 +525,28 @@ int get_starttime_of_pid(pid_t pid, unsigned long long *st) { } int write_one_line_file(const char *fn, const char *line) { - FILE *f; - int r; + _cleanup_fclose_ FILE *f = NULL; assert(fn); assert(line); - if (!(f = fopen(fn, "we"))) + f = fopen(fn, "we"); + if (!f) return -errno; errno = 0; - if (fputs(line, f) < 0) { - r = -errno; - goto finish; - } + if (fputs(line, f) < 0) + return errno ? -errno : -EIO; if (!endswith(line, "\n")) fputc('\n', f); fflush(f); - if (ferror(f)) { - if (errno != 0) - r = -errno; - else - r = -EIO; - } else - r = 0; + if (ferror(f)) + return errno ? -errno : -EIO; -finish: - fclose(f); - return r; + return 0; } int fchmod_umask(int fd, mode_t m) { @@ -699,8 +608,7 @@ finish: } int read_one_line_file(const char *fn, char **line) { - FILE *f; - int r; + _cleanup_fclose_ FILE *f = NULL; char t[LINE_MAX], *c; assert(fn); @@ -712,50 +620,37 @@ int read_one_line_file(const char *fn, char **line) { if (!fgets(t, sizeof(t), f)) { - if (ferror(f)) { - r = -errno; - goto finish; - } + if (ferror(f)) + return errno ? -errno : -EIO; t[0] = 0; } c = strdup(t); - if (!c) { - r = -ENOMEM; - goto finish; - } - + if (!c) + return -ENOMEM; truncate_nl(c); *line = c; - r = 0; - -finish: - fclose(f); - return r; + return 0; } int read_full_file(const char *fn, char **contents, size_t *size) { - FILE *f; - int r; + _cleanup_fclose_ FILE *f = NULL; size_t n, l; - char *buf = NULL; + _cleanup_free_ char *buf = NULL; struct stat st; - if (!(f = fopen(fn, "re"))) + f = fopen(fn, "re"); + if (!f) return -errno; - if (fstat(fileno(f), &st) < 0) { - r = -errno; - goto finish; - } + if (fstat(fileno(f), &st) < 0) + return -errno; /* Safety check */ - if (st.st_size > 4*1024*1024) { - r = -E2BIG; - goto finish; - } + if (st.st_size > 4*1024*1024) + return -E2BIG; n = st.st_size > 0 ? st.st_size : LINE_MAX; l = 0; @@ -764,19 +659,16 @@ int read_full_file(const char *fn, char **contents, size_t *size) { char *t; size_t k; - if (!(t = realloc(buf, n+1))) { - r = -ENOMEM; - goto finish; - } + t = realloc(buf, n+1); + if (!t) + return -ENOMEM; buf = t; k = fread(buf + l, 1, n - l, f); if (k <= 0) { - if (ferror(f)) { - r = -errno; - goto finish; - } + if (ferror(f)) + return -errno; break; } @@ -785,10 +677,8 @@ int read_full_file(const char *fn, char **contents, size_t *size) { n *= 2; /* Safety check */ - if (n > 4*1024*1024) { - r = -E2BIG; - goto finish; - } + if (n > 4*1024*1024) + return -E2BIG; } buf[l] = 0; @@ -798,13 +688,7 @@ int read_full_file(const char *fn, char **contents, size_t *size) { if (size) *size = l; - r = 0; - -finish: - fclose(f); - free(buf); - - return r; + return 0; } int parse_env_file( @@ -923,8 +807,7 @@ int load_env_file( continue; if (!(u = normalize_env_assignment(p))) { - log_error("Out of memory"); - r = -ENOMEM; + r = log_oom(); goto finish; } @@ -932,8 +815,7 @@ int load_env_file( free(u); if (!t) { - log_error("Out of memory"); - r = -ENOMEM; + r = log_oom(); goto finish; } @@ -1022,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) @@ -1044,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) { + + if (isprint(c)) { + if (space) { + if (left <= 4) + break; - k = r; - left = max_length; - while ((c = getc(f)) != EOF) { + *(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; @@ -1097,7 +993,7 @@ int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char * if (h < 0) return h; - r = join("[", t, "]", NULL); + r = strjoin("[", t, "]", NULL); free(t); if (!r) @@ -1158,7 +1054,7 @@ int get_process_exe(pid_t pid, char **name) { return r; } -int get_process_uid(pid_t pid, uid_t *uid) { +static int get_process_id(pid_t pid, const char *field, uid_t *uid) { char *p; FILE *f; int r; @@ -1190,8 +1086,8 @@ int get_process_uid(pid_t pid, uid_t *uid) { l = strstrip(line); - if (startswith(l, "Uid:")) { - l += 4; + if (startswith(l, field)) { + l += strlen(field); l += strspn(l, WHITESPACE); l[strcspn(l, WHITESPACE)] = 0; @@ -1209,6 +1105,14 @@ finish: return r; } +int get_process_uid(pid_t pid, uid_t *uid) { + return get_process_id(pid, "Uid:", uid); +} + +int get_process_gid(pid_t pid, gid_t *gid) { + return get_process_id(pid, "Gid:", gid); +} + char *strnappend(const char *s, const char *suffix, size_t b) { size_t a; char *r; @@ -1226,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); @@ -1314,249 +1221,68 @@ int readlink_and_canonicalize(const char *p, char **r) { return 0; } -int parent_of_path(const char *path, char **_r) { - const char *e, *a = NULL, *b = NULL, *p; - char *r; - bool slash = false; +int reset_all_signal_handlers(void) { + int sig; - assert(path); - assert(_r); + for (sig = 1; sig < _NSIG; sig++) { + struct sigaction sa; - if (!*path) - return -EINVAL; + if (sig == SIGKILL || sig == SIGSTOP) + continue; - for (e = path; *e; e++) { + zero(sa); + sa.sa_handler = SIG_DFL; + sa.sa_flags = SA_RESTART; - if (!slash && *e == '/') { - a = b; - b = e; - slash = true; - } else if (slash && *e != '/') - slash = false; + /* On Linux the first two RT signals are reserved by + * glibc, and sigaction() will return EINVAL for them. */ + if ((sigaction(sig, &sa, NULL) < 0)) + if (errno != EINVAL) + return -errno; } - if (*(e-1) == '/') - p = a; - else - p = b; - - if (!p) - return -EINVAL; - - if (p == path) - r = strdup("/"); - else - r = strndup(path, p-path); - - if (!r) - return -ENOMEM; - - *_r = r; return 0; } +char *strstrip(char *s) { + char *e; -char *file_name_from_path(const char *p) { - char *r; - - assert(p); + /* Drops trailing whitespace. Modifies the string in + * place. Returns pointer to first non-space character */ - if ((r = strrchr(p, '/'))) - return r + 1; + s += strspn(s, WHITESPACE); - return (char*) p; -} + for (e = strchr(s, 0); e > s; e --) + if (!strchr(WHITESPACE, e[-1])) + break; -bool path_is_absolute(const char *p) { - assert(p); + *e = 0; - return p[0] == '/'; + return s; } -bool is_path(const char *p) { +char *delete_chars(char *s, const char *bad) { + char *f, *t; - return !!strchr(p, '/'); -} + /* Drops all whitespace, regardless where in the string */ -char *path_make_absolute(const char *p, const char *prefix) { - assert(p); + for (f = s, t = s; *f; f++) { + if (strchr(bad, *f)) + continue; - /* Makes every item in the list an absolute path by prepending - * the prefix, if specified and necessary */ + *(t++) = *f; + } - if (path_is_absolute(p) || !prefix) - return strdup(p); + *t = 0; - return join(prefix, "/", p, NULL); + return s; } -char *path_make_absolute_cwd(const char *p) { - char *cwd, *r; - - assert(p); +bool in_charset(const char *s, const char* charset) { + const char *i; - /* Similar to path_make_absolute(), but prefixes with the - * current working directory. */ - - if (path_is_absolute(p)) - return strdup(p); - - if (!(cwd = get_current_dir_name())) - return NULL; - - r = path_make_absolute(p, cwd); - free(cwd); - - return r; -} - -char **strv_path_make_absolute_cwd(char **l) { - char **s; - - /* Goes through every item in the string list and makes it - * absolute. This works in place and won't rollback any - * changes on failure. */ - - STRV_FOREACH(s, l) { - char *t; - - if (!(t = path_make_absolute_cwd(*s))) - return NULL; - - free(*s); - *s = t; - } - - return l; -} - -char **strv_path_canonicalize(char **l) { - char **s; - unsigned k = 0; - bool enomem = false; - - if (strv_isempty(l)) - return l; - - /* Goes through every item in the string list and canonicalize - * the path. This works in place and won't rollback any - * changes on failure. */ - - STRV_FOREACH(s, l) { - char *t, *u; - - t = path_make_absolute_cwd(*s); - free(*s); - - if (!t) { - enomem = true; - continue; - } - - errno = 0; - u = canonicalize_file_name(t); - free(t); - - if (!u) { - if (errno == ENOMEM || !errno) - enomem = true; - - continue; - } - - l[k++] = u; - } - - l[k] = NULL; - - if (enomem) - return NULL; - - return l; -} - -char **strv_path_remove_empty(char **l) { - char **f, **t; - - if (!l) - return NULL; - - for (f = t = l; *f; f++) { - - if (dir_is_empty(*f) > 0) { - free(*f); - continue; - } - - *(t++) = *f; - } - - *t = NULL; - return l; -} - -int reset_all_signal_handlers(void) { - int sig; - - for (sig = 1; sig < _NSIG; sig++) { - struct sigaction sa; - - if (sig == SIGKILL || sig == SIGSTOP) - continue; - - zero(sa); - sa.sa_handler = SIG_DFL; - sa.sa_flags = SA_RESTART; - - /* On Linux the first two RT signals are reserved by - * glibc, and sigaction() will return EINVAL for them. */ - if ((sigaction(sig, &sa, NULL) < 0)) - if (errno != EINVAL) - return -errno; - } - - return 0; -} - -char *strstrip(char *s) { - char *e; - - /* Drops trailing whitespace. Modifies the string in - * place. Returns pointer to first non-space character */ - - s += strspn(s, WHITESPACE); - - for (e = strchr(s, 0); e > s; e --) - if (!strchr(WHITESPACE, e[-1])) - break; - - *e = 0; - - return s; -} - -char *delete_chars(char *s, const char *bad) { - char *f, *t; - - /* Drops all whitespace, regardless where in the string */ - - for (f = s, t = s; *f; f++) { - if (strchr(bad, *f)) - continue; - - *(t++) = *f; - } - - *t = 0; - - return s; -} - -bool in_charset(const char *s, const char* charset) { - const char *i; - - assert(s); - assert(charset); + assert(s); + assert(charset); for (i = s; *i; i++) if (!strchr(charset, *i)) @@ -1759,19 +1485,25 @@ char *cescape(const char *s) { return r; } -char *cunescape_length(const char *s, size_t length) { +char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) { char *r, *t; const char *f; + size_t pl; assert(s); - /* Undoes C style string escaping */ + /* Undoes C style string escaping, and optionally prefixes it. */ - r = new(char, length+1); + pl = prefix ? strlen(prefix) : 0; + + r = new(char, pl+length+1); if (!r) return r; - for (f = s, t = r; f < s + length; f++) { + if (prefix) + memcpy(r, prefix, pl); + + for (f = s, t = r + pl; f < s + length; f++) { if (*f != '\\') { *(t++) = *f; @@ -1882,7 +1614,13 @@ finish: return r; } +char *cunescape_length(const char *s, size_t length) { + return cunescape_length_with_prefix(s, length, NULL); +} + char *cunescape(const char *s) { + assert(s); + return cunescape_length(s, strlen(s)); } @@ -1894,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++) { @@ -1973,107 +1712,6 @@ char *bus_path_unescape(const char *f) { return r; } -char *path_kill_slashes(char *path) { - char *f, *t; - bool slash = false; - - /* Removes redundant inner and trailing slashes. Modifies the - * passed string in-place. - * - * ///foo///bar/ becomes /foo/bar - */ - - for (f = path, t = path; *f; f++) { - - if (*f == '/') { - slash = true; - continue; - } - - if (slash) { - slash = false; - *(t++) = '/'; - } - - *(t++) = *f; - } - - /* Special rule, if we are talking of the root directory, a - trailing slash is good */ - - if (t == path && slash) - *(t++) = '/'; - - *t = 0; - return path; -} - -bool path_startswith(const char *path, const char *prefix) { - assert(path); - assert(prefix); - - if ((path[0] == '/') != (prefix[0] == '/')) - return false; - - for (;;) { - size_t a, b; - - path += strspn(path, "/"); - prefix += strspn(prefix, "/"); - - if (*prefix == 0) - return true; - - if (*path == 0) - return false; - - a = strcspn(path, "/"); - b = strcspn(prefix, "/"); - - if (a != b) - return false; - - if (memcmp(path, prefix, a) != 0) - return false; - - path += a; - prefix += b; - } -} - -bool path_equal(const char *a, const char *b) { - assert(a); - assert(b); - - if ((a[0] == '/') != (b[0] == '/')) - return false; - - for (;;) { - size_t j, k; - - a += strspn(a, "/"); - b += strspn(b, "/"); - - if (*a == 0 && *b == 0) - return true; - - if (*a == 0 || *b == 0) - return false; - - j = strcspn(a, "/"); - k = strcspn(b, "/"); - - if (j != k) - return false; - - if (memcmp(a, b, j) != 0) - return false; - - a += j; - b += k; - } -} - char *ascii_strlower(char *t) { char *p; @@ -2086,7 +1724,7 @@ char *ascii_strlower(char *t) { return t; } -bool ignore_file(const char *filename) { +static bool ignore_file_allow_backup(const char *filename) { assert(filename); return @@ -2094,7 +1732,6 @@ bool ignore_file(const char *filename) { streq(filename, "lost+found") || streq(filename, "aquota.user") || streq(filename, "aquota.group") || - endswith(filename, "~") || endswith(filename, ".rpmnew") || endswith(filename, ".rpmsave") || endswith(filename, ".rpmorig") || @@ -2103,6 +1740,15 @@ bool ignore_file(const char *filename) { endswith(filename, ".swp"); } +bool ignore_file(const char *filename) { + assert(filename); + + if (endswith(filename, "~")) + return false; + + return ignore_file_allow_backup(filename); +} + int fd_nonblock(int fd, bool nonblock) { int flags; @@ -2224,160 +1870,24 @@ 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 * const table[] = { - "cifs", - "smbfs", - "ncpfs", - "nfs", - "nfs4", - "gfs", - "gfs2" - }; - - unsigned i; - - for (i = 0; i < ELEMENTSOF(table); i++) - if (streq(table[i], fstype)) - return true; + static const char table[] = + "cifs\0" + "smbfs\0" + "ncpfs\0" + "nfs\0" + "nfs4\0" + "gfs\0" + "gfs2\0"; - return false; + return nulstr_contains(table, fstype); } int chvt(int vt) { - int fd, r = 0; + _cleanup_close_ int fd; - if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0) + fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC); + if (fd < 0) return -errno; if (vt < 0) { @@ -2386,20 +1896,16 @@ int chvt(int vt) { 0 }; - if (ioctl(fd, TIOCLINUX, tiocl) < 0) { - r = -errno; - goto fail; - } + if (ioctl(fd, TIOCLINUX, tiocl) < 0) + return -errno; vt = tiocl[0] <= 0 ? 1 : tiocl[0]; } if (ioctl(fd, VT_ACTIVATE, vt) < 0) - r = -errno; + return -errno; -fail: - close_nointr_nofail(fd); - return r; + return 0; } int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) { @@ -2462,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); @@ -2603,12 +2106,14 @@ int open_terminal(const char *name, int mode) { */ for (;;) { - if ((fd = open(name, mode)) >= 0) + fd = open(name, mode); + if (fd >= 0) break; if (errno != EIO) return -errno; + /* Max 1s in total */ if (c >= 20) return -errno; @@ -2619,7 +2124,8 @@ int open_terminal(const char *name, int mode) { if (fd < 0) return -errno; - if ((r = isatty(fd)) < 0) { + r = isatty(fd); + if (r < 0) { close_nointr_nofail(fd); return -errno; } @@ -2671,8 +2177,16 @@ int flush_fd(int fd) { } } -int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) { - int fd = -1, notify = -1, r, wd = -1; +int acquire_terminal( + const char *name, + bool fail, + bool force, + bool ignore_tiocstty_eperm, + usec_t timeout) { + + int fd = -1, notify = -1, r = 0, wd = -1; + usec_t ts = 0; + struct sigaction sa_old, sa_new; assert(name); @@ -2689,40 +2203,57 @@ int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocst * on the same tty as an untrusted user this should not be a * problem. (Which he probably should not do anyway.) */ + if (timeout != (usec_t) -1) + ts = now(CLOCK_MONOTONIC); + if (!fail && !force) { - if ((notify = inotify_init1(IN_CLOEXEC)) < 0) { + notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0)); + if (notify < 0) { r = -errno; goto fail; } - if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) { + wd = inotify_add_watch(notify, name, IN_CLOSE); + if (wd < 0) { r = -errno; goto fail; } } for (;;) { - if (notify >= 0) - if ((r = flush_fd(notify)) < 0) + if (notify >= 0) { + r = flush_fd(notify); + if (r < 0) goto fail; + } /* We pass here O_NOCTTY only so that we can check the return * value TIOCSCTTY and have a reliable way to figure out if we * successfully became the controlling process of the tty */ - if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0) + fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC); + if (fd < 0) return fd; + /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed + * if we already own the tty. */ + zero(sa_new); + sa_new.sa_handler = SIG_IGN; + sa_new.sa_flags = SA_RESTART; + assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0); + /* First, try to get the tty */ - r = ioctl(fd, TIOCSCTTY, force); + if (ioctl(fd, TIOCSCTTY, force) < 0) + r = -errno; + + assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0); /* Sometimes it makes sense to ignore TIOCSCTTY * returning EPERM, i.e. when very likely we already * are have this controlling terminal. */ - if (r < 0 && errno == EPERM && ignore_tiocstty_eperm) + if (r < 0 && r == -EPERM && ignore_tiocstty_eperm) r = 0; - if (r < 0 && (force || fail || errno != EPERM)) { - r = -errno; + if (r < 0 && (force || fail || r != -EPERM)) { goto fail; } @@ -2738,9 +2269,29 @@ int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocst ssize_t l; struct inotify_event *e; - if ((l = read(notify, inotify_buffer, sizeof(inotify_buffer))) < 0) { + if (timeout != (usec_t) -1) { + usec_t n; + + n = now(CLOCK_MONOTONIC); + if (ts + timeout < n) { + r = -ETIMEDOUT; + goto fail; + } + + r = fd_wait_for_event(fd, POLLIN, ts + timeout - n); + if (r < 0) + goto fail; + + if (r == 0) { + r = -ETIMEDOUT; + goto fail; + } + } + + l = read(notify, inotify_buffer, sizeof(inotify_buffer)); + if (l < 0) { - if (errno == EINTR) + if (errno == EINTR || errno == EAGAIN) continue; r = -errno; @@ -2987,99 +2538,6 @@ ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) { return n; } -int path_is_mount_point(const char *t, bool allow_symlink) { - struct stat a, b; - char *parent; - int r; - - if (allow_symlink) - r = stat(t, &a); - else - r = lstat(t, &a); - - if (r < 0) { - if (errno == ENOENT) - return 0; - - return -errno; - } - - r = parent_of_path(t, &parent); - if (r < 0) - return r; - - r = lstat(parent, &b); - free(parent); - - if (r < 0) - return -errno; - - return a.st_dev != b.st_dev; -} - -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 }, - }; - - 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_bytes(const char *t, off_t *bytes) { static const struct { const char *suffix; @@ -3143,9 +2601,9 @@ int make_stdio(int fd) { assert(fd >= 0); - r = dup2(fd, STDIN_FILENO); - s = dup2(fd, STDOUT_FILENO); - t = dup2(fd, STDERR_FILENO); + r = dup3(fd, STDIN_FILENO, 0); + s = dup3(fd, STDOUT_FILENO, 0); + t = dup3(fd, STDERR_FILENO, 0); if (fd >= 3) close_nointr_nofail(fd); @@ -3153,9 +2611,7 @@ int make_stdio(int fd) { if (r < 0 || s < 0 || t < 0) return -errno; - fd_cloexec(STDIN_FILENO, false); - fd_cloexec(STDOUT_FILENO, false); - fd_cloexec(STDERR_FILENO, false); + /* We rely here that the new fd has O_CLOEXEC not set */ return 0; } @@ -3163,7 +2619,8 @@ int make_stdio(int fd) { int make_null_stdio(void) { int null_fd; - if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0) + null_fd = open("/dev/null", O_RDWR|O_NOCTTY); + if (null_fd < 0) return -errno; return make_stdio(null_fd); @@ -3180,45 +2637,39 @@ bool is_device_path(const char *path) { } int dir_is_empty(const char *path) { - DIR *d; + _cleanup_closedir_ DIR *d; int r; - struct dirent buf, *de; - if (!(d = opendir(path))) + d = opendir(path); + if (!d) return -errno; for (;;) { - if ((r = readdir_r(d, &buf, &de)) > 0) { - r = -r; - break; - } + struct dirent *de; + union dirent_storage buf; - if (!de) { - r = 1; - break; - } + r = readdir_r(d, &buf.de, &de); + if (r > 0) + return -r; - if (!ignore_file(de->d_name)) { - r = 0; - break; - } - } + if (!de) + return 1; - closedir(d); - return r; + if (!ignore_file(de->d_name)) + return 0; + } } unsigned long long random_ull(void) { - int fd; + _cleanup_close_ int fd; uint64_t ull; ssize_t r; - if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0) + fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY); + if (fd < 0) goto fallback; r = loop_read(fd, &ull, sizeof(ull), true); - close_nointr_nofail(fd); - if (r != sizeof(ull)) goto fallback; @@ -3276,41 +2727,40 @@ char* gethostname_malloc(void) { assert_se(uname(&u) >= 0); - if (u.nodename[0]) + if (!isempty(u.nodename) && !streq(u.nodename, "(none)")) return strdup(u.nodename); return strdup(u.sysname); } -char* getlogname_malloc(void) { - uid_t uid; +bool hostname_is_set(void) { + struct utsname u; + + assert_se(uname(&u) >= 0); + + return !isempty(u.nodename) && !streq(u.nodename, "(none)"); +} + +static char *lookup_uid(uid_t uid) { long bufsize; - char *buf, *name; + char *name; + _cleanup_free_ char *buf = NULL; struct passwd pwbuf, *pw = NULL; - struct stat st; - - if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0) - uid = st.st_uid; - else - uid = getuid(); /* Shortcut things to avoid NSS lookups */ if (uid == 0) return strdup("root"); - if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0) + bufsize = sysconf(_SC_GETPW_R_SIZE_MAX); + if (bufsize <= 0) bufsize = 4096; - if (!(buf = malloc(bufsize))) + buf = malloc(bufsize); + if (!buf) return NULL; - if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) { - name = strdup(pw->pw_name); - free(buf); - return name; - } - - free(buf); + if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) + return strdup(pw->pw_name); if (asprintf(&name, "%lu", (unsigned long) uid) < 0) return NULL; @@ -3318,18 +2768,42 @@ char* getlogname_malloc(void) { return name; } +char* getlogname_malloc(void) { + uid_t uid; + struct stat st; + + if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0) + uid = st.st_uid; + else + uid = getuid(); + + return lookup_uid(uid); +} + +char *getusername_malloc(void) { + const char *e; + + e = getenv("USER"); + if (e) + return strdup(e); + + return lookup_uid(getuid()); +} + int getttyname_malloc(int fd, char **r) { char path[PATH_MAX], *c; int k; assert(r); - if ((k = ttyname_r(fd, path, sizeof(path))) != 0) + k = ttyname_r(fd, path, sizeof(path)); + if (k != 0) return -k; char_array_0(path); - if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path))) + c = strdup(startswith(path, "/dev/") ? path + 5 : path); + if (!c) return -ENOMEM; *r = c; @@ -3340,7 +2814,8 @@ int getttyname_harder(int fd, char **r) { int k; char *s; - if ((k = getttyname_malloc(fd, &s)) < 0) + k = getttyname_malloc(fd, &s); + if (k < 0) return k; if (streq(s, "tty")) { @@ -3389,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; } @@ -3407,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; @@ -3428,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; @@ -3458,29 +2938,32 @@ int get_ctty(pid_t pid, dev_t *_devnr, char **r) { return 0; } -static int rm_rf_children(int fd, bool only_dirs, bool honour_sticky) { +int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) { DIR *d; int ret = 0; assert(fd >= 0); /* This returns the first error we run into, but nevertheless - * tries to go on */ + * tries to go on. This closes the passed fd. */ - if (!(d = fdopendir(fd))) { + d = fdopendir(fd); + if (!d) { close_nointr_nofail(fd); return errno == ENOENT ? 0 : -errno; } for (;;) { - struct dirent buf, *de; - bool is_dir, keep_around = false; + struct dirent *de; + union dirent_storage buf; + bool is_dir, keep_around; + struct stat st; int r; - if ((r = readdir_r(d, &buf, &de)) != 0) { - if (ret == 0) - ret = -r; + r = readdir_r(d, &buf.de, &de); + if (r != 0 && ret == 0) { + ret = -r; break; } @@ -3490,54 +2973,43 @@ static int rm_rf_children(int fd, bool only_dirs, bool honour_sticky) { if (streq(de->d_name, ".") || streq(de->d_name, "..")) continue; - if (de->d_type == DT_UNKNOWN) { - struct stat st; - + if (de->d_type == DT_UNKNOWN || + honour_sticky || + (de->d_type == DT_DIR && root_dev)) { if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) { if (ret == 0 && errno != ENOENT) ret = -errno; continue; } - if (honour_sticky) - keep_around = - (st.st_uid == 0 || st.st_uid == getuid()) && - (st.st_mode & S_ISVTX); - is_dir = S_ISDIR(st.st_mode); - + keep_around = + honour_sticky && + (st.st_uid == 0 || st.st_uid == getuid()) && + (st.st_mode & S_ISVTX); } else { - if (honour_sticky) { - struct stat st; - - if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) { - if (ret == 0 && errno != ENOENT) - ret = -errno; - continue; - } - - keep_around = - (st.st_uid == 0 || st.st_uid == getuid()) && - (st.st_mode & S_ISVTX); - } - is_dir = de->d_type == DT_DIR; + keep_around = false; } if (is_dir) { int subdir_fd; - subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW); + /* if root_dev is set, remove subdirectories only, if device is same as dir */ + if (root_dev && st.st_dev != root_dev->st_dev) + continue; + + subdir_fd = openat(fd, de->d_name, + O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME); if (subdir_fd < 0) { if (ret == 0 && errno != ENOENT) ret = -errno; continue; } - if ((r = rm_rf_children(subdir_fd, only_dirs, honour_sticky)) < 0) { - if (ret == 0) - ret = r; - } + r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev); + if (r < 0 && ret == 0) + ret = r; if (!keep_around) if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) { @@ -3559,26 +3031,85 @@ static int rm_rf_children(int fd, bool only_dirs, bool honour_sticky) { return ret; } -int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) { - int fd; - int r; +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; + + assert(fd >= 0); + + if (fstatfs(fd, &s) < 0) { + close_nointr_nofail(fd); + return -errno; + } + + /* We refuse to clean disk file systems with this call. This + * is extra paranoia just to be sure we never ever remove + * non-state data */ + if (!is_temporary_fs(&s)) { + log_error("Attempted to remove disk file system, and we can't allow that."); + close_nointr_nofail(fd); + return -EPERM; + } + + return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev); +} + +static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) { + int fd, r; + struct statfs s; assert(path); - if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) { + /* We refuse to clean the root file system with this + * call. This is extra paranoia to never cause a really + * seriously broken system. */ + if (path_equal(path, "/")) { + log_error("Attempted to remove entire root file system, and we can't allow that."); + return -EPERM; + } + + fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME); + if (fd < 0) { if (errno != ENOTDIR) return -errno; + if (!dangerous) { + if (statfs(path, &s) < 0) + return -errno; + + if (!is_temporary_fs(&s)) { + log_error("Attempted to remove disk file system, and we can't allow that."); + return -EPERM; + } + } + if (delete_root && !only_dirs) - if (unlink(path) < 0) + if (unlink(path) < 0 && errno != ENOENT) return -errno; return 0; } - r = rm_rf_children(fd, only_dirs, honour_sticky); + if (!dangerous) { + if (fstatfs(fd, &s) < 0) { + close_nointr_nofail(fd); + return -errno; + } + + 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; + } + } + r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL); if (delete_root) { if (honour_sticky && file_is_priv_sticky(path) > 0) @@ -3593,6 +3124,14 @@ int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky return r; } +int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) { + return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false); +} + +int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) { + return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true); +} + int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) { assert(path); @@ -3655,35 +3194,39 @@ cpu_set_t* cpu_set_malloc(unsigned *ncpus) { } } -void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) { - char *s = NULL, *spaces = NULL, *e; - int fd = -1, c; - size_t emax, sl, left; +int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) { + static const char status_indent[] = " "; /* "[" STATUS "] " */ + _cleanup_free_ char *s = NULL; + _cleanup_close_ int fd = -1; struct iovec iovec[5]; int n = 0; assert(format); - /* This independent of logging, as status messages are + /* This is independent of logging, as status messages are * optional and go exclusively to the console. */ if (vasprintf(&s, format, ap) < 0) - goto finish; + return log_oom(); fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC); if (fd < 0) - goto finish; + return fd; if (ellipse) { + char *e; + size_t emax, sl; + int c; + c = fd_columns(fd); if (c <= 0) c = 80; - if (status) { - sl = 2 + 6 + 1; /* " [" status "]" */ - emax = (size_t) c > sl ? c - sl - 1 : 0; - } else - emax = c - 1; + sl = status ? sizeof(status_indent)-1 : 0; + + emax = c - sl - 1; + if (emax < 3) + emax = 3; e = ellipsize(s, emax, 75); if (e) { @@ -3693,77 +3236,53 @@ void status_vprintf(const char *status, bool ellipse, const char *format, va_lis } zero(iovec); - IOVEC_SET_STRING(iovec[n++], s); - - if (ellipse) { - sl = strlen(s); - left = emax > sl ? emax - sl : 0; - if (left > 0) { - spaces = malloc(left); - if (spaces) { - memset(spaces, ' ', left); - iovec[n].iov_base = spaces; - iovec[n].iov_len = left; - n++; - } - } - } if (status) { - IOVEC_SET_STRING(iovec[n++], " ["); - IOVEC_SET_STRING(iovec[n++], status); - IOVEC_SET_STRING(iovec[n++], "]\n"); - } else - IOVEC_SET_STRING(iovec[n++], "\n"); + if (!isempty(status)) { + IOVEC_SET_STRING(iovec[n++], "["); + IOVEC_SET_STRING(iovec[n++], status); + IOVEC_SET_STRING(iovec[n++], "] "); + } else + IOVEC_SET_STRING(iovec[n++], status_indent); + } - writev(fd, iovec, n); + IOVEC_SET_STRING(iovec[n++], s); + IOVEC_SET_STRING(iovec[n++], "\n"); -finish: - free(s); - free(spaces); + if (writev(fd, iovec, n) < 0) + return -errno; - if (fd >= 0) - close_nointr_nofail(fd); + return 0; } -void status_printf(const char *status, bool ellipse, const char *format, ...) { +int status_printf(const char *status, bool ellipse, const char *format, ...) { va_list ap; + int r; assert(format); va_start(ap, format); - status_vprintf(status, ellipse, format, ap); + r = status_vprintf(status, ellipse, format, ap); va_end(ap); + + return r; } -void status_welcome(void) { - char *pretty_name = NULL, *ansi_color = NULL; - const char *const_pretty = NULL, *const_color = NULL; +int status_welcome(void) { int r; + _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL; - if ((r = parse_env_file("/etc/os-release", NEWLINE, - "PRETTY_NAME", &pretty_name, - "ANSI_COLOR", &ansi_color, - NULL)) < 0) { - - if (r != -ENOENT) - log_warning("Failed to read /etc/os-release: %s", strerror(-r)); - } - - if (!pretty_name && !const_pretty) - const_pretty = "Linux"; - - if (!ansi_color && !const_color) - const_color = "1"; + r = parse_env_file("/etc/os-release", NEWLINE, + "PRETTY_NAME", &pretty_name, + "ANSI_COLOR", &ansi_color, + NULL); + if (r < 0 && r != -ENOENT) + log_warning("Failed to read /etc/os-release: %s", strerror(-r)); - status_printf(NULL, - false, - "\nWelcome to \x1B[%sm%s\x1B[0m!\n", - const_color ? const_color : ansi_color, - const_pretty ? const_pretty : pretty_name); - - free(ansi_color); - free(pretty_name); + return status_printf(NULL, false, + "\nWelcome to \x1B[%sm%s\x1B[0m!\n", + isempty(ansi_color) ? "1" : ansi_color, + isempty(pretty_name) ? "Linux" : pretty_name); } char *replace_env(const char *format, char **env) { @@ -3914,23 +3433,25 @@ int fd_columns(int fd) { } unsigned columns(void) { - static __thread int parsed_columns = 0; const char *e; + int c; - if (_likely_(parsed_columns > 0)) - return parsed_columns; + if (_likely_(cached_columns > 0)) + return cached_columns; + c = 0; e = getenv("COLUMNS"); if (e) - parsed_columns = atoi(e); + safe_atoi(e, &c); - if (parsed_columns <= 0) - parsed_columns = fd_columns(STDOUT_FILENO); + if (c <= 0) + c = fd_columns(STDOUT_FILENO); - if (parsed_columns <= 0) - parsed_columns = 80; + if (c <= 0) + c = 80; - return parsed_columns; + cached_columns = c; + return c; } int fd_lines(int fd) { @@ -3947,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) { @@ -4025,7 +3563,12 @@ int touch(const char *path) { assert(path); - if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0) + /* This just opens the file for writing, ensuring it + * exists. It doesn't call utimensat() the way /usr/bin/touch + * does it. */ + + fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644); + if (fd < 0) return -errno; close_nointr_nofail(fd); @@ -4036,6 +3579,11 @@ char *unquote(const char *s, const char* quotes) { size_t l; assert(s); + /* This is rather stupid, simply removes the heading and + * trailing quotes if there is one. Doesn't care about + * escaping or anything. We should make this smarter one + * day...*/ + l = strlen(s); if (l < 2) return strdup(s); @@ -4047,39 +3595,40 @@ char *unquote(const char *s, const char* quotes) { } char *normalize_env_assignment(const char *s) { - char *name, *value, *p, *r; + _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL; + char *eq, *r; - p = strchr(s, '='); + eq = strchr(s, '='); + if (!eq) { + char *t; - if (!p) { - if (!(r = strdup(s))) + r = strdup(s); + if (!r) return NULL; - return strstrip(r); + t = strstrip(r); + if (t == r) + return r; + + memmove(r, t, strlen(t) + 1); + return r; } - if (!(name = strndup(s, p - s))) + name = strndup(s, eq - s); + if (!name) return NULL; - if (!(p = strdup(p+1))) { - free(name); + p = strdup(eq + 1); + if (!p) return NULL; - } value = unquote(strstrip(p), QUOTES); - free(p); - - if (!value) { - free(name); + if (!value) return NULL; - } - if (asprintf(&r, "%s=%s", name, value) < 0) + if (asprintf(&r, "%s=%s", strstrip(name), value) < 0) r = NULL; - free(value); - free(name); - return r; } @@ -4113,7 +3662,8 @@ int wait_for_terminate_and_warn(const char *name, pid_t pid) { assert(name); assert(pid > 1); - if ((r = wait_for_terminate(pid, &status)) < 0) { + r = wait_for_terminate(pid, &status); + if (r < 0) { log_warning("Failed to wait for %s: %s", name, strerror(-r)); return r; } @@ -4136,7 +3686,6 @@ int wait_for_terminate_and_warn(const char *name, pid_t pid) { log_warning("%s failed due to unknown reason.", name); return -EPROTO; - } _noreturn_ void freeze(void) { @@ -4177,10 +3726,12 @@ DIR *xopendirat(int fd, const char *name, int flags) { int nfd; DIR *d; - if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0) + nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags); + if (nfd < 0) return NULL; - if (!(d = fdopendir(nfd))) { + d = fdopendir(nfd); + if (!d) { close_nointr_nofail(nfd); return NULL; } @@ -4192,88 +3743,54 @@ int signal_from_string_try_harder(const char *s) { int signo; assert(s); - if ((signo = signal_from_string(s)) <= 0) + signo = signal_from_string(s); + if (signo <= 0) if (startswith(s, "SIG")) return signal_from_string(s+3); 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; - } -} - -char *fstab_node_to_udev_node(const char *p) { +static char *tag_to_udev_node(const char *tagvalue, const char *by) { char *dn, *t, *u; int r; /* FIXME: to follow udev's logic 100% we need to leave valid * UTF8 chars unescaped */ - if (startswith(p, "LABEL=")) { - - if (!(u = unquote(p+6, "\"\'"))) - return NULL; - - t = xescape(u, "/ "); - free(u); - - if (!t) - return NULL; + u = unquote(tagvalue, "\"\'"); + if (u == NULL) + return NULL; - r = asprintf(&dn, "/dev/disk/by-label/%s", t); - free(t); + t = xescape(u, "/ "); + free(u); - if (r < 0) - return NULL; + if (t == NULL) + return NULL; - return dn; - } + r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t); + free(t); - if (startswith(p, "UUID=")) { + if (r < 0) + return NULL; - if (!(u = unquote(p+5, "\"\'"))) - return NULL; + return dn; +} - t = xescape(u, "/ "); - free(u); +char *fstab_node_to_udev_node(const char *p) { + assert(p); - if (!t) - return NULL; + if (startswith(p, "LABEL=")) + return tag_to_udev_node(p+6, "label"); - r = asprintf(&dn, "/dev/disk/by-uuid/%s", t); - free(t); + if (startswith(p, "UUID=")) + return tag_to_udev_node(p+5, "uuid"); - if (r < 0) - return NULL; + if (startswith(p, "PARTUUID=")) + return tag_to_udev_node(p+9, "partuuid"); - return dn; - } + if (startswith(p, "PARTLABEL=")) + return tag_to_udev_node(p+10, "partlabel"); return strdup(p); } @@ -4287,6 +3804,15 @@ bool tty_is_vc(const char *tty) { return vtnr_from_tty(tty) >= 0; } +bool tty_is_console(const char *tty) { + assert(tty); + + if (startswith(tty, "/dev/")) + tty += 5; + + return streq(tty, "console"); +} + int vtnr_from_tty(const char *tty) { int i, r; @@ -4343,7 +3869,7 @@ bool tty_is_vc_resolve(const char *tty) { const char *default_term_for_tty(const char *tty) { assert(tty); - return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt100"; + return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102"; } bool dirent_is_file(const struct dirent *de) { @@ -4363,7 +3889,12 @@ bool dirent_is_file(const struct dirent *de) { bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) { assert(de); - if (!dirent_is_file(de)) + if (de->d_type != DT_REG && + de->d_type != DT_LNK && + de->d_type != DT_UNKNOWN) + return false; + + if (ignore_file_allow_backup(de->d_name)) return false; return endswith(de->d_name, suffix); @@ -4406,7 +3937,7 @@ void execute_directory(const char *directory, DIR *d, char *argv[]) { continue; if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) { - log_error("Out of memory"); + log_oom(); continue; } @@ -4425,8 +3956,7 @@ void execute_directory(const char *directory, DIR *d, char *argv[]) { _argv[1] = NULL; argv = _argv; } else - if (!argv[0]) - argv[0] = path; + argv[0] = path; execv(path, argv); @@ -4458,7 +3988,7 @@ void execute_directory(const char *directory, DIR *d, char *argv[]) { } if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) { - if (!is_clean_exit(si.si_code, si.si_status)) { + if (!is_clean_exit(si.si_code, si.si_status, NULL)) { if (si.si_code == CLD_EXITED) log_error("%s exited with exit status %i.", path, si.si_status); else @@ -4506,134 +4036,6 @@ bool plymouth_running(void) { return access("/run/plymouth/pid", F_OK) >= 0; } -void parse_syslog_priority(char **p, int *priority) { - int a = 0, b = 0, c = 0; - int k; - - assert(p); - assert(*p); - assert(priority); - - if ((*p)[0] != '<') - return; - - if (!strchr(*p, '>')) - return; - - if ((*p)[2] == '>') { - c = undecchar((*p)[1]); - k = 3; - } else if ((*p)[3] == '>') { - b = undecchar((*p)[1]); - c = undecchar((*p)[2]); - k = 4; - } else if ((*p)[4] == '>') { - a = undecchar((*p)[1]); - b = undecchar((*p)[2]); - c = undecchar((*p)[3]); - k = 5; - } else - return; - - if (a < 0 || b < 0 || c < 0) - return; - - *priority = a*100+b*10+c; - *p += k; -} - -void skip_syslog_pid(char **buf) { - char *p; - - assert(buf); - assert(*buf); - - p = *buf; - - if (*p != '[') - return; - - p++; - p += strspn(p, "0123456789"); - - if (*p != ']') - return; - - p++; - - *buf = p; -} - -void skip_syslog_date(char **buf) { - enum { - LETTER, - SPACE, - NUMBER, - SPACE_OR_NUMBER, - COLON - } sequence[] = { - LETTER, LETTER, LETTER, - SPACE, - SPACE_OR_NUMBER, NUMBER, - SPACE, - SPACE_OR_NUMBER, NUMBER, - COLON, - SPACE_OR_NUMBER, NUMBER, - COLON, - SPACE_OR_NUMBER, NUMBER, - SPACE - }; - - char *p; - unsigned i; - - assert(buf); - assert(*buf); - - p = *buf; - - for (i = 0; i < ELEMENTSOF(sequence); i++, p++) { - - if (!*p) - return; - - switch (sequence[i]) { - - case SPACE: - if (*p != ' ') - return; - break; - - case SPACE_OR_NUMBER: - if (*p == ' ') - break; - - /* fall through */ - - case NUMBER: - if (*p < '0' || *p > '9') - return; - - break; - - case LETTER: - if (!(*p >= 'A' && *p <= 'Z') && - !(*p >= 'a' && *p <= 'z')) - return; - - break; - - case COLON: - if (*p != ':') - return; - break; - - } - } - - *buf = p; -} - char* strshorten(char *s, size_t l) { assert(s); @@ -4738,7 +4140,7 @@ int fopen_temporary(const char *path, FILE **_f, char **_temp_path) { if (!t) return -ENOMEM; - fn = file_name_from_path(path); + fn = path_get_file_name(path); k = fn-path; memcpy(t, path, k); t[k] = '.'; @@ -4854,1308 +4256,1620 @@ int vt_disallocate(const char *name) { return 0; } -static int files_add(Hashmap *h, const char *path, const char *suffix) { - DIR *dir; - struct dirent buffer, *de; - int r = 0; +int copy_file(const char *from, const char *to) { + int r, fdf, fdt; - dir = opendir(path); - if (!dir) { - if (errno == ENOENT) - return 0; + assert(from); + assert(to); + + fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY); + if (fdf < 0) + return -errno; + + fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644); + if (fdt < 0) { + close_nointr_nofail(fdf); return -errno; } for (;;) { - int k; - char *p, *f; + char buf[PIPE_BUF]; + ssize_t n, k; - k = readdir_r(dir, &buffer, &de); - if (k != 0) { - r = -k; - goto finish; + n = read(fdf, buf, sizeof(buf)); + if (n < 0) { + r = -errno; + + close_nointr_nofail(fdf); + close_nointr(fdt); + unlink(to); + + return r; } - if (!de) + if (n == 0) break; - if (!dirent_is_file_with_suffix(de, suffix)) - continue; + errno = 0; + k = loop_write(fdt, buf, n, false); + if (n != k) { + r = k < 0 ? k : (errno ? -errno : -EIO); - if (asprintf(&p, "%s/%s", path, de->d_name) < 0) { - r = -ENOMEM; - goto finish; - } + close_nointr_nofail(fdf); + close_nointr(fdt); - f = canonicalize_file_name(p); - if (!f) { - log_error("Failed to canonicalize file name '%s': %m", p); - free(p); - continue; + unlink(to); + return r; } - free(p); + } + + close_nointr_nofail(fdf); + r = close_nointr(fdt); - log_debug("found: %s\n", f); - if (hashmap_put(h, file_name_from_path(f), f) <= 0) - free(f); + if (r < 0) { + unlink(to); + return r; } -finish: - closedir(dir); - return r; + return 0; } -static int base_cmp(const void *a, const void *b) { - const char *s1, *s2; +int symlink_atomic(const char *from, const char *to) { + char *x; + _cleanup_free_ char *t; + const char *fn; + size_t k; + unsigned long long ull; + unsigned i; + int r; - s1 = *(char * const *)a; - s2 = *(char * const *)b; - return strcmp(file_name_from_path(s1), file_name_from_path(s2)); -} + assert(from); + assert(to); -int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) { - Hashmap *fh = NULL; - char **dirs = NULL; - char **files = NULL; - char **p; - va_list ap; - int r = 0; + t = new(char, strlen(to) + 1 + 16 + 1); + if (!t) + return -ENOMEM; - va_start(ap, dir); - dirs = strv_new_ap(dir, ap); - va_end(ap); - if (!dirs) { - r = -ENOMEM; - goto finish; - } - if (!strv_path_canonicalize(dirs)) { - r = -ENOMEM; - goto finish; - } - if (!strv_uniq(dirs)) { - r = -ENOMEM; - goto finish; - } + fn = path_get_file_name(to); + k = fn-to; + memcpy(t, to, k); + t[k] = '.'; + x = stpcpy(t+k+1, fn); - fh = hashmap_new(string_hash_func, string_compare_func); - if (!fh) { - r = -ENOMEM; - goto finish; + ull = random_ull(); + for (i = 0; i < 16; i++) { + *(x++) = hexchar(ull & 0xF); + ull >>= 4; } - STRV_FOREACH(p, dirs) { - if (files_add(fh, *p, suffix) < 0) { - log_error("Failed to search for files."); - r = -EINVAL; - goto finish; - } - } + *x = 0; - files = hashmap_get_strv(fh); - if (files == NULL) { - log_error("Failed to compose list of files."); - r = -ENOMEM; - goto finish; - } + if (symlink(from, t) < 0) + return -errno; - qsort(files, hashmap_size(fh), sizeof(char *), base_cmp); + if (rename(t, to) < 0) { + r = -errno; + unlink(t); + return r; + } -finish: - strv_free(dirs); - hashmap_free(fh); - *strv = files; - return r; + return 0; } -int hwclock_is_localtime(void) { - FILE *f; - bool local = false; +bool display_is_local(const char *display) { + assert(display); - /* - * The third line of adjtime is "UTC" or "LOCAL" or nothing. - * # /etc/adjtime - * 0.0 0 0 - * 0 - * UTC - */ - f = fopen("/etc/adjtime", "re"); - if (f) { - char line[LINE_MAX]; - bool b; + return + display[0] == ':' && + display[1] >= '0' && + display[1] <= '9'; +} - b = fgets(line, sizeof(line), f) && - fgets(line, sizeof(line), f) && - fgets(line, sizeof(line), f); +int socket_from_display(const char *display, char **path) { + size_t k; + char *f, *c; - fclose(f); + assert(display); + assert(path); - if (!b) - return -EIO; + if (!display_is_local(display)) + return -EINVAL; + k = strspn(display+1, "0123456789"); - truncate_nl(line); - local = streq(line, "LOCAL"); + f = new(char, sizeof("/tmp/.X11-unix/X") + k); + if (!f) + return -ENOMEM; - } else if (errno != -ENOENT) - return -errno; + c = stpcpy(f, "/tmp/.X11-unix/X"); + memcpy(c, display+1, k); + c[k] = 0; - return local; + *path = f; + + return 0; } -int hwclock_apply_localtime_delta(int *min) { - const struct timeval *tv_null = NULL; - struct timespec ts; - struct tm *tm; - int minuteswest; - struct timezone tz; +int get_user_creds( + const char **username, + uid_t *uid, gid_t *gid, + const char **home, + const char **shell) { - assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0); - assert_se(tm = localtime(&ts.tv_sec)); - minuteswest = tm->tm_gmtoff / 60; + struct passwd *p; + uid_t u; - tz.tz_minuteswest = -minuteswest; - tz.tz_dsttime = 0; /* DST_NONE*/ + assert(username); + assert(*username); - /* - * If the hardware clock does not run in UTC, but in local time: - * The very first time we set the kernel's timezone, it will warp - * the clock so that it runs in UTC instead of local time. - */ - if (settimeofday(tv_null, &tz) < 0) - return -errno; - if (min) - *min = minuteswest; - return 0; -} + /* We enforce some special rules for uid=0: in order to avoid + * NSS lookups for root we hardcode its data. */ -int hwclock_reset_localtime_delta(void) { - const struct timeval *tv_null = NULL; - struct timezone tz; + if (streq(*username, "root") || streq(*username, "0")) { + *username = "root"; - tz.tz_minuteswest = 0; - tz.tz_dsttime = 0; /* DST_NONE*/ + if (uid) + *uid = 0; - if (settimeofday(tv_null, &tz) < 0) - return -errno; + if (gid) + *gid = 0; - return 0; -} + if (home) + *home = "/root"; -int rtc_open(int flags) { - int fd; - DIR *d; + if (shell) + *shell = "/bin/sh"; - /* First, we try to make use of the /dev/rtc symlink. If that - * doesn't exist, we open the first RTC which has hctosys=1 - * set. If we don't find any we just take the first RTC that - * exists at all. */ + return 0; + } - fd = open("/dev/rtc", flags); - if (fd >= 0) - return fd; + if (parse_uid(*username, &u) >= 0) { + errno = 0; + p = getpwuid(u); - d = opendir("/sys/class/rtc"); - if (!d) - goto fallback; + /* If there are multiple users with the same id, make + * sure to leave $USER to the configured value instead + * of the first occurrence in the database. However if + * the uid was configured by a numeric uid, then let's + * pick the real username from /etc/passwd. */ + if (p) + *username = p->pw_name; + } else { + errno = 0; + p = getpwnam(*username); + } - for (;;) { - char *p, *v; - struct dirent buf, *de; - int r; + if (!p) + return errno != 0 ? -errno : -ESRCH; - r = readdir_r(d, &buf, &de); - if (r != 0) - goto fallback; + if (uid) + *uid = p->pw_uid; - if (!de) - goto fallback; + if (gid) + *gid = p->pw_gid; - if (ignore_file(de->d_name)) - continue; + if (home) + *home = p->pw_dir; - p = join("/sys/class/rtc/", de->d_name, "/hctosys", NULL); - if (!p) { - closedir(d); - return -ENOMEM; - } + if (shell) + *shell = p->pw_shell; - r = read_one_line_file(p, &v); - free(p); + return 0; +} - if (r < 0) - continue; +char* uid_to_name(uid_t uid) { + struct passwd *p; + char *r; - r = parse_boolean(v); - free(v); + if (uid == 0) + return strdup("root"); - if (r <= 0) - continue; + p = getpwuid(uid); + if (p) + return strdup(p->pw_name); - p = strappend("/dev/", de->d_name); - fd = open(p, flags); - free(p); + if (asprintf(&r, "%lu", (unsigned long) uid) < 0) + return NULL; - if (fd >= 0) { - closedir(d); - return fd; - } - } + return r; +} -fallback: - if (d) - closedir(d); +int get_group_creds(const char **groupname, gid_t *gid) { + struct group *g; + gid_t id; - fd = open("/dev/rtc0", flags); - if (fd < 0) - return -errno; + assert(groupname); - return fd; -} + /* We enforce some special rules for gid=0: in order to avoid + * NSS lookups for root we hardcode its data. */ -int hwclock_get_time(struct tm *tm) { - int fd; - int err = 0; + if (streq(*groupname, "root") || streq(*groupname, "0")) { + *groupname = "root"; + + if (gid) + *gid = 0; - assert(tm); + return 0; + } - fd = rtc_open(O_RDONLY|O_CLOEXEC); - if (fd < 0) - return -errno; + if (parse_gid(*groupname, &id) >= 0) { + errno = 0; + g = getgrgid(id); - /* This leaves the timezone fields of struct tm - * uninitialized! */ - if (ioctl(fd, RTC_RD_TIME, tm) < 0) - err = -errno; + if (g) + *groupname = g->gr_name; + } else { + errno = 0; + g = getgrnam(*groupname); + } - /* We don't now daylight saving, so we reset this in order not - * to confused mktime(). */ - tm->tm_isdst = -1; + if (!g) + return errno != 0 ? -errno : -ESRCH; - close_nointr_nofail(fd); + if (gid) + *gid = g->gr_gid; - return err; + return 0; } -int hwclock_set_time(const struct tm *tm) { - int fd; - int err = 0; +int in_group(const char *name) { + gid_t gid, *gids; + int ngroups_max, r, i; - assert(tm); + r = get_group_creds(&name, &gid); + if (r < 0) + return r; - fd = rtc_open(O_RDONLY|O_CLOEXEC); - if (fd < 0) - return -errno; + if (getgid() == gid) + return 1; - if (ioctl(fd, RTC_SET_TIME, tm) < 0) - err = -errno; + if (getegid() == gid) + return 1; - close_nointr_nofail(fd); + ngroups_max = sysconf(_SC_NGROUPS_MAX); + assert(ngroups_max > 0); - return err; -} + gids = alloca(sizeof(gid_t) * ngroups_max); -int copy_file(const char *from, const char *to) { - int r, fdf, fdt; + r = getgroups(ngroups_max, gids); + if (r < 0) + return -errno; - assert(from); - assert(to); + for (i = 0; i < r; i++) + if (gids[i] == gid) + return 1; - fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY); - if (fdf < 0) - return -errno; + return 0; +} - fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644); - if (fdt < 0) { - close_nointr_nofail(fdf); - return -errno; - } +int glob_exists(const char *path) { + glob_t g; + int r, k; - for (;;) { - char buf[PIPE_BUF]; - ssize_t n, k; + assert(path); - n = read(fdf, buf, sizeof(buf)); - if (n < 0) { - r = -errno; + zero(g); + errno = 0; + k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g); - close_nointr_nofail(fdf); - close_nointr(fdt); - unlink(to); + if (k == GLOB_NOMATCH) + r = 0; + else if (k == GLOB_NOSPACE) + r = -ENOMEM; + else if (k == 0) + r = !strv_isempty(g.gl_pathv); + else + r = errno ? -errno : -EIO; - return r; - } + globfree(&g); - if (n == 0) - break; + return r; +} - errno = 0; - k = loop_write(fdt, buf, n, false); - if (n != k) { - r = k < 0 ? k : (errno ? -errno : -EIO); +int dirent_ensure_type(DIR *d, struct dirent *de) { + struct stat st; - close_nointr_nofail(fdf); - close_nointr(fdt); + assert(d); + assert(de); - unlink(to); - return r; - } - } + if (de->d_type != DT_UNKNOWN) + return 0; - close_nointr_nofail(fdf); - r = close_nointr(fdt); + if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) + return -errno; - if (r < 0) { - unlink(to); - return r; - } + de->d_type = + S_ISREG(st.st_mode) ? DT_REG : + S_ISDIR(st.st_mode) ? DT_DIR : + S_ISLNK(st.st_mode) ? DT_LNK : + S_ISFIFO(st.st_mode) ? DT_FIFO : + S_ISSOCK(st.st_mode) ? DT_SOCK : + S_ISCHR(st.st_mode) ? DT_CHR : + S_ISBLK(st.st_mode) ? DT_BLK : + DT_UNKNOWN; return 0; } -int symlink_or_copy(const char *from, const char *to) { - char *pf = NULL, *pt = NULL; - struct stat a, b; +int in_search_path(const char *path, char **search) { + char **i, *parent; int r; - assert(from); - assert(to); + r = path_get_parent(path, &parent); + if (r < 0) + return r; - if (parent_of_path(from, &pf) < 0 || - parent_of_path(to, &pt) < 0) { - r = -ENOMEM; - goto finish; - } + r = 0; - if (stat(pf, &a) < 0 || - stat(pt, &b) < 0) { - r = -errno; - goto finish; + STRV_FOREACH(i, search) { + if (path_equal(parent, *i)) { + r = 1; + break; + } } - if (a.st_dev != b.st_dev) { - free(pf); - free(pt); + free(parent); - return copy_file(from, to); - } + return r; +} - if (symlink(from, to) < 0) { - r = -errno; - goto finish; - } +int get_files_in_directory(const char *path, char ***list) { + DIR *d; + int r = 0; + unsigned n = 0; + char **l = NULL; - r = 0; + assert(path); -finish: - free(pf); - free(pt); + /* Returns all files in a directory in *list, and the number + * of files as return value. If list is NULL returns only the + * number */ - return r; -} + d = opendir(path); + if (!d) + return -errno; -int symlink_or_copy_atomic(const char *from, const char *to) { - char *t, *x; - const char *fn; - size_t k; - unsigned long long ull; - unsigned i; - int r; + for (;;) { + struct dirent *de; + union dirent_storage buf; + int k; - assert(from); - assert(to); + k = readdir_r(d, &buf.de, &de); + if (k != 0) { + r = -k; + goto finish; + } - t = new(char, strlen(to) + 1 + 16 + 1); - if (!t) - return -ENOMEM; + if (!de) + break; - fn = file_name_from_path(to); - k = fn-to; - memcpy(t, to, k); - t[k] = '.'; - x = stpcpy(t+k+1, fn); + dirent_ensure_type(d, de); - ull = random_ull(); - for (i = 0; i < 16; i++) { - *(x++) = hexchar(ull & 0xF); - ull >>= 4; - } + if (!dirent_is_file(de)) + continue; - *x = 0; + if (list) { + if ((unsigned) r >= n) { + char **t; - r = symlink_or_copy(from, t); - if (r < 0) { - unlink(t); - free(t); - return r; - } + n = MAX(16, 2*r); + t = realloc(l, sizeof(char*) * n); + if (!t) { + r = -ENOMEM; + goto finish; + } - if (rename(t, to) < 0) { - r = -errno; - unlink(t); - free(t); - return r; - } + l = t; + } - free(t); - return r; -} + assert((unsigned) r < n); -bool display_is_local(const char *display) { - assert(display); + l[r] = strdup(de->d_name); + if (!l[r]) { + r = -ENOMEM; + goto finish; + } - return - display[0] == ':' && - display[1] >= '0' && - display[1] <= '9'; -} + l[++r] = NULL; + } else + r++; + } -int socket_from_display(const char *display, char **path) { - size_t k; - char *f, *c; +finish: + if (d) + closedir(d); - assert(display); - assert(path); + if (r >= 0) { + if (list) + *list = l; + } else + strv_free(l); - if (!display_is_local(display)) - return -EINVAL; + return r; +} - k = strspn(display+1, "0123456789"); +char *strjoin(const char *x, ...) { + va_list ap; + size_t l; + char *r, *p; - f = new(char, sizeof("/tmp/.X11-unix/X") + k); - if (!f) - return -ENOMEM; + va_start(ap, x); - c = stpcpy(f, "/tmp/.X11-unix/X"); - memcpy(c, display+1, k); - c[k] = 0; + if (x) { + l = strlen(x); - *path = f; + for (;;) { + const char *t; + size_t n; - return 0; -} + t = va_arg(ap, const char *); + if (!t) + break; -int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) { - struct passwd *p; - uid_t u; + n = strlen(t); + if (n > ((size_t) -1) - l) { + va_end(ap); + return NULL; + } - assert(username); - assert(*username); + l += n; + } + } else + l = 0; - /* We enforce some special rules for uid=0: in order to avoid - * NSS lookups for root we hardcode its data. */ + va_end(ap); - if (streq(*username, "root") || streq(*username, "0")) { - *username = "root"; + r = new(char, l+1); + if (!r) + return NULL; - if (uid) - *uid = 0; + if (x) { + p = stpcpy(r, x); - if (gid) - *gid = 0; + va_start(ap, x); - if (home) - *home = "/root"; - return 0; - } + for (;;) { + const char *t; - if (parse_uid(*username, &u) >= 0) { - errno = 0; - p = getpwuid(u); + t = va_arg(ap, const char *); + if (!t) + break; - /* If there are multiple users with the same id, make - * sure to leave $USER to the configured value instead - * of the first occurrence in the database. However if - * the uid was configured by a numeric uid, then let's - * pick the real username from /etc/passwd. */ - if (p) - *username = p->pw_name; - } else { - errno = 0; - p = getpwnam(*username); - } + p = stpcpy(p, t); + } - if (!p) - return errno != 0 ? -errno : -ESRCH; + va_end(ap); + } else + r[0] = 0; - if (uid) - *uid = p->pw_uid; + return r; +} - if (gid) - *gid = p->pw_gid; +bool is_main_thread(void) { + static __thread int cached = 0; - if (home) - *home = p->pw_dir; + if (_unlikely_(cached == 0)) + cached = getpid() == gettid() ? 1 : -1; - return 0; + return cached > 0; } -int get_group_creds(const char **groupname, gid_t *gid) { - struct group *g; - gid_t id; - - assert(groupname); +int block_get_whole_disk(dev_t d, dev_t *ret) { + char *p, *s; + int r; + unsigned n, m; - /* We enforce some special rules for gid=0: in order to avoid - * NSS lookups for root we hardcode its data. */ + assert(ret); - if (streq(*groupname, "root") || streq(*groupname, "0")) { - *groupname = "root"; + /* If it has a queue this is good enough for us */ + if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0) + return -ENOMEM; - if (gid) - *gid = 0; + r = access(p, F_OK); + free(p); + if (r >= 0) { + *ret = d; return 0; } - if (parse_gid(*groupname, &id) >= 0) { - errno = 0; - g = getgrgid(id); - - if (g) - *groupname = g->gr_name; - } else { - errno = 0; - g = getgrnam(*groupname); - } + /* If it is a partition find the originating device */ + if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0) + return -ENOMEM; - if (!g) - return errno != 0 ? -errno : -ESRCH; + r = access(p, F_OK); + free(p); - if (gid) - *gid = g->gr_gid; + if (r < 0) + return -ENOENT; - return 0; -} + /* Get parent dev_t */ + if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0) + return -ENOMEM; -int in_group(const char *name) { - gid_t gid, *gids; - int ngroups_max, r, i; + r = read_one_line_file(p, &s); + free(p); - r = get_group_creds(&name, &gid); if (r < 0) return r; - if (getgid() == gid) - return 1; + r = sscanf(s, "%u:%u", &m, &n); + free(s); - if (getegid() == gid) - return 1; + if (r != 2) + return -EINVAL; - ngroups_max = sysconf(_SC_NGROUPS_MAX); - assert(ngroups_max > 0); + /* Only return this if it is really good enough for us. */ + if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0) + return -ENOMEM; - gids = alloca(sizeof(gid_t) * ngroups_max); + r = access(p, F_OK); + free(p); - r = getgroups(ngroups_max, gids); - if (r < 0) + if (r >= 0) { + *ret = makedev(m, n); + return 0; + } + + return -ENOENT; +} + +int file_is_priv_sticky(const char *p) { + struct stat st; + + assert(p); + + if (lstat(p, &st) < 0) return -errno; - for (i = 0; i < r; i++) - if (gids[i] == gid) - return 1; + return + (st.st_uid == 0 || st.st_uid == getuid()) && + (st.st_mode & S_ISVTX); +} + +static const char *const ioprio_class_table[] = { + [IOPRIO_CLASS_NONE] = "none", + [IOPRIO_CLASS_RT] = "realtime", + [IOPRIO_CLASS_BE] = "best-effort", + [IOPRIO_CLASS_IDLE] = "idle" +}; + +DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX); + +static const char *const sigchld_code_table[] = { + [CLD_EXITED] = "exited", + [CLD_KILLED] = "killed", + [CLD_DUMPED] = "dumped", + [CLD_TRAPPED] = "trapped", + [CLD_STOPPED] = "stopped", + [CLD_CONTINUED] = "continued", +}; + +DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int); + +static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = { + [LOG_FAC(LOG_KERN)] = "kern", + [LOG_FAC(LOG_USER)] = "user", + [LOG_FAC(LOG_MAIL)] = "mail", + [LOG_FAC(LOG_DAEMON)] = "daemon", + [LOG_FAC(LOG_AUTH)] = "auth", + [LOG_FAC(LOG_SYSLOG)] = "syslog", + [LOG_FAC(LOG_LPR)] = "lpr", + [LOG_FAC(LOG_NEWS)] = "news", + [LOG_FAC(LOG_UUCP)] = "uucp", + [LOG_FAC(LOG_CRON)] = "cron", + [LOG_FAC(LOG_AUTHPRIV)] = "authpriv", + [LOG_FAC(LOG_FTP)] = "ftp", + [LOG_FAC(LOG_LOCAL0)] = "local0", + [LOG_FAC(LOG_LOCAL1)] = "local1", + [LOG_FAC(LOG_LOCAL2)] = "local2", + [LOG_FAC(LOG_LOCAL3)] = "local3", + [LOG_FAC(LOG_LOCAL4)] = "local4", + [LOG_FAC(LOG_LOCAL5)] = "local5", + [LOG_FAC(LOG_LOCAL6)] = "local6", + [LOG_FAC(LOG_LOCAL7)] = "local7" +}; + +DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0)); + +static const char *const log_level_table[] = { + [LOG_EMERG] = "emerg", + [LOG_ALERT] = "alert", + [LOG_CRIT] = "crit", + [LOG_ERR] = "err", + [LOG_WARNING] = "warning", + [LOG_NOTICE] = "notice", + [LOG_INFO] = "info", + [LOG_DEBUG] = "debug" +}; + +DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG); + +static const char* const sched_policy_table[] = { + [SCHED_OTHER] = "other", + [SCHED_BATCH] = "batch", + [SCHED_IDLE] = "idle", + [SCHED_FIFO] = "fifo", + [SCHED_RR] = "rr" +}; + +DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX); + +static const char* const rlimit_table[] = { + [RLIMIT_CPU] = "LimitCPU", + [RLIMIT_FSIZE] = "LimitFSIZE", + [RLIMIT_DATA] = "LimitDATA", + [RLIMIT_STACK] = "LimitSTACK", + [RLIMIT_CORE] = "LimitCORE", + [RLIMIT_RSS] = "LimitRSS", + [RLIMIT_NOFILE] = "LimitNOFILE", + [RLIMIT_AS] = "LimitAS", + [RLIMIT_NPROC] = "LimitNPROC", + [RLIMIT_MEMLOCK] = "LimitMEMLOCK", + [RLIMIT_LOCKS] = "LimitLOCKS", + [RLIMIT_SIGPENDING] = "LimitSIGPENDING", + [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE", + [RLIMIT_NICE] = "LimitNICE", + [RLIMIT_RTPRIO] = "LimitRTPRIO", + [RLIMIT_RTTIME] = "LimitRTTIME" +}; + +DEFINE_STRING_TABLE_LOOKUP(rlimit, int); + +static const char* const ip_tos_table[] = { + [IPTOS_LOWDELAY] = "low-delay", + [IPTOS_THROUGHPUT] = "throughput", + [IPTOS_RELIABILITY] = "reliability", + [IPTOS_LOWCOST] = "low-cost", +}; + +DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff); + +static const char *const __signal_table[] = { + [SIGHUP] = "HUP", + [SIGINT] = "INT", + [SIGQUIT] = "QUIT", + [SIGILL] = "ILL", + [SIGTRAP] = "TRAP", + [SIGABRT] = "ABRT", + [SIGBUS] = "BUS", + [SIGFPE] = "FPE", + [SIGKILL] = "KILL", + [SIGUSR1] = "USR1", + [SIGSEGV] = "SEGV", + [SIGUSR2] = "USR2", + [SIGPIPE] = "PIPE", + [SIGALRM] = "ALRM", + [SIGTERM] = "TERM", +#ifdef SIGSTKFLT + [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */ +#endif + [SIGCHLD] = "CHLD", + [SIGCONT] = "CONT", + [SIGSTOP] = "STOP", + [SIGTSTP] = "TSTP", + [SIGTTIN] = "TTIN", + [SIGTTOU] = "TTOU", + [SIGURG] = "URG", + [SIGXCPU] = "XCPU", + [SIGXFSZ] = "XFSZ", + [SIGVTALRM] = "VTALRM", + [SIGPROF] = "PROF", + [SIGWINCH] = "WINCH", + [SIGIO] = "IO", + [SIGPWR] = "PWR", + [SIGSYS] = "SYS" +}; + +DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int); + +const char *signal_to_string(int signo) { + static __thread char buf[12]; + const char *name; + + name = __signal_to_string(signo); + if (name) + return name; + + if (signo >= SIGRTMIN && signo <= SIGRTMAX) + snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN); + else + snprintf(buf, sizeof(buf) - 1, "%d", signo); + char_array_0(buf); + return buf; +} + +int signal_from_string(const char *s) { + int signo; + int offset = 0; + unsigned u; + + signo = __signal_from_string(s); + if (signo > 0) + return signo; + + if (startswith(s, "RTMIN+")) { + s += 6; + offset = SIGRTMIN; + } + if (safe_atou(s, &u) >= 0) { + signo = (int) u + offset; + if (signo > 0 && signo < _NSIG) + return signo; + } + return -1; +} + +bool kexec_loaded(void) { + bool loaded = false; + char *s; + + if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) { + if (s[0] == '1') + loaded = true; + free(s); + } + return loaded; +} + +int strdup_or_null(const char *a, char **b) { + char *c; + + assert(b); + + if (!a) { + *b = NULL; + return 0; + } + + c = strdup(a); + if (!c) + return -ENOMEM; + *b = c; return 0; } -int glob_exists(const char *path) { - glob_t g; - int r, k; +int prot_from_flags(int flags) { - assert(path); + switch (flags & O_ACCMODE) { - zero(g); - errno = 0; - k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g); + case O_RDONLY: + return PROT_READ; - if (k == GLOB_NOMATCH) - r = 0; - else if (k == GLOB_NOSPACE) - r = -ENOMEM; - else if (k == 0) - r = !strv_isempty(g.gl_pathv); - else - r = errno ? -errno : -EIO; + case O_WRONLY: + return PROT_WRITE; + + case O_RDWR: + return PROT_READ|PROT_WRITE; + + default: + return -EINVAL; + } +} + +char *format_bytes(char *buf, size_t l, off_t t) { + unsigned i; + + static const struct { + const char *suffix; + off_t factor; + } table[] = { + { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL }, + { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL }, + { "T", 1024ULL*1024ULL*1024ULL*1024ULL }, + { "G", 1024ULL*1024ULL*1024ULL }, + { "M", 1024ULL*1024ULL }, + { "K", 1024ULL }, + }; + + for (i = 0; i < ELEMENTSOF(table); i++) { + + if (t >= table[i].factor) { + snprintf(buf, l, + "%llu.%llu%s", + (unsigned long long) (t / table[i].factor), + (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL), + table[i].suffix); + + goto finish; + } + } + + snprintf(buf, l, "%lluB", (unsigned long long) t); + +finish: + buf[l-1] = 0; + return buf; + +} + +void* memdup(const void *p, size_t l) { + void *r; + + assert(p); + + r = malloc(l); + if (!r) + return NULL; + + memcpy(r, p, l); + return r; +} + +int fd_inc_sndbuf(int fd, size_t n) { + int r, value; + socklen_t l = sizeof(value); + + r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l); + if (r >= 0 && + l == sizeof(value) && + (size_t) value >= n*2) + return 0; + + value = (int) n; + r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)); + if (r < 0) + return -errno; + + return 1; +} + +int fd_inc_rcvbuf(int fd, size_t n) { + int r, value; + socklen_t l = sizeof(value); + + r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l); + if (r >= 0 && + l == sizeof(value) && + (size_t) value >= n*2) + return 0; - globfree(&g); + value = (int) n; + r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)); + if (r < 0) + return -errno; - return r; + return 1; } -int dirent_ensure_type(DIR *d, struct dirent *de) { - struct stat st; +int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) { + pid_t parent_pid, agent_pid; + int fd; + bool stdout_is_tty, stderr_is_tty; + unsigned n, i; + va_list ap; + char **l; - assert(d); - assert(de); + assert(pid); + assert(path); - if (de->d_type != DT_UNKNOWN) - return 0; + parent_pid = getpid(); - if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) + /* Spawns a temporary TTY agent, making sure it goes away when + * we go away */ + + agent_pid = fork(); + if (agent_pid < 0) return -errno; - de->d_type = - S_ISREG(st.st_mode) ? DT_REG : - S_ISDIR(st.st_mode) ? DT_DIR : - S_ISLNK(st.st_mode) ? DT_LNK : - S_ISFIFO(st.st_mode) ? DT_FIFO : - S_ISSOCK(st.st_mode) ? DT_SOCK : - S_ISCHR(st.st_mode) ? DT_CHR : - S_ISBLK(st.st_mode) ? DT_BLK : - DT_UNKNOWN; + if (agent_pid != 0) { + *pid = agent_pid; + return 0; + } - return 0; -} + /* In the child: + * + * Make sure the agent goes away when the parent dies */ + if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0) + _exit(EXIT_FAILURE); -int in_search_path(const char *path, char **search) { - char **i, *parent; - int r; + /* Check whether our parent died before we were able + * to set the death signal */ + if (getppid() != parent_pid) + _exit(EXIT_SUCCESS); - r = parent_of_path(path, &parent); - if (r < 0) - return r; + /* Don't leak fds to the agent */ + close_all_fds(except, n_except); - r = 0; + stdout_is_tty = isatty(STDOUT_FILENO); + stderr_is_tty = isatty(STDERR_FILENO); - STRV_FOREACH(i, search) { - if (path_equal(parent, *i)) { - r = 1; - break; + if (!stdout_is_tty || !stderr_is_tty) { + /* Detach from stdout/stderr. and reopen + * /dev/tty for them. This is important to + * ensure that when systemctl is started via + * popen() or a similar call that expects to + * read EOF we actually do generate EOF and + * not delay this indefinitely by because we + * keep an unused copy of stdin around. */ + fd = open("/dev/tty", O_WRONLY); + if (fd < 0) { + log_error("Failed to open /dev/tty: %m"); + _exit(EXIT_FAILURE); } + + if (!stdout_is_tty) + dup2(fd, STDOUT_FILENO); + + if (!stderr_is_tty) + dup2(fd, STDERR_FILENO); + + if (fd > 2) + close(fd); } - free(parent); + /* Count arguments */ + va_start(ap, path); + for (n = 0; va_arg(ap, char*); n++) + ; + va_end(ap); - return r; + /* Allocate strv */ + l = alloca(sizeof(char *) * (n + 1)); + + /* Fill in arguments */ + va_start(ap, path); + for (i = 0; i <= n; i++) + l[i] = va_arg(ap, char*); + va_end(ap); + + execv(path, l); + _exit(EXIT_FAILURE); } -int get_files_in_directory(const char *path, char ***list) { - DIR *d; - int r = 0; - unsigned n = 0; - char **l = NULL; +int setrlimit_closest(int resource, const struct rlimit *rlim) { + struct rlimit highest, fixed; - assert(path); + assert(rlim); - /* Returns all files in a directory in *list, and the number - * of files as return value. If list is NULL returns only the - * number */ + if (setrlimit(resource, rlim) >= 0) + return 0; - d = opendir(path); - if (!d) + if (errno != EPERM) return -errno; - for (;;) { - struct dirent buffer, *de; - int k; + /* So we failed to set the desired setrlimit, then let's try + * to get as close as we can */ + assert_se(getrlimit(resource, &highest) == 0); - k = readdir_r(d, &buffer, &de); - if (k != 0) { - r = -k; - goto finish; - } + fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max); + fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max); - if (!de) - break; + if (setrlimit(resource, &fixed) < 0) + return -errno; - dirent_ensure_type(d, de); + return 0; +} - if (!dirent_is_file(de)) - continue; +int getenv_for_pid(pid_t pid, const char *field, char **_value) { + char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL; + int r; + FILE *f; + bool done = false; + size_t l; - if (list) { - if ((unsigned) r >= n) { - char **t; + assert(field); + assert(_value); - n = MAX(16, 2*r); - t = realloc(l, sizeof(char*) * n); - if (!t) { - r = -ENOMEM; - goto finish; - } + if (pid == 0) + pid = getpid(); - l = t; - } + snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid); + char_array_0(path); - assert((unsigned) r < n); + f = fopen(path, "re"); + if (!f) + return -errno; - l[r] = strdup(de->d_name); - if (!l[r]) { + l = strlen(field); + r = 0; + + do { + char line[LINE_MAX]; + unsigned i; + + for (i = 0; i < sizeof(line)-1; i++) { + int c; + + c = getc(f); + if (_unlikely_(c == EOF)) { + done = true; + break; + } else if (c == 0) + break; + + line[i] = c; + } + line[i] = 0; + + if (memcmp(line, field, l) == 0 && line[l] == '=') { + value = strdup(line + l + 1); + if (!value) { r = -ENOMEM; - goto finish; + break; } - l[++r] = NULL; - } else - r++; - } + r = 1; + break; + } -finish: - if (d) - closedir(d); + } while (!done); - if (r >= 0) { - if (list) - *list = l; - } else - strv_free(l); + fclose(f); + + if (r >= 0) + *_value = value; return r; } -char *join(const char *x, ...) { - va_list ap; - size_t l; - char *r, *p; - - va_start(ap, x); - - if (x) { - l = strlen(x); +int can_sleep(const char *type) { + char *w, *state; + size_t l, k; + int r; + _cleanup_free_ char *p = NULL; - for (;;) { - const char *t; + assert(type); - t = va_arg(ap, const char *); - if (!t) - break; + /* If /sys is read-only we cannot sleep */ + if (access("/sys/power/state", W_OK) < 0) + return false; - l += strlen(t); - } - } else - l = 0; + r = read_one_line_file("/sys/power/state", &p); + if (r < 0) + return false; - va_end(ap); + k = strlen(type); + FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) + if (l == k && memcmp(w, type, l) == 0) + return true; - r = new(char, l+1); - if (!r) - return NULL; + return false; +} - if (x) { - p = stpcpy(r, x); +int can_sleep_disk(const char *type) { + char *w, *state; + size_t l, k; + int r; + _cleanup_free_ char *p = NULL; - va_start(ap, x); + assert(type); - for (;;) { - const char *t; + /* 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; - t = va_arg(ap, const char *); - if (!t) - break; + r = read_one_line_file("/sys/power/disk", &p); + if (r < 0) + return false; - p = stpcpy(p, t); - } + k = strlen(type); + FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) { + if (l == k && memcmp(w, type, l) == 0) + return true; - va_end(ap); - } else - r[0] = 0; + if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']') + return true; + } - return r; + return false; } -bool is_main_thread(void) { - static __thread int cached = 0; - - if (_unlikely_(cached == 0)) - cached = getpid() == gettid() ? 1 : -1; +bool is_valid_documentation_url(const char *url) { + assert(url); - return cached > 0; -} + if (startswith(url, "http://") && url[7]) + return true; -int block_get_whole_disk(dev_t d, dev_t *ret) { - char *p, *s; - int r; - unsigned n, m; + if (startswith(url, "https://") && url[8]) + return true; - assert(ret); + if (startswith(url, "file:") && url[5]) + return true; - /* If it has a queue this is good enough for us */ - if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0) - return -ENOMEM; + if (startswith(url, "info:") && url[5]) + return true; - r = access(p, F_OK); - free(p); + if (startswith(url, "man:") && url[4]) + return true; - if (r >= 0) { - *ret = d; - return 0; - } + return false; +} - /* If it is a partition find the originating device */ - if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0) - return -ENOMEM; +bool in_initrd(void) { + static __thread int saved = -1; + struct statfs s; - r = access(p, F_OK); - free(p); + if (saved >= 0) + return saved; - if (r < 0) - return -ENOENT; + /* We make two checks here: + * + * 1. the flag file /etc/initrd-release must exist + * 2. the root file system must be a memory file system + * + * The second check is extra paranoia, since misdetecting an + * initrd can have bad bad consequences due the initrd + * emptying when transititioning to the main systemd. + */ - /* Get parent dev_t */ - if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0) - return -ENOMEM; + saved = access("/etc/initrd-release", F_OK) >= 0 && + statfs("/", &s) >= 0 && + is_temporary_fs(&s); - r = read_one_line_file(p, &s); - free(p); + return saved; +} - if (r < 0) - return r; +void warn_melody(void) { + _cleanup_close_ int fd = -1; - r = sscanf(s, "%u:%u", &m, &n); - free(s); + fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY); + if (fd < 0) + return; - if (r != 2) - return -EINVAL; + /* Yeah, this is synchronous. Kinda sucks. But well... */ - /* Only return this if it is really good enough for us. */ - if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0) - return -ENOMEM; + ioctl(fd, KIOCSOUND, (int)(1193180/440)); + usleep(125*USEC_PER_MSEC); - r = access(p, F_OK); - free(p); + ioctl(fd, KIOCSOUND, (int)(1193180/220)); + usleep(125*USEC_PER_MSEC); - if (r >= 0) { - *ret = makedev(m, n); - return 0; - } + ioctl(fd, KIOCSOUND, (int)(1193180/220)); + usleep(125*USEC_PER_MSEC); - return -ENOENT; + ioctl(fd, KIOCSOUND, 0); } -int file_is_priv_sticky(const char *p) { - struct stat st; +int make_console_stdio(void) { + int fd, r; - assert(p); + /* Make /dev/console the controlling terminal and stdin/stdout/stderr */ - if (lstat(p, &st) < 0) - return -errno; + fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1); + if (fd < 0) { + log_error("Failed to acquire terminal: %s", strerror(-fd)); + return fd; + } - return - (st.st_uid == 0 || st.st_uid == getuid()) && - (st.st_mode & S_ISVTX); + r = make_stdio(fd); + if (r < 0) { + log_error("Failed to duplicate terminal fd: %s", strerror(-r)); + return r; + } + + return 0; } -static const char *const ioprio_class_table[] = { - [IOPRIO_CLASS_NONE] = "none", - [IOPRIO_CLASS_RT] = "realtime", - [IOPRIO_CLASS_BE] = "best-effort", - [IOPRIO_CLASS_IDLE] = "idle" -}; +int get_home_dir(char **_h) { + char *h; + const char *e; + uid_t u; + struct passwd *p; -DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int); + assert(_h); -static const char *const sigchld_code_table[] = { - [CLD_EXITED] = "exited", - [CLD_KILLED] = "killed", - [CLD_DUMPED] = "dumped", - [CLD_TRAPPED] = "trapped", - [CLD_STOPPED] = "stopped", - [CLD_CONTINUED] = "continued", -}; + /* Take the user specified one */ + e = getenv("HOME"); + if (e) { + h = strdup(e); + if (!h) + return -ENOMEM; -DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int); + *_h = h; + return 0; + } -static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = { - [LOG_FAC(LOG_KERN)] = "kern", - [LOG_FAC(LOG_USER)] = "user", - [LOG_FAC(LOG_MAIL)] = "mail", - [LOG_FAC(LOG_DAEMON)] = "daemon", - [LOG_FAC(LOG_AUTH)] = "auth", - [LOG_FAC(LOG_SYSLOG)] = "syslog", - [LOG_FAC(LOG_LPR)] = "lpr", - [LOG_FAC(LOG_NEWS)] = "news", - [LOG_FAC(LOG_UUCP)] = "uucp", - [LOG_FAC(LOG_CRON)] = "cron", - [LOG_FAC(LOG_AUTHPRIV)] = "authpriv", - [LOG_FAC(LOG_FTP)] = "ftp", - [LOG_FAC(LOG_LOCAL0)] = "local0", - [LOG_FAC(LOG_LOCAL1)] = "local1", - [LOG_FAC(LOG_LOCAL2)] = "local2", - [LOG_FAC(LOG_LOCAL3)] = "local3", - [LOG_FAC(LOG_LOCAL4)] = "local4", - [LOG_FAC(LOG_LOCAL5)] = "local5", - [LOG_FAC(LOG_LOCAL6)] = "local6", - [LOG_FAC(LOG_LOCAL7)] = "local7" -}; + /* Hardcode home directory for root to avoid NSS */ + u = getuid(); + if (u == 0) { + h = strdup("/root"); + if (!h) + return -ENOMEM; -DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int); + *_h = h; + return 0; + } -static const char *const log_level_table[] = { - [LOG_EMERG] = "emerg", - [LOG_ALERT] = "alert", - [LOG_CRIT] = "crit", - [LOG_ERR] = "err", - [LOG_WARNING] = "warning", - [LOG_NOTICE] = "notice", - [LOG_INFO] = "info", - [LOG_DEBUG] = "debug" -}; + /* Check the database... */ + errno = 0; + p = getpwuid(u); + if (!p) + return errno ? -errno : -ESRCH; -DEFINE_STRING_TABLE_LOOKUP(log_level, int); + if (!path_is_absolute(p->pw_dir)) + return -EINVAL; -static const char* const sched_policy_table[] = { - [SCHED_OTHER] = "other", - [SCHED_BATCH] = "batch", - [SCHED_IDLE] = "idle", - [SCHED_FIFO] = "fifo", - [SCHED_RR] = "rr" -}; + h = strdup(p->pw_dir); + if (!h) + return -ENOMEM; -DEFINE_STRING_TABLE_LOOKUP(sched_policy, int); + *_h = h; + return 0; +} -static const char* const rlimit_table[] = { - [RLIMIT_CPU] = "LimitCPU", - [RLIMIT_FSIZE] = "LimitFSIZE", - [RLIMIT_DATA] = "LimitDATA", - [RLIMIT_STACK] = "LimitSTACK", - [RLIMIT_CORE] = "LimitCORE", - [RLIMIT_RSS] = "LimitRSS", - [RLIMIT_NOFILE] = "LimitNOFILE", - [RLIMIT_AS] = "LimitAS", - [RLIMIT_NPROC] = "LimitNPROC", - [RLIMIT_MEMLOCK] = "LimitMEMLOCK", - [RLIMIT_LOCKS] = "LimitLOCKS", - [RLIMIT_SIGPENDING] = "LimitSIGPENDING", - [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE", - [RLIMIT_NICE] = "LimitNICE", - [RLIMIT_RTPRIO] = "LimitRTPRIO", - [RLIMIT_RTTIME] = "LimitRTTIME" -}; +int get_shell(char **_sh) { + char *sh; + const char *e; + uid_t u; + struct passwd *p; -DEFINE_STRING_TABLE_LOOKUP(rlimit, int); + assert(_sh); -static const char* const ip_tos_table[] = { - [IPTOS_LOWDELAY] = "low-delay", - [IPTOS_THROUGHPUT] = "throughput", - [IPTOS_RELIABILITY] = "reliability", - [IPTOS_LOWCOST] = "low-cost", -}; + /* Take the user specified one */ + e = getenv("SHELL"); + if (e) { + sh = strdup(e); + if (!sh) + return -ENOMEM; -DEFINE_STRING_TABLE_LOOKUP(ip_tos, int); + *_sh = sh; + return 0; + } -static const char *const __signal_table[] = { - [SIGHUP] = "HUP", - [SIGINT] = "INT", - [SIGQUIT] = "QUIT", - [SIGILL] = "ILL", - [SIGTRAP] = "TRAP", - [SIGABRT] = "ABRT", - [SIGBUS] = "BUS", - [SIGFPE] = "FPE", - [SIGKILL] = "KILL", - [SIGUSR1] = "USR1", - [SIGSEGV] = "SEGV", - [SIGUSR2] = "USR2", - [SIGPIPE] = "PIPE", - [SIGALRM] = "ALRM", - [SIGTERM] = "TERM", -#ifdef SIGSTKFLT - [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */ -#endif - [SIGCHLD] = "CHLD", - [SIGCONT] = "CONT", - [SIGSTOP] = "STOP", - [SIGTSTP] = "TSTP", - [SIGTTIN] = "TTIN", - [SIGTTOU] = "TTOU", - [SIGURG] = "URG", - [SIGXCPU] = "XCPU", - [SIGXFSZ] = "XFSZ", - [SIGVTALRM] = "VTALRM", - [SIGPROF] = "PROF", - [SIGWINCH] = "WINCH", - [SIGIO] = "IO", - [SIGPWR] = "PWR", - [SIGSYS] = "SYS" -}; + /* Hardcode home directory for root to avoid NSS */ + u = getuid(); + if (u == 0) { + sh = strdup("/bin/sh"); + if (!sh) + return -ENOMEM; -DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int); + *_sh = sh; + return 0; + } -const char *signal_to_string(int signo) { - static __thread char buf[12]; - const char *name; + /* Check the database... */ + errno = 0; + p = getpwuid(u); + if (!p) + return errno ? -errno : -ESRCH; - name = __signal_to_string(signo); - if (name) - return name; + if (!path_is_absolute(p->pw_shell)) + return -EINVAL; - if (signo >= SIGRTMIN && signo <= SIGRTMAX) - snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN); - else - snprintf(buf, sizeof(buf) - 1, "%d", signo); - char_array_0(buf); - return buf; + sh = strdup(p->pw_shell); + if (!sh) + return -ENOMEM; + + *_sh = sh; + return 0; } -int signal_from_string(const char *s) { - int signo; - int offset = 0; - unsigned u; +void freep(void *p) { + free(*(void**) p); +} - signo =__signal_from_string(s); - if (signo > 0) - return signo; +void fclosep(FILE **f) { + if (*f) + fclose(*f); +} - if (startswith(s, "RTMIN+")) { - s += 6; - offset = SIGRTMIN; - } - if (safe_atou(s, &u) >= 0) { - signo = (int) u + offset; - if (signo > 0 && signo < _NSIG) - return signo; - } - return -1; +void closep(int *fd) { + if (*fd >= 0) + close_nointr_nofail(*fd); } -bool kexec_loaded(void) { - bool loaded = false; - char *s; +void closedirp(DIR **d) { + if (*d) + closedir(*d); +} - if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) { - if (s[0] == '1') - loaded = true; - free(s); - } - return loaded; +void umaskp(mode_t *u) { + umask(*u); } -int strdup_or_null(const char *a, char **b) { - char *c; +bool filename_is_safe(const char *p) { - assert(b); + if (isempty(p)) + return false; - if (!a) { - *b = NULL; - return 0; - } + if (strchr(p, '/')) + return false; - c = strdup(a); - if (!c) - return -ENOMEM; + if (streq(p, ".")) + return false; - *b = c; - return 0; -} + if (streq(p, "..")) + return false; -int prot_from_flags(int flags) { + if (strlen(p) > FILENAME_MAX) + return false; - switch (flags & O_ACCMODE) { + return true; +} - case O_RDONLY: - return PROT_READ; +bool string_is_safe(const char *p) { + const char *t; - case O_WRONLY: - return PROT_WRITE; + assert(p); - case O_RDWR: - return PROT_READ|PROT_WRITE; + for (t = p; *t; t++) { + if (*t > 0 && *t < ' ') + return false; - default: - return -EINVAL; + if (strchr("\\\"\'", *t)) + return false; } + + return true; } -char *format_bytes(char *buf, size_t l, off_t t) { - unsigned i; +/* 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; - static const struct { - const char *suffix; - off_t factor; - } table[] = { - { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL }, - { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL }, - { "T", 1024ULL*1024ULL*1024ULL*1024ULL }, - { "G", 1024ULL*1024ULL*1024ULL }, - { "M", 1024ULL*1024ULL }, - { "K", 1024ULL }, - }; + 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; +} - for (i = 0; i < ELEMENTSOF(table); i++) { +bool is_locale_utf8(void) { + const char *set; + static int cached_answer = -1; - if (t >= table[i].factor) { - snprintf(buf, l, - "%llu.%llu%s", - (unsigned long long) (t / table[i].factor), - (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL), - table[i].suffix); + if (cached_answer >= 0) + goto out; - goto finish; - } + if (!setlocale(LC_ALL, "")) { + cached_answer = true; + goto out; } - snprintf(buf, l, "%lluB", (unsigned long long) t); + set = nl_langinfo(CODESET); + if (!set) { + cached_answer = true; + goto out; + } -finish: - buf[l-1] = 0; - return buf; + 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_TREE_SPACE] = " ", /* */ + [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */ + }, + /* ASCII fallback */ { + [DRAW_TREE_VERT] = "| ", + [DRAW_TREE_BRANCH] = "|-", + [DRAW_TREE_RIGHT] = "`-", + [DRAW_TREE_SPACE] = " ", + [DRAW_TRIANGULAR_BULLET] = "> ", + } + }; + + return draw_table[!is_locale_utf8()][ch]; } -void* memdup(const void *p, size_t l) { - void *r; +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(p); + assert(text); + assert(old_string); + assert(new_string); - r = malloc(l); + old_len = strlen(old_string); + new_len = strlen(new_string); + + l = strlen(text); + r = new(char, l+1); if (!r) return NULL; - memcpy(r, p, l); - return r; -} + f = text; + t = r; + while (*f) { + char *a; + size_t d, nl; -int fd_inc_sndbuf(int fd, size_t n) { - int r, value; - socklen_t l = sizeof(value); + if (!startswith(f, old_string)) { + *(t++) = *(f++); + continue; + } - r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l); - if (r >= 0 && - l == sizeof(value) && - (size_t) value >= n*2) - return 0; + d = t - r; + nl = l - old_len + new_len; + a = realloc(r, nl + 1); + if (!a) + goto oom; - value = (int) n; - r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)); - if (r < 0) - return -errno; + l = nl; + r = a; + t = r + d; - return 1; + t = stpcpy(t, new_string); + f += old_len; + } + + *t = 0; + return r; + +oom: + free(r); + return NULL; } -int fd_inc_rcvbuf(int fd, size_t n) { - int r, value; - socklen_t l = sizeof(value); +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; - r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l); - if (r >= 0 && - l == sizeof(value) && - (size_t) value >= n*2) - return 0; + assert(ibuf); + assert(*ibuf); - value = (int) n; - r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)); - if (r < 0) - return -errno; + /* Strips ANSI color and replaces TABs by 8 spaces */ - return 1; -} + isz = _isz ? *_isz : strlen(*ibuf); -int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) { - pid_t parent_pid, agent_pid; - int fd; - bool stdout_is_tty, stderr_is_tty; - unsigned n, i; - va_list ap; - char **l; + f = open_memstream(&obuf, &osz); + if (!f) + return NULL; - assert(pid); - assert(path); + for (i = *ibuf; i < *ibuf + isz + 1; i++) { - parent_pid = getpid(); + switch (state) { - /* Spawns a temporary TTY agent, making sure it goes away when - * we go away */ + 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; - agent_pid = fork(); - if (agent_pid < 0) - return -errno; + 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; + } - if (agent_pid != 0) { - *pid = agent_pid; - return 0; - } + break; - /* In the child: - * - * Make sure the agent goes away when the parent dies */ - if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0) - _exit(EXIT_FAILURE); + case STATE_BRACKET: - /* Check whether our parent died before we were able - * to set the death signal */ - if (getppid() != parent_pid) - _exit(EXIT_SUCCESS); + 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; + } + } - /* Don't leak fds to the agent */ - close_all_fds(except, n_except); + if (ferror(f)) { + fclose(f); + free(obuf); + return NULL; + } - stdout_is_tty = isatty(STDOUT_FILENO); - stderr_is_tty = isatty(STDERR_FILENO); + fclose(f); - if (!stdout_is_tty || !stderr_is_tty) { - /* Detach from stdout/stderr. and reopen - * /dev/tty for them. This is important to - * ensure that when systemctl is started via - * popen() or a similar call that expects to - * read EOF we actually do generate EOF and - * not delay this indefinitely by because we - * keep an unused copy of stdin around. */ - fd = open("/dev/tty", O_WRONLY); - if (fd < 0) { - log_error("Failed to open /dev/tty: %m"); - _exit(EXIT_FAILURE); - } + free(*ibuf); + *ibuf = obuf; - if (!stdout_is_tty) - dup2(fd, STDOUT_FILENO); + if (_isz) + *_isz = osz; - if (!stderr_is_tty) - dup2(fd, STDERR_FILENO); + return obuf; +} - if (fd > 2) - close(fd); - } +int on_ac_power(void) { + bool found_offline = false, found_online = false; + _cleanup_closedir_ DIR *d = NULL; - /* Count arguments */ - va_start(ap, path); - for (n = 0; va_arg(ap, char*); n++) - ; - va_end(ap); + d = opendir("/sys/class/power_supply"); + if (!d) + return -errno; - /* Allocate strv */ - l = alloca(sizeof(char *) * (n + 1)); + 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; - /* Fill in arguments */ - va_start(ap, path); - for (i = 0; i <= n; i++) - l[i] = va_arg(ap, char*); - va_end(ap); + k = readdir_r(d, &buf.de, &de); + if (k != 0) + return -k; - execv(path, l); - _exit(EXIT_FAILURE); -} + if (!de) + break; -int setrlimit_closest(int resource, const struct rlimit *rlim) { - struct rlimit highest, fixed; + if (ignore_file(de->d_name)) + continue; - assert(rlim); + device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY); + if (device < 0) { + if (errno == ENOENT || errno == ENOTDIR) + continue; - if (setrlimit(resource, rlim) >= 0) - return 0; + return -errno; + } - if (errno != EPERM) - return -errno; + fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY); + if (fd < 0) { + if (errno == ENOENT) + continue; - /* So we failed to set the desired setrlimit, then let's try - * to get as close as we can */ - assert_se(getrlimit(resource, &highest) == 0); + return -errno; + } - fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max); - fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max); + n = read(fd, contents, sizeof(contents)); + if (n < 0) + return -errno; - if (setrlimit(resource, &fixed) < 0) - return -errno; + if (n != 6 || memcmp(contents, "Mains\n", 6)) + continue; - return 0; -} + close_nointr_nofail(fd); + fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY); + if (fd < 0) { + if (errno == ENOENT) + continue; -int path_is_read_only_fs(const char *path) { - struct statvfs st; + return -errno; + } - assert(path); + n = read(fd, contents, sizeof(contents)); + if (n < 0) + return -errno; - if (statvfs(path, &st) < 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 !!(st.f_flag & ST_RDONLY); + return found_online || !found_offline; }