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) {
191 /* Just ignore EINTR; a retry loop is the wrong
192 * thing to do on Linux.
194 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
195 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
196 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
197 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
199 if (_unlikely_(r < 0 && errno == EINTR))
207 void close_nointr_nofail(int fd) {
208 int saved_errno = errno;
210 /* like close_nointr() but cannot fail, and guarantees errno
213 assert_se(close_nointr(fd) == 0);
218 void close_many(const int fds[], unsigned n_fd) {
221 for (i = 0; i < n_fd; i++)
222 close_nointr_nofail(fds[i]);
225 int parse_boolean(const char *v) {
228 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
230 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
236 int parse_pid(const char *s, pid_t* ret_pid) {
237 unsigned long ul = 0;
244 r = safe_atolu(s, &ul);
250 if ((unsigned long) pid != ul)
260 int parse_uid(const char *s, uid_t* ret_uid) {
261 unsigned long ul = 0;
268 r = safe_atolu(s, &ul);
274 if ((unsigned long) uid != ul)
281 int safe_atou(const char *s, unsigned *ret_u) {
289 l = strtoul(s, &x, 0);
291 if (!x || x == s || *x || errno)
292 return errno ? -errno : -EINVAL;
294 if ((unsigned long) (unsigned) l != l)
297 *ret_u = (unsigned) l;
301 int safe_atoi(const char *s, int *ret_i) {
309 l = strtol(s, &x, 0);
311 if (!x || x == s || *x || errno)
312 return errno ? -errno : -EINVAL;
314 if ((long) (int) l != l)
321 int safe_atollu(const char *s, long long unsigned *ret_llu) {
323 unsigned long long l;
329 l = strtoull(s, &x, 0);
331 if (!x || x == s || *x || errno)
332 return errno ? -errno : -EINVAL;
338 int safe_atolli(const char *s, long long int *ret_lli) {
346 l = strtoll(s, &x, 0);
348 if (!x || x == s || *x || errno)
349 return errno ? -errno : -EINVAL;
355 /* Split a string into words. */
356 char *split(const char *c, size_t *l, const char *separator, char **state) {
359 current = *state ? *state : (char*) c;
361 if (!*current || *c == 0)
364 current += strspn(current, separator);
365 *l = strcspn(current, separator);
368 return (char*) current;
371 /* Split a string into words, but consider strings enclosed in '' and
372 * "" as words even if they include spaces. */
373 char *split_quoted(const char *c, size_t *l, char **state) {
375 bool escaped = false;
377 current = *state ? *state : (char*) c;
379 if (!*current || *c == 0)
382 current += strspn(current, WHITESPACE);
384 if (*current == '\'') {
387 for (e = current; *e; e++) {
397 *state = *e == 0 ? e : e+1;
398 } else if (*current == '\"') {
401 for (e = current; *e; e++) {
411 *state = *e == 0 ? e : e+1;
413 for (e = current; *e; e++) {
418 else if (strchr(WHITESPACE, *e))
425 return (char*) current;
428 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
430 _cleanup_fclose_ FILE *f = NULL;
431 char fn[PATH_MAX], line[LINE_MAX], *p;
437 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
444 if (!fgets(line, sizeof(line), f)) {
445 r = feof(f) ? -EIO : -errno;
449 /* Let's skip the pid and comm fields. The latter is enclosed
450 * in () but does not escape any () in its value, so let's
451 * skip over it manually */
453 p = strrchr(line, ')');
465 if ((long unsigned) (pid_t) ppid != ppid)
468 *_ppid = (pid_t) ppid;
473 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
474 _cleanup_fclose_ FILE *f = NULL;
475 char fn[PATH_MAX], line[LINE_MAX], *p;
480 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
487 if (!fgets(line, sizeof(line), f)) {
494 /* Let's skip the pid and comm fields. The latter is enclosed
495 * in () but does not escape any () in its value, so let's
496 * skip over it manually */
498 p = strrchr(line, ')');
520 "%*d " /* priority */
522 "%*d " /* num_threads */
523 "%*d " /* itrealvalue */
524 "%llu " /* starttime */,
531 int write_one_line_file(const char *fn, const char *line) {
532 _cleanup_fclose_ FILE *f = NULL;
542 if (fputs(line, f) < 0)
543 return errno ? -errno : -EIO;
545 if (!endswith(line, "\n"))
551 return errno ? -errno : -EIO;
556 int fchmod_umask(int fd, mode_t m) {
561 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
567 int write_one_line_file_atomic(const char *fn, const char *line) {
568 _cleanup_fclose_ FILE *f = NULL;
569 _cleanup_free_ char *p = NULL;
575 r = fopen_temporary(fn, &f, &p);
579 fchmod_umask(fileno(f), 0644);
582 if (fputs(line, f) < 0) {
587 if (!endswith(line, "\n"))
593 r = errno ? -errno : -EIO;
595 if (rename(p, fn) < 0)
608 int read_one_line_file(const char *fn, char **line) {
609 _cleanup_fclose_ FILE *f = NULL;
610 char t[LINE_MAX], *c;
619 if (!fgets(t, sizeof(t), f)) {
622 return errno ? -errno : -EIO;
636 int read_full_file(const char *fn, char **contents, size_t *size) {
637 _cleanup_fclose_ FILE *f = NULL;
639 _cleanup_free_ char *buf = NULL;
649 if (fstat(fileno(f), &st) < 0)
653 if (st.st_size > 4*1024*1024)
656 n = st.st_size > 0 ? st.st_size : LINE_MAX;
663 t = realloc(buf, n+1);
668 k = fread(buf + l, 1, n - l, f);
697 const char *separator, ...) {
700 char *contents = NULL, *p;
705 if ((r = read_full_file(fname, &contents, NULL)) < 0)
710 const char *key = NULL;
712 p += strspn(p, separator);
713 p += strspn(p, WHITESPACE);
718 if (!strchr(COMMENTS, *p)) {
722 va_start(ap, separator);
723 while ((key = va_arg(ap, char *))) {
727 value = va_arg(ap, char **);
730 if (!strneq(p, key, n) ||
735 n = strcspn(p, separator);
738 strchr(QUOTES, p[0]) &&
740 v = strndup(p+1, n-2);
751 /* return empty value strings as NULL */
768 p += strcspn(p, separator);
776 int load_env_file(const char *fname, char ***rl) {
778 _cleanup_fclose_ FILE *f;
779 _cleanup_strv_free_ char **m = NULL;
780 _cleanup_free_ char *c = NULL;
785 /* This reads an environment file, but will not complain about
786 * any invalid assignments, that needs to be done by the
789 f = fopen(fname, "re");
794 char l[LINE_MAX], *p, *cs, *b;
796 if (!fgets(l, sizeof(l), f)) {
800 /* The previous line was a continuation line?
801 * Let's process it now, before we leave the
809 /* Is this a continuation line? If so, just append
810 * this to c, and go to next line right-away */
811 cs = endswith(l, "\\\n");
823 /* If the previous line was a continuation line,
824 * append the current line to it */
835 p = strstrip(c ? c : l);
837 if (*p && !strchr(COMMENTS, *p)) {
838 _cleanup_free_ char *u;
841 u = normalize_env_assignment(p);
845 k = strv_extend(&m, u);
860 int write_env_file(const char *fname, char **l) {
865 r = fopen_temporary(fname, &f, &p);
869 fchmod_umask(fileno(f), 0644);
885 if (rename(p, fname) < 0)
900 char *truncate_nl(char *s) {
903 s[strcspn(s, NEWLINE)] = 0;
907 int get_process_comm(pid_t pid, char **name) {
913 r = read_one_line_file("/proc/self/comm", name);
916 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
919 r = read_one_line_file(p, name);
926 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
934 f = fopen("/proc/self/cmdline", "re");
937 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
946 if (max_length == 0) {
948 while ((c = getc(f)) != EOF) {
949 k = realloc(r, len+1);
956 r[len-1] = isprint(c) ? c : ' ';
963 r = new(char, max_length);
971 while ((c = getc(f)) != EOF) {
993 size_t n = MIN(left-1, 3U);
1002 /* Kernel threads have no argv[] */
1003 if (r == NULL || r[0] == 0) {
1012 h = get_process_comm(pid, &t);
1016 r = strjoin("[", t, "]", NULL);
1027 int is_kernel_thread(pid_t pid) {
1037 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1046 count = fread(&c, 1, 1, f);
1050 /* Kernel threads have an empty cmdline */
1053 return eof ? 1 : -errno;
1058 int get_process_exe(pid_t pid, char **name) {
1064 r = readlink_malloc("/proc/self/exe", name);
1067 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1070 r = readlink_malloc(p, name);
1077 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1078 _cleanup_fclose_ FILE *f = NULL;
1079 _cleanup_free_ char *p = NULL;
1080 char line[LINE_MAX];
1088 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1095 FOREACH_LINE(line, f, return -errno) {
1100 if (startswith(l, field)) {
1102 l += strspn(l, WHITESPACE);
1104 l[strcspn(l, WHITESPACE)] = 0;
1106 return parse_uid(l, uid);
1113 int get_process_uid(pid_t pid, uid_t *uid) {
1114 return get_process_id(pid, "Uid:", uid);
1117 int get_process_gid(pid_t pid, gid_t *gid) {
1118 return get_process_id(pid, "Gid:", gid);
1121 char *strnappend(const char *s, const char *suffix, size_t b) {
1129 return strndup(suffix, b);
1138 if (b > ((size_t) -1) - a)
1141 r = new(char, a+b+1);
1146 memcpy(r+a, suffix, b);
1152 char *strappend(const char *s, const char *suffix) {
1153 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1156 int readlink_malloc(const char *p, char **r) {
1166 if (!(c = new(char, l)))
1169 if ((n = readlink(p, c, l-1)) < 0) {
1175 if ((size_t) n < l-1) {
1186 int readlink_and_make_absolute(const char *p, char **r) {
1193 if ((j = readlink_malloc(p, &target)) < 0)
1196 k = file_in_same_dir(p, target);
1206 int readlink_and_canonicalize(const char *p, char **r) {
1213 j = readlink_and_make_absolute(p, &t);
1217 s = canonicalize_file_name(t);
1224 path_kill_slashes(*r);
1229 int reset_all_signal_handlers(void) {
1232 for (sig = 1; sig < _NSIG; sig++) {
1233 struct sigaction sa;
1235 if (sig == SIGKILL || sig == SIGSTOP)
1239 sa.sa_handler = SIG_DFL;
1240 sa.sa_flags = SA_RESTART;
1242 /* On Linux the first two RT signals are reserved by
1243 * glibc, and sigaction() will return EINVAL for them. */
1244 if ((sigaction(sig, &sa, NULL) < 0))
1245 if (errno != EINVAL)
1252 char *strstrip(char *s) {
1255 /* Drops trailing whitespace. Modifies the string in
1256 * place. Returns pointer to first non-space character */
1258 s += strspn(s, WHITESPACE);
1260 for (e = strchr(s, 0); e > s; e --)
1261 if (!strchr(WHITESPACE, e[-1]))
1269 char *delete_chars(char *s, const char *bad) {
1272 /* Drops all whitespace, regardless where in the string */
1274 for (f = s, t = s; *f; f++) {
1275 if (strchr(bad, *f))
1286 bool in_charset(const char *s, const char* charset) {
1292 for (i = s; *i; i++)
1293 if (!strchr(charset, *i))
1299 char *file_in_same_dir(const char *path, const char *filename) {
1306 /* This removes the last component of path and appends
1307 * filename, unless the latter is absolute anyway or the
1310 if (path_is_absolute(filename))
1311 return strdup(filename);
1313 if (!(e = strrchr(path, '/')))
1314 return strdup(filename);
1316 k = strlen(filename);
1317 if (!(r = new(char, e-path+1+k+1)))
1320 memcpy(r, path, e-path+1);
1321 memcpy(r+(e-path)+1, filename, k+1);
1326 int rmdir_parents(const char *path, const char *stop) {
1335 /* Skip trailing slashes */
1336 while (l > 0 && path[l-1] == '/')
1342 /* Skip last component */
1343 while (l > 0 && path[l-1] != '/')
1346 /* Skip trailing slashes */
1347 while (l > 0 && path[l-1] == '/')
1353 if (!(t = strndup(path, l)))
1356 if (path_startswith(stop, t)) {
1365 if (errno != ENOENT)
1373 char hexchar(int x) {
1374 static const char table[16] = "0123456789abcdef";
1376 return table[x & 15];
1379 int unhexchar(char c) {
1381 if (c >= '0' && c <= '9')
1384 if (c >= 'a' && c <= 'f')
1385 return c - 'a' + 10;
1387 if (c >= 'A' && c <= 'F')
1388 return c - 'A' + 10;
1393 char octchar(int x) {
1394 return '0' + (x & 7);
1397 int unoctchar(char c) {
1399 if (c >= '0' && c <= '7')
1405 char decchar(int x) {
1406 return '0' + (x % 10);
1409 int undecchar(char c) {
1411 if (c >= '0' && c <= '9')
1417 char *cescape(const char *s) {
1423 /* Does C style string escaping. */
1425 r = new(char, strlen(s)*4 + 1);
1429 for (f = s, t = r; *f; f++)
1475 /* For special chars we prefer octal over
1476 * hexadecimal encoding, simply because glib's
1477 * g_strescape() does the same */
1478 if ((*f < ' ') || (*f >= 127)) {
1480 *(t++) = octchar((unsigned char) *f >> 6);
1481 *(t++) = octchar((unsigned char) *f >> 3);
1482 *(t++) = octchar((unsigned char) *f);
1493 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1500 /* Undoes C style string escaping, and optionally prefixes it. */
1502 pl = prefix ? strlen(prefix) : 0;
1504 r = new(char, pl+length+1);
1509 memcpy(r, prefix, pl);
1511 for (f = s, t = r + pl; f < s + length; f++) {
1554 /* This is an extension of the XDG syntax files */
1559 /* hexadecimal encoding */
1562 a = unhexchar(f[1]);
1563 b = unhexchar(f[2]);
1565 if (a < 0 || b < 0) {
1566 /* Invalid escape code, let's take it literal then */
1570 *(t++) = (char) ((a << 4) | b);
1585 /* octal encoding */
1588 a = unoctchar(f[0]);
1589 b = unoctchar(f[1]);
1590 c = unoctchar(f[2]);
1592 if (a < 0 || b < 0 || c < 0) {
1593 /* Invalid escape code, let's take it literal then */
1597 *(t++) = (char) ((a << 6) | (b << 3) | c);
1605 /* premature end of string.*/
1610 /* Invalid escape code, let's take it literal then */
1622 char *cunescape_length(const char *s, size_t length) {
1623 return cunescape_length_with_prefix(s, length, NULL);
1626 char *cunescape(const char *s) {
1629 return cunescape_length(s, strlen(s));
1632 char *xescape(const char *s, const char *bad) {
1636 /* Escapes all chars in bad, in addition to \ and all special
1637 * chars, in \xFF style escaping. May be reversed with
1640 r = new(char, strlen(s) * 4 + 1);
1644 for (f = s, t = r; *f; f++) {
1646 if ((*f < ' ') || (*f >= 127) ||
1647 (*f == '\\') || strchr(bad, *f)) {
1650 *(t++) = hexchar(*f >> 4);
1651 *(t++) = hexchar(*f);
1661 char *bus_path_escape(const char *s) {
1667 /* Escapes all chars that D-Bus' object path cannot deal
1668 * with. Can be reverse with bus_path_unescape() */
1670 if (!(r = new(char, strlen(s)*3+1)))
1673 for (f = s, t = r; *f; f++) {
1675 if (!(*f >= 'A' && *f <= 'Z') &&
1676 !(*f >= 'a' && *f <= 'z') &&
1677 !(*f >= '0' && *f <= '9')) {
1679 *(t++) = hexchar(*f >> 4);
1680 *(t++) = hexchar(*f);
1690 char *bus_path_unescape(const char *f) {
1695 if (!(r = strdup(f)))
1698 for (t = r; *f; f++) {
1703 if ((a = unhexchar(f[1])) < 0 ||
1704 (b = unhexchar(f[2])) < 0) {
1705 /* Invalid escape code, let's take it literal then */
1708 *(t++) = (char) ((a << 4) | b);
1720 char *ascii_strlower(char *t) {
1725 for (p = t; *p; p++)
1726 if (*p >= 'A' && *p <= 'Z')
1727 *p = *p - 'A' + 'a';
1732 static bool ignore_file_allow_backup(const char *filename) {
1736 filename[0] == '.' ||
1737 streq(filename, "lost+found") ||
1738 streq(filename, "aquota.user") ||
1739 streq(filename, "aquota.group") ||
1740 endswith(filename, ".rpmnew") ||
1741 endswith(filename, ".rpmsave") ||
1742 endswith(filename, ".rpmorig") ||
1743 endswith(filename, ".dpkg-old") ||
1744 endswith(filename, ".dpkg-new") ||
1745 endswith(filename, ".swp");
1748 bool ignore_file(const char *filename) {
1751 if (endswith(filename, "~"))
1754 return ignore_file_allow_backup(filename);
1757 int fd_nonblock(int fd, bool nonblock) {
1762 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1766 flags |= O_NONBLOCK;
1768 flags &= ~O_NONBLOCK;
1770 if (fcntl(fd, F_SETFL, flags) < 0)
1776 int fd_cloexec(int fd, bool cloexec) {
1781 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1785 flags |= FD_CLOEXEC;
1787 flags &= ~FD_CLOEXEC;
1789 if (fcntl(fd, F_SETFD, flags) < 0)
1795 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1798 assert(n_fdset == 0 || fdset);
1800 for (i = 0; i < n_fdset; i++)
1807 int close_all_fds(const int except[], unsigned n_except) {
1812 assert(n_except == 0 || except);
1814 d = opendir("/proc/self/fd");
1819 /* When /proc isn't available (for example in chroots)
1820 * the fallback is brute forcing through the fd
1823 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1824 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1826 if (fd_in_set(fd, except, n_except))
1829 if (close_nointr(fd) < 0)
1830 if (errno != EBADF && r == 0)
1837 while ((de = readdir(d))) {
1840 if (ignore_file(de->d_name))
1843 if (safe_atoi(de->d_name, &fd) < 0)
1844 /* Let's better ignore this, just in case */
1853 if (fd_in_set(fd, except, n_except))
1856 if (close_nointr(fd) < 0) {
1857 /* Valgrind has its own FD and doesn't want to have it closed */
1858 if (errno != EBADF && r == 0)
1867 bool chars_intersect(const char *a, const char *b) {
1870 /* Returns true if any of the chars in a are in b. */
1871 for (p = a; *p; p++)
1878 bool fstype_is_network(const char *fstype) {
1879 static const char table[] =
1888 return nulstr_contains(table, fstype);
1892 _cleanup_close_ int fd;
1894 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1900 TIOCL_GETKMSGREDIRECT,
1904 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1907 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1910 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1916 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1917 struct termios old_termios, new_termios;
1919 char line[LINE_MAX];
1924 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1925 new_termios = old_termios;
1927 new_termios.c_lflag &= ~ICANON;
1928 new_termios.c_cc[VMIN] = 1;
1929 new_termios.c_cc[VTIME] = 0;
1931 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1934 if (t != (usec_t) -1) {
1935 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1936 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1941 k = fread(&c, 1, 1, f);
1943 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1949 *need_nl = c != '\n';
1956 if (t != (usec_t) -1)
1957 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1960 if (!fgets(line, sizeof(line), f))
1965 if (strlen(line) != 1)
1975 int ask(char *ret, const char *replies, const char *text, ...) {
1985 bool need_nl = true;
1988 fputs(ANSI_HIGHLIGHT_ON, stdout);
1995 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1999 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2002 if (r == -EBADMSG) {
2003 puts("Bad input, please try again.");
2014 if (strchr(replies, c)) {
2019 puts("Read unexpected character, please try again.");
2023 int reset_terminal_fd(int fd, bool switch_to_text) {
2024 struct termios termios;
2027 /* Set terminal to some sane defaults */
2031 /* We leave locked terminal attributes untouched, so that
2032 * Plymouth may set whatever it wants to set, and we don't
2033 * interfere with that. */
2035 /* Disable exclusive mode, just in case */
2036 ioctl(fd, TIOCNXCL);
2038 /* Switch to text mode */
2040 ioctl(fd, KDSETMODE, KD_TEXT);
2042 /* Enable console unicode mode */
2043 ioctl(fd, KDSKBMODE, K_UNICODE);
2045 if (tcgetattr(fd, &termios) < 0) {
2050 /* We only reset the stuff that matters to the software. How
2051 * hardware is set up we don't touch assuming that somebody
2052 * else will do that for us */
2054 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2055 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2056 termios.c_oflag |= ONLCR;
2057 termios.c_cflag |= CREAD;
2058 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2060 termios.c_cc[VINTR] = 03; /* ^C */
2061 termios.c_cc[VQUIT] = 034; /* ^\ */
2062 termios.c_cc[VERASE] = 0177;
2063 termios.c_cc[VKILL] = 025; /* ^X */
2064 termios.c_cc[VEOF] = 04; /* ^D */
2065 termios.c_cc[VSTART] = 021; /* ^Q */
2066 termios.c_cc[VSTOP] = 023; /* ^S */
2067 termios.c_cc[VSUSP] = 032; /* ^Z */
2068 termios.c_cc[VLNEXT] = 026; /* ^V */
2069 termios.c_cc[VWERASE] = 027; /* ^W */
2070 termios.c_cc[VREPRINT] = 022; /* ^R */
2071 termios.c_cc[VEOL] = 0;
2072 termios.c_cc[VEOL2] = 0;
2074 termios.c_cc[VTIME] = 0;
2075 termios.c_cc[VMIN] = 1;
2077 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2081 /* Just in case, flush all crap out */
2082 tcflush(fd, TCIOFLUSH);
2087 int reset_terminal(const char *name) {
2090 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2094 r = reset_terminal_fd(fd, true);
2095 close_nointr_nofail(fd);
2100 int open_terminal(const char *name, int mode) {
2105 * If a TTY is in the process of being closed opening it might
2106 * cause EIO. This is horribly awful, but unlikely to be
2107 * changed in the kernel. Hence we work around this problem by
2108 * retrying a couple of times.
2110 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2114 fd = open(name, mode);
2121 /* Max 1s in total */
2125 usleep(50 * USEC_PER_MSEC);
2134 close_nointr_nofail(fd);
2139 close_nointr_nofail(fd);
2146 int flush_fd(int fd) {
2147 struct pollfd pollfd;
2151 pollfd.events = POLLIN;
2158 if ((r = poll(&pollfd, 1, 0)) < 0) {
2169 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2174 if (errno == EAGAIN)
2185 int acquire_terminal(
2189 bool ignore_tiocstty_eperm,
2192 int fd = -1, notify = -1, r = 0, wd = -1;
2194 struct sigaction sa_old, sa_new;
2198 /* We use inotify to be notified when the tty is closed. We
2199 * create the watch before checking if we can actually acquire
2200 * it, so that we don't lose any event.
2202 * Note: strictly speaking this actually watches for the
2203 * device being closed, it does *not* really watch whether a
2204 * tty loses its controlling process. However, unless some
2205 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2206 * its tty otherwise this will not become a problem. As long
2207 * as the administrator makes sure not configure any service
2208 * on the same tty as an untrusted user this should not be a
2209 * problem. (Which he probably should not do anyway.) */
2211 if (timeout != (usec_t) -1)
2212 ts = now(CLOCK_MONOTONIC);
2214 if (!fail && !force) {
2215 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2221 wd = inotify_add_watch(notify, name, IN_CLOSE);
2230 r = flush_fd(notify);
2235 /* We pass here O_NOCTTY only so that we can check the return
2236 * value TIOCSCTTY and have a reliable way to figure out if we
2237 * successfully became the controlling process of the tty */
2238 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2242 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2243 * if we already own the tty. */
2245 sa_new.sa_handler = SIG_IGN;
2246 sa_new.sa_flags = SA_RESTART;
2247 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2249 /* First, try to get the tty */
2250 if (ioctl(fd, TIOCSCTTY, force) < 0)
2253 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2255 /* Sometimes it makes sense to ignore TIOCSCTTY
2256 * returning EPERM, i.e. when very likely we already
2257 * are have this controlling terminal. */
2258 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2261 if (r < 0 && (force || fail || r != -EPERM)) {
2270 assert(notify >= 0);
2273 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2275 struct inotify_event *e;
2277 if (timeout != (usec_t) -1) {
2280 n = now(CLOCK_MONOTONIC);
2281 if (ts + timeout < n) {
2286 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2296 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2299 if (errno == EINTR || errno == EAGAIN)
2306 e = (struct inotify_event*) inotify_buffer;
2311 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2316 step = sizeof(struct inotify_event) + e->len;
2317 assert(step <= (size_t) l);
2319 e = (struct inotify_event*) ((uint8_t*) e + step);
2326 /* We close the tty fd here since if the old session
2327 * ended our handle will be dead. It's important that
2328 * we do this after sleeping, so that we don't enter
2329 * an endless loop. */
2330 close_nointr_nofail(fd);
2334 close_nointr_nofail(notify);
2336 r = reset_terminal_fd(fd, true);
2338 log_warning("Failed to reset terminal: %s", strerror(-r));
2344 close_nointr_nofail(fd);
2347 close_nointr_nofail(notify);
2352 int release_terminal(void) {
2354 struct sigaction sa_old, sa_new;
2356 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2359 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2360 * by our own TIOCNOTTY */
2363 sa_new.sa_handler = SIG_IGN;
2364 sa_new.sa_flags = SA_RESTART;
2365 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2367 if (ioctl(fd, TIOCNOTTY) < 0)
2370 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2372 close_nointr_nofail(fd);
2376 int sigaction_many(const struct sigaction *sa, ...) {
2381 while ((sig = va_arg(ap, int)) > 0)
2382 if (sigaction(sig, sa, NULL) < 0)
2389 int ignore_signals(int sig, ...) {
2390 struct sigaction sa;
2395 sa.sa_handler = SIG_IGN;
2396 sa.sa_flags = SA_RESTART;
2398 if (sigaction(sig, &sa, NULL) < 0)
2402 while ((sig = va_arg(ap, int)) > 0)
2403 if (sigaction(sig, &sa, NULL) < 0)
2410 int default_signals(int sig, ...) {
2411 struct sigaction sa;
2416 sa.sa_handler = SIG_DFL;
2417 sa.sa_flags = SA_RESTART;
2419 if (sigaction(sig, &sa, NULL) < 0)
2423 while ((sig = va_arg(ap, int)) > 0)
2424 if (sigaction(sig, &sa, NULL) < 0)
2431 int close_pipe(int p[]) {
2437 a = close_nointr(p[0]);
2442 b = close_nointr(p[1]);
2446 return a < 0 ? a : b;
2449 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2458 while (nbytes > 0) {
2461 if ((k = read(fd, p, nbytes)) <= 0) {
2463 if (k < 0 && errno == EINTR)
2466 if (k < 0 && errno == EAGAIN && do_poll) {
2467 struct pollfd pollfd;
2471 pollfd.events = POLLIN;
2473 if (poll(&pollfd, 1, -1) < 0) {
2477 return n > 0 ? n : -errno;
2480 if (pollfd.revents != POLLIN)
2481 return n > 0 ? n : -EIO;
2486 return n > 0 ? n : (k < 0 ? -errno : 0);
2497 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2506 while (nbytes > 0) {
2509 k = write(fd, p, nbytes);
2512 if (k < 0 && errno == EINTR)
2515 if (k < 0 && errno == EAGAIN && do_poll) {
2516 struct pollfd pollfd;
2520 pollfd.events = POLLOUT;
2522 if (poll(&pollfd, 1, -1) < 0) {
2526 return n > 0 ? n : -errno;
2529 if (pollfd.revents != POLLOUT)
2530 return n > 0 ? n : -EIO;
2535 return n > 0 ? n : (k < 0 ? -errno : 0);
2546 int parse_bytes(const char *t, off_t *bytes) {
2547 static const struct {
2553 { "M", 1024ULL*1024ULL },
2554 { "G", 1024ULL*1024ULL*1024ULL },
2555 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2556 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2557 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2574 l = strtoll(p, &e, 10);
2585 e += strspn(e, WHITESPACE);
2587 for (i = 0; i < ELEMENTSOF(table); i++)
2588 if (startswith(e, table[i].suffix)) {
2589 r += (off_t) l * table[i].factor;
2590 p = e + strlen(table[i].suffix);
2594 if (i >= ELEMENTSOF(table))
2604 int make_stdio(int fd) {
2609 r = dup3(fd, STDIN_FILENO, 0);
2610 s = dup3(fd, STDOUT_FILENO, 0);
2611 t = dup3(fd, STDERR_FILENO, 0);
2614 close_nointr_nofail(fd);
2616 if (r < 0 || s < 0 || t < 0)
2619 /* We rely here that the new fd has O_CLOEXEC not set */
2624 int make_null_stdio(void) {
2627 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2631 return make_stdio(null_fd);
2634 bool is_device_path(const char *path) {
2636 /* Returns true on paths that refer to a device, either in
2637 * sysfs or in /dev */
2640 path_startswith(path, "/dev/") ||
2641 path_startswith(path, "/sys/");
2644 int dir_is_empty(const char *path) {
2645 _cleanup_closedir_ DIR *d;
2654 union dirent_storage buf;
2656 r = readdir_r(d, &buf.de, &de);
2663 if (!ignore_file(de->d_name))
2668 unsigned long long random_ull(void) {
2669 _cleanup_close_ int fd;
2673 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2677 r = loop_read(fd, &ull, sizeof(ull), true);
2678 if (r != sizeof(ull))
2684 return random() * RAND_MAX + random();
2687 void rename_process(const char name[8]) {
2690 /* This is a like a poor man's setproctitle(). It changes the
2691 * comm field, argv[0], and also the glibc's internally used
2692 * name of the process. For the first one a limit of 16 chars
2693 * applies, to the second one usually one of 10 (i.e. length
2694 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2695 * "systemd"). If you pass a longer string it will be
2698 prctl(PR_SET_NAME, name);
2700 if (program_invocation_name)
2701 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2703 if (saved_argc > 0) {
2707 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2709 for (i = 1; i < saved_argc; i++) {
2713 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2718 void sigset_add_many(sigset_t *ss, ...) {
2725 while ((sig = va_arg(ap, int)) > 0)
2726 assert_se(sigaddset(ss, sig) == 0);
2730 char* gethostname_malloc(void) {
2733 assert_se(uname(&u) >= 0);
2735 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2736 return strdup(u.nodename);
2738 return strdup(u.sysname);
2741 bool hostname_is_set(void) {
2744 assert_se(uname(&u) >= 0);
2746 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2749 static char *lookup_uid(uid_t uid) {
2752 _cleanup_free_ char *buf = NULL;
2753 struct passwd pwbuf, *pw = NULL;
2755 /* Shortcut things to avoid NSS lookups */
2757 return strdup("root");
2759 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2763 buf = malloc(bufsize);
2767 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2768 return strdup(pw->pw_name);
2770 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2776 char* getlogname_malloc(void) {
2780 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2785 return lookup_uid(uid);
2788 char *getusername_malloc(void) {
2795 return lookup_uid(getuid());
2798 int getttyname_malloc(int fd, char **r) {
2799 char path[PATH_MAX], *c;
2804 k = ttyname_r(fd, path, sizeof(path));
2810 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2818 int getttyname_harder(int fd, char **r) {
2822 k = getttyname_malloc(fd, &s);
2826 if (streq(s, "tty")) {
2828 return get_ctty(0, NULL, r);
2835 int get_ctty_devnr(pid_t pid, dev_t *d) {
2837 char line[LINE_MAX], *p, *fn;
2838 unsigned long ttynr;
2841 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2844 f = fopen(fn, "re");
2849 if (!fgets(line, sizeof(line), f)) {
2850 k = feof(f) ? -EIO : -errno;
2857 p = strrchr(line, ')');
2867 "%*d " /* session */
2872 if (major(ttynr) == 0 && minor(ttynr) == 0)
2879 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2881 char fn[PATH_MAX], *s, *b, *p;
2886 k = get_ctty_devnr(pid, &devnr);
2890 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2893 k = readlink_malloc(fn, &s);
2899 /* This is an ugly hack */
2900 if (major(devnr) == 136) {
2901 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2911 /* Probably something like the ptys which have no
2912 * symlink in /dev/char. Let's return something
2913 * vaguely useful. */
2926 if (startswith(s, "/dev/"))
2928 else if (startswith(s, "../"))
2946 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2952 /* This returns the first error we run into, but nevertheless
2953 * tries to go on. This closes the passed fd. */
2957 close_nointr_nofail(fd);
2959 return errno == ENOENT ? 0 : -errno;
2964 union dirent_storage buf;
2965 bool is_dir, keep_around;
2969 r = readdir_r(d, &buf.de, &de);
2970 if (r != 0 && ret == 0) {
2978 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2981 if (de->d_type == DT_UNKNOWN ||
2983 (de->d_type == DT_DIR && root_dev)) {
2984 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2985 if (ret == 0 && errno != ENOENT)
2990 is_dir = S_ISDIR(st.st_mode);
2993 (st.st_uid == 0 || st.st_uid == getuid()) &&
2994 (st.st_mode & S_ISVTX);
2996 is_dir = de->d_type == DT_DIR;
2997 keep_around = false;
3003 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3004 if (root_dev && st.st_dev != root_dev->st_dev)
3007 subdir_fd = openat(fd, de->d_name,
3008 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3009 if (subdir_fd < 0) {
3010 if (ret == 0 && errno != ENOENT)
3015 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3016 if (r < 0 && ret == 0)
3020 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3021 if (ret == 0 && errno != ENOENT)
3025 } else if (!only_dirs && !keep_around) {
3027 if (unlinkat(fd, de->d_name, 0) < 0) {
3028 if (ret == 0 && errno != ENOENT)
3039 static int is_temporary_fs(struct statfs *s) {
3041 return s->f_type == TMPFS_MAGIC ||
3042 (long)s->f_type == (long)RAMFS_MAGIC;
3045 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3050 if (fstatfs(fd, &s) < 0) {
3051 close_nointr_nofail(fd);
3055 /* We refuse to clean disk file systems with this call. This
3056 * is extra paranoia just to be sure we never ever remove
3058 if (!is_temporary_fs(&s)) {
3059 log_error("Attempted to remove disk file system, and we can't allow that.");
3060 close_nointr_nofail(fd);
3064 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3067 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3073 /* We refuse to clean the root file system with this
3074 * call. This is extra paranoia to never cause a really
3075 * seriously broken system. */
3076 if (path_equal(path, "/")) {
3077 log_error("Attempted to remove entire root file system, and we can't allow that.");
3081 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3084 if (errno != ENOTDIR)
3088 if (statfs(path, &s) < 0)
3091 if (!is_temporary_fs(&s)) {
3092 log_error("Attempted to remove disk file system, and we can't allow that.");
3097 if (delete_root && !only_dirs)
3098 if (unlink(path) < 0 && errno != ENOENT)
3105 if (fstatfs(fd, &s) < 0) {
3106 close_nointr_nofail(fd);
3110 if (!is_temporary_fs(&s)) {
3111 log_error("Attempted to remove disk file system, and we can't allow that.");
3112 close_nointr_nofail(fd);
3117 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3120 if (honour_sticky && file_is_priv_sticky(path) > 0)
3123 if (rmdir(path) < 0 && errno != ENOENT) {
3132 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3133 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3136 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3137 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3140 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3143 /* Under the assumption that we are running privileged we
3144 * first change the access mode and only then hand out
3145 * ownership to avoid a window where access is too open. */
3147 if (mode != (mode_t) -1)
3148 if (chmod(path, mode) < 0)
3151 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3152 if (chown(path, uid, gid) < 0)
3158 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3161 /* Under the assumption that we are running privileged we
3162 * first change the access mode and only then hand out
3163 * ownership to avoid a window where access is too open. */
3165 if (fchmod(fd, mode) < 0)
3168 if (fchown(fd, uid, gid) < 0)
3174 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3178 /* Allocates the cpuset in the right size */
3181 if (!(r = CPU_ALLOC(n)))
3184 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3185 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3195 if (errno != EINVAL)
3202 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3203 static const char status_indent[] = " "; /* "[" STATUS "] " */
3204 _cleanup_free_ char *s = NULL;
3205 _cleanup_close_ int fd = -1;
3206 struct iovec iovec[5];
3211 /* This is independent of logging, as status messages are
3212 * optional and go exclusively to the console. */
3214 if (vasprintf(&s, format, ap) < 0)
3217 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3230 sl = status ? sizeof(status_indent)-1 : 0;
3236 e = ellipsize(s, emax, 75);
3246 if (!isempty(status)) {
3247 IOVEC_SET_STRING(iovec[n++], "[");
3248 IOVEC_SET_STRING(iovec[n++], status);
3249 IOVEC_SET_STRING(iovec[n++], "] ");
3251 IOVEC_SET_STRING(iovec[n++], status_indent);
3254 IOVEC_SET_STRING(iovec[n++], s);
3255 IOVEC_SET_STRING(iovec[n++], "\n");
3257 if (writev(fd, iovec, n) < 0)
3263 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3269 va_start(ap, format);
3270 r = status_vprintf(status, ellipse, format, ap);
3276 int status_welcome(void) {
3278 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3280 r = parse_env_file("/etc/os-release", NEWLINE,
3281 "PRETTY_NAME", &pretty_name,
3282 "ANSI_COLOR", &ansi_color,
3284 if (r < 0 && r != -ENOENT)
3285 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3287 return status_printf(NULL, false,
3288 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3289 isempty(ansi_color) ? "1" : ansi_color,
3290 isempty(pretty_name) ? "Linux" : pretty_name);
3293 char *replace_env(const char *format, char **env) {
3300 const char *e, *word = format;
3305 for (e = format; *e; e ++) {
3316 if (!(k = strnappend(r, word, e-word-1)))
3325 } else if (*e == '$') {
3326 if (!(k = strnappend(r, word, e-word)))
3342 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3344 k = strappend(r, t);
3358 if (!(k = strnappend(r, word, e-word)))
3369 char **replace_env_argv(char **argv, char **env) {
3371 unsigned k = 0, l = 0;
3373 l = strv_length(argv);
3375 if (!(r = new(char*, l+1)))
3378 STRV_FOREACH(i, argv) {
3380 /* If $FOO appears as single word, replace it by the split up variable */
3381 if ((*i)[0] == '$' && (*i)[1] != '{') {
3386 e = strv_env_get(env, *i+1);
3389 if (!(m = strv_split_quoted(e))) {
3400 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3409 memcpy(r + k, m, q * sizeof(char*));
3417 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3418 if (!(r[k++] = replace_env(*i, env))) {
3428 int fd_columns(int fd) {
3432 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3441 unsigned columns(void) {
3445 if (_likely_(cached_columns > 0))
3446 return cached_columns;
3449 e = getenv("COLUMNS");
3454 c = fd_columns(STDOUT_FILENO);
3463 int fd_lines(int fd) {
3467 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3476 unsigned lines(void) {
3480 if (_likely_(cached_lines > 0))
3481 return cached_lines;
3484 e = getenv("LINES");
3489 l = fd_lines(STDOUT_FILENO);
3495 return cached_lines;
3498 /* intended to be used as a SIGWINCH sighandler */
3499 void columns_lines_cache_reset(int signum) {
3505 static int cached_on_tty = -1;
3507 if (_unlikely_(cached_on_tty < 0))
3508 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3510 return cached_on_tty;
3513 int running_in_chroot(void) {
3519 /* Only works as root */
3521 if (stat("/proc/1/root", &a) < 0)
3524 if (stat("/", &b) < 0)
3528 a.st_dev != b.st_dev ||
3529 a.st_ino != b.st_ino;
3532 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3537 assert(percent <= 100);
3538 assert(new_length >= 3);
3540 if (old_length <= 3 || old_length <= new_length)
3541 return strndup(s, old_length);
3543 r = new0(char, new_length+1);
3547 x = (new_length * percent) / 100;
3549 if (x > new_length - 3)
3557 s + old_length - (new_length - x - 3),
3558 new_length - x - 3);
3563 char *ellipsize(const char *s, size_t length, unsigned percent) {
3564 return ellipsize_mem(s, strlen(s), length, percent);
3567 int touch(const char *path) {
3572 /* This just opens the file for writing, ensuring it
3573 * exists. It doesn't call utimensat() the way /usr/bin/touch
3576 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3580 close_nointr_nofail(fd);
3584 char *unquote(const char *s, const char* quotes) {
3588 /* This is rather stupid, simply removes the heading and
3589 * trailing quotes if there is one. Doesn't care about
3590 * escaping or anything. We should make this smarter one
3597 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3598 return strndup(s+1, l-2);
3603 char *normalize_env_assignment(const char *s) {
3604 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3607 eq = strchr(s, '=');
3619 memmove(r, t, strlen(t) + 1);
3623 name = strndup(s, eq - s);
3631 value = unquote(strstrip(p), QUOTES);
3635 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3641 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3652 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3664 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3671 r = wait_for_terminate(pid, &status);
3673 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3677 if (status.si_code == CLD_EXITED) {
3678 if (status.si_status != 0) {
3679 log_warning("%s failed with error code %i.", name, status.si_status);
3680 return status.si_status;
3683 log_debug("%s succeeded.", name);
3686 } else if (status.si_code == CLD_KILLED ||
3687 status.si_code == CLD_DUMPED) {
3689 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3693 log_warning("%s failed due to unknown reason.", name);
3697 _noreturn_ void freeze(void) {
3699 /* Make sure nobody waits for us on a socket anymore */
3700 close_all_fds(NULL, 0);
3708 bool null_or_empty(struct stat *st) {
3711 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3714 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3720 int null_or_empty_path(const char *fn) {
3725 if (stat(fn, &st) < 0)
3728 return null_or_empty(&st);
3731 DIR *xopendirat(int fd, const char *name, int flags) {
3735 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3741 close_nointr_nofail(nfd);
3748 int signal_from_string_try_harder(const char *s) {
3752 signo = signal_from_string(s);
3754 if (startswith(s, "SIG"))
3755 return signal_from_string(s+3);
3760 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3764 /* FIXME: to follow udev's logic 100% we need to leave valid
3765 * UTF8 chars unescaped */
3767 u = unquote(tagvalue, "\"\'");
3771 t = xescape(u, "/ ");
3777 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3786 char *fstab_node_to_udev_node(const char *p) {
3789 if (startswith(p, "LABEL="))
3790 return tag_to_udev_node(p+6, "label");
3792 if (startswith(p, "UUID="))
3793 return tag_to_udev_node(p+5, "uuid");
3795 if (startswith(p, "PARTUUID="))
3796 return tag_to_udev_node(p+9, "partuuid");
3798 if (startswith(p, "PARTLABEL="))
3799 return tag_to_udev_node(p+10, "partlabel");
3804 bool tty_is_vc(const char *tty) {
3807 if (startswith(tty, "/dev/"))
3810 return vtnr_from_tty(tty) >= 0;
3813 bool tty_is_console(const char *tty) {
3816 if (startswith(tty, "/dev/"))
3819 return streq(tty, "console");
3822 int vtnr_from_tty(const char *tty) {
3827 if (startswith(tty, "/dev/"))
3830 if (!startswith(tty, "tty") )
3833 if (tty[3] < '0' || tty[3] > '9')
3836 r = safe_atoi(tty+3, &i);
3840 if (i < 0 || i > 63)
3846 bool tty_is_vc_resolve(const char *tty) {
3847 char *active = NULL;
3852 if (startswith(tty, "/dev/"))
3855 /* Resolve where /dev/console is pointing to, if /sys is
3856 * actually ours (i.e. not read-only-mounted which is a sign
3857 * for container setups) */
3858 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
3859 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3860 /* If multiple log outputs are configured the
3861 * last one is what /dev/console points to */
3862 tty = strrchr(active, ' ');
3875 const char *default_term_for_tty(const char *tty) {
3878 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3881 bool dirent_is_file(const struct dirent *de) {
3884 if (ignore_file(de->d_name))
3887 if (de->d_type != DT_REG &&
3888 de->d_type != DT_LNK &&
3889 de->d_type != DT_UNKNOWN)
3895 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3898 if (de->d_type != DT_REG &&
3899 de->d_type != DT_LNK &&
3900 de->d_type != DT_UNKNOWN)
3903 if (ignore_file_allow_backup(de->d_name))
3906 return endswith(de->d_name, suffix);
3909 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3912 Hashmap *pids = NULL;
3916 /* Executes all binaries in a directory in parallel and waits
3917 * until all they all finished. */
3920 if (!(_d = opendir(directory))) {
3922 if (errno == ENOENT)
3925 log_error("Failed to enumerate directory %s: %m", directory);
3932 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3933 log_error("Failed to allocate set.");
3937 while ((de = readdir(d))) {
3942 if (!dirent_is_file(de))
3945 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3950 if ((pid = fork()) < 0) {
3951 log_error("Failed to fork: %m");
3969 log_error("Failed to execute %s: %m", path);
3970 _exit(EXIT_FAILURE);
3973 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3975 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3976 log_error("Failed to add PID to set: %s", strerror(-k));
3981 while (!hashmap_isempty(pids)) {
3982 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3987 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3992 log_error("waitid() failed: %m");
3996 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3997 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3998 if (si.si_code == CLD_EXITED)
3999 log_error("%s exited with exit status %i.", path, si.si_status);
4001 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4003 log_debug("%s exited successfully.", path);
4014 hashmap_free_free(pids);
4017 int kill_and_sigcont(pid_t pid, int sig) {
4020 r = kill(pid, sig) < 0 ? -errno : 0;
4028 bool nulstr_contains(const char*nulstr, const char *needle) {
4034 NULSTR_FOREACH(i, nulstr)
4035 if (streq(i, needle))
4041 bool plymouth_running(void) {
4042 return access("/run/plymouth/pid", F_OK) >= 0;
4045 char* strshorten(char *s, size_t l) {
4054 static bool hostname_valid_char(char c) {
4056 (c >= 'a' && c <= 'z') ||
4057 (c >= 'A' && c <= 'Z') ||
4058 (c >= '0' && c <= '9') ||
4064 bool hostname_is_valid(const char *s) {
4070 for (p = s; *p; p++)
4071 if (!hostname_valid_char(*p))
4074 if (p-s > HOST_NAME_MAX)
4080 char* hostname_cleanup(char *s) {
4083 for (p = s, d = s; *p; p++)
4084 if ((*p >= 'a' && *p <= 'z') ||
4085 (*p >= 'A' && *p <= 'Z') ||
4086 (*p >= '0' && *p <= '9') ||
4094 strshorten(s, HOST_NAME_MAX);
4098 int pipe_eof(int fd) {
4099 struct pollfd pollfd;
4104 pollfd.events = POLLIN|POLLHUP;
4106 r = poll(&pollfd, 1, 0);
4113 return pollfd.revents & POLLHUP;
4116 int fd_wait_for_event(int fd, int event, usec_t t) {
4117 struct pollfd pollfd;
4122 pollfd.events = event;
4124 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4131 return pollfd.revents;
4134 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4145 t = new(char, strlen(path) + 1 + 6 + 1);
4149 fn = path_get_file_name(path);
4153 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4155 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4161 f = fdopen(fd, "we");
4174 int terminal_vhangup_fd(int fd) {
4177 if (ioctl(fd, TIOCVHANGUP) < 0)
4183 int terminal_vhangup(const char *name) {
4186 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4190 r = terminal_vhangup_fd(fd);
4191 close_nointr_nofail(fd);
4196 int vt_disallocate(const char *name) {
4200 /* Deallocate the VT if possible. If not possible
4201 * (i.e. because it is the active one), at least clear it
4202 * entirely (including the scrollback buffer) */
4204 if (!startswith(name, "/dev/"))
4207 if (!tty_is_vc(name)) {
4208 /* So this is not a VT. I guess we cannot deallocate
4209 * it then. But let's at least clear the screen */
4211 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4216 "\033[r" /* clear scrolling region */
4217 "\033[H" /* move home */
4218 "\033[2J", /* clear screen */
4220 close_nointr_nofail(fd);
4225 if (!startswith(name, "/dev/tty"))
4228 r = safe_atou(name+8, &u);
4235 /* Try to deallocate */
4236 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4240 r = ioctl(fd, VT_DISALLOCATE, u);
4241 close_nointr_nofail(fd);
4249 /* Couldn't deallocate, so let's clear it fully with
4251 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4256 "\033[r" /* clear scrolling region */
4257 "\033[H" /* move home */
4258 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4260 close_nointr_nofail(fd);
4265 int copy_file(const char *from, const char *to) {
4271 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4275 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4277 close_nointr_nofail(fdf);
4285 n = read(fdf, buf, sizeof(buf));
4289 close_nointr_nofail(fdf);
4300 k = loop_write(fdt, buf, n, false);
4302 r = k < 0 ? k : (errno ? -errno : -EIO);
4304 close_nointr_nofail(fdf);
4312 close_nointr_nofail(fdf);
4313 r = close_nointr(fdt);
4323 int symlink_atomic(const char *from, const char *to) {
4325 _cleanup_free_ char *t;
4328 unsigned long long ull;
4335 t = new(char, strlen(to) + 1 + 16 + 1);
4339 fn = path_get_file_name(to);
4343 x = stpcpy(t+k+1, fn);
4346 for (i = 0; i < 16; i++) {
4347 *(x++) = hexchar(ull & 0xF);
4353 if (symlink(from, t) < 0)
4356 if (rename(t, to) < 0) {
4365 bool display_is_local(const char *display) {
4369 display[0] == ':' &&
4370 display[1] >= '0' &&
4374 int socket_from_display(const char *display, char **path) {
4381 if (!display_is_local(display))
4384 k = strspn(display+1, "0123456789");
4386 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4390 c = stpcpy(f, "/tmp/.X11-unix/X");
4391 memcpy(c, display+1, k);
4400 const char **username,
4401 uid_t *uid, gid_t *gid,
4403 const char **shell) {
4411 /* We enforce some special rules for uid=0: in order to avoid
4412 * NSS lookups for root we hardcode its data. */
4414 if (streq(*username, "root") || streq(*username, "0")) {
4432 if (parse_uid(*username, &u) >= 0) {
4436 /* If there are multiple users with the same id, make
4437 * sure to leave $USER to the configured value instead
4438 * of the first occurrence in the database. However if
4439 * the uid was configured by a numeric uid, then let's
4440 * pick the real username from /etc/passwd. */
4442 *username = p->pw_name;
4445 p = getpwnam(*username);
4449 return errno != 0 ? -errno : -ESRCH;
4461 *shell = p->pw_shell;
4466 char* uid_to_name(uid_t uid) {
4471 return strdup("root");
4475 return strdup(p->pw_name);
4477 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4483 int get_group_creds(const char **groupname, gid_t *gid) {
4489 /* We enforce some special rules for gid=0: in order to avoid
4490 * NSS lookups for root we hardcode its data. */
4492 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4493 *groupname = "root";
4501 if (parse_gid(*groupname, &id) >= 0) {
4506 *groupname = g->gr_name;
4509 g = getgrnam(*groupname);
4513 return errno != 0 ? -errno : -ESRCH;
4521 int in_group(const char *name) {
4523 int ngroups_max, r, i;
4525 r = get_group_creds(&name, &gid);
4529 if (getgid() == gid)
4532 if (getegid() == gid)
4535 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4536 assert(ngroups_max > 0);
4538 gids = alloca(sizeof(gid_t) * ngroups_max);
4540 r = getgroups(ngroups_max, gids);
4544 for (i = 0; i < r; i++)
4551 int glob_exists(const char *path) {
4559 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4561 if (k == GLOB_NOMATCH)
4563 else if (k == GLOB_NOSPACE)
4566 r = !strv_isempty(g.gl_pathv);
4568 r = errno ? -errno : -EIO;
4575 int dirent_ensure_type(DIR *d, struct dirent *de) {
4581 if (de->d_type != DT_UNKNOWN)
4584 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4588 S_ISREG(st.st_mode) ? DT_REG :
4589 S_ISDIR(st.st_mode) ? DT_DIR :
4590 S_ISLNK(st.st_mode) ? DT_LNK :
4591 S_ISFIFO(st.st_mode) ? DT_FIFO :
4592 S_ISSOCK(st.st_mode) ? DT_SOCK :
4593 S_ISCHR(st.st_mode) ? DT_CHR :
4594 S_ISBLK(st.st_mode) ? DT_BLK :
4600 int in_search_path(const char *path, char **search) {
4604 r = path_get_parent(path, &parent);
4610 STRV_FOREACH(i, search) {
4611 if (path_equal(parent, *i)) {
4622 int get_files_in_directory(const char *path, char ***list) {
4630 /* Returns all files in a directory in *list, and the number
4631 * of files as return value. If list is NULL returns only the
4640 union dirent_storage buf;
4643 k = readdir_r(d, &buf.de, &de);
4652 dirent_ensure_type(d, de);
4654 if (!dirent_is_file(de))
4658 if ((unsigned) r >= n) {
4662 t = realloc(l, sizeof(char*) * n);
4671 assert((unsigned) r < n);
4673 l[r] = strdup(de->d_name);
4697 char *strjoin(const char *x, ...) {
4711 t = va_arg(ap, const char *);
4716 if (n > ((size_t) -1) - l) {
4740 t = va_arg(ap, const char *);
4754 bool is_main_thread(void) {
4755 static __thread int cached = 0;
4757 if (_unlikely_(cached == 0))
4758 cached = getpid() == gettid() ? 1 : -1;
4763 int block_get_whole_disk(dev_t d, dev_t *ret) {
4770 /* If it has a queue this is good enough for us */
4771 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4774 r = access(p, F_OK);
4782 /* If it is a partition find the originating device */
4783 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4786 r = access(p, F_OK);
4792 /* Get parent dev_t */
4793 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4796 r = read_one_line_file(p, &s);
4802 r = sscanf(s, "%u:%u", &m, &n);
4808 /* Only return this if it is really good enough for us. */
4809 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4812 r = access(p, F_OK);
4816 *ret = makedev(m, n);
4823 int file_is_priv_sticky(const char *p) {
4828 if (lstat(p, &st) < 0)
4832 (st.st_uid == 0 || st.st_uid == getuid()) &&
4833 (st.st_mode & S_ISVTX);
4836 static const char *const ioprio_class_table[] = {
4837 [IOPRIO_CLASS_NONE] = "none",
4838 [IOPRIO_CLASS_RT] = "realtime",
4839 [IOPRIO_CLASS_BE] = "best-effort",
4840 [IOPRIO_CLASS_IDLE] = "idle"
4843 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4845 static const char *const sigchld_code_table[] = {
4846 [CLD_EXITED] = "exited",
4847 [CLD_KILLED] = "killed",
4848 [CLD_DUMPED] = "dumped",
4849 [CLD_TRAPPED] = "trapped",
4850 [CLD_STOPPED] = "stopped",
4851 [CLD_CONTINUED] = "continued",
4854 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4856 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4857 [LOG_FAC(LOG_KERN)] = "kern",
4858 [LOG_FAC(LOG_USER)] = "user",
4859 [LOG_FAC(LOG_MAIL)] = "mail",
4860 [LOG_FAC(LOG_DAEMON)] = "daemon",
4861 [LOG_FAC(LOG_AUTH)] = "auth",
4862 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4863 [LOG_FAC(LOG_LPR)] = "lpr",
4864 [LOG_FAC(LOG_NEWS)] = "news",
4865 [LOG_FAC(LOG_UUCP)] = "uucp",
4866 [LOG_FAC(LOG_CRON)] = "cron",
4867 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4868 [LOG_FAC(LOG_FTP)] = "ftp",
4869 [LOG_FAC(LOG_LOCAL0)] = "local0",
4870 [LOG_FAC(LOG_LOCAL1)] = "local1",
4871 [LOG_FAC(LOG_LOCAL2)] = "local2",
4872 [LOG_FAC(LOG_LOCAL3)] = "local3",
4873 [LOG_FAC(LOG_LOCAL4)] = "local4",
4874 [LOG_FAC(LOG_LOCAL5)] = "local5",
4875 [LOG_FAC(LOG_LOCAL6)] = "local6",
4876 [LOG_FAC(LOG_LOCAL7)] = "local7"
4879 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4881 static const char *const log_level_table[] = {
4882 [LOG_EMERG] = "emerg",
4883 [LOG_ALERT] = "alert",
4884 [LOG_CRIT] = "crit",
4886 [LOG_WARNING] = "warning",
4887 [LOG_NOTICE] = "notice",
4888 [LOG_INFO] = "info",
4889 [LOG_DEBUG] = "debug"
4892 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4894 static const char* const sched_policy_table[] = {
4895 [SCHED_OTHER] = "other",
4896 [SCHED_BATCH] = "batch",
4897 [SCHED_IDLE] = "idle",
4898 [SCHED_FIFO] = "fifo",
4902 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4904 static const char* const rlimit_table[] = {
4905 [RLIMIT_CPU] = "LimitCPU",
4906 [RLIMIT_FSIZE] = "LimitFSIZE",
4907 [RLIMIT_DATA] = "LimitDATA",
4908 [RLIMIT_STACK] = "LimitSTACK",
4909 [RLIMIT_CORE] = "LimitCORE",
4910 [RLIMIT_RSS] = "LimitRSS",
4911 [RLIMIT_NOFILE] = "LimitNOFILE",
4912 [RLIMIT_AS] = "LimitAS",
4913 [RLIMIT_NPROC] = "LimitNPROC",
4914 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4915 [RLIMIT_LOCKS] = "LimitLOCKS",
4916 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4917 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4918 [RLIMIT_NICE] = "LimitNICE",
4919 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4920 [RLIMIT_RTTIME] = "LimitRTTIME"
4923 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4925 static const char* const ip_tos_table[] = {
4926 [IPTOS_LOWDELAY] = "low-delay",
4927 [IPTOS_THROUGHPUT] = "throughput",
4928 [IPTOS_RELIABILITY] = "reliability",
4929 [IPTOS_LOWCOST] = "low-cost",
4932 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4934 static const char *const __signal_table[] = {
4951 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4962 [SIGVTALRM] = "VTALRM",
4964 [SIGWINCH] = "WINCH",
4970 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4972 const char *signal_to_string(int signo) {
4973 static __thread char buf[12];
4976 name = __signal_to_string(signo);
4980 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4981 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4983 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4988 int signal_from_string(const char *s) {
4993 signo = __signal_from_string(s);
4997 if (startswith(s, "RTMIN+")) {
5001 if (safe_atou(s, &u) >= 0) {
5002 signo = (int) u + offset;
5003 if (signo > 0 && signo < _NSIG)
5009 bool kexec_loaded(void) {
5010 bool loaded = false;
5013 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5021 int strdup_or_null(const char *a, char **b) {
5039 int prot_from_flags(int flags) {
5041 switch (flags & O_ACCMODE) {
5050 return PROT_READ|PROT_WRITE;
5057 char *format_bytes(char *buf, size_t l, off_t t) {
5060 static const struct {
5064 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5065 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5066 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5067 { "G", 1024ULL*1024ULL*1024ULL },
5068 { "M", 1024ULL*1024ULL },
5072 for (i = 0; i < ELEMENTSOF(table); i++) {
5074 if (t >= table[i].factor) {
5077 (unsigned long long) (t / table[i].factor),
5078 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5085 snprintf(buf, l, "%lluB", (unsigned long long) t);
5093 void* memdup(const void *p, size_t l) {
5106 int fd_inc_sndbuf(int fd, size_t n) {
5108 socklen_t l = sizeof(value);
5110 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5112 l == sizeof(value) &&
5113 (size_t) value >= n*2)
5117 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5124 int fd_inc_rcvbuf(int fd, size_t n) {
5126 socklen_t l = sizeof(value);
5128 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5130 l == sizeof(value) &&
5131 (size_t) value >= n*2)
5135 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5142 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5143 pid_t parent_pid, agent_pid;
5145 bool stdout_is_tty, stderr_is_tty;
5153 parent_pid = getpid();
5155 /* Spawns a temporary TTY agent, making sure it goes away when
5162 if (agent_pid != 0) {
5169 * Make sure the agent goes away when the parent dies */
5170 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5171 _exit(EXIT_FAILURE);
5173 /* Check whether our parent died before we were able
5174 * to set the death signal */
5175 if (getppid() != parent_pid)
5176 _exit(EXIT_SUCCESS);
5178 /* Don't leak fds to the agent */
5179 close_all_fds(except, n_except);
5181 stdout_is_tty = isatty(STDOUT_FILENO);
5182 stderr_is_tty = isatty(STDERR_FILENO);
5184 if (!stdout_is_tty || !stderr_is_tty) {
5185 /* Detach from stdout/stderr. and reopen
5186 * /dev/tty for them. This is important to
5187 * ensure that when systemctl is started via
5188 * popen() or a similar call that expects to
5189 * read EOF we actually do generate EOF and
5190 * not delay this indefinitely by because we
5191 * keep an unused copy of stdin around. */
5192 fd = open("/dev/tty", O_WRONLY);
5194 log_error("Failed to open /dev/tty: %m");
5195 _exit(EXIT_FAILURE);
5199 dup2(fd, STDOUT_FILENO);
5202 dup2(fd, STDERR_FILENO);
5208 /* Count arguments */
5210 for (n = 0; va_arg(ap, char*); n++)
5215 l = alloca(sizeof(char *) * (n + 1));
5217 /* Fill in arguments */
5219 for (i = 0; i <= n; i++)
5220 l[i] = va_arg(ap, char*);
5224 _exit(EXIT_FAILURE);
5227 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5228 struct rlimit highest, fixed;
5232 if (setrlimit(resource, rlim) >= 0)
5238 /* So we failed to set the desired setrlimit, then let's try
5239 * to get as close as we can */
5240 assert_se(getrlimit(resource, &highest) == 0);
5242 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5243 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5245 if (setrlimit(resource, &fixed) < 0)
5251 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5252 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5264 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5267 f = fopen(path, "re");
5275 char line[LINE_MAX];
5278 for (i = 0; i < sizeof(line)-1; i++) {
5282 if (_unlikely_(c == EOF)) {
5292 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5293 value = strdup(line + l + 1);
5313 int can_sleep(const char *type) {
5317 _cleanup_free_ char *p = NULL;
5321 /* If /sys is read-only we cannot sleep */
5322 if (access("/sys/power/state", W_OK) < 0)
5325 r = read_one_line_file("/sys/power/state", &p);
5330 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5331 if (l == k && memcmp(w, type, l) == 0)
5337 int can_sleep_disk(const char *type) {
5341 _cleanup_free_ char *p = NULL;
5345 /* If /sys is read-only we cannot sleep */
5346 if (access("/sys/power/state", W_OK) < 0 ||
5347 access("/sys/power/disk", W_OK) < 0)
5350 r = read_one_line_file("/sys/power/disk", &p);
5355 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5356 if (l == k && memcmp(w, type, l) == 0)
5359 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5366 bool is_valid_documentation_url(const char *url) {
5369 if (startswith(url, "http://") && url[7])
5372 if (startswith(url, "https://") && url[8])
5375 if (startswith(url, "file:") && url[5])
5378 if (startswith(url, "info:") && url[5])
5381 if (startswith(url, "man:") && url[4])
5387 bool in_initrd(void) {
5388 static __thread int saved = -1;
5394 /* We make two checks here:
5396 * 1. the flag file /etc/initrd-release must exist
5397 * 2. the root file system must be a memory file system
5399 * The second check is extra paranoia, since misdetecting an
5400 * initrd can have bad bad consequences due the initrd
5401 * emptying when transititioning to the main systemd.
5404 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5405 statfs("/", &s) >= 0 &&
5406 is_temporary_fs(&s);
5411 void warn_melody(void) {
5412 _cleanup_close_ int fd = -1;
5414 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5418 /* Yeah, this is synchronous. Kinda sucks. But well... */
5420 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5421 usleep(125*USEC_PER_MSEC);
5423 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5424 usleep(125*USEC_PER_MSEC);
5426 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5427 usleep(125*USEC_PER_MSEC);
5429 ioctl(fd, KIOCSOUND, 0);
5432 int make_console_stdio(void) {
5435 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5437 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5439 log_error("Failed to acquire terminal: %s", strerror(-fd));
5445 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5452 int get_home_dir(char **_h) {
5460 /* Take the user specified one */
5471 /* Hardcode home directory for root to avoid NSS */
5474 h = strdup("/root");
5482 /* Check the database... */
5486 return errno ? -errno : -ESRCH;
5488 if (!path_is_absolute(p->pw_dir))
5491 h = strdup(p->pw_dir);
5499 int get_shell(char **_sh) {
5507 /* Take the user specified one */
5508 e = getenv("SHELL");
5518 /* Hardcode home directory for root to avoid NSS */
5521 sh = strdup("/bin/sh");
5529 /* Check the database... */
5533 return errno ? -errno : -ESRCH;
5535 if (!path_is_absolute(p->pw_shell))
5538 sh = strdup(p->pw_shell);
5546 void freep(void *p) {
5550 void fclosep(FILE **f) {
5555 void pclosep(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 string_has_cc(const char *p) {
5615 for (t = p; *t; t++)
5616 if (*t > 0 && *t < ' ')
5622 bool path_is_safe(const char *p) {
5627 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5630 if (strlen(p) > PATH_MAX)
5633 /* The following two checks are not really dangerous, but hey, they still are confusing */
5634 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5637 if (strstr(p, "//"))
5643 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5644 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5645 int (*compar) (const void *, const void *, void *), void *arg) {
5654 p = (void *)(((const char *) base) + (idx * size));
5655 comparison = compar(key, p, arg);
5658 else if (comparison > 0)
5666 bool is_locale_utf8(void) {
5668 static int cached_answer = -1;
5670 if (cached_answer >= 0)
5673 if (!setlocale(LC_ALL, "")) {
5674 cached_answer = true;
5678 set = nl_langinfo(CODESET);
5680 cached_answer = true;
5684 cached_answer = streq(set, "UTF-8");
5686 return (bool)cached_answer;
5689 const char *draw_special_char(DrawSpecialChar ch) {
5690 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5692 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5693 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5694 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5695 [DRAW_TREE_SPACE] = " ", /* */
5696 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5698 /* ASCII fallback */ {
5699 [DRAW_TREE_VERT] = "| ",
5700 [DRAW_TREE_BRANCH] = "|-",
5701 [DRAW_TREE_RIGHT] = "`-",
5702 [DRAW_TREE_SPACE] = " ",
5703 [DRAW_TRIANGULAR_BULLET] = "> ",
5707 return draw_table[!is_locale_utf8()][ch];
5710 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5713 size_t l, old_len, new_len;
5719 old_len = strlen(old_string);
5720 new_len = strlen(new_string);
5733 if (!startswith(f, old_string)) {
5739 nl = l - old_len + new_len;
5740 a = realloc(r, nl + 1);
5748 t = stpcpy(t, new_string);
5760 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5761 const char *i, *begin = NULL;
5766 } state = STATE_OTHER;
5768 size_t osz = 0, isz;
5774 /* Strips ANSI color and replaces TABs by 8 spaces */
5776 isz = _isz ? *_isz : strlen(*ibuf);
5778 f = open_memstream(&obuf, &osz);
5782 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5787 if (i >= *ibuf + isz) /* EOT */
5789 else if (*i == '\x1B')
5790 state = STATE_ESCAPE;
5791 else if (*i == '\t')
5798 if (i >= *ibuf + isz) { /* EOT */
5801 } else if (*i == '[') {
5802 state = STATE_BRACKET;
5807 state = STATE_OTHER;
5814 if (i >= *ibuf + isz || /* EOT */
5815 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5818 state = STATE_OTHER;
5820 } else if (*i == 'm')
5821 state = STATE_OTHER;
5843 int on_ac_power(void) {
5844 bool found_offline = false, found_online = false;
5845 _cleanup_closedir_ DIR *d = NULL;
5847 d = opendir("/sys/class/power_supply");
5853 union dirent_storage buf;
5854 _cleanup_free_ char *p = NULL;
5855 _cleanup_close_ int fd = -1, device = -1;
5860 k = readdir_r(d, &buf.de, &de);
5867 if (ignore_file(de->d_name))
5870 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5872 if (errno == ENOENT || errno == ENOTDIR)
5878 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5880 if (errno == ENOENT)
5886 n = read(fd, contents, sizeof(contents));
5890 if (n != 6 || memcmp(contents, "Mains\n", 6))
5893 close_nointr_nofail(fd);
5894 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5896 if (errno == ENOENT)
5902 n = read(fd, contents, sizeof(contents));
5906 if (n != 2 || contents[1] != '\n')
5909 if (contents[0] == '1') {
5910 found_online = true;
5912 } else if (contents[0] == '0')
5913 found_offline = true;
5918 return found_online || !found_offline;
5921 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5928 if (!path_strv_canonicalize_uniq(search))
5931 STRV_FOREACH(i, search) {
5932 _cleanup_free_ char *p = NULL;
5935 p = strjoin(*i, "/", path, NULL);
5945 if (errno != ENOENT)
5952 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5953 _cleanup_strv_free_ char **copy = NULL;
5959 if (path_is_absolute(path)) {
5962 f = fopen(path, mode);
5971 copy = strv_copy((char**) search);
5975 return search_and_fopen_internal(path, mode, copy, _f);
5978 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5979 _cleanup_strv_free_ char **s = NULL;
5981 if (path_is_absolute(path)) {
5984 f = fopen(path, mode);
5993 s = strv_split_nulstr(search);
5997 return search_and_fopen_internal(path, mode, s, _f);