1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 #include <linux/tiocl.h>
42 #include <sys/inotify.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
49 #include <netinet/ip.h>
53 #include <sys/capability.h>
55 #include <linux/rtc.h>
67 #include "exit-status.h"
71 char **saved_argv = NULL;
73 size_t page_size(void) {
74 static __thread size_t pgsz = 0;
77 if (_likely_(pgsz > 0))
80 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
87 bool streq_ptr(const char *a, const char *b) {
89 /* Like streq(), but tries to make sense of NULL pointers */
100 usec_t now(clockid_t clock_id) {
103 assert_se(clock_gettime(clock_id, &ts) == 0);
105 return timespec_load(&ts);
108 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
111 ts->realtime = now(CLOCK_REALTIME);
112 ts->monotonic = now(CLOCK_MONOTONIC);
117 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
126 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
128 ts->monotonic = now(CLOCK_MONOTONIC);
130 if ((int64_t) ts->monotonic > delta)
131 ts->monotonic -= delta;
139 usec_t timespec_load(const struct timespec *ts) {
143 (usec_t) ts->tv_sec * USEC_PER_SEC +
144 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
147 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
150 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
151 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
156 usec_t timeval_load(const struct timeval *tv) {
160 (usec_t) tv->tv_sec * USEC_PER_SEC +
161 (usec_t) tv->tv_usec;
164 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
167 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
168 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
173 bool endswith(const char *s, const char *postfix) {
180 pl = strlen(postfix);
188 return memcmp(s + sl - pl, postfix, pl) == 0;
191 bool startswith(const char *s, const char *prefix) {
206 return memcmp(s, prefix, pl) == 0;
209 bool startswith_no_case(const char *s, const char *prefix) {
225 for(i = 0; i < pl; ++i) {
226 if (tolower(s[i]) != tolower(prefix[i]))
233 bool first_word(const char *s, const char *word) {
248 if (memcmp(s, word, wl) != 0)
252 strchr(WHITESPACE, s[wl]);
255 int close_nointr(int fd) {
270 void close_nointr_nofail(int fd) {
271 int saved_errno = errno;
273 /* like close_nointr() but cannot fail, and guarantees errno
276 assert_se(close_nointr(fd) == 0);
281 void close_many(const int fds[], unsigned n_fd) {
284 for (i = 0; i < n_fd; i++)
285 close_nointr_nofail(fds[i]);
288 int parse_boolean(const char *v) {
291 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
293 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
299 int parse_pid(const char *s, pid_t* ret_pid) {
300 unsigned long ul = 0;
307 if ((r = safe_atolu(s, &ul)) < 0)
312 if ((unsigned long) pid != ul)
322 int parse_uid(const char *s, uid_t* ret_uid) {
323 unsigned long ul = 0;
330 if ((r = safe_atolu(s, &ul)) < 0)
335 if ((unsigned long) uid != ul)
342 int safe_atou(const char *s, unsigned *ret_u) {
350 l = strtoul(s, &x, 0);
352 if (!x || *x || errno)
353 return errno ? -errno : -EINVAL;
355 if ((unsigned long) (unsigned) l != l)
358 *ret_u = (unsigned) l;
362 int safe_atoi(const char *s, int *ret_i) {
370 l = strtol(s, &x, 0);
372 if (!x || *x || errno)
373 return errno ? -errno : -EINVAL;
375 if ((long) (int) l != l)
382 int safe_atollu(const char *s, long long unsigned *ret_llu) {
384 unsigned long long l;
390 l = strtoull(s, &x, 0);
392 if (!x || *x || errno)
393 return errno ? -errno : -EINVAL;
399 int safe_atolli(const char *s, long long int *ret_lli) {
407 l = strtoll(s, &x, 0);
409 if (!x || *x || errno)
410 return errno ? -errno : -EINVAL;
416 /* Split a string into words. */
417 char *split(const char *c, size_t *l, const char *separator, char **state) {
420 current = *state ? *state : (char*) c;
422 if (!*current || *c == 0)
425 current += strspn(current, separator);
426 *l = strcspn(current, separator);
429 return (char*) current;
432 /* Split a string into words, but consider strings enclosed in '' and
433 * "" as words even if they include spaces. */
434 char *split_quoted(const char *c, size_t *l, char **state) {
436 bool escaped = false;
438 current = *state ? *state : (char*) c;
440 if (!*current || *c == 0)
443 current += strspn(current, WHITESPACE);
445 if (*current == '\'') {
448 for (e = current; *e; e++) {
458 *state = *e == 0 ? e : e+1;
459 } else if (*current == '\"') {
462 for (e = current; *e; e++) {
472 *state = *e == 0 ? e : e+1;
474 for (e = current; *e; e++) {
479 else if (strchr(WHITESPACE, *e))
486 return (char*) current;
489 char **split_path_and_make_absolute(const char *p) {
493 if (!(l = strv_split(p, ":")))
496 if (!strv_path_make_absolute_cwd(l)) {
504 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
507 char fn[PATH_MAX], line[LINE_MAX], *p;
513 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
516 if (!(f = fopen(fn, "re")))
519 if (!(fgets(line, sizeof(line), f))) {
520 r = feof(f) ? -EIO : -errno;
527 /* Let's skip the pid and comm fields. The latter is enclosed
528 * in () but does not escape any () in its value, so let's
529 * skip over it manually */
531 if (!(p = strrchr(line, ')')))
542 if ((long unsigned) (pid_t) ppid != ppid)
545 *_ppid = (pid_t) ppid;
550 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
553 char fn[PATH_MAX], line[LINE_MAX], *p;
558 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
561 if (!(f = fopen(fn, "re")))
564 if (!(fgets(line, sizeof(line), f))) {
565 r = feof(f) ? -EIO : -errno;
572 /* Let's skip the pid and comm fields. The latter is enclosed
573 * in () but does not escape any () in its value, so let's
574 * skip over it manually */
576 if (!(p = strrchr(line, ')')))
597 "%*d " /* priority */
599 "%*d " /* num_threads */
600 "%*d " /* itrealvalue */
601 "%llu " /* starttime */,
608 int write_one_line_file(const char *fn, const char *line) {
615 if (!(f = fopen(fn, "we")))
619 if (fputs(line, f) < 0) {
624 if (!endswith(line, "\n"))
642 int fchmod_umask(int fd, mode_t m) {
647 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
653 int write_one_line_file_atomic(const char *fn, const char *line) {
661 r = fopen_temporary(fn, &f, &p);
665 fchmod_umask(fileno(f), 0644);
668 if (fputs(line, f) < 0) {
673 if (!endswith(line, "\n"))
684 if (rename(p, fn) < 0)
700 int read_one_line_file(const char *fn, char **line) {
703 char t[LINE_MAX], *c;
708 if (!(f = fopen(fn, "re")))
711 if (!(fgets(t, sizeof(t), f))) {
712 r = feof(f) ? -EIO : -errno;
716 if (!(c = strdup(t))) {
731 int read_full_file(const char *fn, char **contents, size_t *size) {
738 if (!(f = fopen(fn, "re")))
741 if (fstat(fileno(f), &st) < 0) {
747 if (st.st_size > 4*1024*1024) {
752 n = st.st_size > 0 ? st.st_size : LINE_MAX;
759 if (!(t = realloc(buf, n+1))) {
765 k = fread(buf + l, 1, n - l, f);
780 if (n > 4*1024*1024) {
804 const char *separator, ...) {
807 char *contents = NULL, *p;
812 if ((r = read_full_file(fname, &contents, NULL)) < 0)
817 const char *key = NULL;
819 p += strspn(p, separator);
820 p += strspn(p, WHITESPACE);
825 if (!strchr(COMMENTS, *p)) {
829 va_start(ap, separator);
830 while ((key = va_arg(ap, char *))) {
834 value = va_arg(ap, char **);
837 if (strncmp(p, key, n) != 0 ||
842 n = strcspn(p, separator);
845 strchr(QUOTES, p[0]) &&
847 v = strndup(p+1, n-2);
858 /* return empty value strings as NULL */
875 p += strcspn(p, separator);
894 if (!(f = fopen(fname, "re")))
898 char l[LINE_MAX], *p, *u;
901 if (!fgets(l, sizeof(l), f)) {
914 if (strchr(COMMENTS, *p))
917 if (!(u = normalize_env_assignment(p))) {
918 log_error("Out of memory");
923 t = strv_append(m, u);
927 log_error("Out of memory");
950 int write_env_file(const char *fname, char **l) {
955 r = fopen_temporary(fname, &f, &p);
959 fchmod_umask(fileno(f), 0644);
975 if (rename(p, fname) < 0)
990 char *truncate_nl(char *s) {
993 s[strcspn(s, NEWLINE)] = 0;
997 int get_process_comm(pid_t pid, char **name) {
1003 r = read_one_line_file("/proc/self/comm", name);
1006 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
1009 r = read_one_line_file(p, name);
1016 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
1023 assert(max_length > 0);
1027 f = fopen("/proc/self/cmdline", "re");
1030 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1040 r = new(char, max_length);
1048 while ((c = getc(f)) != EOF) {
1070 size_t n = MIN(left-1, 3U);
1071 memcpy(k, "...", n);
1078 /* Kernel threads have no argv[] */
1088 h = get_process_comm(pid, &t);
1092 r = join("[", t, "]", NULL);
1103 int get_process_exe(pid_t pid, char **name) {
1109 r = readlink_malloc("/proc/self/exe", name);
1112 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1115 r = readlink_malloc(p, name);
1122 char *strnappend(const char *s, const char *suffix, size_t b) {
1130 return strndup(suffix, b);
1140 if (!(r = new(char, a+b+1)))
1144 memcpy(r+a, suffix, b);
1150 char *strappend(const char *s, const char *suffix) {
1151 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1154 int readlink_malloc(const char *p, char **r) {
1164 if (!(c = new(char, l)))
1167 if ((n = readlink(p, c, l-1)) < 0) {
1173 if ((size_t) n < l-1) {
1184 int readlink_and_make_absolute(const char *p, char **r) {
1191 if ((j = readlink_malloc(p, &target)) < 0)
1194 k = file_in_same_dir(p, target);
1204 int readlink_and_canonicalize(const char *p, char **r) {
1211 j = readlink_and_make_absolute(p, &t);
1215 s = canonicalize_file_name(t);
1222 path_kill_slashes(*r);
1227 int parent_of_path(const char *path, char **_r) {
1228 const char *e, *a = NULL, *b = NULL, *p;
1238 for (e = path; *e; e++) {
1240 if (!slash && *e == '/') {
1244 } else if (slash && *e != '/')
1259 r = strndup(path, p-path);
1269 char *file_name_from_path(const char *p) {
1274 if ((r = strrchr(p, '/')))
1280 bool path_is_absolute(const char *p) {
1286 bool is_path(const char *p) {
1288 return !!strchr(p, '/');
1291 char *path_make_absolute(const char *p, const char *prefix) {
1294 /* Makes every item in the list an absolute path by prepending
1295 * the prefix, if specified and necessary */
1297 if (path_is_absolute(p) || !prefix)
1300 return join(prefix, "/", p, NULL);
1303 char *path_make_absolute_cwd(const char *p) {
1308 /* Similar to path_make_absolute(), but prefixes with the
1309 * current working directory. */
1311 if (path_is_absolute(p))
1314 if (!(cwd = get_current_dir_name()))
1317 r = path_make_absolute(p, cwd);
1323 char **strv_path_make_absolute_cwd(char **l) {
1326 /* Goes through every item in the string list and makes it
1327 * absolute. This works in place and won't rollback any
1328 * changes on failure. */
1330 STRV_FOREACH(s, l) {
1333 if (!(t = path_make_absolute_cwd(*s)))
1343 char **strv_path_canonicalize(char **l) {
1346 bool enomem = false;
1348 if (strv_isempty(l))
1351 /* Goes through every item in the string list and canonicalize
1352 * the path. This works in place and won't rollback any
1353 * changes on failure. */
1355 STRV_FOREACH(s, l) {
1358 t = path_make_absolute_cwd(*s);
1367 u = canonicalize_file_name(t);
1371 if (errno == ENOMEM || !errno)
1388 char **strv_path_remove_empty(char **l) {
1394 for (f = t = l; *f; f++) {
1396 if (dir_is_empty(*f) > 0) {
1408 int reset_all_signal_handlers(void) {
1411 for (sig = 1; sig < _NSIG; sig++) {
1412 struct sigaction sa;
1414 if (sig == SIGKILL || sig == SIGSTOP)
1418 sa.sa_handler = SIG_DFL;
1419 sa.sa_flags = SA_RESTART;
1421 /* On Linux the first two RT signals are reserved by
1422 * glibc, and sigaction() will return EINVAL for them. */
1423 if ((sigaction(sig, &sa, NULL) < 0))
1424 if (errno != EINVAL)
1431 char *strstrip(char *s) {
1434 /* Drops trailing whitespace. Modifies the string in
1435 * place. Returns pointer to first non-space character */
1437 s += strspn(s, WHITESPACE);
1439 for (e = strchr(s, 0); e > s; e --)
1440 if (!strchr(WHITESPACE, e[-1]))
1448 char *delete_chars(char *s, const char *bad) {
1451 /* Drops all whitespace, regardless where in the string */
1453 for (f = s, t = s; *f; f++) {
1454 if (strchr(bad, *f))
1465 bool in_charset(const char *s, const char* charset) {
1471 for (i = s; *i; i++)
1472 if (!strchr(charset, *i))
1478 char *file_in_same_dir(const char *path, const char *filename) {
1485 /* This removes the last component of path and appends
1486 * filename, unless the latter is absolute anyway or the
1489 if (path_is_absolute(filename))
1490 return strdup(filename);
1492 if (!(e = strrchr(path, '/')))
1493 return strdup(filename);
1495 k = strlen(filename);
1496 if (!(r = new(char, e-path+1+k+1)))
1499 memcpy(r, path, e-path+1);
1500 memcpy(r+(e-path)+1, filename, k+1);
1505 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1508 if (label_mkdir(path, mode) >= 0)
1509 if (chmod_and_chown(path, mode, uid, gid) < 0)
1512 if (lstat(path, &st) < 0)
1515 if ((st.st_mode & 0777) != mode ||
1518 !S_ISDIR(st.st_mode)) {
1527 int mkdir_parents(const char *path, mode_t mode) {
1532 /* Creates every parent directory in the path except the last
1535 p = path + strspn(path, "/");
1540 e = p + strcspn(p, "/");
1541 p = e + strspn(e, "/");
1543 /* Is this the last component? If so, then we're
1548 if (!(t = strndup(path, e - path)))
1551 r = label_mkdir(t, mode);
1554 if (r < 0 && errno != EEXIST)
1559 int mkdir_p(const char *path, mode_t mode) {
1564 if ((r = mkdir_parents(path, mode)) < 0)
1567 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1573 int rmdir_parents(const char *path, const char *stop) {
1582 /* Skip trailing slashes */
1583 while (l > 0 && path[l-1] == '/')
1589 /* Skip last component */
1590 while (l > 0 && path[l-1] != '/')
1593 /* Skip trailing slashes */
1594 while (l > 0 && path[l-1] == '/')
1600 if (!(t = strndup(path, l)))
1603 if (path_startswith(stop, t)) {
1612 if (errno != ENOENT)
1620 char hexchar(int x) {
1621 static const char table[16] = "0123456789abcdef";
1623 return table[x & 15];
1626 int unhexchar(char c) {
1628 if (c >= '0' && c <= '9')
1631 if (c >= 'a' && c <= 'f')
1632 return c - 'a' + 10;
1634 if (c >= 'A' && c <= 'F')
1635 return c - 'A' + 10;
1640 char octchar(int x) {
1641 return '0' + (x & 7);
1644 int unoctchar(char c) {
1646 if (c >= '0' && c <= '7')
1652 char decchar(int x) {
1653 return '0' + (x % 10);
1656 int undecchar(char c) {
1658 if (c >= '0' && c <= '9')
1664 char *cescape(const char *s) {
1670 /* Does C style string escaping. */
1672 if (!(r = new(char, strlen(s)*4 + 1)))
1675 for (f = s, t = r; *f; f++)
1721 /* For special chars we prefer octal over
1722 * hexadecimal encoding, simply because glib's
1723 * g_strescape() does the same */
1724 if ((*f < ' ') || (*f >= 127)) {
1726 *(t++) = octchar((unsigned char) *f >> 6);
1727 *(t++) = octchar((unsigned char) *f >> 3);
1728 *(t++) = octchar((unsigned char) *f);
1739 char *cunescape_length(const char *s, size_t length) {
1745 /* Undoes C style string escaping */
1747 if (!(r = new(char, length+1)))
1750 for (f = s, t = r; f < s + length; f++) {
1793 /* This is an extension of the XDG syntax files */
1798 /* hexadecimal encoding */
1801 if ((a = unhexchar(f[1])) < 0 ||
1802 (b = unhexchar(f[2])) < 0) {
1803 /* Invalid escape code, let's take it literal then */
1807 *(t++) = (char) ((a << 4) | b);
1822 /* octal encoding */
1825 if ((a = unoctchar(f[0])) < 0 ||
1826 (b = unoctchar(f[1])) < 0 ||
1827 (c = unoctchar(f[2])) < 0) {
1828 /* Invalid escape code, let's take it literal then */
1832 *(t++) = (char) ((a << 6) | (b << 3) | c);
1840 /* premature end of string.*/
1845 /* Invalid escape code, let's take it literal then */
1857 char *cunescape(const char *s) {
1858 return cunescape_length(s, strlen(s));
1861 char *xescape(const char *s, const char *bad) {
1865 /* Escapes all chars in bad, in addition to \ and all special
1866 * chars, in \xFF style escaping. May be reversed with
1869 if (!(r = new(char, strlen(s)*4+1)))
1872 for (f = s, t = r; *f; f++) {
1874 if ((*f < ' ') || (*f >= 127) ||
1875 (*f == '\\') || strchr(bad, *f)) {
1878 *(t++) = hexchar(*f >> 4);
1879 *(t++) = hexchar(*f);
1889 char *bus_path_escape(const char *s) {
1895 /* Escapes all chars that D-Bus' object path cannot deal
1896 * with. Can be reverse with bus_path_unescape() */
1898 if (!(r = new(char, strlen(s)*3+1)))
1901 for (f = s, t = r; *f; f++) {
1903 if (!(*f >= 'A' && *f <= 'Z') &&
1904 !(*f >= 'a' && *f <= 'z') &&
1905 !(*f >= '0' && *f <= '9')) {
1907 *(t++) = hexchar(*f >> 4);
1908 *(t++) = hexchar(*f);
1918 char *bus_path_unescape(const char *f) {
1923 if (!(r = strdup(f)))
1926 for (t = r; *f; f++) {
1931 if ((a = unhexchar(f[1])) < 0 ||
1932 (b = unhexchar(f[2])) < 0) {
1933 /* Invalid escape code, let's take it literal then */
1936 *(t++) = (char) ((a << 4) | b);
1948 char *path_kill_slashes(char *path) {
1952 /* Removes redundant inner and trailing slashes. Modifies the
1953 * passed string in-place.
1955 * ///foo///bar/ becomes /foo/bar
1958 for (f = path, t = path; *f; f++) {
1973 /* Special rule, if we are talking of the root directory, a
1974 trailing slash is good */
1976 if (t == path && slash)
1983 bool path_startswith(const char *path, const char *prefix) {
1987 if ((path[0] == '/') != (prefix[0] == '/'))
1993 path += strspn(path, "/");
1994 prefix += strspn(prefix, "/");
2002 a = strcspn(path, "/");
2003 b = strcspn(prefix, "/");
2008 if (memcmp(path, prefix, a) != 0)
2016 bool path_equal(const char *a, const char *b) {
2020 if ((a[0] == '/') != (b[0] == '/'))
2026 a += strspn(a, "/");
2027 b += strspn(b, "/");
2029 if (*a == 0 && *b == 0)
2032 if (*a == 0 || *b == 0)
2035 j = strcspn(a, "/");
2036 k = strcspn(b, "/");
2041 if (memcmp(a, b, j) != 0)
2049 char *ascii_strlower(char *t) {
2054 for (p = t; *p; p++)
2055 if (*p >= 'A' && *p <= 'Z')
2056 *p = *p - 'A' + 'a';
2061 bool ignore_file(const char *filename) {
2065 filename[0] == '.' ||
2066 streq(filename, "lost+found") ||
2067 streq(filename, "aquota.user") ||
2068 streq(filename, "aquota.group") ||
2069 endswith(filename, "~") ||
2070 endswith(filename, ".rpmnew") ||
2071 endswith(filename, ".rpmsave") ||
2072 endswith(filename, ".rpmorig") ||
2073 endswith(filename, ".dpkg-old") ||
2074 endswith(filename, ".dpkg-new") ||
2075 endswith(filename, ".swp");
2078 int fd_nonblock(int fd, bool nonblock) {
2083 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2087 flags |= O_NONBLOCK;
2089 flags &= ~O_NONBLOCK;
2091 if (fcntl(fd, F_SETFL, flags) < 0)
2097 int fd_cloexec(int fd, bool cloexec) {
2102 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2106 flags |= FD_CLOEXEC;
2108 flags &= ~FD_CLOEXEC;
2110 if (fcntl(fd, F_SETFD, flags) < 0)
2116 int close_all_fds(const int except[], unsigned n_except) {
2121 if (!(d = opendir("/proc/self/fd")))
2124 while ((de = readdir(d))) {
2127 if (ignore_file(de->d_name))
2130 if (safe_atoi(de->d_name, &fd) < 0)
2131 /* Let's better ignore this, just in case */
2145 for (i = 0; i < n_except; i++)
2146 if (except[i] == fd) {
2155 if (close_nointr(fd) < 0) {
2156 /* Valgrind has its own FD and doesn't want to have it closed */
2157 if (errno != EBADF && r == 0)
2166 bool chars_intersect(const char *a, const char *b) {
2169 /* Returns true if any of the chars in a are in b. */
2170 for (p = a; *p; p++)
2177 char *format_timestamp(char *buf, size_t l, usec_t t) {
2187 sec = (time_t) (t / USEC_PER_SEC);
2189 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2195 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2198 n = now(CLOCK_REALTIME);
2200 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2205 if (d >= USEC_PER_YEAR)
2206 snprintf(buf, l, "%llu years and %llu months ago",
2207 (unsigned long long) (d / USEC_PER_YEAR),
2208 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2209 else if (d >= USEC_PER_MONTH)
2210 snprintf(buf, l, "%llu months and %llu days ago",
2211 (unsigned long long) (d / USEC_PER_MONTH),
2212 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2213 else if (d >= USEC_PER_WEEK)
2214 snprintf(buf, l, "%llu weeks and %llu days ago",
2215 (unsigned long long) (d / USEC_PER_WEEK),
2216 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2217 else if (d >= 2*USEC_PER_DAY)
2218 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2219 else if (d >= 25*USEC_PER_HOUR)
2220 snprintf(buf, l, "1 day and %lluh ago",
2221 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2222 else if (d >= 6*USEC_PER_HOUR)
2223 snprintf(buf, l, "%lluh ago",
2224 (unsigned long long) (d / USEC_PER_HOUR));
2225 else if (d >= USEC_PER_HOUR)
2226 snprintf(buf, l, "%lluh %llumin ago",
2227 (unsigned long long) (d / USEC_PER_HOUR),
2228 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2229 else if (d >= 5*USEC_PER_MINUTE)
2230 snprintf(buf, l, "%llumin ago",
2231 (unsigned long long) (d / USEC_PER_MINUTE));
2232 else if (d >= USEC_PER_MINUTE)
2233 snprintf(buf, l, "%llumin %llus ago",
2234 (unsigned long long) (d / USEC_PER_MINUTE),
2235 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2236 else if (d >= USEC_PER_SEC)
2237 snprintf(buf, l, "%llus ago",
2238 (unsigned long long) (d / USEC_PER_SEC));
2239 else if (d >= USEC_PER_MSEC)
2240 snprintf(buf, l, "%llums ago",
2241 (unsigned long long) (d / USEC_PER_MSEC));
2243 snprintf(buf, l, "%lluus ago",
2244 (unsigned long long) d);
2246 snprintf(buf, l, "now");
2252 char *format_timespan(char *buf, size_t l, usec_t t) {
2253 static const struct {
2257 { "w", USEC_PER_WEEK },
2258 { "d", USEC_PER_DAY },
2259 { "h", USEC_PER_HOUR },
2260 { "min", USEC_PER_MINUTE },
2261 { "s", USEC_PER_SEC },
2262 { "ms", USEC_PER_MSEC },
2272 if (t == (usec_t) -1)
2276 snprintf(p, l, "0");
2281 /* The result of this function can be parsed with parse_usec */
2283 for (i = 0; i < ELEMENTSOF(table); i++) {
2287 if (t < table[i].usec)
2293 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2294 n = MIN((size_t) k, l);
2307 bool fstype_is_network(const char *fstype) {
2308 static const char * const table[] = {
2320 for (i = 0; i < ELEMENTSOF(table); i++)
2321 if (streq(table[i], fstype))
2330 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2335 TIOCL_GETKMSGREDIRECT,
2339 if (ioctl(fd, TIOCLINUX, tiocl) < 0) {
2344 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2347 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2351 close_nointr_nofail(fd);
2355 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2356 struct termios old_termios, new_termios;
2358 char line[LINE_MAX];
2363 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2364 new_termios = old_termios;
2366 new_termios.c_lflag &= ~ICANON;
2367 new_termios.c_cc[VMIN] = 1;
2368 new_termios.c_cc[VTIME] = 0;
2370 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2373 k = fread(&c, 1, 1, f);
2375 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2381 *need_nl = c != '\n';
2388 if (!(fgets(line, sizeof(line), f)))
2393 if (strlen(line) != 1)
2403 int ask(char *ret, const char *replies, const char *text, ...) {
2410 on_tty = isatty(STDOUT_FILENO);
2416 bool need_nl = true;
2419 fputs("\x1B[1m", stdout);
2426 fputs("\x1B[0m", stdout);
2430 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2432 if (r == -EBADMSG) {
2433 puts("Bad input, please try again.");
2444 if (strchr(replies, c)) {
2449 puts("Read unexpected character, please try again.");
2453 int reset_terminal_fd(int fd) {
2454 struct termios termios;
2457 /* Set terminal to some sane defaults */
2461 /* We leave locked terminal attributes untouched, so that
2462 * Plymouth may set whatever it wants to set, and we don't
2463 * interfere with that. */
2465 /* Disable exclusive mode, just in case */
2466 ioctl(fd, TIOCNXCL);
2468 /* Switch to text mode */
2469 ioctl(fd, KDSETMODE, KD_TEXT);
2471 /* Enable console unicode mode */
2472 ioctl(fd, KDSKBMODE, K_UNICODE);
2474 if (tcgetattr(fd, &termios) < 0) {
2479 /* We only reset the stuff that matters to the software. How
2480 * hardware is set up we don't touch assuming that somebody
2481 * else will do that for us */
2483 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2484 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2485 termios.c_oflag |= ONLCR;
2486 termios.c_cflag |= CREAD;
2487 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2489 termios.c_cc[VINTR] = 03; /* ^C */
2490 termios.c_cc[VQUIT] = 034; /* ^\ */
2491 termios.c_cc[VERASE] = 0177;
2492 termios.c_cc[VKILL] = 025; /* ^X */
2493 termios.c_cc[VEOF] = 04; /* ^D */
2494 termios.c_cc[VSTART] = 021; /* ^Q */
2495 termios.c_cc[VSTOP] = 023; /* ^S */
2496 termios.c_cc[VSUSP] = 032; /* ^Z */
2497 termios.c_cc[VLNEXT] = 026; /* ^V */
2498 termios.c_cc[VWERASE] = 027; /* ^W */
2499 termios.c_cc[VREPRINT] = 022; /* ^R */
2500 termios.c_cc[VEOL] = 0;
2501 termios.c_cc[VEOL2] = 0;
2503 termios.c_cc[VTIME] = 0;
2504 termios.c_cc[VMIN] = 1;
2506 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2510 /* Just in case, flush all crap out */
2511 tcflush(fd, TCIOFLUSH);
2516 int reset_terminal(const char *name) {
2519 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2523 r = reset_terminal_fd(fd);
2524 close_nointr_nofail(fd);
2529 int open_terminal(const char *name, int mode) {
2534 * If a TTY is in the process of being closed opening it might
2535 * cause EIO. This is horribly awful, but unlikely to be
2536 * changed in the kernel. Hence we work around this problem by
2537 * retrying a couple of times.
2539 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2543 if ((fd = open(name, mode)) >= 0)
2552 usleep(50 * USEC_PER_MSEC);
2559 if ((r = isatty(fd)) < 0) {
2560 close_nointr_nofail(fd);
2565 close_nointr_nofail(fd);
2572 int flush_fd(int fd) {
2573 struct pollfd pollfd;
2577 pollfd.events = POLLIN;
2584 if ((r = poll(&pollfd, 1, 0)) < 0) {
2595 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2600 if (errno == EAGAIN)
2611 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2612 int fd = -1, notify = -1, r, wd = -1;
2616 /* We use inotify to be notified when the tty is closed. We
2617 * create the watch before checking if we can actually acquire
2618 * it, so that we don't lose any event.
2620 * Note: strictly speaking this actually watches for the
2621 * device being closed, it does *not* really watch whether a
2622 * tty loses its controlling process. However, unless some
2623 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2624 * its tty otherwise this will not become a problem. As long
2625 * as the administrator makes sure not configure any service
2626 * on the same tty as an untrusted user this should not be a
2627 * problem. (Which he probably should not do anyway.) */
2629 if (!fail && !force) {
2630 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2635 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2643 if ((r = flush_fd(notify)) < 0)
2646 /* We pass here O_NOCTTY only so that we can check the return
2647 * value TIOCSCTTY and have a reliable way to figure out if we
2648 * successfully became the controlling process of the tty */
2649 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2652 /* First, try to get the tty */
2653 r = ioctl(fd, TIOCSCTTY, force);
2655 /* Sometimes it makes sense to ignore TIOCSCTTY
2656 * returning EPERM, i.e. when very likely we already
2657 * are have this controlling terminal. */
2658 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2661 if (r < 0 && (force || fail || errno != EPERM)) {
2671 assert(notify >= 0);
2674 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2676 struct inotify_event *e;
2678 if ((l = read(notify, inotify_buffer, sizeof(inotify_buffer))) < 0) {
2687 e = (struct inotify_event*) inotify_buffer;
2692 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2697 step = sizeof(struct inotify_event) + e->len;
2698 assert(step <= (size_t) l);
2700 e = (struct inotify_event*) ((uint8_t*) e + step);
2707 /* We close the tty fd here since if the old session
2708 * ended our handle will be dead. It's important that
2709 * we do this after sleeping, so that we don't enter
2710 * an endless loop. */
2711 close_nointr_nofail(fd);
2715 close_nointr_nofail(notify);
2717 if ((r = reset_terminal_fd(fd)) < 0)
2718 log_warning("Failed to reset terminal: %s", strerror(-r));
2724 close_nointr_nofail(fd);
2727 close_nointr_nofail(notify);
2732 int release_terminal(void) {
2734 struct sigaction sa_old, sa_new;
2736 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2739 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2740 * by our own TIOCNOTTY */
2743 sa_new.sa_handler = SIG_IGN;
2744 sa_new.sa_flags = SA_RESTART;
2745 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2747 if (ioctl(fd, TIOCNOTTY) < 0)
2750 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2752 close_nointr_nofail(fd);
2756 int sigaction_many(const struct sigaction *sa, ...) {
2761 while ((sig = va_arg(ap, int)) > 0)
2762 if (sigaction(sig, sa, NULL) < 0)
2769 int ignore_signals(int sig, ...) {
2770 struct sigaction sa;
2775 sa.sa_handler = SIG_IGN;
2776 sa.sa_flags = SA_RESTART;
2778 if (sigaction(sig, &sa, NULL) < 0)
2782 while ((sig = va_arg(ap, int)) > 0)
2783 if (sigaction(sig, &sa, NULL) < 0)
2790 int default_signals(int sig, ...) {
2791 struct sigaction sa;
2796 sa.sa_handler = SIG_DFL;
2797 sa.sa_flags = SA_RESTART;
2799 if (sigaction(sig, &sa, NULL) < 0)
2803 while ((sig = va_arg(ap, int)) > 0)
2804 if (sigaction(sig, &sa, NULL) < 0)
2811 int close_pipe(int p[]) {
2817 a = close_nointr(p[0]);
2822 b = close_nointr(p[1]);
2826 return a < 0 ? a : b;
2829 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2838 while (nbytes > 0) {
2841 if ((k = read(fd, p, nbytes)) <= 0) {
2843 if (k < 0 && errno == EINTR)
2846 if (k < 0 && errno == EAGAIN && do_poll) {
2847 struct pollfd pollfd;
2851 pollfd.events = POLLIN;
2853 if (poll(&pollfd, 1, -1) < 0) {
2857 return n > 0 ? n : -errno;
2860 if (pollfd.revents != POLLIN)
2861 return n > 0 ? n : -EIO;
2866 return n > 0 ? n : (k < 0 ? -errno : 0);
2877 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2886 while (nbytes > 0) {
2889 k = write(fd, p, nbytes);
2892 if (k < 0 && errno == EINTR)
2895 if (k < 0 && errno == EAGAIN && do_poll) {
2896 struct pollfd pollfd;
2900 pollfd.events = POLLOUT;
2902 if (poll(&pollfd, 1, -1) < 0) {
2906 return n > 0 ? n : -errno;
2909 if (pollfd.revents != POLLOUT)
2910 return n > 0 ? n : -EIO;
2915 return n > 0 ? n : (k < 0 ? -errno : 0);
2926 int path_is_mount_point(const char *t, bool allow_symlink) {
2937 if (errno == ENOENT)
2943 r = parent_of_path(t, &parent);
2947 r = lstat(parent, &b);
2953 return a.st_dev != b.st_dev;
2956 int parse_usec(const char *t, usec_t *usec) {
2957 static const struct {
2961 { "sec", USEC_PER_SEC },
2962 { "s", USEC_PER_SEC },
2963 { "min", USEC_PER_MINUTE },
2964 { "hr", USEC_PER_HOUR },
2965 { "h", USEC_PER_HOUR },
2966 { "d", USEC_PER_DAY },
2967 { "w", USEC_PER_WEEK },
2968 { "msec", USEC_PER_MSEC },
2969 { "ms", USEC_PER_MSEC },
2970 { "m", USEC_PER_MINUTE },
2973 { "", USEC_PER_SEC },
2989 l = strtoll(p, &e, 10);
3000 e += strspn(e, WHITESPACE);
3002 for (i = 0; i < ELEMENTSOF(table); i++)
3003 if (startswith(e, table[i].suffix)) {
3004 r += (usec_t) l * table[i].usec;
3005 p = e + strlen(table[i].suffix);
3009 if (i >= ELEMENTSOF(table))
3019 int parse_bytes(const char *t, off_t *bytes) {
3020 static const struct {
3026 { "M", 1024ULL*1024ULL },
3027 { "G", 1024ULL*1024ULL*1024ULL },
3028 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3045 l = strtoll(p, &e, 10);
3056 e += strspn(e, WHITESPACE);
3058 for (i = 0; i < ELEMENTSOF(table); i++)
3059 if (startswith(e, table[i].suffix)) {
3060 r += (off_t) l * table[i].factor;
3061 p = e + strlen(table[i].suffix);
3065 if (i >= ELEMENTSOF(table))
3075 int make_stdio(int fd) {
3080 r = dup2(fd, STDIN_FILENO);
3081 s = dup2(fd, STDOUT_FILENO);
3082 t = dup2(fd, STDERR_FILENO);
3085 close_nointr_nofail(fd);
3087 if (r < 0 || s < 0 || t < 0)
3090 fd_cloexec(STDIN_FILENO, false);
3091 fd_cloexec(STDOUT_FILENO, false);
3092 fd_cloexec(STDERR_FILENO, false);
3097 int make_null_stdio(void) {
3100 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3103 return make_stdio(null_fd);
3106 bool is_device_path(const char *path) {
3108 /* Returns true on paths that refer to a device, either in
3109 * sysfs or in /dev */
3112 path_startswith(path, "/dev/") ||
3113 path_startswith(path, "/sys/");
3116 int dir_is_empty(const char *path) {
3119 struct dirent buf, *de;
3121 if (!(d = opendir(path)))
3125 if ((r = readdir_r(d, &buf, &de)) > 0) {
3135 if (!ignore_file(de->d_name)) {
3145 unsigned long long random_ull(void) {
3150 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3153 r = loop_read(fd, &ull, sizeof(ull), true);
3154 close_nointr_nofail(fd);
3156 if (r != sizeof(ull))
3162 return random() * RAND_MAX + random();
3165 void rename_process(const char name[8]) {
3168 prctl(PR_SET_NAME, name);
3170 /* This is a like a poor man's setproctitle(). The string
3171 * passed should fit in 7 chars (i.e. the length of
3174 if (program_invocation_name)
3175 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3177 if (saved_argc > 0) {
3181 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3183 for (i = 1; i < saved_argc; i++) {
3187 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3192 void sigset_add_many(sigset_t *ss, ...) {
3199 while ((sig = va_arg(ap, int)) > 0)
3200 assert_se(sigaddset(ss, sig) == 0);
3204 char* gethostname_malloc(void) {
3207 assert_se(uname(&u) >= 0);
3210 return strdup(u.nodename);
3212 return strdup(u.sysname);
3215 char* getlogname_malloc(void) {
3219 struct passwd pwbuf, *pw = NULL;
3222 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3227 /* Shortcut things to avoid NSS lookups */
3229 return strdup("root");
3231 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3234 if (!(buf = malloc(bufsize)))
3237 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3238 name = strdup(pw->pw_name);
3245 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3251 int getttyname_malloc(int fd, char **r) {
3252 char path[PATH_MAX], *c;
3257 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3262 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3269 int getttyname_harder(int fd, char **r) {
3273 if ((k = getttyname_malloc(fd, &s)) < 0)
3276 if (streq(s, "tty")) {
3278 return get_ctty(0, NULL, r);
3285 int get_ctty_devnr(pid_t pid, dev_t *d) {
3287 char line[LINE_MAX], *p, *fn;
3288 unsigned long ttynr;
3291 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3294 f = fopen(fn, "re");
3299 if (!fgets(line, sizeof(line), f)) {
3300 k = feof(f) ? -EIO : -errno;
3307 p = strrchr(line, ')');
3317 "%*d " /* session */
3326 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3328 char fn[PATH_MAX], *s, *b, *p;
3333 k = get_ctty_devnr(pid, &devnr);
3337 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3340 if ((k = readlink_malloc(fn, &s)) < 0) {
3345 /* This is an ugly hack */
3346 if (major(devnr) == 136) {
3347 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3357 /* Probably something like the ptys which have no
3358 * symlink in /dev/char. Let's return something
3359 * vaguely useful. */
3361 if (!(b = strdup(fn + 5)))
3371 if (startswith(s, "/dev/"))
3373 else if (startswith(s, "../"))
3391 static int rm_rf_children(int fd, bool only_dirs, bool honour_sticky) {
3397 /* This returns the first error we run into, but nevertheless
3400 if (!(d = fdopendir(fd))) {
3401 close_nointr_nofail(fd);
3403 return errno == ENOENT ? 0 : -errno;
3407 struct dirent buf, *de;
3408 bool is_dir, keep_around = false;
3411 if ((r = readdir_r(d, &buf, &de)) != 0) {
3420 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3423 if (de->d_type == DT_UNKNOWN) {
3426 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3427 if (ret == 0 && errno != ENOENT)
3433 keep_around = st.st_uid == 0 && (st.st_mode & S_ISVTX);
3435 is_dir = S_ISDIR(st.st_mode);
3438 if (honour_sticky) {
3441 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3442 if (ret == 0 && errno != ENOENT)
3447 keep_around = st.st_uid == 0 && (st.st_mode & S_ISVTX);
3450 is_dir = de->d_type == DT_DIR;
3456 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3457 if (ret == 0 && errno != ENOENT)
3462 if ((r = rm_rf_children(subdir_fd, only_dirs, honour_sticky)) < 0) {
3468 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3469 if (ret == 0 && errno != ENOENT)
3473 } else if (!only_dirs && !keep_around) {
3475 if (unlinkat(fd, de->d_name, 0) < 0) {
3476 if (ret == 0 && errno != ENOENT)
3487 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3493 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3495 if (errno != ENOTDIR)
3498 if (delete_root && !only_dirs)
3499 if (unlink(path) < 0)
3505 r = rm_rf_children(fd, only_dirs, honour_sticky);
3509 if (honour_sticky && file_is_sticky(path) > 0)
3512 if (rmdir(path) < 0 && errno != ENOENT) {
3521 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3524 /* Under the assumption that we are running privileged we
3525 * first change the access mode and only then hand out
3526 * ownership to avoid a window where access is too open. */
3528 if (chmod(path, mode) < 0)
3531 if (chown(path, uid, gid) < 0)
3537 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3540 /* Under the assumption that we are running privileged we
3541 * first change the access mode and only then hand out
3542 * ownership to avoid a window where access is too open. */
3544 if (fchmod(fd, mode) < 0)
3547 if (fchown(fd, uid, gid) < 0)
3553 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3557 /* Allocates the cpuset in the right size */
3560 if (!(r = CPU_ALLOC(n)))
3563 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3564 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3574 if (errno != EINVAL)
3581 void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3582 char *s = NULL, *spaces = NULL, *e;
3584 size_t emax, sl, left;
3585 struct iovec iovec[5];
3590 /* This independent of logging, as status messages are
3591 * optional and go exclusively to the console. */
3593 if (vasprintf(&s, format, ap) < 0)
3596 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3606 sl = 2 + 6 + 1; /* " [" status "]" */
3607 emax = (size_t) c > sl ? c - sl - 1 : 0;
3611 e = ellipsize(s, emax, 75);
3619 IOVEC_SET_STRING(iovec[n++], s);
3623 left = emax > sl ? emax - sl : 0;
3625 spaces = malloc(left);
3627 memset(spaces, ' ', left);
3628 iovec[n].iov_base = spaces;
3629 iovec[n].iov_len = left;
3636 IOVEC_SET_STRING(iovec[n++], " [");
3637 IOVEC_SET_STRING(iovec[n++], status);
3638 IOVEC_SET_STRING(iovec[n++], "]\n");
3640 IOVEC_SET_STRING(iovec[n++], "\n");
3642 writev(fd, iovec, n);
3649 close_nointr_nofail(fd);
3652 void status_printf(const char *status, bool ellipse, const char *format, ...) {
3657 va_start(ap, format);
3658 status_vprintf(status, ellipse, format, ap);
3662 void status_welcome(void) {
3663 char *pretty_name = NULL, *ansi_color = NULL;
3664 const char *const_pretty = NULL, *const_color = NULL;
3667 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3668 "PRETTY_NAME", &pretty_name,
3669 "ANSI_COLOR", &ansi_color,
3673 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3676 #if defined(TARGET_FEDORA)
3678 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3681 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3685 if (!ansi_color && pretty_name) {
3687 /* This tries to mimic the color magic the old Red Hat sysinit
3690 if (startswith(pretty_name, "Red Hat"))
3691 const_color = "0;31"; /* Red for RHEL */
3692 else if (startswith(pretty_name, "Fedora"))
3693 const_color = "0;34"; /* Blue for Fedora */
3696 #elif defined(TARGET_SUSE)
3699 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3702 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3707 const_color = "0;32"; /* Green for openSUSE */
3709 #elif defined(TARGET_GENTOO)
3712 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3715 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3720 const_color = "1;34"; /* Light Blue for Gentoo */
3722 #elif defined(TARGET_ALTLINUX)
3725 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3728 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3733 const_color = "0;36"; /* Cyan for ALTLinux */
3736 #elif defined(TARGET_DEBIAN)
3741 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3744 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3746 pretty_name = strappend("Debian ", version);
3750 log_warning("Failed to allocate Debian version string.");
3755 const_color = "1;31"; /* Light Red for Debian */
3757 #elif defined(TARGET_UBUNTU)
3759 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3760 "DISTRIB_DESCRIPTION", &pretty_name,
3764 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3768 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3770 #elif defined(TARGET_MANDRIVA)
3775 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3777 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3779 p = strstr(s, " release ");
3783 p[strcspn(p, " ")] = '\0';
3785 /* This corresponds to standard rc.sysinit */
3786 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3787 const_color = "1;36";
3789 log_warning("Failed to allocate Mandriva version string.");
3791 log_warning("Failed to parse /etc/mandriva-release");
3795 #elif defined(TARGET_MEEGO)
3798 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3801 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3806 const_color = "1;35"; /* Bright Magenta for MeeGo */
3809 if (!pretty_name && !const_pretty)
3810 const_pretty = "Linux";
3812 if (!ansi_color && !const_color)
3817 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3818 const_color ? const_color : ansi_color,
3819 const_pretty ? const_pretty : pretty_name);
3825 char *replace_env(const char *format, char **env) {
3832 const char *e, *word = format;
3837 for (e = format; *e; e ++) {
3848 if (!(k = strnappend(r, word, e-word-1)))
3857 } else if (*e == '$') {
3858 if (!(k = strnappend(r, word, e-word)))
3874 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3877 if (!(k = strappend(r, t)))
3890 if (!(k = strnappend(r, word, e-word)))
3901 char **replace_env_argv(char **argv, char **env) {
3903 unsigned k = 0, l = 0;
3905 l = strv_length(argv);
3907 if (!(r = new(char*, l+1)))
3910 STRV_FOREACH(i, argv) {
3912 /* If $FOO appears as single word, replace it by the split up variable */
3913 if ((*i)[0] == '$' && (*i)[1] != '{') {
3918 if ((e = strv_env_get(env, *i+1))) {
3920 if (!(m = strv_split_quoted(e))) {
3931 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3940 memcpy(r + k, m, q * sizeof(char*));
3948 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3949 if (!(r[k++] = replace_env(*i, env))) {
3959 int fd_columns(int fd) {
3963 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3972 unsigned columns(void) {
3973 static __thread int parsed_columns = 0;
3976 if (_likely_(parsed_columns > 0))
3977 return parsed_columns;
3979 e = getenv("COLUMNS");
3981 parsed_columns = atoi(e);
3983 if (parsed_columns <= 0)
3984 parsed_columns = fd_columns(STDOUT_FILENO);
3986 if (parsed_columns <= 0)
3987 parsed_columns = 80;
3989 return parsed_columns;
3992 int running_in_chroot(void) {
3998 /* Only works as root */
4000 if (stat("/proc/1/root", &a) < 0)
4003 if (stat("/", &b) < 0)
4007 a.st_dev != b.st_dev ||
4008 a.st_ino != b.st_ino;
4011 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
4016 assert(percent <= 100);
4017 assert(new_length >= 3);
4019 if (old_length <= 3 || old_length <= new_length)
4020 return strndup(s, old_length);
4022 r = new0(char, new_length+1);
4026 x = (new_length * percent) / 100;
4028 if (x > new_length - 3)
4036 s + old_length - (new_length - x - 3),
4037 new_length - x - 3);
4042 char *ellipsize(const char *s, size_t length, unsigned percent) {
4043 return ellipsize_mem(s, strlen(s), length, percent);
4046 int touch(const char *path) {
4051 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
4054 close_nointr_nofail(fd);
4058 char *unquote(const char *s, const char* quotes) {
4062 if ((l = strlen(s)) < 2)
4065 if (strchr(quotes, s[0]) && s[l-1] == s[0])
4066 return strndup(s+1, l-2);
4071 char *normalize_env_assignment(const char *s) {
4072 char *name, *value, *p, *r;
4077 if (!(r = strdup(s)))
4083 if (!(name = strndup(s, p - s)))
4086 if (!(p = strdup(p+1))) {
4091 value = unquote(strstrip(p), QUOTES);
4099 if (asprintf(&r, "%s=%s", name, value) < 0)
4108 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4119 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4131 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4138 if ((r = wait_for_terminate(pid, &status)) < 0) {
4139 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4143 if (status.si_code == CLD_EXITED) {
4144 if (status.si_status != 0) {
4145 log_warning("%s failed with error code %i.", name, status.si_status);
4146 return status.si_status;
4149 log_debug("%s succeeded.", name);
4152 } else if (status.si_code == CLD_KILLED ||
4153 status.si_code == CLD_DUMPED) {
4155 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4159 log_warning("%s failed due to unknown reason.", name);
4166 /* Make sure nobody waits for us on a socket anymore */
4167 close_all_fds(NULL, 0);
4175 bool null_or_empty(struct stat *st) {
4178 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4181 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4187 int null_or_empty_path(const char *fn) {
4192 if (stat(fn, &st) < 0)
4195 return null_or_empty(&st);
4198 DIR *xopendirat(int fd, const char *name, int flags) {
4202 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4205 if (!(d = fdopendir(nfd))) {
4206 close_nointr_nofail(nfd);
4213 int signal_from_string_try_harder(const char *s) {
4217 if ((signo = signal_from_string(s)) <= 0)
4218 if (startswith(s, "SIG"))
4219 return signal_from_string(s+3);
4224 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4230 if (!dual_timestamp_is_set(t))
4233 fprintf(f, "%s=%llu %llu\n",
4235 (unsigned long long) t->realtime,
4236 (unsigned long long) t->monotonic);
4239 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4240 unsigned long long a, b;
4245 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4246 log_debug("Failed to parse finish timestamp value %s", value);
4253 char *fstab_node_to_udev_node(const char *p) {
4257 /* FIXME: to follow udev's logic 100% we need to leave valid
4258 * UTF8 chars unescaped */
4260 if (startswith(p, "LABEL=")) {
4262 if (!(u = unquote(p+6, "\"\'")))
4265 t = xescape(u, "/ ");
4271 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4280 if (startswith(p, "UUID=")) {
4282 if (!(u = unquote(p+5, "\"\'")))
4285 t = xescape(u, "/ ");
4291 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4303 void filter_environ(const char *prefix) {
4310 for (i = 0, j = 0; environ[i]; i++) {
4312 if (startswith(environ[i], prefix))
4315 environ[j++] = environ[i];
4321 bool tty_is_vc(const char *tty) {
4324 if (startswith(tty, "/dev/"))
4327 return vtnr_from_tty(tty) >= 0;
4330 int vtnr_from_tty(const char *tty) {
4335 if (startswith(tty, "/dev/"))
4338 if (!startswith(tty, "tty") )
4341 if (tty[3] < '0' || tty[3] > '9')
4344 r = safe_atoi(tty+3, &i);
4348 if (i < 0 || i > 63)
4354 const char *default_term_for_tty(const char *tty) {
4355 char *active = NULL;
4360 if (startswith(tty, "/dev/"))
4363 /* Resolve where /dev/console is pointing when determining
4365 if (streq(tty, "console"))
4366 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4367 /* If multiple log outputs are configured the
4368 * last one is what /dev/console points to */
4369 if ((tty = strrchr(active, ' ')))
4375 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
4381 bool dirent_is_file(const struct dirent *de) {
4384 if (ignore_file(de->d_name))
4387 if (de->d_type != DT_REG &&
4388 de->d_type != DT_LNK &&
4389 de->d_type != DT_UNKNOWN)
4395 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4398 if (!dirent_is_file(de))
4401 return endswith(de->d_name, suffix);
4404 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4407 Hashmap *pids = NULL;
4411 /* Executes all binaries in a directory in parallel and waits
4412 * until all they all finished. */
4415 if (!(_d = opendir(directory))) {
4417 if (errno == ENOENT)
4420 log_error("Failed to enumerate directory %s: %m", directory);
4427 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4428 log_error("Failed to allocate set.");
4432 while ((de = readdir(d))) {
4437 if (!dirent_is_file(de))
4440 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4441 log_error("Out of memory");
4445 if ((pid = fork()) < 0) {
4446 log_error("Failed to fork: %m");
4465 log_error("Failed to execute %s: %m", path);
4466 _exit(EXIT_FAILURE);
4469 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4471 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4472 log_error("Failed to add PID to set: %s", strerror(-k));
4477 while (!hashmap_isempty(pids)) {
4482 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4487 log_error("waitid() failed: %m");
4491 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4492 if (!is_clean_exit(si.si_code, si.si_status)) {
4493 if (si.si_code == CLD_EXITED)
4494 log_error("%s exited with exit status %i.", path, si.si_status);
4496 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4498 log_debug("%s exited successfully.", path);
4509 hashmap_free_free(pids);
4512 int kill_and_sigcont(pid_t pid, int sig) {
4515 r = kill(pid, sig) < 0 ? -errno : 0;
4523 bool nulstr_contains(const char*nulstr, const char *needle) {
4529 NULSTR_FOREACH(i, nulstr)
4530 if (streq(i, needle))
4536 bool plymouth_running(void) {
4537 return access("/run/plymouth/pid", F_OK) >= 0;
4540 void parse_syslog_priority(char **p, int *priority) {
4541 int a = 0, b = 0, c = 0;
4551 if (!strchr(*p, '>'))
4554 if ((*p)[2] == '>') {
4555 c = undecchar((*p)[1]);
4557 } else if ((*p)[3] == '>') {
4558 b = undecchar((*p)[1]);
4559 c = undecchar((*p)[2]);
4561 } else if ((*p)[4] == '>') {
4562 a = undecchar((*p)[1]);
4563 b = undecchar((*p)[2]);
4564 c = undecchar((*p)[3]);
4569 if (a < 0 || b < 0 || c < 0)
4572 *priority = a*100+b*10+c;
4576 void skip_syslog_pid(char **buf) {
4588 p += strspn(p, "0123456789");
4598 void skip_syslog_date(char **buf) {
4606 LETTER, LETTER, LETTER,
4608 SPACE_OR_NUMBER, NUMBER,
4610 SPACE_OR_NUMBER, NUMBER,
4612 SPACE_OR_NUMBER, NUMBER,
4614 SPACE_OR_NUMBER, NUMBER,
4626 for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
4631 switch (sequence[i]) {
4638 case SPACE_OR_NUMBER:
4645 if (*p < '0' || *p > '9')
4651 if (!(*p >= 'A' && *p <= 'Z') &&
4652 !(*p >= 'a' && *p <= 'z'))
4668 int have_effective_cap(int value) {
4670 cap_flag_value_t fv;
4673 if (!(cap = cap_get_proc()))
4676 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4685 char* strshorten(char *s, size_t l) {
4694 static bool hostname_valid_char(char c) {
4696 (c >= 'a' && c <= 'z') ||
4697 (c >= 'A' && c <= 'Z') ||
4698 (c >= '0' && c <= '9') ||
4704 bool hostname_is_valid(const char *s) {
4710 for (p = s; *p; p++)
4711 if (!hostname_valid_char(*p))
4714 if (p-s > HOST_NAME_MAX)
4720 char* hostname_cleanup(char *s) {
4723 for (p = s, d = s; *p; p++)
4724 if ((*p >= 'a' && *p <= 'z') ||
4725 (*p >= 'A' && *p <= 'Z') ||
4726 (*p >= '0' && *p <= '9') ||
4734 strshorten(s, HOST_NAME_MAX);
4738 int pipe_eof(int fd) {
4739 struct pollfd pollfd;
4744 pollfd.events = POLLIN|POLLHUP;
4746 r = poll(&pollfd, 1, 0);
4753 return pollfd.revents & POLLHUP;
4756 int fd_wait_for_event(int fd, int event) {
4757 struct pollfd pollfd;
4762 pollfd.events = event;
4764 r = poll(&pollfd, 1, -1);
4771 return pollfd.revents;
4774 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4785 t = new(char, strlen(path) + 1 + 6 + 1);
4789 fn = file_name_from_path(path);
4793 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4795 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4801 f = fdopen(fd, "we");
4814 int terminal_vhangup_fd(int fd) {
4817 if (ioctl(fd, TIOCVHANGUP) < 0)
4823 int terminal_vhangup(const char *name) {
4826 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4830 r = terminal_vhangup_fd(fd);
4831 close_nointr_nofail(fd);
4836 int vt_disallocate(const char *name) {
4840 /* Deallocate the VT if possible. If not possible
4841 * (i.e. because it is the active one), at least clear it
4842 * entirely (including the scrollback buffer) */
4844 if (!startswith(name, "/dev/"))
4847 if (!tty_is_vc(name)) {
4848 /* So this is not a VT. I guess we cannot deallocate
4849 * it then. But let's at least clear the screen */
4851 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4856 "\033[r" /* clear scrolling region */
4857 "\033[H" /* move home */
4858 "\033[2J", /* clear screen */
4860 close_nointr_nofail(fd);
4865 if (!startswith(name, "/dev/tty"))
4868 r = safe_atou(name+8, &u);
4875 /* Try to deallocate */
4876 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4880 r = ioctl(fd, VT_DISALLOCATE, u);
4881 close_nointr_nofail(fd);
4889 /* Couldn't deallocate, so let's clear it fully with
4891 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4896 "\033[r" /* clear scrolling region */
4897 "\033[H" /* move home */
4898 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4900 close_nointr_nofail(fd);
4905 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4907 struct dirent buffer, *de;
4910 dir = opendir(path);
4912 if (errno == ENOENT)
4921 k = readdir_r(dir, &buffer, &de);
4930 if (!dirent_is_file_with_suffix(de, suffix))
4933 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4938 f = canonicalize_file_name(p);
4940 log_error("Failed to canonicalize file name '%s': %m", p);
4946 log_debug("found: %s\n", f);
4947 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
4956 static int base_cmp(const void *a, const void *b) {
4957 const char *s1, *s2;
4959 s1 = *(char * const *)a;
4960 s2 = *(char * const *)b;
4961 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4964 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
4967 char **files = NULL;
4973 dirs = strv_new_ap(dir, ap);
4979 if (!strv_path_canonicalize(dirs)) {
4983 if (!strv_uniq(dirs)) {
4988 fh = hashmap_new(string_hash_func, string_compare_func);
4994 STRV_FOREACH(p, dirs) {
4995 if (files_add(fh, *p, suffix) < 0) {
4996 log_error("Failed to search for files.");
5002 files = hashmap_get_strv(fh);
5003 if (files == NULL) {
5004 log_error("Failed to compose list of files.");
5009 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
5018 int hwclock_is_localtime(void) {
5023 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
5029 f = fopen("/etc/adjtime", "re");
5031 char line[LINE_MAX];
5034 b = fgets(line, sizeof(line), f) &&
5035 fgets(line, sizeof(line), f) &&
5036 fgets(line, sizeof(line), f);
5045 local = streq(line, "LOCAL");
5047 } else if (errno != -ENOENT)
5053 int hwclock_apply_localtime_delta(int *min) {
5054 const struct timeval *tv_null = NULL;
5060 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
5061 assert_se(tm = localtime(&ts.tv_sec));
5062 minuteswest = tm->tm_gmtoff / 60;
5064 tz.tz_minuteswest = -minuteswest;
5065 tz.tz_dsttime = 0; /* DST_NONE*/
5068 * If the hardware clock does not run in UTC, but in local time:
5069 * The very first time we set the kernel's timezone, it will warp
5070 * the clock so that it runs in UTC instead of local time.
5072 if (settimeofday(tv_null, &tz) < 0)
5079 int hwclock_reset_localtime_delta(void) {
5080 const struct timeval *tv_null = NULL;
5083 tz.tz_minuteswest = 0;
5084 tz.tz_dsttime = 0; /* DST_NONE*/
5086 if (settimeofday(tv_null, &tz) < 0)
5092 int hwclock_get_time(struct tm *tm) {
5098 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
5102 /* This leaves the timezone fields of struct tm
5104 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
5107 /* We don't now daylight saving, so we reset this in order not
5108 * to confused mktime(). */
5111 close_nointr_nofail(fd);
5116 int hwclock_set_time(const struct tm *tm) {
5122 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
5126 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5129 close_nointr_nofail(fd);
5134 int copy_file(const char *from, const char *to) {
5140 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5144 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5146 close_nointr_nofail(fdf);
5154 n = read(fdf, buf, sizeof(buf));
5158 close_nointr_nofail(fdf);
5169 k = loop_write(fdt, buf, n, false);
5171 r = k < 0 ? k : (errno ? -errno : -EIO);
5173 close_nointr_nofail(fdf);
5181 close_nointr_nofail(fdf);
5182 r = close_nointr(fdt);
5192 int symlink_or_copy(const char *from, const char *to) {
5193 char *pf = NULL, *pt = NULL;
5200 if (parent_of_path(from, &pf) < 0 ||
5201 parent_of_path(to, &pt) < 0) {
5206 if (stat(pf, &a) < 0 ||
5212 if (a.st_dev != b.st_dev) {
5216 return copy_file(from, to);
5219 if (symlink(from, to) < 0) {
5233 int symlink_or_copy_atomic(const char *from, const char *to) {
5237 unsigned long long ull;
5244 t = new(char, strlen(to) + 1 + 16 + 1);
5248 fn = file_name_from_path(to);
5252 x = stpcpy(t+k+1, fn);
5255 for (i = 0; i < 16; i++) {
5256 *(x++) = hexchar(ull & 0xF);
5262 r = symlink_or_copy(from, t);
5269 if (rename(t, to) < 0) {
5280 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5287 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5291 r = read_one_line_file("/proc/self/sessionid", &s);
5295 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5298 r = read_one_line_file(p, &s);
5305 r = safe_atou32(s, &u);
5311 if (u == (uint32_t) -1 || u <= 0)
5318 int audit_loginuid_from_pid(pid_t pid, uid_t *uid) {
5325 /* Only use audit login uid if we are executed with sufficient
5326 * capabilities so that pam_loginuid could do its job. If we
5327 * are lacking the CAP_AUDIT_CONTROL capabality we most likely
5328 * are being run in a container and /proc/self/loginuid is
5329 * useless since it probably contains a uid of the host
5332 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5336 r = read_one_line_file("/proc/self/loginuid", &s);
5340 if (asprintf(&p, "/proc/%lu/loginuid", (unsigned long) pid) < 0)
5343 r = read_one_line_file(p, &s);
5350 r = parse_uid(s, &u);
5356 if (u == (uid_t) -1)
5363 bool display_is_local(const char *display) {
5367 display[0] == ':' &&
5368 display[1] >= '0' &&
5372 int socket_from_display(const char *display, char **path) {
5379 if (!display_is_local(display))
5382 k = strspn(display+1, "0123456789");
5384 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5388 c = stpcpy(f, "/tmp/.X11-unix/X");
5389 memcpy(c, display+1, k);
5397 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5404 /* We enforce some special rules for uid=0: in order to avoid
5405 * NSS lookups for root we hardcode its data. */
5407 if (streq(*username, "root") || streq(*username, "0")) {
5421 if (parse_uid(*username, &u) >= 0) {
5425 /* If there are multiple users with the same id, make
5426 * sure to leave $USER to the configured value instead
5427 * of the first occurrence in the database. However if
5428 * the uid was configured by a numeric uid, then let's
5429 * pick the real username from /etc/passwd. */
5431 *username = p->pw_name;
5434 p = getpwnam(*username);
5438 return errno != 0 ? -errno : -ESRCH;
5452 int get_group_creds(const char **groupname, gid_t *gid) {
5458 /* We enforce some special rules for gid=0: in order to avoid
5459 * NSS lookups for root we hardcode its data. */
5461 if (streq(*groupname, "root") || streq(*groupname, "0")) {
5462 *groupname = "root";
5470 if (parse_gid(*groupname, &id) >= 0) {
5475 *groupname = g->gr_name;
5478 g = getgrnam(*groupname);
5482 return errno != 0 ? -errno : -ESRCH;
5490 int glob_exists(const char *path) {
5498 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5500 if (k == GLOB_NOMATCH)
5502 else if (k == GLOB_NOSPACE)
5505 r = !strv_isempty(g.gl_pathv);
5507 r = errno ? -errno : -EIO;
5514 int dirent_ensure_type(DIR *d, struct dirent *de) {
5520 if (de->d_type != DT_UNKNOWN)
5523 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5527 S_ISREG(st.st_mode) ? DT_REG :
5528 S_ISDIR(st.st_mode) ? DT_DIR :
5529 S_ISLNK(st.st_mode) ? DT_LNK :
5530 S_ISFIFO(st.st_mode) ? DT_FIFO :
5531 S_ISSOCK(st.st_mode) ? DT_SOCK :
5532 S_ISCHR(st.st_mode) ? DT_CHR :
5533 S_ISBLK(st.st_mode) ? DT_BLK :
5539 int in_search_path(const char *path, char **search) {
5543 r = parent_of_path(path, &parent);
5549 STRV_FOREACH(i, search) {
5550 if (path_equal(parent, *i)) {
5561 int get_files_in_directory(const char *path, char ***list) {
5569 /* Returns all files in a directory in *list, and the number
5570 * of files as return value. If list is NULL returns only the
5578 struct dirent buffer, *de;
5581 k = readdir_r(d, &buffer, &de);
5590 dirent_ensure_type(d, de);
5592 if (!dirent_is_file(de))
5596 if ((unsigned) r >= n) {
5600 t = realloc(l, sizeof(char*) * n);
5609 assert((unsigned) r < n);
5611 l[r] = strdup(de->d_name);
5635 char *join(const char *x, ...) {
5648 t = va_arg(ap, const char *);
5671 t = va_arg(ap, const char *);
5685 bool is_main_thread(void) {
5686 static __thread int cached = 0;
5688 if (_unlikely_(cached == 0))
5689 cached = getpid() == gettid() ? 1 : -1;
5694 int block_get_whole_disk(dev_t d, dev_t *ret) {
5701 /* If it has a queue this is good enough for us */
5702 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5705 r = access(p, F_OK);
5713 /* If it is a partition find the originating device */
5714 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5717 r = access(p, F_OK);
5723 /* Get parent dev_t */
5724 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5727 r = read_one_line_file(p, &s);
5733 r = sscanf(s, "%u:%u", &m, &n);
5739 /* Only return this if it is really good enough for us. */
5740 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5743 r = access(p, F_OK);
5747 *ret = makedev(m, n);
5754 int file_is_sticky(const char *p) {
5759 if (lstat(p, &st) < 0)
5764 (st.st_mode & S_ISVTX);
5767 static const char *const ioprio_class_table[] = {
5768 [IOPRIO_CLASS_NONE] = "none",
5769 [IOPRIO_CLASS_RT] = "realtime",
5770 [IOPRIO_CLASS_BE] = "best-effort",
5771 [IOPRIO_CLASS_IDLE] = "idle"
5774 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5776 static const char *const sigchld_code_table[] = {
5777 [CLD_EXITED] = "exited",
5778 [CLD_KILLED] = "killed",
5779 [CLD_DUMPED] = "dumped",
5780 [CLD_TRAPPED] = "trapped",
5781 [CLD_STOPPED] = "stopped",
5782 [CLD_CONTINUED] = "continued",
5785 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5787 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5788 [LOG_FAC(LOG_KERN)] = "kern",
5789 [LOG_FAC(LOG_USER)] = "user",
5790 [LOG_FAC(LOG_MAIL)] = "mail",
5791 [LOG_FAC(LOG_DAEMON)] = "daemon",
5792 [LOG_FAC(LOG_AUTH)] = "auth",
5793 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5794 [LOG_FAC(LOG_LPR)] = "lpr",
5795 [LOG_FAC(LOG_NEWS)] = "news",
5796 [LOG_FAC(LOG_UUCP)] = "uucp",
5797 [LOG_FAC(LOG_CRON)] = "cron",
5798 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5799 [LOG_FAC(LOG_FTP)] = "ftp",
5800 [LOG_FAC(LOG_LOCAL0)] = "local0",
5801 [LOG_FAC(LOG_LOCAL1)] = "local1",
5802 [LOG_FAC(LOG_LOCAL2)] = "local2",
5803 [LOG_FAC(LOG_LOCAL3)] = "local3",
5804 [LOG_FAC(LOG_LOCAL4)] = "local4",
5805 [LOG_FAC(LOG_LOCAL5)] = "local5",
5806 [LOG_FAC(LOG_LOCAL6)] = "local6",
5807 [LOG_FAC(LOG_LOCAL7)] = "local7"
5810 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5812 static const char *const log_level_table[] = {
5813 [LOG_EMERG] = "emerg",
5814 [LOG_ALERT] = "alert",
5815 [LOG_CRIT] = "crit",
5817 [LOG_WARNING] = "warning",
5818 [LOG_NOTICE] = "notice",
5819 [LOG_INFO] = "info",
5820 [LOG_DEBUG] = "debug"
5823 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5825 static const char* const sched_policy_table[] = {
5826 [SCHED_OTHER] = "other",
5827 [SCHED_BATCH] = "batch",
5828 [SCHED_IDLE] = "idle",
5829 [SCHED_FIFO] = "fifo",
5833 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5835 static const char* const rlimit_table[] = {
5836 [RLIMIT_CPU] = "LimitCPU",
5837 [RLIMIT_FSIZE] = "LimitFSIZE",
5838 [RLIMIT_DATA] = "LimitDATA",
5839 [RLIMIT_STACK] = "LimitSTACK",
5840 [RLIMIT_CORE] = "LimitCORE",
5841 [RLIMIT_RSS] = "LimitRSS",
5842 [RLIMIT_NOFILE] = "LimitNOFILE",
5843 [RLIMIT_AS] = "LimitAS",
5844 [RLIMIT_NPROC] = "LimitNPROC",
5845 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5846 [RLIMIT_LOCKS] = "LimitLOCKS",
5847 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5848 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5849 [RLIMIT_NICE] = "LimitNICE",
5850 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5851 [RLIMIT_RTTIME] = "LimitRTTIME"
5854 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5856 static const char* const ip_tos_table[] = {
5857 [IPTOS_LOWDELAY] = "low-delay",
5858 [IPTOS_THROUGHPUT] = "throughput",
5859 [IPTOS_RELIABILITY] = "reliability",
5860 [IPTOS_LOWCOST] = "low-cost",
5863 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5865 static const char *const __signal_table[] = {
5882 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5893 [SIGVTALRM] = "VTALRM",
5895 [SIGWINCH] = "WINCH",
5901 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5903 const char *signal_to_string(int signo) {
5904 static __thread char buf[12];
5907 name = __signal_to_string(signo);
5911 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5912 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5914 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5919 int signal_from_string(const char *s) {
5924 signo =__signal_from_string(s);
5928 if (startswith(s, "RTMIN+")) {
5932 if (safe_atou(s, &u) >= 0) {
5933 signo = (int) u + offset;
5934 if (signo > 0 && signo < _NSIG)
5940 bool kexec_loaded(void) {
5941 bool loaded = false;
5944 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5952 int strdup_or_null(const char *a, char **b) {
5970 int prot_from_flags(int flags) {
5972 switch (flags & O_ACCMODE) {
5981 return PROT_READ|PROT_WRITE;
5988 unsigned long cap_last_cap(void) {
5989 static __thread unsigned long saved;
5990 static __thread bool valid = false;
5996 p = (unsigned long) CAP_LAST_CAP;
5998 if (prctl(PR_CAPBSET_READ, p) < 0) {
6000 /* Hmm, look downwards, until we find one that
6002 for (p--; p > 0; p --)
6003 if (prctl(PR_CAPBSET_READ, p) >= 0)
6008 /* Hmm, look upwards, until we find one that doesn't
6011 if (prctl(PR_CAPBSET_READ, p+1) < 0)
6021 char *format_bytes(char *buf, size_t l, off_t t) {
6024 static const struct {
6028 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
6029 { "G", 1024ULL*1024ULL*1024ULL },
6030 { "M", 1024ULL*1024ULL },
6034 for (i = 0; i < ELEMENTSOF(table); i++) {
6036 if (t >= table[i].factor) {
6039 (unsigned long long) (t / table[i].factor),
6040 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
6047 snprintf(buf, l, "%lluB", (unsigned long long) t);
6055 void* memdup(const void *p, size_t l) {