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"
76 char **saved_argv = NULL;
78 static volatile unsigned cached_columns = 0;
79 static volatile unsigned cached_lines = 0;
81 size_t page_size(void) {
82 static __thread size_t pgsz = 0;
85 if (_likely_(pgsz > 0))
88 r = sysconf(_SC_PAGESIZE);
95 bool streq_ptr(const char *a, const char *b) {
97 /* Like streq(), but tries to make sense of NULL pointers */
108 char* endswith(const char *s, const char *postfix) {
115 pl = strlen(postfix);
118 return (char*) s + sl;
123 if (memcmp(s + sl - pl, postfix, pl) != 0)
126 return (char*) s + sl - pl;
129 char* startswith(const char *s, const char *prefix) {
146 char* startswith_no_case(const char *s, const char *prefix) {
156 if (tolower(*a) != tolower(*b))
163 bool first_word(const char *s, const char *word) {
178 if (memcmp(s, word, wl) != 0)
182 strchr(WHITESPACE, s[wl]);
185 int close_nointr(int fd) {
200 void close_nointr_nofail(int fd) {
201 int saved_errno = errno;
203 /* like close_nointr() but cannot fail, and guarantees errno
206 assert_se(close_nointr(fd) == 0);
211 void close_many(const int fds[], unsigned n_fd) {
214 for (i = 0; i < n_fd; i++)
215 close_nointr_nofail(fds[i]);
218 int parse_boolean(const char *v) {
221 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
223 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
229 int parse_pid(const char *s, pid_t* ret_pid) {
230 unsigned long ul = 0;
237 r = safe_atolu(s, &ul);
243 if ((unsigned long) pid != ul)
253 int parse_uid(const char *s, uid_t* ret_uid) {
254 unsigned long ul = 0;
261 r = safe_atolu(s, &ul);
267 if ((unsigned long) uid != ul)
274 int safe_atou(const char *s, unsigned *ret_u) {
282 l = strtoul(s, &x, 0);
284 if (!x || x == s || *x || errno)
285 return errno ? -errno : -EINVAL;
287 if ((unsigned long) (unsigned) l != l)
290 *ret_u = (unsigned) l;
294 int safe_atoi(const char *s, int *ret_i) {
302 l = strtol(s, &x, 0);
304 if (!x || x == s || *x || errno)
305 return errno ? -errno : -EINVAL;
307 if ((long) (int) l != l)
314 int safe_atollu(const char *s, long long unsigned *ret_llu) {
316 unsigned long long l;
322 l = strtoull(s, &x, 0);
324 if (!x || x == s || *x || errno)
325 return errno ? -errno : -EINVAL;
331 int safe_atolli(const char *s, long long int *ret_lli) {
339 l = strtoll(s, &x, 0);
341 if (!x || x == s || *x || errno)
342 return errno ? -errno : -EINVAL;
348 /* Split a string into words. */
349 char *split(const char *c, size_t *l, const char *separator, char **state) {
352 current = *state ? *state : (char*) c;
354 if (!*current || *c == 0)
357 current += strspn(current, separator);
358 *l = strcspn(current, separator);
361 return (char*) current;
364 /* Split a string into words, but consider strings enclosed in '' and
365 * "" as words even if they include spaces. */
366 char *split_quoted(const char *c, size_t *l, char **state) {
368 bool escaped = false;
370 current = *state ? *state : (char*) c;
372 if (!*current || *c == 0)
375 current += strspn(current, WHITESPACE);
377 if (*current == '\'') {
380 for (e = current; *e; e++) {
390 *state = *e == 0 ? e : e+1;
391 } else if (*current == '\"') {
394 for (e = current; *e; e++) {
404 *state = *e == 0 ? e : e+1;
406 for (e = current; *e; e++) {
411 else if (strchr(WHITESPACE, *e))
418 return (char*) current;
421 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
423 _cleanup_fclose_ FILE *f = NULL;
424 char fn[PATH_MAX], line[LINE_MAX], *p;
430 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
437 if (!fgets(line, sizeof(line), f)) {
438 r = feof(f) ? -EIO : -errno;
442 /* Let's skip the pid and comm fields. The latter is enclosed
443 * in () but does not escape any () in its value, so let's
444 * skip over it manually */
446 p = strrchr(line, ')');
458 if ((long unsigned) (pid_t) ppid != ppid)
461 *_ppid = (pid_t) ppid;
466 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
467 _cleanup_fclose_ FILE *f = NULL;
468 char fn[PATH_MAX], line[LINE_MAX], *p;
473 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
480 if (!fgets(line, sizeof(line), f)) {
487 /* Let's skip the pid and comm fields. The latter is enclosed
488 * in () but does not escape any () in its value, so let's
489 * skip over it manually */
491 p = strrchr(line, ')');
513 "%*d " /* priority */
515 "%*d " /* num_threads */
516 "%*d " /* itrealvalue */
517 "%llu " /* starttime */,
524 int write_one_line_file(const char *fn, const char *line) {
525 _cleanup_fclose_ FILE *f = NULL;
535 if (fputs(line, f) < 0)
536 return errno ? -errno : -EIO;
538 if (!endswith(line, "\n"))
544 return errno ? -errno : -EIO;
549 int fchmod_umask(int fd, mode_t m) {
554 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
560 int write_one_line_file_atomic(const char *fn, const char *line) {
561 _cleanup_fclose_ FILE *f = NULL;
562 _cleanup_free_ char *p = NULL;
568 r = fopen_temporary(fn, &f, &p);
572 fchmod_umask(fileno(f), 0644);
575 if (fputs(line, f) < 0) {
580 if (!endswith(line, "\n"))
586 r = errno ? -errno : -EIO;
588 if (rename(p, fn) < 0)
601 int read_one_line_file(const char *fn, char **line) {
602 _cleanup_fclose_ FILE *f = NULL;
603 char t[LINE_MAX], *c;
612 if (!fgets(t, sizeof(t), f)) {
615 return errno ? -errno : -EIO;
629 int read_full_file(const char *fn, char **contents, size_t *size) {
630 _cleanup_fclose_ FILE *f = NULL;
632 _cleanup_free_ char *buf = NULL;
642 if (fstat(fileno(f), &st) < 0)
646 if (st.st_size > 4*1024*1024)
649 n = st.st_size > 0 ? st.st_size : LINE_MAX;
656 t = realloc(buf, n+1);
661 k = fread(buf + l, 1, n - l, f);
690 const char *separator, ...) {
693 char *contents = NULL, *p;
698 if ((r = read_full_file(fname, &contents, NULL)) < 0)
703 const char *key = NULL;
705 p += strspn(p, separator);
706 p += strspn(p, WHITESPACE);
711 if (!strchr(COMMENTS, *p)) {
715 va_start(ap, separator);
716 while ((key = va_arg(ap, char *))) {
720 value = va_arg(ap, char **);
723 if (strncmp(p, key, n) != 0 ||
728 n = strcspn(p, separator);
731 strchr(QUOTES, p[0]) &&
733 v = strndup(p+1, n-2);
744 /* return empty value strings as NULL */
761 p += strcspn(p, separator);
769 int load_env_file(const char *fname,
772 FILE _cleanup_fclose_ *f;
774 char _cleanup_free_ *c = NULL;
775 char _cleanup_strv_free_ **m = NULL;
780 f = fopen(fname, "re");
785 char l[LINE_MAX], *p, *u, *cs;
788 if (!fgets(l, sizeof(l), f)) {
795 cs = endswith(l, "\\\n");
817 p = strstrip(c ? c : l);
822 if (strchr(COMMENTS, *p))
825 u = normalize_env_assignment(p);
832 t = strv_append(m, u);
848 int write_env_file(const char *fname, char **l) {
853 r = fopen_temporary(fname, &f, &p);
857 fchmod_umask(fileno(f), 0644);
873 if (rename(p, fname) < 0)
888 char *truncate_nl(char *s) {
891 s[strcspn(s, NEWLINE)] = 0;
895 int get_process_comm(pid_t pid, char **name) {
901 r = read_one_line_file("/proc/self/comm", name);
904 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
907 r = read_one_line_file(p, name);
914 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
922 f = fopen("/proc/self/cmdline", "re");
925 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
934 if (max_length == 0) {
936 while ((c = getc(f)) != EOF) {
937 k = realloc(r, len+1);
944 r[len-1] = isprint(c) ? c : ' ';
951 r = new(char, max_length);
959 while ((c = getc(f)) != EOF) {
981 size_t n = MIN(left-1, 3U);
990 /* Kernel threads have no argv[] */
991 if (r == NULL || r[0] == 0) {
1000 h = get_process_comm(pid, &t);
1004 r = strjoin("[", t, "]", NULL);
1015 int is_kernel_thread(pid_t pid) {
1025 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1034 count = fread(&c, 1, 1, f);
1038 /* Kernel threads have an empty cmdline */
1041 return eof ? 1 : -errno;
1046 int get_process_exe(pid_t pid, char **name) {
1052 r = readlink_malloc("/proc/self/exe", name);
1055 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1058 r = readlink_malloc(p, name);
1065 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1075 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1085 char line[LINE_MAX], *l;
1087 if (!fgets(line, sizeof(line), f)) {
1097 if (startswith(l, field)) {
1099 l += strspn(l, WHITESPACE);
1101 l[strcspn(l, WHITESPACE)] = 0;
1103 r = parse_uid(l, uid);
1116 int get_process_uid(pid_t pid, uid_t *uid) {
1117 return get_process_id(pid, "Uid:", uid);
1120 int get_process_gid(pid_t pid, gid_t *gid) {
1121 return get_process_id(pid, "Gid:", gid);
1124 char *strnappend(const char *s, const char *suffix, size_t b) {
1132 return strndup(suffix, b);
1141 if (b > ((size_t) -1) - a)
1144 r = new(char, a+b+1);
1149 memcpy(r+a, suffix, b);
1155 char *strappend(const char *s, const char *suffix) {
1156 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1159 int readlink_malloc(const char *p, char **r) {
1169 if (!(c = new(char, l)))
1172 if ((n = readlink(p, c, l-1)) < 0) {
1178 if ((size_t) n < l-1) {
1189 int readlink_and_make_absolute(const char *p, char **r) {
1196 if ((j = readlink_malloc(p, &target)) < 0)
1199 k = file_in_same_dir(p, target);
1209 int readlink_and_canonicalize(const char *p, char **r) {
1216 j = readlink_and_make_absolute(p, &t);
1220 s = canonicalize_file_name(t);
1227 path_kill_slashes(*r);
1232 int reset_all_signal_handlers(void) {
1235 for (sig = 1; sig < _NSIG; sig++) {
1236 struct sigaction sa;
1238 if (sig == SIGKILL || sig == SIGSTOP)
1242 sa.sa_handler = SIG_DFL;
1243 sa.sa_flags = SA_RESTART;
1245 /* On Linux the first two RT signals are reserved by
1246 * glibc, and sigaction() will return EINVAL for them. */
1247 if ((sigaction(sig, &sa, NULL) < 0))
1248 if (errno != EINVAL)
1255 char *strstrip(char *s) {
1258 /* Drops trailing whitespace. Modifies the string in
1259 * place. Returns pointer to first non-space character */
1261 s += strspn(s, WHITESPACE);
1263 for (e = strchr(s, 0); e > s; e --)
1264 if (!strchr(WHITESPACE, e[-1]))
1272 char *delete_chars(char *s, const char *bad) {
1275 /* Drops all whitespace, regardless where in the string */
1277 for (f = s, t = s; *f; f++) {
1278 if (strchr(bad, *f))
1289 bool in_charset(const char *s, const char* charset) {
1295 for (i = s; *i; i++)
1296 if (!strchr(charset, *i))
1302 char *file_in_same_dir(const char *path, const char *filename) {
1309 /* This removes the last component of path and appends
1310 * filename, unless the latter is absolute anyway or the
1313 if (path_is_absolute(filename))
1314 return strdup(filename);
1316 if (!(e = strrchr(path, '/')))
1317 return strdup(filename);
1319 k = strlen(filename);
1320 if (!(r = new(char, e-path+1+k+1)))
1323 memcpy(r, path, e-path+1);
1324 memcpy(r+(e-path)+1, filename, k+1);
1329 int rmdir_parents(const char *path, const char *stop) {
1338 /* Skip trailing slashes */
1339 while (l > 0 && path[l-1] == '/')
1345 /* Skip last component */
1346 while (l > 0 && path[l-1] != '/')
1349 /* Skip trailing slashes */
1350 while (l > 0 && path[l-1] == '/')
1356 if (!(t = strndup(path, l)))
1359 if (path_startswith(stop, t)) {
1368 if (errno != ENOENT)
1376 char hexchar(int x) {
1377 static const char table[16] = "0123456789abcdef";
1379 return table[x & 15];
1382 int unhexchar(char c) {
1384 if (c >= '0' && c <= '9')
1387 if (c >= 'a' && c <= 'f')
1388 return c - 'a' + 10;
1390 if (c >= 'A' && c <= 'F')
1391 return c - 'A' + 10;
1396 char octchar(int x) {
1397 return '0' + (x & 7);
1400 int unoctchar(char c) {
1402 if (c >= '0' && c <= '7')
1408 char decchar(int x) {
1409 return '0' + (x % 10);
1412 int undecchar(char c) {
1414 if (c >= '0' && c <= '9')
1420 char *cescape(const char *s) {
1426 /* Does C style string escaping. */
1428 r = new(char, strlen(s)*4 + 1);
1432 for (f = s, t = r; *f; f++)
1478 /* For special chars we prefer octal over
1479 * hexadecimal encoding, simply because glib's
1480 * g_strescape() does the same */
1481 if ((*f < ' ') || (*f >= 127)) {
1483 *(t++) = octchar((unsigned char) *f >> 6);
1484 *(t++) = octchar((unsigned char) *f >> 3);
1485 *(t++) = octchar((unsigned char) *f);
1496 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1503 /* Undoes C style string escaping, and optionally prefixes it. */
1505 pl = prefix ? strlen(prefix) : 0;
1507 r = new(char, pl+length+1);
1512 memcpy(r, prefix, pl);
1514 for (f = s, t = r + pl; f < s + length; f++) {
1557 /* This is an extension of the XDG syntax files */
1562 /* hexadecimal encoding */
1565 a = unhexchar(f[1]);
1566 b = unhexchar(f[2]);
1568 if (a < 0 || b < 0) {
1569 /* Invalid escape code, let's take it literal then */
1573 *(t++) = (char) ((a << 4) | b);
1588 /* octal encoding */
1591 a = unoctchar(f[0]);
1592 b = unoctchar(f[1]);
1593 c = unoctchar(f[2]);
1595 if (a < 0 || b < 0 || c < 0) {
1596 /* Invalid escape code, let's take it literal then */
1600 *(t++) = (char) ((a << 6) | (b << 3) | c);
1608 /* premature end of string.*/
1613 /* Invalid escape code, let's take it literal then */
1625 char *cunescape_length(const char *s, size_t length) {
1626 return cunescape_length_with_prefix(s, length, NULL);
1629 char *cunescape(const char *s) {
1632 return cunescape_length(s, strlen(s));
1635 char *xescape(const char *s, const char *bad) {
1639 /* Escapes all chars in bad, in addition to \ and all special
1640 * chars, in \xFF style escaping. May be reversed with
1643 r = new(char, strlen(s) * 4 + 1);
1647 for (f = s, t = r; *f; f++) {
1649 if ((*f < ' ') || (*f >= 127) ||
1650 (*f == '\\') || strchr(bad, *f)) {
1653 *(t++) = hexchar(*f >> 4);
1654 *(t++) = hexchar(*f);
1664 char *bus_path_escape(const char *s) {
1670 /* Escapes all chars that D-Bus' object path cannot deal
1671 * with. Can be reverse with bus_path_unescape() */
1673 if (!(r = new(char, strlen(s)*3+1)))
1676 for (f = s, t = r; *f; f++) {
1678 if (!(*f >= 'A' && *f <= 'Z') &&
1679 !(*f >= 'a' && *f <= 'z') &&
1680 !(*f >= '0' && *f <= '9')) {
1682 *(t++) = hexchar(*f >> 4);
1683 *(t++) = hexchar(*f);
1693 char *bus_path_unescape(const char *f) {
1698 if (!(r = strdup(f)))
1701 for (t = r; *f; f++) {
1706 if ((a = unhexchar(f[1])) < 0 ||
1707 (b = unhexchar(f[2])) < 0) {
1708 /* Invalid escape code, let's take it literal then */
1711 *(t++) = (char) ((a << 4) | b);
1723 char *ascii_strlower(char *t) {
1728 for (p = t; *p; p++)
1729 if (*p >= 'A' && *p <= 'Z')
1730 *p = *p - 'A' + 'a';
1735 static bool ignore_file_allow_backup(const char *filename) {
1739 filename[0] == '.' ||
1740 streq(filename, "lost+found") ||
1741 streq(filename, "aquota.user") ||
1742 streq(filename, "aquota.group") ||
1743 endswith(filename, ".rpmnew") ||
1744 endswith(filename, ".rpmsave") ||
1745 endswith(filename, ".rpmorig") ||
1746 endswith(filename, ".dpkg-old") ||
1747 endswith(filename, ".dpkg-new") ||
1748 endswith(filename, ".swp");
1751 bool ignore_file(const char *filename) {
1754 if (endswith(filename, "~"))
1757 return ignore_file_allow_backup(filename);
1760 int fd_nonblock(int fd, bool nonblock) {
1765 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1769 flags |= O_NONBLOCK;
1771 flags &= ~O_NONBLOCK;
1773 if (fcntl(fd, F_SETFL, flags) < 0)
1779 int fd_cloexec(int fd, bool cloexec) {
1784 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1788 flags |= FD_CLOEXEC;
1790 flags &= ~FD_CLOEXEC;
1792 if (fcntl(fd, F_SETFD, flags) < 0)
1798 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1801 assert(n_fdset == 0 || fdset);
1803 for (i = 0; i < n_fdset; i++)
1810 int close_all_fds(const int except[], unsigned n_except) {
1815 assert(n_except == 0 || except);
1817 d = opendir("/proc/self/fd");
1822 /* When /proc isn't available (for example in chroots)
1823 * the fallback is brute forcing through the fd
1826 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1827 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1829 if (fd_in_set(fd, except, n_except))
1832 if (close_nointr(fd) < 0)
1833 if (errno != EBADF && r == 0)
1840 while ((de = readdir(d))) {
1843 if (ignore_file(de->d_name))
1846 if (safe_atoi(de->d_name, &fd) < 0)
1847 /* Let's better ignore this, just in case */
1856 if (fd_in_set(fd, except, n_except))
1859 if (close_nointr(fd) < 0) {
1860 /* Valgrind has its own FD and doesn't want to have it closed */
1861 if (errno != EBADF && r == 0)
1870 bool chars_intersect(const char *a, const char *b) {
1873 /* Returns true if any of the chars in a are in b. */
1874 for (p = a; *p; p++)
1881 bool fstype_is_network(const char *fstype) {
1882 static const char table[] =
1891 return nulstr_contains(table, fstype);
1895 _cleanup_close_ int fd;
1897 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1903 TIOCL_GETKMSGREDIRECT,
1907 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1910 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1913 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1919 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1920 struct termios old_termios, new_termios;
1922 char line[LINE_MAX];
1927 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1928 new_termios = old_termios;
1930 new_termios.c_lflag &= ~ICANON;
1931 new_termios.c_cc[VMIN] = 1;
1932 new_termios.c_cc[VTIME] = 0;
1934 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1937 if (t != (usec_t) -1) {
1938 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1939 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1944 k = fread(&c, 1, 1, f);
1946 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1952 *need_nl = c != '\n';
1959 if (t != (usec_t) -1)
1960 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1963 if (!fgets(line, sizeof(line), f))
1968 if (strlen(line) != 1)
1978 int ask(char *ret, const char *replies, const char *text, ...) {
1988 bool need_nl = true;
1991 fputs(ANSI_HIGHLIGHT_ON, stdout);
1998 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2002 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2005 if (r == -EBADMSG) {
2006 puts("Bad input, please try again.");
2017 if (strchr(replies, c)) {
2022 puts("Read unexpected character, please try again.");
2026 int reset_terminal_fd(int fd, bool switch_to_text) {
2027 struct termios termios;
2030 /* Set terminal to some sane defaults */
2034 /* We leave locked terminal attributes untouched, so that
2035 * Plymouth may set whatever it wants to set, and we don't
2036 * interfere with that. */
2038 /* Disable exclusive mode, just in case */
2039 ioctl(fd, TIOCNXCL);
2041 /* Switch to text mode */
2043 ioctl(fd, KDSETMODE, KD_TEXT);
2045 /* Enable console unicode mode */
2046 ioctl(fd, KDSKBMODE, K_UNICODE);
2048 if (tcgetattr(fd, &termios) < 0) {
2053 /* We only reset the stuff that matters to the software. How
2054 * hardware is set up we don't touch assuming that somebody
2055 * else will do that for us */
2057 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2058 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2059 termios.c_oflag |= ONLCR;
2060 termios.c_cflag |= CREAD;
2061 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2063 termios.c_cc[VINTR] = 03; /* ^C */
2064 termios.c_cc[VQUIT] = 034; /* ^\ */
2065 termios.c_cc[VERASE] = 0177;
2066 termios.c_cc[VKILL] = 025; /* ^X */
2067 termios.c_cc[VEOF] = 04; /* ^D */
2068 termios.c_cc[VSTART] = 021; /* ^Q */
2069 termios.c_cc[VSTOP] = 023; /* ^S */
2070 termios.c_cc[VSUSP] = 032; /* ^Z */
2071 termios.c_cc[VLNEXT] = 026; /* ^V */
2072 termios.c_cc[VWERASE] = 027; /* ^W */
2073 termios.c_cc[VREPRINT] = 022; /* ^R */
2074 termios.c_cc[VEOL] = 0;
2075 termios.c_cc[VEOL2] = 0;
2077 termios.c_cc[VTIME] = 0;
2078 termios.c_cc[VMIN] = 1;
2080 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2084 /* Just in case, flush all crap out */
2085 tcflush(fd, TCIOFLUSH);
2090 int reset_terminal(const char *name) {
2093 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2097 r = reset_terminal_fd(fd, true);
2098 close_nointr_nofail(fd);
2103 int open_terminal(const char *name, int mode) {
2108 * If a TTY is in the process of being closed opening it might
2109 * cause EIO. This is horribly awful, but unlikely to be
2110 * changed in the kernel. Hence we work around this problem by
2111 * retrying a couple of times.
2113 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2117 fd = open(name, mode);
2124 /* Max 1s in total */
2128 usleep(50 * USEC_PER_MSEC);
2137 close_nointr_nofail(fd);
2142 close_nointr_nofail(fd);
2149 int flush_fd(int fd) {
2150 struct pollfd pollfd;
2154 pollfd.events = POLLIN;
2161 if ((r = poll(&pollfd, 1, 0)) < 0) {
2172 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2177 if (errno == EAGAIN)
2188 int acquire_terminal(
2192 bool ignore_tiocstty_eperm,
2195 int fd = -1, notify = -1, r = 0, wd = -1;
2197 struct sigaction sa_old, sa_new;
2201 /* We use inotify to be notified when the tty is closed. We
2202 * create the watch before checking if we can actually acquire
2203 * it, so that we don't lose any event.
2205 * Note: strictly speaking this actually watches for the
2206 * device being closed, it does *not* really watch whether a
2207 * tty loses its controlling process. However, unless some
2208 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2209 * its tty otherwise this will not become a problem. As long
2210 * as the administrator makes sure not configure any service
2211 * on the same tty as an untrusted user this should not be a
2212 * problem. (Which he probably should not do anyway.) */
2214 if (timeout != (usec_t) -1)
2215 ts = now(CLOCK_MONOTONIC);
2217 if (!fail && !force) {
2218 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2224 wd = inotify_add_watch(notify, name, IN_CLOSE);
2233 r = flush_fd(notify);
2238 /* We pass here O_NOCTTY only so that we can check the return
2239 * value TIOCSCTTY and have a reliable way to figure out if we
2240 * successfully became the controlling process of the tty */
2241 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2245 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2246 * if we already own the tty. */
2248 sa_new.sa_handler = SIG_IGN;
2249 sa_new.sa_flags = SA_RESTART;
2250 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2252 /* First, try to get the tty */
2253 if (ioctl(fd, TIOCSCTTY, force) < 0)
2256 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2258 /* Sometimes it makes sense to ignore TIOCSCTTY
2259 * returning EPERM, i.e. when very likely we already
2260 * are have this controlling terminal. */
2261 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2264 if (r < 0 && (force || fail || r != -EPERM)) {
2273 assert(notify >= 0);
2276 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2278 struct inotify_event *e;
2280 if (timeout != (usec_t) -1) {
2283 n = now(CLOCK_MONOTONIC);
2284 if (ts + timeout < n) {
2289 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2299 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2302 if (errno == EINTR || errno == EAGAIN)
2309 e = (struct inotify_event*) inotify_buffer;
2314 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2319 step = sizeof(struct inotify_event) + e->len;
2320 assert(step <= (size_t) l);
2322 e = (struct inotify_event*) ((uint8_t*) e + step);
2329 /* We close the tty fd here since if the old session
2330 * ended our handle will be dead. It's important that
2331 * we do this after sleeping, so that we don't enter
2332 * an endless loop. */
2333 close_nointr_nofail(fd);
2337 close_nointr_nofail(notify);
2339 r = reset_terminal_fd(fd, true);
2341 log_warning("Failed to reset terminal: %s", strerror(-r));
2347 close_nointr_nofail(fd);
2350 close_nointr_nofail(notify);
2355 int release_terminal(void) {
2357 struct sigaction sa_old, sa_new;
2359 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2362 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2363 * by our own TIOCNOTTY */
2366 sa_new.sa_handler = SIG_IGN;
2367 sa_new.sa_flags = SA_RESTART;
2368 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2370 if (ioctl(fd, TIOCNOTTY) < 0)
2373 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2375 close_nointr_nofail(fd);
2379 int sigaction_many(const struct sigaction *sa, ...) {
2384 while ((sig = va_arg(ap, int)) > 0)
2385 if (sigaction(sig, sa, NULL) < 0)
2392 int ignore_signals(int sig, ...) {
2393 struct sigaction sa;
2398 sa.sa_handler = SIG_IGN;
2399 sa.sa_flags = SA_RESTART;
2401 if (sigaction(sig, &sa, NULL) < 0)
2405 while ((sig = va_arg(ap, int)) > 0)
2406 if (sigaction(sig, &sa, NULL) < 0)
2413 int default_signals(int sig, ...) {
2414 struct sigaction sa;
2419 sa.sa_handler = SIG_DFL;
2420 sa.sa_flags = SA_RESTART;
2422 if (sigaction(sig, &sa, NULL) < 0)
2426 while ((sig = va_arg(ap, int)) > 0)
2427 if (sigaction(sig, &sa, NULL) < 0)
2434 int close_pipe(int p[]) {
2440 a = close_nointr(p[0]);
2445 b = close_nointr(p[1]);
2449 return a < 0 ? a : b;
2452 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2461 while (nbytes > 0) {
2464 if ((k = read(fd, p, nbytes)) <= 0) {
2466 if (k < 0 && errno == EINTR)
2469 if (k < 0 && errno == EAGAIN && do_poll) {
2470 struct pollfd pollfd;
2474 pollfd.events = POLLIN;
2476 if (poll(&pollfd, 1, -1) < 0) {
2480 return n > 0 ? n : -errno;
2483 if (pollfd.revents != POLLIN)
2484 return n > 0 ? n : -EIO;
2489 return n > 0 ? n : (k < 0 ? -errno : 0);
2500 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2509 while (nbytes > 0) {
2512 k = write(fd, p, nbytes);
2515 if (k < 0 && errno == EINTR)
2518 if (k < 0 && errno == EAGAIN && do_poll) {
2519 struct pollfd pollfd;
2523 pollfd.events = POLLOUT;
2525 if (poll(&pollfd, 1, -1) < 0) {
2529 return n > 0 ? n : -errno;
2532 if (pollfd.revents != POLLOUT)
2533 return n > 0 ? n : -EIO;
2538 return n > 0 ? n : (k < 0 ? -errno : 0);
2549 int parse_bytes(const char *t, off_t *bytes) {
2550 static const struct {
2556 { "M", 1024ULL*1024ULL },
2557 { "G", 1024ULL*1024ULL*1024ULL },
2558 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2559 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2560 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2577 l = strtoll(p, &e, 10);
2588 e += strspn(e, WHITESPACE);
2590 for (i = 0; i < ELEMENTSOF(table); i++)
2591 if (startswith(e, table[i].suffix)) {
2592 r += (off_t) l * table[i].factor;
2593 p = e + strlen(table[i].suffix);
2597 if (i >= ELEMENTSOF(table))
2607 int make_stdio(int fd) {
2612 r = dup3(fd, STDIN_FILENO, 0);
2613 s = dup3(fd, STDOUT_FILENO, 0);
2614 t = dup3(fd, STDERR_FILENO, 0);
2617 close_nointr_nofail(fd);
2619 if (r < 0 || s < 0 || t < 0)
2622 /* We rely here that the new fd has O_CLOEXEC not set */
2627 int make_null_stdio(void) {
2630 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2634 return make_stdio(null_fd);
2637 bool is_device_path(const char *path) {
2639 /* Returns true on paths that refer to a device, either in
2640 * sysfs or in /dev */
2643 path_startswith(path, "/dev/") ||
2644 path_startswith(path, "/sys/");
2647 int dir_is_empty(const char *path) {
2648 _cleanup_closedir_ DIR *d;
2657 union dirent_storage buf;
2659 r = readdir_r(d, &buf.de, &de);
2666 if (!ignore_file(de->d_name))
2671 unsigned long long random_ull(void) {
2672 _cleanup_close_ int fd;
2676 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2680 r = loop_read(fd, &ull, sizeof(ull), true);
2681 if (r != sizeof(ull))
2687 return random() * RAND_MAX + random();
2690 void rename_process(const char name[8]) {
2693 /* This is a like a poor man's setproctitle(). It changes the
2694 * comm field, argv[0], and also the glibc's internally used
2695 * name of the process. For the first one a limit of 16 chars
2696 * applies, to the second one usually one of 10 (i.e. length
2697 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2698 * "systemd"). If you pass a longer string it will be
2701 prctl(PR_SET_NAME, name);
2703 if (program_invocation_name)
2704 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2706 if (saved_argc > 0) {
2710 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2712 for (i = 1; i < saved_argc; i++) {
2716 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2721 void sigset_add_many(sigset_t *ss, ...) {
2728 while ((sig = va_arg(ap, int)) > 0)
2729 assert_se(sigaddset(ss, sig) == 0);
2733 char* gethostname_malloc(void) {
2736 assert_se(uname(&u) >= 0);
2738 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2739 return strdup(u.nodename);
2741 return strdup(u.sysname);
2744 bool hostname_is_set(void) {
2747 assert_se(uname(&u) >= 0);
2749 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2752 static char *lookup_uid(uid_t uid) {
2755 _cleanup_free_ char *buf = NULL;
2756 struct passwd pwbuf, *pw = NULL;
2758 /* Shortcut things to avoid NSS lookups */
2760 return strdup("root");
2762 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2766 buf = malloc(bufsize);
2770 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2771 return strdup(pw->pw_name);
2773 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2779 char* getlogname_malloc(void) {
2783 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2788 return lookup_uid(uid);
2791 char *getusername_malloc(void) {
2798 return lookup_uid(getuid());
2801 int getttyname_malloc(int fd, char **r) {
2802 char path[PATH_MAX], *c;
2807 k = ttyname_r(fd, path, sizeof(path));
2813 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2821 int getttyname_harder(int fd, char **r) {
2825 k = getttyname_malloc(fd, &s);
2829 if (streq(s, "tty")) {
2831 return get_ctty(0, NULL, r);
2838 int get_ctty_devnr(pid_t pid, dev_t *d) {
2840 char line[LINE_MAX], *p, *fn;
2841 unsigned long ttynr;
2844 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2847 f = fopen(fn, "re");
2852 if (!fgets(line, sizeof(line), f)) {
2853 k = feof(f) ? -EIO : -errno;
2860 p = strrchr(line, ')');
2870 "%*d " /* session */
2875 if (major(ttynr) == 0 && minor(ttynr) == 0)
2882 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2884 char fn[PATH_MAX], *s, *b, *p;
2889 k = get_ctty_devnr(pid, &devnr);
2893 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2896 k = readlink_malloc(fn, &s);
2902 /* This is an ugly hack */
2903 if (major(devnr) == 136) {
2904 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2914 /* Probably something like the ptys which have no
2915 * symlink in /dev/char. Let's return something
2916 * vaguely useful. */
2929 if (startswith(s, "/dev/"))
2931 else if (startswith(s, "../"))
2949 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2955 /* This returns the first error we run into, but nevertheless
2956 * tries to go on. This closes the passed fd. */
2960 close_nointr_nofail(fd);
2962 return errno == ENOENT ? 0 : -errno;
2967 union dirent_storage buf;
2968 bool is_dir, keep_around;
2972 r = readdir_r(d, &buf.de, &de);
2973 if (r != 0 && ret == 0) {
2981 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2984 if (de->d_type == DT_UNKNOWN ||
2986 (de->d_type == DT_DIR && root_dev)) {
2987 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2988 if (ret == 0 && errno != ENOENT)
2993 is_dir = S_ISDIR(st.st_mode);
2996 (st.st_uid == 0 || st.st_uid == getuid()) &&
2997 (st.st_mode & S_ISVTX);
2999 is_dir = de->d_type == DT_DIR;
3000 keep_around = false;
3006 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3007 if (root_dev && st.st_dev != root_dev->st_dev)
3010 subdir_fd = openat(fd, de->d_name,
3011 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3012 if (subdir_fd < 0) {
3013 if (ret == 0 && errno != ENOENT)
3018 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3019 if (r < 0 && ret == 0)
3023 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3024 if (ret == 0 && errno != ENOENT)
3028 } else if (!only_dirs && !keep_around) {
3030 if (unlinkat(fd, de->d_name, 0) < 0) {
3031 if (ret == 0 && errno != ENOENT)
3042 static int is_temporary_fs(struct statfs *s) {
3044 return s->f_type == TMPFS_MAGIC ||
3045 (long)s->f_type == (long)RAMFS_MAGIC;
3048 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3053 if (fstatfs(fd, &s) < 0) {
3054 close_nointr_nofail(fd);
3058 /* We refuse to clean disk file systems with this call. This
3059 * is extra paranoia just to be sure we never ever remove
3061 if (!is_temporary_fs(&s)) {
3062 log_error("Attempted to remove disk file system, and we can't allow that.");
3063 close_nointr_nofail(fd);
3067 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3070 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3076 /* We refuse to clean the root file system with this
3077 * call. This is extra paranoia to never cause a really
3078 * seriously broken system. */
3079 if (path_equal(path, "/")) {
3080 log_error("Attempted to remove entire root file system, and we can't allow that.");
3084 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3087 if (errno != ENOTDIR)
3091 if (statfs(path, &s) < 0)
3094 if (!is_temporary_fs(&s)) {
3095 log_error("Attempted to remove disk file system, and we can't allow that.");
3100 if (delete_root && !only_dirs)
3101 if (unlink(path) < 0 && errno != ENOENT)
3108 if (fstatfs(fd, &s) < 0) {
3109 close_nointr_nofail(fd);
3113 if (!is_temporary_fs(&s)) {
3114 log_error("Attempted to remove disk file system, and we can't allow that.");
3115 close_nointr_nofail(fd);
3120 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3123 if (honour_sticky && file_is_priv_sticky(path) > 0)
3126 if (rmdir(path) < 0 && errno != ENOENT) {
3135 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3136 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3139 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3140 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3143 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3146 /* Under the assumption that we are running privileged we
3147 * first change the access mode and only then hand out
3148 * ownership to avoid a window where access is too open. */
3150 if (mode != (mode_t) -1)
3151 if (chmod(path, mode) < 0)
3154 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3155 if (chown(path, uid, gid) < 0)
3161 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3164 /* Under the assumption that we are running privileged we
3165 * first change the access mode and only then hand out
3166 * ownership to avoid a window where access is too open. */
3168 if (fchmod(fd, mode) < 0)
3171 if (fchown(fd, uid, gid) < 0)
3177 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3181 /* Allocates the cpuset in the right size */
3184 if (!(r = CPU_ALLOC(n)))
3187 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3188 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3198 if (errno != EINVAL)
3205 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3206 static const char status_indent[] = " "; /* "[" STATUS "] " */
3207 _cleanup_free_ char *s = NULL;
3208 _cleanup_close_ int fd = -1;
3209 struct iovec iovec[5];
3214 /* This is independent of logging, as status messages are
3215 * optional and go exclusively to the console. */
3217 if (vasprintf(&s, format, ap) < 0)
3220 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3233 sl = status ? sizeof(status_indent)-1 : 0;
3239 e = ellipsize(s, emax, 75);
3249 if (!isempty(status)) {
3250 IOVEC_SET_STRING(iovec[n++], "[");
3251 IOVEC_SET_STRING(iovec[n++], status);
3252 IOVEC_SET_STRING(iovec[n++], "] ");
3254 IOVEC_SET_STRING(iovec[n++], status_indent);
3257 IOVEC_SET_STRING(iovec[n++], s);
3258 IOVEC_SET_STRING(iovec[n++], "\n");
3260 if (writev(fd, iovec, n) < 0)
3266 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3272 va_start(ap, format);
3273 r = status_vprintf(status, ellipse, format, ap);
3279 int status_welcome(void) {
3281 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3283 r = parse_env_file("/etc/os-release", NEWLINE,
3284 "PRETTY_NAME", &pretty_name,
3285 "ANSI_COLOR", &ansi_color,
3287 if (r < 0 && r != -ENOENT)
3288 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3290 return status_printf(NULL, false,
3291 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3292 isempty(ansi_color) ? "1" : ansi_color,
3293 isempty(pretty_name) ? "Linux" : pretty_name);
3296 char *replace_env(const char *format, char **env) {
3303 const char *e, *word = format;
3308 for (e = format; *e; e ++) {
3319 if (!(k = strnappend(r, word, e-word-1)))
3328 } else if (*e == '$') {
3329 if (!(k = strnappend(r, word, e-word)))
3345 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3347 k = strappend(r, t);
3361 if (!(k = strnappend(r, word, e-word)))
3372 char **replace_env_argv(char **argv, char **env) {
3374 unsigned k = 0, l = 0;
3376 l = strv_length(argv);
3378 if (!(r = new(char*, l+1)))
3381 STRV_FOREACH(i, argv) {
3383 /* If $FOO appears as single word, replace it by the split up variable */
3384 if ((*i)[0] == '$' && (*i)[1] != '{') {
3389 e = strv_env_get(env, *i+1);
3392 if (!(m = strv_split_quoted(e))) {
3403 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3412 memcpy(r + k, m, q * sizeof(char*));
3420 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3421 if (!(r[k++] = replace_env(*i, env))) {
3431 int fd_columns(int fd) {
3435 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3444 unsigned columns(void) {
3448 if (_likely_(cached_columns > 0))
3449 return cached_columns;
3452 e = getenv("COLUMNS");
3457 c = fd_columns(STDOUT_FILENO);
3466 int fd_lines(int fd) {
3470 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3479 unsigned lines(void) {
3483 if (_likely_(cached_lines > 0))
3484 return cached_lines;
3487 e = getenv("LINES");
3492 l = fd_lines(STDOUT_FILENO);
3498 return cached_lines;
3501 /* intended to be used as a SIGWINCH sighandler */
3502 void columns_lines_cache_reset(int signum) {
3508 static int cached_on_tty = -1;
3510 if (_unlikely_(cached_on_tty < 0))
3511 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3513 return cached_on_tty;
3516 int running_in_chroot(void) {
3522 /* Only works as root */
3524 if (stat("/proc/1/root", &a) < 0)
3527 if (stat("/", &b) < 0)
3531 a.st_dev != b.st_dev ||
3532 a.st_ino != b.st_ino;
3535 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3540 assert(percent <= 100);
3541 assert(new_length >= 3);
3543 if (old_length <= 3 || old_length <= new_length)
3544 return strndup(s, old_length);
3546 r = new0(char, new_length+1);
3550 x = (new_length * percent) / 100;
3552 if (x > new_length - 3)
3560 s + old_length - (new_length - x - 3),
3561 new_length - x - 3);
3566 char *ellipsize(const char *s, size_t length, unsigned percent) {
3567 return ellipsize_mem(s, strlen(s), length, percent);
3570 int touch(const char *path) {
3575 /* This just opens the file for writing, ensuring it
3576 * exists. It doesn't call utimensat() the way /usr/bin/touch
3579 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3583 close_nointr_nofail(fd);
3587 char *unquote(const char *s, const char* quotes) {
3591 /* This is rather stupid, simply removes the heading and
3592 * trailing quotes if there is one. Doesn't care about
3593 * escaping or anything. We should make this smarter one
3600 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3601 return strndup(s+1, l-2);
3606 char *normalize_env_assignment(const char *s) {
3607 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3610 eq = strchr(s, '=');
3622 memmove(r, t, strlen(t) + 1);
3626 name = strndup(s, eq - s);
3634 value = unquote(strstrip(p), QUOTES);
3638 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3644 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3655 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3667 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3674 r = wait_for_terminate(pid, &status);
3676 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3680 if (status.si_code == CLD_EXITED) {
3681 if (status.si_status != 0) {
3682 log_warning("%s failed with error code %i.", name, status.si_status);
3683 return status.si_status;
3686 log_debug("%s succeeded.", name);
3689 } else if (status.si_code == CLD_KILLED ||
3690 status.si_code == CLD_DUMPED) {
3692 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3696 log_warning("%s failed due to unknown reason.", name);
3700 _noreturn_ void freeze(void) {
3702 /* Make sure nobody waits for us on a socket anymore */
3703 close_all_fds(NULL, 0);
3711 bool null_or_empty(struct stat *st) {
3714 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3717 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3723 int null_or_empty_path(const char *fn) {
3728 if (stat(fn, &st) < 0)
3731 return null_or_empty(&st);
3734 DIR *xopendirat(int fd, const char *name, int flags) {
3738 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3744 close_nointr_nofail(nfd);
3751 int signal_from_string_try_harder(const char *s) {
3755 signo = signal_from_string(s);
3757 if (startswith(s, "SIG"))
3758 return signal_from_string(s+3);
3763 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3767 /* FIXME: to follow udev's logic 100% we need to leave valid
3768 * UTF8 chars unescaped */
3770 u = unquote(tagvalue, "\"\'");
3774 t = xescape(u, "/ ");
3780 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3789 char *fstab_node_to_udev_node(const char *p) {
3792 if (startswith(p, "LABEL="))
3793 return tag_to_udev_node(p+6, "label");
3795 if (startswith(p, "UUID="))
3796 return tag_to_udev_node(p+5, "uuid");
3798 if (startswith(p, "PARTUUID="))
3799 return tag_to_udev_node(p+9, "partuuid");
3801 if (startswith(p, "PARTLABEL="))
3802 return tag_to_udev_node(p+10, "partlabel");
3807 bool tty_is_vc(const char *tty) {
3810 if (startswith(tty, "/dev/"))
3813 return vtnr_from_tty(tty) >= 0;
3816 bool tty_is_console(const char *tty) {
3819 if (startswith(tty, "/dev/"))
3822 return streq(tty, "console");
3825 int vtnr_from_tty(const char *tty) {
3830 if (startswith(tty, "/dev/"))
3833 if (!startswith(tty, "tty") )
3836 if (tty[3] < '0' || tty[3] > '9')
3839 r = safe_atoi(tty+3, &i);
3843 if (i < 0 || i > 63)
3849 bool tty_is_vc_resolve(const char *tty) {
3850 char *active = NULL;
3855 if (startswith(tty, "/dev/"))
3858 /* Resolve where /dev/console is pointing to, if /sys is
3859 * actually ours (i.e. not read-only-mounted which is a sign
3860 * for container setups) */
3861 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
3862 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3863 /* If multiple log outputs are configured the
3864 * last one is what /dev/console points to */
3865 tty = strrchr(active, ' ');
3878 const char *default_term_for_tty(const char *tty) {
3881 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3884 bool dirent_is_file(const struct dirent *de) {
3887 if (ignore_file(de->d_name))
3890 if (de->d_type != DT_REG &&
3891 de->d_type != DT_LNK &&
3892 de->d_type != DT_UNKNOWN)
3898 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3901 if (de->d_type != DT_REG &&
3902 de->d_type != DT_LNK &&
3903 de->d_type != DT_UNKNOWN)
3906 if (ignore_file_allow_backup(de->d_name))
3909 return endswith(de->d_name, suffix);
3912 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3915 Hashmap *pids = NULL;
3919 /* Executes all binaries in a directory in parallel and waits
3920 * until all they all finished. */
3923 if (!(_d = opendir(directory))) {
3925 if (errno == ENOENT)
3928 log_error("Failed to enumerate directory %s: %m", directory);
3935 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3936 log_error("Failed to allocate set.");
3940 while ((de = readdir(d))) {
3945 if (!dirent_is_file(de))
3948 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3953 if ((pid = fork()) < 0) {
3954 log_error("Failed to fork: %m");
3972 log_error("Failed to execute %s: %m", path);
3973 _exit(EXIT_FAILURE);
3976 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3978 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3979 log_error("Failed to add PID to set: %s", strerror(-k));
3984 while (!hashmap_isempty(pids)) {
3985 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3990 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3995 log_error("waitid() failed: %m");
3999 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4000 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4001 if (si.si_code == CLD_EXITED)
4002 log_error("%s exited with exit status %i.", path, si.si_status);
4004 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4006 log_debug("%s exited successfully.", path);
4017 hashmap_free_free(pids);
4020 int kill_and_sigcont(pid_t pid, int sig) {
4023 r = kill(pid, sig) < 0 ? -errno : 0;
4031 bool nulstr_contains(const char*nulstr, const char *needle) {
4037 NULSTR_FOREACH(i, nulstr)
4038 if (streq(i, needle))
4044 bool plymouth_running(void) {
4045 return access("/run/plymouth/pid", F_OK) >= 0;
4048 char* strshorten(char *s, size_t l) {
4057 static bool hostname_valid_char(char c) {
4059 (c >= 'a' && c <= 'z') ||
4060 (c >= 'A' && c <= 'Z') ||
4061 (c >= '0' && c <= '9') ||
4067 bool hostname_is_valid(const char *s) {
4073 for (p = s; *p; p++)
4074 if (!hostname_valid_char(*p))
4077 if (p-s > HOST_NAME_MAX)
4083 char* hostname_cleanup(char *s) {
4086 for (p = s, d = s; *p; p++)
4087 if ((*p >= 'a' && *p <= 'z') ||
4088 (*p >= 'A' && *p <= 'Z') ||
4089 (*p >= '0' && *p <= '9') ||
4097 strshorten(s, HOST_NAME_MAX);
4101 int pipe_eof(int fd) {
4102 struct pollfd pollfd;
4107 pollfd.events = POLLIN|POLLHUP;
4109 r = poll(&pollfd, 1, 0);
4116 return pollfd.revents & POLLHUP;
4119 int fd_wait_for_event(int fd, int event, usec_t t) {
4120 struct pollfd pollfd;
4125 pollfd.events = event;
4127 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4134 return pollfd.revents;
4137 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4148 t = new(char, strlen(path) + 1 + 6 + 1);
4152 fn = path_get_file_name(path);
4156 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4158 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4164 f = fdopen(fd, "we");
4177 int terminal_vhangup_fd(int fd) {
4180 if (ioctl(fd, TIOCVHANGUP) < 0)
4186 int terminal_vhangup(const char *name) {
4189 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4193 r = terminal_vhangup_fd(fd);
4194 close_nointr_nofail(fd);
4199 int vt_disallocate(const char *name) {
4203 /* Deallocate the VT if possible. If not possible
4204 * (i.e. because it is the active one), at least clear it
4205 * entirely (including the scrollback buffer) */
4207 if (!startswith(name, "/dev/"))
4210 if (!tty_is_vc(name)) {
4211 /* So this is not a VT. I guess we cannot deallocate
4212 * it then. But let's at least clear the screen */
4214 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4219 "\033[r" /* clear scrolling region */
4220 "\033[H" /* move home */
4221 "\033[2J", /* clear screen */
4223 close_nointr_nofail(fd);
4228 if (!startswith(name, "/dev/tty"))
4231 r = safe_atou(name+8, &u);
4238 /* Try to deallocate */
4239 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4243 r = ioctl(fd, VT_DISALLOCATE, u);
4244 close_nointr_nofail(fd);
4252 /* Couldn't deallocate, so let's clear it fully with
4254 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4259 "\033[r" /* clear scrolling region */
4260 "\033[H" /* move home */
4261 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4263 close_nointr_nofail(fd);
4268 int copy_file(const char *from, const char *to) {
4274 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4278 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4280 close_nointr_nofail(fdf);
4288 n = read(fdf, buf, sizeof(buf));
4292 close_nointr_nofail(fdf);
4303 k = loop_write(fdt, buf, n, false);
4305 r = k < 0 ? k : (errno ? -errno : -EIO);
4307 close_nointr_nofail(fdf);
4315 close_nointr_nofail(fdf);
4316 r = close_nointr(fdt);
4326 int symlink_atomic(const char *from, const char *to) {
4328 _cleanup_free_ char *t;
4331 unsigned long long ull;
4338 t = new(char, strlen(to) + 1 + 16 + 1);
4342 fn = path_get_file_name(to);
4346 x = stpcpy(t+k+1, fn);
4349 for (i = 0; i < 16; i++) {
4350 *(x++) = hexchar(ull & 0xF);
4356 if (symlink(from, t) < 0)
4359 if (rename(t, to) < 0) {
4368 bool display_is_local(const char *display) {
4372 display[0] == ':' &&
4373 display[1] >= '0' &&
4377 int socket_from_display(const char *display, char **path) {
4384 if (!display_is_local(display))
4387 k = strspn(display+1, "0123456789");
4389 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4393 c = stpcpy(f, "/tmp/.X11-unix/X");
4394 memcpy(c, display+1, k);
4403 const char **username,
4404 uid_t *uid, gid_t *gid,
4406 const char **shell) {
4414 /* We enforce some special rules for uid=0: in order to avoid
4415 * NSS lookups for root we hardcode its data. */
4417 if (streq(*username, "root") || streq(*username, "0")) {
4435 if (parse_uid(*username, &u) >= 0) {
4439 /* If there are multiple users with the same id, make
4440 * sure to leave $USER to the configured value instead
4441 * of the first occurrence in the database. However if
4442 * the uid was configured by a numeric uid, then let's
4443 * pick the real username from /etc/passwd. */
4445 *username = p->pw_name;
4448 p = getpwnam(*username);
4452 return errno != 0 ? -errno : -ESRCH;
4464 *shell = p->pw_shell;
4469 char* uid_to_name(uid_t uid) {
4474 return strdup("root");
4478 return strdup(p->pw_name);
4480 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4486 int get_group_creds(const char **groupname, gid_t *gid) {
4492 /* We enforce some special rules for gid=0: in order to avoid
4493 * NSS lookups for root we hardcode its data. */
4495 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4496 *groupname = "root";
4504 if (parse_gid(*groupname, &id) >= 0) {
4509 *groupname = g->gr_name;
4512 g = getgrnam(*groupname);
4516 return errno != 0 ? -errno : -ESRCH;
4524 int in_group(const char *name) {
4526 int ngroups_max, r, i;
4528 r = get_group_creds(&name, &gid);
4532 if (getgid() == gid)
4535 if (getegid() == gid)
4538 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4539 assert(ngroups_max > 0);
4541 gids = alloca(sizeof(gid_t) * ngroups_max);
4543 r = getgroups(ngroups_max, gids);
4547 for (i = 0; i < r; i++)
4554 int glob_exists(const char *path) {
4562 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4564 if (k == GLOB_NOMATCH)
4566 else if (k == GLOB_NOSPACE)
4569 r = !strv_isempty(g.gl_pathv);
4571 r = errno ? -errno : -EIO;
4578 int dirent_ensure_type(DIR *d, struct dirent *de) {
4584 if (de->d_type != DT_UNKNOWN)
4587 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4591 S_ISREG(st.st_mode) ? DT_REG :
4592 S_ISDIR(st.st_mode) ? DT_DIR :
4593 S_ISLNK(st.st_mode) ? DT_LNK :
4594 S_ISFIFO(st.st_mode) ? DT_FIFO :
4595 S_ISSOCK(st.st_mode) ? DT_SOCK :
4596 S_ISCHR(st.st_mode) ? DT_CHR :
4597 S_ISBLK(st.st_mode) ? DT_BLK :
4603 int in_search_path(const char *path, char **search) {
4607 r = path_get_parent(path, &parent);
4613 STRV_FOREACH(i, search) {
4614 if (path_equal(parent, *i)) {
4625 int get_files_in_directory(const char *path, char ***list) {
4633 /* Returns all files in a directory in *list, and the number
4634 * of files as return value. If list is NULL returns only the
4643 union dirent_storage buf;
4646 k = readdir_r(d, &buf.de, &de);
4655 dirent_ensure_type(d, de);
4657 if (!dirent_is_file(de))
4661 if ((unsigned) r >= n) {
4665 t = realloc(l, sizeof(char*) * n);
4674 assert((unsigned) r < n);
4676 l[r] = strdup(de->d_name);
4700 char *strjoin(const char *x, ...) {
4714 t = va_arg(ap, const char *);
4719 if (n > ((size_t) -1) - l) {
4743 t = va_arg(ap, const char *);
4757 bool is_main_thread(void) {
4758 static __thread int cached = 0;
4760 if (_unlikely_(cached == 0))
4761 cached = getpid() == gettid() ? 1 : -1;
4766 int block_get_whole_disk(dev_t d, dev_t *ret) {
4773 /* If it has a queue this is good enough for us */
4774 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4777 r = access(p, F_OK);
4785 /* If it is a partition find the originating device */
4786 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4789 r = access(p, F_OK);
4795 /* Get parent dev_t */
4796 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4799 r = read_one_line_file(p, &s);
4805 r = sscanf(s, "%u:%u", &m, &n);
4811 /* Only return this if it is really good enough for us. */
4812 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4815 r = access(p, F_OK);
4819 *ret = makedev(m, n);
4826 int file_is_priv_sticky(const char *p) {
4831 if (lstat(p, &st) < 0)
4835 (st.st_uid == 0 || st.st_uid == getuid()) &&
4836 (st.st_mode & S_ISVTX);
4839 static const char *const ioprio_class_table[] = {
4840 [IOPRIO_CLASS_NONE] = "none",
4841 [IOPRIO_CLASS_RT] = "realtime",
4842 [IOPRIO_CLASS_BE] = "best-effort",
4843 [IOPRIO_CLASS_IDLE] = "idle"
4846 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4848 static const char *const sigchld_code_table[] = {
4849 [CLD_EXITED] = "exited",
4850 [CLD_KILLED] = "killed",
4851 [CLD_DUMPED] = "dumped",
4852 [CLD_TRAPPED] = "trapped",
4853 [CLD_STOPPED] = "stopped",
4854 [CLD_CONTINUED] = "continued",
4857 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4859 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4860 [LOG_FAC(LOG_KERN)] = "kern",
4861 [LOG_FAC(LOG_USER)] = "user",
4862 [LOG_FAC(LOG_MAIL)] = "mail",
4863 [LOG_FAC(LOG_DAEMON)] = "daemon",
4864 [LOG_FAC(LOG_AUTH)] = "auth",
4865 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4866 [LOG_FAC(LOG_LPR)] = "lpr",
4867 [LOG_FAC(LOG_NEWS)] = "news",
4868 [LOG_FAC(LOG_UUCP)] = "uucp",
4869 [LOG_FAC(LOG_CRON)] = "cron",
4870 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4871 [LOG_FAC(LOG_FTP)] = "ftp",
4872 [LOG_FAC(LOG_LOCAL0)] = "local0",
4873 [LOG_FAC(LOG_LOCAL1)] = "local1",
4874 [LOG_FAC(LOG_LOCAL2)] = "local2",
4875 [LOG_FAC(LOG_LOCAL3)] = "local3",
4876 [LOG_FAC(LOG_LOCAL4)] = "local4",
4877 [LOG_FAC(LOG_LOCAL5)] = "local5",
4878 [LOG_FAC(LOG_LOCAL6)] = "local6",
4879 [LOG_FAC(LOG_LOCAL7)] = "local7"
4882 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4884 static const char *const log_level_table[] = {
4885 [LOG_EMERG] = "emerg",
4886 [LOG_ALERT] = "alert",
4887 [LOG_CRIT] = "crit",
4889 [LOG_WARNING] = "warning",
4890 [LOG_NOTICE] = "notice",
4891 [LOG_INFO] = "info",
4892 [LOG_DEBUG] = "debug"
4895 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4897 static const char* const sched_policy_table[] = {
4898 [SCHED_OTHER] = "other",
4899 [SCHED_BATCH] = "batch",
4900 [SCHED_IDLE] = "idle",
4901 [SCHED_FIFO] = "fifo",
4905 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4907 static const char* const rlimit_table[] = {
4908 [RLIMIT_CPU] = "LimitCPU",
4909 [RLIMIT_FSIZE] = "LimitFSIZE",
4910 [RLIMIT_DATA] = "LimitDATA",
4911 [RLIMIT_STACK] = "LimitSTACK",
4912 [RLIMIT_CORE] = "LimitCORE",
4913 [RLIMIT_RSS] = "LimitRSS",
4914 [RLIMIT_NOFILE] = "LimitNOFILE",
4915 [RLIMIT_AS] = "LimitAS",
4916 [RLIMIT_NPROC] = "LimitNPROC",
4917 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4918 [RLIMIT_LOCKS] = "LimitLOCKS",
4919 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4920 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4921 [RLIMIT_NICE] = "LimitNICE",
4922 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4923 [RLIMIT_RTTIME] = "LimitRTTIME"
4926 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4928 static const char* const ip_tos_table[] = {
4929 [IPTOS_LOWDELAY] = "low-delay",
4930 [IPTOS_THROUGHPUT] = "throughput",
4931 [IPTOS_RELIABILITY] = "reliability",
4932 [IPTOS_LOWCOST] = "low-cost",
4935 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4937 static const char *const __signal_table[] = {
4954 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4965 [SIGVTALRM] = "VTALRM",
4967 [SIGWINCH] = "WINCH",
4973 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4975 const char *signal_to_string(int signo) {
4976 static __thread char buf[12];
4979 name = __signal_to_string(signo);
4983 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4984 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4986 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4991 int signal_from_string(const char *s) {
4996 signo = __signal_from_string(s);
5000 if (startswith(s, "RTMIN+")) {
5004 if (safe_atou(s, &u) >= 0) {
5005 signo = (int) u + offset;
5006 if (signo > 0 && signo < _NSIG)
5012 bool kexec_loaded(void) {
5013 bool loaded = false;
5016 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5024 int strdup_or_null(const char *a, char **b) {
5042 int prot_from_flags(int flags) {
5044 switch (flags & O_ACCMODE) {
5053 return PROT_READ|PROT_WRITE;
5060 char *format_bytes(char *buf, size_t l, off_t t) {
5063 static const struct {
5067 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5068 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5069 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5070 { "G", 1024ULL*1024ULL*1024ULL },
5071 { "M", 1024ULL*1024ULL },
5075 for (i = 0; i < ELEMENTSOF(table); i++) {
5077 if (t >= table[i].factor) {
5080 (unsigned long long) (t / table[i].factor),
5081 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5088 snprintf(buf, l, "%lluB", (unsigned long long) t);
5096 void* memdup(const void *p, size_t l) {
5109 int fd_inc_sndbuf(int fd, size_t n) {
5111 socklen_t l = sizeof(value);
5113 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5115 l == sizeof(value) &&
5116 (size_t) value >= n*2)
5120 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5127 int fd_inc_rcvbuf(int fd, size_t n) {
5129 socklen_t l = sizeof(value);
5131 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5133 l == sizeof(value) &&
5134 (size_t) value >= n*2)
5138 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5145 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5146 pid_t parent_pid, agent_pid;
5148 bool stdout_is_tty, stderr_is_tty;
5156 parent_pid = getpid();
5158 /* Spawns a temporary TTY agent, making sure it goes away when
5165 if (agent_pid != 0) {
5172 * Make sure the agent goes away when the parent dies */
5173 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5174 _exit(EXIT_FAILURE);
5176 /* Check whether our parent died before we were able
5177 * to set the death signal */
5178 if (getppid() != parent_pid)
5179 _exit(EXIT_SUCCESS);
5181 /* Don't leak fds to the agent */
5182 close_all_fds(except, n_except);
5184 stdout_is_tty = isatty(STDOUT_FILENO);
5185 stderr_is_tty = isatty(STDERR_FILENO);
5187 if (!stdout_is_tty || !stderr_is_tty) {
5188 /* Detach from stdout/stderr. and reopen
5189 * /dev/tty for them. This is important to
5190 * ensure that when systemctl is started via
5191 * popen() or a similar call that expects to
5192 * read EOF we actually do generate EOF and
5193 * not delay this indefinitely by because we
5194 * keep an unused copy of stdin around. */
5195 fd = open("/dev/tty", O_WRONLY);
5197 log_error("Failed to open /dev/tty: %m");
5198 _exit(EXIT_FAILURE);
5202 dup2(fd, STDOUT_FILENO);
5205 dup2(fd, STDERR_FILENO);
5211 /* Count arguments */
5213 for (n = 0; va_arg(ap, char*); n++)
5218 l = alloca(sizeof(char *) * (n + 1));
5220 /* Fill in arguments */
5222 for (i = 0; i <= n; i++)
5223 l[i] = va_arg(ap, char*);
5227 _exit(EXIT_FAILURE);
5230 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5231 struct rlimit highest, fixed;
5235 if (setrlimit(resource, rlim) >= 0)
5241 /* So we failed to set the desired setrlimit, then let's try
5242 * to get as close as we can */
5243 assert_se(getrlimit(resource, &highest) == 0);
5245 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5246 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5248 if (setrlimit(resource, &fixed) < 0)
5254 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5255 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5267 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5270 f = fopen(path, "re");
5278 char line[LINE_MAX];
5281 for (i = 0; i < sizeof(line)-1; i++) {
5285 if (_unlikely_(c == EOF)) {
5295 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5296 value = strdup(line + l + 1);
5316 int can_sleep(const char *type) {
5320 _cleanup_free_ char *p = NULL;
5324 /* If /sys is read-only we cannot sleep */
5325 if (access("/sys/power/state", W_OK) < 0)
5328 r = read_one_line_file("/sys/power/state", &p);
5333 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5334 if (l == k && memcmp(w, type, l) == 0)
5340 int can_sleep_disk(const char *type) {
5344 _cleanup_free_ char *p = NULL;
5348 /* If /sys is read-only we cannot sleep */
5349 if (access("/sys/power/state", W_OK) < 0 ||
5350 access("/sys/power/disk", W_OK) < 0)
5353 r = read_one_line_file("/sys/power/disk", &p);
5358 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5359 if (l == k && memcmp(w, type, l) == 0)
5362 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5369 bool is_valid_documentation_url(const char *url) {
5372 if (startswith(url, "http://") && url[7])
5375 if (startswith(url, "https://") && url[8])
5378 if (startswith(url, "file:") && url[5])
5381 if (startswith(url, "info:") && url[5])
5384 if (startswith(url, "man:") && url[4])
5390 bool in_initrd(void) {
5391 static __thread int saved = -1;
5397 /* We make two checks here:
5399 * 1. the flag file /etc/initrd-release must exist
5400 * 2. the root file system must be a memory file system
5402 * The second check is extra paranoia, since misdetecting an
5403 * initrd can have bad bad consequences due the initrd
5404 * emptying when transititioning to the main systemd.
5407 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5408 statfs("/", &s) >= 0 &&
5409 is_temporary_fs(&s);
5414 void warn_melody(void) {
5415 _cleanup_close_ int fd = -1;
5417 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5421 /* Yeah, this is synchronous. Kinda sucks. But well... */
5423 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5424 usleep(125*USEC_PER_MSEC);
5426 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5427 usleep(125*USEC_PER_MSEC);
5429 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5430 usleep(125*USEC_PER_MSEC);
5432 ioctl(fd, KIOCSOUND, 0);
5435 int make_console_stdio(void) {
5438 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5440 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5442 log_error("Failed to acquire terminal: %s", strerror(-fd));
5448 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5455 int get_home_dir(char **_h) {
5463 /* Take the user specified one */
5474 /* Hardcode home directory for root to avoid NSS */
5477 h = strdup("/root");
5485 /* Check the database... */
5489 return errno ? -errno : -ESRCH;
5491 if (!path_is_absolute(p->pw_dir))
5494 h = strdup(p->pw_dir);
5502 int get_shell(char **_sh) {
5510 /* Take the user specified one */
5511 e = getenv("SHELL");
5521 /* Hardcode home directory for root to avoid NSS */
5524 sh = strdup("/bin/sh");
5532 /* Check the database... */
5536 return errno ? -errno : -ESRCH;
5538 if (!path_is_absolute(p->pw_shell))
5541 sh = strdup(p->pw_shell);
5549 void freep(void *p) {
5553 void fclosep(FILE **f) {
5558 void pclosep(FILE **f) {
5563 void closep(int *fd) {
5565 close_nointr_nofail(*fd);
5568 void closedirp(DIR **d) {
5573 void umaskp(mode_t *u) {
5577 bool filename_is_safe(const char *p) {
5591 if (strlen(p) > FILENAME_MAX)
5597 bool string_is_safe(const char *p) {
5602 for (t = p; *t; t++) {
5603 if (*t > 0 && *t < ' ')
5606 if (strchr("\\\"\'", *t))
5613 bool string_has_cc(const char *p) {
5618 for (t = p; *t; t++)
5619 if (*t > 0 && *t < ' ')
5625 bool path_is_safe(const char *p) {
5630 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5633 if (strlen(p) > PATH_MAX)
5636 /* The following two checks are not really dangerous, but hey, they still are confusing */
5637 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5640 if (strstr(p, "//"))
5646 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5647 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5648 int (*compar) (const void *, const void *, void *), void *arg) {
5657 p = (void *)(((const char *) base) + (idx * size));
5658 comparison = compar(key, p, arg);
5661 else if (comparison > 0)
5669 bool is_locale_utf8(void) {
5671 static int cached_answer = -1;
5673 if (cached_answer >= 0)
5676 if (!setlocale(LC_ALL, "")) {
5677 cached_answer = true;
5681 set = nl_langinfo(CODESET);
5683 cached_answer = true;
5687 cached_answer = streq(set, "UTF-8");
5689 return (bool)cached_answer;
5692 const char *draw_special_char(DrawSpecialChar ch) {
5693 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5695 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5696 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5697 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5698 [DRAW_TREE_SPACE] = " ", /* */
5699 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5701 /* ASCII fallback */ {
5702 [DRAW_TREE_VERT] = "| ",
5703 [DRAW_TREE_BRANCH] = "|-",
5704 [DRAW_TREE_RIGHT] = "`-",
5705 [DRAW_TREE_SPACE] = " ",
5706 [DRAW_TRIANGULAR_BULLET] = "> ",
5710 return draw_table[!is_locale_utf8()][ch];
5713 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5716 size_t l, old_len, new_len;
5722 old_len = strlen(old_string);
5723 new_len = strlen(new_string);
5736 if (!startswith(f, old_string)) {
5742 nl = l - old_len + new_len;
5743 a = realloc(r, nl + 1);
5751 t = stpcpy(t, new_string);
5763 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5764 const char *i, *begin = NULL;
5769 } state = STATE_OTHER;
5771 size_t osz = 0, isz;
5777 /* Strips ANSI color and replaces TABs by 8 spaces */
5779 isz = _isz ? *_isz : strlen(*ibuf);
5781 f = open_memstream(&obuf, &osz);
5785 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5790 if (i >= *ibuf + isz) /* EOT */
5792 else if (*i == '\x1B')
5793 state = STATE_ESCAPE;
5794 else if (*i == '\t')
5801 if (i >= *ibuf + isz) { /* EOT */
5804 } else if (*i == '[') {
5805 state = STATE_BRACKET;
5810 state = STATE_OTHER;
5817 if (i >= *ibuf + isz || /* EOT */
5818 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5821 state = STATE_OTHER;
5823 } else if (*i == 'm')
5824 state = STATE_OTHER;
5846 int on_ac_power(void) {
5847 bool found_offline = false, found_online = false;
5848 _cleanup_closedir_ DIR *d = NULL;
5850 d = opendir("/sys/class/power_supply");
5856 union dirent_storage buf;
5857 _cleanup_free_ char *p = NULL;
5858 _cleanup_close_ int fd = -1, device = -1;
5863 k = readdir_r(d, &buf.de, &de);
5870 if (ignore_file(de->d_name))
5873 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5875 if (errno == ENOENT || errno == ENOTDIR)
5881 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5883 if (errno == ENOENT)
5889 n = read(fd, contents, sizeof(contents));
5893 if (n != 6 || memcmp(contents, "Mains\n", 6))
5896 close_nointr_nofail(fd);
5897 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5899 if (errno == ENOENT)
5905 n = read(fd, contents, sizeof(contents));
5909 if (n != 2 || contents[1] != '\n')
5912 if (contents[0] == '1') {
5913 found_online = true;
5915 } else if (contents[0] == '0')
5916 found_offline = true;
5921 return found_online || !found_offline;