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 Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser 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>
58 #include <linux/magic.h>
70 #include "path-util.h"
71 #include "exit-status.h"
75 char **saved_argv = NULL;
77 static volatile unsigned cached_columns = 0;
78 static volatile unsigned cached_lines = 0;
80 bool is_efiboot(void) {
81 return access("/sys/firmware/efi", F_OK) >= 0;
84 size_t page_size(void) {
85 static __thread size_t pgsz = 0;
88 if (_likely_(pgsz > 0))
91 r = sysconf(_SC_PAGESIZE);
98 bool streq_ptr(const char *a, const char *b) {
100 /* Like streq(), but tries to make sense of NULL pointers */
111 char* endswith(const char *s, const char *postfix) {
118 pl = strlen(postfix);
121 return (char*) s + sl;
126 if (memcmp(s + sl - pl, postfix, pl) != 0)
129 return (char*) s + sl - pl;
132 char* startswith(const char *s, const char *prefix) {
149 char* startswith_no_case(const char *s, const char *prefix) {
159 if (tolower(*a) != tolower(*b))
166 bool first_word(const char *s, const char *word) {
181 if (memcmp(s, word, wl) != 0)
185 strchr(WHITESPACE, s[wl]);
188 int close_nointr(int fd) {
203 void close_nointr_nofail(int fd) {
204 int saved_errno = errno;
206 /* like close_nointr() but cannot fail, and guarantees errno
209 assert_se(close_nointr(fd) == 0);
214 void close_many(const int fds[], unsigned n_fd) {
217 for (i = 0; i < n_fd; i++)
218 close_nointr_nofail(fds[i]);
221 int parse_boolean(const char *v) {
224 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
226 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
232 int parse_pid(const char *s, pid_t* ret_pid) {
233 unsigned long ul = 0;
240 r = safe_atolu(s, &ul);
246 if ((unsigned long) pid != ul)
256 int parse_uid(const char *s, uid_t* ret_uid) {
257 unsigned long ul = 0;
264 r = safe_atolu(s, &ul);
270 if ((unsigned long) uid != ul)
277 int safe_atou(const char *s, unsigned *ret_u) {
285 l = strtoul(s, &x, 0);
287 if (!x || x == s || *x || errno)
288 return errno ? -errno : -EINVAL;
290 if ((unsigned long) (unsigned) l != l)
293 *ret_u = (unsigned) l;
297 int safe_atoi(const char *s, int *ret_i) {
305 l = strtol(s, &x, 0);
307 if (!x || x == s || *x || errno)
308 return errno ? -errno : -EINVAL;
310 if ((long) (int) l != l)
317 int safe_atollu(const char *s, long long unsigned *ret_llu) {
319 unsigned long long l;
325 l = strtoull(s, &x, 0);
327 if (!x || x == s || *x || errno)
328 return errno ? -errno : -EINVAL;
334 int safe_atolli(const char *s, long long int *ret_lli) {
342 l = strtoll(s, &x, 0);
344 if (!x || x == s || *x || errno)
345 return errno ? -errno : -EINVAL;
351 /* Split a string into words. */
352 char *split(const char *c, size_t *l, const char *separator, char **state) {
355 current = *state ? *state : (char*) c;
357 if (!*current || *c == 0)
360 current += strspn(current, separator);
361 *l = strcspn(current, separator);
364 return (char*) current;
367 /* Split a string into words, but consider strings enclosed in '' and
368 * "" as words even if they include spaces. */
369 char *split_quoted(const char *c, size_t *l, char **state) {
371 bool escaped = false;
373 current = *state ? *state : (char*) c;
375 if (!*current || *c == 0)
378 current += strspn(current, WHITESPACE);
380 if (*current == '\'') {
383 for (e = current; *e; e++) {
393 *state = *e == 0 ? e : e+1;
394 } else if (*current == '\"') {
397 for (e = current; *e; e++) {
407 *state = *e == 0 ? e : e+1;
409 for (e = current; *e; e++) {
414 else if (strchr(WHITESPACE, *e))
421 return (char*) current;
424 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
426 _cleanup_fclose_ FILE *f = NULL;
427 char fn[PATH_MAX], line[LINE_MAX], *p;
433 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
440 if (!fgets(line, sizeof(line), f)) {
441 r = feof(f) ? -EIO : -errno;
445 /* Let's skip the pid and comm fields. The latter is enclosed
446 * in () but does not escape any () in its value, so let's
447 * skip over it manually */
449 p = strrchr(line, ')');
461 if ((long unsigned) (pid_t) ppid != ppid)
464 *_ppid = (pid_t) ppid;
469 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
470 _cleanup_fclose_ FILE *f = NULL;
471 char fn[PATH_MAX], line[LINE_MAX], *p;
476 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
483 if (!fgets(line, sizeof(line), f)) {
490 /* Let's skip the pid and comm fields. The latter is enclosed
491 * in () but does not escape any () in its value, so let's
492 * skip over it manually */
494 p = strrchr(line, ')');
516 "%*d " /* priority */
518 "%*d " /* num_threads */
519 "%*d " /* itrealvalue */
520 "%llu " /* starttime */,
527 int write_one_line_file(const char *fn, const char *line) {
528 _cleanup_fclose_ FILE *f = NULL;
538 if (fputs(line, f) < 0)
539 return errno ? -errno : -EIO;
541 if (!endswith(line, "\n"))
547 return errno ? -errno : -EIO;
552 int fchmod_umask(int fd, mode_t m) {
557 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
563 int write_one_line_file_atomic(const char *fn, const char *line) {
571 r = fopen_temporary(fn, &f, &p);
575 fchmod_umask(fileno(f), 0644);
578 if (fputs(line, f) < 0) {
583 if (!endswith(line, "\n"))
594 if (rename(p, fn) < 0)
610 int read_one_line_file(const char *fn, char **line) {
611 _cleanup_fclose_ FILE *f = NULL;
612 char t[LINE_MAX], *c;
621 if (!fgets(t, sizeof(t), f)) {
624 return errno ? -errno : -EIO;
638 int read_full_file(const char *fn, char **contents, size_t *size) {
639 _cleanup_fclose_ FILE *f = NULL;
641 _cleanup_free_ char *buf = NULL;
651 if (fstat(fileno(f), &st) < 0)
655 if (st.st_size > 4*1024*1024)
658 n = st.st_size > 0 ? st.st_size : LINE_MAX;
665 t = realloc(buf, n+1);
670 k = fread(buf + l, 1, n - l, f);
699 const char *separator, ...) {
702 char *contents = NULL, *p;
707 if ((r = read_full_file(fname, &contents, NULL)) < 0)
712 const char *key = NULL;
714 p += strspn(p, separator);
715 p += strspn(p, WHITESPACE);
720 if (!strchr(COMMENTS, *p)) {
724 va_start(ap, separator);
725 while ((key = va_arg(ap, char *))) {
729 value = va_arg(ap, char **);
732 if (strncmp(p, key, n) != 0 ||
737 n = strcspn(p, separator);
740 strchr(QUOTES, p[0]) &&
742 v = strndup(p+1, n-2);
753 /* return empty value strings as NULL */
770 p += strcspn(p, separator);
778 int load_env_file(const char *fname,
781 FILE _cleanup_fclose_ *f;
783 char _cleanup_free_ *c = NULL;
784 char _cleanup_strv_free_ **m = NULL;
789 f = fopen(fname, "re");
794 char l[LINE_MAX], *p, *u, *cs;
797 if (!fgets(l, sizeof(l), f)) {
804 cs = endswith(l, "\\\n");
826 p = strstrip(c ? c : l);
831 if (strchr(COMMENTS, *p))
834 u = normalize_env_assignment(p);
841 t = strv_append(m, u);
857 int write_env_file(const char *fname, char **l) {
862 r = fopen_temporary(fname, &f, &p);
866 fchmod_umask(fileno(f), 0644);
882 if (rename(p, fname) < 0)
897 char *truncate_nl(char *s) {
900 s[strcspn(s, NEWLINE)] = 0;
904 int get_process_comm(pid_t pid, char **name) {
910 r = read_one_line_file("/proc/self/comm", name);
913 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
916 r = read_one_line_file(p, name);
923 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
931 f = fopen("/proc/self/cmdline", "re");
934 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
943 if (max_length == 0) {
945 while ((c = getc(f)) != EOF) {
946 k = realloc(r, len+1);
953 r[len-1] = isprint(c) ? c : ' ';
960 r = new(char, max_length);
968 while ((c = getc(f)) != EOF) {
990 size_t n = MIN(left-1, 3U);
999 /* Kernel threads have no argv[] */
1000 if (r == NULL || r[0] == 0) {
1009 h = get_process_comm(pid, &t);
1013 r = strjoin("[", t, "]", NULL);
1024 int is_kernel_thread(pid_t pid) {
1034 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1043 count = fread(&c, 1, 1, f);
1047 /* Kernel threads have an empty cmdline */
1050 return eof ? 1 : -errno;
1055 int get_process_exe(pid_t pid, char **name) {
1061 r = readlink_malloc("/proc/self/exe", name);
1064 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1067 r = readlink_malloc(p, name);
1074 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1084 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1094 char line[LINE_MAX], *l;
1096 if (!fgets(line, sizeof(line), f)) {
1106 if (startswith(l, field)) {
1108 l += strspn(l, WHITESPACE);
1110 l[strcspn(l, WHITESPACE)] = 0;
1112 r = parse_uid(l, uid);
1125 int get_process_uid(pid_t pid, uid_t *uid) {
1126 return get_process_id(pid, "Uid:", uid);
1129 int get_process_gid(pid_t pid, gid_t *gid) {
1130 return get_process_id(pid, "Gid:", gid);
1133 char *strnappend(const char *s, const char *suffix, size_t b) {
1141 return strndup(suffix, b);
1150 if (b > ((size_t) -1) - a)
1153 r = new(char, a+b+1);
1158 memcpy(r+a, suffix, b);
1164 char *strappend(const char *s, const char *suffix) {
1165 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1168 int readlink_malloc(const char *p, char **r) {
1178 if (!(c = new(char, l)))
1181 if ((n = readlink(p, c, l-1)) < 0) {
1187 if ((size_t) n < l-1) {
1198 int readlink_and_make_absolute(const char *p, char **r) {
1205 if ((j = readlink_malloc(p, &target)) < 0)
1208 k = file_in_same_dir(p, target);
1218 int readlink_and_canonicalize(const char *p, char **r) {
1225 j = readlink_and_make_absolute(p, &t);
1229 s = canonicalize_file_name(t);
1236 path_kill_slashes(*r);
1241 int reset_all_signal_handlers(void) {
1244 for (sig = 1; sig < _NSIG; sig++) {
1245 struct sigaction sa;
1247 if (sig == SIGKILL || sig == SIGSTOP)
1251 sa.sa_handler = SIG_DFL;
1252 sa.sa_flags = SA_RESTART;
1254 /* On Linux the first two RT signals are reserved by
1255 * glibc, and sigaction() will return EINVAL for them. */
1256 if ((sigaction(sig, &sa, NULL) < 0))
1257 if (errno != EINVAL)
1264 char *strstrip(char *s) {
1267 /* Drops trailing whitespace. Modifies the string in
1268 * place. Returns pointer to first non-space character */
1270 s += strspn(s, WHITESPACE);
1272 for (e = strchr(s, 0); e > s; e --)
1273 if (!strchr(WHITESPACE, e[-1]))
1281 char *delete_chars(char *s, const char *bad) {
1284 /* Drops all whitespace, regardless where in the string */
1286 for (f = s, t = s; *f; f++) {
1287 if (strchr(bad, *f))
1298 bool in_charset(const char *s, const char* charset) {
1304 for (i = s; *i; i++)
1305 if (!strchr(charset, *i))
1311 char *file_in_same_dir(const char *path, const char *filename) {
1318 /* This removes the last component of path and appends
1319 * filename, unless the latter is absolute anyway or the
1322 if (path_is_absolute(filename))
1323 return strdup(filename);
1325 if (!(e = strrchr(path, '/')))
1326 return strdup(filename);
1328 k = strlen(filename);
1329 if (!(r = new(char, e-path+1+k+1)))
1332 memcpy(r, path, e-path+1);
1333 memcpy(r+(e-path)+1, filename, k+1);
1338 int rmdir_parents(const char *path, const char *stop) {
1347 /* Skip trailing slashes */
1348 while (l > 0 && path[l-1] == '/')
1354 /* Skip last component */
1355 while (l > 0 && path[l-1] != '/')
1358 /* Skip trailing slashes */
1359 while (l > 0 && path[l-1] == '/')
1365 if (!(t = strndup(path, l)))
1368 if (path_startswith(stop, t)) {
1377 if (errno != ENOENT)
1385 char hexchar(int x) {
1386 static const char table[16] = "0123456789abcdef";
1388 return table[x & 15];
1391 int unhexchar(char c) {
1393 if (c >= '0' && c <= '9')
1396 if (c >= 'a' && c <= 'f')
1397 return c - 'a' + 10;
1399 if (c >= 'A' && c <= 'F')
1400 return c - 'A' + 10;
1405 char octchar(int x) {
1406 return '0' + (x & 7);
1409 int unoctchar(char c) {
1411 if (c >= '0' && c <= '7')
1417 char decchar(int x) {
1418 return '0' + (x % 10);
1421 int undecchar(char c) {
1423 if (c >= '0' && c <= '9')
1429 char *cescape(const char *s) {
1435 /* Does C style string escaping. */
1437 r = new(char, strlen(s)*4 + 1);
1441 for (f = s, t = r; *f; f++)
1487 /* For special chars we prefer octal over
1488 * hexadecimal encoding, simply because glib's
1489 * g_strescape() does the same */
1490 if ((*f < ' ') || (*f >= 127)) {
1492 *(t++) = octchar((unsigned char) *f >> 6);
1493 *(t++) = octchar((unsigned char) *f >> 3);
1494 *(t++) = octchar((unsigned char) *f);
1505 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1512 /* Undoes C style string escaping, and optionally prefixes it. */
1514 pl = prefix ? strlen(prefix) : 0;
1516 r = new(char, pl+length+1);
1521 memcpy(r, prefix, pl);
1523 for (f = s, t = r + pl; f < s + length; f++) {
1566 /* This is an extension of the XDG syntax files */
1571 /* hexadecimal encoding */
1574 a = unhexchar(f[1]);
1575 b = unhexchar(f[2]);
1577 if (a < 0 || b < 0) {
1578 /* Invalid escape code, let's take it literal then */
1582 *(t++) = (char) ((a << 4) | b);
1597 /* octal encoding */
1600 a = unoctchar(f[0]);
1601 b = unoctchar(f[1]);
1602 c = unoctchar(f[2]);
1604 if (a < 0 || b < 0 || c < 0) {
1605 /* Invalid escape code, let's take it literal then */
1609 *(t++) = (char) ((a << 6) | (b << 3) | c);
1617 /* premature end of string.*/
1622 /* Invalid escape code, let's take it literal then */
1634 char *cunescape_length(const char *s, size_t length) {
1635 return cunescape_length_with_prefix(s, length, NULL);
1638 char *cunescape(const char *s) {
1641 return cunescape_length(s, strlen(s));
1644 char *xescape(const char *s, const char *bad) {
1648 /* Escapes all chars in bad, in addition to \ and all special
1649 * chars, in \xFF style escaping. May be reversed with
1652 r = new(char, strlen(s) * 4 + 1);
1656 for (f = s, t = r; *f; f++) {
1658 if ((*f < ' ') || (*f >= 127) ||
1659 (*f == '\\') || strchr(bad, *f)) {
1662 *(t++) = hexchar(*f >> 4);
1663 *(t++) = hexchar(*f);
1673 char *bus_path_escape(const char *s) {
1679 /* Escapes all chars that D-Bus' object path cannot deal
1680 * with. Can be reverse with bus_path_unescape() */
1682 if (!(r = new(char, strlen(s)*3+1)))
1685 for (f = s, t = r; *f; f++) {
1687 if (!(*f >= 'A' && *f <= 'Z') &&
1688 !(*f >= 'a' && *f <= 'z') &&
1689 !(*f >= '0' && *f <= '9')) {
1691 *(t++) = hexchar(*f >> 4);
1692 *(t++) = hexchar(*f);
1702 char *bus_path_unescape(const char *f) {
1707 if (!(r = strdup(f)))
1710 for (t = r; *f; f++) {
1715 if ((a = unhexchar(f[1])) < 0 ||
1716 (b = unhexchar(f[2])) < 0) {
1717 /* Invalid escape code, let's take it literal then */
1720 *(t++) = (char) ((a << 4) | b);
1732 char *ascii_strlower(char *t) {
1737 for (p = t; *p; p++)
1738 if (*p >= 'A' && *p <= 'Z')
1739 *p = *p - 'A' + 'a';
1744 static bool ignore_file_allow_backup(const char *filename) {
1748 filename[0] == '.' ||
1749 streq(filename, "lost+found") ||
1750 streq(filename, "aquota.user") ||
1751 streq(filename, "aquota.group") ||
1752 endswith(filename, ".rpmnew") ||
1753 endswith(filename, ".rpmsave") ||
1754 endswith(filename, ".rpmorig") ||
1755 endswith(filename, ".dpkg-old") ||
1756 endswith(filename, ".dpkg-new") ||
1757 endswith(filename, ".swp");
1760 bool ignore_file(const char *filename) {
1763 if (endswith(filename, "~"))
1766 return ignore_file_allow_backup(filename);
1769 int fd_nonblock(int fd, bool nonblock) {
1774 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1778 flags |= O_NONBLOCK;
1780 flags &= ~O_NONBLOCK;
1782 if (fcntl(fd, F_SETFL, flags) < 0)
1788 int fd_cloexec(int fd, bool cloexec) {
1793 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1797 flags |= FD_CLOEXEC;
1799 flags &= ~FD_CLOEXEC;
1801 if (fcntl(fd, F_SETFD, flags) < 0)
1807 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1810 assert(n_fdset == 0 || fdset);
1812 for (i = 0; i < n_fdset; i++)
1819 int close_all_fds(const int except[], unsigned n_except) {
1824 assert(n_except == 0 || except);
1826 d = opendir("/proc/self/fd");
1831 /* When /proc isn't available (for example in chroots)
1832 * the fallback is brute forcing through the fd
1835 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1836 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1838 if (fd_in_set(fd, except, n_except))
1841 if (close_nointr(fd) < 0)
1842 if (errno != EBADF && r == 0)
1849 while ((de = readdir(d))) {
1852 if (ignore_file(de->d_name))
1855 if (safe_atoi(de->d_name, &fd) < 0)
1856 /* Let's better ignore this, just in case */
1865 if (fd_in_set(fd, except, n_except))
1868 if (close_nointr(fd) < 0) {
1869 /* Valgrind has its own FD and doesn't want to have it closed */
1870 if (errno != EBADF && r == 0)
1879 bool chars_intersect(const char *a, const char *b) {
1882 /* Returns true if any of the chars in a are in b. */
1883 for (p = a; *p; p++)
1890 bool fstype_is_network(const char *fstype) {
1891 static const char table[] =
1900 return nulstr_contains(table, fstype);
1904 _cleanup_close_ int fd;
1906 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1912 TIOCL_GETKMSGREDIRECT,
1916 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1919 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1922 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1928 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1929 struct termios old_termios, new_termios;
1931 char line[LINE_MAX];
1936 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1937 new_termios = old_termios;
1939 new_termios.c_lflag &= ~ICANON;
1940 new_termios.c_cc[VMIN] = 1;
1941 new_termios.c_cc[VTIME] = 0;
1943 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1946 if (t != (usec_t) -1) {
1947 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1948 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1953 k = fread(&c, 1, 1, f);
1955 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1961 *need_nl = c != '\n';
1968 if (t != (usec_t) -1)
1969 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1972 if (!fgets(line, sizeof(line), f))
1977 if (strlen(line) != 1)
1987 int ask(char *ret, const char *replies, const char *text, ...) {
1997 bool need_nl = true;
2000 fputs(ANSI_HIGHLIGHT_ON, stdout);
2007 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2011 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2014 if (r == -EBADMSG) {
2015 puts("Bad input, please try again.");
2026 if (strchr(replies, c)) {
2031 puts("Read unexpected character, please try again.");
2035 int reset_terminal_fd(int fd, bool switch_to_text) {
2036 struct termios termios;
2039 /* Set terminal to some sane defaults */
2043 /* We leave locked terminal attributes untouched, so that
2044 * Plymouth may set whatever it wants to set, and we don't
2045 * interfere with that. */
2047 /* Disable exclusive mode, just in case */
2048 ioctl(fd, TIOCNXCL);
2050 /* Switch to text mode */
2052 ioctl(fd, KDSETMODE, KD_TEXT);
2054 /* Enable console unicode mode */
2055 ioctl(fd, KDSKBMODE, K_UNICODE);
2057 if (tcgetattr(fd, &termios) < 0) {
2062 /* We only reset the stuff that matters to the software. How
2063 * hardware is set up we don't touch assuming that somebody
2064 * else will do that for us */
2066 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2067 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2068 termios.c_oflag |= ONLCR;
2069 termios.c_cflag |= CREAD;
2070 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2072 termios.c_cc[VINTR] = 03; /* ^C */
2073 termios.c_cc[VQUIT] = 034; /* ^\ */
2074 termios.c_cc[VERASE] = 0177;
2075 termios.c_cc[VKILL] = 025; /* ^X */
2076 termios.c_cc[VEOF] = 04; /* ^D */
2077 termios.c_cc[VSTART] = 021; /* ^Q */
2078 termios.c_cc[VSTOP] = 023; /* ^S */
2079 termios.c_cc[VSUSP] = 032; /* ^Z */
2080 termios.c_cc[VLNEXT] = 026; /* ^V */
2081 termios.c_cc[VWERASE] = 027; /* ^W */
2082 termios.c_cc[VREPRINT] = 022; /* ^R */
2083 termios.c_cc[VEOL] = 0;
2084 termios.c_cc[VEOL2] = 0;
2086 termios.c_cc[VTIME] = 0;
2087 termios.c_cc[VMIN] = 1;
2089 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2093 /* Just in case, flush all crap out */
2094 tcflush(fd, TCIOFLUSH);
2099 int reset_terminal(const char *name) {
2102 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2106 r = reset_terminal_fd(fd, true);
2107 close_nointr_nofail(fd);
2112 int open_terminal(const char *name, int mode) {
2117 * If a TTY is in the process of being closed opening it might
2118 * cause EIO. This is horribly awful, but unlikely to be
2119 * changed in the kernel. Hence we work around this problem by
2120 * retrying a couple of times.
2122 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2126 fd = open(name, mode);
2133 /* Max 1s in total */
2137 usleep(50 * USEC_PER_MSEC);
2146 close_nointr_nofail(fd);
2151 close_nointr_nofail(fd);
2158 int flush_fd(int fd) {
2159 struct pollfd pollfd;
2163 pollfd.events = POLLIN;
2170 if ((r = poll(&pollfd, 1, 0)) < 0) {
2181 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2186 if (errno == EAGAIN)
2197 int acquire_terminal(
2201 bool ignore_tiocstty_eperm,
2204 int fd = -1, notify = -1, r = 0, wd = -1;
2206 struct sigaction sa_old, sa_new;
2210 /* We use inotify to be notified when the tty is closed. We
2211 * create the watch before checking if we can actually acquire
2212 * it, so that we don't lose any event.
2214 * Note: strictly speaking this actually watches for the
2215 * device being closed, it does *not* really watch whether a
2216 * tty loses its controlling process. However, unless some
2217 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2218 * its tty otherwise this will not become a problem. As long
2219 * as the administrator makes sure not configure any service
2220 * on the same tty as an untrusted user this should not be a
2221 * problem. (Which he probably should not do anyway.) */
2223 if (timeout != (usec_t) -1)
2224 ts = now(CLOCK_MONOTONIC);
2226 if (!fail && !force) {
2227 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2233 wd = inotify_add_watch(notify, name, IN_CLOSE);
2242 r = flush_fd(notify);
2247 /* We pass here O_NOCTTY only so that we can check the return
2248 * value TIOCSCTTY and have a reliable way to figure out if we
2249 * successfully became the controlling process of the tty */
2250 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2254 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2255 * if we already own the tty. */
2257 sa_new.sa_handler = SIG_IGN;
2258 sa_new.sa_flags = SA_RESTART;
2259 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2261 /* First, try to get the tty */
2262 if (ioctl(fd, TIOCSCTTY, force) < 0)
2265 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2267 /* Sometimes it makes sense to ignore TIOCSCTTY
2268 * returning EPERM, i.e. when very likely we already
2269 * are have this controlling terminal. */
2270 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2273 if (r < 0 && (force || fail || r != -EPERM)) {
2282 assert(notify >= 0);
2285 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2287 struct inotify_event *e;
2289 if (timeout != (usec_t) -1) {
2292 n = now(CLOCK_MONOTONIC);
2293 if (ts + timeout < n) {
2298 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2308 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2311 if (errno == EINTR || errno == EAGAIN)
2318 e = (struct inotify_event*) inotify_buffer;
2323 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2328 step = sizeof(struct inotify_event) + e->len;
2329 assert(step <= (size_t) l);
2331 e = (struct inotify_event*) ((uint8_t*) e + step);
2338 /* We close the tty fd here since if the old session
2339 * ended our handle will be dead. It's important that
2340 * we do this after sleeping, so that we don't enter
2341 * an endless loop. */
2342 close_nointr_nofail(fd);
2346 close_nointr_nofail(notify);
2348 r = reset_terminal_fd(fd, true);
2350 log_warning("Failed to reset terminal: %s", strerror(-r));
2356 close_nointr_nofail(fd);
2359 close_nointr_nofail(notify);
2364 int release_terminal(void) {
2366 struct sigaction sa_old, sa_new;
2368 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2371 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2372 * by our own TIOCNOTTY */
2375 sa_new.sa_handler = SIG_IGN;
2376 sa_new.sa_flags = SA_RESTART;
2377 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2379 if (ioctl(fd, TIOCNOTTY) < 0)
2382 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2384 close_nointr_nofail(fd);
2388 int sigaction_many(const struct sigaction *sa, ...) {
2393 while ((sig = va_arg(ap, int)) > 0)
2394 if (sigaction(sig, sa, NULL) < 0)
2401 int ignore_signals(int sig, ...) {
2402 struct sigaction sa;
2407 sa.sa_handler = SIG_IGN;
2408 sa.sa_flags = SA_RESTART;
2410 if (sigaction(sig, &sa, NULL) < 0)
2414 while ((sig = va_arg(ap, int)) > 0)
2415 if (sigaction(sig, &sa, NULL) < 0)
2422 int default_signals(int sig, ...) {
2423 struct sigaction sa;
2428 sa.sa_handler = SIG_DFL;
2429 sa.sa_flags = SA_RESTART;
2431 if (sigaction(sig, &sa, NULL) < 0)
2435 while ((sig = va_arg(ap, int)) > 0)
2436 if (sigaction(sig, &sa, NULL) < 0)
2443 int close_pipe(int p[]) {
2449 a = close_nointr(p[0]);
2454 b = close_nointr(p[1]);
2458 return a < 0 ? a : b;
2461 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2470 while (nbytes > 0) {
2473 if ((k = read(fd, p, nbytes)) <= 0) {
2475 if (k < 0 && errno == EINTR)
2478 if (k < 0 && errno == EAGAIN && do_poll) {
2479 struct pollfd pollfd;
2483 pollfd.events = POLLIN;
2485 if (poll(&pollfd, 1, -1) < 0) {
2489 return n > 0 ? n : -errno;
2492 if (pollfd.revents != POLLIN)
2493 return n > 0 ? n : -EIO;
2498 return n > 0 ? n : (k < 0 ? -errno : 0);
2509 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2518 while (nbytes > 0) {
2521 k = write(fd, p, nbytes);
2524 if (k < 0 && errno == EINTR)
2527 if (k < 0 && errno == EAGAIN && do_poll) {
2528 struct pollfd pollfd;
2532 pollfd.events = POLLOUT;
2534 if (poll(&pollfd, 1, -1) < 0) {
2538 return n > 0 ? n : -errno;
2541 if (pollfd.revents != POLLOUT)
2542 return n > 0 ? n : -EIO;
2547 return n > 0 ? n : (k < 0 ? -errno : 0);
2558 int parse_bytes(const char *t, off_t *bytes) {
2559 static const struct {
2565 { "M", 1024ULL*1024ULL },
2566 { "G", 1024ULL*1024ULL*1024ULL },
2567 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2568 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2569 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2586 l = strtoll(p, &e, 10);
2597 e += strspn(e, WHITESPACE);
2599 for (i = 0; i < ELEMENTSOF(table); i++)
2600 if (startswith(e, table[i].suffix)) {
2601 r += (off_t) l * table[i].factor;
2602 p = e + strlen(table[i].suffix);
2606 if (i >= ELEMENTSOF(table))
2616 int make_stdio(int fd) {
2621 r = dup3(fd, STDIN_FILENO, 0);
2622 s = dup3(fd, STDOUT_FILENO, 0);
2623 t = dup3(fd, STDERR_FILENO, 0);
2626 close_nointr_nofail(fd);
2628 if (r < 0 || s < 0 || t < 0)
2631 /* We rely here that the new fd has O_CLOEXEC not set */
2636 int make_null_stdio(void) {
2639 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2643 return make_stdio(null_fd);
2646 bool is_device_path(const char *path) {
2648 /* Returns true on paths that refer to a device, either in
2649 * sysfs or in /dev */
2652 path_startswith(path, "/dev/") ||
2653 path_startswith(path, "/sys/");
2656 int dir_is_empty(const char *path) {
2657 _cleanup_closedir_ DIR *d;
2666 union dirent_storage buf;
2668 r = readdir_r(d, &buf.de, &de);
2675 if (!ignore_file(de->d_name))
2680 unsigned long long random_ull(void) {
2681 _cleanup_close_ int fd;
2685 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2689 r = loop_read(fd, &ull, sizeof(ull), true);
2690 if (r != sizeof(ull))
2696 return random() * RAND_MAX + random();
2699 void rename_process(const char name[8]) {
2702 /* This is a like a poor man's setproctitle(). It changes the
2703 * comm field, argv[0], and also the glibc's internally used
2704 * name of the process. For the first one a limit of 16 chars
2705 * applies, to the second one usually one of 10 (i.e. length
2706 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2707 * "systemd"). If you pass a longer string it will be
2710 prctl(PR_SET_NAME, name);
2712 if (program_invocation_name)
2713 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2715 if (saved_argc > 0) {
2719 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2721 for (i = 1; i < saved_argc; i++) {
2725 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2730 void sigset_add_many(sigset_t *ss, ...) {
2737 while ((sig = va_arg(ap, int)) > 0)
2738 assert_se(sigaddset(ss, sig) == 0);
2742 char* gethostname_malloc(void) {
2745 assert_se(uname(&u) >= 0);
2747 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2748 return strdup(u.nodename);
2750 return strdup(u.sysname);
2753 bool hostname_is_set(void) {
2756 assert_se(uname(&u) >= 0);
2758 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2761 static char *lookup_uid(uid_t uid) {
2764 _cleanup_free_ char *buf = NULL;
2765 struct passwd pwbuf, *pw = NULL;
2767 /* Shortcut things to avoid NSS lookups */
2769 return strdup("root");
2771 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2775 buf = malloc(bufsize);
2779 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2780 return strdup(pw->pw_name);
2782 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2788 char* getlogname_malloc(void) {
2792 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2797 return lookup_uid(uid);
2800 char *getusername_malloc(void) {
2807 return lookup_uid(getuid());
2810 int getttyname_malloc(int fd, char **r) {
2811 char path[PATH_MAX], *c;
2816 k = ttyname_r(fd, path, sizeof(path));
2822 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2830 int getttyname_harder(int fd, char **r) {
2834 k = getttyname_malloc(fd, &s);
2838 if (streq(s, "tty")) {
2840 return get_ctty(0, NULL, r);
2847 int get_ctty_devnr(pid_t pid, dev_t *d) {
2849 char line[LINE_MAX], *p, *fn;
2850 unsigned long ttynr;
2853 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2856 f = fopen(fn, "re");
2861 if (!fgets(line, sizeof(line), f)) {
2862 k = feof(f) ? -EIO : -errno;
2869 p = strrchr(line, ')');
2879 "%*d " /* session */
2884 if (major(ttynr) == 0 && minor(ttynr) == 0)
2891 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2893 char fn[PATH_MAX], *s, *b, *p;
2898 k = get_ctty_devnr(pid, &devnr);
2902 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2905 k = readlink_malloc(fn, &s);
2911 /* This is an ugly hack */
2912 if (major(devnr) == 136) {
2913 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2923 /* Probably something like the ptys which have no
2924 * symlink in /dev/char. Let's return something
2925 * vaguely useful. */
2938 if (startswith(s, "/dev/"))
2940 else if (startswith(s, "../"))
2958 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2964 /* This returns the first error we run into, but nevertheless
2965 * tries to go on. This closes the passed fd. */
2969 close_nointr_nofail(fd);
2971 return errno == ENOENT ? 0 : -errno;
2976 union dirent_storage buf;
2977 bool is_dir, keep_around;
2981 r = readdir_r(d, &buf.de, &de);
2982 if (r != 0 && ret == 0) {
2990 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2993 if (de->d_type == DT_UNKNOWN ||
2995 (de->d_type == DT_DIR && root_dev)) {
2996 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2997 if (ret == 0 && errno != ENOENT)
3002 is_dir = S_ISDIR(st.st_mode);
3005 (st.st_uid == 0 || st.st_uid == getuid()) &&
3006 (st.st_mode & S_ISVTX);
3008 is_dir = de->d_type == DT_DIR;
3009 keep_around = false;
3015 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3016 if (root_dev && st.st_dev != root_dev->st_dev)
3019 subdir_fd = openat(fd, de->d_name,
3020 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3021 if (subdir_fd < 0) {
3022 if (ret == 0 && errno != ENOENT)
3027 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3028 if (r < 0 && ret == 0)
3032 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3033 if (ret == 0 && errno != ENOENT)
3037 } else if (!only_dirs && !keep_around) {
3039 if (unlinkat(fd, de->d_name, 0) < 0) {
3040 if (ret == 0 && errno != ENOENT)
3051 static int is_temporary_fs(struct statfs *s) {
3053 return s->f_type == TMPFS_MAGIC ||
3054 (long)s->f_type == (long)RAMFS_MAGIC;
3057 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3062 if (fstatfs(fd, &s) < 0) {
3063 close_nointr_nofail(fd);
3067 /* We refuse to clean disk file systems with this call. This
3068 * is extra paranoia just to be sure we never ever remove
3070 if (!is_temporary_fs(&s)) {
3071 log_error("Attempted to remove disk file system, and we can't allow that.");
3072 close_nointr_nofail(fd);
3076 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3079 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3085 /* We refuse to clean the root file system with this
3086 * call. This is extra paranoia to never cause a really
3087 * seriously broken system. */
3088 if (path_equal(path, "/")) {
3089 log_error("Attempted to remove entire root file system, and we can't allow that.");
3093 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3096 if (errno != ENOTDIR)
3100 if (statfs(path, &s) < 0)
3103 if (!is_temporary_fs(&s)) {
3104 log_error("Attempted to remove disk file system, and we can't allow that.");
3109 if (delete_root && !only_dirs)
3110 if (unlink(path) < 0 && errno != ENOENT)
3117 if (fstatfs(fd, &s) < 0) {
3118 close_nointr_nofail(fd);
3122 if (!is_temporary_fs(&s)) {
3123 log_error("Attempted to remove disk file system, and we can't allow that.");
3124 close_nointr_nofail(fd);
3129 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3132 if (honour_sticky && file_is_priv_sticky(path) > 0)
3135 if (rmdir(path) < 0 && errno != ENOENT) {
3144 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3145 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3148 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3149 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3152 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3155 /* Under the assumption that we are running privileged we
3156 * first change the access mode and only then hand out
3157 * ownership to avoid a window where access is too open. */
3159 if (mode != (mode_t) -1)
3160 if (chmod(path, mode) < 0)
3163 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3164 if (chown(path, uid, gid) < 0)
3170 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3173 /* Under the assumption that we are running privileged we
3174 * first change the access mode and only then hand out
3175 * ownership to avoid a window where access is too open. */
3177 if (fchmod(fd, mode) < 0)
3180 if (fchown(fd, uid, gid) < 0)
3186 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3190 /* Allocates the cpuset in the right size */
3193 if (!(r = CPU_ALLOC(n)))
3196 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3197 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3207 if (errno != EINVAL)
3214 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3215 static const char status_indent[] = " "; /* "[" STATUS "] " */
3216 _cleanup_free_ char *s = NULL;
3217 _cleanup_close_ int fd = -1;
3218 struct iovec iovec[5];
3223 /* This is independent of logging, as status messages are
3224 * optional and go exclusively to the console. */
3226 if (vasprintf(&s, format, ap) < 0)
3229 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3242 sl = status ? sizeof(status_indent)-1 : 0;
3248 e = ellipsize(s, emax, 75);
3258 if (!isempty(status)) {
3259 IOVEC_SET_STRING(iovec[n++], "[");
3260 IOVEC_SET_STRING(iovec[n++], status);
3261 IOVEC_SET_STRING(iovec[n++], "] ");
3263 IOVEC_SET_STRING(iovec[n++], status_indent);
3266 IOVEC_SET_STRING(iovec[n++], s);
3267 IOVEC_SET_STRING(iovec[n++], "\n");
3269 if (writev(fd, iovec, n) < 0)
3275 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3281 va_start(ap, format);
3282 r = status_vprintf(status, ellipse, format, ap);
3288 int status_welcome(void) {
3290 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3292 r = parse_env_file("/etc/os-release", NEWLINE,
3293 "PRETTY_NAME", &pretty_name,
3294 "ANSI_COLOR", &ansi_color,
3296 if (r < 0 && r != -ENOENT)
3297 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3299 return status_printf(NULL, false,
3300 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3301 isempty(ansi_color) ? "1" : ansi_color,
3302 isempty(pretty_name) ? "Linux" : pretty_name);
3305 char *replace_env(const char *format, char **env) {
3312 const char *e, *word = format;
3317 for (e = format; *e; e ++) {
3328 if (!(k = strnappend(r, word, e-word-1)))
3337 } else if (*e == '$') {
3338 if (!(k = strnappend(r, word, e-word)))
3354 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3357 if (!(k = strappend(r, t)))
3370 if (!(k = strnappend(r, word, e-word)))
3381 char **replace_env_argv(char **argv, char **env) {
3383 unsigned k = 0, l = 0;
3385 l = strv_length(argv);
3387 if (!(r = new(char*, l+1)))
3390 STRV_FOREACH(i, argv) {
3392 /* If $FOO appears as single word, replace it by the split up variable */
3393 if ((*i)[0] == '$' && (*i)[1] != '{') {
3398 if ((e = strv_env_get(env, *i+1))) {
3400 if (!(m = strv_split_quoted(e))) {
3411 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3420 memcpy(r + k, m, q * sizeof(char*));
3428 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3429 if (!(r[k++] = replace_env(*i, env))) {
3439 int fd_columns(int fd) {
3443 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3452 unsigned columns(void) {
3456 if (_likely_(cached_columns > 0))
3457 return cached_columns;
3460 e = getenv("COLUMNS");
3465 c = fd_columns(STDOUT_FILENO);
3474 int fd_lines(int fd) {
3478 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3487 unsigned lines(void) {
3491 if (_likely_(cached_lines > 0))
3492 return cached_lines;
3495 e = getenv("LINES");
3500 l = fd_lines(STDOUT_FILENO);
3506 return cached_lines;
3509 /* intended to be used as a SIGWINCH sighandler */
3510 void columns_lines_cache_reset(int signum) {
3516 static int cached_on_tty = -1;
3518 if (_unlikely_(cached_on_tty < 0))
3519 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3521 return cached_on_tty;
3524 int running_in_chroot(void) {
3530 /* Only works as root */
3532 if (stat("/proc/1/root", &a) < 0)
3535 if (stat("/", &b) < 0)
3539 a.st_dev != b.st_dev ||
3540 a.st_ino != b.st_ino;
3543 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3548 assert(percent <= 100);
3549 assert(new_length >= 3);
3551 if (old_length <= 3 || old_length <= new_length)
3552 return strndup(s, old_length);
3554 r = new0(char, new_length+1);
3558 x = (new_length * percent) / 100;
3560 if (x > new_length - 3)
3568 s + old_length - (new_length - x - 3),
3569 new_length - x - 3);
3574 char *ellipsize(const char *s, size_t length, unsigned percent) {
3575 return ellipsize_mem(s, strlen(s), length, percent);
3578 int touch(const char *path) {
3583 /* This just opens the file for writing, ensuring it
3584 * exists. It doesn't call utimensat() the way /usr/bin/touch
3587 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3591 close_nointr_nofail(fd);
3595 char *unquote(const char *s, const char* quotes) {
3599 /* This is rather stupid, simply removes the heading and
3600 * trailing quotes if there is one. Doesn't care about
3601 * escaping or anything. We should make this smarter one
3608 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3609 return strndup(s+1, l-2);
3614 char *normalize_env_assignment(const char *s) {
3615 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3618 eq = strchr(s, '=');
3630 memmove(r, t, strlen(t) + 1);
3634 name = strndup(s, eq - s);
3642 value = unquote(strstrip(p), QUOTES);
3646 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3652 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3663 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3675 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3682 r = wait_for_terminate(pid, &status);
3684 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3688 if (status.si_code == CLD_EXITED) {
3689 if (status.si_status != 0) {
3690 log_warning("%s failed with error code %i.", name, status.si_status);
3691 return status.si_status;
3694 log_debug("%s succeeded.", name);
3697 } else if (status.si_code == CLD_KILLED ||
3698 status.si_code == CLD_DUMPED) {
3700 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3704 log_warning("%s failed due to unknown reason.", name);
3708 _noreturn_ void freeze(void) {
3710 /* Make sure nobody waits for us on a socket anymore */
3711 close_all_fds(NULL, 0);
3719 bool null_or_empty(struct stat *st) {
3722 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3725 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3731 int null_or_empty_path(const char *fn) {
3736 if (stat(fn, &st) < 0)
3739 return null_or_empty(&st);
3742 DIR *xopendirat(int fd, const char *name, int flags) {
3746 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3752 close_nointr_nofail(nfd);
3759 int signal_from_string_try_harder(const char *s) {
3763 signo = signal_from_string(s);
3765 if (startswith(s, "SIG"))
3766 return signal_from_string(s+3);
3771 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3775 /* FIXME: to follow udev's logic 100% we need to leave valid
3776 * UTF8 chars unescaped */
3778 u = unquote(tagvalue, "\"\'");
3782 t = xescape(u, "/ ");
3788 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3797 char *fstab_node_to_udev_node(const char *p) {
3800 if (startswith(p, "LABEL="))
3801 return tag_to_udev_node(p+6, "label");
3803 if (startswith(p, "UUID="))
3804 return tag_to_udev_node(p+5, "uuid");
3806 if (startswith(p, "PARTUUID="))
3807 return tag_to_udev_node(p+9, "partuuid");
3809 if (startswith(p, "PARTLABEL="))
3810 return tag_to_udev_node(p+10, "partlabel");
3815 bool tty_is_vc(const char *tty) {
3818 if (startswith(tty, "/dev/"))
3821 return vtnr_from_tty(tty) >= 0;
3824 bool tty_is_console(const char *tty) {
3827 if (startswith(tty, "/dev/"))
3830 return streq(tty, "console");
3833 int vtnr_from_tty(const char *tty) {
3838 if (startswith(tty, "/dev/"))
3841 if (!startswith(tty, "tty") )
3844 if (tty[3] < '0' || tty[3] > '9')
3847 r = safe_atoi(tty+3, &i);
3851 if (i < 0 || i > 63)
3857 bool tty_is_vc_resolve(const char *tty) {
3858 char *active = NULL;
3863 if (startswith(tty, "/dev/"))
3866 /* Resolve where /dev/console is pointing to, if /sys is
3867 * actually ours (i.e. not read-only-mounted which is a sign
3868 * for container setups) */
3869 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
3870 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3871 /* If multiple log outputs are configured the
3872 * last one is what /dev/console points to */
3873 tty = strrchr(active, ' ');
3886 const char *default_term_for_tty(const char *tty) {
3889 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3892 bool dirent_is_file(const struct dirent *de) {
3895 if (ignore_file(de->d_name))
3898 if (de->d_type != DT_REG &&
3899 de->d_type != DT_LNK &&
3900 de->d_type != DT_UNKNOWN)
3906 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3909 if (de->d_type != DT_REG &&
3910 de->d_type != DT_LNK &&
3911 de->d_type != DT_UNKNOWN)
3914 if (ignore_file_allow_backup(de->d_name))
3917 return endswith(de->d_name, suffix);
3920 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3923 Hashmap *pids = NULL;
3927 /* Executes all binaries in a directory in parallel and waits
3928 * until all they all finished. */
3931 if (!(_d = opendir(directory))) {
3933 if (errno == ENOENT)
3936 log_error("Failed to enumerate directory %s: %m", directory);
3943 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3944 log_error("Failed to allocate set.");
3948 while ((de = readdir(d))) {
3953 if (!dirent_is_file(de))
3956 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3961 if ((pid = fork()) < 0) {
3962 log_error("Failed to fork: %m");
3980 log_error("Failed to execute %s: %m", path);
3981 _exit(EXIT_FAILURE);
3984 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3986 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3987 log_error("Failed to add PID to set: %s", strerror(-k));
3992 while (!hashmap_isempty(pids)) {
3993 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3998 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4003 log_error("waitid() failed: %m");
4007 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4008 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4009 if (si.si_code == CLD_EXITED)
4010 log_error("%s exited with exit status %i.", path, si.si_status);
4012 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4014 log_debug("%s exited successfully.", path);
4025 hashmap_free_free(pids);
4028 int kill_and_sigcont(pid_t pid, int sig) {
4031 r = kill(pid, sig) < 0 ? -errno : 0;
4039 bool nulstr_contains(const char*nulstr, const char *needle) {
4045 NULSTR_FOREACH(i, nulstr)
4046 if (streq(i, needle))
4052 bool plymouth_running(void) {
4053 return access("/run/plymouth/pid", F_OK) >= 0;
4056 char* strshorten(char *s, size_t l) {
4065 static bool hostname_valid_char(char c) {
4067 (c >= 'a' && c <= 'z') ||
4068 (c >= 'A' && c <= 'Z') ||
4069 (c >= '0' && c <= '9') ||
4075 bool hostname_is_valid(const char *s) {
4081 for (p = s; *p; p++)
4082 if (!hostname_valid_char(*p))
4085 if (p-s > HOST_NAME_MAX)
4091 char* hostname_cleanup(char *s) {
4094 for (p = s, d = s; *p; p++)
4095 if ((*p >= 'a' && *p <= 'z') ||
4096 (*p >= 'A' && *p <= 'Z') ||
4097 (*p >= '0' && *p <= '9') ||
4105 strshorten(s, HOST_NAME_MAX);
4109 int pipe_eof(int fd) {
4110 struct pollfd pollfd;
4115 pollfd.events = POLLIN|POLLHUP;
4117 r = poll(&pollfd, 1, 0);
4124 return pollfd.revents & POLLHUP;
4127 int fd_wait_for_event(int fd, int event, usec_t t) {
4128 struct pollfd pollfd;
4133 pollfd.events = event;
4135 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4142 return pollfd.revents;
4145 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4156 t = new(char, strlen(path) + 1 + 6 + 1);
4160 fn = path_get_file_name(path);
4164 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4166 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4172 f = fdopen(fd, "we");
4185 int terminal_vhangup_fd(int fd) {
4188 if (ioctl(fd, TIOCVHANGUP) < 0)
4194 int terminal_vhangup(const char *name) {
4197 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4201 r = terminal_vhangup_fd(fd);
4202 close_nointr_nofail(fd);
4207 int vt_disallocate(const char *name) {
4211 /* Deallocate the VT if possible. If not possible
4212 * (i.e. because it is the active one), at least clear it
4213 * entirely (including the scrollback buffer) */
4215 if (!startswith(name, "/dev/"))
4218 if (!tty_is_vc(name)) {
4219 /* So this is not a VT. I guess we cannot deallocate
4220 * it then. But let's at least clear the screen */
4222 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4227 "\033[r" /* clear scrolling region */
4228 "\033[H" /* move home */
4229 "\033[2J", /* clear screen */
4231 close_nointr_nofail(fd);
4236 if (!startswith(name, "/dev/tty"))
4239 r = safe_atou(name+8, &u);
4246 /* Try to deallocate */
4247 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4251 r = ioctl(fd, VT_DISALLOCATE, u);
4252 close_nointr_nofail(fd);
4260 /* Couldn't deallocate, so let's clear it fully with
4262 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4267 "\033[r" /* clear scrolling region */
4268 "\033[H" /* move home */
4269 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4271 close_nointr_nofail(fd);
4276 int copy_file(const char *from, const char *to) {
4282 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4286 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4288 close_nointr_nofail(fdf);
4296 n = read(fdf, buf, sizeof(buf));
4300 close_nointr_nofail(fdf);
4311 k = loop_write(fdt, buf, n, false);
4313 r = k < 0 ? k : (errno ? -errno : -EIO);
4315 close_nointr_nofail(fdf);
4323 close_nointr_nofail(fdf);
4324 r = close_nointr(fdt);
4334 int symlink_atomic(const char *from, const char *to) {
4336 _cleanup_free_ char *t;
4339 unsigned long long ull;
4346 t = new(char, strlen(to) + 1 + 16 + 1);
4350 fn = path_get_file_name(to);
4354 x = stpcpy(t+k+1, fn);
4357 for (i = 0; i < 16; i++) {
4358 *(x++) = hexchar(ull & 0xF);
4364 if (symlink(from, t) < 0)
4367 if (rename(t, to) < 0) {
4376 bool display_is_local(const char *display) {
4380 display[0] == ':' &&
4381 display[1] >= '0' &&
4385 int socket_from_display(const char *display, char **path) {
4392 if (!display_is_local(display))
4395 k = strspn(display+1, "0123456789");
4397 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4401 c = stpcpy(f, "/tmp/.X11-unix/X");
4402 memcpy(c, display+1, k);
4411 const char **username,
4412 uid_t *uid, gid_t *gid,
4414 const char **shell) {
4422 /* We enforce some special rules for uid=0: in order to avoid
4423 * NSS lookups for root we hardcode its data. */
4425 if (streq(*username, "root") || streq(*username, "0")) {
4443 if (parse_uid(*username, &u) >= 0) {
4447 /* If there are multiple users with the same id, make
4448 * sure to leave $USER to the configured value instead
4449 * of the first occurrence in the database. However if
4450 * the uid was configured by a numeric uid, then let's
4451 * pick the real username from /etc/passwd. */
4453 *username = p->pw_name;
4456 p = getpwnam(*username);
4460 return errno != 0 ? -errno : -ESRCH;
4472 *shell = p->pw_shell;
4477 char* uid_to_name(uid_t uid) {
4482 return strdup("root");
4486 return strdup(p->pw_name);
4488 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4494 int get_group_creds(const char **groupname, gid_t *gid) {
4500 /* We enforce some special rules for gid=0: in order to avoid
4501 * NSS lookups for root we hardcode its data. */
4503 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4504 *groupname = "root";
4512 if (parse_gid(*groupname, &id) >= 0) {
4517 *groupname = g->gr_name;
4520 g = getgrnam(*groupname);
4524 return errno != 0 ? -errno : -ESRCH;
4532 int in_group(const char *name) {
4534 int ngroups_max, r, i;
4536 r = get_group_creds(&name, &gid);
4540 if (getgid() == gid)
4543 if (getegid() == gid)
4546 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4547 assert(ngroups_max > 0);
4549 gids = alloca(sizeof(gid_t) * ngroups_max);
4551 r = getgroups(ngroups_max, gids);
4555 for (i = 0; i < r; i++)
4562 int glob_exists(const char *path) {
4570 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4572 if (k == GLOB_NOMATCH)
4574 else if (k == GLOB_NOSPACE)
4577 r = !strv_isempty(g.gl_pathv);
4579 r = errno ? -errno : -EIO;
4586 int dirent_ensure_type(DIR *d, struct dirent *de) {
4592 if (de->d_type != DT_UNKNOWN)
4595 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4599 S_ISREG(st.st_mode) ? DT_REG :
4600 S_ISDIR(st.st_mode) ? DT_DIR :
4601 S_ISLNK(st.st_mode) ? DT_LNK :
4602 S_ISFIFO(st.st_mode) ? DT_FIFO :
4603 S_ISSOCK(st.st_mode) ? DT_SOCK :
4604 S_ISCHR(st.st_mode) ? DT_CHR :
4605 S_ISBLK(st.st_mode) ? DT_BLK :
4611 int in_search_path(const char *path, char **search) {
4615 r = path_get_parent(path, &parent);
4621 STRV_FOREACH(i, search) {
4622 if (path_equal(parent, *i)) {
4633 int get_files_in_directory(const char *path, char ***list) {
4641 /* Returns all files in a directory in *list, and the number
4642 * of files as return value. If list is NULL returns only the
4651 union dirent_storage buf;
4654 k = readdir_r(d, &buf.de, &de);
4663 dirent_ensure_type(d, de);
4665 if (!dirent_is_file(de))
4669 if ((unsigned) r >= n) {
4673 t = realloc(l, sizeof(char*) * n);
4682 assert((unsigned) r < n);
4684 l[r] = strdup(de->d_name);
4708 char *strjoin(const char *x, ...) {
4722 t = va_arg(ap, const char *);
4727 if (n > ((size_t) -1) - l) {
4751 t = va_arg(ap, const char *);
4765 bool is_main_thread(void) {
4766 static __thread int cached = 0;
4768 if (_unlikely_(cached == 0))
4769 cached = getpid() == gettid() ? 1 : -1;
4774 int block_get_whole_disk(dev_t d, dev_t *ret) {
4781 /* If it has a queue this is good enough for us */
4782 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4785 r = access(p, F_OK);
4793 /* If it is a partition find the originating device */
4794 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4797 r = access(p, F_OK);
4803 /* Get parent dev_t */
4804 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4807 r = read_one_line_file(p, &s);
4813 r = sscanf(s, "%u:%u", &m, &n);
4819 /* Only return this if it is really good enough for us. */
4820 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4823 r = access(p, F_OK);
4827 *ret = makedev(m, n);
4834 int file_is_priv_sticky(const char *p) {
4839 if (lstat(p, &st) < 0)
4843 (st.st_uid == 0 || st.st_uid == getuid()) &&
4844 (st.st_mode & S_ISVTX);
4847 static const char *const ioprio_class_table[] = {
4848 [IOPRIO_CLASS_NONE] = "none",
4849 [IOPRIO_CLASS_RT] = "realtime",
4850 [IOPRIO_CLASS_BE] = "best-effort",
4851 [IOPRIO_CLASS_IDLE] = "idle"
4854 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4856 static const char *const sigchld_code_table[] = {
4857 [CLD_EXITED] = "exited",
4858 [CLD_KILLED] = "killed",
4859 [CLD_DUMPED] = "dumped",
4860 [CLD_TRAPPED] = "trapped",
4861 [CLD_STOPPED] = "stopped",
4862 [CLD_CONTINUED] = "continued",
4865 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4867 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4868 [LOG_FAC(LOG_KERN)] = "kern",
4869 [LOG_FAC(LOG_USER)] = "user",
4870 [LOG_FAC(LOG_MAIL)] = "mail",
4871 [LOG_FAC(LOG_DAEMON)] = "daemon",
4872 [LOG_FAC(LOG_AUTH)] = "auth",
4873 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4874 [LOG_FAC(LOG_LPR)] = "lpr",
4875 [LOG_FAC(LOG_NEWS)] = "news",
4876 [LOG_FAC(LOG_UUCP)] = "uucp",
4877 [LOG_FAC(LOG_CRON)] = "cron",
4878 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4879 [LOG_FAC(LOG_FTP)] = "ftp",
4880 [LOG_FAC(LOG_LOCAL0)] = "local0",
4881 [LOG_FAC(LOG_LOCAL1)] = "local1",
4882 [LOG_FAC(LOG_LOCAL2)] = "local2",
4883 [LOG_FAC(LOG_LOCAL3)] = "local3",
4884 [LOG_FAC(LOG_LOCAL4)] = "local4",
4885 [LOG_FAC(LOG_LOCAL5)] = "local5",
4886 [LOG_FAC(LOG_LOCAL6)] = "local6",
4887 [LOG_FAC(LOG_LOCAL7)] = "local7"
4890 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4892 static const char *const log_level_table[] = {
4893 [LOG_EMERG] = "emerg",
4894 [LOG_ALERT] = "alert",
4895 [LOG_CRIT] = "crit",
4897 [LOG_WARNING] = "warning",
4898 [LOG_NOTICE] = "notice",
4899 [LOG_INFO] = "info",
4900 [LOG_DEBUG] = "debug"
4903 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4905 static const char* const sched_policy_table[] = {
4906 [SCHED_OTHER] = "other",
4907 [SCHED_BATCH] = "batch",
4908 [SCHED_IDLE] = "idle",
4909 [SCHED_FIFO] = "fifo",
4913 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4915 static const char* const rlimit_table[] = {
4916 [RLIMIT_CPU] = "LimitCPU",
4917 [RLIMIT_FSIZE] = "LimitFSIZE",
4918 [RLIMIT_DATA] = "LimitDATA",
4919 [RLIMIT_STACK] = "LimitSTACK",
4920 [RLIMIT_CORE] = "LimitCORE",
4921 [RLIMIT_RSS] = "LimitRSS",
4922 [RLIMIT_NOFILE] = "LimitNOFILE",
4923 [RLIMIT_AS] = "LimitAS",
4924 [RLIMIT_NPROC] = "LimitNPROC",
4925 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4926 [RLIMIT_LOCKS] = "LimitLOCKS",
4927 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4928 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4929 [RLIMIT_NICE] = "LimitNICE",
4930 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4931 [RLIMIT_RTTIME] = "LimitRTTIME"
4934 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4936 static const char* const ip_tos_table[] = {
4937 [IPTOS_LOWDELAY] = "low-delay",
4938 [IPTOS_THROUGHPUT] = "throughput",
4939 [IPTOS_RELIABILITY] = "reliability",
4940 [IPTOS_LOWCOST] = "low-cost",
4943 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4945 static const char *const __signal_table[] = {
4962 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4973 [SIGVTALRM] = "VTALRM",
4975 [SIGWINCH] = "WINCH",
4981 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4983 const char *signal_to_string(int signo) {
4984 static __thread char buf[12];
4987 name = __signal_to_string(signo);
4991 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4992 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4994 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4999 int signal_from_string(const char *s) {
5004 signo = __signal_from_string(s);
5008 if (startswith(s, "RTMIN+")) {
5012 if (safe_atou(s, &u) >= 0) {
5013 signo = (int) u + offset;
5014 if (signo > 0 && signo < _NSIG)
5020 bool kexec_loaded(void) {
5021 bool loaded = false;
5024 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5032 int strdup_or_null(const char *a, char **b) {
5050 int prot_from_flags(int flags) {
5052 switch (flags & O_ACCMODE) {
5061 return PROT_READ|PROT_WRITE;
5068 char *format_bytes(char *buf, size_t l, off_t t) {
5071 static const struct {
5075 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5076 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5077 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5078 { "G", 1024ULL*1024ULL*1024ULL },
5079 { "M", 1024ULL*1024ULL },
5083 for (i = 0; i < ELEMENTSOF(table); i++) {
5085 if (t >= table[i].factor) {
5088 (unsigned long long) (t / table[i].factor),
5089 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5096 snprintf(buf, l, "%lluB", (unsigned long long) t);
5104 void* memdup(const void *p, size_t l) {
5117 int fd_inc_sndbuf(int fd, size_t n) {
5119 socklen_t l = sizeof(value);
5121 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5123 l == sizeof(value) &&
5124 (size_t) value >= n*2)
5128 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5135 int fd_inc_rcvbuf(int fd, size_t n) {
5137 socklen_t l = sizeof(value);
5139 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5141 l == sizeof(value) &&
5142 (size_t) value >= n*2)
5146 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5153 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5154 pid_t parent_pid, agent_pid;
5156 bool stdout_is_tty, stderr_is_tty;
5164 parent_pid = getpid();
5166 /* Spawns a temporary TTY agent, making sure it goes away when
5173 if (agent_pid != 0) {
5180 * Make sure the agent goes away when the parent dies */
5181 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5182 _exit(EXIT_FAILURE);
5184 /* Check whether our parent died before we were able
5185 * to set the death signal */
5186 if (getppid() != parent_pid)
5187 _exit(EXIT_SUCCESS);
5189 /* Don't leak fds to the agent */
5190 close_all_fds(except, n_except);
5192 stdout_is_tty = isatty(STDOUT_FILENO);
5193 stderr_is_tty = isatty(STDERR_FILENO);
5195 if (!stdout_is_tty || !stderr_is_tty) {
5196 /* Detach from stdout/stderr. and reopen
5197 * /dev/tty for them. This is important to
5198 * ensure that when systemctl is started via
5199 * popen() or a similar call that expects to
5200 * read EOF we actually do generate EOF and
5201 * not delay this indefinitely by because we
5202 * keep an unused copy of stdin around. */
5203 fd = open("/dev/tty", O_WRONLY);
5205 log_error("Failed to open /dev/tty: %m");
5206 _exit(EXIT_FAILURE);
5210 dup2(fd, STDOUT_FILENO);
5213 dup2(fd, STDERR_FILENO);
5219 /* Count arguments */
5221 for (n = 0; va_arg(ap, char*); n++)
5226 l = alloca(sizeof(char *) * (n + 1));
5228 /* Fill in arguments */
5230 for (i = 0; i <= n; i++)
5231 l[i] = va_arg(ap, char*);
5235 _exit(EXIT_FAILURE);
5238 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5239 struct rlimit highest, fixed;
5243 if (setrlimit(resource, rlim) >= 0)
5249 /* So we failed to set the desired setrlimit, then let's try
5250 * to get as close as we can */
5251 assert_se(getrlimit(resource, &highest) == 0);
5253 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5254 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5256 if (setrlimit(resource, &fixed) < 0)
5262 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5263 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5275 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5278 f = fopen(path, "re");
5286 char line[LINE_MAX];
5289 for (i = 0; i < sizeof(line)-1; i++) {
5293 if (_unlikely_(c == EOF)) {
5303 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5304 value = strdup(line + l + 1);
5324 int can_sleep(const char *type) {
5328 _cleanup_free_ char *p = NULL;
5332 /* If /sys is read-only we cannot sleep */
5333 if (access("/sys/power/state", W_OK) < 0)
5336 r = read_one_line_file("/sys/power/state", &p);
5341 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5342 if (l == k && memcmp(w, type, l) == 0)
5348 int can_sleep_disk(const char *type) {
5352 _cleanup_free_ char *p = NULL;
5356 /* If /sys is read-only we cannot sleep */
5357 if (access("/sys/power/state", W_OK) < 0 ||
5358 access("/sys/power/disk", W_OK) < 0)
5361 r = read_one_line_file("/sys/power/disk", &p);
5366 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5367 if (l == k && memcmp(w, type, l) == 0)
5370 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5377 bool is_valid_documentation_url(const char *url) {
5380 if (startswith(url, "http://") && url[7])
5383 if (startswith(url, "https://") && url[8])
5386 if (startswith(url, "file:") && url[5])
5389 if (startswith(url, "info:") && url[5])
5392 if (startswith(url, "man:") && url[4])
5398 bool in_initrd(void) {
5399 static __thread int saved = -1;
5405 /* We make two checks here:
5407 * 1. the flag file /etc/initrd-release must exist
5408 * 2. the root file system must be a memory file system
5410 * The second check is extra paranoia, since misdetecting an
5411 * initrd can have bad bad consequences due the initrd
5412 * emptying when transititioning to the main systemd.
5415 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5416 statfs("/", &s) >= 0 &&
5417 is_temporary_fs(&s);
5422 void warn_melody(void) {
5423 _cleanup_close_ int fd = -1;
5425 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5429 /* Yeah, this is synchronous. Kinda sucks. But well... */
5431 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5432 usleep(125*USEC_PER_MSEC);
5434 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5435 usleep(125*USEC_PER_MSEC);
5437 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5438 usleep(125*USEC_PER_MSEC);
5440 ioctl(fd, KIOCSOUND, 0);
5443 int make_console_stdio(void) {
5446 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5448 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5450 log_error("Failed to acquire terminal: %s", strerror(-fd));
5456 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5463 int get_home_dir(char **_h) {
5471 /* Take the user specified one */
5482 /* Hardcode home directory for root to avoid NSS */
5485 h = strdup("/root");
5493 /* Check the database... */
5497 return errno ? -errno : -ESRCH;
5499 if (!path_is_absolute(p->pw_dir))
5502 h = strdup(p->pw_dir);
5510 int get_shell(char **_sh) {
5518 /* Take the user specified one */
5519 e = getenv("SHELL");
5529 /* Hardcode home directory for root to avoid NSS */
5532 sh = strdup("/bin/sh");
5540 /* Check the database... */
5544 return errno ? -errno : -ESRCH;
5546 if (!path_is_absolute(p->pw_shell))
5549 sh = strdup(p->pw_shell);
5557 void freep(void *p) {
5561 void fclosep(FILE **f) {
5566 void closep(int *fd) {
5568 close_nointr_nofail(*fd);
5571 void closedirp(DIR **d) {
5576 void umaskp(mode_t *u) {
5580 bool filename_is_safe(const char *p) {
5594 if (strlen(p) > FILENAME_MAX)
5600 bool string_is_safe(const char *p) {
5605 for (t = p; *t; t++) {
5606 if (*t > 0 && *t < ' ')
5609 if (strchr("\\\"\'", *t))
5616 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5617 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5618 int (*compar) (const void *, const void *, void *), void *arg) {
5627 p = (void *)(((const char *) base) + (idx * size));
5628 comparison = compar(key, p, arg);
5631 else if (comparison > 0)
5639 bool is_locale_utf8(void) {
5641 static int cached_answer = -1;
5643 if (cached_answer >= 0)
5646 if (!setlocale(LC_ALL, "")) {
5647 cached_answer = true;
5651 set = nl_langinfo(CODESET);
5653 cached_answer = true;
5657 cached_answer = streq(set, "UTF-8");
5659 return (bool)cached_answer;
5662 const char *draw_special_char(DrawSpecialChar ch) {
5663 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5665 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5666 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5667 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5668 [DRAW_TREE_SPACE] = " ", /* */
5669 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5671 /* ASCII fallback */ {
5672 [DRAW_TREE_VERT] = "| ",
5673 [DRAW_TREE_BRANCH] = "|-",
5674 [DRAW_TREE_RIGHT] = "`-",
5675 [DRAW_TREE_SPACE] = " ",
5676 [DRAW_TRIANGULAR_BULLET] = "> ",
5680 return draw_table[!is_locale_utf8()][ch];
5683 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5686 size_t l, old_len, new_len;
5692 old_len = strlen(old_string);
5693 new_len = strlen(new_string);
5706 if (!startswith(f, old_string)) {
5712 nl = l - old_len + new_len;
5713 a = realloc(r, nl + 1);
5721 t = stpcpy(t, new_string);
5733 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5734 const char *i, *begin = NULL;
5739 } state = STATE_OTHER;
5741 size_t osz = 0, isz;
5747 /* Strips ANSI color and replaces TABs by 8 spaces */
5749 isz = _isz ? *_isz : strlen(*ibuf);
5751 f = open_memstream(&obuf, &osz);
5755 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5760 if (i >= *ibuf + isz) /* EOT */
5762 else if (*i == '\x1B')
5763 state = STATE_ESCAPE;
5764 else if (*i == '\t')
5771 if (i >= *ibuf + isz) { /* EOT */
5774 } else if (*i == '[') {
5775 state = STATE_BRACKET;
5780 state = STATE_OTHER;
5787 if (i >= *ibuf + isz || /* EOT */
5788 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5791 state = STATE_OTHER;
5793 } else if (*i == 'm')
5794 state = STATE_OTHER;
5816 int on_ac_power(void) {
5817 bool found_offline = false, found_online = false;
5818 _cleanup_closedir_ DIR *d = NULL;
5820 d = opendir("/sys/class/power_supply");
5826 union dirent_storage buf;
5827 _cleanup_free_ char *p = NULL;
5828 _cleanup_close_ int fd = -1, device = -1;
5833 k = readdir_r(d, &buf.de, &de);
5840 if (ignore_file(de->d_name))
5843 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5845 if (errno == ENOENT || errno == ENOTDIR)
5851 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5853 if (errno == ENOENT)
5859 n = read(fd, contents, sizeof(contents));
5863 if (n != 6 || memcmp(contents, "Mains\n", 6))
5866 close_nointr_nofail(fd);
5867 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5869 if (errno == ENOENT)
5875 n = read(fd, contents, sizeof(contents));
5879 if (n != 2 || contents[1] != '\n')
5882 if (contents[0] == '1') {
5883 found_online = true;
5885 } else if (contents[0] == '0')
5886 found_offline = true;
5891 return found_online || !found_offline;