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) {
564 _cleanup_fclose_ FILE *f = NULL;
565 _cleanup_free_ char *p = NULL;
571 r = fopen_temporary(fn, &f, &p);
575 fchmod_umask(fileno(f), 0644);
578 if (fputs(line, f) < 0) {
583 if (!endswith(line, "\n"))
589 r = errno ? -errno : -EIO;
591 if (rename(p, fn) < 0)
604 int read_one_line_file(const char *fn, char **line) {
605 _cleanup_fclose_ FILE *f = NULL;
606 char t[LINE_MAX], *c;
615 if (!fgets(t, sizeof(t), f)) {
618 return errno ? -errno : -EIO;
632 int read_full_file(const char *fn, char **contents, size_t *size) {
633 _cleanup_fclose_ FILE *f = NULL;
635 _cleanup_free_ char *buf = NULL;
645 if (fstat(fileno(f), &st) < 0)
649 if (st.st_size > 4*1024*1024)
652 n = st.st_size > 0 ? st.st_size : LINE_MAX;
659 t = realloc(buf, n+1);
664 k = fread(buf + l, 1, n - l, f);
693 const char *separator, ...) {
696 char *contents = NULL, *p;
701 if ((r = read_full_file(fname, &contents, NULL)) < 0)
706 const char *key = NULL;
708 p += strspn(p, separator);
709 p += strspn(p, WHITESPACE);
714 if (!strchr(COMMENTS, *p)) {
718 va_start(ap, separator);
719 while ((key = va_arg(ap, char *))) {
723 value = va_arg(ap, char **);
726 if (strncmp(p, key, n) != 0 ||
731 n = strcspn(p, separator);
734 strchr(QUOTES, p[0]) &&
736 v = strndup(p+1, n-2);
747 /* return empty value strings as NULL */
764 p += strcspn(p, separator);
772 int load_env_file(const char *fname,
775 FILE _cleanup_fclose_ *f;
777 char _cleanup_free_ *c = NULL;
778 char _cleanup_strv_free_ **m = NULL;
783 f = fopen(fname, "re");
788 char l[LINE_MAX], *p, *u, *cs;
791 if (!fgets(l, sizeof(l), f)) {
798 cs = endswith(l, "\\\n");
820 p = strstrip(c ? c : l);
825 if (strchr(COMMENTS, *p))
828 u = normalize_env_assignment(p);
835 t = strv_append(m, u);
851 int write_env_file(const char *fname, char **l) {
856 r = fopen_temporary(fname, &f, &p);
860 fchmod_umask(fileno(f), 0644);
876 if (rename(p, fname) < 0)
891 char *truncate_nl(char *s) {
894 s[strcspn(s, NEWLINE)] = 0;
898 int get_process_comm(pid_t pid, char **name) {
904 r = read_one_line_file("/proc/self/comm", name);
907 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
910 r = read_one_line_file(p, name);
917 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
925 f = fopen("/proc/self/cmdline", "re");
928 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
937 if (max_length == 0) {
939 while ((c = getc(f)) != EOF) {
940 k = realloc(r, len+1);
947 r[len-1] = isprint(c) ? c : ' ';
954 r = new(char, max_length);
962 while ((c = getc(f)) != EOF) {
984 size_t n = MIN(left-1, 3U);
993 /* Kernel threads have no argv[] */
994 if (r == NULL || r[0] == 0) {
1003 h = get_process_comm(pid, &t);
1007 r = strjoin("[", t, "]", NULL);
1018 int is_kernel_thread(pid_t pid) {
1028 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1037 count = fread(&c, 1, 1, f);
1041 /* Kernel threads have an empty cmdline */
1044 return eof ? 1 : -errno;
1049 int get_process_exe(pid_t pid, char **name) {
1055 r = readlink_malloc("/proc/self/exe", name);
1058 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1061 r = readlink_malloc(p, name);
1068 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1078 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1088 char line[LINE_MAX], *l;
1090 if (!fgets(line, sizeof(line), f)) {
1100 if (startswith(l, field)) {
1102 l += strspn(l, WHITESPACE);
1104 l[strcspn(l, WHITESPACE)] = 0;
1106 r = parse_uid(l, uid);
1119 int get_process_uid(pid_t pid, uid_t *uid) {
1120 return get_process_id(pid, "Uid:", uid);
1123 int get_process_gid(pid_t pid, gid_t *gid) {
1124 return get_process_id(pid, "Gid:", gid);
1127 char *strnappend(const char *s, const char *suffix, size_t b) {
1135 return strndup(suffix, b);
1144 if (b > ((size_t) -1) - a)
1147 r = new(char, a+b+1);
1152 memcpy(r+a, suffix, b);
1158 char *strappend(const char *s, const char *suffix) {
1159 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1162 int readlink_malloc(const char *p, char **r) {
1172 if (!(c = new(char, l)))
1175 if ((n = readlink(p, c, l-1)) < 0) {
1181 if ((size_t) n < l-1) {
1192 int readlink_and_make_absolute(const char *p, char **r) {
1199 if ((j = readlink_malloc(p, &target)) < 0)
1202 k = file_in_same_dir(p, target);
1212 int readlink_and_canonicalize(const char *p, char **r) {
1219 j = readlink_and_make_absolute(p, &t);
1223 s = canonicalize_file_name(t);
1230 path_kill_slashes(*r);
1235 int reset_all_signal_handlers(void) {
1238 for (sig = 1; sig < _NSIG; sig++) {
1239 struct sigaction sa;
1241 if (sig == SIGKILL || sig == SIGSTOP)
1245 sa.sa_handler = SIG_DFL;
1246 sa.sa_flags = SA_RESTART;
1248 /* On Linux the first two RT signals are reserved by
1249 * glibc, and sigaction() will return EINVAL for them. */
1250 if ((sigaction(sig, &sa, NULL) < 0))
1251 if (errno != EINVAL)
1258 char *strstrip(char *s) {
1261 /* Drops trailing whitespace. Modifies the string in
1262 * place. Returns pointer to first non-space character */
1264 s += strspn(s, WHITESPACE);
1266 for (e = strchr(s, 0); e > s; e --)
1267 if (!strchr(WHITESPACE, e[-1]))
1275 char *delete_chars(char *s, const char *bad) {
1278 /* Drops all whitespace, regardless where in the string */
1280 for (f = s, t = s; *f; f++) {
1281 if (strchr(bad, *f))
1292 bool in_charset(const char *s, const char* charset) {
1298 for (i = s; *i; i++)
1299 if (!strchr(charset, *i))
1305 char *file_in_same_dir(const char *path, const char *filename) {
1312 /* This removes the last component of path and appends
1313 * filename, unless the latter is absolute anyway or the
1316 if (path_is_absolute(filename))
1317 return strdup(filename);
1319 if (!(e = strrchr(path, '/')))
1320 return strdup(filename);
1322 k = strlen(filename);
1323 if (!(r = new(char, e-path+1+k+1)))
1326 memcpy(r, path, e-path+1);
1327 memcpy(r+(e-path)+1, filename, k+1);
1332 int rmdir_parents(const char *path, const char *stop) {
1341 /* Skip trailing slashes */
1342 while (l > 0 && path[l-1] == '/')
1348 /* Skip last component */
1349 while (l > 0 && path[l-1] != '/')
1352 /* Skip trailing slashes */
1353 while (l > 0 && path[l-1] == '/')
1359 if (!(t = strndup(path, l)))
1362 if (path_startswith(stop, t)) {
1371 if (errno != ENOENT)
1379 char hexchar(int x) {
1380 static const char table[16] = "0123456789abcdef";
1382 return table[x & 15];
1385 int unhexchar(char c) {
1387 if (c >= '0' && c <= '9')
1390 if (c >= 'a' && c <= 'f')
1391 return c - 'a' + 10;
1393 if (c >= 'A' && c <= 'F')
1394 return c - 'A' + 10;
1399 char octchar(int x) {
1400 return '0' + (x & 7);
1403 int unoctchar(char c) {
1405 if (c >= '0' && c <= '7')
1411 char decchar(int x) {
1412 return '0' + (x % 10);
1415 int undecchar(char c) {
1417 if (c >= '0' && c <= '9')
1423 char *cescape(const char *s) {
1429 /* Does C style string escaping. */
1431 r = new(char, strlen(s)*4 + 1);
1435 for (f = s, t = r; *f; f++)
1481 /* For special chars we prefer octal over
1482 * hexadecimal encoding, simply because glib's
1483 * g_strescape() does the same */
1484 if ((*f < ' ') || (*f >= 127)) {
1486 *(t++) = octchar((unsigned char) *f >> 6);
1487 *(t++) = octchar((unsigned char) *f >> 3);
1488 *(t++) = octchar((unsigned char) *f);
1499 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1506 /* Undoes C style string escaping, and optionally prefixes it. */
1508 pl = prefix ? strlen(prefix) : 0;
1510 r = new(char, pl+length+1);
1515 memcpy(r, prefix, pl);
1517 for (f = s, t = r + pl; f < s + length; f++) {
1560 /* This is an extension of the XDG syntax files */
1565 /* hexadecimal encoding */
1568 a = unhexchar(f[1]);
1569 b = unhexchar(f[2]);
1571 if (a < 0 || b < 0) {
1572 /* Invalid escape code, let's take it literal then */
1576 *(t++) = (char) ((a << 4) | b);
1591 /* octal encoding */
1594 a = unoctchar(f[0]);
1595 b = unoctchar(f[1]);
1596 c = unoctchar(f[2]);
1598 if (a < 0 || b < 0 || c < 0) {
1599 /* Invalid escape code, let's take it literal then */
1603 *(t++) = (char) ((a << 6) | (b << 3) | c);
1611 /* premature end of string.*/
1616 /* Invalid escape code, let's take it literal then */
1628 char *cunescape_length(const char *s, size_t length) {
1629 return cunescape_length_with_prefix(s, length, NULL);
1632 char *cunescape(const char *s) {
1635 return cunescape_length(s, strlen(s));
1638 char *xescape(const char *s, const char *bad) {
1642 /* Escapes all chars in bad, in addition to \ and all special
1643 * chars, in \xFF style escaping. May be reversed with
1646 r = new(char, strlen(s) * 4 + 1);
1650 for (f = s, t = r; *f; f++) {
1652 if ((*f < ' ') || (*f >= 127) ||
1653 (*f == '\\') || strchr(bad, *f)) {
1656 *(t++) = hexchar(*f >> 4);
1657 *(t++) = hexchar(*f);
1667 char *bus_path_escape(const char *s) {
1673 /* Escapes all chars that D-Bus' object path cannot deal
1674 * with. Can be reverse with bus_path_unescape() */
1676 if (!(r = new(char, strlen(s)*3+1)))
1679 for (f = s, t = r; *f; f++) {
1681 if (!(*f >= 'A' && *f <= 'Z') &&
1682 !(*f >= 'a' && *f <= 'z') &&
1683 !(*f >= '0' && *f <= '9')) {
1685 *(t++) = hexchar(*f >> 4);
1686 *(t++) = hexchar(*f);
1696 char *bus_path_unescape(const char *f) {
1701 if (!(r = strdup(f)))
1704 for (t = r; *f; f++) {
1709 if ((a = unhexchar(f[1])) < 0 ||
1710 (b = unhexchar(f[2])) < 0) {
1711 /* Invalid escape code, let's take it literal then */
1714 *(t++) = (char) ((a << 4) | b);
1726 char *ascii_strlower(char *t) {
1731 for (p = t; *p; p++)
1732 if (*p >= 'A' && *p <= 'Z')
1733 *p = *p - 'A' + 'a';
1738 static bool ignore_file_allow_backup(const char *filename) {
1742 filename[0] == '.' ||
1743 streq(filename, "lost+found") ||
1744 streq(filename, "aquota.user") ||
1745 streq(filename, "aquota.group") ||
1746 endswith(filename, ".rpmnew") ||
1747 endswith(filename, ".rpmsave") ||
1748 endswith(filename, ".rpmorig") ||
1749 endswith(filename, ".dpkg-old") ||
1750 endswith(filename, ".dpkg-new") ||
1751 endswith(filename, ".swp");
1754 bool ignore_file(const char *filename) {
1757 if (endswith(filename, "~"))
1760 return ignore_file_allow_backup(filename);
1763 int fd_nonblock(int fd, bool nonblock) {
1768 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1772 flags |= O_NONBLOCK;
1774 flags &= ~O_NONBLOCK;
1776 if (fcntl(fd, F_SETFL, flags) < 0)
1782 int fd_cloexec(int fd, bool cloexec) {
1787 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1791 flags |= FD_CLOEXEC;
1793 flags &= ~FD_CLOEXEC;
1795 if (fcntl(fd, F_SETFD, flags) < 0)
1801 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1804 assert(n_fdset == 0 || fdset);
1806 for (i = 0; i < n_fdset; i++)
1813 int close_all_fds(const int except[], unsigned n_except) {
1818 assert(n_except == 0 || except);
1820 d = opendir("/proc/self/fd");
1825 /* When /proc isn't available (for example in chroots)
1826 * the fallback is brute forcing through the fd
1829 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1830 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1832 if (fd_in_set(fd, except, n_except))
1835 if (close_nointr(fd) < 0)
1836 if (errno != EBADF && r == 0)
1843 while ((de = readdir(d))) {
1846 if (ignore_file(de->d_name))
1849 if (safe_atoi(de->d_name, &fd) < 0)
1850 /* Let's better ignore this, just in case */
1859 if (fd_in_set(fd, except, n_except))
1862 if (close_nointr(fd) < 0) {
1863 /* Valgrind has its own FD and doesn't want to have it closed */
1864 if (errno != EBADF && r == 0)
1873 bool chars_intersect(const char *a, const char *b) {
1876 /* Returns true if any of the chars in a are in b. */
1877 for (p = a; *p; p++)
1884 bool fstype_is_network(const char *fstype) {
1885 static const char table[] =
1894 return nulstr_contains(table, fstype);
1898 _cleanup_close_ int fd;
1900 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1906 TIOCL_GETKMSGREDIRECT,
1910 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1913 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1916 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1922 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1923 struct termios old_termios, new_termios;
1925 char line[LINE_MAX];
1930 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1931 new_termios = old_termios;
1933 new_termios.c_lflag &= ~ICANON;
1934 new_termios.c_cc[VMIN] = 1;
1935 new_termios.c_cc[VTIME] = 0;
1937 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1940 if (t != (usec_t) -1) {
1941 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1942 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1947 k = fread(&c, 1, 1, f);
1949 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1955 *need_nl = c != '\n';
1962 if (t != (usec_t) -1)
1963 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1966 if (!fgets(line, sizeof(line), f))
1971 if (strlen(line) != 1)
1981 int ask(char *ret, const char *replies, const char *text, ...) {
1991 bool need_nl = true;
1994 fputs(ANSI_HIGHLIGHT_ON, stdout);
2001 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2005 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2008 if (r == -EBADMSG) {
2009 puts("Bad input, please try again.");
2020 if (strchr(replies, c)) {
2025 puts("Read unexpected character, please try again.");
2029 int reset_terminal_fd(int fd, bool switch_to_text) {
2030 struct termios termios;
2033 /* Set terminal to some sane defaults */
2037 /* We leave locked terminal attributes untouched, so that
2038 * Plymouth may set whatever it wants to set, and we don't
2039 * interfere with that. */
2041 /* Disable exclusive mode, just in case */
2042 ioctl(fd, TIOCNXCL);
2044 /* Switch to text mode */
2046 ioctl(fd, KDSETMODE, KD_TEXT);
2048 /* Enable console unicode mode */
2049 ioctl(fd, KDSKBMODE, K_UNICODE);
2051 if (tcgetattr(fd, &termios) < 0) {
2056 /* We only reset the stuff that matters to the software. How
2057 * hardware is set up we don't touch assuming that somebody
2058 * else will do that for us */
2060 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2061 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2062 termios.c_oflag |= ONLCR;
2063 termios.c_cflag |= CREAD;
2064 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2066 termios.c_cc[VINTR] = 03; /* ^C */
2067 termios.c_cc[VQUIT] = 034; /* ^\ */
2068 termios.c_cc[VERASE] = 0177;
2069 termios.c_cc[VKILL] = 025; /* ^X */
2070 termios.c_cc[VEOF] = 04; /* ^D */
2071 termios.c_cc[VSTART] = 021; /* ^Q */
2072 termios.c_cc[VSTOP] = 023; /* ^S */
2073 termios.c_cc[VSUSP] = 032; /* ^Z */
2074 termios.c_cc[VLNEXT] = 026; /* ^V */
2075 termios.c_cc[VWERASE] = 027; /* ^W */
2076 termios.c_cc[VREPRINT] = 022; /* ^R */
2077 termios.c_cc[VEOL] = 0;
2078 termios.c_cc[VEOL2] = 0;
2080 termios.c_cc[VTIME] = 0;
2081 termios.c_cc[VMIN] = 1;
2083 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2087 /* Just in case, flush all crap out */
2088 tcflush(fd, TCIOFLUSH);
2093 int reset_terminal(const char *name) {
2096 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2100 r = reset_terminal_fd(fd, true);
2101 close_nointr_nofail(fd);
2106 int open_terminal(const char *name, int mode) {
2111 * If a TTY is in the process of being closed opening it might
2112 * cause EIO. This is horribly awful, but unlikely to be
2113 * changed in the kernel. Hence we work around this problem by
2114 * retrying a couple of times.
2116 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2120 fd = open(name, mode);
2127 /* Max 1s in total */
2131 usleep(50 * USEC_PER_MSEC);
2140 close_nointr_nofail(fd);
2145 close_nointr_nofail(fd);
2152 int flush_fd(int fd) {
2153 struct pollfd pollfd;
2157 pollfd.events = POLLIN;
2164 if ((r = poll(&pollfd, 1, 0)) < 0) {
2175 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2180 if (errno == EAGAIN)
2191 int acquire_terminal(
2195 bool ignore_tiocstty_eperm,
2198 int fd = -1, notify = -1, r = 0, wd = -1;
2200 struct sigaction sa_old, sa_new;
2204 /* We use inotify to be notified when the tty is closed. We
2205 * create the watch before checking if we can actually acquire
2206 * it, so that we don't lose any event.
2208 * Note: strictly speaking this actually watches for the
2209 * device being closed, it does *not* really watch whether a
2210 * tty loses its controlling process. However, unless some
2211 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2212 * its tty otherwise this will not become a problem. As long
2213 * as the administrator makes sure not configure any service
2214 * on the same tty as an untrusted user this should not be a
2215 * problem. (Which he probably should not do anyway.) */
2217 if (timeout != (usec_t) -1)
2218 ts = now(CLOCK_MONOTONIC);
2220 if (!fail && !force) {
2221 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2227 wd = inotify_add_watch(notify, name, IN_CLOSE);
2236 r = flush_fd(notify);
2241 /* We pass here O_NOCTTY only so that we can check the return
2242 * value TIOCSCTTY and have a reliable way to figure out if we
2243 * successfully became the controlling process of the tty */
2244 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2248 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2249 * if we already own the tty. */
2251 sa_new.sa_handler = SIG_IGN;
2252 sa_new.sa_flags = SA_RESTART;
2253 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2255 /* First, try to get the tty */
2256 if (ioctl(fd, TIOCSCTTY, force) < 0)
2259 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2261 /* Sometimes it makes sense to ignore TIOCSCTTY
2262 * returning EPERM, i.e. when very likely we already
2263 * are have this controlling terminal. */
2264 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2267 if (r < 0 && (force || fail || r != -EPERM)) {
2276 assert(notify >= 0);
2279 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2281 struct inotify_event *e;
2283 if (timeout != (usec_t) -1) {
2286 n = now(CLOCK_MONOTONIC);
2287 if (ts + timeout < n) {
2292 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2302 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2305 if (errno == EINTR || errno == EAGAIN)
2312 e = (struct inotify_event*) inotify_buffer;
2317 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2322 step = sizeof(struct inotify_event) + e->len;
2323 assert(step <= (size_t) l);
2325 e = (struct inotify_event*) ((uint8_t*) e + step);
2332 /* We close the tty fd here since if the old session
2333 * ended our handle will be dead. It's important that
2334 * we do this after sleeping, so that we don't enter
2335 * an endless loop. */
2336 close_nointr_nofail(fd);
2340 close_nointr_nofail(notify);
2342 r = reset_terminal_fd(fd, true);
2344 log_warning("Failed to reset terminal: %s", strerror(-r));
2350 close_nointr_nofail(fd);
2353 close_nointr_nofail(notify);
2358 int release_terminal(void) {
2360 struct sigaction sa_old, sa_new;
2362 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2365 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2366 * by our own TIOCNOTTY */
2369 sa_new.sa_handler = SIG_IGN;
2370 sa_new.sa_flags = SA_RESTART;
2371 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2373 if (ioctl(fd, TIOCNOTTY) < 0)
2376 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2378 close_nointr_nofail(fd);
2382 int sigaction_many(const struct sigaction *sa, ...) {
2387 while ((sig = va_arg(ap, int)) > 0)
2388 if (sigaction(sig, sa, NULL) < 0)
2395 int ignore_signals(int sig, ...) {
2396 struct sigaction sa;
2401 sa.sa_handler = SIG_IGN;
2402 sa.sa_flags = SA_RESTART;
2404 if (sigaction(sig, &sa, NULL) < 0)
2408 while ((sig = va_arg(ap, int)) > 0)
2409 if (sigaction(sig, &sa, NULL) < 0)
2416 int default_signals(int sig, ...) {
2417 struct sigaction sa;
2422 sa.sa_handler = SIG_DFL;
2423 sa.sa_flags = SA_RESTART;
2425 if (sigaction(sig, &sa, NULL) < 0)
2429 while ((sig = va_arg(ap, int)) > 0)
2430 if (sigaction(sig, &sa, NULL) < 0)
2437 int close_pipe(int p[]) {
2443 a = close_nointr(p[0]);
2448 b = close_nointr(p[1]);
2452 return a < 0 ? a : b;
2455 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2464 while (nbytes > 0) {
2467 if ((k = read(fd, p, nbytes)) <= 0) {
2469 if (k < 0 && errno == EINTR)
2472 if (k < 0 && errno == EAGAIN && do_poll) {
2473 struct pollfd pollfd;
2477 pollfd.events = POLLIN;
2479 if (poll(&pollfd, 1, -1) < 0) {
2483 return n > 0 ? n : -errno;
2486 if (pollfd.revents != POLLIN)
2487 return n > 0 ? n : -EIO;
2492 return n > 0 ? n : (k < 0 ? -errno : 0);
2503 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2512 while (nbytes > 0) {
2515 k = write(fd, p, nbytes);
2518 if (k < 0 && errno == EINTR)
2521 if (k < 0 && errno == EAGAIN && do_poll) {
2522 struct pollfd pollfd;
2526 pollfd.events = POLLOUT;
2528 if (poll(&pollfd, 1, -1) < 0) {
2532 return n > 0 ? n : -errno;
2535 if (pollfd.revents != POLLOUT)
2536 return n > 0 ? n : -EIO;
2541 return n > 0 ? n : (k < 0 ? -errno : 0);
2552 int parse_bytes(const char *t, off_t *bytes) {
2553 static const struct {
2559 { "M", 1024ULL*1024ULL },
2560 { "G", 1024ULL*1024ULL*1024ULL },
2561 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2562 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2563 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2580 l = strtoll(p, &e, 10);
2591 e += strspn(e, WHITESPACE);
2593 for (i = 0; i < ELEMENTSOF(table); i++)
2594 if (startswith(e, table[i].suffix)) {
2595 r += (off_t) l * table[i].factor;
2596 p = e + strlen(table[i].suffix);
2600 if (i >= ELEMENTSOF(table))
2610 int make_stdio(int fd) {
2615 r = dup3(fd, STDIN_FILENO, 0);
2616 s = dup3(fd, STDOUT_FILENO, 0);
2617 t = dup3(fd, STDERR_FILENO, 0);
2620 close_nointr_nofail(fd);
2622 if (r < 0 || s < 0 || t < 0)
2625 /* We rely here that the new fd has O_CLOEXEC not set */
2630 int make_null_stdio(void) {
2633 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2637 return make_stdio(null_fd);
2640 bool is_device_path(const char *path) {
2642 /* Returns true on paths that refer to a device, either in
2643 * sysfs or in /dev */
2646 path_startswith(path, "/dev/") ||
2647 path_startswith(path, "/sys/");
2650 int dir_is_empty(const char *path) {
2651 _cleanup_closedir_ DIR *d;
2660 union dirent_storage buf;
2662 r = readdir_r(d, &buf.de, &de);
2669 if (!ignore_file(de->d_name))
2674 unsigned long long random_ull(void) {
2675 _cleanup_close_ int fd;
2679 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2683 r = loop_read(fd, &ull, sizeof(ull), true);
2684 if (r != sizeof(ull))
2690 return random() * RAND_MAX + random();
2693 void rename_process(const char name[8]) {
2696 /* This is a like a poor man's setproctitle(). It changes the
2697 * comm field, argv[0], and also the glibc's internally used
2698 * name of the process. For the first one a limit of 16 chars
2699 * applies, to the second one usually one of 10 (i.e. length
2700 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2701 * "systemd"). If you pass a longer string it will be
2704 prctl(PR_SET_NAME, name);
2706 if (program_invocation_name)
2707 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2709 if (saved_argc > 0) {
2713 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2715 for (i = 1; i < saved_argc; i++) {
2719 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2724 void sigset_add_many(sigset_t *ss, ...) {
2731 while ((sig = va_arg(ap, int)) > 0)
2732 assert_se(sigaddset(ss, sig) == 0);
2736 char* gethostname_malloc(void) {
2739 assert_se(uname(&u) >= 0);
2741 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2742 return strdup(u.nodename);
2744 return strdup(u.sysname);
2747 bool hostname_is_set(void) {
2750 assert_se(uname(&u) >= 0);
2752 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2755 static char *lookup_uid(uid_t uid) {
2758 _cleanup_free_ char *buf = NULL;
2759 struct passwd pwbuf, *pw = NULL;
2761 /* Shortcut things to avoid NSS lookups */
2763 return strdup("root");
2765 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2769 buf = malloc(bufsize);
2773 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2774 return strdup(pw->pw_name);
2776 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2782 char* getlogname_malloc(void) {
2786 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2791 return lookup_uid(uid);
2794 char *getusername_malloc(void) {
2801 return lookup_uid(getuid());
2804 int getttyname_malloc(int fd, char **r) {
2805 char path[PATH_MAX], *c;
2810 k = ttyname_r(fd, path, sizeof(path));
2816 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2824 int getttyname_harder(int fd, char **r) {
2828 k = getttyname_malloc(fd, &s);
2832 if (streq(s, "tty")) {
2834 return get_ctty(0, NULL, r);
2841 int get_ctty_devnr(pid_t pid, dev_t *d) {
2843 char line[LINE_MAX], *p, *fn;
2844 unsigned long ttynr;
2847 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2850 f = fopen(fn, "re");
2855 if (!fgets(line, sizeof(line), f)) {
2856 k = feof(f) ? -EIO : -errno;
2863 p = strrchr(line, ')');
2873 "%*d " /* session */
2878 if (major(ttynr) == 0 && minor(ttynr) == 0)
2885 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2887 char fn[PATH_MAX], *s, *b, *p;
2892 k = get_ctty_devnr(pid, &devnr);
2896 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2899 k = readlink_malloc(fn, &s);
2905 /* This is an ugly hack */
2906 if (major(devnr) == 136) {
2907 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2917 /* Probably something like the ptys which have no
2918 * symlink in /dev/char. Let's return something
2919 * vaguely useful. */
2932 if (startswith(s, "/dev/"))
2934 else if (startswith(s, "../"))
2952 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2958 /* This returns the first error we run into, but nevertheless
2959 * tries to go on. This closes the passed fd. */
2963 close_nointr_nofail(fd);
2965 return errno == ENOENT ? 0 : -errno;
2970 union dirent_storage buf;
2971 bool is_dir, keep_around;
2975 r = readdir_r(d, &buf.de, &de);
2976 if (r != 0 && ret == 0) {
2984 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2987 if (de->d_type == DT_UNKNOWN ||
2989 (de->d_type == DT_DIR && root_dev)) {
2990 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2991 if (ret == 0 && errno != ENOENT)
2996 is_dir = S_ISDIR(st.st_mode);
2999 (st.st_uid == 0 || st.st_uid == getuid()) &&
3000 (st.st_mode & S_ISVTX);
3002 is_dir = de->d_type == DT_DIR;
3003 keep_around = false;
3009 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3010 if (root_dev && st.st_dev != root_dev->st_dev)
3013 subdir_fd = openat(fd, de->d_name,
3014 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3015 if (subdir_fd < 0) {
3016 if (ret == 0 && errno != ENOENT)
3021 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3022 if (r < 0 && ret == 0)
3026 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3027 if (ret == 0 && errno != ENOENT)
3031 } else if (!only_dirs && !keep_around) {
3033 if (unlinkat(fd, de->d_name, 0) < 0) {
3034 if (ret == 0 && errno != ENOENT)
3045 static int is_temporary_fs(struct statfs *s) {
3047 return s->f_type == TMPFS_MAGIC ||
3048 (long)s->f_type == (long)RAMFS_MAGIC;
3051 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3056 if (fstatfs(fd, &s) < 0) {
3057 close_nointr_nofail(fd);
3061 /* We refuse to clean disk file systems with this call. This
3062 * is extra paranoia just to be sure we never ever remove
3064 if (!is_temporary_fs(&s)) {
3065 log_error("Attempted to remove disk file system, and we can't allow that.");
3066 close_nointr_nofail(fd);
3070 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3073 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3079 /* We refuse to clean the root file system with this
3080 * call. This is extra paranoia to never cause a really
3081 * seriously broken system. */
3082 if (path_equal(path, "/")) {
3083 log_error("Attempted to remove entire root file system, and we can't allow that.");
3087 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3090 if (errno != ENOTDIR)
3094 if (statfs(path, &s) < 0)
3097 if (!is_temporary_fs(&s)) {
3098 log_error("Attempted to remove disk file system, and we can't allow that.");
3103 if (delete_root && !only_dirs)
3104 if (unlink(path) < 0 && errno != ENOENT)
3111 if (fstatfs(fd, &s) < 0) {
3112 close_nointr_nofail(fd);
3116 if (!is_temporary_fs(&s)) {
3117 log_error("Attempted to remove disk file system, and we can't allow that.");
3118 close_nointr_nofail(fd);
3123 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3126 if (honour_sticky && file_is_priv_sticky(path) > 0)
3129 if (rmdir(path) < 0 && errno != ENOENT) {
3138 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3139 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3142 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3143 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3146 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3149 /* Under the assumption that we are running privileged we
3150 * first change the access mode and only then hand out
3151 * ownership to avoid a window where access is too open. */
3153 if (mode != (mode_t) -1)
3154 if (chmod(path, mode) < 0)
3157 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3158 if (chown(path, uid, gid) < 0)
3164 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3167 /* Under the assumption that we are running privileged we
3168 * first change the access mode and only then hand out
3169 * ownership to avoid a window where access is too open. */
3171 if (fchmod(fd, mode) < 0)
3174 if (fchown(fd, uid, gid) < 0)
3180 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3184 /* Allocates the cpuset in the right size */
3187 if (!(r = CPU_ALLOC(n)))
3190 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3191 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3201 if (errno != EINVAL)
3208 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3209 static const char status_indent[] = " "; /* "[" STATUS "] " */
3210 _cleanup_free_ char *s = NULL;
3211 _cleanup_close_ int fd = -1;
3212 struct iovec iovec[5];
3217 /* This is independent of logging, as status messages are
3218 * optional and go exclusively to the console. */
3220 if (vasprintf(&s, format, ap) < 0)
3223 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3236 sl = status ? sizeof(status_indent)-1 : 0;
3242 e = ellipsize(s, emax, 75);
3252 if (!isempty(status)) {
3253 IOVEC_SET_STRING(iovec[n++], "[");
3254 IOVEC_SET_STRING(iovec[n++], status);
3255 IOVEC_SET_STRING(iovec[n++], "] ");
3257 IOVEC_SET_STRING(iovec[n++], status_indent);
3260 IOVEC_SET_STRING(iovec[n++], s);
3261 IOVEC_SET_STRING(iovec[n++], "\n");
3263 if (writev(fd, iovec, n) < 0)
3269 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3275 va_start(ap, format);
3276 r = status_vprintf(status, ellipse, format, ap);
3282 int status_welcome(void) {
3284 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3286 r = parse_env_file("/etc/os-release", NEWLINE,
3287 "PRETTY_NAME", &pretty_name,
3288 "ANSI_COLOR", &ansi_color,
3290 if (r < 0 && r != -ENOENT)
3291 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3293 return status_printf(NULL, false,
3294 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3295 isempty(ansi_color) ? "1" : ansi_color,
3296 isempty(pretty_name) ? "Linux" : pretty_name);
3299 char *replace_env(const char *format, char **env) {
3306 const char *e, *word = format;
3311 for (e = format; *e; e ++) {
3322 if (!(k = strnappend(r, word, e-word-1)))
3331 } else if (*e == '$') {
3332 if (!(k = strnappend(r, word, e-word)))
3348 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3351 if (!(k = strappend(r, t)))
3364 if (!(k = strnappend(r, word, e-word)))
3375 char **replace_env_argv(char **argv, char **env) {
3377 unsigned k = 0, l = 0;
3379 l = strv_length(argv);
3381 if (!(r = new(char*, l+1)))
3384 STRV_FOREACH(i, argv) {
3386 /* If $FOO appears as single word, replace it by the split up variable */
3387 if ((*i)[0] == '$' && (*i)[1] != '{') {
3392 if ((e = strv_env_get(env, *i+1))) {
3394 if (!(m = strv_split_quoted(e))) {
3405 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3414 memcpy(r + k, m, q * sizeof(char*));
3422 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3423 if (!(r[k++] = replace_env(*i, env))) {
3433 int fd_columns(int fd) {
3437 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3446 unsigned columns(void) {
3450 if (_likely_(cached_columns > 0))
3451 return cached_columns;
3454 e = getenv("COLUMNS");
3459 c = fd_columns(STDOUT_FILENO);
3468 int fd_lines(int fd) {
3472 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3481 unsigned lines(void) {
3485 if (_likely_(cached_lines > 0))
3486 return cached_lines;
3489 e = getenv("LINES");
3494 l = fd_lines(STDOUT_FILENO);
3500 return cached_lines;
3503 /* intended to be used as a SIGWINCH sighandler */
3504 void columns_lines_cache_reset(int signum) {
3510 static int cached_on_tty = -1;
3512 if (_unlikely_(cached_on_tty < 0))
3513 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3515 return cached_on_tty;
3518 int running_in_chroot(void) {
3524 /* Only works as root */
3526 if (stat("/proc/1/root", &a) < 0)
3529 if (stat("/", &b) < 0)
3533 a.st_dev != b.st_dev ||
3534 a.st_ino != b.st_ino;
3537 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3542 assert(percent <= 100);
3543 assert(new_length >= 3);
3545 if (old_length <= 3 || old_length <= new_length)
3546 return strndup(s, old_length);
3548 r = new0(char, new_length+1);
3552 x = (new_length * percent) / 100;
3554 if (x > new_length - 3)
3562 s + old_length - (new_length - x - 3),
3563 new_length - x - 3);
3568 char *ellipsize(const char *s, size_t length, unsigned percent) {
3569 return ellipsize_mem(s, strlen(s), length, percent);
3572 int touch(const char *path) {
3577 /* This just opens the file for writing, ensuring it
3578 * exists. It doesn't call utimensat() the way /usr/bin/touch
3581 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3585 close_nointr_nofail(fd);
3589 char *unquote(const char *s, const char* quotes) {
3593 /* This is rather stupid, simply removes the heading and
3594 * trailing quotes if there is one. Doesn't care about
3595 * escaping or anything. We should make this smarter one
3602 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3603 return strndup(s+1, l-2);
3608 char *normalize_env_assignment(const char *s) {
3609 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3612 eq = strchr(s, '=');
3624 memmove(r, t, strlen(t) + 1);
3628 name = strndup(s, eq - s);
3636 value = unquote(strstrip(p), QUOTES);
3640 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3646 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3657 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3669 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3676 r = wait_for_terminate(pid, &status);
3678 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3682 if (status.si_code == CLD_EXITED) {
3683 if (status.si_status != 0) {
3684 log_warning("%s failed with error code %i.", name, status.si_status);
3685 return status.si_status;
3688 log_debug("%s succeeded.", name);
3691 } else if (status.si_code == CLD_KILLED ||
3692 status.si_code == CLD_DUMPED) {
3694 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3698 log_warning("%s failed due to unknown reason.", name);
3702 _noreturn_ void freeze(void) {
3704 /* Make sure nobody waits for us on a socket anymore */
3705 close_all_fds(NULL, 0);
3713 bool null_or_empty(struct stat *st) {
3716 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3719 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3725 int null_or_empty_path(const char *fn) {
3730 if (stat(fn, &st) < 0)
3733 return null_or_empty(&st);
3736 DIR *xopendirat(int fd, const char *name, int flags) {
3740 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3746 close_nointr_nofail(nfd);
3753 int signal_from_string_try_harder(const char *s) {
3757 signo = signal_from_string(s);
3759 if (startswith(s, "SIG"))
3760 return signal_from_string(s+3);
3765 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3769 /* FIXME: to follow udev's logic 100% we need to leave valid
3770 * UTF8 chars unescaped */
3772 u = unquote(tagvalue, "\"\'");
3776 t = xescape(u, "/ ");
3782 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3791 char *fstab_node_to_udev_node(const char *p) {
3794 if (startswith(p, "LABEL="))
3795 return tag_to_udev_node(p+6, "label");
3797 if (startswith(p, "UUID="))
3798 return tag_to_udev_node(p+5, "uuid");
3800 if (startswith(p, "PARTUUID="))
3801 return tag_to_udev_node(p+9, "partuuid");
3803 if (startswith(p, "PARTLABEL="))
3804 return tag_to_udev_node(p+10, "partlabel");
3809 bool tty_is_vc(const char *tty) {
3812 if (startswith(tty, "/dev/"))
3815 return vtnr_from_tty(tty) >= 0;
3818 bool tty_is_console(const char *tty) {
3821 if (startswith(tty, "/dev/"))
3824 return streq(tty, "console");
3827 int vtnr_from_tty(const char *tty) {
3832 if (startswith(tty, "/dev/"))
3835 if (!startswith(tty, "tty") )
3838 if (tty[3] < '0' || tty[3] > '9')
3841 r = safe_atoi(tty+3, &i);
3845 if (i < 0 || i > 63)
3851 bool tty_is_vc_resolve(const char *tty) {
3852 char *active = NULL;
3857 if (startswith(tty, "/dev/"))
3860 /* Resolve where /dev/console is pointing to, if /sys is
3861 * actually ours (i.e. not read-only-mounted which is a sign
3862 * for container setups) */
3863 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
3864 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3865 /* If multiple log outputs are configured the
3866 * last one is what /dev/console points to */
3867 tty = strrchr(active, ' ');
3880 const char *default_term_for_tty(const char *tty) {
3883 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3886 bool dirent_is_file(const struct dirent *de) {
3889 if (ignore_file(de->d_name))
3892 if (de->d_type != DT_REG &&
3893 de->d_type != DT_LNK &&
3894 de->d_type != DT_UNKNOWN)
3900 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3903 if (de->d_type != DT_REG &&
3904 de->d_type != DT_LNK &&
3905 de->d_type != DT_UNKNOWN)
3908 if (ignore_file_allow_backup(de->d_name))
3911 return endswith(de->d_name, suffix);
3914 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3917 Hashmap *pids = NULL;
3921 /* Executes all binaries in a directory in parallel and waits
3922 * until all they all finished. */
3925 if (!(_d = opendir(directory))) {
3927 if (errno == ENOENT)
3930 log_error("Failed to enumerate directory %s: %m", directory);
3937 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3938 log_error("Failed to allocate set.");
3942 while ((de = readdir(d))) {
3947 if (!dirent_is_file(de))
3950 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3955 if ((pid = fork()) < 0) {
3956 log_error("Failed to fork: %m");
3974 log_error("Failed to execute %s: %m", path);
3975 _exit(EXIT_FAILURE);
3978 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3980 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3981 log_error("Failed to add PID to set: %s", strerror(-k));
3986 while (!hashmap_isempty(pids)) {
3987 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3992 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3997 log_error("waitid() failed: %m");
4001 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4002 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4003 if (si.si_code == CLD_EXITED)
4004 log_error("%s exited with exit status %i.", path, si.si_status);
4006 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4008 log_debug("%s exited successfully.", path);
4019 hashmap_free_free(pids);
4022 int kill_and_sigcont(pid_t pid, int sig) {
4025 r = kill(pid, sig) < 0 ? -errno : 0;
4033 bool nulstr_contains(const char*nulstr, const char *needle) {
4039 NULSTR_FOREACH(i, nulstr)
4040 if (streq(i, needle))
4046 bool plymouth_running(void) {
4047 return access("/run/plymouth/pid", F_OK) >= 0;
4050 char* strshorten(char *s, size_t l) {
4059 static bool hostname_valid_char(char c) {
4061 (c >= 'a' && c <= 'z') ||
4062 (c >= 'A' && c <= 'Z') ||
4063 (c >= '0' && c <= '9') ||
4069 bool hostname_is_valid(const char *s) {
4075 for (p = s; *p; p++)
4076 if (!hostname_valid_char(*p))
4079 if (p-s > HOST_NAME_MAX)
4085 char* hostname_cleanup(char *s) {
4088 for (p = s, d = s; *p; p++)
4089 if ((*p >= 'a' && *p <= 'z') ||
4090 (*p >= 'A' && *p <= 'Z') ||
4091 (*p >= '0' && *p <= '9') ||
4099 strshorten(s, HOST_NAME_MAX);
4103 int pipe_eof(int fd) {
4104 struct pollfd pollfd;
4109 pollfd.events = POLLIN|POLLHUP;
4111 r = poll(&pollfd, 1, 0);
4118 return pollfd.revents & POLLHUP;
4121 int fd_wait_for_event(int fd, int event, usec_t t) {
4122 struct pollfd pollfd;
4127 pollfd.events = event;
4129 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4136 return pollfd.revents;
4139 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4150 t = new(char, strlen(path) + 1 + 6 + 1);
4154 fn = path_get_file_name(path);
4158 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4160 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4166 f = fdopen(fd, "we");
4179 int terminal_vhangup_fd(int fd) {
4182 if (ioctl(fd, TIOCVHANGUP) < 0)
4188 int terminal_vhangup(const char *name) {
4191 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4195 r = terminal_vhangup_fd(fd);
4196 close_nointr_nofail(fd);
4201 int vt_disallocate(const char *name) {
4205 /* Deallocate the VT if possible. If not possible
4206 * (i.e. because it is the active one), at least clear it
4207 * entirely (including the scrollback buffer) */
4209 if (!startswith(name, "/dev/"))
4212 if (!tty_is_vc(name)) {
4213 /* So this is not a VT. I guess we cannot deallocate
4214 * it then. But let's at least clear the screen */
4216 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4221 "\033[r" /* clear scrolling region */
4222 "\033[H" /* move home */
4223 "\033[2J", /* clear screen */
4225 close_nointr_nofail(fd);
4230 if (!startswith(name, "/dev/tty"))
4233 r = safe_atou(name+8, &u);
4240 /* Try to deallocate */
4241 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4245 r = ioctl(fd, VT_DISALLOCATE, u);
4246 close_nointr_nofail(fd);
4254 /* Couldn't deallocate, so let's clear it fully with
4256 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4261 "\033[r" /* clear scrolling region */
4262 "\033[H" /* move home */
4263 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4265 close_nointr_nofail(fd);
4270 int copy_file(const char *from, const char *to) {
4276 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4280 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4282 close_nointr_nofail(fdf);
4290 n = read(fdf, buf, sizeof(buf));
4294 close_nointr_nofail(fdf);
4305 k = loop_write(fdt, buf, n, false);
4307 r = k < 0 ? k : (errno ? -errno : -EIO);
4309 close_nointr_nofail(fdf);
4317 close_nointr_nofail(fdf);
4318 r = close_nointr(fdt);
4328 int symlink_atomic(const char *from, const char *to) {
4330 _cleanup_free_ char *t;
4333 unsigned long long ull;
4340 t = new(char, strlen(to) + 1 + 16 + 1);
4344 fn = path_get_file_name(to);
4348 x = stpcpy(t+k+1, fn);
4351 for (i = 0; i < 16; i++) {
4352 *(x++) = hexchar(ull & 0xF);
4358 if (symlink(from, t) < 0)
4361 if (rename(t, to) < 0) {
4370 bool display_is_local(const char *display) {
4374 display[0] == ':' &&
4375 display[1] >= '0' &&
4379 int socket_from_display(const char *display, char **path) {
4386 if (!display_is_local(display))
4389 k = strspn(display+1, "0123456789");
4391 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4395 c = stpcpy(f, "/tmp/.X11-unix/X");
4396 memcpy(c, display+1, k);
4405 const char **username,
4406 uid_t *uid, gid_t *gid,
4408 const char **shell) {
4416 /* We enforce some special rules for uid=0: in order to avoid
4417 * NSS lookups for root we hardcode its data. */
4419 if (streq(*username, "root") || streq(*username, "0")) {
4437 if (parse_uid(*username, &u) >= 0) {
4441 /* If there are multiple users with the same id, make
4442 * sure to leave $USER to the configured value instead
4443 * of the first occurrence in the database. However if
4444 * the uid was configured by a numeric uid, then let's
4445 * pick the real username from /etc/passwd. */
4447 *username = p->pw_name;
4450 p = getpwnam(*username);
4454 return errno != 0 ? -errno : -ESRCH;
4466 *shell = p->pw_shell;
4471 char* uid_to_name(uid_t uid) {
4476 return strdup("root");
4480 return strdup(p->pw_name);
4482 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4488 int get_group_creds(const char **groupname, gid_t *gid) {
4494 /* We enforce some special rules for gid=0: in order to avoid
4495 * NSS lookups for root we hardcode its data. */
4497 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4498 *groupname = "root";
4506 if (parse_gid(*groupname, &id) >= 0) {
4511 *groupname = g->gr_name;
4514 g = getgrnam(*groupname);
4518 return errno != 0 ? -errno : -ESRCH;
4526 int in_group(const char *name) {
4528 int ngroups_max, r, i;
4530 r = get_group_creds(&name, &gid);
4534 if (getgid() == gid)
4537 if (getegid() == gid)
4540 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4541 assert(ngroups_max > 0);
4543 gids = alloca(sizeof(gid_t) * ngroups_max);
4545 r = getgroups(ngroups_max, gids);
4549 for (i = 0; i < r; i++)
4556 int glob_exists(const char *path) {
4564 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4566 if (k == GLOB_NOMATCH)
4568 else if (k == GLOB_NOSPACE)
4571 r = !strv_isempty(g.gl_pathv);
4573 r = errno ? -errno : -EIO;
4580 int dirent_ensure_type(DIR *d, struct dirent *de) {
4586 if (de->d_type != DT_UNKNOWN)
4589 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4593 S_ISREG(st.st_mode) ? DT_REG :
4594 S_ISDIR(st.st_mode) ? DT_DIR :
4595 S_ISLNK(st.st_mode) ? DT_LNK :
4596 S_ISFIFO(st.st_mode) ? DT_FIFO :
4597 S_ISSOCK(st.st_mode) ? DT_SOCK :
4598 S_ISCHR(st.st_mode) ? DT_CHR :
4599 S_ISBLK(st.st_mode) ? DT_BLK :
4605 int in_search_path(const char *path, char **search) {
4609 r = path_get_parent(path, &parent);
4615 STRV_FOREACH(i, search) {
4616 if (path_equal(parent, *i)) {
4627 int get_files_in_directory(const char *path, char ***list) {
4635 /* Returns all files in a directory in *list, and the number
4636 * of files as return value. If list is NULL returns only the
4645 union dirent_storage buf;
4648 k = readdir_r(d, &buf.de, &de);
4657 dirent_ensure_type(d, de);
4659 if (!dirent_is_file(de))
4663 if ((unsigned) r >= n) {
4667 t = realloc(l, sizeof(char*) * n);
4676 assert((unsigned) r < n);
4678 l[r] = strdup(de->d_name);
4702 char *strjoin(const char *x, ...) {
4716 t = va_arg(ap, const char *);
4721 if (n > ((size_t) -1) - l) {
4745 t = va_arg(ap, const char *);
4759 bool is_main_thread(void) {
4760 static __thread int cached = 0;
4762 if (_unlikely_(cached == 0))
4763 cached = getpid() == gettid() ? 1 : -1;
4768 int block_get_whole_disk(dev_t d, dev_t *ret) {
4775 /* If it has a queue this is good enough for us */
4776 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4779 r = access(p, F_OK);
4787 /* If it is a partition find the originating device */
4788 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4791 r = access(p, F_OK);
4797 /* Get parent dev_t */
4798 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4801 r = read_one_line_file(p, &s);
4807 r = sscanf(s, "%u:%u", &m, &n);
4813 /* Only return this if it is really good enough for us. */
4814 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4817 r = access(p, F_OK);
4821 *ret = makedev(m, n);
4828 int file_is_priv_sticky(const char *p) {
4833 if (lstat(p, &st) < 0)
4837 (st.st_uid == 0 || st.st_uid == getuid()) &&
4838 (st.st_mode & S_ISVTX);
4841 static const char *const ioprio_class_table[] = {
4842 [IOPRIO_CLASS_NONE] = "none",
4843 [IOPRIO_CLASS_RT] = "realtime",
4844 [IOPRIO_CLASS_BE] = "best-effort",
4845 [IOPRIO_CLASS_IDLE] = "idle"
4848 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4850 static const char *const sigchld_code_table[] = {
4851 [CLD_EXITED] = "exited",
4852 [CLD_KILLED] = "killed",
4853 [CLD_DUMPED] = "dumped",
4854 [CLD_TRAPPED] = "trapped",
4855 [CLD_STOPPED] = "stopped",
4856 [CLD_CONTINUED] = "continued",
4859 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4861 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4862 [LOG_FAC(LOG_KERN)] = "kern",
4863 [LOG_FAC(LOG_USER)] = "user",
4864 [LOG_FAC(LOG_MAIL)] = "mail",
4865 [LOG_FAC(LOG_DAEMON)] = "daemon",
4866 [LOG_FAC(LOG_AUTH)] = "auth",
4867 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4868 [LOG_FAC(LOG_LPR)] = "lpr",
4869 [LOG_FAC(LOG_NEWS)] = "news",
4870 [LOG_FAC(LOG_UUCP)] = "uucp",
4871 [LOG_FAC(LOG_CRON)] = "cron",
4872 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4873 [LOG_FAC(LOG_FTP)] = "ftp",
4874 [LOG_FAC(LOG_LOCAL0)] = "local0",
4875 [LOG_FAC(LOG_LOCAL1)] = "local1",
4876 [LOG_FAC(LOG_LOCAL2)] = "local2",
4877 [LOG_FAC(LOG_LOCAL3)] = "local3",
4878 [LOG_FAC(LOG_LOCAL4)] = "local4",
4879 [LOG_FAC(LOG_LOCAL5)] = "local5",
4880 [LOG_FAC(LOG_LOCAL6)] = "local6",
4881 [LOG_FAC(LOG_LOCAL7)] = "local7"
4884 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4886 static const char *const log_level_table[] = {
4887 [LOG_EMERG] = "emerg",
4888 [LOG_ALERT] = "alert",
4889 [LOG_CRIT] = "crit",
4891 [LOG_WARNING] = "warning",
4892 [LOG_NOTICE] = "notice",
4893 [LOG_INFO] = "info",
4894 [LOG_DEBUG] = "debug"
4897 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4899 static const char* const sched_policy_table[] = {
4900 [SCHED_OTHER] = "other",
4901 [SCHED_BATCH] = "batch",
4902 [SCHED_IDLE] = "idle",
4903 [SCHED_FIFO] = "fifo",
4907 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4909 static const char* const rlimit_table[] = {
4910 [RLIMIT_CPU] = "LimitCPU",
4911 [RLIMIT_FSIZE] = "LimitFSIZE",
4912 [RLIMIT_DATA] = "LimitDATA",
4913 [RLIMIT_STACK] = "LimitSTACK",
4914 [RLIMIT_CORE] = "LimitCORE",
4915 [RLIMIT_RSS] = "LimitRSS",
4916 [RLIMIT_NOFILE] = "LimitNOFILE",
4917 [RLIMIT_AS] = "LimitAS",
4918 [RLIMIT_NPROC] = "LimitNPROC",
4919 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4920 [RLIMIT_LOCKS] = "LimitLOCKS",
4921 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4922 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4923 [RLIMIT_NICE] = "LimitNICE",
4924 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4925 [RLIMIT_RTTIME] = "LimitRTTIME"
4928 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4930 static const char* const ip_tos_table[] = {
4931 [IPTOS_LOWDELAY] = "low-delay",
4932 [IPTOS_THROUGHPUT] = "throughput",
4933 [IPTOS_RELIABILITY] = "reliability",
4934 [IPTOS_LOWCOST] = "low-cost",
4937 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4939 static const char *const __signal_table[] = {
4956 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4967 [SIGVTALRM] = "VTALRM",
4969 [SIGWINCH] = "WINCH",
4975 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4977 const char *signal_to_string(int signo) {
4978 static __thread char buf[12];
4981 name = __signal_to_string(signo);
4985 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4986 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4988 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4993 int signal_from_string(const char *s) {
4998 signo = __signal_from_string(s);
5002 if (startswith(s, "RTMIN+")) {
5006 if (safe_atou(s, &u) >= 0) {
5007 signo = (int) u + offset;
5008 if (signo > 0 && signo < _NSIG)
5014 bool kexec_loaded(void) {
5015 bool loaded = false;
5018 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5026 int strdup_or_null(const char *a, char **b) {
5044 int prot_from_flags(int flags) {
5046 switch (flags & O_ACCMODE) {
5055 return PROT_READ|PROT_WRITE;
5062 char *format_bytes(char *buf, size_t l, off_t t) {
5065 static const struct {
5069 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5070 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5071 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5072 { "G", 1024ULL*1024ULL*1024ULL },
5073 { "M", 1024ULL*1024ULL },
5077 for (i = 0; i < ELEMENTSOF(table); i++) {
5079 if (t >= table[i].factor) {
5082 (unsigned long long) (t / table[i].factor),
5083 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5090 snprintf(buf, l, "%lluB", (unsigned long long) t);
5098 void* memdup(const void *p, size_t l) {
5111 int fd_inc_sndbuf(int fd, size_t n) {
5113 socklen_t l = sizeof(value);
5115 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5117 l == sizeof(value) &&
5118 (size_t) value >= n*2)
5122 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5129 int fd_inc_rcvbuf(int fd, size_t n) {
5131 socklen_t l = sizeof(value);
5133 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5135 l == sizeof(value) &&
5136 (size_t) value >= n*2)
5140 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5147 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5148 pid_t parent_pid, agent_pid;
5150 bool stdout_is_tty, stderr_is_tty;
5158 parent_pid = getpid();
5160 /* Spawns a temporary TTY agent, making sure it goes away when
5167 if (agent_pid != 0) {
5174 * Make sure the agent goes away when the parent dies */
5175 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5176 _exit(EXIT_FAILURE);
5178 /* Check whether our parent died before we were able
5179 * to set the death signal */
5180 if (getppid() != parent_pid)
5181 _exit(EXIT_SUCCESS);
5183 /* Don't leak fds to the agent */
5184 close_all_fds(except, n_except);
5186 stdout_is_tty = isatty(STDOUT_FILENO);
5187 stderr_is_tty = isatty(STDERR_FILENO);
5189 if (!stdout_is_tty || !stderr_is_tty) {
5190 /* Detach from stdout/stderr. and reopen
5191 * /dev/tty for them. This is important to
5192 * ensure that when systemctl is started via
5193 * popen() or a similar call that expects to
5194 * read EOF we actually do generate EOF and
5195 * not delay this indefinitely by because we
5196 * keep an unused copy of stdin around. */
5197 fd = open("/dev/tty", O_WRONLY);
5199 log_error("Failed to open /dev/tty: %m");
5200 _exit(EXIT_FAILURE);
5204 dup2(fd, STDOUT_FILENO);
5207 dup2(fd, STDERR_FILENO);
5213 /* Count arguments */
5215 for (n = 0; va_arg(ap, char*); n++)
5220 l = alloca(sizeof(char *) * (n + 1));
5222 /* Fill in arguments */
5224 for (i = 0; i <= n; i++)
5225 l[i] = va_arg(ap, char*);
5229 _exit(EXIT_FAILURE);
5232 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5233 struct rlimit highest, fixed;
5237 if (setrlimit(resource, rlim) >= 0)
5243 /* So we failed to set the desired setrlimit, then let's try
5244 * to get as close as we can */
5245 assert_se(getrlimit(resource, &highest) == 0);
5247 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5248 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5250 if (setrlimit(resource, &fixed) < 0)
5256 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5257 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5269 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5272 f = fopen(path, "re");
5280 char line[LINE_MAX];
5283 for (i = 0; i < sizeof(line)-1; i++) {
5287 if (_unlikely_(c == EOF)) {
5297 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5298 value = strdup(line + l + 1);
5318 int can_sleep(const char *type) {
5322 _cleanup_free_ char *p = NULL;
5326 /* If /sys is read-only we cannot sleep */
5327 if (access("/sys/power/state", W_OK) < 0)
5330 r = read_one_line_file("/sys/power/state", &p);
5335 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5336 if (l == k && memcmp(w, type, l) == 0)
5342 int can_sleep_disk(const char *type) {
5346 _cleanup_free_ char *p = NULL;
5350 /* If /sys is read-only we cannot sleep */
5351 if (access("/sys/power/state", W_OK) < 0 ||
5352 access("/sys/power/disk", W_OK) < 0)
5355 r = read_one_line_file("/sys/power/disk", &p);
5360 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5361 if (l == k && memcmp(w, type, l) == 0)
5364 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5371 bool is_valid_documentation_url(const char *url) {
5374 if (startswith(url, "http://") && url[7])
5377 if (startswith(url, "https://") && url[8])
5380 if (startswith(url, "file:") && url[5])
5383 if (startswith(url, "info:") && url[5])
5386 if (startswith(url, "man:") && url[4])
5392 bool in_initrd(void) {
5393 static __thread int saved = -1;
5399 /* We make two checks here:
5401 * 1. the flag file /etc/initrd-release must exist
5402 * 2. the root file system must be a memory file system
5404 * The second check is extra paranoia, since misdetecting an
5405 * initrd can have bad bad consequences due the initrd
5406 * emptying when transititioning to the main systemd.
5409 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5410 statfs("/", &s) >= 0 &&
5411 is_temporary_fs(&s);
5416 void warn_melody(void) {
5417 _cleanup_close_ int fd = -1;
5419 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5423 /* Yeah, this is synchronous. Kinda sucks. But well... */
5425 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5426 usleep(125*USEC_PER_MSEC);
5428 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5429 usleep(125*USEC_PER_MSEC);
5431 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5432 usleep(125*USEC_PER_MSEC);
5434 ioctl(fd, KIOCSOUND, 0);
5437 int make_console_stdio(void) {
5440 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5442 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5444 log_error("Failed to acquire terminal: %s", strerror(-fd));
5450 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5457 int get_home_dir(char **_h) {
5465 /* Take the user specified one */
5476 /* Hardcode home directory for root to avoid NSS */
5479 h = strdup("/root");
5487 /* Check the database... */
5491 return errno ? -errno : -ESRCH;
5493 if (!path_is_absolute(p->pw_dir))
5496 h = strdup(p->pw_dir);
5504 int get_shell(char **_sh) {
5512 /* Take the user specified one */
5513 e = getenv("SHELL");
5523 /* Hardcode home directory for root to avoid NSS */
5526 sh = strdup("/bin/sh");
5534 /* Check the database... */
5538 return errno ? -errno : -ESRCH;
5540 if (!path_is_absolute(p->pw_shell))
5543 sh = strdup(p->pw_shell);
5551 void freep(void *p) {
5555 void fclosep(FILE **f) {
5560 void closep(int *fd) {
5562 close_nointr_nofail(*fd);
5565 void closedirp(DIR **d) {
5570 void umaskp(mode_t *u) {
5574 bool filename_is_safe(const char *p) {
5588 if (strlen(p) > FILENAME_MAX)
5594 bool string_is_safe(const char *p) {
5599 for (t = p; *t; t++) {
5600 if (*t > 0 && *t < ' ')
5603 if (strchr("\\\"\'", *t))
5610 bool path_is_safe(const char *p) {
5615 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5618 if (strlen(p) > PATH_MAX)
5621 /* The following two checks are not really dangerous, but hey, they still are confusing */
5622 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5625 if (strstr(p, "//"))
5631 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5632 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5633 int (*compar) (const void *, const void *, void *), void *arg) {
5642 p = (void *)(((const char *) base) + (idx * size));
5643 comparison = compar(key, p, arg);
5646 else if (comparison > 0)
5654 bool is_locale_utf8(void) {
5656 static int cached_answer = -1;
5658 if (cached_answer >= 0)
5661 if (!setlocale(LC_ALL, "")) {
5662 cached_answer = true;
5666 set = nl_langinfo(CODESET);
5668 cached_answer = true;
5672 cached_answer = streq(set, "UTF-8");
5674 return (bool)cached_answer;
5677 const char *draw_special_char(DrawSpecialChar ch) {
5678 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5680 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5681 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5682 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5683 [DRAW_TREE_SPACE] = " ", /* */
5684 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5686 /* ASCII fallback */ {
5687 [DRAW_TREE_VERT] = "| ",
5688 [DRAW_TREE_BRANCH] = "|-",
5689 [DRAW_TREE_RIGHT] = "`-",
5690 [DRAW_TREE_SPACE] = " ",
5691 [DRAW_TRIANGULAR_BULLET] = "> ",
5695 return draw_table[!is_locale_utf8()][ch];
5698 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5701 size_t l, old_len, new_len;
5707 old_len = strlen(old_string);
5708 new_len = strlen(new_string);
5721 if (!startswith(f, old_string)) {
5727 nl = l - old_len + new_len;
5728 a = realloc(r, nl + 1);
5736 t = stpcpy(t, new_string);
5748 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5749 const char *i, *begin = NULL;
5754 } state = STATE_OTHER;
5756 size_t osz = 0, isz;
5762 /* Strips ANSI color and replaces TABs by 8 spaces */
5764 isz = _isz ? *_isz : strlen(*ibuf);
5766 f = open_memstream(&obuf, &osz);
5770 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5775 if (i >= *ibuf + isz) /* EOT */
5777 else if (*i == '\x1B')
5778 state = STATE_ESCAPE;
5779 else if (*i == '\t')
5786 if (i >= *ibuf + isz) { /* EOT */
5789 } else if (*i == '[') {
5790 state = STATE_BRACKET;
5795 state = STATE_OTHER;
5802 if (i >= *ibuf + isz || /* EOT */
5803 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5806 state = STATE_OTHER;
5808 } else if (*i == 'm')
5809 state = STATE_OTHER;
5831 int on_ac_power(void) {
5832 bool found_offline = false, found_online = false;
5833 _cleanup_closedir_ DIR *d = NULL;
5835 d = opendir("/sys/class/power_supply");
5841 union dirent_storage buf;
5842 _cleanup_free_ char *p = NULL;
5843 _cleanup_close_ int fd = -1, device = -1;
5848 k = readdir_r(d, &buf.de, &de);
5855 if (ignore_file(de->d_name))
5858 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5860 if (errno == ENOENT || errno == ENOTDIR)
5866 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5868 if (errno == ENOENT)
5874 n = read(fd, contents, sizeof(contents));
5878 if (n != 6 || memcmp(contents, "Mains\n", 6))
5881 close_nointr_nofail(fd);
5882 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5884 if (errno == ENOENT)
5890 n = read(fd, contents, sizeof(contents));
5894 if (n != 2 || contents[1] != '\n')
5897 if (contents[0] == '1') {
5898 found_online = true;
5900 } else if (contents[0] == '0')
5901 found_offline = true;
5906 return found_online || !found_offline;