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>
64 #include "exit-status.h"
67 size_t page_size(void) {
68 static __thread size_t pgsz = 0;
74 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
81 bool streq_ptr(const char *a, const char *b) {
83 /* Like streq(), but tries to make sense of NULL pointers */
94 usec_t now(clockid_t clock_id) {
97 assert_se(clock_gettime(clock_id, &ts) == 0);
99 return timespec_load(&ts);
102 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
105 ts->realtime = now(CLOCK_REALTIME);
106 ts->monotonic = now(CLOCK_MONOTONIC);
111 usec_t timespec_load(const struct timespec *ts) {
115 (usec_t) ts->tv_sec * USEC_PER_SEC +
116 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
119 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
122 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
123 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
128 usec_t timeval_load(const struct timeval *tv) {
132 (usec_t) tv->tv_sec * USEC_PER_SEC +
133 (usec_t) tv->tv_usec;
136 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
139 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
140 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
145 bool endswith(const char *s, const char *postfix) {
152 pl = strlen(postfix);
160 return memcmp(s + sl - pl, postfix, pl) == 0;
163 bool startswith(const char *s, const char *prefix) {
178 return memcmp(s, prefix, pl) == 0;
181 bool startswith_no_case(const char *s, const char *prefix) {
197 for(i = 0; i < pl; ++i) {
198 if (tolower(s[i]) != tolower(prefix[i]))
205 bool first_word(const char *s, const char *word) {
220 if (memcmp(s, word, wl) != 0)
224 strchr(WHITESPACE, s[wl]);
227 int close_nointr(int fd) {
233 if ((r = close(fd)) >= 0)
241 void close_nointr_nofail(int fd) {
242 int saved_errno = errno;
244 /* like close_nointr() but cannot fail, and guarantees errno
247 assert_se(close_nointr(fd) == 0);
252 void close_many(const int fds[], unsigned n_fd) {
255 for (i = 0; i < n_fd; i++)
256 close_nointr_nofail(fds[i]);
259 int parse_boolean(const char *v) {
262 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
264 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
270 int parse_pid(const char *s, pid_t* ret_pid) {
271 unsigned long ul = 0;
278 if ((r = safe_atolu(s, &ul)) < 0)
283 if ((unsigned long) pid != ul)
293 int safe_atou(const char *s, unsigned *ret_u) {
301 l = strtoul(s, &x, 0);
303 if (!x || *x || errno)
304 return errno ? -errno : -EINVAL;
306 if ((unsigned long) (unsigned) l != l)
309 *ret_u = (unsigned) l;
313 int safe_atoi(const char *s, int *ret_i) {
321 l = strtol(s, &x, 0);
323 if (!x || *x || errno)
324 return errno ? -errno : -EINVAL;
326 if ((long) (int) l != l)
333 int safe_atollu(const char *s, long long unsigned *ret_llu) {
335 unsigned long long l;
341 l = strtoull(s, &x, 0);
343 if (!x || *x || errno)
344 return errno ? -errno : -EINVAL;
350 int safe_atolli(const char *s, long long int *ret_lli) {
358 l = strtoll(s, &x, 0);
360 if (!x || *x || errno)
361 return errno ? -errno : -EINVAL;
367 /* Split a string into words. */
368 char *split(const char *c, size_t *l, const char *separator, char **state) {
371 current = *state ? *state : (char*) c;
373 if (!*current || *c == 0)
376 current += strspn(current, separator);
377 *l = strcspn(current, separator);
380 return (char*) current;
383 /* Split a string into words, but consider strings enclosed in '' and
384 * "" as words even if they include spaces. */
385 char *split_quoted(const char *c, size_t *l, char **state) {
387 bool escaped = false;
389 current = *state ? *state : (char*) c;
391 if (!*current || *c == 0)
394 current += strspn(current, WHITESPACE);
396 if (*current == '\'') {
399 for (e = current; *e; e++) {
409 *state = *e == 0 ? e : e+1;
410 } else if (*current == '\"') {
413 for (e = current; *e; e++) {
423 *state = *e == 0 ? e : e+1;
425 for (e = current; *e; e++) {
430 else if (strchr(WHITESPACE, *e))
437 return (char*) current;
440 char **split_path_and_make_absolute(const char *p) {
444 if (!(l = strv_split(p, ":")))
447 if (!strv_path_make_absolute_cwd(l)) {
455 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
458 char fn[PATH_MAX], line[LINE_MAX], *p;
464 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
467 if (!(f = fopen(fn, "r")))
470 if (!(fgets(line, sizeof(line), f))) {
478 /* Let's skip the pid and comm fields. The latter is enclosed
479 * in () but does not escape any () in its value, so let's
480 * skip over it manually */
482 if (!(p = strrchr(line, ')')))
493 if ((long unsigned) (pid_t) ppid != ppid)
496 *_ppid = (pid_t) ppid;
501 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
504 char fn[PATH_MAX], line[LINE_MAX], *p;
509 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
512 if (!(f = fopen(fn, "r")))
515 if (!(fgets(line, sizeof(line), f))) {
523 /* Let's skip the pid and comm fields. The latter is enclosed
524 * in () but does not escape any () in its value, so let's
525 * skip over it manually */
527 if (!(p = strrchr(line, ')')))
548 "%*d " /* priority */
550 "%*d " /* num_threads */
551 "%*d " /* itrealvalue */
552 "%llu " /* starttime */,
559 int write_one_line_file(const char *fn, const char *line) {
566 if (!(f = fopen(fn, "we")))
569 if (fputs(line, f) < 0) {
574 if (!endswith(line, "\n"))
592 int read_one_line_file(const char *fn, char **line) {
595 char t[LINE_MAX], *c;
600 if (!(f = fopen(fn, "re")))
603 if (!(fgets(t, sizeof(t), f))) {
608 if (!(c = strdup(t))) {
623 int read_full_file(const char *fn, char **contents) {
630 if (!(f = fopen(fn, "re")))
633 if (fstat(fileno(f), &st) < 0) {
638 n = st.st_size > 0 ? st.st_size : LINE_MAX;
645 if (!(t = realloc(buf, n+1))) {
651 k = fread(buf + l, 1, n - l, f);
666 if (n > 4*1024*1024) {
674 else if (!(buf = calloc(1, 1))) {
693 const char *separator, ...) {
701 if ((r = read_full_file(fname, &contents)) < 0)
706 const char *key = NULL;
708 p += strspn(p, separator);
709 p += strspn(p, WHITESPACE);
714 if (!strchr(COMMENTS, *p)) {
718 va_start(ap, separator);
719 while ((key = va_arg(ap, char *))) {
723 value = va_arg(ap, char **);
726 if (strncmp(p, key, n) != 0 ||
731 n = strcspn(p, separator);
734 strchr(QUOTES, p[0]) &&
736 v = strndup(p+1, n-2);
747 /* return empty value strings as NULL */
764 p += strcspn(p, separator);
783 if (!(f = fopen(fname, "re")))
787 char l[LINE_MAX], *p, *u;
790 if (!fgets(l, sizeof(l), f)) {
803 if (strchr(COMMENTS, *p))
806 if (!(u = normalize_env_assignment(p))) {
807 log_error("Out of memory");
812 t = strv_append(m, u);
816 log_error("Out of memory");
839 int write_env_file(const char *fname, char **l) {
845 f = fopen(fname, "we");
856 r = ferror(f) ? -errno : 0;
862 char *truncate_nl(char *s) {
865 s[strcspn(s, NEWLINE)] = 0;
869 int get_process_name(pid_t pid, char **name) {
876 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
879 r = read_one_line_file(p, name);
888 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
896 assert(max_length > 0);
899 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
908 if (!(r = new(char, max_length))) {
915 while ((c = getc(f)) != EOF) {
937 size_t n = MIN(left-1, 3U);
945 /* Kernel threads have no argv[] */
952 if ((h = get_process_name(pid, &t)) < 0)
955 h = asprintf(&r, "[%s]", t);
966 char *strnappend(const char *s, const char *suffix, size_t b) {
974 return strndup(suffix, b);
984 if (!(r = new(char, a+b+1)))
988 memcpy(r+a, suffix, b);
994 char *strappend(const char *s, const char *suffix) {
995 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
998 int readlink_malloc(const char *p, char **r) {
1008 if (!(c = new(char, l)))
1011 if ((n = readlink(p, c, l-1)) < 0) {
1017 if ((size_t) n < l-1) {
1028 int readlink_and_make_absolute(const char *p, char **r) {
1035 if ((j = readlink_malloc(p, &target)) < 0)
1038 k = file_in_same_dir(p, target);
1048 int parent_of_path(const char *path, char **_r) {
1049 const char *e, *a = NULL, *b = NULL, *p;
1059 for (e = path; *e; e++) {
1061 if (!slash && *e == '/') {
1065 } else if (slash && *e != '/')
1080 r = strndup(path, p-path);
1090 char *file_name_from_path(const char *p) {
1095 if ((r = strrchr(p, '/')))
1101 bool path_is_absolute(const char *p) {
1107 bool is_path(const char *p) {
1109 return !!strchr(p, '/');
1112 char *path_make_absolute(const char *p, const char *prefix) {
1117 /* Makes every item in the list an absolute path by prepending
1118 * the prefix, if specified and necessary */
1120 if (path_is_absolute(p) || !prefix)
1123 if (asprintf(&r, "%s/%s", prefix, p) < 0)
1129 char *path_make_absolute_cwd(const char *p) {
1134 /* Similar to path_make_absolute(), but prefixes with the
1135 * current working directory. */
1137 if (path_is_absolute(p))
1140 if (!(cwd = get_current_dir_name()))
1143 r = path_make_absolute(p, cwd);
1149 char **strv_path_make_absolute_cwd(char **l) {
1152 /* Goes through every item in the string list and makes it
1153 * absolute. This works in place and won't rollback any
1154 * changes on failure. */
1156 STRV_FOREACH(s, l) {
1159 if (!(t = path_make_absolute_cwd(*s)))
1169 char **strv_path_canonicalize(char **l) {
1172 bool enomem = false;
1174 if (strv_isempty(l))
1177 /* Goes through every item in the string list and canonicalize
1178 * the path. This works in place and won't rollback any
1179 * changes on failure. */
1181 STRV_FOREACH(s, l) {
1184 t = path_make_absolute_cwd(*s);
1193 u = canonicalize_file_name(t);
1197 if (errno == ENOMEM || !errno)
1214 char **strv_path_remove_empty(char **l) {
1220 for (f = t = l; *f; f++) {
1222 if (dir_is_empty(*f) > 0) {
1234 int reset_all_signal_handlers(void) {
1237 for (sig = 1; sig < _NSIG; sig++) {
1238 struct sigaction sa;
1240 if (sig == SIGKILL || sig == SIGSTOP)
1244 sa.sa_handler = SIG_DFL;
1245 sa.sa_flags = SA_RESTART;
1247 /* On Linux the first two RT signals are reserved by
1248 * glibc, and sigaction() will return EINVAL for them. */
1249 if ((sigaction(sig, &sa, NULL) < 0))
1250 if (errno != EINVAL)
1257 char *strstrip(char *s) {
1260 /* Drops trailing whitespace. Modifies the string in
1261 * place. Returns pointer to first non-space character */
1263 s += strspn(s, WHITESPACE);
1265 for (e = s; *e; e++)
1266 if (!strchr(WHITESPACE, *e))
1277 char *delete_chars(char *s, const char *bad) {
1280 /* Drops all whitespace, regardless where in the string */
1282 for (f = s, t = s; *f; f++) {
1283 if (strchr(bad, *f))
1294 char *file_in_same_dir(const char *path, const char *filename) {
1301 /* This removes the last component of path and appends
1302 * filename, unless the latter is absolute anyway or the
1305 if (path_is_absolute(filename))
1306 return strdup(filename);
1308 if (!(e = strrchr(path, '/')))
1309 return strdup(filename);
1311 k = strlen(filename);
1312 if (!(r = new(char, e-path+1+k+1)))
1315 memcpy(r, path, e-path+1);
1316 memcpy(r+(e-path)+1, filename, k+1);
1321 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1324 if (label_mkdir(path, mode) >= 0)
1325 if (chmod_and_chown(path, mode, uid, gid) < 0)
1328 if (lstat(path, &st) < 0)
1331 if ((st.st_mode & 0777) != mode ||
1334 !S_ISDIR(st.st_mode)) {
1343 int mkdir_parents(const char *path, mode_t mode) {
1348 /* Creates every parent directory in the path except the last
1351 p = path + strspn(path, "/");
1356 e = p + strcspn(p, "/");
1357 p = e + strspn(e, "/");
1359 /* Is this the last component? If so, then we're
1364 if (!(t = strndup(path, e - path)))
1367 r = label_mkdir(t, mode);
1370 if (r < 0 && errno != EEXIST)
1375 int mkdir_p(const char *path, mode_t mode) {
1380 if ((r = mkdir_parents(path, mode)) < 0)
1383 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1389 int rmdir_parents(const char *path, const char *stop) {
1398 /* Skip trailing slashes */
1399 while (l > 0 && path[l-1] == '/')
1405 /* Skip last component */
1406 while (l > 0 && path[l-1] != '/')
1409 /* Skip trailing slashes */
1410 while (l > 0 && path[l-1] == '/')
1416 if (!(t = strndup(path, l)))
1419 if (path_startswith(stop, t)) {
1428 if (errno != ENOENT)
1436 char hexchar(int x) {
1437 static const char table[16] = "0123456789abcdef";
1439 return table[x & 15];
1442 int unhexchar(char c) {
1444 if (c >= '0' && c <= '9')
1447 if (c >= 'a' && c <= 'f')
1448 return c - 'a' + 10;
1450 if (c >= 'A' && c <= 'F')
1451 return c - 'A' + 10;
1456 char octchar(int x) {
1457 return '0' + (x & 7);
1460 int unoctchar(char c) {
1462 if (c >= '0' && c <= '7')
1468 char decchar(int x) {
1469 return '0' + (x % 10);
1472 int undecchar(char c) {
1474 if (c >= '0' && c <= '9')
1480 char *cescape(const char *s) {
1486 /* Does C style string escaping. */
1488 if (!(r = new(char, strlen(s)*4 + 1)))
1491 for (f = s, t = r; *f; f++)
1537 /* For special chars we prefer octal over
1538 * hexadecimal encoding, simply because glib's
1539 * g_strescape() does the same */
1540 if ((*f < ' ') || (*f >= 127)) {
1542 *(t++) = octchar((unsigned char) *f >> 6);
1543 *(t++) = octchar((unsigned char) *f >> 3);
1544 *(t++) = octchar((unsigned char) *f);
1555 char *cunescape_length(const char *s, size_t length) {
1561 /* Undoes C style string escaping */
1563 if (!(r = new(char, length+1)))
1566 for (f = s, t = r; f < s + length; f++) {
1609 /* This is an extension of the XDG syntax files */
1614 /* hexadecimal encoding */
1617 if ((a = unhexchar(f[1])) < 0 ||
1618 (b = unhexchar(f[2])) < 0) {
1619 /* Invalid escape code, let's take it literal then */
1623 *(t++) = (char) ((a << 4) | b);
1638 /* octal encoding */
1641 if ((a = unoctchar(f[0])) < 0 ||
1642 (b = unoctchar(f[1])) < 0 ||
1643 (c = unoctchar(f[2])) < 0) {
1644 /* Invalid escape code, let's take it literal then */
1648 *(t++) = (char) ((a << 6) | (b << 3) | c);
1656 /* premature end of string.*/
1661 /* Invalid escape code, let's take it literal then */
1673 char *cunescape(const char *s) {
1674 return cunescape_length(s, strlen(s));
1677 char *xescape(const char *s, const char *bad) {
1681 /* Escapes all chars in bad, in addition to \ and all special
1682 * chars, in \xFF style escaping. May be reversed with
1685 if (!(r = new(char, strlen(s)*4+1)))
1688 for (f = s, t = r; *f; f++) {
1690 if ((*f < ' ') || (*f >= 127) ||
1691 (*f == '\\') || strchr(bad, *f)) {
1694 *(t++) = hexchar(*f >> 4);
1695 *(t++) = hexchar(*f);
1705 char *bus_path_escape(const char *s) {
1711 /* Escapes all chars that D-Bus' object path cannot deal
1712 * with. Can be reverse with bus_path_unescape() */
1714 if (!(r = new(char, strlen(s)*3+1)))
1717 for (f = s, t = r; *f; f++) {
1719 if (!(*f >= 'A' && *f <= 'Z') &&
1720 !(*f >= 'a' && *f <= 'z') &&
1721 !(*f >= '0' && *f <= '9')) {
1723 *(t++) = hexchar(*f >> 4);
1724 *(t++) = hexchar(*f);
1734 char *bus_path_unescape(const char *f) {
1739 if (!(r = strdup(f)))
1742 for (t = r; *f; f++) {
1747 if ((a = unhexchar(f[1])) < 0 ||
1748 (b = unhexchar(f[2])) < 0) {
1749 /* Invalid escape code, let's take it literal then */
1752 *(t++) = (char) ((a << 4) | b);
1764 char *path_kill_slashes(char *path) {
1768 /* Removes redundant inner and trailing slashes. Modifies the
1769 * passed string in-place.
1771 * ///foo///bar/ becomes /foo/bar
1774 for (f = path, t = path; *f; f++) {
1789 /* Special rule, if we are talking of the root directory, a
1790 trailing slash is good */
1792 if (t == path && slash)
1799 bool path_startswith(const char *path, const char *prefix) {
1803 if ((path[0] == '/') != (prefix[0] == '/'))
1809 path += strspn(path, "/");
1810 prefix += strspn(prefix, "/");
1818 a = strcspn(path, "/");
1819 b = strcspn(prefix, "/");
1824 if (memcmp(path, prefix, a) != 0)
1832 bool path_equal(const char *a, const char *b) {
1836 if ((a[0] == '/') != (b[0] == '/'))
1842 a += strspn(a, "/");
1843 b += strspn(b, "/");
1845 if (*a == 0 && *b == 0)
1848 if (*a == 0 || *b == 0)
1851 j = strcspn(a, "/");
1852 k = strcspn(b, "/");
1857 if (memcmp(a, b, j) != 0)
1865 char *ascii_strlower(char *t) {
1870 for (p = t; *p; p++)
1871 if (*p >= 'A' && *p <= 'Z')
1872 *p = *p - 'A' + 'a';
1877 bool ignore_file(const char *filename) {
1881 filename[0] == '.' ||
1882 streq(filename, "lost+found") ||
1883 streq(filename, "aquota.user") ||
1884 streq(filename, "aquota.group") ||
1885 endswith(filename, "~") ||
1886 endswith(filename, ".rpmnew") ||
1887 endswith(filename, ".rpmsave") ||
1888 endswith(filename, ".rpmorig") ||
1889 endswith(filename, ".dpkg-old") ||
1890 endswith(filename, ".dpkg-new") ||
1891 endswith(filename, ".swp");
1894 int fd_nonblock(int fd, bool nonblock) {
1899 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1903 flags |= O_NONBLOCK;
1905 flags &= ~O_NONBLOCK;
1907 if (fcntl(fd, F_SETFL, flags) < 0)
1913 int fd_cloexec(int fd, bool cloexec) {
1918 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1922 flags |= FD_CLOEXEC;
1924 flags &= ~FD_CLOEXEC;
1926 if (fcntl(fd, F_SETFD, flags) < 0)
1932 int close_all_fds(const int except[], unsigned n_except) {
1937 if (!(d = opendir("/proc/self/fd")))
1940 while ((de = readdir(d))) {
1943 if (ignore_file(de->d_name))
1946 if (safe_atoi(de->d_name, &fd) < 0)
1947 /* Let's better ignore this, just in case */
1961 for (i = 0; i < n_except; i++)
1962 if (except[i] == fd) {
1971 if (close_nointr(fd) < 0) {
1972 /* Valgrind has its own FD and doesn't want to have it closed */
1973 if (errno != EBADF && r == 0)
1982 bool chars_intersect(const char *a, const char *b) {
1985 /* Returns true if any of the chars in a are in b. */
1986 for (p = a; *p; p++)
1993 char *format_timestamp(char *buf, size_t l, usec_t t) {
2003 sec = (time_t) (t / USEC_PER_SEC);
2005 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2011 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2014 n = now(CLOCK_REALTIME);
2016 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2021 if (d >= USEC_PER_YEAR)
2022 snprintf(buf, l, "%llu years and %llu months ago",
2023 (unsigned long long) (d / USEC_PER_YEAR),
2024 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2025 else if (d >= USEC_PER_MONTH)
2026 snprintf(buf, l, "%llu months and %llu days ago",
2027 (unsigned long long) (d / USEC_PER_MONTH),
2028 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2029 else if (d >= USEC_PER_WEEK)
2030 snprintf(buf, l, "%llu weeks and %llu days ago",
2031 (unsigned long long) (d / USEC_PER_WEEK),
2032 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2033 else if (d >= 2*USEC_PER_DAY)
2034 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2035 else if (d >= 25*USEC_PER_HOUR)
2036 snprintf(buf, l, "1 day and %lluh ago",
2037 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2038 else if (d >= 6*USEC_PER_HOUR)
2039 snprintf(buf, l, "%lluh ago",
2040 (unsigned long long) (d / USEC_PER_HOUR));
2041 else if (d >= USEC_PER_HOUR)
2042 snprintf(buf, l, "%lluh %llumin ago",
2043 (unsigned long long) (d / USEC_PER_HOUR),
2044 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2045 else if (d >= 5*USEC_PER_MINUTE)
2046 snprintf(buf, l, "%llumin ago",
2047 (unsigned long long) (d / USEC_PER_MINUTE));
2048 else if (d >= USEC_PER_MINUTE)
2049 snprintf(buf, l, "%llumin %llus ago",
2050 (unsigned long long) (d / USEC_PER_MINUTE),
2051 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2052 else if (d >= USEC_PER_SEC)
2053 snprintf(buf, l, "%llus ago",
2054 (unsigned long long) (d / USEC_PER_SEC));
2055 else if (d >= USEC_PER_MSEC)
2056 snprintf(buf, l, "%llums ago",
2057 (unsigned long long) (d / USEC_PER_MSEC));
2059 snprintf(buf, l, "%lluus ago",
2060 (unsigned long long) d);
2062 snprintf(buf, l, "now");
2068 char *format_timespan(char *buf, size_t l, usec_t t) {
2069 static const struct {
2073 { "w", USEC_PER_WEEK },
2074 { "d", USEC_PER_DAY },
2075 { "h", USEC_PER_HOUR },
2076 { "min", USEC_PER_MINUTE },
2077 { "s", USEC_PER_SEC },
2078 { "ms", USEC_PER_MSEC },
2088 if (t == (usec_t) -1)
2092 snprintf(p, l, "0");
2097 /* The result of this function can be parsed with parse_usec */
2099 for (i = 0; i < ELEMENTSOF(table); i++) {
2103 if (t < table[i].usec)
2109 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2110 n = MIN((size_t) k, l);
2123 bool fstype_is_network(const char *fstype) {
2124 static const char * const table[] = {
2136 for (i = 0; i < ELEMENTSOF(table); i++)
2137 if (streq(table[i], fstype))
2146 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2151 TIOCL_GETKMSGREDIRECT,
2155 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2158 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2161 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2164 close_nointr_nofail(r);
2168 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2169 struct termios old_termios, new_termios;
2171 char line[LINE_MAX];
2176 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2177 new_termios = old_termios;
2179 new_termios.c_lflag &= ~ICANON;
2180 new_termios.c_cc[VMIN] = 1;
2181 new_termios.c_cc[VTIME] = 0;
2183 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2186 k = fread(&c, 1, 1, f);
2188 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2194 *need_nl = c != '\n';
2201 if (!(fgets(line, sizeof(line), f)))
2206 if (strlen(line) != 1)
2216 int ask(char *ret, const char *replies, const char *text, ...) {
2223 on_tty = isatty(STDOUT_FILENO);
2229 bool need_nl = true;
2232 fputs("\x1B[1m", stdout);
2239 fputs("\x1B[0m", stdout);
2243 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2245 if (r == -EBADMSG) {
2246 puts("Bad input, please try again.");
2257 if (strchr(replies, c)) {
2262 puts("Read unexpected character, please try again.");
2266 int reset_terminal_fd(int fd) {
2267 struct termios termios;
2271 /* Set terminal to some sane defaults */
2275 /* We leave locked terminal attributes untouched, so that
2276 * Plymouth may set whatever it wants to set, and we don't
2277 * interfere with that. */
2279 /* Disable exclusive mode, just in case */
2280 ioctl(fd, TIOCNXCL);
2282 /* Enable console unicode mode */
2284 ioctl(fd, KDSKBMODE, &arg);
2286 if (tcgetattr(fd, &termios) < 0) {
2291 /* We only reset the stuff that matters to the software. How
2292 * hardware is set up we don't touch assuming that somebody
2293 * else will do that for us */
2295 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2296 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2297 termios.c_oflag |= ONLCR;
2298 termios.c_cflag |= CREAD;
2299 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2301 termios.c_cc[VINTR] = 03; /* ^C */
2302 termios.c_cc[VQUIT] = 034; /* ^\ */
2303 termios.c_cc[VERASE] = 0177;
2304 termios.c_cc[VKILL] = 025; /* ^X */
2305 termios.c_cc[VEOF] = 04; /* ^D */
2306 termios.c_cc[VSTART] = 021; /* ^Q */
2307 termios.c_cc[VSTOP] = 023; /* ^S */
2308 termios.c_cc[VSUSP] = 032; /* ^Z */
2309 termios.c_cc[VLNEXT] = 026; /* ^V */
2310 termios.c_cc[VWERASE] = 027; /* ^W */
2311 termios.c_cc[VREPRINT] = 022; /* ^R */
2312 termios.c_cc[VEOL] = 0;
2313 termios.c_cc[VEOL2] = 0;
2315 termios.c_cc[VTIME] = 0;
2316 termios.c_cc[VMIN] = 1;
2318 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2322 /* Just in case, flush all crap out */
2323 tcflush(fd, TCIOFLUSH);
2328 int reset_terminal(const char *name) {
2331 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2335 r = reset_terminal_fd(fd);
2336 close_nointr_nofail(fd);
2341 int open_terminal(const char *name, int mode) {
2346 * If a TTY is in the process of being closed opening it might
2347 * cause EIO. This is horribly awful, but unlikely to be
2348 * changed in the kernel. Hence we work around this problem by
2349 * retrying a couple of times.
2351 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2355 if ((fd = open(name, mode)) >= 0)
2364 usleep(50 * USEC_PER_MSEC);
2371 if ((r = isatty(fd)) < 0) {
2372 close_nointr_nofail(fd);
2377 close_nointr_nofail(fd);
2384 int flush_fd(int fd) {
2385 struct pollfd pollfd;
2389 pollfd.events = POLLIN;
2396 if ((r = poll(&pollfd, 1, 0)) < 0) {
2407 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2412 if (errno == EAGAIN)
2423 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2424 int fd = -1, notify = -1, r, wd = -1;
2428 /* We use inotify to be notified when the tty is closed. We
2429 * create the watch before checking if we can actually acquire
2430 * it, so that we don't lose any event.
2432 * Note: strictly speaking this actually watches for the
2433 * device being closed, it does *not* really watch whether a
2434 * tty loses its controlling process. However, unless some
2435 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2436 * its tty otherwise this will not become a problem. As long
2437 * as the administrator makes sure not configure any service
2438 * on the same tty as an untrusted user this should not be a
2439 * problem. (Which he probably should not do anyway.) */
2441 if (!fail && !force) {
2442 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2447 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2455 if ((r = flush_fd(notify)) < 0)
2458 /* We pass here O_NOCTTY only so that we can check the return
2459 * value TIOCSCTTY and have a reliable way to figure out if we
2460 * successfully became the controlling process of the tty */
2461 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2464 /* First, try to get the tty */
2465 r = ioctl(fd, TIOCSCTTY, force);
2467 /* Sometimes it makes sense to ignore TIOCSCTTY
2468 * returning EPERM, i.e. when very likely we already
2469 * are have this controlling terminal. */
2470 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2473 if (r < 0 && (force || fail || errno != EPERM)) {
2483 assert(notify >= 0);
2486 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2488 struct inotify_event *e;
2490 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2499 e = (struct inotify_event*) inotify_buffer;
2504 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2509 step = sizeof(struct inotify_event) + e->len;
2510 assert(step <= (size_t) l);
2512 e = (struct inotify_event*) ((uint8_t*) e + step);
2519 /* We close the tty fd here since if the old session
2520 * ended our handle will be dead. It's important that
2521 * we do this after sleeping, so that we don't enter
2522 * an endless loop. */
2523 close_nointr_nofail(fd);
2527 close_nointr_nofail(notify);
2529 if ((r = reset_terminal_fd(fd)) < 0)
2530 log_warning("Failed to reset terminal: %s", strerror(-r));
2536 close_nointr_nofail(fd);
2539 close_nointr_nofail(notify);
2544 int release_terminal(void) {
2546 struct sigaction sa_old, sa_new;
2548 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2551 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2552 * by our own TIOCNOTTY */
2555 sa_new.sa_handler = SIG_IGN;
2556 sa_new.sa_flags = SA_RESTART;
2557 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2559 if (ioctl(fd, TIOCNOTTY) < 0)
2562 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2564 close_nointr_nofail(fd);
2568 int sigaction_many(const struct sigaction *sa, ...) {
2573 while ((sig = va_arg(ap, int)) > 0)
2574 if (sigaction(sig, sa, NULL) < 0)
2581 int ignore_signals(int sig, ...) {
2582 struct sigaction sa;
2587 sa.sa_handler = SIG_IGN;
2588 sa.sa_flags = SA_RESTART;
2590 if (sigaction(sig, &sa, NULL) < 0)
2594 while ((sig = va_arg(ap, int)) > 0)
2595 if (sigaction(sig, &sa, NULL) < 0)
2602 int default_signals(int sig, ...) {
2603 struct sigaction sa;
2608 sa.sa_handler = SIG_DFL;
2609 sa.sa_flags = SA_RESTART;
2611 if (sigaction(sig, &sa, NULL) < 0)
2615 while ((sig = va_arg(ap, int)) > 0)
2616 if (sigaction(sig, &sa, NULL) < 0)
2623 int close_pipe(int p[]) {
2629 a = close_nointr(p[0]);
2634 b = close_nointr(p[1]);
2638 return a < 0 ? a : b;
2641 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2650 while (nbytes > 0) {
2653 if ((k = read(fd, p, nbytes)) <= 0) {
2655 if (k < 0 && errno == EINTR)
2658 if (k < 0 && errno == EAGAIN && do_poll) {
2659 struct pollfd pollfd;
2663 pollfd.events = POLLIN;
2665 if (poll(&pollfd, 1, -1) < 0) {
2669 return n > 0 ? n : -errno;
2672 if (pollfd.revents != POLLIN)
2673 return n > 0 ? n : -EIO;
2678 return n > 0 ? n : (k < 0 ? -errno : 0);
2689 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2698 while (nbytes > 0) {
2701 if ((k = write(fd, p, nbytes)) <= 0) {
2703 if (k < 0 && errno == EINTR)
2706 if (k < 0 && errno == EAGAIN && do_poll) {
2707 struct pollfd pollfd;
2711 pollfd.events = POLLOUT;
2713 if (poll(&pollfd, 1, -1) < 0) {
2717 return n > 0 ? n : -errno;
2720 if (pollfd.revents != POLLOUT)
2721 return n > 0 ? n : -EIO;
2726 return n > 0 ? n : (k < 0 ? -errno : 0);
2737 int path_is_mount_point(const char *t) {
2742 if (lstat(t, &a) < 0) {
2743 if (errno == ENOENT)
2749 if ((r = parent_of_path(t, &parent)) < 0)
2752 r = lstat(parent, &b);
2758 return a.st_dev != b.st_dev;
2761 int parse_usec(const char *t, usec_t *usec) {
2762 static const struct {
2766 { "sec", USEC_PER_SEC },
2767 { "s", USEC_PER_SEC },
2768 { "min", USEC_PER_MINUTE },
2769 { "hr", USEC_PER_HOUR },
2770 { "h", USEC_PER_HOUR },
2771 { "d", USEC_PER_DAY },
2772 { "w", USEC_PER_WEEK },
2773 { "msec", USEC_PER_MSEC },
2774 { "ms", USEC_PER_MSEC },
2775 { "m", USEC_PER_MINUTE },
2778 { "", USEC_PER_SEC },
2794 l = strtoll(p, &e, 10);
2805 e += strspn(e, WHITESPACE);
2807 for (i = 0; i < ELEMENTSOF(table); i++)
2808 if (startswith(e, table[i].suffix)) {
2809 r += (usec_t) l * table[i].usec;
2810 p = e + strlen(table[i].suffix);
2814 if (i >= ELEMENTSOF(table))
2824 int make_stdio(int fd) {
2829 r = dup2(fd, STDIN_FILENO);
2830 s = dup2(fd, STDOUT_FILENO);
2831 t = dup2(fd, STDERR_FILENO);
2834 close_nointr_nofail(fd);
2836 if (r < 0 || s < 0 || t < 0)
2842 int make_null_stdio(void) {
2845 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2848 return make_stdio(null_fd);
2851 bool is_device_path(const char *path) {
2853 /* Returns true on paths that refer to a device, either in
2854 * sysfs or in /dev */
2857 path_startswith(path, "/dev/") ||
2858 path_startswith(path, "/sys/");
2861 int dir_is_empty(const char *path) {
2864 struct dirent buf, *de;
2866 if (!(d = opendir(path)))
2870 if ((r = readdir_r(d, &buf, &de)) > 0) {
2880 if (!ignore_file(de->d_name)) {
2890 unsigned long long random_ull(void) {
2895 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2898 r = loop_read(fd, &ull, sizeof(ull), true);
2899 close_nointr_nofail(fd);
2901 if (r != sizeof(ull))
2907 return random() * RAND_MAX + random();
2910 void rename_process(const char name[8]) {
2913 prctl(PR_SET_NAME, name);
2915 /* This is a like a poor man's setproctitle(). The string
2916 * passed should fit in 7 chars (i.e. the length of
2919 if (program_invocation_name)
2920 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2923 void sigset_add_many(sigset_t *ss, ...) {
2930 while ((sig = va_arg(ap, int)) > 0)
2931 assert_se(sigaddset(ss, sig) == 0);
2935 char* gethostname_malloc(void) {
2938 assert_se(uname(&u) >= 0);
2941 return strdup(u.nodename);
2943 return strdup(u.sysname);
2946 char* getlogname_malloc(void) {
2950 struct passwd pwbuf, *pw = NULL;
2953 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2958 /* Shortcut things to avoid NSS lookups */
2960 return strdup("root");
2962 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2965 if (!(buf = malloc(bufsize)))
2968 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2969 name = strdup(pw->pw_name);
2976 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2982 int getttyname_malloc(int fd, char **r) {
2983 char path[PATH_MAX], *c;
2988 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
2993 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3000 int getttyname_harder(int fd, char **r) {
3004 if ((k = getttyname_malloc(fd, &s)) < 0)
3007 if (streq(s, "tty")) {
3009 return get_ctty(r, NULL);
3016 int get_ctty_devnr(dev_t *d) {
3018 char line[LINE_MAX], *p;
3019 unsigned long ttynr;
3022 if (!(f = fopen("/proc/self/stat", "r")))
3025 if (!(fgets(line, sizeof(line), f))) {
3033 if (!(p = strrchr(line, ')')))
3042 "%*d " /* session */
3051 int get_ctty(char **r, dev_t *_devnr) {
3053 char fn[PATH_MAX], *s, *b, *p;
3058 if ((k = get_ctty_devnr(&devnr)) < 0)
3061 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3064 if ((k = readlink_malloc(fn, &s)) < 0) {
3069 /* This is an ugly hack */
3070 if (major(devnr) == 136) {
3071 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3081 /* Probably something like the ptys which have no
3082 * symlink in /dev/char. Let's return something
3083 * vaguely useful. */
3085 if (!(b = strdup(fn + 5)))
3095 if (startswith(s, "/dev/"))
3097 else if (startswith(s, "../"))
3115 static int rm_rf_children(int fd, bool only_dirs) {
3121 /* This returns the first error we run into, but nevertheless
3124 if (!(d = fdopendir(fd))) {
3125 close_nointr_nofail(fd);
3127 return errno == ENOENT ? 0 : -errno;
3131 struct dirent buf, *de;
3135 if ((r = readdir_r(d, &buf, &de)) != 0) {
3144 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3147 if (de->d_type == DT_UNKNOWN) {
3150 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3151 if (ret == 0 && errno != ENOENT)
3156 is_dir = S_ISDIR(st.st_mode);
3158 is_dir = de->d_type == DT_DIR;
3163 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3164 if (ret == 0 && errno != ENOENT)
3169 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3174 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3175 if (ret == 0 && errno != ENOENT)
3178 } else if (!only_dirs) {
3180 if (unlinkat(fd, de->d_name, 0) < 0) {
3181 if (ret == 0 && errno != ENOENT)
3192 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3198 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3200 if (errno != ENOTDIR)
3203 if (delete_root && !only_dirs)
3204 if (unlink(path) < 0)
3210 r = rm_rf_children(fd, only_dirs);
3213 if (rmdir(path) < 0) {
3221 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3224 /* Under the assumption that we are running privileged we
3225 * first change the access mode and only then hand out
3226 * ownership to avoid a window where access is too open. */
3228 if (chmod(path, mode) < 0)
3231 if (chown(path, uid, gid) < 0)
3237 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3241 /* Allocates the cpuset in the right size */
3244 if (!(r = CPU_ALLOC(n)))
3247 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3248 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3258 if (errno != EINVAL)
3265 void status_vprintf(const char *format, va_list ap) {
3271 /* This independent of logging, as status messages are
3272 * optional and go exclusively to the console. */
3274 if (vasprintf(&s, format, ap) < 0)
3277 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3280 write(fd, s, strlen(s));
3286 close_nointr_nofail(fd);
3289 void status_printf(const char *format, ...) {
3294 va_start(ap, format);
3295 status_vprintf(format, ap);
3299 void status_welcome(void) {
3300 char *pretty_name = NULL, *ansi_color = NULL;
3301 const char *const_pretty = NULL, *const_color = NULL;
3304 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3305 "PRETTY_NAME", &pretty_name,
3306 "ANSI_COLOR", &ansi_color,
3310 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3313 #if defined(TARGET_FEDORA)
3315 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3318 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3322 if (!ansi_color && pretty_name) {
3324 /* This tries to mimic the color magic the old Red Hat sysinit
3327 if (startswith(pretty_name, "Red Hat"))
3328 const_color = "0;31"; /* Red for RHEL */
3329 else if (startswith(pretty_name, "Fedora"))
3330 const_color = "0;34"; /* Blue for Fedora */
3333 #elif defined(TARGET_SUSE)
3336 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3339 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3344 const_color = "0;32"; /* Green for openSUSE */
3346 #elif defined(TARGET_GENTOO)
3349 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3352 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3357 const_color = "1;34"; /* Light Blue for Gentoo */
3359 #elif defined(TARGET_ALTLINUX)
3362 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3365 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3370 const_color = "0;36"; /* Cyan for ALTLinux */
3373 #elif defined(TARGET_DEBIAN)
3378 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3381 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3383 pretty_name = strappend("Debian ", version);
3387 log_warning("Failed to allocate Debian version string.");
3392 const_color = "1;31"; /* Light Red for Debian */
3394 #elif defined(TARGET_UBUNTU)
3396 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3397 "DISTRIB_DESCRIPTION", &pretty_name,
3401 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3405 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3407 #elif defined(TARGET_MANDRIVA)
3412 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3414 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3416 p = strstr(s, " release ");
3420 p[strcspn(p, " ")] = '\0';
3422 /* This corresponds to standard rc.sysinit */
3423 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3424 const_color = "1;36";
3426 log_warning("Failed to allocate Mandriva version string.");
3428 log_warning("Failed to parse /etc/mandriva-release");
3432 #elif defined(TARGET_MEEGO)
3435 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3438 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3443 const_color = "1;35"; /* Bright Magenta for MeeGo */
3446 if (!pretty_name && !const_pretty)
3447 const_pretty = "Linux";
3449 if (!ansi_color && !const_color)
3452 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3453 const_color ? const_color : ansi_color,
3454 const_pretty ? const_pretty : pretty_name);
3460 char *replace_env(const char *format, char **env) {
3467 const char *e, *word = format;
3472 for (e = format; *e; e ++) {
3483 if (!(k = strnappend(r, word, e-word-1)))
3492 } else if (*e == '$') {
3493 if (!(k = strnappend(r, word, e-word)))
3509 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3512 if (!(k = strappend(r, t)))
3525 if (!(k = strnappend(r, word, e-word)))
3536 char **replace_env_argv(char **argv, char **env) {
3538 unsigned k = 0, l = 0;
3540 l = strv_length(argv);
3542 if (!(r = new(char*, l+1)))
3545 STRV_FOREACH(i, argv) {
3547 /* If $FOO appears as single word, replace it by the split up variable */
3548 if ((*i)[0] == '$' && (*i)[1] != '{') {
3553 if ((e = strv_env_get(env, *i+1))) {
3555 if (!(m = strv_split_quoted(e))) {
3566 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3575 memcpy(r + k, m, q * sizeof(char*));
3583 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3584 if (!(r[k++] = replace_env(*i, env))) {
3595 static __thread int parsed_columns = 0;
3598 if (parsed_columns > 0)
3599 return parsed_columns;
3601 if ((e = getenv("COLUMNS")))
3602 parsed_columns = atoi(e);
3604 if (parsed_columns <= 0) {
3608 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3609 parsed_columns = ws.ws_col;
3612 if (parsed_columns <= 0)
3613 parsed_columns = 80;
3615 return parsed_columns;
3618 int running_in_chroot(void) {
3624 /* Only works as root */
3626 if (stat("/proc/1/root", &a) < 0)
3629 if (stat("/", &b) < 0)
3633 a.st_dev != b.st_dev ||
3634 a.st_ino != b.st_ino;
3637 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3642 assert(percent <= 100);
3643 assert(length >= 3);
3647 if (l <= 3 || l <= length)
3650 if (!(r = new0(char, length+1)))
3653 x = (length * percent) / 100;
3663 s + l - (length - x - 3),
3669 int touch(const char *path) {
3674 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3677 close_nointr_nofail(fd);
3681 char *unquote(const char *s, const char* quotes) {
3685 if ((l = strlen(s)) < 2)
3688 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3689 return strndup(s+1, l-2);
3694 char *normalize_env_assignment(const char *s) {
3695 char *name, *value, *p, *r;
3700 if (!(r = strdup(s)))
3706 if (!(name = strndup(s, p - s)))
3709 if (!(p = strdup(p+1))) {
3714 value = unquote(strstrip(p), QUOTES);
3722 if (asprintf(&r, "%s=%s", name, value) < 0)
3731 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3738 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3750 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3757 if ((r = wait_for_terminate(pid, &status)) < 0) {
3758 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3762 if (status.si_code == CLD_EXITED) {
3763 if (status.si_status != 0) {
3764 log_warning("%s failed with error code %i.", name, status.si_status);
3765 return status.si_status;
3768 log_debug("%s succeeded.", name);
3771 } else if (status.si_code == CLD_KILLED ||
3772 status.si_code == CLD_DUMPED) {
3774 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3778 log_warning("%s failed due to unknown reason.", name);
3785 /* Make sure nobody waits for us on a socket anymore */
3786 close_all_fds(NULL, 0);
3794 bool null_or_empty(struct stat *st) {
3797 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3800 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3806 DIR *xopendirat(int fd, const char *name, int flags) {
3810 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3813 if (!(d = fdopendir(nfd))) {
3814 close_nointr_nofail(nfd);
3821 int signal_from_string_try_harder(const char *s) {
3825 if ((signo = signal_from_string(s)) <= 0)
3826 if (startswith(s, "SIG"))
3827 return signal_from_string(s+3);
3832 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3838 if (!dual_timestamp_is_set(t))
3841 fprintf(f, "%s=%llu %llu\n",
3843 (unsigned long long) t->realtime,
3844 (unsigned long long) t->monotonic);
3847 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3848 unsigned long long a, b;
3853 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3854 log_debug("Failed to parse finish timestamp value %s", value);
3861 char *fstab_node_to_udev_node(const char *p) {
3865 /* FIXME: to follow udev's logic 100% we need to leave valid
3866 * UTF8 chars unescaped */
3868 if (startswith(p, "LABEL=")) {
3870 if (!(u = unquote(p+6, "\"\'")))
3873 t = xescape(u, "/ ");
3879 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3888 if (startswith(p, "UUID=")) {
3890 if (!(u = unquote(p+5, "\"\'")))
3893 t = xescape(u, "/ ");
3899 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
3911 void filter_environ(const char *prefix) {
3918 for (i = 0, j = 0; environ[i]; i++) {
3920 if (startswith(environ[i], prefix))
3923 environ[j++] = environ[i];
3929 bool tty_is_vc(const char *tty) {
3932 if (startswith(tty, "/dev/"))
3935 return startswith(tty, "tty") &&
3936 tty[3] >= '0' && tty[3] <= '9';
3939 const char *default_term_for_tty(const char *tty) {
3940 char *active = NULL;
3945 if (startswith(tty, "/dev/"))
3948 /* Resolve where /dev/console is pointing when determining
3950 if (streq(tty, "console"))
3951 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3952 /* If multiple log outputs are configured the
3953 * last one is what /dev/console points to */
3954 if ((tty = strrchr(active, ' ')))
3960 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
3966 /* Returns a short identifier for the various VM implementations */
3967 int detect_vm(const char **id) {
3969 #if defined(__i386__) || defined(__x86_64__)
3971 /* Both CPUID and DMI are x86 specific interfaces... */
3973 static const char *const dmi_vendors[] = {
3974 "/sys/class/dmi/id/sys_vendor",
3975 "/sys/class/dmi/id/board_vendor",
3976 "/sys/class/dmi/id/bios_vendor"
3979 static const char dmi_vendor_table[] =
3981 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3982 "VMware\0" "vmware\0"
3984 "Microsoft Corporation\0" "microsoft\0"
3985 "innotek GmbH\0" "oracle\0"
3987 "Bochs\0" "bochs\0";
3989 static const char cpuid_vendor_table[] =
3990 "XenVMMXenVMM\0" "xen\0"
3991 "KVMKVMKVM\0" "kvm\0"
3992 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3993 "VMwareVMware\0" "vmware\0"
3994 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
3995 "Microsoft Hv\0" "microsoft\0";
4006 /* http://lwn.net/Articles/301888/ */
4009 #if defined (__i386__)
4012 #elif defined (__amd64__)
4017 /* First detect whether there is a hypervisor */
4019 __asm__ __volatile__ (
4020 /* ebx/rbx is being used for PIC! */
4021 " push %%"REG_b" \n\t"
4023 " pop %%"REG_b" \n\t"
4025 : "=a" (eax), "=c" (ecx)
4029 hypervisor = !!(ecx & 0x80000000U);
4033 /* There is a hypervisor, see what it is */
4035 __asm__ __volatile__ (
4036 /* ebx/rbx is being used for PIC! */
4037 " push %%"REG_b" \n\t"
4039 " mov %%ebx, %1 \n\t"
4040 " pop %%"REG_b" \n\t"
4042 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
4046 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
4047 if (streq(sig.text, j)) {
4056 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
4059 const char *found = NULL;
4061 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
4068 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
4069 if (startswith(s, j))
4092 int detect_container(const char **id) {
4095 /* Unfortunately many of these operations require root access
4096 * in one way or another */
4101 if (running_in_chroot() > 0) {
4109 /* /proc/vz exists in container and outside of the container,
4110 * /proc/bc only outside of the container. */
4111 if (access("/proc/vz", F_OK) >= 0 &&
4112 access("/proc/bc", F_OK) < 0) {
4120 if ((f = fopen("/proc/self/cgroup", "r"))) {
4123 char line[LINE_MAX], *p;
4125 if (!fgets(line, sizeof(line), f))
4128 if (!(p = strchr(strstrip(line), ':')))
4131 if (strncmp(p, ":ns:", 4))
4134 if (!streq(p, ":ns:/")) {
4150 /* Returns a short identifier for the various VM/container implementations */
4151 int detect_virtualization(const char **id) {
4152 static __thread const char *cached_id = NULL;
4158 if (cached_id == (const char*) -1)
4167 if ((r = detect_container(&_id)) != 0)
4170 r = detect_vm(&_id);
4179 cached_id = (const char*) -1;
4184 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4187 Hashmap *pids = NULL;
4191 /* Executes all binaries in a directory in parallel and waits
4192 * until all they all finished. */
4195 if (!(_d = opendir(directory))) {
4197 if (errno == ENOENT)
4200 log_error("Failed to enumerate directory %s: %m", directory);
4207 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4208 log_error("Failed to allocate set.");
4212 while ((de = readdir(d))) {
4217 if (ignore_file(de->d_name))
4220 if (de->d_type != DT_REG &&
4221 de->d_type != DT_LNK &&
4222 de->d_type != DT_UNKNOWN)
4225 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4226 log_error("Out of memory");
4230 if ((pid = fork()) < 0) {
4231 log_error("Failed to fork: %m");
4250 log_error("Failed to execute %s: %m", path);
4251 _exit(EXIT_FAILURE);
4254 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4256 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4257 log_error("Failed to add PID to set: %s", strerror(-k));
4262 while (!hashmap_isempty(pids)) {
4267 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4272 log_error("waitid() failed: %m");
4276 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4277 if (!is_clean_exit(si.si_code, si.si_status)) {
4278 if (si.si_code == CLD_EXITED)
4279 log_error("%s exited with exit status %i.", path, si.si_status);
4281 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4283 log_debug("%s exited successfully.", path);
4294 hashmap_free_free(pids);
4297 int kill_and_sigcont(pid_t pid, int sig) {
4300 r = kill(pid, sig) < 0 ? -errno : 0;
4308 bool nulstr_contains(const char*nulstr, const char *needle) {
4314 NULSTR_FOREACH(i, nulstr)
4315 if (streq(i, needle))
4321 bool plymouth_running(void) {
4322 return access("/run/plymouth/pid", F_OK) >= 0;
4325 void parse_syslog_priority(char **p, int *priority) {
4326 int a = 0, b = 0, c = 0;
4336 if (!strchr(*p, '>'))
4339 if ((*p)[2] == '>') {
4340 c = undecchar((*p)[1]);
4342 } else if ((*p)[3] == '>') {
4343 b = undecchar((*p)[1]);
4344 c = undecchar((*p)[2]);
4346 } else if ((*p)[4] == '>') {
4347 a = undecchar((*p)[1]);
4348 b = undecchar((*p)[2]);
4349 c = undecchar((*p)[3]);
4354 if (a < 0 || b < 0 || c < 0)
4357 *priority = a*100+b*10+c;
4361 int have_effective_cap(int value) {
4363 cap_flag_value_t fv;
4366 if (!(cap = cap_get_proc()))
4369 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4378 char* strshorten(char *s, size_t l) {
4387 static bool hostname_valid_char(char c) {
4389 (c >= 'a' && c <= 'z') ||
4390 (c >= 'A' && c <= 'Z') ||
4391 (c >= '0' && c <= '9') ||
4397 bool hostname_is_valid(const char *s) {
4403 for (p = s; *p; p++)
4404 if (!hostname_valid_char(*p))
4407 if (p-s > HOST_NAME_MAX)
4413 char* hostname_cleanup(char *s) {
4416 for (p = s, d = s; *p; p++)
4417 if ((*p >= 'a' && *p <= 'z') ||
4418 (*p >= 'A' && *p <= 'Z') ||
4419 (*p >= '0' && *p <= '9') ||
4427 strshorten(s, HOST_NAME_MAX);
4431 int terminal_vhangup_fd(int fd) {
4432 if (ioctl(fd, TIOCVHANGUP) < 0)
4438 int terminal_vhangup(const char *name) {
4441 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4445 r = terminal_vhangup_fd(fd);
4446 close_nointr_nofail(fd);
4451 int vt_disallocate(const char *name) {
4455 /* Deallocate the VT if possible. If not possible
4456 * (i.e. because it is the active one), at least clear it
4457 * entirely (including the scrollback buffer) */
4459 if (!startswith(name, "/dev/"))
4462 if (!tty_is_vc(name)) {
4463 /* So this is not a VT. I guess we cannot deallocate
4464 * it then. But let's at least clear the screen */
4466 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4470 loop_write(fd, "\033[H\033[2J", 7, false); /* clear screen */
4471 close_nointr_nofail(fd);
4476 if (!startswith(name, "/dev/tty"))
4479 r = safe_atou(name+8, &u);
4486 /* Try to deallocate */
4487 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4491 r = ioctl(fd, VT_DISALLOCATE, u);
4492 close_nointr_nofail(fd);
4500 /* Couldn't deallocate, so let's clear it fully with
4502 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4506 /* Requires Linux 2.6.40 */
4507 loop_write(fd, "\033[H\033[3J", 7, false); /* clear screen including scrollback */
4508 close_nointr_nofail(fd);
4513 static const char *const ioprio_class_table[] = {
4514 [IOPRIO_CLASS_NONE] = "none",
4515 [IOPRIO_CLASS_RT] = "realtime",
4516 [IOPRIO_CLASS_BE] = "best-effort",
4517 [IOPRIO_CLASS_IDLE] = "idle"
4520 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
4522 static const char *const sigchld_code_table[] = {
4523 [CLD_EXITED] = "exited",
4524 [CLD_KILLED] = "killed",
4525 [CLD_DUMPED] = "dumped",
4526 [CLD_TRAPPED] = "trapped",
4527 [CLD_STOPPED] = "stopped",
4528 [CLD_CONTINUED] = "continued",
4531 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4533 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4534 [LOG_FAC(LOG_KERN)] = "kern",
4535 [LOG_FAC(LOG_USER)] = "user",
4536 [LOG_FAC(LOG_MAIL)] = "mail",
4537 [LOG_FAC(LOG_DAEMON)] = "daemon",
4538 [LOG_FAC(LOG_AUTH)] = "auth",
4539 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4540 [LOG_FAC(LOG_LPR)] = "lpr",
4541 [LOG_FAC(LOG_NEWS)] = "news",
4542 [LOG_FAC(LOG_UUCP)] = "uucp",
4543 [LOG_FAC(LOG_CRON)] = "cron",
4544 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4545 [LOG_FAC(LOG_FTP)] = "ftp",
4546 [LOG_FAC(LOG_LOCAL0)] = "local0",
4547 [LOG_FAC(LOG_LOCAL1)] = "local1",
4548 [LOG_FAC(LOG_LOCAL2)] = "local2",
4549 [LOG_FAC(LOG_LOCAL3)] = "local3",
4550 [LOG_FAC(LOG_LOCAL4)] = "local4",
4551 [LOG_FAC(LOG_LOCAL5)] = "local5",
4552 [LOG_FAC(LOG_LOCAL6)] = "local6",
4553 [LOG_FAC(LOG_LOCAL7)] = "local7"
4556 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
4558 static const char *const log_level_table[] = {
4559 [LOG_EMERG] = "emerg",
4560 [LOG_ALERT] = "alert",
4561 [LOG_CRIT] = "crit",
4563 [LOG_WARNING] = "warning",
4564 [LOG_NOTICE] = "notice",
4565 [LOG_INFO] = "info",
4566 [LOG_DEBUG] = "debug"
4569 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
4571 static const char* const sched_policy_table[] = {
4572 [SCHED_OTHER] = "other",
4573 [SCHED_BATCH] = "batch",
4574 [SCHED_IDLE] = "idle",
4575 [SCHED_FIFO] = "fifo",
4579 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
4581 static const char* const rlimit_table[] = {
4582 [RLIMIT_CPU] = "LimitCPU",
4583 [RLIMIT_FSIZE] = "LimitFSIZE",
4584 [RLIMIT_DATA] = "LimitDATA",
4585 [RLIMIT_STACK] = "LimitSTACK",
4586 [RLIMIT_CORE] = "LimitCORE",
4587 [RLIMIT_RSS] = "LimitRSS",
4588 [RLIMIT_NOFILE] = "LimitNOFILE",
4589 [RLIMIT_AS] = "LimitAS",
4590 [RLIMIT_NPROC] = "LimitNPROC",
4591 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4592 [RLIMIT_LOCKS] = "LimitLOCKS",
4593 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4594 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4595 [RLIMIT_NICE] = "LimitNICE",
4596 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4597 [RLIMIT_RTTIME] = "LimitRTTIME"
4600 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4602 static const char* const ip_tos_table[] = {
4603 [IPTOS_LOWDELAY] = "low-delay",
4604 [IPTOS_THROUGHPUT] = "throughput",
4605 [IPTOS_RELIABILITY] = "reliability",
4606 [IPTOS_LOWCOST] = "low-cost",
4609 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
4611 static const char *const signal_table[] = {
4628 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4639 [SIGVTALRM] = "VTALRM",
4641 [SIGWINCH] = "WINCH",
4647 DEFINE_STRING_TABLE_LOOKUP(signal, int);
4649 static int file_is_conf(const struct dirent *d, const char *suffix) {
4652 if (ignore_file(d->d_name))
4655 if (d->d_type != DT_REG &&
4656 d->d_type != DT_LNK &&
4657 d->d_type != DT_UNKNOWN)
4660 return endswith(d->d_name, suffix);
4663 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4668 dir = opendir(path);
4670 if (errno == ENOENT)
4675 for (de = readdir(dir); de; de = readdir(dir)) {
4679 if (!file_is_conf(de, suffix))
4682 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4687 f = canonicalize_file_name(p);
4689 log_error("Failed to canonicalize file name '%s': %m", p);
4695 log_debug("found: %s\n", f);
4696 base = f + strlen(path) + 1;
4697 if (hashmap_put(h, base, f) <= 0)
4706 static int base_cmp(const void *a, const void *b) {
4707 const char *s1, *s2;
4709 s1 = *(char * const *)a;
4710 s2 = *(char * const *)b;
4711 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4714 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
4717 char **files = NULL;
4723 dirs = strv_new_ap(dir, ap);
4729 if (!strv_path_canonicalize(dirs)) {
4733 if (!strv_uniq(dirs)) {
4738 fh = hashmap_new(string_hash_func, string_compare_func);
4744 STRV_FOREACH(p, dirs) {
4745 if (files_add(fh, *p, suffix) < 0) {
4746 log_error("Failed to search for files.");
4752 files = hashmap_get_strv(fh);
4753 if (files == NULL) {
4754 log_error("Failed to compose list of files.");
4759 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
4767 bool hwclock_is_localtime(void) {
4769 char line[LINE_MAX];
4773 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
4779 f = fopen("/etc/adjtime", "re");
4781 if (fgets(line, sizeof(line), f) &&
4782 fgets(line, sizeof(line), f) &&
4783 fgets(line, sizeof(line), f) ) {
4784 if (!strcmp(line, "LOCAL\n"))
4792 int hwclock_apply_localtime_delta(void) {
4793 const struct timeval *tv_null = NULL;
4799 gettimeofday(&tv, NULL);
4800 tm = localtime(&tv.tv_sec);
4801 minuteswest = tm->tm_gmtoff / 60;
4803 tz.tz_minuteswest = -minuteswest;
4804 tz.tz_dsttime = 0; /* DST_NONE*/
4807 * If the hardware clock does not run in UTC, but in local time:
4808 * The very first time we set the kernel's timezone, it will warp
4809 * the clock so that it runs in UTC instead of local time.
4811 if (settimeofday(tv_null, &tz) < 0)
4817 int hwclock_get_time(struct tm *tm) {
4821 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4824 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
4831 int hwclock_set_time(const struct tm *tm) {
4835 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4838 if (ioctl(fd, RTC_SET_TIME, tm) < 0)