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>
66 #include "exit-status.h"
70 char **saved_argv = NULL;
72 size_t page_size(void) {
73 static __thread size_t pgsz = 0;
79 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
86 bool streq_ptr(const char *a, const char *b) {
88 /* Like streq(), but tries to make sense of NULL pointers */
99 usec_t now(clockid_t clock_id) {
102 assert_se(clock_gettime(clock_id, &ts) == 0);
104 return timespec_load(&ts);
107 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
110 ts->realtime = now(CLOCK_REALTIME);
111 ts->monotonic = now(CLOCK_MONOTONIC);
116 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
125 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
127 ts->monotonic = now(CLOCK_MONOTONIC);
129 if ((int64_t) ts->monotonic > delta)
130 ts->monotonic -= delta;
138 usec_t timespec_load(const struct timespec *ts) {
142 (usec_t) ts->tv_sec * USEC_PER_SEC +
143 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
146 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
149 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
150 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
155 usec_t timeval_load(const struct timeval *tv) {
159 (usec_t) tv->tv_sec * USEC_PER_SEC +
160 (usec_t) tv->tv_usec;
163 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
166 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
167 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
172 bool endswith(const char *s, const char *postfix) {
179 pl = strlen(postfix);
187 return memcmp(s + sl - pl, postfix, pl) == 0;
190 bool startswith(const char *s, const char *prefix) {
205 return memcmp(s, prefix, pl) == 0;
208 bool startswith_no_case(const char *s, const char *prefix) {
224 for(i = 0; i < pl; ++i) {
225 if (tolower(s[i]) != tolower(prefix[i]))
232 bool first_word(const char *s, const char *word) {
247 if (memcmp(s, word, wl) != 0)
251 strchr(WHITESPACE, s[wl]);
254 int close_nointr(int fd) {
269 void close_nointr_nofail(int fd) {
270 int saved_errno = errno;
272 /* like close_nointr() but cannot fail, and guarantees errno
275 assert_se(close_nointr(fd) == 0);
280 void close_many(const int fds[], unsigned n_fd) {
283 for (i = 0; i < n_fd; i++)
284 close_nointr_nofail(fds[i]);
287 int parse_boolean(const char *v) {
290 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
292 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
298 int parse_pid(const char *s, pid_t* ret_pid) {
299 unsigned long ul = 0;
306 if ((r = safe_atolu(s, &ul)) < 0)
311 if ((unsigned long) pid != ul)
321 int parse_uid(const char *s, uid_t* ret_uid) {
322 unsigned long ul = 0;
329 if ((r = safe_atolu(s, &ul)) < 0)
334 if ((unsigned long) uid != ul)
341 int safe_atou(const char *s, unsigned *ret_u) {
349 l = strtoul(s, &x, 0);
351 if (!x || *x || errno)
352 return errno ? -errno : -EINVAL;
354 if ((unsigned long) (unsigned) l != l)
357 *ret_u = (unsigned) l;
361 int safe_atoi(const char *s, int *ret_i) {
369 l = strtol(s, &x, 0);
371 if (!x || *x || errno)
372 return errno ? -errno : -EINVAL;
374 if ((long) (int) l != l)
381 int safe_atollu(const char *s, long long unsigned *ret_llu) {
383 unsigned long long l;
389 l = strtoull(s, &x, 0);
391 if (!x || *x || errno)
392 return errno ? -errno : -EINVAL;
398 int safe_atolli(const char *s, long long int *ret_lli) {
406 l = strtoll(s, &x, 0);
408 if (!x || *x || errno)
409 return errno ? -errno : -EINVAL;
415 /* Split a string into words. */
416 char *split(const char *c, size_t *l, const char *separator, char **state) {
419 current = *state ? *state : (char*) c;
421 if (!*current || *c == 0)
424 current += strspn(current, separator);
425 *l = strcspn(current, separator);
428 return (char*) current;
431 /* Split a string into words, but consider strings enclosed in '' and
432 * "" as words even if they include spaces. */
433 char *split_quoted(const char *c, size_t *l, char **state) {
435 bool escaped = false;
437 current = *state ? *state : (char*) c;
439 if (!*current || *c == 0)
442 current += strspn(current, WHITESPACE);
444 if (*current == '\'') {
447 for (e = current; *e; e++) {
457 *state = *e == 0 ? e : e+1;
458 } else if (*current == '\"') {
461 for (e = current; *e; e++) {
471 *state = *e == 0 ? e : e+1;
473 for (e = current; *e; e++) {
478 else if (strchr(WHITESPACE, *e))
485 return (char*) current;
488 char **split_path_and_make_absolute(const char *p) {
492 if (!(l = strv_split(p, ":")))
495 if (!strv_path_make_absolute_cwd(l)) {
503 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
506 char fn[PATH_MAX], line[LINE_MAX], *p;
512 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
515 if (!(f = fopen(fn, "re")))
518 if (!(fgets(line, sizeof(line), f))) {
526 /* Let's skip the pid and comm fields. The latter is enclosed
527 * in () but does not escape any () in its value, so let's
528 * skip over it manually */
530 if (!(p = strrchr(line, ')')))
541 if ((long unsigned) (pid_t) ppid != ppid)
544 *_ppid = (pid_t) ppid;
549 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
552 char fn[PATH_MAX], line[LINE_MAX], *p;
557 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
560 if (!(f = fopen(fn, "re")))
563 if (!(fgets(line, sizeof(line), f))) {
571 /* Let's skip the pid and comm fields. The latter is enclosed
572 * in () but does not escape any () in its value, so let's
573 * skip over it manually */
575 if (!(p = strrchr(line, ')')))
596 "%*d " /* priority */
598 "%*d " /* num_threads */
599 "%*d " /* itrealvalue */
600 "%llu " /* starttime */,
607 int write_one_line_file(const char *fn, const char *line) {
614 if (!(f = fopen(fn, "we")))
618 if (fputs(line, f) < 0) {
623 if (!endswith(line, "\n"))
641 int fchmod_umask(int fd, mode_t m) {
646 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
652 int write_one_line_file_atomic(const char *fn, const char *line) {
660 r = fopen_temporary(fn, &f, &p);
664 fchmod_umask(fileno(f), 0644);
667 if (fputs(line, f) < 0) {
672 if (!endswith(line, "\n"))
683 if (rename(p, fn) < 0)
699 int read_one_line_file(const char *fn, char **line) {
702 char t[LINE_MAX], *c;
707 if (!(f = fopen(fn, "re")))
710 if (!(fgets(t, sizeof(t), f))) {
715 if (!(c = strdup(t))) {
730 int read_full_file(const char *fn, char **contents, size_t *size) {
737 if (!(f = fopen(fn, "re")))
740 if (fstat(fileno(f), &st) < 0) {
746 if (st.st_size > 4*1024*1024) {
751 n = st.st_size > 0 ? st.st_size : LINE_MAX;
758 if (!(t = realloc(buf, n+1))) {
764 k = fread(buf + l, 1, n - l, f);
779 if (n > 4*1024*1024) {
787 else if (!(buf = calloc(1, 1))) {
809 const char *separator, ...) {
812 char *contents = NULL, *p;
817 if ((r = read_full_file(fname, &contents, NULL)) < 0)
822 const char *key = NULL;
824 p += strspn(p, separator);
825 p += strspn(p, WHITESPACE);
830 if (!strchr(COMMENTS, *p)) {
834 va_start(ap, separator);
835 while ((key = va_arg(ap, char *))) {
839 value = va_arg(ap, char **);
842 if (strncmp(p, key, n) != 0 ||
847 n = strcspn(p, separator);
850 strchr(QUOTES, p[0]) &&
852 v = strndup(p+1, n-2);
863 /* return empty value strings as NULL */
880 p += strcspn(p, separator);
899 if (!(f = fopen(fname, "re")))
903 char l[LINE_MAX], *p, *u;
906 if (!fgets(l, sizeof(l), f)) {
919 if (strchr(COMMENTS, *p))
922 if (!(u = normalize_env_assignment(p))) {
923 log_error("Out of memory");
928 t = strv_append(m, u);
932 log_error("Out of memory");
955 int write_env_file(const char *fname, char **l) {
960 r = fopen_temporary(fname, &f, &p);
964 fchmod_umask(fileno(f), 0644);
980 if (rename(p, fname) < 0)
995 char *truncate_nl(char *s) {
998 s[strcspn(s, NEWLINE)] = 0;
1002 int get_process_name(pid_t pid, char **name) {
1009 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
1012 r = read_one_line_file(p, name);
1021 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
1029 assert(max_length > 0);
1032 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1041 if (!(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[] */
1085 if ((h = get_process_name(pid, &t)) < 0)
1088 h = asprintf(&r, "[%s]", t);
1099 char *strnappend(const char *s, const char *suffix, size_t b) {
1107 return strndup(suffix, b);
1117 if (!(r = new(char, a+b+1)))
1121 memcpy(r+a, suffix, b);
1127 char *strappend(const char *s, const char *suffix) {
1128 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1131 int readlink_malloc(const char *p, char **r) {
1141 if (!(c = new(char, l)))
1144 if ((n = readlink(p, c, l-1)) < 0) {
1150 if ((size_t) n < l-1) {
1161 int readlink_and_make_absolute(const char *p, char **r) {
1168 if ((j = readlink_malloc(p, &target)) < 0)
1171 k = file_in_same_dir(p, target);
1181 int readlink_and_canonicalize(const char *p, char **r) {
1188 j = readlink_and_make_absolute(p, &t);
1192 s = canonicalize_file_name(t);
1199 path_kill_slashes(*r);
1204 int parent_of_path(const char *path, char **_r) {
1205 const char *e, *a = NULL, *b = NULL, *p;
1215 for (e = path; *e; e++) {
1217 if (!slash && *e == '/') {
1221 } else if (slash && *e != '/')
1236 r = strndup(path, p-path);
1246 char *file_name_from_path(const char *p) {
1251 if ((r = strrchr(p, '/')))
1257 bool path_is_absolute(const char *p) {
1263 bool is_path(const char *p) {
1265 return !!strchr(p, '/');
1268 char *path_make_absolute(const char *p, const char *prefix) {
1271 /* Makes every item in the list an absolute path by prepending
1272 * the prefix, if specified and necessary */
1274 if (path_is_absolute(p) || !prefix)
1277 return join(prefix, "/", p, NULL);
1280 char *path_make_absolute_cwd(const char *p) {
1285 /* Similar to path_make_absolute(), but prefixes with the
1286 * current working directory. */
1288 if (path_is_absolute(p))
1291 if (!(cwd = get_current_dir_name()))
1294 r = path_make_absolute(p, cwd);
1300 char **strv_path_make_absolute_cwd(char **l) {
1303 /* Goes through every item in the string list and makes it
1304 * absolute. This works in place and won't rollback any
1305 * changes on failure. */
1307 STRV_FOREACH(s, l) {
1310 if (!(t = path_make_absolute_cwd(*s)))
1320 char **strv_path_canonicalize(char **l) {
1323 bool enomem = false;
1325 if (strv_isempty(l))
1328 /* Goes through every item in the string list and canonicalize
1329 * the path. This works in place and won't rollback any
1330 * changes on failure. */
1332 STRV_FOREACH(s, l) {
1335 t = path_make_absolute_cwd(*s);
1344 u = canonicalize_file_name(t);
1348 if (errno == ENOMEM || !errno)
1365 char **strv_path_remove_empty(char **l) {
1371 for (f = t = l; *f; f++) {
1373 if (dir_is_empty(*f) > 0) {
1385 int reset_all_signal_handlers(void) {
1388 for (sig = 1; sig < _NSIG; sig++) {
1389 struct sigaction sa;
1391 if (sig == SIGKILL || sig == SIGSTOP)
1395 sa.sa_handler = SIG_DFL;
1396 sa.sa_flags = SA_RESTART;
1398 /* On Linux the first two RT signals are reserved by
1399 * glibc, and sigaction() will return EINVAL for them. */
1400 if ((sigaction(sig, &sa, NULL) < 0))
1401 if (errno != EINVAL)
1408 char *strstrip(char *s) {
1411 /* Drops trailing whitespace. Modifies the string in
1412 * place. Returns pointer to first non-space character */
1414 s += strspn(s, WHITESPACE);
1416 for (e = strchr(s, 0); e > s; e --)
1417 if (!strchr(WHITESPACE, e[-1]))
1425 char *delete_chars(char *s, const char *bad) {
1428 /* Drops all whitespace, regardless where in the string */
1430 for (f = s, t = s; *f; f++) {
1431 if (strchr(bad, *f))
1442 bool in_charset(const char *s, const char* charset) {
1448 for (i = s; *i; i++)
1449 if (!strchr(charset, *i))
1455 char *file_in_same_dir(const char *path, const char *filename) {
1462 /* This removes the last component of path and appends
1463 * filename, unless the latter is absolute anyway or the
1466 if (path_is_absolute(filename))
1467 return strdup(filename);
1469 if (!(e = strrchr(path, '/')))
1470 return strdup(filename);
1472 k = strlen(filename);
1473 if (!(r = new(char, e-path+1+k+1)))
1476 memcpy(r, path, e-path+1);
1477 memcpy(r+(e-path)+1, filename, k+1);
1482 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1485 if (label_mkdir(path, mode) >= 0)
1486 if (chmod_and_chown(path, mode, uid, gid) < 0)
1489 if (lstat(path, &st) < 0)
1492 if ((st.st_mode & 0777) != mode ||
1495 !S_ISDIR(st.st_mode)) {
1504 int mkdir_parents(const char *path, mode_t mode) {
1509 /* Creates every parent directory in the path except the last
1512 p = path + strspn(path, "/");
1517 e = p + strcspn(p, "/");
1518 p = e + strspn(e, "/");
1520 /* Is this the last component? If so, then we're
1525 if (!(t = strndup(path, e - path)))
1528 r = label_mkdir(t, mode);
1531 if (r < 0 && errno != EEXIST)
1536 int mkdir_p(const char *path, mode_t mode) {
1541 if ((r = mkdir_parents(path, mode)) < 0)
1544 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1550 int rmdir_parents(const char *path, const char *stop) {
1559 /* Skip trailing slashes */
1560 while (l > 0 && path[l-1] == '/')
1566 /* Skip last component */
1567 while (l > 0 && path[l-1] != '/')
1570 /* Skip trailing slashes */
1571 while (l > 0 && path[l-1] == '/')
1577 if (!(t = strndup(path, l)))
1580 if (path_startswith(stop, t)) {
1589 if (errno != ENOENT)
1597 char hexchar(int x) {
1598 static const char table[16] = "0123456789abcdef";
1600 return table[x & 15];
1603 int unhexchar(char c) {
1605 if (c >= '0' && c <= '9')
1608 if (c >= 'a' && c <= 'f')
1609 return c - 'a' + 10;
1611 if (c >= 'A' && c <= 'F')
1612 return c - 'A' + 10;
1617 char octchar(int x) {
1618 return '0' + (x & 7);
1621 int unoctchar(char c) {
1623 if (c >= '0' && c <= '7')
1629 char decchar(int x) {
1630 return '0' + (x % 10);
1633 int undecchar(char c) {
1635 if (c >= '0' && c <= '9')
1641 char *cescape(const char *s) {
1647 /* Does C style string escaping. */
1649 if (!(r = new(char, strlen(s)*4 + 1)))
1652 for (f = s, t = r; *f; f++)
1698 /* For special chars we prefer octal over
1699 * hexadecimal encoding, simply because glib's
1700 * g_strescape() does the same */
1701 if ((*f < ' ') || (*f >= 127)) {
1703 *(t++) = octchar((unsigned char) *f >> 6);
1704 *(t++) = octchar((unsigned char) *f >> 3);
1705 *(t++) = octchar((unsigned char) *f);
1716 char *cunescape_length(const char *s, size_t length) {
1722 /* Undoes C style string escaping */
1724 if (!(r = new(char, length+1)))
1727 for (f = s, t = r; f < s + length; f++) {
1770 /* This is an extension of the XDG syntax files */
1775 /* hexadecimal encoding */
1778 if ((a = unhexchar(f[1])) < 0 ||
1779 (b = unhexchar(f[2])) < 0) {
1780 /* Invalid escape code, let's take it literal then */
1784 *(t++) = (char) ((a << 4) | b);
1799 /* octal encoding */
1802 if ((a = unoctchar(f[0])) < 0 ||
1803 (b = unoctchar(f[1])) < 0 ||
1804 (c = unoctchar(f[2])) < 0) {
1805 /* Invalid escape code, let's take it literal then */
1809 *(t++) = (char) ((a << 6) | (b << 3) | c);
1817 /* premature end of string.*/
1822 /* Invalid escape code, let's take it literal then */
1834 char *cunescape(const char *s) {
1835 return cunescape_length(s, strlen(s));
1838 char *xescape(const char *s, const char *bad) {
1842 /* Escapes all chars in bad, in addition to \ and all special
1843 * chars, in \xFF style escaping. May be reversed with
1846 if (!(r = new(char, strlen(s)*4+1)))
1849 for (f = s, t = r; *f; f++) {
1851 if ((*f < ' ') || (*f >= 127) ||
1852 (*f == '\\') || strchr(bad, *f)) {
1855 *(t++) = hexchar(*f >> 4);
1856 *(t++) = hexchar(*f);
1866 char *bus_path_escape(const char *s) {
1872 /* Escapes all chars that D-Bus' object path cannot deal
1873 * with. Can be reverse with bus_path_unescape() */
1875 if (!(r = new(char, strlen(s)*3+1)))
1878 for (f = s, t = r; *f; f++) {
1880 if (!(*f >= 'A' && *f <= 'Z') &&
1881 !(*f >= 'a' && *f <= 'z') &&
1882 !(*f >= '0' && *f <= '9')) {
1884 *(t++) = hexchar(*f >> 4);
1885 *(t++) = hexchar(*f);
1895 char *bus_path_unescape(const char *f) {
1900 if (!(r = strdup(f)))
1903 for (t = r; *f; f++) {
1908 if ((a = unhexchar(f[1])) < 0 ||
1909 (b = unhexchar(f[2])) < 0) {
1910 /* Invalid escape code, let's take it literal then */
1913 *(t++) = (char) ((a << 4) | b);
1925 char *path_kill_slashes(char *path) {
1929 /* Removes redundant inner and trailing slashes. Modifies the
1930 * passed string in-place.
1932 * ///foo///bar/ becomes /foo/bar
1935 for (f = path, t = path; *f; f++) {
1950 /* Special rule, if we are talking of the root directory, a
1951 trailing slash is good */
1953 if (t == path && slash)
1960 bool path_startswith(const char *path, const char *prefix) {
1964 if ((path[0] == '/') != (prefix[0] == '/'))
1970 path += strspn(path, "/");
1971 prefix += strspn(prefix, "/");
1979 a = strcspn(path, "/");
1980 b = strcspn(prefix, "/");
1985 if (memcmp(path, prefix, a) != 0)
1993 bool path_equal(const char *a, const char *b) {
1997 if ((a[0] == '/') != (b[0] == '/'))
2003 a += strspn(a, "/");
2004 b += strspn(b, "/");
2006 if (*a == 0 && *b == 0)
2009 if (*a == 0 || *b == 0)
2012 j = strcspn(a, "/");
2013 k = strcspn(b, "/");
2018 if (memcmp(a, b, j) != 0)
2026 char *ascii_strlower(char *t) {
2031 for (p = t; *p; p++)
2032 if (*p >= 'A' && *p <= 'Z')
2033 *p = *p - 'A' + 'a';
2038 bool ignore_file(const char *filename) {
2042 filename[0] == '.' ||
2043 streq(filename, "lost+found") ||
2044 streq(filename, "aquota.user") ||
2045 streq(filename, "aquota.group") ||
2046 endswith(filename, "~") ||
2047 endswith(filename, ".rpmnew") ||
2048 endswith(filename, ".rpmsave") ||
2049 endswith(filename, ".rpmorig") ||
2050 endswith(filename, ".dpkg-old") ||
2051 endswith(filename, ".dpkg-new") ||
2052 endswith(filename, ".swp");
2055 int fd_nonblock(int fd, bool nonblock) {
2060 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2064 flags |= O_NONBLOCK;
2066 flags &= ~O_NONBLOCK;
2068 if (fcntl(fd, F_SETFL, flags) < 0)
2074 int fd_cloexec(int fd, bool cloexec) {
2079 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2083 flags |= FD_CLOEXEC;
2085 flags &= ~FD_CLOEXEC;
2087 if (fcntl(fd, F_SETFD, flags) < 0)
2093 int close_all_fds(const int except[], unsigned n_except) {
2098 if (!(d = opendir("/proc/self/fd")))
2101 while ((de = readdir(d))) {
2104 if (ignore_file(de->d_name))
2107 if (safe_atoi(de->d_name, &fd) < 0)
2108 /* Let's better ignore this, just in case */
2122 for (i = 0; i < n_except; i++)
2123 if (except[i] == fd) {
2132 if (close_nointr(fd) < 0) {
2133 /* Valgrind has its own FD and doesn't want to have it closed */
2134 if (errno != EBADF && r == 0)
2143 bool chars_intersect(const char *a, const char *b) {
2146 /* Returns true if any of the chars in a are in b. */
2147 for (p = a; *p; p++)
2154 char *format_timestamp(char *buf, size_t l, usec_t t) {
2164 sec = (time_t) (t / USEC_PER_SEC);
2166 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2172 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2175 n = now(CLOCK_REALTIME);
2177 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2182 if (d >= USEC_PER_YEAR)
2183 snprintf(buf, l, "%llu years and %llu months ago",
2184 (unsigned long long) (d / USEC_PER_YEAR),
2185 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2186 else if (d >= USEC_PER_MONTH)
2187 snprintf(buf, l, "%llu months and %llu days ago",
2188 (unsigned long long) (d / USEC_PER_MONTH),
2189 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2190 else if (d >= USEC_PER_WEEK)
2191 snprintf(buf, l, "%llu weeks and %llu days ago",
2192 (unsigned long long) (d / USEC_PER_WEEK),
2193 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2194 else if (d >= 2*USEC_PER_DAY)
2195 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2196 else if (d >= 25*USEC_PER_HOUR)
2197 snprintf(buf, l, "1 day and %lluh ago",
2198 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2199 else if (d >= 6*USEC_PER_HOUR)
2200 snprintf(buf, l, "%lluh ago",
2201 (unsigned long long) (d / USEC_PER_HOUR));
2202 else if (d >= USEC_PER_HOUR)
2203 snprintf(buf, l, "%lluh %llumin ago",
2204 (unsigned long long) (d / USEC_PER_HOUR),
2205 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2206 else if (d >= 5*USEC_PER_MINUTE)
2207 snprintf(buf, l, "%llumin ago",
2208 (unsigned long long) (d / USEC_PER_MINUTE));
2209 else if (d >= USEC_PER_MINUTE)
2210 snprintf(buf, l, "%llumin %llus ago",
2211 (unsigned long long) (d / USEC_PER_MINUTE),
2212 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2213 else if (d >= USEC_PER_SEC)
2214 snprintf(buf, l, "%llus ago",
2215 (unsigned long long) (d / USEC_PER_SEC));
2216 else if (d >= USEC_PER_MSEC)
2217 snprintf(buf, l, "%llums ago",
2218 (unsigned long long) (d / USEC_PER_MSEC));
2220 snprintf(buf, l, "%lluus ago",
2221 (unsigned long long) d);
2223 snprintf(buf, l, "now");
2229 char *format_timespan(char *buf, size_t l, usec_t t) {
2230 static const struct {
2234 { "w", USEC_PER_WEEK },
2235 { "d", USEC_PER_DAY },
2236 { "h", USEC_PER_HOUR },
2237 { "min", USEC_PER_MINUTE },
2238 { "s", USEC_PER_SEC },
2239 { "ms", USEC_PER_MSEC },
2249 if (t == (usec_t) -1)
2253 snprintf(p, l, "0");
2258 /* The result of this function can be parsed with parse_usec */
2260 for (i = 0; i < ELEMENTSOF(table); i++) {
2264 if (t < table[i].usec)
2270 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2271 n = MIN((size_t) k, l);
2284 bool fstype_is_network(const char *fstype) {
2285 static const char * const table[] = {
2297 for (i = 0; i < ELEMENTSOF(table); i++)
2298 if (streq(table[i], fstype))
2307 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2312 TIOCL_GETKMSGREDIRECT,
2316 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2319 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2322 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2325 close_nointr_nofail(r);
2329 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2330 struct termios old_termios, new_termios;
2332 char line[LINE_MAX];
2337 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2338 new_termios = old_termios;
2340 new_termios.c_lflag &= ~ICANON;
2341 new_termios.c_cc[VMIN] = 1;
2342 new_termios.c_cc[VTIME] = 0;
2344 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2347 k = fread(&c, 1, 1, f);
2349 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2355 *need_nl = c != '\n';
2362 if (!(fgets(line, sizeof(line), f)))
2367 if (strlen(line) != 1)
2377 int ask(char *ret, const char *replies, const char *text, ...) {
2384 on_tty = isatty(STDOUT_FILENO);
2390 bool need_nl = true;
2393 fputs("\x1B[1m", stdout);
2400 fputs("\x1B[0m", stdout);
2404 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2406 if (r == -EBADMSG) {
2407 puts("Bad input, please try again.");
2418 if (strchr(replies, c)) {
2423 puts("Read unexpected character, please try again.");
2427 int reset_terminal_fd(int fd) {
2428 struct termios termios;
2432 /* Set terminal to some sane defaults */
2436 /* We leave locked terminal attributes untouched, so that
2437 * Plymouth may set whatever it wants to set, and we don't
2438 * interfere with that. */
2440 /* Disable exclusive mode, just in case */
2441 ioctl(fd, TIOCNXCL);
2443 /* Enable console unicode mode */
2445 ioctl(fd, KDSKBMODE, &arg);
2447 if (tcgetattr(fd, &termios) < 0) {
2452 /* We only reset the stuff that matters to the software. How
2453 * hardware is set up we don't touch assuming that somebody
2454 * else will do that for us */
2456 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2457 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2458 termios.c_oflag |= ONLCR;
2459 termios.c_cflag |= CREAD;
2460 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2462 termios.c_cc[VINTR] = 03; /* ^C */
2463 termios.c_cc[VQUIT] = 034; /* ^\ */
2464 termios.c_cc[VERASE] = 0177;
2465 termios.c_cc[VKILL] = 025; /* ^X */
2466 termios.c_cc[VEOF] = 04; /* ^D */
2467 termios.c_cc[VSTART] = 021; /* ^Q */
2468 termios.c_cc[VSTOP] = 023; /* ^S */
2469 termios.c_cc[VSUSP] = 032; /* ^Z */
2470 termios.c_cc[VLNEXT] = 026; /* ^V */
2471 termios.c_cc[VWERASE] = 027; /* ^W */
2472 termios.c_cc[VREPRINT] = 022; /* ^R */
2473 termios.c_cc[VEOL] = 0;
2474 termios.c_cc[VEOL2] = 0;
2476 termios.c_cc[VTIME] = 0;
2477 termios.c_cc[VMIN] = 1;
2479 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2483 /* Just in case, flush all crap out */
2484 tcflush(fd, TCIOFLUSH);
2489 int reset_terminal(const char *name) {
2492 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2496 r = reset_terminal_fd(fd);
2497 close_nointr_nofail(fd);
2502 int open_terminal(const char *name, int mode) {
2507 * If a TTY is in the process of being closed opening it might
2508 * cause EIO. This is horribly awful, but unlikely to be
2509 * changed in the kernel. Hence we work around this problem by
2510 * retrying a couple of times.
2512 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2516 if ((fd = open(name, mode)) >= 0)
2525 usleep(50 * USEC_PER_MSEC);
2532 if ((r = isatty(fd)) < 0) {
2533 close_nointr_nofail(fd);
2538 close_nointr_nofail(fd);
2545 int flush_fd(int fd) {
2546 struct pollfd pollfd;
2550 pollfd.events = POLLIN;
2557 if ((r = poll(&pollfd, 1, 0)) < 0) {
2568 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2573 if (errno == EAGAIN)
2584 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2585 int fd = -1, notify = -1, r, wd = -1;
2589 /* We use inotify to be notified when the tty is closed. We
2590 * create the watch before checking if we can actually acquire
2591 * it, so that we don't lose any event.
2593 * Note: strictly speaking this actually watches for the
2594 * device being closed, it does *not* really watch whether a
2595 * tty loses its controlling process. However, unless some
2596 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2597 * its tty otherwise this will not become a problem. As long
2598 * as the administrator makes sure not configure any service
2599 * on the same tty as an untrusted user this should not be a
2600 * problem. (Which he probably should not do anyway.) */
2602 if (!fail && !force) {
2603 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2608 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2616 if ((r = flush_fd(notify)) < 0)
2619 /* We pass here O_NOCTTY only so that we can check the return
2620 * value TIOCSCTTY and have a reliable way to figure out if we
2621 * successfully became the controlling process of the tty */
2622 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2625 /* First, try to get the tty */
2626 r = ioctl(fd, TIOCSCTTY, force);
2628 /* Sometimes it makes sense to ignore TIOCSCTTY
2629 * returning EPERM, i.e. when very likely we already
2630 * are have this controlling terminal. */
2631 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2634 if (r < 0 && (force || fail || errno != EPERM)) {
2644 assert(notify >= 0);
2647 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2649 struct inotify_event *e;
2651 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2660 e = (struct inotify_event*) inotify_buffer;
2665 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2670 step = sizeof(struct inotify_event) + e->len;
2671 assert(step <= (size_t) l);
2673 e = (struct inotify_event*) ((uint8_t*) e + step);
2680 /* We close the tty fd here since if the old session
2681 * ended our handle will be dead. It's important that
2682 * we do this after sleeping, so that we don't enter
2683 * an endless loop. */
2684 close_nointr_nofail(fd);
2688 close_nointr_nofail(notify);
2690 if ((r = reset_terminal_fd(fd)) < 0)
2691 log_warning("Failed to reset terminal: %s", strerror(-r));
2697 close_nointr_nofail(fd);
2700 close_nointr_nofail(notify);
2705 int release_terminal(void) {
2707 struct sigaction sa_old, sa_new;
2709 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2712 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2713 * by our own TIOCNOTTY */
2716 sa_new.sa_handler = SIG_IGN;
2717 sa_new.sa_flags = SA_RESTART;
2718 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2720 if (ioctl(fd, TIOCNOTTY) < 0)
2723 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2725 close_nointr_nofail(fd);
2729 int sigaction_many(const struct sigaction *sa, ...) {
2734 while ((sig = va_arg(ap, int)) > 0)
2735 if (sigaction(sig, sa, NULL) < 0)
2742 int ignore_signals(int sig, ...) {
2743 struct sigaction sa;
2748 sa.sa_handler = SIG_IGN;
2749 sa.sa_flags = SA_RESTART;
2751 if (sigaction(sig, &sa, NULL) < 0)
2755 while ((sig = va_arg(ap, int)) > 0)
2756 if (sigaction(sig, &sa, NULL) < 0)
2763 int default_signals(int sig, ...) {
2764 struct sigaction sa;
2769 sa.sa_handler = SIG_DFL;
2770 sa.sa_flags = SA_RESTART;
2772 if (sigaction(sig, &sa, NULL) < 0)
2776 while ((sig = va_arg(ap, int)) > 0)
2777 if (sigaction(sig, &sa, NULL) < 0)
2784 int close_pipe(int p[]) {
2790 a = close_nointr(p[0]);
2795 b = close_nointr(p[1]);
2799 return a < 0 ? a : b;
2802 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2811 while (nbytes > 0) {
2814 if ((k = read(fd, p, nbytes)) <= 0) {
2816 if (k < 0 && errno == EINTR)
2819 if (k < 0 && errno == EAGAIN && do_poll) {
2820 struct pollfd pollfd;
2824 pollfd.events = POLLIN;
2826 if (poll(&pollfd, 1, -1) < 0) {
2830 return n > 0 ? n : -errno;
2833 if (pollfd.revents != POLLIN)
2834 return n > 0 ? n : -EIO;
2839 return n > 0 ? n : (k < 0 ? -errno : 0);
2850 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2859 while (nbytes > 0) {
2862 if ((k = write(fd, p, nbytes)) <= 0) {
2864 if (k < 0 && errno == EINTR)
2867 if (k < 0 && errno == EAGAIN && do_poll) {
2868 struct pollfd pollfd;
2872 pollfd.events = POLLOUT;
2874 if (poll(&pollfd, 1, -1) < 0) {
2878 return n > 0 ? n : -errno;
2881 if (pollfd.revents != POLLOUT)
2882 return n > 0 ? n : -EIO;
2887 return n > 0 ? n : (k < 0 ? -errno : 0);
2898 int path_is_mount_point(const char *t) {
2903 if (lstat(t, &a) < 0) {
2904 if (errno == ENOENT)
2910 if ((r = parent_of_path(t, &parent)) < 0)
2913 r = lstat(parent, &b);
2919 return a.st_dev != b.st_dev;
2922 int parse_usec(const char *t, usec_t *usec) {
2923 static const struct {
2927 { "sec", USEC_PER_SEC },
2928 { "s", USEC_PER_SEC },
2929 { "min", USEC_PER_MINUTE },
2930 { "hr", USEC_PER_HOUR },
2931 { "h", USEC_PER_HOUR },
2932 { "d", USEC_PER_DAY },
2933 { "w", USEC_PER_WEEK },
2934 { "msec", USEC_PER_MSEC },
2935 { "ms", USEC_PER_MSEC },
2936 { "m", USEC_PER_MINUTE },
2939 { "", USEC_PER_SEC },
2955 l = strtoll(p, &e, 10);
2966 e += strspn(e, WHITESPACE);
2968 for (i = 0; i < ELEMENTSOF(table); i++)
2969 if (startswith(e, table[i].suffix)) {
2970 r += (usec_t) l * table[i].usec;
2971 p = e + strlen(table[i].suffix);
2975 if (i >= ELEMENTSOF(table))
2985 int parse_bytes(const char *t, off_t *bytes) {
2986 static const struct {
2992 { "M", 1024ULL*1024ULL },
2993 { "G", 1024ULL*1024ULL*1024ULL },
2994 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3011 l = strtoll(p, &e, 10);
3022 e += strspn(e, WHITESPACE);
3024 for (i = 0; i < ELEMENTSOF(table); i++)
3025 if (startswith(e, table[i].suffix)) {
3026 r += (off_t) l * table[i].factor;
3027 p = e + strlen(table[i].suffix);
3031 if (i >= ELEMENTSOF(table))
3041 int make_stdio(int fd) {
3046 r = dup2(fd, STDIN_FILENO);
3047 s = dup2(fd, STDOUT_FILENO);
3048 t = dup2(fd, STDERR_FILENO);
3051 close_nointr_nofail(fd);
3053 if (r < 0 || s < 0 || t < 0)
3056 fd_cloexec(STDIN_FILENO, false);
3057 fd_cloexec(STDOUT_FILENO, false);
3058 fd_cloexec(STDERR_FILENO, false);
3063 int make_null_stdio(void) {
3066 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3069 return make_stdio(null_fd);
3072 bool is_device_path(const char *path) {
3074 /* Returns true on paths that refer to a device, either in
3075 * sysfs or in /dev */
3078 path_startswith(path, "/dev/") ||
3079 path_startswith(path, "/sys/");
3082 int dir_is_empty(const char *path) {
3085 struct dirent buf, *de;
3087 if (!(d = opendir(path)))
3091 if ((r = readdir_r(d, &buf, &de)) > 0) {
3101 if (!ignore_file(de->d_name)) {
3111 unsigned long long random_ull(void) {
3116 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3119 r = loop_read(fd, &ull, sizeof(ull), true);
3120 close_nointr_nofail(fd);
3122 if (r != sizeof(ull))
3128 return random() * RAND_MAX + random();
3131 void rename_process(const char name[8]) {
3134 prctl(PR_SET_NAME, name);
3136 /* This is a like a poor man's setproctitle(). The string
3137 * passed should fit in 7 chars (i.e. the length of
3140 if (program_invocation_name)
3141 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3143 if (saved_argc > 0) {
3147 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3149 for (i = 1; i < saved_argc; i++) {
3153 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3158 void sigset_add_many(sigset_t *ss, ...) {
3165 while ((sig = va_arg(ap, int)) > 0)
3166 assert_se(sigaddset(ss, sig) == 0);
3170 char* gethostname_malloc(void) {
3173 assert_se(uname(&u) >= 0);
3176 return strdup(u.nodename);
3178 return strdup(u.sysname);
3181 char* getlogname_malloc(void) {
3185 struct passwd pwbuf, *pw = NULL;
3188 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3193 /* Shortcut things to avoid NSS lookups */
3195 return strdup("root");
3197 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3200 if (!(buf = malloc(bufsize)))
3203 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3204 name = strdup(pw->pw_name);
3211 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3217 int getttyname_malloc(int fd, char **r) {
3218 char path[PATH_MAX], *c;
3223 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3228 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3235 int getttyname_harder(int fd, char **r) {
3239 if ((k = getttyname_malloc(fd, &s)) < 0)
3242 if (streq(s, "tty")) {
3244 return get_ctty(0, NULL, r);
3251 int get_ctty_devnr(pid_t pid, dev_t *d) {
3253 char line[LINE_MAX], *p, *fn;
3254 unsigned long ttynr;
3257 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3260 f = fopen(fn, "re");
3265 if (!fgets(line, sizeof(line), f)) {
3273 p = strrchr(line, ')');
3283 "%*d " /* session */
3292 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3294 char fn[PATH_MAX], *s, *b, *p;
3299 k = get_ctty_devnr(pid, &devnr);
3303 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3306 if ((k = readlink_malloc(fn, &s)) < 0) {
3311 /* This is an ugly hack */
3312 if (major(devnr) == 136) {
3313 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3323 /* Probably something like the ptys which have no
3324 * symlink in /dev/char. Let's return something
3325 * vaguely useful. */
3327 if (!(b = strdup(fn + 5)))
3337 if (startswith(s, "/dev/"))
3339 else if (startswith(s, "../"))
3357 static int rm_rf_children(int fd, bool only_dirs) {
3363 /* This returns the first error we run into, but nevertheless
3366 if (!(d = fdopendir(fd))) {
3367 close_nointr_nofail(fd);
3369 return errno == ENOENT ? 0 : -errno;
3373 struct dirent buf, *de;
3377 if ((r = readdir_r(d, &buf, &de)) != 0) {
3386 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3389 if (de->d_type == DT_UNKNOWN) {
3392 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3393 if (ret == 0 && errno != ENOENT)
3398 is_dir = S_ISDIR(st.st_mode);
3400 is_dir = de->d_type == DT_DIR;
3405 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3406 if (ret == 0 && errno != ENOENT)
3411 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3416 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3417 if (ret == 0 && errno != ENOENT)
3420 } else if (!only_dirs) {
3422 if (unlinkat(fd, de->d_name, 0) < 0) {
3423 if (ret == 0 && errno != ENOENT)
3434 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3440 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3442 if (errno != ENOTDIR)
3445 if (delete_root && !only_dirs)
3446 if (unlink(path) < 0)
3452 r = rm_rf_children(fd, only_dirs);
3455 if (rmdir(path) < 0) {
3463 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3466 /* Under the assumption that we are running privileged we
3467 * first change the access mode and only then hand out
3468 * ownership to avoid a window where access is too open. */
3470 if (chmod(path, mode) < 0)
3473 if (chown(path, uid, gid) < 0)
3479 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3483 /* Allocates the cpuset in the right size */
3486 if (!(r = CPU_ALLOC(n)))
3489 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3490 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3500 if (errno != EINVAL)
3507 void status_vprintf(const char *format, va_list ap) {