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 char *file_in_same_dir(const char *path, const char *filename) {
1449 /* This removes the last component of path and appends
1450 * filename, unless the latter is absolute anyway or the
1453 if (path_is_absolute(filename))
1454 return strdup(filename);
1456 if (!(e = strrchr(path, '/')))
1457 return strdup(filename);
1459 k = strlen(filename);
1460 if (!(r = new(char, e-path+1+k+1)))
1463 memcpy(r, path, e-path+1);
1464 memcpy(r+(e-path)+1, filename, k+1);
1469 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1472 if (label_mkdir(path, mode) >= 0)
1473 if (chmod_and_chown(path, mode, uid, gid) < 0)
1476 if (lstat(path, &st) < 0)
1479 if ((st.st_mode & 0777) != mode ||
1482 !S_ISDIR(st.st_mode)) {
1491 int mkdir_parents(const char *path, mode_t mode) {
1496 /* Creates every parent directory in the path except the last
1499 p = path + strspn(path, "/");
1504 e = p + strcspn(p, "/");
1505 p = e + strspn(e, "/");
1507 /* Is this the last component? If so, then we're
1512 if (!(t = strndup(path, e - path)))
1515 r = label_mkdir(t, mode);
1518 if (r < 0 && errno != EEXIST)
1523 int mkdir_p(const char *path, mode_t mode) {
1528 if ((r = mkdir_parents(path, mode)) < 0)
1531 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1537 int rmdir_parents(const char *path, const char *stop) {
1546 /* Skip trailing slashes */
1547 while (l > 0 && path[l-1] == '/')
1553 /* Skip last component */
1554 while (l > 0 && path[l-1] != '/')
1557 /* Skip trailing slashes */
1558 while (l > 0 && path[l-1] == '/')
1564 if (!(t = strndup(path, l)))
1567 if (path_startswith(stop, t)) {
1576 if (errno != ENOENT)
1584 char hexchar(int x) {
1585 static const char table[16] = "0123456789abcdef";
1587 return table[x & 15];
1590 int unhexchar(char c) {
1592 if (c >= '0' && c <= '9')
1595 if (c >= 'a' && c <= 'f')
1596 return c - 'a' + 10;
1598 if (c >= 'A' && c <= 'F')
1599 return c - 'A' + 10;
1604 char octchar(int x) {
1605 return '0' + (x & 7);
1608 int unoctchar(char c) {
1610 if (c >= '0' && c <= '7')
1616 char decchar(int x) {
1617 return '0' + (x % 10);
1620 int undecchar(char c) {
1622 if (c >= '0' && c <= '9')
1628 char *cescape(const char *s) {
1634 /* Does C style string escaping. */
1636 if (!(r = new(char, strlen(s)*4 + 1)))
1639 for (f = s, t = r; *f; f++)
1685 /* For special chars we prefer octal over
1686 * hexadecimal encoding, simply because glib's
1687 * g_strescape() does the same */
1688 if ((*f < ' ') || (*f >= 127)) {
1690 *(t++) = octchar((unsigned char) *f >> 6);
1691 *(t++) = octchar((unsigned char) *f >> 3);
1692 *(t++) = octchar((unsigned char) *f);
1703 char *cunescape_length(const char *s, size_t length) {
1709 /* Undoes C style string escaping */
1711 if (!(r = new(char, length+1)))
1714 for (f = s, t = r; f < s + length; f++) {
1757 /* This is an extension of the XDG syntax files */
1762 /* hexadecimal encoding */
1765 if ((a = unhexchar(f[1])) < 0 ||
1766 (b = unhexchar(f[2])) < 0) {
1767 /* Invalid escape code, let's take it literal then */
1771 *(t++) = (char) ((a << 4) | b);
1786 /* octal encoding */
1789 if ((a = unoctchar(f[0])) < 0 ||
1790 (b = unoctchar(f[1])) < 0 ||
1791 (c = unoctchar(f[2])) < 0) {
1792 /* Invalid escape code, let's take it literal then */
1796 *(t++) = (char) ((a << 6) | (b << 3) | c);
1804 /* premature end of string.*/
1809 /* Invalid escape code, let's take it literal then */
1821 char *cunescape(const char *s) {
1822 return cunescape_length(s, strlen(s));
1825 char *xescape(const char *s, const char *bad) {
1829 /* Escapes all chars in bad, in addition to \ and all special
1830 * chars, in \xFF style escaping. May be reversed with
1833 if (!(r = new(char, strlen(s)*4+1)))
1836 for (f = s, t = r; *f; f++) {
1838 if ((*f < ' ') || (*f >= 127) ||
1839 (*f == '\\') || strchr(bad, *f)) {
1842 *(t++) = hexchar(*f >> 4);
1843 *(t++) = hexchar(*f);
1853 char *bus_path_escape(const char *s) {
1859 /* Escapes all chars that D-Bus' object path cannot deal
1860 * with. Can be reverse with bus_path_unescape() */
1862 if (!(r = new(char, strlen(s)*3+1)))
1865 for (f = s, t = r; *f; f++) {
1867 if (!(*f >= 'A' && *f <= 'Z') &&
1868 !(*f >= 'a' && *f <= 'z') &&
1869 !(*f >= '0' && *f <= '9')) {
1871 *(t++) = hexchar(*f >> 4);
1872 *(t++) = hexchar(*f);
1882 char *bus_path_unescape(const char *f) {
1887 if (!(r = strdup(f)))
1890 for (t = r; *f; f++) {
1895 if ((a = unhexchar(f[1])) < 0 ||
1896 (b = unhexchar(f[2])) < 0) {
1897 /* Invalid escape code, let's take it literal then */
1900 *(t++) = (char) ((a << 4) | b);
1912 char *path_kill_slashes(char *path) {
1916 /* Removes redundant inner and trailing slashes. Modifies the
1917 * passed string in-place.
1919 * ///foo///bar/ becomes /foo/bar
1922 for (f = path, t = path; *f; f++) {
1937 /* Special rule, if we are talking of the root directory, a
1938 trailing slash is good */
1940 if (t == path && slash)
1947 bool path_startswith(const char *path, const char *prefix) {
1951 if ((path[0] == '/') != (prefix[0] == '/'))
1957 path += strspn(path, "/");
1958 prefix += strspn(prefix, "/");
1966 a = strcspn(path, "/");
1967 b = strcspn(prefix, "/");
1972 if (memcmp(path, prefix, a) != 0)
1980 bool path_equal(const char *a, const char *b) {
1984 if ((a[0] == '/') != (b[0] == '/'))
1990 a += strspn(a, "/");
1991 b += strspn(b, "/");
1993 if (*a == 0 && *b == 0)
1996 if (*a == 0 || *b == 0)
1999 j = strcspn(a, "/");
2000 k = strcspn(b, "/");
2005 if (memcmp(a, b, j) != 0)
2013 char *ascii_strlower(char *t) {
2018 for (p = t; *p; p++)
2019 if (*p >= 'A' && *p <= 'Z')
2020 *p = *p - 'A' + 'a';
2025 bool ignore_file(const char *filename) {
2029 filename[0] == '.' ||
2030 streq(filename, "lost+found") ||
2031 streq(filename, "aquota.user") ||
2032 streq(filename, "aquota.group") ||
2033 endswith(filename, "~") ||
2034 endswith(filename, ".rpmnew") ||
2035 endswith(filename, ".rpmsave") ||
2036 endswith(filename, ".rpmorig") ||
2037 endswith(filename, ".dpkg-old") ||
2038 endswith(filename, ".dpkg-new") ||
2039 endswith(filename, ".swp");
2042 int fd_nonblock(int fd, bool nonblock) {
2047 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2051 flags |= O_NONBLOCK;
2053 flags &= ~O_NONBLOCK;
2055 if (fcntl(fd, F_SETFL, flags) < 0)
2061 int fd_cloexec(int fd, bool cloexec) {
2066 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2070 flags |= FD_CLOEXEC;
2072 flags &= ~FD_CLOEXEC;
2074 if (fcntl(fd, F_SETFD, flags) < 0)
2080 int close_all_fds(const int except[], unsigned n_except) {
2085 if (!(d = opendir("/proc/self/fd")))
2088 while ((de = readdir(d))) {
2091 if (ignore_file(de->d_name))
2094 if (safe_atoi(de->d_name, &fd) < 0)
2095 /* Let's better ignore this, just in case */
2109 for (i = 0; i < n_except; i++)
2110 if (except[i] == fd) {
2119 if (close_nointr(fd) < 0) {
2120 /* Valgrind has its own FD and doesn't want to have it closed */
2121 if (errno != EBADF && r == 0)
2130 bool chars_intersect(const char *a, const char *b) {
2133 /* Returns true if any of the chars in a are in b. */
2134 for (p = a; *p; p++)
2141 char *format_timestamp(char *buf, size_t l, usec_t t) {
2151 sec = (time_t) (t / USEC_PER_SEC);
2153 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2159 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2162 n = now(CLOCK_REALTIME);
2164 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2169 if (d >= USEC_PER_YEAR)
2170 snprintf(buf, l, "%llu years and %llu months ago",
2171 (unsigned long long) (d / USEC_PER_YEAR),
2172 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2173 else if (d >= USEC_PER_MONTH)
2174 snprintf(buf, l, "%llu months and %llu days ago",
2175 (unsigned long long) (d / USEC_PER_MONTH),
2176 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2177 else if (d >= USEC_PER_WEEK)
2178 snprintf(buf, l, "%llu weeks and %llu days ago",
2179 (unsigned long long) (d / USEC_PER_WEEK),
2180 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2181 else if (d >= 2*USEC_PER_DAY)
2182 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2183 else if (d >= 25*USEC_PER_HOUR)
2184 snprintf(buf, l, "1 day and %lluh ago",
2185 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2186 else if (d >= 6*USEC_PER_HOUR)
2187 snprintf(buf, l, "%lluh ago",
2188 (unsigned long long) (d / USEC_PER_HOUR));
2189 else if (d >= USEC_PER_HOUR)
2190 snprintf(buf, l, "%lluh %llumin ago",
2191 (unsigned long long) (d / USEC_PER_HOUR),
2192 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2193 else if (d >= 5*USEC_PER_MINUTE)
2194 snprintf(buf, l, "%llumin ago",
2195 (unsigned long long) (d / USEC_PER_MINUTE));
2196 else if (d >= USEC_PER_MINUTE)
2197 snprintf(buf, l, "%llumin %llus ago",
2198 (unsigned long long) (d / USEC_PER_MINUTE),
2199 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2200 else if (d >= USEC_PER_SEC)
2201 snprintf(buf, l, "%llus ago",
2202 (unsigned long long) (d / USEC_PER_SEC));
2203 else if (d >= USEC_PER_MSEC)
2204 snprintf(buf, l, "%llums ago",
2205 (unsigned long long) (d / USEC_PER_MSEC));
2207 snprintf(buf, l, "%lluus ago",
2208 (unsigned long long) d);
2210 snprintf(buf, l, "now");
2216 char *format_timespan(char *buf, size_t l, usec_t t) {
2217 static const struct {
2221 { "w", USEC_PER_WEEK },
2222 { "d", USEC_PER_DAY },
2223 { "h", USEC_PER_HOUR },
2224 { "min", USEC_PER_MINUTE },
2225 { "s", USEC_PER_SEC },
2226 { "ms", USEC_PER_MSEC },
2236 if (t == (usec_t) -1)
2240 snprintf(p, l, "0");
2245 /* The result of this function can be parsed with parse_usec */
2247 for (i = 0; i < ELEMENTSOF(table); i++) {
2251 if (t < table[i].usec)
2257 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2258 n = MIN((size_t) k, l);
2271 bool fstype_is_network(const char *fstype) {
2272 static const char * const table[] = {
2284 for (i = 0; i < ELEMENTSOF(table); i++)
2285 if (streq(table[i], fstype))
2294 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2299 TIOCL_GETKMSGREDIRECT,
2303 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2306 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2309 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2312 close_nointr_nofail(r);
2316 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2317 struct termios old_termios, new_termios;
2319 char line[LINE_MAX];
2324 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2325 new_termios = old_termios;
2327 new_termios.c_lflag &= ~ICANON;
2328 new_termios.c_cc[VMIN] = 1;
2329 new_termios.c_cc[VTIME] = 0;
2331 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2334 k = fread(&c, 1, 1, f);
2336 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2342 *need_nl = c != '\n';
2349 if (!(fgets(line, sizeof(line), f)))
2354 if (strlen(line) != 1)
2364 int ask(char *ret, const char *replies, const char *text, ...) {
2371 on_tty = isatty(STDOUT_FILENO);
2377 bool need_nl = true;
2380 fputs("\x1B[1m", stdout);
2387 fputs("\x1B[0m", stdout);
2391 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2393 if (r == -EBADMSG) {
2394 puts("Bad input, please try again.");
2405 if (strchr(replies, c)) {
2410 puts("Read unexpected character, please try again.");
2414 int reset_terminal_fd(int fd) {
2415 struct termios termios;
2419 /* Set terminal to some sane defaults */
2423 /* We leave locked terminal attributes untouched, so that
2424 * Plymouth may set whatever it wants to set, and we don't
2425 * interfere with that. */
2427 /* Disable exclusive mode, just in case */
2428 ioctl(fd, TIOCNXCL);
2430 /* Enable console unicode mode */
2432 ioctl(fd, KDSKBMODE, &arg);
2434 if (tcgetattr(fd, &termios) < 0) {
2439 /* We only reset the stuff that matters to the software. How
2440 * hardware is set up we don't touch assuming that somebody
2441 * else will do that for us */
2443 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2444 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2445 termios.c_oflag |= ONLCR;
2446 termios.c_cflag |= CREAD;
2447 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2449 termios.c_cc[VINTR] = 03; /* ^C */
2450 termios.c_cc[VQUIT] = 034; /* ^\ */
2451 termios.c_cc[VERASE] = 0177;
2452 termios.c_cc[VKILL] = 025; /* ^X */
2453 termios.c_cc[VEOF] = 04; /* ^D */
2454 termios.c_cc[VSTART] = 021; /* ^Q */
2455 termios.c_cc[VSTOP] = 023; /* ^S */
2456 termios.c_cc[VSUSP] = 032; /* ^Z */
2457 termios.c_cc[VLNEXT] = 026; /* ^V */
2458 termios.c_cc[VWERASE] = 027; /* ^W */
2459 termios.c_cc[VREPRINT] = 022; /* ^R */
2460 termios.c_cc[VEOL] = 0;
2461 termios.c_cc[VEOL2] = 0;
2463 termios.c_cc[VTIME] = 0;
2464 termios.c_cc[VMIN] = 1;
2466 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2470 /* Just in case, flush all crap out */
2471 tcflush(fd, TCIOFLUSH);
2476 int reset_terminal(const char *name) {
2479 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2483 r = reset_terminal_fd(fd);
2484 close_nointr_nofail(fd);
2489 int open_terminal(const char *name, int mode) {
2494 * If a TTY is in the process of being closed opening it might
2495 * cause EIO. This is horribly awful, but unlikely to be
2496 * changed in the kernel. Hence we work around this problem by
2497 * retrying a couple of times.
2499 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2503 if ((fd = open(name, mode)) >= 0)
2512 usleep(50 * USEC_PER_MSEC);
2519 if ((r = isatty(fd)) < 0) {
2520 close_nointr_nofail(fd);
2525 close_nointr_nofail(fd);
2532 int flush_fd(int fd) {
2533 struct pollfd pollfd;
2537 pollfd.events = POLLIN;
2544 if ((r = poll(&pollfd, 1, 0)) < 0) {
2555 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2560 if (errno == EAGAIN)
2571 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2572 int fd = -1, notify = -1, r, wd = -1;
2576 /* We use inotify to be notified when the tty is closed. We
2577 * create the watch before checking if we can actually acquire
2578 * it, so that we don't lose any event.
2580 * Note: strictly speaking this actually watches for the
2581 * device being closed, it does *not* really watch whether a
2582 * tty loses its controlling process. However, unless some
2583 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2584 * its tty otherwise this will not become a problem. As long
2585 * as the administrator makes sure not configure any service
2586 * on the same tty as an untrusted user this should not be a
2587 * problem. (Which he probably should not do anyway.) */
2589 if (!fail && !force) {
2590 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2595 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2603 if ((r = flush_fd(notify)) < 0)
2606 /* We pass here O_NOCTTY only so that we can check the return
2607 * value TIOCSCTTY and have a reliable way to figure out if we
2608 * successfully became the controlling process of the tty */
2609 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2612 /* First, try to get the tty */
2613 r = ioctl(fd, TIOCSCTTY, force);
2615 /* Sometimes it makes sense to ignore TIOCSCTTY
2616 * returning EPERM, i.e. when very likely we already
2617 * are have this controlling terminal. */
2618 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2621 if (r < 0 && (force || fail || errno != EPERM)) {
2631 assert(notify >= 0);
2634 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2636 struct inotify_event *e;
2638 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2647 e = (struct inotify_event*) inotify_buffer;
2652 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2657 step = sizeof(struct inotify_event) + e->len;
2658 assert(step <= (size_t) l);
2660 e = (struct inotify_event*) ((uint8_t*) e + step);
2667 /* We close the tty fd here since if the old session
2668 * ended our handle will be dead. It's important that
2669 * we do this after sleeping, so that we don't enter
2670 * an endless loop. */
2671 close_nointr_nofail(fd);
2675 close_nointr_nofail(notify);
2677 if ((r = reset_terminal_fd(fd)) < 0)
2678 log_warning("Failed to reset terminal: %s", strerror(-r));
2684 close_nointr_nofail(fd);
2687 close_nointr_nofail(notify);
2692 int release_terminal(void) {
2694 struct sigaction sa_old, sa_new;
2696 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2699 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2700 * by our own TIOCNOTTY */
2703 sa_new.sa_handler = SIG_IGN;
2704 sa_new.sa_flags = SA_RESTART;
2705 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2707 if (ioctl(fd, TIOCNOTTY) < 0)
2710 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2712 close_nointr_nofail(fd);
2716 int sigaction_many(const struct sigaction *sa, ...) {
2721 while ((sig = va_arg(ap, int)) > 0)
2722 if (sigaction(sig, sa, NULL) < 0)
2729 int ignore_signals(int sig, ...) {
2730 struct sigaction sa;
2735 sa.sa_handler = SIG_IGN;
2736 sa.sa_flags = SA_RESTART;
2738 if (sigaction(sig, &sa, NULL) < 0)
2742 while ((sig = va_arg(ap, int)) > 0)
2743 if (sigaction(sig, &sa, NULL) < 0)
2750 int default_signals(int sig, ...) {
2751 struct sigaction sa;
2756 sa.sa_handler = SIG_DFL;
2757 sa.sa_flags = SA_RESTART;
2759 if (sigaction(sig, &sa, NULL) < 0)
2763 while ((sig = va_arg(ap, int)) > 0)
2764 if (sigaction(sig, &sa, NULL) < 0)
2771 int close_pipe(int p[]) {
2777 a = close_nointr(p[0]);
2782 b = close_nointr(p[1]);
2786 return a < 0 ? a : b;
2789 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2798 while (nbytes > 0) {
2801 if ((k = read(fd, p, nbytes)) <= 0) {
2803 if (k < 0 && errno == EINTR)
2806 if (k < 0 && errno == EAGAIN && do_poll) {
2807 struct pollfd pollfd;
2811 pollfd.events = POLLIN;
2813 if (poll(&pollfd, 1, -1) < 0) {
2817 return n > 0 ? n : -errno;
2820 if (pollfd.revents != POLLIN)
2821 return n > 0 ? n : -EIO;
2826 return n > 0 ? n : (k < 0 ? -errno : 0);
2837 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2846 while (nbytes > 0) {
2849 if ((k = write(fd, p, nbytes)) <= 0) {
2851 if (k < 0 && errno == EINTR)
2854 if (k < 0 && errno == EAGAIN && do_poll) {
2855 struct pollfd pollfd;
2859 pollfd.events = POLLOUT;
2861 if (poll(&pollfd, 1, -1) < 0) {
2865 return n > 0 ? n : -errno;
2868 if (pollfd.revents != POLLOUT)
2869 return n > 0 ? n : -EIO;
2874 return n > 0 ? n : (k < 0 ? -errno : 0);
2885 int path_is_mount_point(const char *t) {
2890 if (lstat(t, &a) < 0) {
2891 if (errno == ENOENT)
2897 if ((r = parent_of_path(t, &parent)) < 0)
2900 r = lstat(parent, &b);
2906 return a.st_dev != b.st_dev;
2909 int parse_usec(const char *t, usec_t *usec) {
2910 static const struct {
2914 { "sec", USEC_PER_SEC },
2915 { "s", USEC_PER_SEC },
2916 { "min", USEC_PER_MINUTE },
2917 { "hr", USEC_PER_HOUR },
2918 { "h", USEC_PER_HOUR },
2919 { "d", USEC_PER_DAY },
2920 { "w", USEC_PER_WEEK },
2921 { "msec", USEC_PER_MSEC },
2922 { "ms", USEC_PER_MSEC },
2923 { "m", USEC_PER_MINUTE },
2926 { "", USEC_PER_SEC },
2942 l = strtoll(p, &e, 10);
2953 e += strspn(e, WHITESPACE);
2955 for (i = 0; i < ELEMENTSOF(table); i++)
2956 if (startswith(e, table[i].suffix)) {
2957 r += (usec_t) l * table[i].usec;
2958 p = e + strlen(table[i].suffix);
2962 if (i >= ELEMENTSOF(table))
2972 int make_stdio(int fd) {
2977 r = dup2(fd, STDIN_FILENO);
2978 s = dup2(fd, STDOUT_FILENO);
2979 t = dup2(fd, STDERR_FILENO);
2982 close_nointr_nofail(fd);
2984 if (r < 0 || s < 0 || t < 0)
2987 fd_cloexec(STDIN_FILENO, false);
2988 fd_cloexec(STDOUT_FILENO, false);
2989 fd_cloexec(STDERR_FILENO, false);
2994 int make_null_stdio(void) {
2997 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3000 return make_stdio(null_fd);
3003 bool is_device_path(const char *path) {
3005 /* Returns true on paths that refer to a device, either in
3006 * sysfs or in /dev */
3009 path_startswith(path, "/dev/") ||
3010 path_startswith(path, "/sys/");
3013 int dir_is_empty(const char *path) {
3016 struct dirent buf, *de;
3018 if (!(d = opendir(path)))
3022 if ((r = readdir_r(d, &buf, &de)) > 0) {
3032 if (!ignore_file(de->d_name)) {
3042 unsigned long long random_ull(void) {
3047 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3050 r = loop_read(fd, &ull, sizeof(ull), true);
3051 close_nointr_nofail(fd);
3053 if (r != sizeof(ull))
3059 return random() * RAND_MAX + random();
3062 void rename_process(const char name[8]) {
3065 prctl(PR_SET_NAME, name);
3067 /* This is a like a poor man's setproctitle(). The string
3068 * passed should fit in 7 chars (i.e. the length of
3071 if (program_invocation_name)
3072 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3074 if (saved_argc > 0) {
3078 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3080 for (i = 1; i < saved_argc; i++) {
3084 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3089 void sigset_add_many(sigset_t *ss, ...) {
3096 while ((sig = va_arg(ap, int)) > 0)
3097 assert_se(sigaddset(ss, sig) == 0);
3101 char* gethostname_malloc(void) {
3104 assert_se(uname(&u) >= 0);
3107 return strdup(u.nodename);
3109 return strdup(u.sysname);
3112 char* getlogname_malloc(void) {
3116 struct passwd pwbuf, *pw = NULL;
3119 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3124 /* Shortcut things to avoid NSS lookups */
3126 return strdup("root");
3128 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3131 if (!(buf = malloc(bufsize)))
3134 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3135 name = strdup(pw->pw_name);
3142 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3148 int getttyname_malloc(int fd, char **r) {
3149 char path[PATH_MAX], *c;
3154 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3159 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3166 int getttyname_harder(int fd, char **r) {
3170 if ((k = getttyname_malloc(fd, &s)) < 0)
3173 if (streq(s, "tty")) {
3175 return get_ctty(0, NULL, r);
3182 int get_ctty_devnr(pid_t pid, dev_t *d) {
3184 char line[LINE_MAX], *p, *fn;
3185 unsigned long ttynr;
3188 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3191 f = fopen(fn, "re");
3196 if (!fgets(line, sizeof(line), f)) {
3204 p = strrchr(line, ')');
3214 "%*d " /* session */
3223 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3225 char fn[PATH_MAX], *s, *b, *p;
3230 k = get_ctty_devnr(pid, &devnr);
3234 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3237 if ((k = readlink_malloc(fn, &s)) < 0) {
3242 /* This is an ugly hack */
3243 if (major(devnr) == 136) {
3244 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3254 /* Probably something like the ptys which have no
3255 * symlink in /dev/char. Let's return something
3256 * vaguely useful. */
3258 if (!(b = strdup(fn + 5)))
3268 if (startswith(s, "/dev/"))
3270 else if (startswith(s, "../"))
3288 static int rm_rf_children(int fd, bool only_dirs) {
3294 /* This returns the first error we run into, but nevertheless
3297 if (!(d = fdopendir(fd))) {
3298 close_nointr_nofail(fd);
3300 return errno == ENOENT ? 0 : -errno;
3304 struct dirent buf, *de;
3308 if ((r = readdir_r(d, &buf, &de)) != 0) {
3317 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3320 if (de->d_type == DT_UNKNOWN) {
3323 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3324 if (ret == 0 && errno != ENOENT)
3329 is_dir = S_ISDIR(st.st_mode);
3331 is_dir = de->d_type == DT_DIR;
3336 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3337 if (ret == 0 && errno != ENOENT)
3342 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3347 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3348 if (ret == 0 && errno != ENOENT)
3351 } else if (!only_dirs) {
3353 if (unlinkat(fd, de->d_name, 0) < 0) {
3354 if (ret == 0 && errno != ENOENT)
3365 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3371 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3373 if (errno != ENOTDIR)
3376 if (delete_root && !only_dirs)
3377 if (unlink(path) < 0)
3383 r = rm_rf_children(fd, only_dirs);
3386 if (rmdir(path) < 0) {
3394 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3397 /* Under the assumption that we are running privileged we
3398 * first change the access mode and only then hand out
3399 * ownership to avoid a window where access is too open. */
3401 if (chmod(path, mode) < 0)
3404 if (chown(path, uid, gid) < 0)
3410 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3414 /* Allocates the cpuset in the right size */
3417 if (!(r = CPU_ALLOC(n)))
3420 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3421 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3431 if (errno != EINVAL)
3438 void status_vprintf(const char *format, va_list ap) {
3444 /* This independent of logging, as status messages are
3445 * optional and go exclusively to the console. */
3447 if (vasprintf(&s, format, ap) < 0)
3450 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3453 write(fd, s, strlen(s));
3459 close_nointr_nofail(fd);
3462 void status_printf(const char *format, ...) {
3467 va_start(ap, format);
3468 status_vprintf(format, ap);
3472 void status_welcome(void) {
3473 char *pretty_name = NULL, *ansi_color = NULL;
3474 const char *const_pretty = NULL, *const_color = NULL;
3477 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3478 "PRETTY_NAME", &pretty_name,
3479 "ANSI_COLOR", &ansi_color,
3483 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3486 #if defined(TARGET_FEDORA)
3488 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3491 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3495 if (!ansi_color && pretty_name) {
3497 /* This tries to mimic the color magic the old Red Hat sysinit
3500 if (startswith(pretty_name, "Red Hat"))
3501 const_color = "0;31"; /* Red for RHEL */
3502 else if (startswith(pretty_name, "Fedora"))
3503 const_color = "0;34"; /* Blue for Fedora */
3506 #elif defined(TARGET_SUSE)
3509 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3512 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3517 const_color = "0;32"; /* Green for openSUSE */
3519 #elif defined(TARGET_GENTOO)
3522 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3525 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3530 const_color = "1;34"; /* Light Blue for Gentoo */
3532 #elif defined(TARGET_ALTLINUX)
3535 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3538 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3543 const_color = "0;36"; /* Cyan for ALTLinux */
3546 #elif defined(TARGET_DEBIAN)
3551 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3554 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3556 pretty_name = strappend("Debian ", version);
3560 log_warning("Failed to allocate Debian version string.");
3565 const_color = "1;31"; /* Light Red for Debian */
3567 #elif defined(TARGET_UBUNTU)
3569 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3570 "DISTRIB_DESCRIPTION", &pretty_name,
3574 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3578 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3580 #elif defined(TARGET_MANDRIVA)
3585 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3587 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3589 p = strstr(s, " release ");
3593 p[strcspn(p, " ")] = '\0';
3595 /* This corresponds to standard rc.sysinit */
3596 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3597 const_color = "1;36";
3599 log_warning("Failed to allocate Mandriva version string.");
3601 log_warning("Failed to parse /etc/mandriva-release");
3605 #elif defined(TARGET_MEEGO)
3608 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3611 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3616 const_color = "1;35"; /* Bright Magenta for MeeGo */
3619 if (!pretty_name && !const_pretty)
3620 const_pretty = "Linux";
3622 if (!ansi_color && !const_color)
3625 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3626 const_color ? const_color : ansi_color,
3627 const_pretty ? const_pretty : pretty_name);
3633 char *replace_env(const char *format, char **env) {
3640 const char *e, *word = format;
3645 for (e = format; *e; e ++) {
3656 if (!(k = strnappend(r, word, e-word-1)))
3665 } else if (*e == '$') {
3666 if (!(k = strnappend(r, word, e-word)))
3682 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3685 if (!(k = strappend(r, t)))
3698 if (!(k = strnappend(r, word, e-word)))
3709 char **replace_env_argv(char **argv, char **env) {
3711 unsigned k = 0, l = 0;
3713 l = strv_length(argv);
3715 if (!(r = new(char*, l+1)))
3718 STRV_FOREACH(i, argv) {
3720 /* If $FOO appears as single word, replace it by the split up variable */
3721 if ((*i)[0] == '$' && (*i)[1] != '{') {
3726 if ((e = strv_env_get(env, *i+1))) {
3728 if (!(m = strv_split_quoted(e))) {
3739 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3748 memcpy(r + k, m, q * sizeof(char*));
3756 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3757 if (!(r[k++] = replace_env(*i, env))) {
3768 static __thread int parsed_columns = 0;
3771 if (parsed_columns > 0)
3772 return parsed_columns;
3774 if ((e = getenv("COLUMNS")))
3775 parsed_columns = atoi(e);
3777 if (parsed_columns <= 0) {
3781 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3782 parsed_columns = ws.ws_col;
3785 if (parsed_columns <= 0)
3786 parsed_columns = 80;
3788 return parsed_columns;
3791 int running_in_chroot(void) {
3797 /* Only works as root */
3799 if (stat("/proc/1/root", &a) < 0)
3802 if (stat("/", &b) < 0)
3806 a.st_dev != b.st_dev ||
3807 a.st_ino != b.st_ino;
3810 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3815 assert(percent <= 100);
3816 assert(length >= 3);
3820 if (l <= 3 || l <= length)
3823 if (!(r = new0(char, length+1)))
3826 x = (length * percent) / 100;
3836 s + l - (length - x - 3),
3842 int touch(const char *path) {
3847 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3850 close_nointr_nofail(fd);
3854 char *unquote(const char *s, const char* quotes) {
3858 if ((l = strlen(s)) < 2)
3861 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3862 return strndup(s+1, l-2);
3867 char *normalize_env_assignment(const char *s) {
3868 char *name, *value, *p, *r;
3873 if (!(r = strdup(s)))
3879 if (!(name = strndup(s, p - s)))
3882 if (!(p = strdup(p+1))) {
3887 value = unquote(strstrip(p), QUOTES);
3895 if (asprintf(&r, "%s=%s", name, value) < 0)
3904 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3915 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3927 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3934 if ((r = wait_for_terminate(pid, &status)) < 0) {
3935 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3939 if (status.si_code == CLD_EXITED) {
3940 if (status.si_status != 0) {
3941 log_warning("%s failed with error code %i.", name, status.si_status);
3942 return status.si_status;
3945 log_debug("%s succeeded.", name);
3948 } else if (status.si_code == CLD_KILLED ||
3949 status.si_code == CLD_DUMPED) {
3951 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3955 log_warning("%s failed due to unknown reason.", name);
3962 /* Make sure nobody waits for us on a socket anymore */
3963 close_all_fds(NULL, 0);
3971 bool null_or_empty(struct stat *st) {
3974 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3977 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3983 int null_or_empty_path(const char *fn) {
3988 if (stat(fn, &st) < 0)
3991 return null_or_empty(&st);
3994 DIR *xopendirat(int fd, const char *name, int flags) {
3998 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4001 if (!(d = fdopendir(nfd))) {
4002 close_nointr_nofail(nfd);
4009 int signal_from_string_try_harder(const char *s) {
4013 if ((signo = signal_from_string(s)) <= 0)
4014 if (startswith(s, "SIG"))
4015 return signal_from_string(s+3);
4020 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4026 if (!dual_timestamp_is_set(t))
4029 fprintf(f, "%s=%llu %llu\n",
4031 (unsigned long long) t->realtime,
4032 (unsigned long long) t->monotonic);
4035 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4036 unsigned long long a, b;
4041 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4042 log_debug("Failed to parse finish timestamp value %s", value);
4049 char *fstab_node_to_udev_node(const char *p) {
4053 /* FIXME: to follow udev's logic 100% we need to leave valid
4054 * UTF8 chars unescaped */
4056 if (startswith(p, "LABEL=")) {
4058 if (!(u = unquote(p+6, "\"\'")))
4061 t = xescape(u, "/ ");
4067 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4076 if (startswith(p, "UUID=")) {
4078 if (!(u = unquote(p+5, "\"\'")))
4081 t = xescape(u, "/ ");
4087 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4099 void filter_environ(const char *prefix) {
4106 for (i = 0, j = 0; environ[i]; i++) {
4108 if (startswith(environ[i], prefix))
4111 environ[j++] = environ[i];
4117 bool tty_is_vc(const char *tty) {
4120 if (startswith(tty, "/dev/"))
4123 return vtnr_from_tty(tty) >= 0;
4126 int vtnr_from_tty(const char *tty) {
4131 if (startswith(tty, "/dev/"))
4134 if (!startswith(tty, "tty") )
4137 if (tty[3] < '0' || tty[3] > '9')
4140 r = safe_atoi(tty+3, &i);
4144 if (i < 0 || i > 63)
4150 const char *default_term_for_tty(const char *tty) {
4151 char *active = NULL;
4156 if (startswith(tty, "/dev/"))
4159 /* Resolve where /dev/console is pointing when determining
4161 if (streq(tty, "console"))
4162 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4163 /* If multiple log outputs are configured the
4164 * last one is what /dev/console points to */
4165 if ((tty = strrchr(active, ' ')))
4171 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
4177 /* Returns a short identifier for the various VM implementations */
4178 int detect_vm(const char **id) {
4180 #if defined(__i386__) || defined(__x86_64__)
4182 /* Both CPUID and DMI are x86 specific interfaces... */
4184 static const char *const dmi_vendors[] = {
4185 "/sys/class/dmi/id/sys_vendor",
4186 "/sys/class/dmi/id/board_vendor",
4187 "/sys/class/dmi/id/bios_vendor"
4190 static const char dmi_vendor_table[] =
4192 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4193 "VMware\0" "vmware\0"
4195 "Microsoft Corporation\0" "microsoft\0"
4196 "innotek GmbH\0" "oracle\0"
4198 "Bochs\0" "bochs\0";
4200 static const char cpuid_vendor_table[] =
4201 "XenVMMXenVMM\0" "xen\0"
4202 "KVMKVMKVM\0" "kvm\0"
4203 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4204 "VMwareVMware\0" "vmware\0"
4205 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
4206 "Microsoft Hv\0" "microsoft\0";
4217 /* http://lwn.net/Articles/301888/ */
4220 #if defined (__i386__)
4223 #elif defined (__amd64__)
4228 /* First detect whether there is a hypervisor */
4230 __asm__ __volatile__ (
4231 /* ebx/rbx is being used for PIC! */
4232 " push %%"REG_b" \n\t"
4234 " pop %%"REG_b" \n\t"
4236 : "=a" (eax), "=c" (ecx)
4240 hypervisor = !!(ecx & 0x80000000U);
4244 /* There is a hypervisor, see what it is */
4246 __asm__ __volatile__ (
4247 /* ebx/rbx is being used for PIC! */
4248 " push %%"REG_b" \n\t"
4250 " mov %%ebx, %1 \n\t"
4251 " pop %%"REG_b" \n\t"
4253 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
4257 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
4258 if (streq(sig.text, j)) {
4267 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
4270 const char *found = NULL;
4272 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
4279 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
4280 if (startswith(s, j))
4303 int detect_container(const char **id) {
4306 /* Unfortunately many of these operations require root access
4307 * in one way or another */
4312 if (running_in_chroot() > 0) {
4320 /* /proc/vz exists in container and outside of the container,
4321 * /proc/bc only outside of the container. */
4322 if (access("/proc/vz", F_OK) >= 0 &&
4323 access("/proc/bc", F_OK) < 0) {
4331 if ((f = fopen("/proc/self/cgroup", "re"))) {
4334 char line[LINE_MAX], *p;
4336 if (!fgets(line, sizeof(line), f))
4339 if (!(p = strchr(strstrip(line), ':')))
4342 if (strncmp(p, ":ns:", 4))
4345 if (!streq(p, ":ns:/")) {
4361 /* Returns a short identifier for the various VM/container implementations */
4362 int detect_virtualization(const char **id) {
4363 static __thread const char *cached_id = NULL;
4369 if (cached_id == (const char*) -1)
4378 if ((r = detect_container(&_id)) != 0)
4381 r = detect_vm(&_id);
4390 cached_id = (const char*) -1;
4395 bool dirent_is_file(struct dirent *de) {
4398 if (ignore_file(de->d_name))
4401 if (de->d_type != DT_REG &&
4402 de->d_type != DT_LNK &&
4403 de->d_type != DT_UNKNOWN)
4409 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4412 Hashmap *pids = NULL;
4416 /* Executes all binaries in a directory in parallel and waits
4417 * until all they all finished. */
4420 if (!(_d = opendir(directory))) {
4422 if (errno == ENOENT)
4425 log_error("Failed to enumerate directory %s: %m", directory);
4432 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4433 log_error("Failed to allocate set.");
4437 while ((de = readdir(d))) {
4442 if (!dirent_is_file(de))
4445 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4446 log_error("Out of memory");
4450 if ((pid = fork()) < 0) {
4451 log_error("Failed to fork: %m");
4470 log_error("Failed to execute %s: %m", path);
4471 _exit(EXIT_FAILURE);
4474 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4476 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4477 log_error("Failed to add PID to set: %s", strerror(-k));
4482 while (!hashmap_isempty(pids)) {
4487 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4492 log_error("waitid() failed: %m");
4496 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4497 if (!is_clean_exit(si.si_code, si.si_status)) {
4498 if (si.si_code == CLD_EXITED)
4499 log_error("%s exited with exit status %i.", path, si.si_status);
4501 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4503 log_debug("%s exited successfully.", path);
4514 hashmap_free_free(pids);
4517 int kill_and_sigcont(pid_t pid, int sig) {
4520 r = kill(pid, sig) < 0 ? -errno : 0;
4528 bool nulstr_contains(const char*nulstr, const char *needle) {
4534 NULSTR_FOREACH(i, nulstr)
4535 if (streq(i, needle))
4541 bool plymouth_running(void) {
4542 return access("/run/plymouth/pid", F_OK) >= 0;
4545 void parse_syslog_priority(char **p, int *priority) {
4546 int a = 0, b = 0, c = 0;
4556 if (!strchr(*p, '>'))
4559 if ((*p)[2] == '>') {
4560 c = undecchar((*p)[1]);
4562 } else if ((*p)[3] == '>') {
4563 b = undecchar((*p)[1]);
4564 c = undecchar((*p)[2]);
4566 } else if ((*p)[4] == '>') {
4567 a = undecchar((*p)[1]);
4568 b = undecchar((*p)[2]);
4569 c = undecchar((*p)[3]);
4574 if (a < 0 || b < 0 || c < 0)
4577 *priority = a*100+b*10+c;
4581 int have_effective_cap(int value) {
4583 cap_flag_value_t fv;
4586 if (!(cap = cap_get_proc()))
4589 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4598 char* strshorten(char *s, size_t l) {
4607 static bool hostname_valid_char(char c) {
4609 (c >= 'a' && c <= 'z') ||
4610 (c >= 'A' && c <= 'Z') ||
4611 (c >= '0' && c <= '9') ||
4617 bool hostname_is_valid(const char *s) {
4623 for (p = s; *p; p++)
4624 if (!hostname_valid_char(*p))
4627 if (p-s > HOST_NAME_MAX)
4633 char* hostname_cleanup(char *s) {
4636 for (p = s, d = s; *p; p++)
4637 if ((*p >= 'a' && *p <= 'z') ||
4638 (*p >= 'A' && *p <= 'Z') ||
4639 (*p >= '0' && *p <= '9') ||
4647 strshorten(s, HOST_NAME_MAX);
4651 int pipe_eof(int fd) {
4652 struct pollfd pollfd;
4657 pollfd.events = POLLIN|POLLHUP;
4659 r = poll(&pollfd, 1, 0);
4666 return pollfd.revents & POLLHUP;
4669 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4680 t = new(char, strlen(path) + 1 + 6 + 1);
4684 fn = file_name_from_path(path);
4688 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4690 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4696 f = fdopen(fd, "we");
4709 int terminal_vhangup_fd(int fd) {
4712 if (ioctl(fd, TIOCVHANGUP) < 0)
4718 int terminal_vhangup(const char *name) {
4721 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4725 r = terminal_vhangup_fd(fd);
4726 close_nointr_nofail(fd);
4731 int vt_disallocate(const char *name) {
4735 /* Deallocate the VT if possible. If not possible
4736 * (i.e. because it is the active one), at least clear it
4737 * entirely (including the scrollback buffer) */
4739 if (!startswith(name, "/dev/"))
4742 if (!tty_is_vc(name)) {
4743 /* So this is not a VT. I guess we cannot deallocate
4744 * it then. But let's at least clear the screen */
4746 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4751 "\033[r" /* clear scrolling region */
4752 "\033[H" /* move home */
4753 "\033[2J", /* clear screen */
4755 close_nointr_nofail(fd);
4760 if (!startswith(name, "/dev/tty"))
4763 r = safe_atou(name+8, &u);
4770 /* Try to deallocate */
4771 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4775 r = ioctl(fd, VT_DISALLOCATE, u);
4776 close_nointr_nofail(fd);
4784 /* Couldn't deallocate, so let's clear it fully with
4786 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4791 "\033[r" /* clear scrolling region */
4792 "\033[H" /* move home */
4793 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4795 close_nointr_nofail(fd);
4801 static int file_is_conf(const struct dirent *d, const char *suffix) {
4804 if (ignore_file(d->d_name))
4807 if (d->d_type != DT_REG &&
4808 d->d_type != DT_LNK &&
4809 d->d_type != DT_UNKNOWN)
4812 return endswith(d->d_name, suffix);
4815 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4817 struct dirent buffer, *de;
4820 dir = opendir(path);
4822 if (errno == ENOENT)
4831 k = readdir_r(dir, &buffer, &de);
4840 if (!file_is_conf(de, suffix))
4843 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4848 f = canonicalize_file_name(p);
4850 log_error("Failed to canonicalize file name '%s': %m", p);
4856 log_debug("found: %s\n", f);
4857 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
4866 static int base_cmp(const void *a, const void *b) {
4867 const char *s1, *s2;
4869 s1 = *(char * const *)a;
4870 s2 = *(char * const *)b;
4871 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4874 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
4877 char **files = NULL;
4883 dirs = strv_new_ap(dir, ap);
4889 if (!strv_path_canonicalize(dirs)) {
4893 if (!strv_uniq(dirs)) {
4898 fh = hashmap_new(string_hash_func, string_compare_func);
4904 STRV_FOREACH(p, dirs) {
4905 if (files_add(fh, *p, suffix) < 0) {
4906 log_error("Failed to search for files.");
4912 files = hashmap_get_strv(fh);
4913 if (files == NULL) {
4914 log_error("Failed to compose list of files.");
4919 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
4928 int hwclock_is_localtime(void) {
4933 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
4939 f = fopen("/etc/adjtime", "re");
4941 char line[LINE_MAX];
4944 b = fgets(line, sizeof(line), f) &&
4945 fgets(line, sizeof(line), f) &&
4946 fgets(line, sizeof(line), f);
4955 local = streq(line, "LOCAL");
4957 } else if (errno != -ENOENT)
4963 int hwclock_apply_localtime_delta(int *min) {
4964 const struct timeval *tv_null = NULL;
4970 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
4971 assert_se(tm = localtime(&ts.tv_sec));
4972 minuteswest = tm->tm_gmtoff / 60;
4974 tz.tz_minuteswest = -minuteswest;
4975 tz.tz_dsttime = 0; /* DST_NONE*/
4978 * If the hardware clock does not run in UTC, but in local time:
4979 * The very first time we set the kernel's timezone, it will warp
4980 * the clock so that it runs in UTC instead of local time.
4982 if (settimeofday(tv_null, &tz) < 0)
4989 int hwclock_reset_localtime_delta(void) {
4990 const struct timeval *tv_null = NULL;
4993 tz.tz_minuteswest = 0;
4994 tz.tz_dsttime = 0; /* DST_NONE*/
4996 if (settimeofday(tv_null, &tz) < 0)
5002 int hwclock_get_time(struct tm *tm) {
5008 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
5012 /* This leaves the timezone fields of struct tm
5014 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
5017 /* We don't now daylight saving, so we reset this in order not
5018 * to confused mktime(). */
5021 close_nointr_nofail(fd);
5026 int hwclock_set_time(const struct tm *tm) {
5032 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
5036 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5039 close_nointr_nofail(fd);
5044 int copy_file(const char *from, const char *to) {
5050 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5054 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5056 close_nointr_nofail(fdf);
5064 n = read(fdf, buf, sizeof(buf));
5068 close_nointr_nofail(fdf);
5079 k = loop_write(fdt, buf, n, false);
5081 r = k < 0 ? k : (errno ? -errno : -EIO);
5083 close_nointr_nofail(fdf);
5091 close_nointr_nofail(fdf);
5092 r = close_nointr(fdt);
5102 int symlink_or_copy(const char *from, const char *to) {
5103 char *pf = NULL, *pt = NULL;
5110 if (parent_of_path(from, &pf) < 0 ||
5111 parent_of_path(to, &pt) < 0) {
5116 if (stat(pf, &a) < 0 ||
5122 if (a.st_dev != b.st_dev) {
5126 return copy_file(from, to);
5129 if (symlink(from, to) < 0) {
5143 int symlink_or_copy_atomic(const char *from, const char *to) {
5147 unsigned long long ull;
5154 t = new(char, strlen(to) + 1 + 16 + 1);
5158 fn = file_name_from_path(to);
5162 x = stpcpy(t+k+1, fn);
5165 for (i = 0; i < 16; i++) {
5166 *(x++) = hexchar(ull & 0xF);
5172 r = symlink_or_copy(from, t);
5179 if (rename(t, to) < 0) {
5190 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5198 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5201 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5204 r = read_one_line_file(p, &s);
5209 r = safe_atou32(s, &u);
5215 if (u == (uint32_t) -1 || u <= 0)
5222 bool display_is_local(const char *display) {
5226 display[0] == ':' &&
5227 display[1] >= '0' &&
5231 int socket_from_display(const char *display, char **path) {
5238 if (!display_is_local(display))
5241 k = strspn(display+1, "0123456789");
5243 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5247 c = stpcpy(f, "/tmp/.X11-unix/X");
5248 memcpy(c, display+1, k);
5256 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5263 /* We enforce some special rules for uid=0: in order to avoid
5264 * NSS lookups for root we hardcode its data. */
5266 if (streq(*username, "root") || streq(*username, "0")) {
5280 if (parse_uid(*username, &u) >= 0) {
5284 /* If there are multiple users with the same id, make
5285 * sure to leave $USER to the configured value instead
5286 * of the first occurrence in the database. However if
5287 * the uid was configured by a numeric uid, then let's
5288 * pick the real username from /etc/passwd. */
5290 *username = p->pw_name;
5293 p = getpwnam(*username);
5297 return errno != 0 ? -errno : -ESRCH;
5311 int get_group_creds(const char **groupname, gid_t *gid) {
5317 /* We enforce some special rules for gid=0: in order to avoid
5318 * NSS lookups for root we hardcode its data. */
5320 if (streq(*groupname, "root") || streq(*groupname, "0")) {
5321 *groupname = "root";
5329 if (parse_gid(*groupname, &id) >= 0) {
5334 *groupname = g->gr_name;
5337 g = getgrnam(*groupname);
5341 return errno != 0 ? -errno : -ESRCH;
5349 int glob_exists(const char *path) {
5357 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5359 if (k == GLOB_NOMATCH)
5361 else if (k == GLOB_NOSPACE)
5364 r = !strv_isempty(g.gl_pathv);
5366 r = errno ? -errno : -EIO;
5373 int dirent_ensure_type(DIR *d, struct dirent *de) {
5379 if (de->d_type != DT_UNKNOWN)
5382 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5386 S_ISREG(st.st_mode) ? DT_REG :
5387 S_ISDIR(st.st_mode) ? DT_DIR :
5388 S_ISLNK(st.st_mode) ? DT_LNK :
5389 S_ISFIFO(st.st_mode) ? DT_FIFO :
5390 S_ISSOCK(st.st_mode) ? DT_SOCK :
5391 S_ISCHR(st.st_mode) ? DT_CHR :
5392 S_ISBLK(st.st_mode) ? DT_BLK :
5398 int in_search_path(const char *path, char **search) {
5402 r = parent_of_path(path, &parent);
5408 STRV_FOREACH(i, search) {
5409 if (path_equal(parent, *i)) {
5420 int get_files_in_directory(const char *path, char ***list) {
5428 /* Returns all files in a directory in *list, and the number
5429 * of files as return value. If list is NULL returns only the
5434 struct dirent buffer, *de;
5437 k = readdir_r(d, &buffer, &de);
5446 dirent_ensure_type(d, de);
5448 if (!dirent_is_file(de))
5452 if ((unsigned) r >= n) {
5456 t = realloc(l, sizeof(char*) * n);
5465 assert((unsigned) r < n);
5467 l[r] = strdup(de->d_name);
5491 char *join(const char *x, ...) {
5504 t = va_arg(ap, const char *);
5527 t = va_arg(ap, const char *);
5539 static const char *const ioprio_class_table[] = {
5540 [IOPRIO_CLASS_NONE] = "none",
5541 [IOPRIO_CLASS_RT] = "realtime",
5542 [IOPRIO_CLASS_BE] = "best-effort",
5543 [IOPRIO_CLASS_IDLE] = "idle"
5546 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5548 static const char *const sigchld_code_table[] = {
5549 [CLD_EXITED] = "exited",
5550 [CLD_KILLED] = "killed",
5551 [CLD_DUMPED] = "dumped",
5552 [CLD_TRAPPED] = "trapped",
5553 [CLD_STOPPED] = "stopped",
5554 [CLD_CONTINUED] = "continued",
5557 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5559 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5560 [LOG_FAC(LOG_KERN)] = "kern",
5561 [LOG_FAC(LOG_USER)] = "user",
5562 [LOG_FAC(LOG_MAIL)] = "mail",
5563 [LOG_FAC(LOG_DAEMON)] = "daemon",
5564 [LOG_FAC(LOG_AUTH)] = "auth",
5565 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5566 [LOG_FAC(LOG_LPR)] = "lpr",
5567 [LOG_FAC(LOG_NEWS)] = "news",
5568 [LOG_FAC(LOG_UUCP)] = "uucp",
5569 [LOG_FAC(LOG_CRON)] = "cron",
5570 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5571 [LOG_FAC(LOG_FTP)] = "ftp",
5572 [LOG_FAC(LOG_LOCAL0)] = "local0",
5573 [LOG_FAC(LOG_LOCAL1)] = "local1",
5574 [LOG_FAC(LOG_LOCAL2)] = "local2",
5575 [LOG_FAC(LOG_LOCAL3)] = "local3",
5576 [LOG_FAC(LOG_LOCAL4)] = "local4",
5577 [LOG_FAC(LOG_LOCAL5)] = "local5",
5578 [LOG_FAC(LOG_LOCAL6)] = "local6",
5579 [LOG_FAC(LOG_LOCAL7)] = "local7"
5582 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5584 static const char *const log_level_table[] = {
5585 [LOG_EMERG] = "emerg",
5586 [LOG_ALERT] = "alert",
5587 [LOG_CRIT] = "crit",
5589 [LOG_WARNING] = "warning",
5590 [LOG_NOTICE] = "notice",
5591 [LOG_INFO] = "info",
5592 [LOG_DEBUG] = "debug"
5595 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5597 static const char* const sched_policy_table[] = {
5598 [SCHED_OTHER] = "other",
5599 [SCHED_BATCH] = "batch",
5600 [SCHED_IDLE] = "idle",
5601 [SCHED_FIFO] = "fifo",
5605 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5607 static const char* const rlimit_table[] = {
5608 [RLIMIT_CPU] = "LimitCPU",
5609 [RLIMIT_FSIZE] = "LimitFSIZE",
5610 [RLIMIT_DATA] = "LimitDATA",
5611 [RLIMIT_STACK] = "LimitSTACK",
5612 [RLIMIT_CORE] = "LimitCORE",
5613 [RLIMIT_RSS] = "LimitRSS",
5614 [RLIMIT_NOFILE] = "LimitNOFILE",
5615 [RLIMIT_AS] = "LimitAS",
5616 [RLIMIT_NPROC] = "LimitNPROC",
5617 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5618 [RLIMIT_LOCKS] = "LimitLOCKS",
5619 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5620 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5621 [RLIMIT_NICE] = "LimitNICE",
5622 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5623 [RLIMIT_RTTIME] = "LimitRTTIME"
5626 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5628 static const char* const ip_tos_table[] = {
5629 [IPTOS_LOWDELAY] = "low-delay",
5630 [IPTOS_THROUGHPUT] = "throughput",
5631 [IPTOS_RELIABILITY] = "reliability",
5632 [IPTOS_LOWCOST] = "low-cost",
5635 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5637 static const char *const signal_table[] = {
5654 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5665 [SIGVTALRM] = "VTALRM",
5667 [SIGWINCH] = "WINCH",
5673 DEFINE_STRING_TABLE_LOOKUP(signal, int);